hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
48.5k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a00293545a9fb8ed884163cac2906093759d1645
| 4,969
|
cc
|
C++
|
libs/jsRuntime/src/CppBridge/V8NativeObject.cc
|
v8App/v8App
|
96c5278ae9078d508537f2e801b9ba0272ab1168
|
[
"MIT"
] | null | null | null |
libs/jsRuntime/src/CppBridge/V8NativeObject.cc
|
v8App/v8App
|
96c5278ae9078d508537f2e801b9ba0272ab1168
|
[
"MIT"
] | null | null | null |
libs/jsRuntime/src/CppBridge/V8NativeObject.cc
|
v8App/v8App
|
96c5278ae9078d508537f2e801b9ba0272ab1168
|
[
"MIT"
] | null | null | null |
// Copyright 2020 The v8App Authors. All rights reserved.
// Use of this source code is governed by a MIT license that can be
// found in the LICENSE file.
#include "CppBridge/V8NativeObject.h"
#include "CppBridge/V8ObjectTemplateBuilder.h"
namespace v8App
{
namespace JSRuntime
{
namespace CppBridge
{
V8NativeObjectInfo *V8NativeObjectInfo::From(v8::Local<v8::Object> inObject)
{
if (inObject->InternalFieldCount() != kMaxReservedInternalFields)
{
return nullptr;
}
V8NativeObjectInfo *info = static_cast<V8NativeObjectInfo *>(
inObject->GetAlignedPointerFromInternalField(kV8NativeObjectInfo));
return info;
}
V8NativeObjectBase::V8NativeObjectBase() = default;
V8NativeObjectBase::~V8NativeObjectBase()
{
m_Object.Reset();
}
V8ObjectTemplateBuilder V8NativeObjectBase::GetObjectTemplateBuilder(v8::Isolate *inIsolate)
{
return V8ObjectTemplateBuilder(inIsolate, GetTypeName());
}
v8::Local<v8::ObjectTemplate> V8NativeObjectBase::GetOrCreateObjectTemplate(v8::Isolate *inIsolate, V8NativeObjectInfo *inInfo)
{
JSRuntime *runtime = JSRuntime::GetRuntime(inIsolate);
v8::Local<v8::ObjectTemplate> objTemplate = runtime->GetObjectTemplate(inInfo);
if (objTemplate.IsEmpty())
{
objTemplate = GetObjectTemplateBuilder(inIsolate).Build();
CHECK_FALSE(objTemplate.IsEmpty());
runtime->SetObjectTemplate(inInfo, objTemplate);
}
CHECK_EQ(kMaxReservedInternalFields, objTemplate->InternalFieldCount());
return objTemplate;
}
const char *V8NativeObjectBase::GetTypeName()
{
return nullptr;
}
void V8NativeObjectBase::FirstWeakCallback(const v8::WeakCallbackInfo<V8NativeObjectBase> &inInfo)
{
V8NativeObjectBase *baseObject = inInfo.GetParameter();
baseObject->m_Destrying = true;
baseObject->m_Object.Reset();
inInfo.SetSecondPassCallback(SecondWeakCallback);
}
void V8NativeObjectBase::SecondWeakCallback(const v8::WeakCallbackInfo<V8NativeObjectBase> &inInfo)
{
V8NativeObjectBase *baseObject = inInfo.GetParameter();
delete baseObject;
}
v8::MaybeLocal<v8::Object> V8NativeObjectBase::GetV8NativeObjectInternal(v8::Isolate *inIsolate, V8NativeObjectInfo *inInfo)
{
if (m_Object.IsEmpty() == false)
{
return v8::MaybeLocal<v8::Object>(v8::Local<v8::Object>::New(inIsolate, m_Object));
}
if (m_Destrying)
{
return v8::MaybeLocal<v8::Object>();
}
v8::Local<v8::ObjectTemplate> objTemplate = GetOrCreateObjectTemplate(inIsolate, inInfo);
v8::Local<v8::Object> object;
if (objTemplate->NewInstance(inIsolate->GetCurrentContext()).ToLocal(&object) == false)
{
delete this;
return v8::MaybeLocal<v8::Object>(object);
}
int indexes[] = {kV8NativeObjectInfo, kV8NativeObjectInstance};
void *values[] = {inInfo, this};
object->SetAlignedPointerInInternalFields(2, indexes, values);
m_Object.Reset(inIsolate, object);
m_Object.SetWeak(this, FirstWeakCallback, v8::WeakCallbackType::kParameter);
return v8::MaybeLocal<v8::Object>(object);
}
void *FromV8NativeObjectInternal(v8::Isolate *inIsolate, v8::Local<v8::Value> inValue, V8NativeObjectInfo *inInfo)
{
if (inValue->IsObject() == false)
{
return nullptr;
}
v8::Local<v8::Object> object = v8::Local<v8::Object>::Cast(inValue);
//we should at a min have kMaxReservedInternalFields fields
if (object->InternalFieldCount() < kMaxReservedInternalFields)
{
return nullptr;
}
V8NativeObjectInfo *info = V8NativeObjectInfo::From(object);
if (info == nullptr)
{
return nullptr;
}
if (info != inInfo)
{
return nullptr;
}
return object->GetAlignedPointerFromInternalField(kV8NativeObjectInstance);
}
}
}
}
| 37.643939
| 139
| 0.546388
|
v8App
|
a0037d69dffd17fb983fcbb45ab1fdc85f09292b
| 827
|
cpp
|
C++
|
serverapp/src/db/SystemPlan.cpp
|
mjgerdes/cg
|
be378b140df7d7e9bd16512a1d9a54d3439b03f7
|
[
"MIT"
] | null | null | null |
serverapp/src/db/SystemPlan.cpp
|
mjgerdes/cg
|
be378b140df7d7e9bd16512a1d9a54d3439b03f7
|
[
"MIT"
] | null | null | null |
serverapp/src/db/SystemPlan.cpp
|
mjgerdes/cg
|
be378b140df7d7e9bd16512a1d9a54d3439b03f7
|
[
"MIT"
] | null | null | null |
#include "SystemPlan.hpp"
#include "SystemProvider.hpp"
#include "CardProvider.hpp"
using namespace db;
SystemPlan::SystemPlan() : m_systemId(data::SystemData::universal), m_cards() {}
SystemPlan::SystemPlan(const System& system)
: m_systemId(system.id()), m_cards() {
fillCards(system);
}
void SystemPlan::fillCards(const System& system) {
m_cards.resize(system.size());
std::transform(system.cards().cbegin(), system.cards().cend(),
m_cards.begin(), [](const Card& card) { return card.id(); });
}
db::SystemPlan::System_ptr SystemPlan::load(const SystemProvider& sp,
const CardProvider& cp) {
auto system = std::make_unique<System>(sp.get(m_systemId));
for (const auto& cardId : m_cards) {
if (!system->tryAddCard(cp.get(cardId))) return nullptr;
}
return std::move(system);
} // end load
| 27.566667
| 80
| 0.697703
|
mjgerdes
|
a006086cc4e575c937f9df394afc6c76d7b60e8b
| 3,603
|
cpp
|
C++
|
test/training_data/plag_original_codes/abc070_d_7677426_229_plag.cpp
|
xryuseix/SA-Plag
|
167f7a2b2fa81ff00fd5263772a74c2c5c61941d
|
[
"MIT"
] | 13
|
2021-01-20T19:53:16.000Z
|
2021-11-14T16:30:32.000Z
|
test/training_data/plag_original_codes/abc070_d_7677426_229_plag.cpp
|
xryuseix/SA-Plag
|
167f7a2b2fa81ff00fd5263772a74c2c5c61941d
|
[
"MIT"
] | null | null | null |
test/training_data/plag_original_codes/abc070_d_7677426_229_plag.cpp
|
xryuseix/SA-Plag
|
167f7a2b2fa81ff00fd5263772a74c2c5c61941d
|
[
"MIT"
] | null | null | null |
/*
引用元:https://atcoder.jp/contests/abc070/tasks/abc070_d
D - Transit Tree PathEditorial
// ソースコードの引用元 : https://atcoder.jp/contests/abc070/submissions/7677426
// 提出ID : 7677426
// 問題ID : abc070_d
// コンテストID : abc070
// ユーザID : xryuseix
// コード長 : 3404
// 実行時間 : 232
*/
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <vector>
#include <list>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <cctype>
#include <climits>
#include <string>
#include <bitset>
#include <cfloat>
using namespace std;
typedef long double ld;
typedef long long int ll;
typedef unsigned long long int ull;
typedef vector<int> vi;
typedef vector<char> vc;
typedef vector<double> vd;
typedef vector<string> vs;
typedef vector<ll> vll;
typedef vector<pair<int, int>> vpii;
typedef vector<vector<int>> vvi;
typedef vector<vector<char>> vvc;
typedef vector<vector<string>> vvs;
typedef vector<vector<ll>> vvll;
#define rep(i, n) for (int i = 0; i < (n); ++i)
#define rrep(i, n) for (int i = 1; i <= (n); ++i)
#define drep(i, n) for (int i = (n)-1; i >= 0; --i)
#define fin(ans) cout << (ans) << endl
#define STI(s) atoi(s.c_str())
#define mp(p, q) make_pair(p, q)
#define pb(n) push_back(n)
#define all(a) a.begin(), a.end()
#define rall(a) a.rbegin(), a.rend()
#define Sort(a) sort(a.begin(), a.end())
#define Rort(a) sort(a.rbegin(), a.rend())
template <class T> inline bool chmax(T &a, T b) {
if (a < b) {
a = b;
return 1;
}
return 0;
}
template <class T> inline bool chmin(T &a, T b) {
if (a > b) {
a = b;
return 1;
}
return 0;
}
const int P = 1000000007;
const int INF = INT_MAX;
const ll LLINF = 1LL << 60;
class DIJKSTRA {
public:
int V;
struct dk_edge {
int to;
ll cost;
};
typedef pair<ll, int> PI; // firstは最短距離、secondは頂点の番号
vector<vector<dk_edge> > G;
vector<ll> d; //これ答え。d[i]:=V[i]までの最短距離
vector<int> prev; //経路復元
DIJKSTRA(int size) {
V = size;
G = vector<vector<dk_edge> >(V);
prev = vector<int>(V, -1);
}
void add(int from, int to, ll cost) {
dk_edge e = {to, cost};
G[from].push_back(e);
}
void dijkstra(int s) {
// greater<P>を指定することでfirstが小さい順に取り出せるようにする
priority_queue<PI, vector<PI>, greater<PI> > que;
d = vector<ll>(V, LLINF);
d[s] = 0;
que.push(PI(0, s));
while (!que.empty()) {
PI p = que.top();
que.pop();
int v = p.second;
if (d[v] < p.first) continue;
for (int i = 0; i < G[v].size(); i++) {
dk_edge e = G[v][i];
if (d[e.to] > d[v] + e.cost) {
d[e.to] = d[v] + e.cost;
prev[e.to] = v;
que.push(PI(d[e.to], e.to));
}
}
}
}
vector<int> get_path(int t) {
vector<int> path;
for (; t != -1; t = prev[t]) {
// tがsになるまでprev[t]をたどっていく
path.push_back(t);
}
//このままだとt->sの順になっているので逆順にする
reverse(path.begin(), path.end());
return path;
}
void show(void) {
for (int i = 0; i < d.size() - 1; i++) {
cout << d[i] << " ";
}
cout << d[d.size() - 1] << endl;
}
};
int main(void) {
ios::sync_with_stdio(false);
cin.tie(0);
//////////////////////////////////////////////////////
ll n;
cin >> n;
ll a, b, c;
DIJKSTRA wa(n);
rep(i, n - 1) {
cin >> a >> b >> c;
a--;
b--;
wa.add(a, b, c);
wa.add(b, a, c);
}
ll q, k;
cin >> q >> k;
ll x, y;
k--;
wa.dijkstra(k);
// wa.show();
rep(i, q) {
cin >> x >> y;
x--;
y--;
fin((ll)wa.d[x] + (ll)wa.d[y]);
}
//////////////////////////////////////////////////////
return 0;
}
| 21.070175
| 70
| 0.541216
|
xryuseix
|
a00ad16a9c56394bfeb58832cc16f4bbf7192940
| 179
|
cpp
|
C++
|
avs_dx/DxVisualsShaders/dummy.cpp
|
Const-me/vis_avs_dx
|
da1fd9f4323d7891dea233147e6ae16790ad9ada
|
[
"MIT"
] | 33
|
2019-01-28T03:32:17.000Z
|
2022-02-12T18:17:26.000Z
|
avs_dx/DxVisualsShaders/dummy.cpp
|
visbot/vis_avs_dx
|
03e55f8932a97ad845ff223d3602ff2300c3d1d4
|
[
"MIT"
] | 2
|
2019-11-18T17:54:58.000Z
|
2020-07-21T18:11:21.000Z
|
avs_dx/DxVisualsShaders/dummy.cpp
|
Const-me/vis_avs_dx
|
da1fd9f4323d7891dea233147e6ae16790ad9ada
|
[
"MIT"
] | 5
|
2019-02-16T23:00:11.000Z
|
2022-03-27T15:22:10.000Z
|
// A dummy function to make linker happy. This project doesn't contain any C++ code, it's workaround for the build system to compile HLSL shaders.
void dxVisualsShadersDummy() { }
| 89.5
| 146
| 0.77095
|
Const-me
|
a0173ef17d8c9b06cfdb019689f2eb2661e49b6f
| 807
|
cc
|
C++
|
Tests/KinematicLineFit_unit.cc
|
orionning676/KinKal
|
689ec932155b7fe31d46c398bcb78bcac93581d7
|
[
"Apache-1.1"
] | 2
|
2020-04-21T18:24:55.000Z
|
2020-09-24T19:01:47.000Z
|
Tests/KinematicLineFit_unit.cc
|
orionning676/KinKal
|
689ec932155b7fe31d46c398bcb78bcac93581d7
|
[
"Apache-1.1"
] | 45
|
2020-03-16T18:27:59.000Z
|
2022-01-13T05:18:35.000Z
|
Tests/KinematicLineFit_unit.cc
|
orionning676/KinKal
|
689ec932155b7fe31d46c398bcb78bcac93581d7
|
[
"Apache-1.1"
] | 15
|
2020-02-21T01:10:49.000Z
|
2022-03-24T12:13:35.000Z
|
/*
Original Author: S Middleton 2020
*/
#include "KinKal/Trajectory/KinematicLine.hh"
#include "KinKal/Tests/FitTest.hh"
int main(int argc, char *argv[]){
KinKal::DVEC sigmas(0.5, 0.004, 0.5, 0.002, 0.4, 0.05); // expected parameter sigmas
if(argc == 1){
cout << "Adding momentum constraint" << endl;
std::vector<std::string> arguments;
arguments.push_back(argv[0]);
arguments.push_back("--constrainpar");
arguments.push_back("5");
arguments.push_back("--Bz");
arguments.push_back("0.0");
std::vector<char*> myargv;
for (const auto& arg : arguments)
myargv.push_back((char*)arg.data());
myargv.push_back(nullptr);
return FitTest<KinematicLine>(myargv.size()-1,myargv.data(),sigmas);
} else
return FitTest<KinematicLine>(argc,argv,sigmas);
}
| 32.28
| 86
| 0.665428
|
orionning676
|
a0174acc6305ac4def91ae9040c200768e5cf6db
| 630
|
cpp
|
C++
|
dotNetInstallerLib/Schema.cpp
|
baSSiLL/dotnetinstaller
|
2a983649553cd322f674fe06685f0c1d47f638b2
|
[
"MIT"
] | null | null | null |
dotNetInstallerLib/Schema.cpp
|
baSSiLL/dotnetinstaller
|
2a983649553cd322f674fe06685f0c1d47f638b2
|
[
"MIT"
] | null | null | null |
dotNetInstallerLib/Schema.cpp
|
baSSiLL/dotnetinstaller
|
2a983649553cd322f674fe06685f0c1d47f638b2
|
[
"MIT"
] | 1
|
2020-04-30T10:25:58.000Z
|
2020-04-30T10:25:58.000Z
|
#include "StdAfx.h"
#include "Schema.h"
#include "InstallerLog.h"
Schema::Schema()
: generator(L"dotNetInstaller InstallerEditor")
, version(L"1")
{
}
void Schema::Load(TiXmlElement * node)
{
CHECK_BOOL(node != NULL,
L"Expected 'schema' node");
CHECK_BOOL(0 == strcmp(node->Value(), "schema"),
L"Expected 'schema' node, got '" << DVLib::string2wstring(node->Value()) << L"'");
version = DVLib::UTF8string2wstring(node->Attribute("version"));
generator = DVLib::UTF8string2wstring(node->Attribute("generator"));
LOG(L"Loaded schema: version=" << version << L", generator=" << generator);
}
| 25.2
| 85
| 0.653968
|
baSSiLL
|
a01903a488a67c23fda4047cd668a16ad59506b9
| 7,238
|
hpp
|
C++
|
xvm/xvm.hpp
|
kiven-li/xscrip
|
ed762811aaf502ee20b5d00083926f7647def57d
|
[
"MIT"
] | 15
|
2018-11-10T11:30:09.000Z
|
2022-02-28T06:00:57.000Z
|
xvm/xvm.hpp
|
kiven-li/xscrip
|
ed762811aaf502ee20b5d00083926f7647def57d
|
[
"MIT"
] | null | null | null |
xvm/xvm.hpp
|
kiven-li/xscrip
|
ed762811aaf502ee20b5d00083926f7647def57d
|
[
"MIT"
] | 10
|
2019-06-19T03:33:53.000Z
|
2021-08-20T01:24:42.000Z
|
#ifndef __XSCRIPT_XVM_HPP__
#define __XSCRIPT_XVM_HPP__
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdarg.h>
#include <time.h>
#include <ctype.h>
#include <assert.h>
#include <vector>
#include "xvm_interface.hpp"
#include "../common/instruction.hpp"
#include "../common/utility.hpp"
namespace xscript {
namespace xvm {
//script loading
#define EXEC_FILE_EXT ".XSE"
#define XSE_ID_STRING "XSE0"
#define MAJOR_VERSION 0
#define MINOR_VERSION 8
#define MAX_THREAD_COUNT 1024//the maximum number of scripts that can be loaded at once.
#define DEF_STACK_SIZE 1024
#define MAX_COERCION_STRING_SIZE 64//the maximum allocated space for a string coercion
#define MAX_HOST_API_SIZE 1024//maximum number of functions in the host API
#define MAX_FUNC_NAME_SIZE 256
//multithreading
#define THREAD_PRIORITY_DUR_LOW 20//low-priority thread timeslice
#define THREAD_PRIORITY_DUR_MED 40
#define THREAD_PRIORITY_DUR_HIGH 80
enum XVM_THREAD_MODE
{
THREAD_MODE_MULTI = 0,
THREAD_MODE_SINGLE,
};
//runtime value
struct xvm_value
{
int type;
union
{
int int_literal;
float float_literal;
//char* string_literal;
int string_index;
int stack_index;
int instruction_index;
int function_index;
int host_api_index;
int reg;
};
int offset_index;
};
typedef std::vector<xvm_value> value_vector;
//runtime stack
struct runtime_stack
{
value_vector elements;
int size;
int top;
int frame;
};
//functions
struct function
{
int entry_point;
int param_count;
int local_data_size;
int stack_frame_size;
string name;
};
typedef std::vector<function> function_vector;
//instruction
struct xvm_code
{
int opcode;
int opcount;
value_vector oplist;
};
typedef std::vector<xvm_code> xvm_code_vector;
struct xvm_code_stream
{
xvm_code_vector codes;
int current_code;
};
//host API call
typedef std::vector<std::string> string_vector;
//script
struct script
{
bool is_active;//is this script structure in use
//header data
int global_data_size;
int is_main_function_present;
int main_function_index;
//runtime tracking
bool is_running;
bool is_paused;
int pause_end_time;
//threading
int timeslice_duration;
//register file
xvm_value _RetVal;
//script data
function_vector function_table;
xvm_code_stream code_stream;
string_vector host_api_table;
string_vector string_table;
runtime_stack stack;
};
//host API
struct host_api_function
{
int is_active;
int thread_index;
string name;
host_api_function_ptr function;
};
//Macros
#define resolve_stack_index(index) (index < 0 ? index += scripts[current_thread].stack.frame : index)
#define is_valid_thread_index(index) (index < 0 || index > MAX_THREAD_COUNT ? false : true)
#define is_thread_active(index) (is_valid_thread_index(index) && scripts[index].is_active ? true : false)
class xvm : public xvm_interface
{
public:
xvm();
~xvm();
//------------script interface---------------//
void xvm_init();
void xvm_shutdown();
int xvm_load_script(const char* script_name, int& script_index, int thread_timeslice);
void xvm_unload_script(int script_index);
void xvm_reset_script(int script_index);
void xvm_run_script(int timeslice_duration);
void xvm_start_script(int script_index);
void xvm_stop_script(int script_index);
void xvm_pause_script(int script_index, int duration);
void xvm_unpause_script(int script_index);
void xvm_pass_int_param(int script_index, int v);
void xvm_pass_float_param(int script_index, float v);
void xvm_pass_string_param(int script_index, const char* str);
int xvm_get_return_as_int(int script_index);
float xvm_get_return_as_float(int script_index);
string xvm_get_return_as_string(int script_index);
void xvm_call_script_function(int script_index, const char* fname);
void xvm_invoke_script_function(int script_index, const char* fname);
//------------host API interface---------------//
void xvm_register_host_api(int script_index, const char* fname, host_api_function_ptr fn);
int xvm_get_param_as_int(int script_index, int param_index);
float xvm_get_param_as_float(int script_index, int param_index);
string xvm_get_param_as_string(int script_index, int param_index);
void xvm_return_from_host(int script_index, int param_count);
void xvm_return_int_from_host(int script_index, int param_count, int v);
void xvm_return_float_from_host(int script_index, int param_count, float v);
void xvm_return_string_from_host(int script_index, int param_count, char* str);
private:
//------------operand interface----------------//
int cast_value_to_int(const xvm_value& v);
float cast_value_to_float(const xvm_value& v);
string cast_value_to_string(const xvm_value& v);
void copy_value(xvm_value* dest, const xvm_value& source);
int get_operand_type(int index);
int resolve_operand_stack_index(int index);
xvm_value resolve_operand_value(int index);
int resolve_operand_type(int index);
int resolve_operand_as_int(int index);
float resolve_operand_as_float(int index);
string resolve_operand_as_string(int index);
int resolve_operand_as_instruction_index(int index);
int resolve_operand_as_function_index(int index);
string resolve_operand_as_host_api(int index);
xvm_value* resolve_operand_ptr(int index);
//------------runtime stack interface-------------//
xvm_value get_stack_value(int script_index, int index);
void set_stack_value(int script_index, int index, const xvm_value& v);
void push(int script_index, const xvm_value& v);
xvm_value pop(int script_index);
void push_frame(int script_index, int size);
void pop_frame(int size);
//------------function table interface------------//
int get_function_index_by_name(int script_index, const char* str);
function get_function(int script_index, int index);
//------------host API interface-----------------//
string get_host_api(int index);
//------------time-------------------------------//
int get_current_time();
//------------function---------------------------//
void call_function(int script_index, int index);
//------------string table-----------------------//
int add_string_if_new(const string& str);
string get_string(int sindex);
private:
script scripts[MAX_THREAD_COUNT];
host_api_function host_apis[MAX_HOST_API_SIZE];
//threading
int current_thread;
int current_thread_mode;
int current_thread_active_time;
};
}//namespace xvm
}//namespace xscript
#endif //__XSCRIPT_XVM_HPP__
| 28.952
| 106
| 0.668002
|
kiven-li
|
a01de795ae2657ed39ae4096188e7469caf791cd
| 9,362
|
hpp
|
C++
|
kernel/src/dispatch_syscall_callback_op.hpp
|
kangdazhi/hypervisor
|
95848672b1b2907f37f91343ae139d1bbd858b9d
|
[
"MIT"
] | null | null | null |
kernel/src/dispatch_syscall_callback_op.hpp
|
kangdazhi/hypervisor
|
95848672b1b2907f37f91343ae139d1bbd858b9d
|
[
"MIT"
] | null | null | null |
kernel/src/dispatch_syscall_callback_op.hpp
|
kangdazhi/hypervisor
|
95848672b1b2907f37f91343ae139d1bbd858b9d
|
[
"MIT"
] | null | null | null |
/// @copyright
/// Copyright (C) 2020 Assured Information Security, Inc.
///
/// @copyright
/// 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:
///
/// @copyright
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// @copyright
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
/// SOFTWARE.
#ifndef DISPATCH_SYSCALL_CALLBACK_OP_HPP
#define DISPATCH_SYSCALL_CALLBACK_OP_HPP
#include <bf_constants.hpp>
#include <ext_t.hpp>
#include <tls_t.hpp>
#include <bsl/convert.hpp>
#include <bsl/debug.hpp>
#include <bsl/likely.hpp>
#include <bsl/safe_integral.hpp>
#include <bsl/touch.hpp>
#include <bsl/unlikely.hpp>
namespace mk
{
/// <!-- description -->
/// @brief Implements the bf_callback_op_register_bootstrap syscall
///
/// <!-- inputs/outputs -->
/// @param mut_tls the current TLS block
/// @param mut_ext the extension that made the syscall
/// @return Returns a bf_status_t containing success or failure
///
[[nodiscard]] constexpr auto
syscall_callback_op_register_bootstrap(tls_t &mut_tls, ext_t &mut_ext) noexcept
-> syscall::bf_status_t
{
bsl::safe_uintmax const callback{mut_tls.ext_reg1};
if (bsl::unlikely(callback.is_zero())) {
bsl::error() << "the bootstrap callback cannot be null" // --
<< bsl::endl // --
<< bsl::here(); // --
return syscall::BF_STATUS_FAILURE_UNKNOWN;
}
if (bsl::unlikely(mut_ext.bootstrap_ip())) {
bsl::error() << "mut_ext " // --
<< bsl::hex(mut_ext.id()) // --
<< " already registered a bootstrap callback\n" // --
<< bsl::here(); // --
return syscall::BF_STATUS_FAILURE_UNKNOWN;
}
mut_ext.set_bootstrap_ip(callback);
return syscall::BF_STATUS_SUCCESS;
}
/// <!-- description -->
/// @brief Implements the bf_callback_op_register_vmexit syscall
///
/// <!-- inputs/outputs -->
/// @param mut_tls the current TLS block
/// @param mut_ext the extension that made the syscall
/// @return Returns a bf_status_t containing success or failure
///
[[nodiscard]] constexpr auto
syscall_callback_op_register_vmexit(tls_t &mut_tls, ext_t &mut_ext) noexcept
-> syscall::bf_status_t
{
bsl::safe_uintmax const callback{mut_tls.ext_reg1};
if (bsl::unlikely(callback.is_zero())) {
bsl::error() << "the vmexit callback cannot be null" // --
<< bsl::endl // --
<< bsl::here(); // --
return syscall::BF_STATUS_FAILURE_UNKNOWN;
}
if (bsl::unlikely(mut_ext.vmexit_ip())) {
bsl::error() << "mut_ext " // --
<< bsl::hex(mut_ext.id()) // --
<< " already registered a vmexit callback\n" // --
<< bsl::here(); // --
return syscall::BF_STATUS_FAILURE_UNKNOWN;
}
if (bsl::unlikely(nullptr != mut_tls.ext_vmexit)) {
bsl::error() << "mut_ext " // --
<< bsl::hex(static_cast<ext_t *>(mut_tls.ext_vmexit)->id()) // --
<< " already registered a vmexit callback\n" // --
<< bsl::here(); // --
return syscall::BF_STATUS_FAILURE_UNKNOWN;
}
mut_ext.set_vmexit_ip(callback);
mut_tls.ext_vmexit = &mut_ext;
return syscall::BF_STATUS_SUCCESS;
}
/// <!-- description -->
/// @brief Implements the bf_callback_op_register_fail syscall
///
/// <!-- inputs/outputs -->
/// @param mut_tls the current TLS block
/// @param mut_ext the extension that made the syscall
/// @return Returns a bf_status_t containing success or failure
///
[[nodiscard]] constexpr auto
syscall_callback_op_register_fail(tls_t &mut_tls, ext_t &mut_ext) noexcept
-> syscall::bf_status_t
{
bsl::safe_uintmax const callback{mut_tls.ext_reg1};
if (bsl::unlikely(callback.is_zero())) {
bsl::error() << "the fast fail callback cannot be null" // --
<< bsl::endl // --
<< bsl::here(); // --
return syscall::BF_STATUS_FAILURE_UNKNOWN;
}
if (bsl::unlikely(mut_ext.fail_ip())) {
bsl::error() << "mut_ext " // --
<< bsl::hex(mut_ext.id()) // --
<< " already registered a fast fail callback\n" // --
<< bsl::here(); // --
return syscall::BF_STATUS_FAILURE_UNKNOWN;
}
if (bsl::unlikely(nullptr != mut_tls.ext_fail)) {
bsl::error() << "mut_ext " // --
<< bsl::hex(static_cast<ext_t *>(mut_tls.ext_fail)->id()) // --
<< " already registered a fast fail callback\n" // --
<< bsl::here(); // --
return syscall::BF_STATUS_FAILURE_UNKNOWN;
}
mut_ext.set_fail_ip(callback);
mut_tls.ext_fail = &mut_ext;
return syscall::BF_STATUS_SUCCESS;
}
/// <!-- description -->
/// @brief Dispatches the bf_callback_op syscalls
///
/// <!-- inputs/outputs -->
/// @param mut_tls the current TLS block
/// @param mut_ext the extension that made the syscall
/// @return Returns a bf_status_t containing success or failure
///
[[nodiscard]] constexpr auto
dispatch_syscall_callback_op(tls_t &mut_tls, ext_t &mut_ext) noexcept -> syscall::bf_status_t
{
if (bsl::unlikely(!mut_ext.is_handle_valid(bsl::to_umax(mut_tls.ext_reg0)))) {
bsl::error() << "invalid handle " // --
<< bsl::hex(mut_tls.ext_reg0) // --
<< bsl::endl // --
<< bsl::here(); // --
return syscall::BF_STATUS_FAILURE_INVALID_HANDLE;
}
switch (syscall::bf_syscall_index(bsl::to_umax(mut_tls.ext_syscall)).get()) {
case syscall::BF_CALLBACK_OP_REGISTER_BOOTSTRAP_IDX_VAL.get(): {
auto const ret{syscall_callback_op_register_bootstrap(mut_tls, mut_ext)};
if (bsl::unlikely(ret != syscall::BF_STATUS_SUCCESS)) {
bsl::print<bsl::V>() << bsl::here();
return ret;
}
return ret;
}
case syscall::BF_CALLBACK_OP_REGISTER_VMEXIT_IDX_VAL.get(): {
auto const ret{syscall_callback_op_register_vmexit(mut_tls, mut_ext)};
if (bsl::unlikely(ret != syscall::BF_STATUS_SUCCESS)) {
bsl::print<bsl::V>() << bsl::here();
return ret;
}
return ret;
}
case syscall::BF_CALLBACK_OP_REGISTER_FAIL_IDX_VAL.get(): {
auto const ret{syscall_callback_op_register_fail(mut_tls, mut_ext)};
if (bsl::unlikely(ret != syscall::BF_STATUS_SUCCESS)) {
bsl::print<bsl::V>() << bsl::here();
return ret;
}
return ret;
}
default: {
break;
}
}
bsl::error() << "unknown syscall " //--
<< bsl::hex(mut_tls.ext_syscall) //--
<< bsl::endl //--
<< bsl::here(); //--
return syscall::BF_STATUS_FAILURE_UNSUPPORTED;
}
}
#endif
| 40.528139
| 97
| 0.508118
|
kangdazhi
|
a022ac19edb278e205ce512be3d327b5683c5499
| 3,060
|
cpp
|
C++
|
examples/mongocxx/document_validation.cpp
|
CURG-old/mongo-cxx-driver
|
06d29a00e4e554e7930e3f8ab40ebcecc9ab31c8
|
[
"Apache-2.0"
] | null | null | null |
examples/mongocxx/document_validation.cpp
|
CURG-old/mongo-cxx-driver
|
06d29a00e4e554e7930e3f8ab40ebcecc9ab31c8
|
[
"Apache-2.0"
] | null | null | null |
examples/mongocxx/document_validation.cpp
|
CURG-old/mongo-cxx-driver
|
06d29a00e4e554e7930e3f8ab40ebcecc9ab31c8
|
[
"Apache-2.0"
] | 1
|
2021-06-18T05:00:10.000Z
|
2021-06-18T05:00:10.000Z
|
// Copyright 2016 MongoDB 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 <iostream>
#include <bsoncxx/builder/stream/document.hpp>
#include <bsoncxx/stdx/string_view.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/exception/exception.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/stdx.hpp>
#include <mongocxx/uri.hpp>
using bsoncxx::builder::stream::document;
using bsoncxx::builder::stream::open_document;
using bsoncxx::builder::stream::close_document;
using mongocxx::stdx::string_view;
using mongocxx::collection;
using mongocxx::validation_criteria;
int main(int, char**) {
mongocxx::instance inst{};
mongocxx::client conn{mongocxx::uri{}};
auto db = conn["test"];
// Create a collection with document validation enabled.
{
// @begin: cpp-create-collection-with-document-validation
validation_criteria validation;
validation.level(validation_criteria::validation_level::k_strict);
validation.action(validation_criteria::validation_action::k_error);
// Add a validation rule: all zombies need to eat some brains.
document rule;
rule << "brains" << open_document << "$gt" << 0 << close_document;
validation.rule(rule.extract());
mongocxx::options::create_collection opts;
opts.validation_criteria(validation);
// Clean up any old collections with this name
if (db.has_collection("zombies")) {
db["zombies"].drop();
}
collection zombies = db.create_collection("zombies", opts);
try {
// Insert a document passing validation
document betty;
betty << "name"
<< "Bloody Betty"
<< "brains" << 3;
auto res = zombies.insert_one(betty.extract());
std::cout << "Bloody Betty passed document validation!" << std::endl;
// Insert a document failing validation
document fred;
fred << "name"
<< "Undead Fred"
<< "brains" << 0;
// Inserting a failing document should throw
auto res2 = zombies.insert_one(fred.extract());
std::cout << "ERROR: server does not support document validation." << std::endl;
} catch (const mongocxx::exception& e) {
std::cout << "Some zombie needs to eat more brains:" << std::endl;
std::cout << e.what() << std::endl;
}
// @end: cpp-create-collection-with-document-validation
}
}
| 34
| 92
| 0.643137
|
CURG-old
|
a0248e1851cfb8395910016eba296900989e99b4
| 1,917
|
cpp
|
C++
|
17. Game_Routes.cpp
|
Anksus/CSES-Graph-solutions
|
6e9ce06abb8a3f5c8a9824add8dd8f31b7cf219c
|
[
"MIT"
] | null | null | null |
17. Game_Routes.cpp
|
Anksus/CSES-Graph-solutions
|
6e9ce06abb8a3f5c8a9824add8dd8f31b7cf219c
|
[
"MIT"
] | null | null | null |
17. Game_Routes.cpp
|
Anksus/CSES-Graph-solutions
|
6e9ce06abb8a3f5c8a9824add8dd8f31b7cf219c
|
[
"MIT"
] | null | null | null |
// While recurring to the destination node, we set all the nodes to 0.
// but the last one to 1 and getting this values pass to all the routes back,
// so that they can be collected back at 1st node.
// act[mxN] is for detecting cycle, just a bellman ford stuff.
// There are 2 approach to solve this problem (according to my knowledge).
// 1. Traditional BFS (gives TLE for large N)
// 2. DP + DFS (works like a charm)
#include <bits/stdc++.h>
using namespace std;
#define pii pair<int,int>
#define int64 int64_t
#define IOS ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define ll long long
#define pb push_back
#define str string
#define ri(x) int x;cin>>x;
#define rl(x) ll x; cin>>x;
#define rs(x) str x; cin>>x;
#define rd(x) d x; cin>>x;
#define w(x) cout<<x;
#define vec(x) std::vector<x>
#define nl '\n'
#define all(x) x.begin(),x.end()
#define map_traverse(it,x) for(auto it = BN(x); it!= ED(x); it++)
#define debug(x) for(auto y : x) {cout<<y<<" ";} cout<<nl;
#define PI 3.14159265358979323846264338327950L
#define rep(i,a,b) for(int i=a;i<b;i++)
#define per(i,n) for(int i=n-1;i>=0;i--)
#define vi vector<int>
const unsigned int M = 1000000007;
int n,m,k,q;
const int mxN=2e5;
const int N = 100031;
bool bad = false;
std::vector<int>a[N],par(mxN,0),vis(mxN,0);
int dp[mxN];
vi adj[mxN]; int act[mxN];
vector<pii> g[mxN];
void dfs(int u){
dp[u] = u==n?1:0;
vis[u]=1;
act[u]=1;
for(auto x: adj[u]){
if(act[x]){
cout<<"IMPOSSIBLE";
exit(0);
}else if(!vis[x]){
par[x]=u;
dfs(x);
}
dp[u] = (dp[x]+dp[u])%M;
}
act[u]=0;
}
void solve(){
cin>>n>>m;
rep(i,0,m){
int a,b;
cin>>a>>b;
adj[a].pb(b);
}
par[1]=-1;
rep(i,1,n+1){
if(!vis[i]){
dfs(i);
}
}
cout<<dp[1];
}
int main(){
IOS;
solve();
}
| 23.378049
| 77
| 0.573292
|
Anksus
|
a028105f6e3e6e5d7a78a3bd808b5bc8619bff86
| 1,249
|
inl
|
C++
|
ZEngine/include/zengine/Debug/Assert.inl
|
AarnoldGad/ZucchiniEngine
|
cb27d2a534a3f21ec59eaa116f052a169a811c06
|
[
"Zlib"
] | 1
|
2020-12-04T17:56:22.000Z
|
2020-12-04T17:56:22.000Z
|
ZEngine/include/zengine/Debug/Assert.inl
|
AarnoldGad/ZEngine
|
cb27d2a534a3f21ec59eaa116f052a169a811c06
|
[
"Zlib"
] | 1
|
2022-02-02T23:24:34.000Z
|
2022-02-02T23:24:34.000Z
|
ZEngine/include/zengine/Debug/Assert.inl
|
AarnoldGad/ZucchiniEngine
|
cb27d2a534a3f21ec59eaa116f052a169a811c06
|
[
"Zlib"
] | null | null | null |
#include <zengine/Memory/New.hpp>
// Inspired by https://www.foonathan.net/2016/09/assertions/
[[noreturn]] inline void ze::AssertHandler::handle(SourceLocation const& location, char const* expression, char const* message) noexcept
{
LOG_TRACE(location.file, "::", location.function, " (", location.line, ") : Assertion failed \"", expression, "\"", (message ? " : " : ""), (message ? message : ""));
std::abort();
}
template<typename EvaluatorFn, typename HandlerType, typename... Args, std::enable_if_t<HandlerType::enabled, int> >
inline void ze::Assert(EvaluatorFn const& evaluator, SourceLocation const& location, char const* expression, HandlerType handler, Args&&... args) noexcept
{
if (!evaluator())
{
handler.handle(location, expression, std::forward<Args>(args)...);
std::abort();
}
}
template<typename EvaluatorFn, typename HandlerType, typename... Args, std::enable_if_t<!HandlerType::enabled, int> >
inline void ze::Assert([[maybe_unused]] EvaluatorFn const& evaluator, [[maybe_unused]] SourceLocation const& location,
[[maybe_unused]] char const* expression, [[maybe_unused]] HandlerType handler, [[maybe_unused]] Args&&... args) noexcept
{}
#include <zengine/Memory/NewOff.hpp>
| 46.259259
| 169
| 0.698959
|
AarnoldGad
|
a02f68e17ca378ce63bfbdc9931fb683cd610aa4
| 1,950
|
cpp
|
C++
|
engine/source/wide/ui/property/basic/ui_property_image.cpp
|
skarab/coffee-master
|
6c3ff71b7f15735e41c9859b6db981b94414c783
|
[
"MIT"
] | null | null | null |
engine/source/wide/ui/property/basic/ui_property_image.cpp
|
skarab/coffee-master
|
6c3ff71b7f15735e41c9859b6db981b94414c783
|
[
"MIT"
] | null | null | null |
engine/source/wide/ui/property/basic/ui_property_image.cpp
|
skarab/coffee-master
|
6c3ff71b7f15735e41c9859b6db981b94414c783
|
[
"MIT"
] | null | null | null |
//------------------------------------------------------------------------------------------------//
/// @file wide/ui/property/basic/ui_property_image.cpp
//------------------------------------------------------------------------------------------------//
//-INCLUDES---------------------------------------------------------------------------------------//
#include "wide/ui/property/basic/ui_property_image.h"
#include "wide/ui/window/ui_window_manager.h"
//------------------------------------------------------------------------------------------------//
namespace coffee
{
//-META---------------------------------------------------------------------------------------//
COFFEE_BeginType(ui::PropertyImage);
COFFEE_Ancestor(ui::Property);
COFFEE_EndType();
namespace ui
{
//-CONSTRUCTORS-------------------------------------------------------------------------------//
PropertyImage::PropertyImage() :
_Image(NULL)
{
}
//--------------------------------------------------------------------------------------------//
PropertyImage::~PropertyImage()
{
}
//-OPERATIONS---------------------------------------------------------------------------------//
void PropertyImage::CreateContent()
{
basic::Image* image = (basic::Image*)GetData();
GetLayout().SetStyle(LAYOUT_STYLE_VerticalCanvas | LAYOUT_STYLE_StickChildren
| LAYOUT_STYLE_HorizontalExpand | LAYOUT_STYLE_VerticalShrink);
_Image = COFFEE_New(widget::Image);
_Image->Create(this, basic::Vector2i(),
basic::Vector2i(),
widget::IMAGE_STYLE_AutoSize | widget::IMAGE_STYLE_DrawFrame);
_Image->GetLayout().SetStyle(LAYOUT_STYLE_HorizontalCanvas
| LAYOUT_STYLE_HorizontalExpand);
_Image->SetImage(*image);
}
}
}
//------------------------------------------------------------------------------------------------//
| 36.111111
| 100
| 0.372308
|
skarab
|
a036b667983dbdbeaca972ec404cf0132a4ea5a3
| 3,348
|
cpp
|
C++
|
game/source/Behaviour/SplashProjectile.cpp
|
kermado/Total-Resistance
|
debaf40ba3be6590a70c9922e1d1a5e075f4ede3
|
[
"MIT"
] | 3
|
2015-04-25T22:57:58.000Z
|
2019-11-05T18:36:31.000Z
|
game/source/Behaviour/SplashProjectile.cpp
|
kermado/Total-Resistance
|
debaf40ba3be6590a70c9922e1d1a5e075f4ede3
|
[
"MIT"
] | 1
|
2016-06-23T15:22:41.000Z
|
2016-06-23T15:22:41.000Z
|
game/source/Behaviour/SplashProjectile.cpp
|
kermado/Total-Resistance
|
debaf40ba3be6590a70c9922e1d1a5e075f4ede3
|
[
"MIT"
] | null | null | null |
#include "Behaviour/SplashProjectile.hpp"
#include <Engine/Audio.hpp>
#include <Engine/Event/CreateGameObjectEvent.hpp>
#include <Engine/Event/DestroyGameObjectEvent.hpp>
#include "ExplosionFactory.hpp"
#include "Attribute/Tags.hpp"
#include "Event/InflictDamageEvent.hpp"
namespace Behaviour
{
SplashProjectile::SplashProjectile(std::shared_ptr<Engine::Window> window,
std::shared_ptr<Engine::ResourceManager> resourceManager,
std::shared_ptr<Engine::EventDispatcher> sceneEventDispatcher,
std::shared_ptr<Engine::EventDispatcher> gameObjectEventDispatcher,
std::weak_ptr<Engine::GameObject> gameObject,
std::shared_ptr<Engine::Attribute::Transform> transformAttribute,
const PlayingSurface& playingSurface,
std::string tag,
float damage)
: IBehaviour(window, resourceManager, sceneEventDispatcher, gameObjectEventDispatcher, gameObject)
, m_transformAttribute(transformAttribute)
, m_playingSurface(playingSurface)
, m_tag(tag)
, m_damage(damage)
, m_explosionFactory(std::make_shared<ExplosionFactory>())
, m_inRange()
, m_collisionSubscription(0)
{
// Subscribe to receive CollisionEvents.
m_collisionSubscription = GetGameObjectEventDispatcher()->Subscribe<Engine::Event::CollisionEvent>(
[this](const Engine::Event::CollisionEvent& event)
{
std::shared_ptr<Engine::GameObject> otherGameObject = event.GetOtherGameObject();
if (!otherGameObject->IsDead() && otherGameObject->HasAttribute<Attribute::Tags>())
{
std::shared_ptr<Attribute::Tags> tagsAttribute =
otherGameObject->GetAttribute<Attribute::Tags>();
if (tagsAttribute->HasTag(m_tag))
{
m_inRange.push_back(otherGameObject);
}
}
}
);
}
SplashProjectile::~SplashProjectile()
{
// Unsubscribe for CollisionEvents.
GetGameObjectEventDispatcher()->Unsubscribe<Engine::Event::CollisionEvent>(m_collisionSubscription);
}
void SplashProjectile::Update(double deltaTime)
{
const glm::vec3 position = m_transformAttribute->GetPosition();
const glm::vec2 playingSurfaceHalfDimensions = m_playingSurface.GetDimensions() * 0.5f;
// TODO: Add check for elevation above ground.
if (position.x < - playingSurfaceHalfDimensions.x ||
position.x > playingSurfaceHalfDimensions.x ||
position.z < - playingSurfaceHalfDimensions.y ||
position.z > playingSurfaceHalfDimensions.y ||
position.y < 0.0f)
{
// If the projectile has hit the ground, then inflict damage on
// the Game Objects within range.
if (position.y < 0.0f)
{
for (std::shared_ptr<Engine::GameObject> gameObject : m_inRange)
{
gameObject->BroadcastEnqueue<Event::InflictDamageEvent>(m_damage);
}
// Play a large explosion sound.
Engine::Audio::GetInstance().Play(GetResourceManager()->GetAudio("resources/audio/MissileExplosion.wav"));
}
GetSceneEventDispatcher()->Enqueue<Engine::Event::CreateGameObjectEvent>(
m_explosionFactory,
[this](std::shared_ptr<Engine::GameObject> explosion)
{
std::shared_ptr<Engine::Attribute::Transform> transform =
explosion->GetAttribute<Engine::Attribute::Transform>();
transform->SetPosition(m_transformAttribute->GetPosition());
}
);
GetGameObjectEventDispatcher()->Enqueue<Engine::Event::DestroyGameObjectEvent>();
}
// Clear the list of Game Objects in range.
m_inRange.clear();
}
}
| 33.818182
| 110
| 0.744325
|
kermado
|
a0406ccdce644546f2185d212f0c2f34a8cf96ba
| 354
|
hpp
|
C++
|
src/communication.hpp
|
linyinfeng/n-body
|
e40c859689d76a3f36cd08e072d7ee24685e8be4
|
[
"MIT"
] | 1
|
2021-11-28T15:13:06.000Z
|
2021-11-28T15:13:06.000Z
|
src/communication.hpp
|
linyinfeng/n-body
|
e40c859689d76a3f36cd08e072d7ee24685e8be4
|
[
"MIT"
] | null | null | null |
src/communication.hpp
|
linyinfeng/n-body
|
e40c859689d76a3f36cd08e072d7ee24685e8be4
|
[
"MIT"
] | 1
|
2019-11-10T14:01:55.000Z
|
2019-11-10T14:01:55.000Z
|
#ifndef N_BODY_COMMUNICATION_HPP
#define N_BODY_COMMUNICATION_HPP
#include <boost/mpi.hpp>
#include <cstddef>
namespace n_body::communication {
struct Division {
std::size_t count;
std::size_t begin;
std::size_t end;
explicit Division(const boost::mpi::communicator &comm, std::size_t total);
};
} // namespace n_body::communication
#endif
| 17.7
| 77
| 0.751412
|
linyinfeng
|
a04221971486748c6703dd6b1138f6b3e6465e7b
| 4,217
|
cpp
|
C++
|
src/interpreter.cpp
|
nirvanasupermind/pocketlisp
|
2a4b5aca245c547d88f581fefd89cca5473d8a1f
|
[
"MIT"
] | 1
|
2022-03-18T18:43:04.000Z
|
2022-03-18T18:43:04.000Z
|
src/interpreter.cpp
|
nirvanasupermind/pocketlisp
|
2a4b5aca245c547d88f581fefd89cca5473d8a1f
|
[
"MIT"
] | null | null | null |
src/interpreter.cpp
|
nirvanasupermind/pocketlisp
|
2a4b5aca245c547d88f581fefd89cca5473d8a1f
|
[
"MIT"
] | null | null | null |
#include "./parser.cpp"
#include "./scopes.cpp"
#include "./utils.cpp"
namespace lispy
{
class Interpreter
{
public:
std::string file;
Interpreter(std::string file)
{
this->file = file;
}
Value visit(Node node, Scope *scope)
{
std::cout << node.str() << '\n';
switch (node.type)
{
case NumberNode:
return visit_number_node(node, scope);
case SymbolNode:
return visit_symbol_node(node, scope);
default:
return visit_list_node(node, scope);
}
}
Value visit_number_node(Node node, Scope *scope)
{
return Value(ValueType::Number, node.value);
}
Value visit_symbol_node(Node node, Scope *scope)
{
Value *result = scope->get(node.symbol);
if(result == NULL) {
std::cout << file << ':' << node.ln << ": "
<< "unbound variable '"+node.symbol+"'" << '\n';
std::exit(EXIT_FAILURE);
}
return *result;
}
Value visit_list_node(Node node, Scope *scope)
{
if(node.nodes.size() == 0)
return Value();
std::string tag = node.nodes[0].symbol;
// std::cout << node.nodes[1].str() << '\n';
if (tag == "def")
{
add_variable(node.ln, node.nodes[1], node.nodes[2], scope);
}
else if (tag == "let")
{
if (node.nodes[1].type != NodeType::ListNode || node.nodes[2].type != NodeType::ListNode)
{
std::cout << file << ':' << node.ln << ": "
<< "bad let expression" << '\n';
std::exit(EXIT_FAILURE);
}
Scope *child_scope = new Scope(scope);
for (int i = 0; i < node.nodes[1].nodes.size(); i++)
{
if (node.nodes[1].nodes[i].type != NodeType::ListNode)
{
std::cout << file << ':' << node.ln << ": "
<< "bad let expression" << '\n';
std::exit(EXIT_FAILURE);
}
add_variable(node.ln, node.nodes[1].nodes[i].nodes[0], node.nodes[1].nodes[i].nodes[1], child_scope);
}
for (int i = 0; i < node.nodes[2].nodes.size() - 1; i++)
{
visit(node.nodes[2].nodes[i], child_scope);
}
if(node.nodes[2].nodes.size() == 0)
return Value();
return visit(node.nodes[2].nodes[node.nodes[2].nodes.size() - 1], child_scope);
}
else
{
Value func = visit(node.nodes[0], scope);
if (func.type != ValueType::Function)
{
std::cout << file << ':' << node.ln << ": "
<< "call of non-function: " << func.str() << '\n';
std::exit(EXIT_FAILURE);
}
std::vector<Value> args;
for (int i = 1; i < node.nodes.size(); i++)
{
args.push_back(visit(node.nodes[i], scope));
}
return func.function(file, node.ln, args);
}
}
// In a seperate utility function as this code is repeated several times throughout the visit_list_node method
Value add_variable(int ln, Node name_node, Node val_node, Scope *scope)
{
if (name_node.type != NodeType::SymbolNode)
{
std::cout << file << ':' << ln << ": "
<< "bad variable definition" << '\n';
std::exit(EXIT_FAILURE);
}
std::string name = name_node.symbol;
Value value = visit(val_node, scope);
scope->set(name, &value);
return value;
}
};
}
| 31.007353
| 121
| 0.417595
|
nirvanasupermind
|
a043887263fac9b983f96da13c7c3292e444f870
| 257
|
cpp
|
C++
|
3.Stacks and Queues/Queue_STL.cpp
|
suraj0803/DSA
|
6ea21e452d7662e2351ee2a7b0415722e1bbf094
|
[
"MIT"
] | null | null | null |
3.Stacks and Queues/Queue_STL.cpp
|
suraj0803/DSA
|
6ea21e452d7662e2351ee2a7b0415722e1bbf094
|
[
"MIT"
] | null | null | null |
3.Stacks and Queues/Queue_STL.cpp
|
suraj0803/DSA
|
6ea21e452d7662e2351ee2a7b0415722e1bbf094
|
[
"MIT"
] | null | null | null |
#include<iostream>
#include<queue>
using namespace std;
int main()
{
queue<int> q;
for(int i=0; i<5; i++){
q.push(i);
}
while(!q.empty()){
cout<<q.front()<<" <-";
q.pop();
}
return 0;
}
| 12.85
| 32
| 0.424125
|
suraj0803
|
a04992790c1b99c1b77e7f32a3d8c02b1009cae9
| 3,464
|
cpp
|
C++
|
package/win32/android/gameplay/src/Layout.cpp
|
sharkpp/openhsp
|
0d412fd8f79a6ccae1d33c13addc06fb623fb1fe
|
[
"BSD-3-Clause"
] | 1
|
2021-06-17T02:16:22.000Z
|
2021-06-17T02:16:22.000Z
|
package/win32/android/gameplay/src/Layout.cpp
|
sharkpp/openhsp
|
0d412fd8f79a6ccae1d33c13addc06fb623fb1fe
|
[
"BSD-3-Clause"
] | null | null | null |
package/win32/android/gameplay/src/Layout.cpp
|
sharkpp/openhsp
|
0d412fd8f79a6ccae1d33c13addc06fb623fb1fe
|
[
"BSD-3-Clause"
] | 1
|
2021-06-17T02:16:23.000Z
|
2021-06-17T02:16:23.000Z
|
#include "Base.h"
#include "Layout.h"
#include "Control.h"
#include "Container.h"
namespace gameplay
{
void Layout::align(Control* control, const Container* container)
{
GP_ASSERT(control);
GP_ASSERT(container);
if (control->_alignment != Control::ALIGN_TOP_LEFT ||
control->_isAlignmentSet ||
control->_autoWidth || control->_autoHeight)
{
Rectangle controlBounds = control->getBounds();
const Theme::Margin& controlMargin = control->getMargin();
const Rectangle& containerBounds = container->getBounds();
const Theme::Border& containerBorder = container->getBorder(container->getState());
const Theme::Padding& containerPadding = container->getPadding();
float clipWidth;
float clipHeight;
if (container->getScroll() != Container::SCROLL_NONE)
{
const Rectangle& verticalScrollBarBounds = container->getImageRegion("verticalScrollBar", container->getState());
const Rectangle& horizontalScrollBarBounds = container->getImageRegion("horizontalScrollBar", container->getState());
clipWidth = containerBounds.width - containerBorder.left - containerBorder.right - containerPadding.left - containerPadding.right - verticalScrollBarBounds.width;
clipHeight = containerBounds.height - containerBorder.top - containerBorder.bottom - containerPadding.top - containerPadding.bottom - horizontalScrollBarBounds.height;
}
else
{
clipWidth = containerBounds.width - containerBorder.left - containerBorder.right - containerPadding.left - containerPadding.right;
clipHeight = containerBounds.height - containerBorder.top - containerBorder.bottom - containerPadding.top - containerPadding.bottom;
}
if (control->_autoWidth)
{
controlBounds.width = clipWidth - controlMargin.left - controlMargin.right;
}
if (control->_autoHeight)
{
controlBounds.height = clipHeight - controlMargin.top - controlMargin.bottom;
}
// Vertical alignment
if ((control->_alignment & Control::ALIGN_BOTTOM) == Control::ALIGN_BOTTOM)
{
controlBounds.y = clipHeight - controlBounds.height - controlMargin.bottom;
}
else if ((control->_alignment & Control::ALIGN_VCENTER) == Control::ALIGN_VCENTER)
{
controlBounds.y = clipHeight * 0.5f - controlBounds.height * 0.5f;
}
else if ((control->_alignment & Control::ALIGN_TOP) == Control::ALIGN_TOP)
{
controlBounds.y = controlMargin.top;
}
// Horizontal alignment
if ((control->_alignment & Control::ALIGN_RIGHT) == Control::ALIGN_RIGHT)
{
controlBounds.x = clipWidth - controlBounds.width - controlMargin.right;
}
else if ((control->_alignment & Control::ALIGN_HCENTER) == Control::ALIGN_HCENTER)
{
controlBounds.x = clipWidth * 0.5f - controlBounds.width * 0.5f;
}
else if ((control->_alignment & Control::ALIGN_LEFT) == Control::ALIGN_LEFT)
{
controlBounds.x = controlMargin.left;
}
control->setBounds(controlBounds);
}
}
bool Layout::touchEvent(Touch::TouchEvent evt, int x, int y, unsigned int contactIndex)
{
return false;
}
}
| 40.27907
| 180
| 0.637413
|
sharkpp
|
a04c7ab0203bbceaa445fee1a93471cb65575331
| 1,474
|
cpp
|
C++
|
src/prod/src/data/txnreplicator/RuntimeFolders.cpp
|
vishnuk007/service-fabric
|
d0afdea185ae932cc3c9eacf179692e6fddbc630
|
[
"MIT"
] | 2,542
|
2018-03-14T21:56:12.000Z
|
2019-05-06T01:18:20.000Z
|
src/prod/src/data/txnreplicator/RuntimeFolders.cpp
|
vishnuk007/service-fabric
|
d0afdea185ae932cc3c9eacf179692e6fddbc630
|
[
"MIT"
] | 994
|
2019-05-07T02:39:30.000Z
|
2022-03-31T13:23:04.000Z
|
src/prod/src/data/txnreplicator/RuntimeFolders.cpp
|
vishnuk007/service-fabric
|
d0afdea185ae932cc3c9eacf179692e6fddbc630
|
[
"MIT"
] | 300
|
2018-03-14T21:57:17.000Z
|
2019-05-06T20:07:00.000Z
|
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "stdafx.h"
using namespace ktl;
using namespace TxnReplicator;
RuntimeFolders::RuntimeFolders(__in LPCWSTR workDirectory)
: KObject()
, KShared()
, workDirectory_()
{
NTSTATUS status = KString::Create(
workDirectory_,
GetThisAllocator(),
workDirectory);
THROW_ON_FAILURE(status);
}
RuntimeFolders::~RuntimeFolders()
{
}
IRuntimeFolders::SPtr RuntimeFolders::Create(
__in IFabricCodePackageActivationContext & codePackage,
__in KAllocator& allocator)
{
RuntimeFolders * pointer = _new(RUNTIMEFOLDERS_TAG, allocator)RuntimeFolders(codePackage.get_WorkDirectory());
THROW_ON_ALLOCATION_FAILURE(pointer);
return IRuntimeFolders::SPtr(pointer);
}
IRuntimeFolders::SPtr RuntimeFolders::Create(
__in IFabricTransactionalReplicatorRuntimeConfigurations & runtimeConfigurations,
__in KAllocator& allocator)
{
RuntimeFolders * pointer = _new(RUNTIMEFOLDERS_TAG, allocator)RuntimeFolders(runtimeConfigurations.get_WorkDirectory());
THROW_ON_ALLOCATION_FAILURE(pointer);
return IRuntimeFolders::SPtr(pointer);
}
LPCWSTR RuntimeFolders::get_WorkDirectory() const
{
return *workDirectory_;
}
| 28.346154
| 124
| 0.694708
|
vishnuk007
|
a05100200dbd0ae514766364c276a2c3061690f4
| 13,826
|
cpp
|
C++
|
src/snmp/session.cpp
|
Aseman-Land/QtSnmp
|
4e04214d94324d4ed43d15ea77950b026bfd9b3b
|
[
"MIT"
] | null | null | null |
src/snmp/session.cpp
|
Aseman-Land/QtSnmp
|
4e04214d94324d4ed43d15ea77950b026bfd9b3b
|
[
"MIT"
] | null | null | null |
src/snmp/session.cpp
|
Aseman-Land/QtSnmp
|
4e04214d94324d4ed43d15ea77950b026bfd9b3b
|
[
"MIT"
] | null | null | null |
#include "session.h"
#include "qtsnmpdata.h"
#include "requestvaluesjob.h"
#include "requestsubvaluesjob.h"
#include "setvaluejob.h"
#include "defines.h"
#include <QDateTime>
#include <QHostAddress>
#include <math.h>
namespace qtsnmpclient {
namespace {
const int default_response_timeout = 10000;
const quint16 SnmpPort = 161;
QString errorStatusText( const int val ) {
switch( val ) {
case 0:
return "No errors";
case 1:
return "Too big";
case 2:
return "No such name";
case 3:
return "Bad value";
case 4:
return "Read only";
case 5:
return "Other errors";
default:
Q_ASSERT( false );
break;
}
return QString( "Unsupported error(%1)" ).arg( val );
}
}
Session::Session( QObject*const parent )
: QObject( parent )
, m_community( "public" )
, m_socket( new QUdpSocket( this ) )
, m_response_wait_timer( new QTimer( this ) )
{
connect( m_socket,
SIGNAL(readyRead()),
SLOT(onReadyRead()) );
connect( m_response_wait_timer,
SIGNAL(timeout()),
SLOT(cancelWork()) );
m_response_wait_timer->setInterval( default_response_timeout );
}
QHostAddress Session::agentAddress() const {
return m_agent_address;
}
void Session::setAgentAddress( const QHostAddress& value ) {
bool ok = !value.isNull();
ok = ok && ( QHostAddress( QHostAddress::Any ) != value );
if( ok ) {
m_agent_address = value;
m_socket->close();
m_socket->bind();
} else {
qWarning() << Q_FUNC_INFO << "attempt to set invalid agent address( " << value << ")";
}
}
QByteArray Session::community() const {
return m_community;
}
void Session::setCommunity( const QByteArray& value ) {
m_community = value;
}
int Session::responseTimeout() const {
return m_response_wait_timer->interval();
}
void Session::setResponseTimeout( const int value ) {
if( value != m_response_wait_timer->interval() ) {
m_response_wait_timer->setInterval( value );
}
}
bool Session::isBusy() const {
return !m_current_work.isNull() || !m_work_queue.isEmpty();
}
qint32 Session::requestValues( const QStringList& oid_list ) {
const qint32 work_id = createWorkId();
addWork( JobPointer( new RequestValuesJob( this,
work_id,
oid_list) ) );
return work_id;
}
qint32 Session::requestSubValues( const QString& oid ) {
const qint32 work_id = createWorkId();
addWork( JobPointer( new RequestSubValuesJob( this,
work_id,
oid ) ) );
return work_id;
}
qint32 Session::setValue( const QByteArray& community,
const QString& oid,
const int type,
const QByteArray& value )
{
const qint32 work_id = createWorkId();
addWork( JobPointer( new SetValueJob( this,
work_id,
community,
oid,
type,
value ) ) );
return work_id;
}
void Session::addWork( const JobPointer& work ) {
#ifndef Q_CC_MSVC
IN_QOBJECT_THREAD( work );
#endif
const int queue_limit = 10;
if( m_work_queue.count() < queue_limit ) {
m_work_queue.push_back( work );
startNextWork();
} else {
qWarning() << "Warning: snmp request( " << work->description() << ") "
<< "to " << m_agent_address.toString() << " dropped, queue if full";
}
}
void Session::startNextWork() {
if( m_current_work.isNull() && !m_work_queue.isEmpty() ){
m_current_work = m_work_queue.takeFirst();
m_current_work->start();
}
}
void Session::completeWork( const QtSnmpDataList& values ) {
Q_ASSERT( ! m_current_work.isNull() );
emit responseReceived( m_current_work->id(), values );
m_current_work.clear();
startNextWork();
}
void Session::cancelWork() {
if( !m_current_work.isNull() ) {
emit requestFailed( m_current_work->id() );
m_current_work.clear();
}
m_response_wait_timer->stop();
m_request_id = -1;
startNextWork();
}
void Session::sendRequestGetValues( const QStringList& names ) {
Q_ASSERT( -1 == m_request_id );
if( -1 == m_request_id ) {
updateRequestId();
QtSnmpData full_packet = QtSnmpData::sequence();
full_packet.addChild( QtSnmpData::integer( 0 ) );
full_packet.addChild( QtSnmpData::string( m_community ) );
QtSnmpData request( QtSnmpData::GET_REQUEST_TYPE );
request.addChild( QtSnmpData::integer( m_request_id ) );
request.addChild( QtSnmpData::integer( 0 ) );
request.addChild( QtSnmpData::integer( 0 ) );
QtSnmpData seq_all_obj = QtSnmpData::sequence();
for( const auto& oid_key : names ) {
QtSnmpData seq_obj_info = QtSnmpData::sequence();
seq_obj_info.addChild( QtSnmpData::oid( oid_key.toLatin1() ) );
seq_obj_info.addChild( QtSnmpData::null() );
seq_all_obj.addChild( seq_obj_info );
}
request.addChild( seq_all_obj );
full_packet.addChild( request );
sendDatagram( full_packet.makeSnmpChunk() );
} else {
qWarning() << Q_FUNC_INFO << "we already wait response";
}
}
void Session::sendRequestGetNextValue( const QString& name ) {
Q_ASSERT( -1 == m_request_id );
if( -1 == m_request_id ) {
updateRequestId();
QtSnmpData full_packet = QtSnmpData::sequence();
full_packet.addChild( QtSnmpData::integer( 0 ) );
full_packet.addChild( QtSnmpData::string( m_community ) );
QtSnmpData request( QtSnmpData::GET_NEXT_REQUEST_TYPE );
request.addChild( QtSnmpData::integer( m_request_id ) );
request.addChild( QtSnmpData::integer( 0 ) );
request.addChild( QtSnmpData::integer( 0 ) );
QtSnmpData seq_all_obj = QtSnmpData::sequence();
QtSnmpData seq_obj_info = QtSnmpData::sequence();
seq_obj_info.addChild( QtSnmpData::oid( name.toLatin1() ) );
seq_obj_info.addChild( QtSnmpData::null() );
seq_all_obj.addChild( seq_obj_info );
request.addChild( seq_all_obj );
full_packet.addChild( request );
sendDatagram( full_packet.makeSnmpChunk() );
} else {
qWarning() << Q_FUNC_INFO << "we already wait response";
}
}
void Session::sendRequestSetValue( const QByteArray& community,
const QString& name,
const int type,
const QByteArray& value )
{
Q_ASSERT( -1 == m_request_id );
if( -1 == m_request_id ) {
updateRequestId();
auto pdu_packet = QtSnmpData::sequence();
pdu_packet.addChild( QtSnmpData::integer( 0 ) );
pdu_packet.addChild( QtSnmpData::string( community ) );
auto request_type = QtSnmpData( QtSnmpData::SET_REQUEST_TYPE );
request_type.addChild( QtSnmpData::integer( m_request_id ) );
request_type.addChild( QtSnmpData::integer( 0 ) );
request_type.addChild( QtSnmpData::integer( 0 ) );
auto seq_all_obj = QtSnmpData::sequence();
auto seq_obj_info = QtSnmpData::sequence();
seq_obj_info.addChild( QtSnmpData::oid( name.toLatin1() ) );
seq_obj_info.addChild( QtSnmpData( type, value ) );
seq_all_obj.addChild( seq_obj_info );
request_type.addChild( seq_all_obj );
pdu_packet.addChild( request_type );
sendDatagram( pdu_packet.makeSnmpChunk() );
} else {
qWarning() << Q_FUNC_INFO << "we already wait response";
}
}
void Session::onReadyRead() {
const int size = static_cast< int >( m_socket->pendingDatagramSize() );
if( size ) {
QByteArray datagram;
datagram.resize( size );
m_socket->readDatagram( datagram.data(), size );
const auto& list = getResponseData( datagram );
if( !list.isEmpty() ) {
Q_ASSERT( !m_current_work.isNull() );
m_current_work->processData( list );
}
}
}
QtSnmpDataList Session::getResponseData( const QByteArray& datagram ) {
QtSnmpDataList result;
const auto list = QtSnmpData::parseData( datagram );
Q_ASSERT( !list.isEmpty() );
for( const auto& packet : list ) {
const QtSnmpDataList resp_list = packet.children();
if( 3 == resp_list.count() ) {
const auto& resp = resp_list.at( 2 );
Q_ASSERT( QtSnmpData::GET_RESPONSE_TYPE == resp.type() );
if( QtSnmpData::GET_RESPONSE_TYPE != resp.type() ) {
qWarning() << Q_FUNC_INFO << "Err: unexpected response type";
return result;
}
const auto& children = resp.children();
Q_ASSERT( 4 == children.count() );
if( 4 != children.count() ) {
qWarning() << Q_FUNC_INFO << "Err: unexpected child count";
return result;
}
const auto& request_id_data = children.at( 0 );
Q_ASSERT( QtSnmpData::INTEGER_TYPE == request_id_data.type() );
if( QtSnmpData::INTEGER_TYPE != request_id_data.type() ) {
qWarning() << Q_FUNC_INFO << "Err: request id type";
return result;
}
const int response_req_id = request_id_data.intValue();
Q_ASSERT( response_req_id == m_request_id );
if( response_req_id == m_request_id ) {
m_response_wait_timer->stop();
m_request_id = -1;
} else {
qWarning() << Q_FUNC_INFO
<< "Err: unexpected request_id: " << response_req_id
<< " (expected: " << m_request_id << ")";
return result;
}
const auto& error_state_data = children.at( 1 );
Q_ASSERT( QtSnmpData::INTEGER_TYPE == error_state_data.type() );
if( QtSnmpData::INTEGER_TYPE != error_state_data.type() ) {
qWarning() << Q_FUNC_INFO << "Err: unexpected error state type";
return result;
}
const auto& error_index_data = children.at( 2 );
Q_ASSERT( QtSnmpData::INTEGER_TYPE == error_index_data.type() );
if( QtSnmpData::INTEGER_TYPE != error_index_data.type() ) {
qWarning() << Q_FUNC_INFO << "Err: unexpected error index type";
return result;
}
const int err_st = error_state_data.intValue();
const int err_in = error_index_data.intValue();
if( err_st || err_in ) {
qWarning() << Q_FUNC_INFO << QString( "error [ status: %1; index: %2 ] in answer from %3 for %4" )
.arg( errorStatusText( err_st ) )
.arg( QString::number( err_in ) )
.arg( m_agent_address.toString() )
.arg( m_current_work->description() );
cancelWork();
return result;
}
const auto& variable_list_data = children.at( 3 );
Q_ASSERT( QtSnmpData::SEQUENCE_TYPE == variable_list_data.type() );
if( QtSnmpData::SEQUENCE_TYPE != variable_list_data.type() ) {
qWarning() << Q_FUNC_INFO << "Err: unexpected variable list type";
return result;
}
const auto& variable_list = variable_list_data.children();
for( int i = variable_list.count() - 1; i >= 0; --i ) {
const auto& variable = variable_list.at( i );
if( QtSnmpData::SEQUENCE_TYPE == variable.type() ) {
const QtSnmpDataList& items = variable.children();
if( 2 == items.count() ) {
const auto& object = items.at( 0 );
if( QtSnmpData::OBJECT_TYPE == object.type() ) {
auto result_item = items.at( 1 );
result_item.setAddress( object.data() );
result << result_item;
} else {
qWarning() << Q_FUNC_INFO << "invalid packet content";
Q_ASSERT( false );
}
} else {
qWarning() << Q_FUNC_INFO << "invalid packet type";
Q_ASSERT( false );
}
} else {
qWarning() << Q_FUNC_INFO << "invalid packet type";
Q_ASSERT( false );
}
}
} else {
qWarning() << Q_FUNC_INFO << "parse_get_response error 2";
}
}
return result;
}
void Session::sendDatagram( const QByteArray& datagram ) {
if( m_socket->writeDatagram( datagram, m_agent_address, SnmpPort ) ) {
Q_ASSERT( ! m_response_wait_timer->isActive() );
m_response_wait_timer->start();
} else {
Q_ASSERT( false );
cancelWork();
}
}
qint32 Session::createWorkId() {
++m_work_id;
if( m_work_id < 1 ) {
m_work_id = 1;
} else if( m_work_id > 0x7FFF ) {
m_work_id = 1;
}
return m_work_id;
}
void Session::updateRequestId() {
m_request_id = 1 + abs( rand() ) % 0x7FFF;
}
} // namespace qtsnmpclient
| 36.193717
| 114
| 0.553595
|
Aseman-Land
|
a054a212010b793ac03b4ef74271f1b57987dc30
| 2,663
|
cpp
|
C++
|
Source Code V2/TssTest/RickerSource.cpp
|
DavidGeUSA/TSS
|
e364e324948c68efc6362a0db3aa51696227fa60
|
[
"MIT"
] | 11
|
2020-09-27T07:35:22.000Z
|
2022-03-09T11:01:31.000Z
|
Source Code V2/TssTest/RickerSource.cpp
|
DavidGeUSA/TSS
|
e364e324948c68efc6362a0db3aa51696227fa60
|
[
"MIT"
] | 1
|
2020-10-28T13:14:58.000Z
|
2020-10-28T21:04:44.000Z
|
Source Code V2/TssTest/RickerSource.cpp
|
DavidGeUSA/TSS
|
e364e324948c68efc6362a0db3aa51696227fa60
|
[
"MIT"
] | 7
|
2020-09-27T07:35:24.000Z
|
2022-01-02T13:53:21.000Z
|
/*******************************************************************
Author: David Ge (dge893@gmail.com, aka Wei Ge)
Last modified: 11/21/2020
Allrights reserved by David Ge
field source of Ricker function
********************************************************************/
#include "RickerSource.h"
RickerSource::RickerSource()
{
courant = 1.0 / sqrt(3.0);
}
RickerSource::~RickerSource()
{
}
#define TP_FS_PPW "FS.PPW"
int RickerSource::initialize(TaskFile *configs)
{
int ret = ERR_OK;
ppw = configs->getDouble(TP_FS_PPW, false);
ret = configs->getErrorCode();
if (ret == ERR_OK)
{
if (ppw <= 0.0)
{
ret = ERR_TASK_INVALID_VALUE;
configs->setNameOfInvalidValue(TP_FS_PPW);
}
}
return ret;
}
int RickerSource::initialize(SimStruct *params)
{
int ret = FieldSourceTss::initialize(params);
i0 = pams->nx / 2;
j0 = pams->ny / 2;
k0 = pams->nz / 2;
w0 = k0 + (pams->nz + 1)*(j0 + (pams->ny + 1)*i0);
iN = i0 - pams->smax;
iP = i0 + pams->smax;
jN = j0 - pams->smax;
jP = j0 + pams->smax;
kN = k0 - pams->smax;
kP = k0 + pams->smax;
return ret;
}
bool RickerSource::isInSource(unsigned int i, unsigned int j, unsigned int k)
{
return (i >= iN && i <= iP && j >= jN && j <= jP && k >= kN && k <= kP);
}
int RickerSource::applySources(double t, size_t tIndex, Point3Dstruct *efile, Point3Dstruct *hfile)
{
int ret = ERR_OK;
//H = C.F.dJm + C.G.dJe + ...
//E = C.U.dJe + C.W.dJm + ...
if (pams->kmax == 0)
{
//g[0] = 0
//u[0]*Je
//apply at center
//int i = pams->nx / 2;
//int j = pams->ny / 2;
//int k = pams->nz / 2;
double arg;
arg = M_PI * ((courant * (double)tIndex - 0.0) / ppw - 1.0);
arg = arg * arg;
arg = (1.0 - 2.0 * arg) * exp(-arg);
efile[w0].z += arg;
}
else //if (pams->kmax == 1)
{
//int i = pams->nx / 2;
//int j = pams->ny / 2;
//int k = pams->nz / 2;
double arg;
arg = M_PI * ((courant * (double)tIndex - 0.0) / ppw - 1.0);
arg = arg * arg;
arg = (1.0 - 2.0 * arg) * exp(-arg);
efile[w0].z += arg;
}
return ret;
}
int RickerSource::applyToZrotateSymmetry(double t, size_t tIndex, RotateSymmetryField *efile, RotateSymmetryField *hfile)
{
int ret = ERR_OK;
//H = C.F.dJm + C.G.dJe + ...
//E = C.U.dJe + C.W.dJm + ...
//
//g[0] = 0
//u[0]*Je
//apply at center
//int i = pams->nx / 2;
//int j = pams->ny / 2;
//int k = pams->nz / 2;
double arg;
arg = M_PI * ((courant * (double)tIndex - 0.0) / ppw - 1.0);
arg = arg * arg;
arg = (1.0 - 2.0 * arg) * exp(-arg);
//efile[w0].z += arg;
(efile->getFieldOnPlane(i0, k0))->z += arg;
return ret;
}
| 24.657407
| 122
| 0.524972
|
DavidGeUSA
|
a05608ff85f4cba18a3d7f4b7eb83ecb96cb4308
| 96,243
|
cpp
|
C++
|
quantlibnode.cpp
|
quantlibnode/quantlibnode
|
b50348131af77a2b6c295f44ef3245daf05c4afc
|
[
"MIT"
] | 27
|
2016-11-19T16:51:21.000Z
|
2021-09-08T16:44:15.000Z
|
quantlibnode.cpp
|
quantlibnode/quantlibnode
|
b50348131af77a2b6c295f44ef3245daf05c4afc
|
[
"MIT"
] | 1
|
2016-12-28T16:38:38.000Z
|
2017-02-17T05:32:13.000Z
|
quantlibnode.cpp
|
quantlibnode/quantlibnode
|
b50348131af77a2b6c295f44ef3245daf05c4afc
|
[
"MIT"
] | 10
|
2016-12-28T02:31:38.000Z
|
2021-06-15T09:02:07.000Z
|
/*
Copyright (C) 2016 -2017 Jerry Jin
*/
#include <v8.h>
#include <node.h>
#include <nan.h>
#include "quantlibnode.hpp"
#include <oh/repository.hpp>
#include <oh/enumerations/typefactory.hpp>
#include <oh/enumerations/enumregistry.hpp>
#include <qlo/enumerations/register/register_all.hpp>
using namespace node;
using namespace v8;
NAN_MODULE_INIT(init){
static ObjectHandler::Repository repository;
static ObjectHandler::ProcessorFactory processorFactory;
static ObjectHandler::EnumTypeRegistry enumTypeRegistry;
static ObjectHandler::EnumClassRegistry enumClassRegistry;
static ObjectHandler::EnumPairRegistry enumPairRegistry;
QuantLibAddin::registerEnumerations();
Nan::SetMethod(target, "AbcdFunction", QuantLibNode::AbcdFunction);
Nan::SetMethod(target, "AbcdCalibration", QuantLibNode::AbcdCalibration);
Nan::SetMethod(target, "AbcdFunctionInstantaneousValue", QuantLibNode::AbcdFunctionInstantaneousValue);
Nan::SetMethod(target, "AbcdFunctionInstantaneousCovariance", QuantLibNode::AbcdFunctionInstantaneousCovariance);
Nan::SetMethod(target, "AbcdFunctionInstantaneousVariance", QuantLibNode::AbcdFunctionInstantaneousVariance);
Nan::SetMethod(target, "AbcdFunctionInstantaneousVolatility", QuantLibNode::AbcdFunctionInstantaneousVolatility);
Nan::SetMethod(target, "AbcdFunctionCovariance", QuantLibNode::AbcdFunctionCovariance);
Nan::SetMethod(target, "AbcdFunctionVariance", QuantLibNode::AbcdFunctionVariance);
Nan::SetMethod(target, "AbcdFunctionVolatility", QuantLibNode::AbcdFunctionVolatility);
Nan::SetMethod(target, "AbcdFunctionShortTermVolatility", QuantLibNode::AbcdFunctionShortTermVolatility);
Nan::SetMethod(target, "AbcdFunctionLongTermVolatility", QuantLibNode::AbcdFunctionLongTermVolatility);
Nan::SetMethod(target, "AbcdFunctionMaximumLocation", QuantLibNode::AbcdFunctionMaximumLocation);
Nan::SetMethod(target, "AbcdFunctionMaximumVolatility", QuantLibNode::AbcdFunctionMaximumVolatility);
Nan::SetMethod(target, "AbcdFunctionA", QuantLibNode::AbcdFunctionA);
Nan::SetMethod(target, "AbcdFunctionB", QuantLibNode::AbcdFunctionB);
Nan::SetMethod(target, "AbcdFunctionC", QuantLibNode::AbcdFunctionC);
Nan::SetMethod(target, "AbcdFunctionD", QuantLibNode::AbcdFunctionD);
Nan::SetMethod(target, "AbcdDFunction", QuantLibNode::AbcdDFunction);
Nan::SetMethod(target, "AbcdCalibrationCompute", QuantLibNode::AbcdCalibrationCompute);
Nan::SetMethod(target, "AbcdCalibrationK", QuantLibNode::AbcdCalibrationK);
Nan::SetMethod(target, "AbcdCalibrationError", QuantLibNode::AbcdCalibrationError);
Nan::SetMethod(target, "AbcdCalibrationMaxError", QuantLibNode::AbcdCalibrationMaxError);
Nan::SetMethod(target, "AbcdCalibrationEndCriteria", QuantLibNode::AbcdCalibrationEndCriteria);
Nan::SetMethod(target, "AbcdCalibrationA", QuantLibNode::AbcdCalibrationA);
Nan::SetMethod(target, "AbcdCalibrationB", QuantLibNode::AbcdCalibrationB);
Nan::SetMethod(target, "AbcdCalibrationC", QuantLibNode::AbcdCalibrationC);
Nan::SetMethod(target, "AbcdCalibrationD", QuantLibNode::AbcdCalibrationD);
Nan::SetMethod(target, "AccountingEngine", QuantLibNode::AccountingEngine);
Nan::SetMethod(target, "AccountingEngineMultiplePathValues", QuantLibNode::AccountingEngineMultiplePathValues);
Nan::SetMethod(target, "AlphaFormInverseLinear", QuantLibNode::AlphaFormInverseLinear);
Nan::SetMethod(target, "AlphaFormLinearHyperbolic", QuantLibNode::AlphaFormLinearHyperbolic);
Nan::SetMethod(target, "AlphaFormOperator", QuantLibNode::AlphaFormOperator);
Nan::SetMethod(target, "AlphaFormSetAlpha", QuantLibNode::AlphaFormSetAlpha);
Nan::SetMethod(target, "AssetSwap", QuantLibNode::AssetSwap);
Nan::SetMethod(target, "AssetSwap2", QuantLibNode::AssetSwap2);
Nan::SetMethod(target, "AssetSwapBondLegAnalysis", QuantLibNode::AssetSwapBondLegAnalysis);
Nan::SetMethod(target, "AssetSwapFloatingLegAnalysis", QuantLibNode::AssetSwapFloatingLegAnalysis);
Nan::SetMethod(target, "AssetSwapFairSpread", QuantLibNode::AssetSwapFairSpread);
Nan::SetMethod(target, "AssetSwapFloatingLegBPS", QuantLibNode::AssetSwapFloatingLegBPS);
Nan::SetMethod(target, "AssetSwapFairCleanPrice", QuantLibNode::AssetSwapFairCleanPrice);
Nan::SetMethod(target, "AssetSwapFairNonParRepayment", QuantLibNode::AssetSwapFairNonParRepayment);
Nan::SetMethod(target, "AssetSwapParSwap", QuantLibNode::AssetSwapParSwap);
Nan::SetMethod(target, "AssetSwapPayBondCoupon", QuantLibNode::AssetSwapPayBondCoupon);
Nan::SetMethod(target, "GaussianLHPLossmodel", QuantLibNode::GaussianLHPLossmodel);
Nan::SetMethod(target, "IHGaussPoolLossModel", QuantLibNode::IHGaussPoolLossModel);
Nan::SetMethod(target, "IHStudentPoolLossModel", QuantLibNode::IHStudentPoolLossModel);
Nan::SetMethod(target, "GBinomialLossmodel", QuantLibNode::GBinomialLossmodel);
Nan::SetMethod(target, "TBinomialLossmodel", QuantLibNode::TBinomialLossmodel);
Nan::SetMethod(target, "BaseCorrelationLossModel", QuantLibNode::BaseCorrelationLossModel);
Nan::SetMethod(target, "GMCLossModel", QuantLibNode::GMCLossModel);
Nan::SetMethod(target, "GRandomRRMCLossModel", QuantLibNode::GRandomRRMCLossModel);
Nan::SetMethod(target, "TMCLossModel", QuantLibNode::TMCLossModel);
Nan::SetMethod(target, "TRandomRRMCLossModel", QuantLibNode::TRandomRRMCLossModel);
Nan::SetMethod(target, "GSaddlePointLossmodel", QuantLibNode::GSaddlePointLossmodel);
Nan::SetMethod(target, "TSaddlePointLossmodel", QuantLibNode::TSaddlePointLossmodel);
Nan::SetMethod(target, "GRecursiveLossmodel", QuantLibNode::GRecursiveLossmodel);
Nan::SetMethod(target, "FixedRateBond", QuantLibNode::FixedRateBond);
Nan::SetMethod(target, "FixedRateBond2", QuantLibNode::FixedRateBond2);
Nan::SetMethod(target, "FloatingRateBond", QuantLibNode::FloatingRateBond);
Nan::SetMethod(target, "CmsRateBond", QuantLibNode::CmsRateBond);
Nan::SetMethod(target, "ZeroCouponBond", QuantLibNode::ZeroCouponBond);
Nan::SetMethod(target, "Bond", QuantLibNode::Bond);
Nan::SetMethod(target, "BondSettlementDays", QuantLibNode::BondSettlementDays);
Nan::SetMethod(target, "BondCalendar", QuantLibNode::BondCalendar);
Nan::SetMethod(target, "BondNotionals", QuantLibNode::BondNotionals);
Nan::SetMethod(target, "BondNotional", QuantLibNode::BondNotional);
Nan::SetMethod(target, "BondMaturityDate", QuantLibNode::BondMaturityDate);
Nan::SetMethod(target, "BondIssueDate", QuantLibNode::BondIssueDate);
Nan::SetMethod(target, "BondIsTradable", QuantLibNode::BondIsTradable);
Nan::SetMethod(target, "BondSettlementDate", QuantLibNode::BondSettlementDate);
Nan::SetMethod(target, "BondCleanPrice", QuantLibNode::BondCleanPrice);
Nan::SetMethod(target, "BondDescription", QuantLibNode::BondDescription);
Nan::SetMethod(target, "BondCurrency", QuantLibNode::BondCurrency);
Nan::SetMethod(target, "BondRedemptionAmount", QuantLibNode::BondRedemptionAmount);
Nan::SetMethod(target, "BondRedemptionDate", QuantLibNode::BondRedemptionDate);
Nan::SetMethod(target, "BondFlowAnalysis", QuantLibNode::BondFlowAnalysis);
Nan::SetMethod(target, "BondSetCouponPricer", QuantLibNode::BondSetCouponPricer);
Nan::SetMethod(target, "BondSetCouponPricers", QuantLibNode::BondSetCouponPricers);
Nan::SetMethod(target, "BondStartDate", QuantLibNode::BondStartDate);
Nan::SetMethod(target, "BondPreviousCashFlowDate", QuantLibNode::BondPreviousCashFlowDate);
Nan::SetMethod(target, "BondNextCashFlowDate", QuantLibNode::BondNextCashFlowDate);
Nan::SetMethod(target, "BondPreviousCashFlowAmount", QuantLibNode::BondPreviousCashFlowAmount);
Nan::SetMethod(target, "BondNextCashFlowAmount", QuantLibNode::BondNextCashFlowAmount);
Nan::SetMethod(target, "BondPreviousCouponRate", QuantLibNode::BondPreviousCouponRate);
Nan::SetMethod(target, "BondNextCouponRate", QuantLibNode::BondNextCouponRate);
Nan::SetMethod(target, "BondAccrualStartDate", QuantLibNode::BondAccrualStartDate);
Nan::SetMethod(target, "BondAccrualEndDate", QuantLibNode::BondAccrualEndDate);
Nan::SetMethod(target, "BondReferencePeriodStart", QuantLibNode::BondReferencePeriodStart);
Nan::SetMethod(target, "BondReferencePeriodEnd", QuantLibNode::BondReferencePeriodEnd);
Nan::SetMethod(target, "BondAccrualPeriod", QuantLibNode::BondAccrualPeriod);
Nan::SetMethod(target, "BondAccrualDays", QuantLibNode::BondAccrualDays);
Nan::SetMethod(target, "BondAccruedPeriod", QuantLibNode::BondAccruedPeriod);
Nan::SetMethod(target, "BondAccruedDays", QuantLibNode::BondAccruedDays);
Nan::SetMethod(target, "BondAccruedAmount", QuantLibNode::BondAccruedAmount);
Nan::SetMethod(target, "BondCleanPriceFromYieldTermStructure", QuantLibNode::BondCleanPriceFromYieldTermStructure);
Nan::SetMethod(target, "BondBpsFromYieldTermStructure", QuantLibNode::BondBpsFromYieldTermStructure);
Nan::SetMethod(target, "BondAtmRateFromYieldTermStructure", QuantLibNode::BondAtmRateFromYieldTermStructure);
Nan::SetMethod(target, "BondCleanPriceFromYield", QuantLibNode::BondCleanPriceFromYield);
Nan::SetMethod(target, "BondDirtyPriceFromYield", QuantLibNode::BondDirtyPriceFromYield);
Nan::SetMethod(target, "BondBpsFromYield", QuantLibNode::BondBpsFromYield);
Nan::SetMethod(target, "BondYieldFromCleanPrice", QuantLibNode::BondYieldFromCleanPrice);
Nan::SetMethod(target, "BondDurationFromYield", QuantLibNode::BondDurationFromYield);
Nan::SetMethod(target, "BondConvexityFromYield", QuantLibNode::BondConvexityFromYield);
Nan::SetMethod(target, "BondCleanPriceFromZSpread", QuantLibNode::BondCleanPriceFromZSpread);
Nan::SetMethod(target, "BondZSpreadFromCleanPrice", QuantLibNode::BondZSpreadFromCleanPrice);
Nan::SetMethod(target, "BondAlive", QuantLibNode::BondAlive);
Nan::SetMethod(target, "BondMaturityLookup", QuantLibNode::BondMaturityLookup);
Nan::SetMethod(target, "BondMaturitySort", QuantLibNode::BondMaturitySort);
Nan::SetMethod(target, "MTBrownianGeneratorFactory", QuantLibNode::MTBrownianGeneratorFactory);
Nan::SetMethod(target, "CCTEU", QuantLibNode::CCTEU);
Nan::SetMethod(target, "BTP", QuantLibNode::BTP);
Nan::SetMethod(target, "BTP2", QuantLibNode::BTP2);
Nan::SetMethod(target, "RendistatoBasket", QuantLibNode::RendistatoBasket);
Nan::SetMethod(target, "RendistatoCalculator", QuantLibNode::RendistatoCalculator);
Nan::SetMethod(target, "RendistatoEquivalentSwapLengthQuote", QuantLibNode::RendistatoEquivalentSwapLengthQuote);
Nan::SetMethod(target, "RendistatoEquivalentSwapSpreadQuote", QuantLibNode::RendistatoEquivalentSwapSpreadQuote);
Nan::SetMethod(target, "RendistatoBasketSize", QuantLibNode::RendistatoBasketSize);
Nan::SetMethod(target, "RendistatoBasketOutstanding", QuantLibNode::RendistatoBasketOutstanding);
Nan::SetMethod(target, "RendistatoBasketOutstandings", QuantLibNode::RendistatoBasketOutstandings);
Nan::SetMethod(target, "RendistatoBasketWeights", QuantLibNode::RendistatoBasketWeights);
Nan::SetMethod(target, "RendistatoCalculatorYield", QuantLibNode::RendistatoCalculatorYield);
Nan::SetMethod(target, "RendistatoCalculatorDuration", QuantLibNode::RendistatoCalculatorDuration);
Nan::SetMethod(target, "RendistatoCalculatorYields", QuantLibNode::RendistatoCalculatorYields);
Nan::SetMethod(target, "RendistatoCalculatorDurations", QuantLibNode::RendistatoCalculatorDurations);
Nan::SetMethod(target, "RendistatoCalculatorSwapLengths", QuantLibNode::RendistatoCalculatorSwapLengths);
Nan::SetMethod(target, "RendistatoCalculatorSwapRates", QuantLibNode::RendistatoCalculatorSwapRates);
Nan::SetMethod(target, "RendistatoCalculatorSwapYields", QuantLibNode::RendistatoCalculatorSwapYields);
Nan::SetMethod(target, "RendistatoCalculatorSwapDurations", QuantLibNode::RendistatoCalculatorSwapDurations);
Nan::SetMethod(target, "RendistatoCalculatorEquivalentSwapRate", QuantLibNode::RendistatoCalculatorEquivalentSwapRate);
Nan::SetMethod(target, "RendistatoCalculatorEquivalentSwapYield", QuantLibNode::RendistatoCalculatorEquivalentSwapYield);
Nan::SetMethod(target, "RendistatoCalculatorEquivalentSwapDuration", QuantLibNode::RendistatoCalculatorEquivalentSwapDuration);
Nan::SetMethod(target, "RendistatoCalculatorEquivalentSwapSpread", QuantLibNode::RendistatoCalculatorEquivalentSwapSpread);
Nan::SetMethod(target, "RendistatoCalculatorEquivalentSwapLength", QuantLibNode::RendistatoCalculatorEquivalentSwapLength);
Nan::SetMethod(target, "CalendarHolidayList", QuantLibNode::CalendarHolidayList);
Nan::SetMethod(target, "CalendarName", QuantLibNode::CalendarName);
Nan::SetMethod(target, "CalendarIsBusinessDay", QuantLibNode::CalendarIsBusinessDay);
Nan::SetMethod(target, "CalendarIsHoliday", QuantLibNode::CalendarIsHoliday);
Nan::SetMethod(target, "CalendarIsEndOfMonth", QuantLibNode::CalendarIsEndOfMonth);
Nan::SetMethod(target, "CalendarEndOfMonth", QuantLibNode::CalendarEndOfMonth);
Nan::SetMethod(target, "CalendarAddHoliday", QuantLibNode::CalendarAddHoliday);
Nan::SetMethod(target, "CalendarRemoveHoliday", QuantLibNode::CalendarRemoveHoliday);
Nan::SetMethod(target, "CalendarAdjust", QuantLibNode::CalendarAdjust);
Nan::SetMethod(target, "CalendarAdvance", QuantLibNode::CalendarAdvance);
Nan::SetMethod(target, "CalendarBusinessDaysBetween", QuantLibNode::CalendarBusinessDaysBetween);
Nan::SetMethod(target, "SwaptionHelper", QuantLibNode::SwaptionHelper);
Nan::SetMethod(target, "CalibrationHelperSetPricingEngine", QuantLibNode::CalibrationHelperSetPricingEngine);
Nan::SetMethod(target, "CalibrationHelperImpliedVolatility", QuantLibNode::CalibrationHelperImpliedVolatility);
Nan::SetMethod(target, "SwaptionHelperModelValue", QuantLibNode::SwaptionHelperModelValue);
Nan::SetMethod(target, "OneFactorAffineModelCalibrate", QuantLibNode::OneFactorAffineModelCalibrate);
Nan::SetMethod(target, "ModelG2Calibrate", QuantLibNode::ModelG2Calibrate);
Nan::SetMethod(target, "CapFloor", QuantLibNode::CapFloor);
Nan::SetMethod(target, "MakeCapFloor", QuantLibNode::MakeCapFloor);
Nan::SetMethod(target, "CapFloorType", QuantLibNode::CapFloorType);
Nan::SetMethod(target, "CapFloorCapRates", QuantLibNode::CapFloorCapRates);
Nan::SetMethod(target, "CapFloorFloorRates", QuantLibNode::CapFloorFloorRates);
Nan::SetMethod(target, "CapFloorAtmRate", QuantLibNode::CapFloorAtmRate);
Nan::SetMethod(target, "CapFloorStartDate", QuantLibNode::CapFloorStartDate);
Nan::SetMethod(target, "CapFloorMaturityDate", QuantLibNode::CapFloorMaturityDate);
Nan::SetMethod(target, "CapFloorImpliedVolatility", QuantLibNode::CapFloorImpliedVolatility);
Nan::SetMethod(target, "CapFloorLegAnalysis", QuantLibNode::CapFloorLegAnalysis);
Nan::SetMethod(target, "RelinkableHandleOptionletVolatilityStructure", QuantLibNode::RelinkableHandleOptionletVolatilityStructure);
Nan::SetMethod(target, "ConstantOptionletVolatility", QuantLibNode::ConstantOptionletVolatility);
Nan::SetMethod(target, "SpreadedOptionletVolatility", QuantLibNode::SpreadedOptionletVolatility);
Nan::SetMethod(target, "StrippedOptionletAdapter", QuantLibNode::StrippedOptionletAdapter);
Nan::SetMethod(target, "StrippedOptionlet", QuantLibNode::StrippedOptionlet);
Nan::SetMethod(target, "OptionletStripper1", QuantLibNode::OptionletStripper1);
Nan::SetMethod(target, "OptionletStripper2", QuantLibNode::OptionletStripper2);
Nan::SetMethod(target, "CapFloorTermVolCurve", QuantLibNode::CapFloorTermVolCurve);
Nan::SetMethod(target, "CapFloorTermVolSurface", QuantLibNode::CapFloorTermVolSurface);
Nan::SetMethod(target, "OptionletVTSVolatility", QuantLibNode::OptionletVTSVolatility);
Nan::SetMethod(target, "OptionletVTSVolatility2", QuantLibNode::OptionletVTSVolatility2);
Nan::SetMethod(target, "OptionletVTSBlackVariance", QuantLibNode::OptionletVTSBlackVariance);
Nan::SetMethod(target, "OptionletVTSBlackVariance2", QuantLibNode::OptionletVTSBlackVariance2);
Nan::SetMethod(target, "StrippedOptionletBaseStrikes", QuantLibNode::StrippedOptionletBaseStrikes);
Nan::SetMethod(target, "StrippedOptionletBaseOptionletVolatilities", QuantLibNode::StrippedOptionletBaseOptionletVolatilities);
Nan::SetMethod(target, "StrippedOptionletBaseOptionletFixingDates", QuantLibNode::StrippedOptionletBaseOptionletFixingDates);
Nan::SetMethod(target, "StrippedOptionletBaseOptionletFixingTimes", QuantLibNode::StrippedOptionletBaseOptionletFixingTimes);
Nan::SetMethod(target, "StrippedOptionletBaseAtmOptionletRates", QuantLibNode::StrippedOptionletBaseAtmOptionletRates);
Nan::SetMethod(target, "StrippedOptionletBaseDayCounter", QuantLibNode::StrippedOptionletBaseDayCounter);
Nan::SetMethod(target, "StrippedOptionletBaseCalendar", QuantLibNode::StrippedOptionletBaseCalendar);
Nan::SetMethod(target, "StrippedOptionletBaseSettlementDays", QuantLibNode::StrippedOptionletBaseSettlementDays);
Nan::SetMethod(target, "StrippedOptionletBaseBusinessDayConvention", QuantLibNode::StrippedOptionletBaseBusinessDayConvention);
Nan::SetMethod(target, "OptionletStripperOptionletFixingTenors", QuantLibNode::OptionletStripperOptionletFixingTenors);
Nan::SetMethod(target, "OptionletStripperOptionletPaymentDates", QuantLibNode::OptionletStripperOptionletPaymentDates);
Nan::SetMethod(target, "OptionletStripperOptionletAccrualPeriods", QuantLibNode::OptionletStripperOptionletAccrualPeriods);
Nan::SetMethod(target, "OptionletStripper1CapFloorPrices", QuantLibNode::OptionletStripper1CapFloorPrices);
Nan::SetMethod(target, "OptionletStripper1CapFloorVolatilities", QuantLibNode::OptionletStripper1CapFloorVolatilities);
Nan::SetMethod(target, "OptionletStripper1OptionletPrices", QuantLibNode::OptionletStripper1OptionletPrices);
Nan::SetMethod(target, "OptionletStripper1SwitchStrike", QuantLibNode::OptionletStripper1SwitchStrike);
Nan::SetMethod(target, "OptionletStripper2SpreadsVol", QuantLibNode::OptionletStripper2SpreadsVol);
Nan::SetMethod(target, "OptionletStripper2AtmCapFloorPrices", QuantLibNode::OptionletStripper2AtmCapFloorPrices);
Nan::SetMethod(target, "OptionletStripper2AtmCapFloorStrikes", QuantLibNode::OptionletStripper2AtmCapFloorStrikes);
Nan::SetMethod(target, "CapFloorTermVTSVolatility", QuantLibNode::CapFloorTermVTSVolatility);
Nan::SetMethod(target, "CapFloorTermVTSVolatility2", QuantLibNode::CapFloorTermVTSVolatility2);
Nan::SetMethod(target, "CapFloorTermVolCurveOptionTenors", QuantLibNode::CapFloorTermVolCurveOptionTenors);
Nan::SetMethod(target, "CapFloorTermVolCurveOptionDates", QuantLibNode::CapFloorTermVolCurveOptionDates);
Nan::SetMethod(target, "CapFloorTermVolSurfaceOptionTenors", QuantLibNode::CapFloorTermVolSurfaceOptionTenors);
Nan::SetMethod(target, "CapFloorTermVolSurfaceOptionDates", QuantLibNode::CapFloorTermVolSurfaceOptionDates);
Nan::SetMethod(target, "CapFloorTermVolSurfaceStrikes", QuantLibNode::CapFloorTermVolSurfaceStrikes);
Nan::SetMethod(target, "CmsMarket", QuantLibNode::CmsMarket);
Nan::SetMethod(target, "BrowseCmsMarket", QuantLibNode::BrowseCmsMarket);
Nan::SetMethod(target, "CmsMarketCalibration", QuantLibNode::CmsMarketCalibration);
Nan::SetMethod(target, "CmsMarketCalibrationCompute", QuantLibNode::CmsMarketCalibrationCompute);
Nan::SetMethod(target, "CmsMarketCalibrationError", QuantLibNode::CmsMarketCalibrationError);
Nan::SetMethod(target, "CmsMarketCalibrationEndCriteria", QuantLibNode::CmsMarketCalibrationEndCriteria);
Nan::SetMethod(target, "CmsMarketCalibrationElapsed", QuantLibNode::CmsMarketCalibrationElapsed);
Nan::SetMethod(target, "CmsMarketCalibrationSparseSabrParameters", QuantLibNode::CmsMarketCalibrationSparseSabrParameters);
Nan::SetMethod(target, "CmsMarketCalibrationDenseSabrParameters", QuantLibNode::CmsMarketCalibrationDenseSabrParameters);
Nan::SetMethod(target, "SimultaneousCalibrationBrowseCmsMarket", QuantLibNode::SimultaneousCalibrationBrowseCmsMarket);
Nan::SetMethod(target, "MarketModelLmLinearExponentialCorrelationModel", QuantLibNode::MarketModelLmLinearExponentialCorrelationModel);
Nan::SetMethod(target, "HistoricalForwardRatesAnalysis", QuantLibNode::HistoricalForwardRatesAnalysis);
Nan::SetMethod(target, "HistoricalRatesAnalysis", QuantLibNode::HistoricalRatesAnalysis);
Nan::SetMethod(target, "TimeHomogeneousForwardCorrelation", QuantLibNode::TimeHomogeneousForwardCorrelation);
Nan::SetMethod(target, "ExponentialForwardCorrelation", QuantLibNode::ExponentialForwardCorrelation);
Nan::SetMethod(target, "CotSwapFromFwdCorrelation", QuantLibNode::CotSwapFromFwdCorrelation);
Nan::SetMethod(target, "HistoricalForwardRatesAnalysisSkippedDates", QuantLibNode::HistoricalForwardRatesAnalysisSkippedDates);
Nan::SetMethod(target, "HistoricalForwardRatesAnalysisSkippedDatesErrorMessage", QuantLibNode::HistoricalForwardRatesAnalysisSkippedDatesErrorMessage);
Nan::SetMethod(target, "HistoricalForwardRatesAnalysisFailedDates", QuantLibNode::HistoricalForwardRatesAnalysisFailedDates);
Nan::SetMethod(target, "HistoricalForwardRatesAnalysisFailedDatesErrorMessage", QuantLibNode::HistoricalForwardRatesAnalysisFailedDatesErrorMessage);
Nan::SetMethod(target, "HistoricalForwardRatesAnalysisFixingPeriods", QuantLibNode::HistoricalForwardRatesAnalysisFixingPeriods);
Nan::SetMethod(target, "HistoricalRatesAnalysisSkippedDates", QuantLibNode::HistoricalRatesAnalysisSkippedDates);
Nan::SetMethod(target, "HistoricalRatesAnalysisSkippedDatesErrorMessage", QuantLibNode::HistoricalRatesAnalysisSkippedDatesErrorMessage);
Nan::SetMethod(target, "PiecewiseConstantCorrelationCorrelation", QuantLibNode::PiecewiseConstantCorrelationCorrelation);
Nan::SetMethod(target, "PiecewiseConstantCorrelationTimes", QuantLibNode::PiecewiseConstantCorrelationTimes);
Nan::SetMethod(target, "PiecewiseConstantCorrelationNumberOfRates", QuantLibNode::PiecewiseConstantCorrelationNumberOfRates);
Nan::SetMethod(target, "ExponentialCorrelations", QuantLibNode::ExponentialCorrelations);
Nan::SetMethod(target, "FixedRateLeg", QuantLibNode::FixedRateLeg);
Nan::SetMethod(target, "FixedRateLeg2", QuantLibNode::FixedRateLeg2);
Nan::SetMethod(target, "IborLeg", QuantLibNode::IborLeg);
Nan::SetMethod(target, "DigitalIborLeg", QuantLibNode::DigitalIborLeg);
Nan::SetMethod(target, "CmsLeg", QuantLibNode::CmsLeg);
Nan::SetMethod(target, "DigitalCmsLeg", QuantLibNode::DigitalCmsLeg);
Nan::SetMethod(target, "RangeAccrualLeg", QuantLibNode::RangeAccrualLeg);
Nan::SetMethod(target, "CmsZeroLeg", QuantLibNode::CmsZeroLeg);
Nan::SetMethod(target, "IborCouponPricer", QuantLibNode::IborCouponPricer);
Nan::SetMethod(target, "CmsCouponPricer", QuantLibNode::CmsCouponPricer);
Nan::SetMethod(target, "ConundrumPricerByNumericalIntegration", QuantLibNode::ConundrumPricerByNumericalIntegration);
Nan::SetMethod(target, "DigitalReplication", QuantLibNode::DigitalReplication);
Nan::SetMethod(target, "ConundrumPricerByNumericalIntegrationUpperLimit", QuantLibNode::ConundrumPricerByNumericalIntegrationUpperLimit);
Nan::SetMethod(target, "CreditDefaultSwap", QuantLibNode::CreditDefaultSwap);
Nan::SetMethod(target, "MidPointCdsEngine", QuantLibNode::MidPointCdsEngine);
Nan::SetMethod(target, "HazardRateCurve", QuantLibNode::HazardRateCurve);
Nan::SetMethod(target, "SpreadCdsHelper", QuantLibNode::SpreadCdsHelper);
Nan::SetMethod(target, "UpfrontCdsHelper", QuantLibNode::UpfrontCdsHelper);
Nan::SetMethod(target, "PiecewiseHazardRateCurve", QuantLibNode::PiecewiseHazardRateCurve);
Nan::SetMethod(target, "PiecewiseFlatForwardCurve", QuantLibNode::PiecewiseFlatForwardCurve);
Nan::SetMethod(target, "RiskyFixedBond", QuantLibNode::RiskyFixedBond);
Nan::SetMethod(target, "Issuer", QuantLibNode::Issuer);
Nan::SetMethod(target, "DefaultEvent", QuantLibNode::DefaultEvent);
Nan::SetMethod(target, "SyntheticCDO", QuantLibNode::SyntheticCDO);
Nan::SetMethod(target, "MidPointCDOEngine", QuantLibNode::MidPointCDOEngine);
Nan::SetMethod(target, "NthToDefault", QuantLibNode::NthToDefault);
Nan::SetMethod(target, "IntegralNtdEngine", QuantLibNode::IntegralNtdEngine);
Nan::SetMethod(target, "BlackCdsOptionEngine", QuantLibNode::BlackCdsOptionEngine);
Nan::SetMethod(target, "CDSOption", QuantLibNode::CDSOption);
Nan::SetMethod(target, "BaseCorrelationTermStructure", QuantLibNode::BaseCorrelationTermStructure);
Nan::SetMethod(target, "CdsCouponLegNPV", QuantLibNode::CdsCouponLegNPV);
Nan::SetMethod(target, "CdsDefaultLegNPV", QuantLibNode::CdsDefaultLegNPV);
Nan::SetMethod(target, "CdsFairSpread", QuantLibNode::CdsFairSpread);
Nan::SetMethod(target, "CdsFairUpfront", QuantLibNode::CdsFairUpfront);
Nan::SetMethod(target, "HRDates", QuantLibNode::HRDates);
Nan::SetMethod(target, "HRates", QuantLibNode::HRates);
Nan::SetMethod(target, "CdsOptionImpliedVol", QuantLibNode::CdsOptionImpliedVol);
Nan::SetMethod(target, "BaseCorrelationValue", QuantLibNode::BaseCorrelationValue);
Nan::SetMethod(target, "CTSMMCapletOriginalCalibration", QuantLibNode::CTSMMCapletOriginalCalibration);
Nan::SetMethod(target, "CTSMMCapletAlphaFormCalibration", QuantLibNode::CTSMMCapletAlphaFormCalibration);
Nan::SetMethod(target, "CTSMMCapletMaxHomogeneityCalibration", QuantLibNode::CTSMMCapletMaxHomogeneityCalibration);
Nan::SetMethod(target, "CTSMMCapletCalibrationCalibrate", QuantLibNode::CTSMMCapletCalibrationCalibrate);
Nan::SetMethod(target, "CTSMMCapletCalibrationFailures", QuantLibNode::CTSMMCapletCalibrationFailures);
Nan::SetMethod(target, "CTSMMCapletCalibrationDeformationSize", QuantLibNode::CTSMMCapletCalibrationDeformationSize);
Nan::SetMethod(target, "CTSMMCapletCalibrationMarketCapletVols", QuantLibNode::CTSMMCapletCalibrationMarketCapletVols);
Nan::SetMethod(target, "CTSMMCapletCalibrationModelCapletVols", QuantLibNode::CTSMMCapletCalibrationModelCapletVols);
Nan::SetMethod(target, "CTSMMCapletCalibrationCapletRmsError", QuantLibNode::CTSMMCapletCalibrationCapletRmsError);
Nan::SetMethod(target, "CTSMMCapletCalibrationCapletMaxError", QuantLibNode::CTSMMCapletCalibrationCapletMaxError);
Nan::SetMethod(target, "CTSMMCapletCalibrationMarketSwaptionVols", QuantLibNode::CTSMMCapletCalibrationMarketSwaptionVols);
Nan::SetMethod(target, "CTSMMCapletCalibrationModelSwaptionVols", QuantLibNode::CTSMMCapletCalibrationModelSwaptionVols);
Nan::SetMethod(target, "CTSMMCapletCalibrationSwaptionRmsError", QuantLibNode::CTSMMCapletCalibrationSwaptionRmsError);
Nan::SetMethod(target, "CTSMMCapletCalibrationSwaptionMaxError", QuantLibNode::CTSMMCapletCalibrationSwaptionMaxError);
Nan::SetMethod(target, "CTSMMCapletCalibrationSwapPseudoRoot", QuantLibNode::CTSMMCapletCalibrationSwapPseudoRoot);
Nan::SetMethod(target, "CTSMMCapletCalibrationTimeDependentCalibratedSwaptionVols", QuantLibNode::CTSMMCapletCalibrationTimeDependentCalibratedSwaptionVols);
Nan::SetMethod(target, "CTSMMCapletCalibrationTimeDependentUnCalibratedSwaptionVols", QuantLibNode::CTSMMCapletCalibrationTimeDependentUnCalibratedSwaptionVols);
Nan::SetMethod(target, "CTSMMCapletAlphaFormCalibrationAlpha", QuantLibNode::CTSMMCapletAlphaFormCalibrationAlpha);
Nan::SetMethod(target, "CMSwapCurveState", QuantLibNode::CMSwapCurveState);
Nan::SetMethod(target, "CoterminalSwapCurveState", QuantLibNode::CoterminalSwapCurveState);
Nan::SetMethod(target, "LMMCurveState", QuantLibNode::LMMCurveState);
Nan::SetMethod(target, "CurveStateRateTimes", QuantLibNode::CurveStateRateTimes);
Nan::SetMethod(target, "CurveStateRateTaus", QuantLibNode::CurveStateRateTaus);
Nan::SetMethod(target, "CurveStateForwardRates", QuantLibNode::CurveStateForwardRates);
Nan::SetMethod(target, "CurveStateCoterminalSwapRates", QuantLibNode::CurveStateCoterminalSwapRates);
Nan::SetMethod(target, "CurveStateCMSwapRates", QuantLibNode::CurveStateCMSwapRates);
Nan::SetMethod(target, "CMSwapCurveStateSetOnCMSwapRates", QuantLibNode::CMSwapCurveStateSetOnCMSwapRates);
Nan::SetMethod(target, "CoterminalSwapCurveStateSetOnCoterminalSwapRates", QuantLibNode::CoterminalSwapCurveStateSetOnCoterminalSwapRates);
Nan::SetMethod(target, "LMMCurveStateSetOnForwardRates", QuantLibNode::LMMCurveStateSetOnForwardRates);
Nan::SetMethod(target, "LMMCurveStateSetOnDiscountRatios", QuantLibNode::LMMCurveStateSetOnDiscountRatios);
Nan::SetMethod(target, "ForwardsFromDiscountRatios", QuantLibNode::ForwardsFromDiscountRatios);
Nan::SetMethod(target, "CoterminalSwapRatesFromDiscountRatios", QuantLibNode::CoterminalSwapRatesFromDiscountRatios);
Nan::SetMethod(target, "CoterminalSwapAnnuitiesFromDiscountRatios", QuantLibNode::CoterminalSwapAnnuitiesFromDiscountRatios);
Nan::SetMethod(target, "ConstantMaturitySwapRatesFromDiscountRatios", QuantLibNode::ConstantMaturitySwapRatesFromDiscountRatios);
Nan::SetMethod(target, "ConstantMaturitySwapAnnuitiesFromDiscountRatios", QuantLibNode::ConstantMaturitySwapAnnuitiesFromDiscountRatios);
Nan::SetMethod(target, "PeriodFromFrequency", QuantLibNode::PeriodFromFrequency);
Nan::SetMethod(target, "FrequencyFromPeriod", QuantLibNode::FrequencyFromPeriod);
Nan::SetMethod(target, "PeriodLessThan", QuantLibNode::PeriodLessThan);
Nan::SetMethod(target, "PeriodEquivalent", QuantLibNode::PeriodEquivalent);
Nan::SetMethod(target, "DateMinDate", QuantLibNode::DateMinDate);
Nan::SetMethod(target, "DateMaxDate", QuantLibNode::DateMaxDate);
Nan::SetMethod(target, "DateIsLeap", QuantLibNode::DateIsLeap);
Nan::SetMethod(target, "DateEndOfMonth", QuantLibNode::DateEndOfMonth);
Nan::SetMethod(target, "DateIsEndOfMonth", QuantLibNode::DateIsEndOfMonth);
Nan::SetMethod(target, "DateNextWeekday", QuantLibNode::DateNextWeekday);
Nan::SetMethod(target, "DateNthWeekday", QuantLibNode::DateNthWeekday);
Nan::SetMethod(target, "IMMIsIMMdate", QuantLibNode::IMMIsIMMdate);
Nan::SetMethod(target, "IMMIsIMMcode", QuantLibNode::IMMIsIMMcode);
Nan::SetMethod(target, "IMMcode", QuantLibNode::IMMcode);
Nan::SetMethod(target, "IMMNextCode", QuantLibNode::IMMNextCode);
Nan::SetMethod(target, "IMMNextCodes", QuantLibNode::IMMNextCodes);
Nan::SetMethod(target, "IMMdate", QuantLibNode::IMMdate);
Nan::SetMethod(target, "IMMNextDate", QuantLibNode::IMMNextDate);
Nan::SetMethod(target, "IMMNextDates", QuantLibNode::IMMNextDates);
Nan::SetMethod(target, "ASXIsASXdate", QuantLibNode::ASXIsASXdate);
Nan::SetMethod(target, "ASXIsASXcode", QuantLibNode::ASXIsASXcode);
Nan::SetMethod(target, "ASXcode", QuantLibNode::ASXcode);
Nan::SetMethod(target, "ASXNextCode", QuantLibNode::ASXNextCode);
Nan::SetMethod(target, "ASXNextCodes", QuantLibNode::ASXNextCodes);
Nan::SetMethod(target, "ASXdate", QuantLibNode::ASXdate);
Nan::SetMethod(target, "ASXNextDate", QuantLibNode::ASXNextDate);
Nan::SetMethod(target, "ASXNextDates", QuantLibNode::ASXNextDates);
Nan::SetMethod(target, "ECBKnownDates", QuantLibNode::ECBKnownDates);
Nan::SetMethod(target, "ECBAddDate", QuantLibNode::ECBAddDate);
Nan::SetMethod(target, "ECBRemoveDate", QuantLibNode::ECBRemoveDate);
Nan::SetMethod(target, "ECBdate2", QuantLibNode::ECBdate2);
Nan::SetMethod(target, "ECBdate", QuantLibNode::ECBdate);
Nan::SetMethod(target, "ECBcode", QuantLibNode::ECBcode);
Nan::SetMethod(target, "ECBNextDate", QuantLibNode::ECBNextDate);
Nan::SetMethod(target, "ECBNextDate2", QuantLibNode::ECBNextDate2);
Nan::SetMethod(target, "ECBNextDates", QuantLibNode::ECBNextDates);
Nan::SetMethod(target, "ECBIsECBdate", QuantLibNode::ECBIsECBdate);
Nan::SetMethod(target, "ECBIsECBcode", QuantLibNode::ECBIsECBcode);
Nan::SetMethod(target, "ECBNextCode", QuantLibNode::ECBNextCode);
Nan::SetMethod(target, "ECBNextCode2", QuantLibNode::ECBNextCode2);
Nan::SetMethod(target, "DayCounterName", QuantLibNode::DayCounterName);
Nan::SetMethod(target, "DayCounterDayCount", QuantLibNode::DayCounterDayCount);
Nan::SetMethod(target, "DayCounterYearFraction", QuantLibNode::DayCounterYearFraction);
Nan::SetMethod(target, "CreditBasket", QuantLibNode::CreditBasket);
Nan::SetMethod(target, "CreditBasketSetLossModel", QuantLibNode::CreditBasketSetLossModel);
Nan::SetMethod(target, "CreditBasketSize", QuantLibNode::CreditBasketSize);
Nan::SetMethod(target, "CreditBasketLiveNotional", QuantLibNode::CreditBasketLiveNotional);
Nan::SetMethod(target, "CreditBasketLoss", QuantLibNode::CreditBasketLoss);
Nan::SetMethod(target, "CreditBasketAttachLive", QuantLibNode::CreditBasketAttachLive);
Nan::SetMethod(target, "CreditBasketDetachLive", QuantLibNode::CreditBasketDetachLive);
Nan::SetMethod(target, "ExpectedTrancheLoss", QuantLibNode::ExpectedTrancheLoss);
Nan::SetMethod(target, "CreditBasketPercentile", QuantLibNode::CreditBasketPercentile);
Nan::SetMethod(target, "CreditBasketESF", QuantLibNode::CreditBasketESF);
Nan::SetMethod(target, "CreditBasketNthEventP", QuantLibNode::CreditBasketNthEventP);
Nan::SetMethod(target, "CreditBasketProbLoss", QuantLibNode::CreditBasketProbLoss);
Nan::SetMethod(target, "CreditBasketSplitLoss", QuantLibNode::CreditBasketSplitLoss);
Nan::SetMethod(target, "CreditBasketDefaulCorrel", QuantLibNode::CreditBasketDefaulCorrel);
Nan::SetMethod(target, "RelinkableHandleDefaultProbabilityTermStructure", QuantLibNode::RelinkableHandleDefaultProbabilityTermStructure);
Nan::SetMethod(target, "FlatHazardRate", QuantLibNode::FlatHazardRate);
Nan::SetMethod(target, "DefaultTSDefaultProbability", QuantLibNode::DefaultTSDefaultProbability);
Nan::SetMethod(target, "ProbabilityToHR", QuantLibNode::ProbabilityToHR);
Nan::SetMethod(target, "LMMDriftCalculator", QuantLibNode::LMMDriftCalculator);
Nan::SetMethod(target, "LMMNormalDriftCalculator", QuantLibNode::LMMNormalDriftCalculator);
Nan::SetMethod(target, "CMSMMDriftCalculator", QuantLibNode::CMSMMDriftCalculator);
Nan::SetMethod(target, "SMMDriftCalculator", QuantLibNode::SMMDriftCalculator);
Nan::SetMethod(target, "LMMDriftCalculatorComputePlain", QuantLibNode::LMMDriftCalculatorComputePlain);
Nan::SetMethod(target, "LMMDriftCalculatorComputeReduced", QuantLibNode::LMMDriftCalculatorComputeReduced);
Nan::SetMethod(target, "LMMDriftCalculatorCompute", QuantLibNode::LMMDriftCalculatorCompute);
Nan::SetMethod(target, "LMMNormalDriftCalculatorComputePlain", QuantLibNode::LMMNormalDriftCalculatorComputePlain);
Nan::SetMethod(target, "LMMNormalDriftCalculatorComputeReduced", QuantLibNode::LMMNormalDriftCalculatorComputeReduced);
Nan::SetMethod(target, "LMMNormalDriftCalculatorCompute", QuantLibNode::LMMNormalDriftCalculatorCompute);
Nan::SetMethod(target, "CMSMMDriftCalculatorCompute", QuantLibNode::CMSMMDriftCalculatorCompute);
Nan::SetMethod(target, "SMMDriftCalculatorCompute", QuantLibNode::SMMDriftCalculatorCompute);
Nan::SetMethod(target, "EvolutionDescription", QuantLibNode::EvolutionDescription);
Nan::SetMethod(target, "EvolutionDescriptionFromProduct", QuantLibNode::EvolutionDescriptionFromProduct);
Nan::SetMethod(target, "EvolutionDescriptionRateTimes", QuantLibNode::EvolutionDescriptionRateTimes);
Nan::SetMethod(target, "EvolutionDescriptionRateTaus", QuantLibNode::EvolutionDescriptionRateTaus);
Nan::SetMethod(target, "EvolutionDescriptionEvolutionTimes", QuantLibNode::EvolutionDescriptionEvolutionTimes);
Nan::SetMethod(target, "EvolutionDescriptionFirstAliveRate", QuantLibNode::EvolutionDescriptionFirstAliveRate);
Nan::SetMethod(target, "EvolutionDescriptionNumberOfRates", QuantLibNode::EvolutionDescriptionNumberOfRates);
Nan::SetMethod(target, "EvolutionDescriptionNumberOfSteps", QuantLibNode::EvolutionDescriptionNumberOfSteps);
Nan::SetMethod(target, "TerminalMeasure", QuantLibNode::TerminalMeasure);
Nan::SetMethod(target, "MoneyMarketMeasure", QuantLibNode::MoneyMarketMeasure);
Nan::SetMethod(target, "MoneyMarketPlusMeasure", QuantLibNode::MoneyMarketPlusMeasure);
Nan::SetMethod(target, "IsInTerminalMeasure", QuantLibNode::IsInTerminalMeasure);
Nan::SetMethod(target, "IsInMoneyMarketMeasure", QuantLibNode::IsInMoneyMarketMeasure);
Nan::SetMethod(target, "IsInMoneyMarketPlusMeasure", QuantLibNode::IsInMoneyMarketPlusMeasure);
Nan::SetMethod(target, "AmericanExercise", QuantLibNode::AmericanExercise);
Nan::SetMethod(target, "EuropeanExercise", QuantLibNode::EuropeanExercise);
Nan::SetMethod(target, "BermudanExercise", QuantLibNode::BermudanExercise);
Nan::SetMethod(target, "ExerciseDates", QuantLibNode::ExerciseDates);
Nan::SetMethod(target, "ExerciseLastDate", QuantLibNode::ExerciseLastDate);
Nan::SetMethod(target, "FRA", QuantLibNode::FRA);
Nan::SetMethod(target, "FRAforwardRate", QuantLibNode::FRAforwardRate);
Nan::SetMethod(target, "FRAforwardValue", QuantLibNode::FRAforwardValue);
Nan::SetMethod(target, "FRAspotValue", QuantLibNode::FRAspotValue);
Nan::SetMethod(target, "HandleCurrentLink", QuantLibNode::HandleCurrentLink);
Nan::SetMethod(target, "HandleEmpty", QuantLibNode::HandleEmpty);
Nan::SetMethod(target, "RelinkableHandleLinkTo", QuantLibNode::RelinkableHandleLinkTo);
Nan::SetMethod(target, "IborIndex", QuantLibNode::IborIndex);
Nan::SetMethod(target, "OvernightIndex", QuantLibNode::OvernightIndex);
Nan::SetMethod(target, "Euribor", QuantLibNode::Euribor);
Nan::SetMethod(target, "Euribor365", QuantLibNode::Euribor365);
Nan::SetMethod(target, "Eonia", QuantLibNode::Eonia);
Nan::SetMethod(target, "Libor", QuantLibNode::Libor);
Nan::SetMethod(target, "Sonia", QuantLibNode::Sonia);
Nan::SetMethod(target, "SwapIndex", QuantLibNode::SwapIndex);
Nan::SetMethod(target, "EuriborSwap", QuantLibNode::EuriborSwap);
Nan::SetMethod(target, "LiborSwap", QuantLibNode::LiborSwap);
Nan::SetMethod(target, "EuriborSwapIsdaFixA", QuantLibNode::EuriborSwapIsdaFixA);
Nan::SetMethod(target, "BMAIndex", QuantLibNode::BMAIndex);
Nan::SetMethod(target, "ProxyIbor", QuantLibNode::ProxyIbor);
Nan::SetMethod(target, "IndexName", QuantLibNode::IndexName);
Nan::SetMethod(target, "IndexFixingCalendar", QuantLibNode::IndexFixingCalendar);
Nan::SetMethod(target, "IndexIsValidFixingDate", QuantLibNode::IndexIsValidFixingDate);
Nan::SetMethod(target, "IndexFixing", QuantLibNode::IndexFixing);
Nan::SetMethod(target, "IndexAddFixings", QuantLibNode::IndexAddFixings);
Nan::SetMethod(target, "IndexAddFixings2", QuantLibNode::IndexAddFixings2);
Nan::SetMethod(target, "IndexClearFixings", QuantLibNode::IndexClearFixings);
Nan::SetMethod(target, "InterestRateIndexFamilyName", QuantLibNode::InterestRateIndexFamilyName);
Nan::SetMethod(target, "InterestRateIndexTenor", QuantLibNode::InterestRateIndexTenor);
Nan::SetMethod(target, "InterestRateIndexFixingDays", QuantLibNode::InterestRateIndexFixingDays);
Nan::SetMethod(target, "InterestRateIndexCurrency", QuantLibNode::InterestRateIndexCurrency);
Nan::SetMethod(target, "InterestRateIndexDayCounter", QuantLibNode::InterestRateIndexDayCounter);
Nan::SetMethod(target, "InterestRateIndexValueDate", QuantLibNode::InterestRateIndexValueDate);
Nan::SetMethod(target, "InterestRateIndexFixingDate", QuantLibNode::InterestRateIndexFixingDate);
Nan::SetMethod(target, "InterestRateIndexMaturity", QuantLibNode::InterestRateIndexMaturity);
Nan::SetMethod(target, "IborIndexBusinessDayConv", QuantLibNode::IborIndexBusinessDayConv);
Nan::SetMethod(target, "IborIndexEndOfMonth", QuantLibNode::IborIndexEndOfMonth);
Nan::SetMethod(target, "SwapIndexFixedLegTenor", QuantLibNode::SwapIndexFixedLegTenor);
Nan::SetMethod(target, "SwapIndexFixedLegBDC", QuantLibNode::SwapIndexFixedLegBDC);
Nan::SetMethod(target, "InstrumentNPV", QuantLibNode::InstrumentNPV);
Nan::SetMethod(target, "InstrumentErrorEstimate", QuantLibNode::InstrumentErrorEstimate);
Nan::SetMethod(target, "InstrumentValuationDate", QuantLibNode::InstrumentValuationDate);
Nan::SetMethod(target, "InstrumentResults", QuantLibNode::InstrumentResults);
Nan::SetMethod(target, "InstrumentIsExpired", QuantLibNode::InstrumentIsExpired);
Nan::SetMethod(target, "InstrumentSetPricingEngine", QuantLibNode::InstrumentSetPricingEngine);
Nan::SetMethod(target, "Interpolation", QuantLibNode::Interpolation);
Nan::SetMethod(target, "MixedLinearCubicInterpolation", QuantLibNode::MixedLinearCubicInterpolation);
Nan::SetMethod(target, "CubicInterpolation", QuantLibNode::CubicInterpolation);
Nan::SetMethod(target, "AbcdInterpolation", QuantLibNode::AbcdInterpolation);
Nan::SetMethod(target, "SABRInterpolation", QuantLibNode::SABRInterpolation);
Nan::SetMethod(target, "Interpolation2D", QuantLibNode::Interpolation2D);
Nan::SetMethod(target, "ExtrapolatorEnableExtrapolation", QuantLibNode::ExtrapolatorEnableExtrapolation);
Nan::SetMethod(target, "InterpolationInterpolate", QuantLibNode::InterpolationInterpolate);
Nan::SetMethod(target, "InterpolationDerivative", QuantLibNode::InterpolationDerivative);
Nan::SetMethod(target, "InterpolationSecondDerivative", QuantLibNode::InterpolationSecondDerivative);
Nan::SetMethod(target, "InterpolationPrimitive", QuantLibNode::InterpolationPrimitive);
Nan::SetMethod(target, "InterpolationIsInRange", QuantLibNode::InterpolationIsInRange);
Nan::SetMethod(target, "InterpolationXmin", QuantLibNode::InterpolationXmin);
Nan::SetMethod(target, "InterpolationXmax", QuantLibNode::InterpolationXmax);
Nan::SetMethod(target, "CubicInterpolationPrimitiveConstants", QuantLibNode::CubicInterpolationPrimitiveConstants);
Nan::SetMethod(target, "CubicInterpolationACoefficients", QuantLibNode::CubicInterpolationACoefficients);
Nan::SetMethod(target, "CubicInterpolationBCoefficients", QuantLibNode::CubicInterpolationBCoefficients);
Nan::SetMethod(target, "CubicInterpolationCCoefficients", QuantLibNode::CubicInterpolationCCoefficients);
Nan::SetMethod(target, "CubicInterpolationMonotonicityAdjustments", QuantLibNode::CubicInterpolationMonotonicityAdjustments);
Nan::SetMethod(target, "AbcdInterpolationA", QuantLibNode::AbcdInterpolationA);
Nan::SetMethod(target, "AbcdInterpolationB", QuantLibNode::AbcdInterpolationB);
Nan::SetMethod(target, "AbcdInterpolationC", QuantLibNode::AbcdInterpolationC);
Nan::SetMethod(target, "AbcdInterpolationD", QuantLibNode::AbcdInterpolationD);
Nan::SetMethod(target, "AbcdInterpolationRmsError", QuantLibNode::AbcdInterpolationRmsError);
Nan::SetMethod(target, "AbcdInterpolationMaxError", QuantLibNode::AbcdInterpolationMaxError);
Nan::SetMethod(target, "AbcdInterpolationEndCriteria", QuantLibNode::AbcdInterpolationEndCriteria);
Nan::SetMethod(target, "SABRInterpolationExpiry", QuantLibNode::SABRInterpolationExpiry);
Nan::SetMethod(target, "SABRInterpolationForward", QuantLibNode::SABRInterpolationForward);
Nan::SetMethod(target, "SABRInterpolationAlpha", QuantLibNode::SABRInterpolationAlpha);
Nan::SetMethod(target, "SABRInterpolationBeta", QuantLibNode::SABRInterpolationBeta);
Nan::SetMethod(target, "SABRInterpolationNu", QuantLibNode::SABRInterpolationNu);
Nan::SetMethod(target, "SABRInterpolationRho", QuantLibNode::SABRInterpolationRho);
Nan::SetMethod(target, "SABRInterpolationRmsError", QuantLibNode::SABRInterpolationRmsError);
Nan::SetMethod(target, "SABRInterpolationMaxError", QuantLibNode::SABRInterpolationMaxError);
Nan::SetMethod(target, "SABRInterpolationEndCriteria", QuantLibNode::SABRInterpolationEndCriteria);
Nan::SetMethod(target, "SABRInterpolationWeights", QuantLibNode::SABRInterpolationWeights);
Nan::SetMethod(target, "Interpolation2DXmin", QuantLibNode::Interpolation2DXmin);
Nan::SetMethod(target, "Interpolation2DXmax", QuantLibNode::Interpolation2DXmax);
Nan::SetMethod(target, "Interpolation2DXvalues", QuantLibNode::Interpolation2DXvalues);
Nan::SetMethod(target, "Interpolation2DYmin", QuantLibNode::Interpolation2DYmin);
Nan::SetMethod(target, "Interpolation2DYmax", QuantLibNode::Interpolation2DYmax);
Nan::SetMethod(target, "Interpolation2DYvalues", QuantLibNode::Interpolation2DYvalues);
Nan::SetMethod(target, "Interpolation2DzData", QuantLibNode::Interpolation2DzData);
Nan::SetMethod(target, "Interpolation2DIsInRange", QuantLibNode::Interpolation2DIsInRange);
Nan::SetMethod(target, "Interpolation2DInterpolate", QuantLibNode::Interpolation2DInterpolate);
Nan::SetMethod(target, "GaussianDefaultProbLM", QuantLibNode::GaussianDefaultProbLM);
Nan::SetMethod(target, "TDefaultProbLM", QuantLibNode::TDefaultProbLM);
Nan::SetMethod(target, "GaussianLMDefaultCorrel", QuantLibNode::GaussianLMDefaultCorrel);
Nan::SetMethod(target, "GaussianLMAssetCorrel", QuantLibNode::GaussianLMAssetCorrel);
Nan::SetMethod(target, "GaussianLMProbNHits", QuantLibNode::GaussianLMProbNHits);
Nan::SetMethod(target, "TLMDefaultCorrel", QuantLibNode::TLMDefaultCorrel);
Nan::SetMethod(target, "TLMAssetCorrel", QuantLibNode::TLMAssetCorrel);
Nan::SetMethod(target, "TLMProbNHits", QuantLibNode::TLMProbNHits);
Nan::SetMethod(target, "Leg", QuantLibNode::Leg);
Nan::SetMethod(target, "LegFromCapFloor", QuantLibNode::LegFromCapFloor);
Nan::SetMethod(target, "LegFromSwap", QuantLibNode::LegFromSwap);
Nan::SetMethod(target, "MultiPhaseLeg", QuantLibNode::MultiPhaseLeg);
Nan::SetMethod(target, "InterestRate", QuantLibNode::InterestRate);
Nan::SetMethod(target, "LegFlowAnalysis", QuantLibNode::LegFlowAnalysis);
Nan::SetMethod(target, "LegSetCouponPricers", QuantLibNode::LegSetCouponPricers);
Nan::SetMethod(target, "InterestRateRate", QuantLibNode::InterestRateRate);
Nan::SetMethod(target, "InterestRateDayCounter", QuantLibNode::InterestRateDayCounter);
Nan::SetMethod(target, "InterestRateCompounding", QuantLibNode::InterestRateCompounding);
Nan::SetMethod(target, "InterestRateFrequency", QuantLibNode::InterestRateFrequency);
Nan::SetMethod(target, "InterestRateDiscountFactor", QuantLibNode::InterestRateDiscountFactor);
Nan::SetMethod(target, "InterestRateCompoundFactor", QuantLibNode::InterestRateCompoundFactor);
Nan::SetMethod(target, "InterestRateEquivalentRate", QuantLibNode::InterestRateEquivalentRate);
Nan::SetMethod(target, "LegStartDate", QuantLibNode::LegStartDate);
Nan::SetMethod(target, "LegMaturityDate", QuantLibNode::LegMaturityDate);
Nan::SetMethod(target, "LegIsExpired", QuantLibNode::LegIsExpired);
Nan::SetMethod(target, "LegPreviousCashFlowDate", QuantLibNode::LegPreviousCashFlowDate);
Nan::SetMethod(target, "LegNextCashFlowDate", QuantLibNode::LegNextCashFlowDate);
Nan::SetMethod(target, "LegPreviousCashFlowAmount", QuantLibNode::LegPreviousCashFlowAmount);
Nan::SetMethod(target, "LegNextCashFlowAmount", QuantLibNode::LegNextCashFlowAmount);
Nan::SetMethod(target, "LegPreviousCouponRate", QuantLibNode::LegPreviousCouponRate);
Nan::SetMethod(target, "LegNextCouponRate", QuantLibNode::LegNextCouponRate);
Nan::SetMethod(target, "LegNominal", QuantLibNode::LegNominal);
Nan::SetMethod(target, "LegAccrualStartDate", QuantLibNode::LegAccrualStartDate);
Nan::SetMethod(target, "LegAccrualEndDate", QuantLibNode::LegAccrualEndDate);
Nan::SetMethod(target, "LegReferencePeriodStart", QuantLibNode::LegReferencePeriodStart);
Nan::SetMethod(target, "LegReferencePeriodEnd", QuantLibNode::LegReferencePeriodEnd);
Nan::SetMethod(target, "LegAccrualPeriod", QuantLibNode::LegAccrualPeriod);
Nan::SetMethod(target, "LegAccrualDays", QuantLibNode::LegAccrualDays);
Nan::SetMethod(target, "LegAccruedPeriod", QuantLibNode::LegAccruedPeriod);
Nan::SetMethod(target, "LegAccruedDays", QuantLibNode::LegAccruedDays);
Nan::SetMethod(target, "LegAccruedAmount", QuantLibNode::LegAccruedAmount);
Nan::SetMethod(target, "LegNPV", QuantLibNode::LegNPV);
Nan::SetMethod(target, "LegBPS", QuantLibNode::LegBPS);
Nan::SetMethod(target, "LegAtmRate", QuantLibNode::LegAtmRate);
Nan::SetMethod(target, "LegNPVFromYield", QuantLibNode::LegNPVFromYield);
Nan::SetMethod(target, "LegBPSFromYield", QuantLibNode::LegBPSFromYield);
Nan::SetMethod(target, "LegYield", QuantLibNode::LegYield);
Nan::SetMethod(target, "LegDuration", QuantLibNode::LegDuration);
Nan::SetMethod(target, "LegConvexity", QuantLibNode::LegConvexity);
Nan::SetMethod(target, "LegBasisPointValue", QuantLibNode::LegBasisPointValue);
Nan::SetMethod(target, "LegYieldValueBasisPoint", QuantLibNode::LegYieldValueBasisPoint);
Nan::SetMethod(target, "LegNPVFromZSpread", QuantLibNode::LegNPVFromZSpread);
Nan::SetMethod(target, "LegZSpread", QuantLibNode::LegZSpread);
Nan::SetMethod(target, "InterestRateImpliedRate", QuantLibNode::InterestRateImpliedRate);
Nan::SetMethod(target, "ForwardRatePc", QuantLibNode::ForwardRatePc);
Nan::SetMethod(target, "ForwardRateIpc", QuantLibNode::ForwardRateIpc);
Nan::SetMethod(target, "ForwardRateNormalPc", QuantLibNode::ForwardRateNormalPc);
Nan::SetMethod(target, "MarketModelEvolverStartNewPath", QuantLibNode::MarketModelEvolverStartNewPath);
Nan::SetMethod(target, "MarketModelEvolverAdvanceStep", QuantLibNode::MarketModelEvolverAdvanceStep);
Nan::SetMethod(target, "MarketModelEvolverCurrentStep", QuantLibNode::MarketModelEvolverCurrentStep);
Nan::SetMethod(target, "MarketModelEvolverNumeraires", QuantLibNode::MarketModelEvolverNumeraires);
Nan::SetMethod(target, "FlatVol", QuantLibNode::FlatVol);
Nan::SetMethod(target, "AbcdVol", QuantLibNode::AbcdVol);
Nan::SetMethod(target, "PseudoRootFacade", QuantLibNode::PseudoRootFacade);
Nan::SetMethod(target, "CotSwapToFwdAdapter", QuantLibNode::CotSwapToFwdAdapter);
Nan::SetMethod(target, "FwdPeriodAdapter", QuantLibNode::FwdPeriodAdapter);
Nan::SetMethod(target, "FwdToCotSwapAdapter", QuantLibNode::FwdToCotSwapAdapter);
Nan::SetMethod(target, "FlatVolFactory", QuantLibNode::FlatVolFactory);
Nan::SetMethod(target, "MarketModelInitialRates", QuantLibNode::MarketModelInitialRates);
Nan::SetMethod(target, "MarketModelDisplacements", QuantLibNode::MarketModelDisplacements);
Nan::SetMethod(target, "MarketModelNumberOfRates", QuantLibNode::MarketModelNumberOfRates);
Nan::SetMethod(target, "MarketModelNumberOfFactors", QuantLibNode::MarketModelNumberOfFactors);
Nan::SetMethod(target, "MarketModelNumberOfSteps", QuantLibNode::MarketModelNumberOfSteps);
Nan::SetMethod(target, "MarketModelPseudoRoot", QuantLibNode::MarketModelPseudoRoot);
Nan::SetMethod(target, "MarketModelCovariance", QuantLibNode::MarketModelCovariance);
Nan::SetMethod(target, "MarketModelTotalCovariance", QuantLibNode::MarketModelTotalCovariance);
Nan::SetMethod(target, "MarketModelTimeDependentVolatility", QuantLibNode::MarketModelTimeDependentVolatility);
Nan::SetMethod(target, "CoterminalSwapForwardJacobian", QuantLibNode::CoterminalSwapForwardJacobian);
Nan::SetMethod(target, "CoterminalSwapZedMatrix", QuantLibNode::CoterminalSwapZedMatrix);
Nan::SetMethod(target, "CoinitialSwapForwardJacobian", QuantLibNode::CoinitialSwapForwardJacobian);
Nan::SetMethod(target, "CoinitialSwapZedMatrix", QuantLibNode::CoinitialSwapZedMatrix);
Nan::SetMethod(target, "CmSwapForwardJacobian", QuantLibNode::CmSwapForwardJacobian);
Nan::SetMethod(target, "CmSwapZedMatrix", QuantLibNode::CmSwapZedMatrix);
Nan::SetMethod(target, "Annuity", QuantLibNode::Annuity);
Nan::SetMethod(target, "SwapDerivative", QuantLibNode::SwapDerivative);
Nan::SetMethod(target, "RateVolDifferences", QuantLibNode::RateVolDifferences);
Nan::SetMethod(target, "RateInstVolDifferences", QuantLibNode::RateInstVolDifferences);
Nan::SetMethod(target, "SymmetricSchurDecomposition", QuantLibNode::SymmetricSchurDecomposition);
Nan::SetMethod(target, "CovarianceDecomposition", QuantLibNode::CovarianceDecomposition);
Nan::SetMethod(target, "SymmetricSchurDecompositionEigenvalues", QuantLibNode::SymmetricSchurDecompositionEigenvalues);
Nan::SetMethod(target, "SymmetricSchurDecompositionEigenvectors", QuantLibNode::SymmetricSchurDecompositionEigenvectors);
Nan::SetMethod(target, "CovarianceDecompositionVariances", QuantLibNode::CovarianceDecompositionVariances);
Nan::SetMethod(target, "CovarianceDecompositionStandardDeviations", QuantLibNode::CovarianceDecompositionStandardDeviations);
Nan::SetMethod(target, "CovarianceDecompositionCorrelationMatrix", QuantLibNode::CovarianceDecompositionCorrelationMatrix);
Nan::SetMethod(target, "PrimeNumber", QuantLibNode::PrimeNumber);
Nan::SetMethod(target, "NormDist", QuantLibNode::NormDist);
Nan::SetMethod(target, "NormSDist", QuantLibNode::NormSDist);
Nan::SetMethod(target, "NormInv", QuantLibNode::NormInv);
Nan::SetMethod(target, "NormSInv", QuantLibNode::NormSInv);
Nan::SetMethod(target, "CholeskyDecomposition", QuantLibNode::CholeskyDecomposition);
Nan::SetMethod(target, "PseudoSqrt", QuantLibNode::PseudoSqrt);
Nan::SetMethod(target, "RankReducedSqrt", QuantLibNode::RankReducedSqrt);
Nan::SetMethod(target, "GetCovariance", QuantLibNode::GetCovariance);
Nan::SetMethod(target, "EndCriteria", QuantLibNode::EndCriteria);
Nan::SetMethod(target, "NoConstraint", QuantLibNode::NoConstraint);
Nan::SetMethod(target, "Simplex", QuantLibNode::Simplex);
Nan::SetMethod(target, "LevenbergMarquardt", QuantLibNode::LevenbergMarquardt);
Nan::SetMethod(target, "ConjugateGradient", QuantLibNode::ConjugateGradient);
Nan::SetMethod(target, "SteepestDescent", QuantLibNode::SteepestDescent);
Nan::SetMethod(target, "ArmijoLineSearch", QuantLibNode::ArmijoLineSearch);
Nan::SetMethod(target, "EndCriteriaMaxIterations", QuantLibNode::EndCriteriaMaxIterations);
Nan::SetMethod(target, "EndCriteriaMaxStationaryStateIterations", QuantLibNode::EndCriteriaMaxStationaryStateIterations);
Nan::SetMethod(target, "EndCriteriaFunctionEpsilon", QuantLibNode::EndCriteriaFunctionEpsilon);
Nan::SetMethod(target, "EndCriteriaGradientNormEpsilon", QuantLibNode::EndCriteriaGradientNormEpsilon);
Nan::SetMethod(target, "SphereCylinderOptimizerClosest", QuantLibNode::SphereCylinderOptimizerClosest);
Nan::SetMethod(target, "SecondsToString", QuantLibNode::SecondsToString);
Nan::SetMethod(target, "BarrierOption", QuantLibNode::BarrierOption);
Nan::SetMethod(target, "CaAsianOption", QuantLibNode::CaAsianOption);
Nan::SetMethod(target, "DaAsianOption", QuantLibNode::DaAsianOption);
Nan::SetMethod(target, "DividendVanillaOption", QuantLibNode::DividendVanillaOption);
Nan::SetMethod(target, "ForwardVanillaOption", QuantLibNode::ForwardVanillaOption);
Nan::SetMethod(target, "VanillaOption", QuantLibNode::VanillaOption);
Nan::SetMethod(target, "EuropeanOption", QuantLibNode::EuropeanOption);
Nan::SetMethod(target, "QuantoVanillaOption", QuantLibNode::QuantoVanillaOption);
Nan::SetMethod(target, "QuantoForwardVanillaOption", QuantLibNode::QuantoForwardVanillaOption);
Nan::SetMethod(target, "Delta", QuantLibNode::Delta);
Nan::SetMethod(target, "DeltaForward", QuantLibNode::DeltaForward);
Nan::SetMethod(target, "Elasticity", QuantLibNode::Elasticity);
Nan::SetMethod(target, "Gamma", QuantLibNode::Gamma);
Nan::SetMethod(target, "Theta", QuantLibNode::Theta);
Nan::SetMethod(target, "ThetaPerDay", QuantLibNode::ThetaPerDay);
Nan::SetMethod(target, "Vega", QuantLibNode::Vega);
Nan::SetMethod(target, "Rho", QuantLibNode::Rho);
Nan::SetMethod(target, "DividendRho", QuantLibNode::DividendRho);
Nan::SetMethod(target, "ItmCashProbability", QuantLibNode::ItmCashProbability);
Nan::SetMethod(target, "OvernightIndexedSwap", QuantLibNode::OvernightIndexedSwap);
Nan::SetMethod(target, "MakeOIS", QuantLibNode::MakeOIS);
Nan::SetMethod(target, "MakeDatedOIS", QuantLibNode::MakeDatedOIS);
Nan::SetMethod(target, "OvernightIndexedSwapFromOISRateHelper", QuantLibNode::OvernightIndexedSwapFromOISRateHelper);
Nan::SetMethod(target, "OvernightIndexedSwapFixedLegBPS", QuantLibNode::OvernightIndexedSwapFixedLegBPS);
Nan::SetMethod(target, "OvernightIndexedSwapFixedLegNPV", QuantLibNode::OvernightIndexedSwapFixedLegNPV);
Nan::SetMethod(target, "OvernightIndexedSwapFairRate", QuantLibNode::OvernightIndexedSwapFairRate);
Nan::SetMethod(target, "OvernightIndexedSwapOvernightLegBPS", QuantLibNode::OvernightIndexedSwapOvernightLegBPS);
Nan::SetMethod(target, "OvernightIndexedSwapOvernightLegNPV", QuantLibNode::OvernightIndexedSwapOvernightLegNPV);
Nan::SetMethod(target, "OvernightIndexedSwapFairSpread", QuantLibNode::OvernightIndexedSwapFairSpread);
Nan::SetMethod(target, "OvernightIndexedSwapType", QuantLibNode::OvernightIndexedSwapType);
Nan::SetMethod(target, "OvernightIndexedSwapNominal", QuantLibNode::OvernightIndexedSwapNominal);
Nan::SetMethod(target, "OvernightIndexedSwapFixedRate", QuantLibNode::OvernightIndexedSwapFixedRate);
Nan::SetMethod(target, "OvernightIndexedSwapFixedDayCount", QuantLibNode::OvernightIndexedSwapFixedDayCount);
Nan::SetMethod(target, "OvernightIndexedSwapSpread", QuantLibNode::OvernightIndexedSwapSpread);
Nan::SetMethod(target, "OvernightIndexedSwapFixedLegAnalysis", QuantLibNode::OvernightIndexedSwapFixedLegAnalysis);
Nan::SetMethod(target, "OvernightIndexedSwapOvernightLegAnalysis", QuantLibNode::OvernightIndexedSwapOvernightLegAnalysis);
Nan::SetMethod(target, "StrikedTypePayoff", QuantLibNode::StrikedTypePayoff);
Nan::SetMethod(target, "DoubleStickyRatchetPayoff", QuantLibNode::DoubleStickyRatchetPayoff);
Nan::SetMethod(target, "RatchetPayoff", QuantLibNode::RatchetPayoff);
Nan::SetMethod(target, "StickyPayoff", QuantLibNode::StickyPayoff);
Nan::SetMethod(target, "RatchetMaxPayoff", QuantLibNode::RatchetMaxPayoff);
Nan::SetMethod(target, "RatchetMinPayoff", QuantLibNode::RatchetMinPayoff);
Nan::SetMethod(target, "StickyMaxPayoff", QuantLibNode::StickyMaxPayoff);
Nan::SetMethod(target, "StickyMinPayoff", QuantLibNode::StickyMinPayoff);
Nan::SetMethod(target, "PayoffName", QuantLibNode::PayoffName);
Nan::SetMethod(target, "PayoffDescription", QuantLibNode::PayoffDescription);
Nan::SetMethod(target, "PayoffValue", QuantLibNode::PayoffValue);
Nan::SetMethod(target, "PayoffOptionType", QuantLibNode::PayoffOptionType);
Nan::SetMethod(target, "PayoffStrike", QuantLibNode::PayoffStrike);
Nan::SetMethod(target, "PayoffThirdParameter", QuantLibNode::PayoffThirdParameter);
Nan::SetMethod(target, "PiecewiseYieldCurve", QuantLibNode::PiecewiseYieldCurve);
Nan::SetMethod(target, "PiecewiseYieldCurveTimes", QuantLibNode::PiecewiseYieldCurveTimes);
Nan::SetMethod(target, "PiecewiseYieldCurveDates", QuantLibNode::PiecewiseYieldCurveDates);
Nan::SetMethod(target, "PiecewiseYieldCurveData", QuantLibNode::PiecewiseYieldCurveData);
Nan::SetMethod(target, "PiecewiseYieldCurveJumpTimes", QuantLibNode::PiecewiseYieldCurveJumpTimes);
Nan::SetMethod(target, "PiecewiseYieldCurveJumpDates", QuantLibNode::PiecewiseYieldCurveJumpDates);
Nan::SetMethod(target, "MidEquivalent", QuantLibNode::MidEquivalent);
Nan::SetMethod(target, "MidSafe", QuantLibNode::MidSafe);
Nan::SetMethod(target, "BlackCalculator2", QuantLibNode::BlackCalculator2);
Nan::SetMethod(target, "BlackCalculator", QuantLibNode::BlackCalculator);
Nan::SetMethod(target, "BlackScholesCalculator2", QuantLibNode::BlackScholesCalculator2);
Nan::SetMethod(target, "BlackScholesCalculator", QuantLibNode::BlackScholesCalculator);
Nan::SetMethod(target, "PricingEngine", QuantLibNode::PricingEngine);
Nan::SetMethod(target, "DiscountingSwapEngine", QuantLibNode::DiscountingSwapEngine);
Nan::SetMethod(target, "BinomialPricingEngine", QuantLibNode::BinomialPricingEngine);
Nan::SetMethod(target, "BlackSwaptionEngine", QuantLibNode::BlackSwaptionEngine);
Nan::SetMethod(target, "BlackSwaptionEngine2", QuantLibNode::BlackSwaptionEngine2);
Nan::SetMethod(target, "BlackCapFloorEngine", QuantLibNode::BlackCapFloorEngine);
Nan::SetMethod(target, "BlackCapFloorEngine2", QuantLibNode::BlackCapFloorEngine2);
Nan::SetMethod(target, "AnalyticCapFloorEngine", QuantLibNode::AnalyticCapFloorEngine);
Nan::SetMethod(target, "BondEngine", QuantLibNode::BondEngine);
Nan::SetMethod(target, "JamshidianSwaptionEngine", QuantLibNode::JamshidianSwaptionEngine);
Nan::SetMethod(target, "TreeSwaptionEngine", QuantLibNode::TreeSwaptionEngine);
Nan::SetMethod(target, "ModelG2SwaptionEngine", QuantLibNode::ModelG2SwaptionEngine);
Nan::SetMethod(target, "BlackCalculatorValue", QuantLibNode::BlackCalculatorValue);
Nan::SetMethod(target, "BlackCalculatorDeltaForward", QuantLibNode::BlackCalculatorDeltaForward);
Nan::SetMethod(target, "BlackCalculatorDelta", QuantLibNode::BlackCalculatorDelta);
Nan::SetMethod(target, "BlackCalculatorElasticityForward", QuantLibNode::BlackCalculatorElasticityForward);
Nan::SetMethod(target, "BlackCalculatorElasticity", QuantLibNode::BlackCalculatorElasticity);
Nan::SetMethod(target, "BlackCalculatorGammaForward", QuantLibNode::BlackCalculatorGammaForward);
Nan::SetMethod(target, "BlackCalculatorGamma", QuantLibNode::BlackCalculatorGamma);
Nan::SetMethod(target, "BlackCalculatorTheta", QuantLibNode::BlackCalculatorTheta);
Nan::SetMethod(target, "BlackCalculatorThetaPerDay", QuantLibNode::BlackCalculatorThetaPerDay);
Nan::SetMethod(target, "BlackCalculatorVega", QuantLibNode::BlackCalculatorVega);
Nan::SetMethod(target, "BlackCalculatorRho", QuantLibNode::BlackCalculatorRho);
Nan::SetMethod(target, "BlackCalculatorDividendRho", QuantLibNode::BlackCalculatorDividendRho);
Nan::SetMethod(target, "BlackCalculatorItmCashProbability", QuantLibNode::BlackCalculatorItmCashProbability);
Nan::SetMethod(target, "BlackCalculatorItmAssetProbability", QuantLibNode::BlackCalculatorItmAssetProbability);
Nan::SetMethod(target, "BlackCalculatorStrikeSensitivity", QuantLibNode::BlackCalculatorStrikeSensitivity);
Nan::SetMethod(target, "BlackCalculatorAlpha", QuantLibNode::BlackCalculatorAlpha);
Nan::SetMethod(target, "BlackCalculatorBeta", QuantLibNode::BlackCalculatorBeta);
Nan::SetMethod(target, "BlackScholesCalculatorDelta", QuantLibNode::BlackScholesCalculatorDelta);
Nan::SetMethod(target, "BlackScholesCalculatorElasticity", QuantLibNode::BlackScholesCalculatorElasticity);
Nan::SetMethod(target, "BlackScholesCalculatorGamma", QuantLibNode::BlackScholesCalculatorGamma);
Nan::SetMethod(target, "BlackScholesCalculatorTheta", QuantLibNode::BlackScholesCalculatorTheta);
Nan::SetMethod(target, "BlackScholesCalculatorThetaPerDay", QuantLibNode::BlackScholesCalculatorThetaPerDay);
Nan::SetMethod(target, "BlackFormula", QuantLibNode::BlackFormula);
Nan::SetMethod(target, "BlackFormulaCashItmProbability", QuantLibNode::BlackFormulaCashItmProbability);
Nan::SetMethod(target, "BlackFormulaImpliedStdDevApproximation", QuantLibNode::BlackFormulaImpliedStdDevApproximation);
Nan::SetMethod(target, "BlackFormulaImpliedStdDev", QuantLibNode::BlackFormulaImpliedStdDev);
Nan::SetMethod(target, "BlackFormulaStdDevDerivative", QuantLibNode::BlackFormulaStdDevDerivative);
Nan::SetMethod(target, "BachelierBlackFormula", QuantLibNode::BachelierBlackFormula);
Nan::SetMethod(target, "BlackFormula2", QuantLibNode::BlackFormula2);
Nan::SetMethod(target, "BlackFormulaCashItmProbability2", QuantLibNode::BlackFormulaCashItmProbability2);
Nan::SetMethod(target, "BlackFormulaImpliedStdDevApproximation2", QuantLibNode::BlackFormulaImpliedStdDevApproximation2);
Nan::SetMethod(target, "BlackFormulaImpliedStdDev2", QuantLibNode::BlackFormulaImpliedStdDev2);
Nan::SetMethod(target, "BlackFormulaStdDevDerivative2", QuantLibNode::BlackFormulaStdDevDerivative2);
Nan::SetMethod(target, "BachelierBlackFormula2", QuantLibNode::BachelierBlackFormula2);
Nan::SetMethod(target, "GeneralizedBlackScholesProcess", QuantLibNode::GeneralizedBlackScholesProcess);
Nan::SetMethod(target, "MarketModelMultiProductComposite", QuantLibNode::MarketModelMultiProductComposite);
Nan::SetMethod(target, "MarketModelOneStepForwards", QuantLibNode::MarketModelOneStepForwards);
Nan::SetMethod(target, "MarketModelMultiStepRatchet", QuantLibNode::MarketModelMultiStepRatchet);
Nan::SetMethod(target, "MarketModelOneStepOptionlets", QuantLibNode::MarketModelOneStepOptionlets);
Nan::SetMethod(target, "MarketModelMultiProductCompositeAdd", QuantLibNode::MarketModelMultiProductCompositeAdd);
Nan::SetMethod(target, "MarketModelMultiProductCompositeFinalize", QuantLibNode::MarketModelMultiProductCompositeFinalize);
Nan::SetMethod(target, "MarketModelMultiProductSuggestedNumeraires", QuantLibNode::MarketModelMultiProductSuggestedNumeraires);
Nan::SetMethod(target, "MarketModelMultiProductPossibleCashFlowTimes", QuantLibNode::MarketModelMultiProductPossibleCashFlowTimes);
Nan::SetMethod(target, "MarketModelMultiProductNumberOfProducts", QuantLibNode::MarketModelMultiProductNumberOfProducts);
Nan::SetMethod(target, "MarketModelMultiProductMaxNumberOfCashFlowsPerProductPerStep", QuantLibNode::MarketModelMultiProductMaxNumberOfCashFlowsPerProductPerStep);
Nan::SetMethod(target, "SimpleQuote", QuantLibNode::SimpleQuote);
Nan::SetMethod(target, "ForwardValueQuote", QuantLibNode::ForwardValueQuote);
Nan::SetMethod(target, "ForwardSwapQuote", QuantLibNode::ForwardSwapQuote);
Nan::SetMethod(target, "ImpliedStdDevQuote", QuantLibNode::ImpliedStdDevQuote);
Nan::SetMethod(target, "EurodollarFuturesImpliedStdDevQuote", QuantLibNode::EurodollarFuturesImpliedStdDevQuote);
Nan::SetMethod(target, "CompositeQuote", QuantLibNode::CompositeQuote);
Nan::SetMethod(target, "FuturesConvAdjustmentQuote", QuantLibNode::FuturesConvAdjustmentQuote);
Nan::SetMethod(target, "LastFixingQuote", QuantLibNode::LastFixingQuote);
Nan::SetMethod(target, "RelinkableHandleQuote", QuantLibNode::RelinkableHandleQuote);
Nan::SetMethod(target, "QuoteValue", QuantLibNode::QuoteValue);
Nan::SetMethod(target, "QuoteIsValid", QuantLibNode::QuoteIsValid);
Nan::SetMethod(target, "SimpleQuoteReset", QuantLibNode::SimpleQuoteReset);
Nan::SetMethod(target, "SimpleQuoteSetValue", QuantLibNode::SimpleQuoteSetValue);
Nan::SetMethod(target, "SimpleQuoteSetTickValue", QuantLibNode::SimpleQuoteSetTickValue);
Nan::SetMethod(target, "SimpleQuoteTickValue", QuantLibNode::SimpleQuoteTickValue);
Nan::SetMethod(target, "FuturesConvAdjustmentQuoteVolatility", QuantLibNode::FuturesConvAdjustmentQuoteVolatility);
Nan::SetMethod(target, "FuturesConvAdjustmentQuoteMeanReversion", QuantLibNode::FuturesConvAdjustmentQuoteMeanReversion);
Nan::SetMethod(target, "FuturesConvAdjustmentQuoteImmDate", QuantLibNode::FuturesConvAdjustmentQuoteImmDate);
Nan::SetMethod(target, "FuturesConvAdjustmentQuoteFuturesValue", QuantLibNode::FuturesConvAdjustmentQuoteFuturesValue);
Nan::SetMethod(target, "LastFixingQuoteReferenceDate", QuantLibNode::LastFixingQuoteReferenceDate);
Nan::SetMethod(target, "BucketAnalysis", QuantLibNode::BucketAnalysis);
Nan::SetMethod(target, "BucketAnalysisDelta", QuantLibNode::BucketAnalysisDelta);
Nan::SetMethod(target, "BucketAnalysisDelta2", QuantLibNode::BucketAnalysisDelta2);
Nan::SetMethod(target, "MersenneTwisterRsg", QuantLibNode::MersenneTwisterRsg);
Nan::SetMethod(target, "FaureRsg", QuantLibNode::FaureRsg);
Nan::SetMethod(target, "HaltonRsg", QuantLibNode::HaltonRsg);
Nan::SetMethod(target, "SobolRsg", QuantLibNode::SobolRsg);
Nan::SetMethod(target, "Variates", QuantLibNode::Variates);
Nan::SetMethod(target, "Rand", QuantLibNode::Rand);
Nan::SetMethod(target, "Randomize", QuantLibNode::Randomize);
Nan::SetMethod(target, "RangeAccrualFloatersCoupon", QuantLibNode::RangeAccrualFloatersCoupon);
Nan::SetMethod(target, "RangeAccrualFloatersCouponFromLeg", QuantLibNode::RangeAccrualFloatersCouponFromLeg);
Nan::SetMethod(target, "RangeAccrualPricerByBgm", QuantLibNode::RangeAccrualPricerByBgm);
Nan::SetMethod(target, "RangeAccrualFloatersCouponSetPricer", QuantLibNode::RangeAccrualFloatersCouponSetPricer);
Nan::SetMethod(target, "RangeAccrualFloatersCouponObservationDates", QuantLibNode::RangeAccrualFloatersCouponObservationDates);
Nan::SetMethod(target, "RangeAccrualFloatersCouponStarDate", QuantLibNode::RangeAccrualFloatersCouponStarDate);
Nan::SetMethod(target, "RangeAccrualFloatersCouponEndDate", QuantLibNode::RangeAccrualFloatersCouponEndDate);
Nan::SetMethod(target, "RangeAccrualFloatersCouponObservationsNo", QuantLibNode::RangeAccrualFloatersCouponObservationsNo);
Nan::SetMethod(target, "RangeAccrualFloatersPrice", QuantLibNode::RangeAccrualFloatersPrice);
Nan::SetMethod(target, "SimpleFloaterPrice", QuantLibNode::SimpleFloaterPrice);
Nan::SetMethod(target, "DepositRateHelper", QuantLibNode::DepositRateHelper);
Nan::SetMethod(target, "DepositRateHelper2", QuantLibNode::DepositRateHelper2);
Nan::SetMethod(target, "SwapRateHelper", QuantLibNode::SwapRateHelper);
Nan::SetMethod(target, "SwapRateHelper2", QuantLibNode::SwapRateHelper2);
Nan::SetMethod(target, "OISRateHelper", QuantLibNode::OISRateHelper);
Nan::SetMethod(target, "DatedOISRateHelper", QuantLibNode::DatedOISRateHelper);
Nan::SetMethod(target, "FraRateHelper", QuantLibNode::FraRateHelper);
Nan::SetMethod(target, "FraRateHelper2", QuantLibNode::FraRateHelper2);
Nan::SetMethod(target, "BondHelper", QuantLibNode::BondHelper);
Nan::SetMethod(target, "FixedRateBondHelper", QuantLibNode::FixedRateBondHelper);
Nan::SetMethod(target, "FuturesRateHelper", QuantLibNode::FuturesRateHelper);
Nan::SetMethod(target, "FuturesRateHelper2", QuantLibNode::FuturesRateHelper2);
Nan::SetMethod(target, "FuturesRateHelper3", QuantLibNode::FuturesRateHelper3);
Nan::SetMethod(target, "FxSwapRateHelper", QuantLibNode::FxSwapRateHelper);
Nan::SetMethod(target, "RateHelperEarliestDate", QuantLibNode::RateHelperEarliestDate);
Nan::SetMethod(target, "RateHelperLatestRelevantDate", QuantLibNode::RateHelperLatestRelevantDate);
Nan::SetMethod(target, "RateHelperPillarDate", QuantLibNode::RateHelperPillarDate);
Nan::SetMethod(target, "RateHelperMaturityDate", QuantLibNode::RateHelperMaturityDate);
Nan::SetMethod(target, "RateHelperQuoteName", QuantLibNode::RateHelperQuoteName);
Nan::SetMethod(target, "RateHelperQuoteValue", QuantLibNode::RateHelperQuoteValue);
Nan::SetMethod(target, "RateHelperQuoteIsValid", QuantLibNode::RateHelperQuoteIsValid);
Nan::SetMethod(target, "RateHelperImpliedQuote", QuantLibNode::RateHelperImpliedQuote);
Nan::SetMethod(target, "RateHelperQuoteError", QuantLibNode::RateHelperQuoteError);
Nan::SetMethod(target, "SwapRateHelperSpread", QuantLibNode::SwapRateHelperSpread);
Nan::SetMethod(target, "SwapRateHelperForwardStart", QuantLibNode::SwapRateHelperForwardStart);
Nan::SetMethod(target, "FuturesRateHelperConvexityAdjustment", QuantLibNode::FuturesRateHelperConvexityAdjustment);
Nan::SetMethod(target, "FxSwapRateHelperSpotValue", QuantLibNode::FxSwapRateHelperSpotValue);
Nan::SetMethod(target, "FxSwapRateHelperTenor", QuantLibNode::FxSwapRateHelperTenor);
Nan::SetMethod(target, "FxSwapRateHelperFixingDays", QuantLibNode::FxSwapRateHelperFixingDays);
Nan::SetMethod(target, "FxSwapRateHelperCalendar", QuantLibNode::FxSwapRateHelperCalendar);
Nan::SetMethod(target, "FxSwapRateHelperBDC", QuantLibNode::FxSwapRateHelperBDC);
Nan::SetMethod(target, "FxSwapRateHelperEOM", QuantLibNode::FxSwapRateHelperEOM);
Nan::SetMethod(target, "FxSwapRateHelperIsBaseCurrencyCollateralCurrency", QuantLibNode::FxSwapRateHelperIsBaseCurrencyCollateralCurrency);
Nan::SetMethod(target, "RateHelperSelection", QuantLibNode::RateHelperSelection);
Nan::SetMethod(target, "RateHelperRate", QuantLibNode::RateHelperRate);
Nan::SetMethod(target, "Schedule", QuantLibNode::Schedule);
Nan::SetMethod(target, "ScheduleFromDateVector", QuantLibNode::ScheduleFromDateVector);
Nan::SetMethod(target, "ScheduleTruncated", QuantLibNode::ScheduleTruncated);
Nan::SetMethod(target, "ScheduleSize", QuantLibNode::ScheduleSize);
Nan::SetMethod(target, "SchedulePreviousDate", QuantLibNode::SchedulePreviousDate);
Nan::SetMethod(target, "ScheduleNextDate", QuantLibNode::ScheduleNextDate);
Nan::SetMethod(target, "ScheduleDates", QuantLibNode::ScheduleDates);
Nan::SetMethod(target, "ScheduleIsRegular", QuantLibNode::ScheduleIsRegular);
Nan::SetMethod(target, "ScheduleEmpty", QuantLibNode::ScheduleEmpty);
Nan::SetMethod(target, "ScheduleCalendar", QuantLibNode::ScheduleCalendar);
Nan::SetMethod(target, "ScheduleStartDate", QuantLibNode::ScheduleStartDate);
Nan::SetMethod(target, "ScheduleEndDate", QuantLibNode::ScheduleEndDate);
Nan::SetMethod(target, "ScheduleTenor", QuantLibNode::ScheduleTenor);
Nan::SetMethod(target, "ScheduleBDC", QuantLibNode::ScheduleBDC);
Nan::SetMethod(target, "ScheduleTerminationDateBDC", QuantLibNode::ScheduleTerminationDateBDC);
Nan::SetMethod(target, "ScheduleRule", QuantLibNode::ScheduleRule);
Nan::SetMethod(target, "ScheduleEndOfMonth", QuantLibNode::ScheduleEndOfMonth);
Nan::SetMethod(target, "SequenceStatistics", QuantLibNode::SequenceStatistics);
Nan::SetMethod(target, "SequenceStatistics2", QuantLibNode::SequenceStatistics2);
Nan::SetMethod(target, "SequenceStatisticsInc", QuantLibNode::SequenceStatisticsInc);
Nan::SetMethod(target, "SequenceStatisticsInc2", QuantLibNode::SequenceStatisticsInc2);
Nan::SetMethod(target, "SequenceStatisticsSamples", QuantLibNode::SequenceStatisticsSamples);
Nan::SetMethod(target, "SequenceStatisticsWeightSum", QuantLibNode::SequenceStatisticsWeightSum);
Nan::SetMethod(target, "SequenceStatisticsMean", QuantLibNode::SequenceStatisticsMean);
Nan::SetMethod(target, "SequenceStatisticsVariance", QuantLibNode::SequenceStatisticsVariance);
Nan::SetMethod(target, "SequenceStatisticsStandardDeviation", QuantLibNode::SequenceStatisticsStandardDeviation);
Nan::SetMethod(target, "SequenceStatisticsDownsideVariance", QuantLibNode::SequenceStatisticsDownsideVariance);
Nan::SetMethod(target, "SequenceStatisticsDownsideDeviation", QuantLibNode::SequenceStatisticsDownsideDeviation);
Nan::SetMethod(target, "SequenceStatisticsSemiVariance", QuantLibNode::SequenceStatisticsSemiVariance);
Nan::SetMethod(target, "SequenceStatisticsSemiDeviation", QuantLibNode::SequenceStatisticsSemiDeviation);
Nan::SetMethod(target, "SequenceStatisticsErrorEstimate", QuantLibNode::SequenceStatisticsErrorEstimate);
Nan::SetMethod(target, "SequenceStatisticsSkewness", QuantLibNode::SequenceStatisticsSkewness);
Nan::SetMethod(target, "SequenceStatisticsKurtosis", QuantLibNode::SequenceStatisticsKurtosis);
Nan::SetMethod(target, "SequenceStatisticsMin", QuantLibNode::SequenceStatisticsMin);
Nan::SetMethod(target, "SequenceStatisticsMax", QuantLibNode::SequenceStatisticsMax);
Nan::SetMethod(target, "SequenceStatisticsGaussianPercentile", QuantLibNode::SequenceStatisticsGaussianPercentile);
Nan::SetMethod(target, "SequenceStatisticsPercentile", QuantLibNode::SequenceStatisticsPercentile);
Nan::SetMethod(target, "SequenceStatisticsGaussianPotentialUpside", QuantLibNode::SequenceStatisticsGaussianPotentialUpside);
Nan::SetMethod(target, "SequenceStatisticsPotentialUpside", QuantLibNode::SequenceStatisticsPotentialUpside);
Nan::SetMethod(target, "SequenceStatisticsGaussianValueAtRisk", QuantLibNode::SequenceStatisticsGaussianValueAtRisk);
Nan::SetMethod(target, "SequenceStatisticsValueAtRisk", QuantLibNode::SequenceStatisticsValueAtRisk);
Nan::SetMethod(target, "SequenceStatisticsRegret", QuantLibNode::SequenceStatisticsRegret);
Nan::SetMethod(target, "SequenceStatisticsGaussianShortfall", QuantLibNode::SequenceStatisticsGaussianShortfall);
Nan::SetMethod(target, "SequenceStatisticsShortfall", QuantLibNode::SequenceStatisticsShortfall);
Nan::SetMethod(target, "SequenceStatisticsGaussianAverageShortfall", QuantLibNode::SequenceStatisticsGaussianAverageShortfall);
Nan::SetMethod(target, "SequenceStatisticsAverageShortfall", QuantLibNode::SequenceStatisticsAverageShortfall);
Nan::SetMethod(target, "SequenceStatisticsSize", QuantLibNode::SequenceStatisticsSize);
Nan::SetMethod(target, "SequenceStatisticsCovariance", QuantLibNode::SequenceStatisticsCovariance);
Nan::SetMethod(target, "SequenceStatisticsCorrelation", QuantLibNode::SequenceStatisticsCorrelation);
Nan::SetMethod(target, "SettingsEvaluationDate", QuantLibNode::SettingsEvaluationDate);
Nan::SetMethod(target, "SettingsSetEvaluationDate", QuantLibNode::SettingsSetEvaluationDate);
Nan::SetMethod(target, "SettingsEnforceTodaysHistoricFixings", QuantLibNode::SettingsEnforceTodaysHistoricFixings);
Nan::SetMethod(target, "SettingsSetEnforceTodaysHistoricFixings", QuantLibNode::SettingsSetEnforceTodaysHistoricFixings);
Nan::SetMethod(target, "HullWhite", QuantLibNode::HullWhite);
Nan::SetMethod(target, "Vasicek", QuantLibNode::Vasicek);
Nan::SetMethod(target, "ModelG2", QuantLibNode::ModelG2);
Nan::SetMethod(target, "VasicekA", QuantLibNode::VasicekA);
Nan::SetMethod(target, "VasicekB", QuantLibNode::VasicekB);
Nan::SetMethod(target, "VasicekLambda", QuantLibNode::VasicekLambda);
Nan::SetMethod(target, "VasicekSigma", QuantLibNode::VasicekSigma);
Nan::SetMethod(target, "ModelG2A", QuantLibNode::ModelG2A);
Nan::SetMethod(target, "ModelG2sigma", QuantLibNode::ModelG2sigma);
Nan::SetMethod(target, "ModelG2B", QuantLibNode::ModelG2B);
Nan::SetMethod(target, "ModelG2eta", QuantLibNode::ModelG2eta);
Nan::SetMethod(target, "ModelG2rho", QuantLibNode::ModelG2rho);
Nan::SetMethod(target, "FuturesConvexityBias", QuantLibNode::FuturesConvexityBias);
Nan::SetMethod(target, "FlatSmileSection", QuantLibNode::FlatSmileSection);
Nan::SetMethod(target, "SabrInterpolatedSmileSection", QuantLibNode::SabrInterpolatedSmileSection);
Nan::SetMethod(target, "SabrInterpolatedSmileSection1", QuantLibNode::SabrInterpolatedSmileSection1);
Nan::SetMethod(target, "SabrSmileSection", QuantLibNode::SabrSmileSection);
Nan::SetMethod(target, "InterpolatedSmileSection", QuantLibNode::InterpolatedSmileSection);
Nan::SetMethod(target, "SmileSectionFromSabrVolSurface", QuantLibNode::SmileSectionFromSabrVolSurface);
Nan::SetMethod(target, "SmileSectionVolatility", QuantLibNode::SmileSectionVolatility);
Nan::SetMethod(target, "SmileSectionVariance", QuantLibNode::SmileSectionVariance);
Nan::SetMethod(target, "SmileSectionAtmLevel", QuantLibNode::SmileSectionAtmLevel);
Nan::SetMethod(target, "SmileSectionExerciseDate", QuantLibNode::SmileSectionExerciseDate);
Nan::SetMethod(target, "SmileSectionDayCounter", QuantLibNode::SmileSectionDayCounter);
Nan::SetMethod(target, "SabrInterpolatedSmileSectionAlpha", QuantLibNode::SabrInterpolatedSmileSectionAlpha);
Nan::SetMethod(target, "SabrInterpolatedSmileSectionBeta", QuantLibNode::SabrInterpolatedSmileSectionBeta);
Nan::SetMethod(target, "SabrInterpolatedSmileSectionNu", QuantLibNode::SabrInterpolatedSmileSectionNu);
Nan::SetMethod(target, "SabrInterpolatedSmileSectionRho", QuantLibNode::SabrInterpolatedSmileSectionRho);
Nan::SetMethod(target, "SabrInterpolatedSmileSectionError", QuantLibNode::SabrInterpolatedSmileSectionError);
Nan::SetMethod(target, "SabrInterpolatedSmileSectionMaxError", QuantLibNode::SabrInterpolatedSmileSectionMaxError);
Nan::SetMethod(target, "SabrInterpolatedSmileSectionEndCriteria", QuantLibNode::SabrInterpolatedSmileSectionEndCriteria);
Nan::SetMethod(target, "Statistics", QuantLibNode::Statistics);
Nan::SetMethod(target, "IncrementalStatistics", QuantLibNode::IncrementalStatistics);
Nan::SetMethod(target, "StatisticsSamples", QuantLibNode::StatisticsSamples);
Nan::SetMethod(target, "StatisticsWeightSum", QuantLibNode::StatisticsWeightSum);
Nan::SetMethod(target, "StatisticsMean", QuantLibNode::StatisticsMean);
Nan::SetMethod(target, "StatisticsVariance", QuantLibNode::StatisticsVariance);
Nan::SetMethod(target, "StatisticsStandardDeviation", QuantLibNode::StatisticsStandardDeviation);
Nan::SetMethod(target, "StatisticsErrorEstimate", QuantLibNode::StatisticsErrorEstimate);
Nan::SetMethod(target, "StatisticsSkewness", QuantLibNode::StatisticsSkewness);
Nan::SetMethod(target, "StatisticsKurtosis", QuantLibNode::StatisticsKurtosis);
Nan::SetMethod(target, "StatisticsMin", QuantLibNode::StatisticsMin);
Nan::SetMethod(target, "StatisticsMax", QuantLibNode::StatisticsMax);
Nan::SetMethod(target, "StatisticsPercentile", QuantLibNode::StatisticsPercentile);
Nan::SetMethod(target, "StatisticsTopPercentile", QuantLibNode::StatisticsTopPercentile);
Nan::SetMethod(target, "StatisticsGaussianDownsideVariance", QuantLibNode::StatisticsGaussianDownsideVariance);
Nan::SetMethod(target, "StatisticsGaussianDownsideDeviation", QuantLibNode::StatisticsGaussianDownsideDeviation);
Nan::SetMethod(target, "StatisticsGaussianRegret", QuantLibNode::StatisticsGaussianRegret);
Nan::SetMethod(target, "StatisticsGaussianPercentile", QuantLibNode::StatisticsGaussianPercentile);
Nan::SetMethod(target, "StatisticsGaussianTopPercentile", QuantLibNode::StatisticsGaussianTopPercentile);
Nan::SetMethod(target, "StatisticsGaussianPotentialUpside", QuantLibNode::StatisticsGaussianPotentialUpside);
Nan::SetMethod(target, "StatisticsGaussianValueAtRisk", QuantLibNode::StatisticsGaussianValueAtRisk);
Nan::SetMethod(target, "StatisticsGaussianExpectedShortfall", QuantLibNode::StatisticsGaussianExpectedShortfall);
Nan::SetMethod(target, "StatisticsGaussianShortfall", QuantLibNode::StatisticsGaussianShortfall);
Nan::SetMethod(target, "StatisticsGaussianAverageShortfall", QuantLibNode::StatisticsGaussianAverageShortfall);
Nan::SetMethod(target, "StatisticsSemiVariance", QuantLibNode::StatisticsSemiVariance);
Nan::SetMethod(target, "StatisticsSemiDeviation", QuantLibNode::StatisticsSemiDeviation);
Nan::SetMethod(target, "StatisticsDownsideVariance", QuantLibNode::StatisticsDownsideVariance);
Nan::SetMethod(target, "StatisticsDownsideDeviation", QuantLibNode::StatisticsDownsideDeviation);
Nan::SetMethod(target, "StatisticsRegret", QuantLibNode::StatisticsRegret);
Nan::SetMethod(target, "StatisticsPotentialUpside", QuantLibNode::StatisticsPotentialUpside);
Nan::SetMethod(target, "StatisticsValueAtRisk", QuantLibNode::StatisticsValueAtRisk);
Nan::SetMethod(target, "StatisticsExpectedShortfall", QuantLibNode::StatisticsExpectedShortfall);
Nan::SetMethod(target, "StatisticsShortfall", QuantLibNode::StatisticsShortfall);
Nan::SetMethod(target, "StatisticsAverageShortfall", QuantLibNode::StatisticsAverageShortfall);
Nan::SetMethod(target, "GaussianDownsideVariance", QuantLibNode::GaussianDownsideVariance);
Nan::SetMethod(target, "GaussianDownsideDeviation", QuantLibNode::GaussianDownsideDeviation);
Nan::SetMethod(target, "GaussianRegret", QuantLibNode::GaussianRegret);
Nan::SetMethod(target, "GaussianPercentile", QuantLibNode::GaussianPercentile);
Nan::SetMethod(target, "GaussianTopPercentile", QuantLibNode::GaussianTopPercentile);
Nan::SetMethod(target, "GaussianPotentialUpside", QuantLibNode::GaussianPotentialUpside);
Nan::SetMethod(target, "GaussianValueAtRisk", QuantLibNode::GaussianValueAtRisk);
Nan::SetMethod(target, "GaussianExpectedShortfall", QuantLibNode::GaussianExpectedShortfall);
Nan::SetMethod(target, "GaussianShortfall", QuantLibNode::GaussianShortfall);
Nan::SetMethod(target, "GaussianAverageShortfall", QuantLibNode::GaussianAverageShortfall);
Nan::SetMethod(target, "Swap", QuantLibNode::Swap);
Nan::SetMethod(target, "MakeCms", QuantLibNode::MakeCms);
Nan::SetMethod(target, "SwapLegBPS", QuantLibNode::SwapLegBPS);
Nan::SetMethod(target, "SwapLegNPV", QuantLibNode::SwapLegNPV);
Nan::SetMethod(target, "SwapStartDate", QuantLibNode::SwapStartDate);
Nan::SetMethod(target, "SwapMaturityDate", QuantLibNode::SwapMaturityDate);
Nan::SetMethod(target, "SwapLegAnalysis", QuantLibNode::SwapLegAnalysis);
Nan::SetMethod(target, "Swaption", QuantLibNode::Swaption);
Nan::SetMethod(target, "MakeSwaption", QuantLibNode::MakeSwaption);
Nan::SetMethod(target, "SwaptionType", QuantLibNode::SwaptionType);
Nan::SetMethod(target, "SwaptionSettlementType", QuantLibNode::SwaptionSettlementType);
Nan::SetMethod(target, "SwaptionImpliedVolatility", QuantLibNode::SwaptionImpliedVolatility);
Nan::SetMethod(target, "RelinkableHandleSwaptionVolatilityStructure", QuantLibNode::RelinkableHandleSwaptionVolatilityStructure);
Nan::SetMethod(target, "ConstantSwaptionVolatility", QuantLibNode::ConstantSwaptionVolatility);
Nan::SetMethod(target, "SpreadedSwaptionVolatility", QuantLibNode::SpreadedSwaptionVolatility);
Nan::SetMethod(target, "SwaptionVTSMatrix", QuantLibNode::SwaptionVTSMatrix);
Nan::SetMethod(target, "SwaptionVolCube2", QuantLibNode::SwaptionVolCube2);
Nan::SetMethod(target, "SwaptionVolCube1", QuantLibNode::SwaptionVolCube1);
Nan::SetMethod(target, "SmileSectionByCube", QuantLibNode::SmileSectionByCube);
Nan::SetMethod(target, "SmileSectionByCube2", QuantLibNode::SmileSectionByCube2);
Nan::SetMethod(target, "SwaptionVTSVolatility", QuantLibNode::SwaptionVTSVolatility);
Nan::SetMethod(target, "SwaptionVTSVolatility2", QuantLibNode::SwaptionVTSVolatility2);
Nan::SetMethod(target, "SwaptionVTSBlackVariance", QuantLibNode::SwaptionVTSBlackVariance);
Nan::SetMethod(target, "SwaptionVTSBlackVariance2", QuantLibNode::SwaptionVTSBlackVariance2);
Nan::SetMethod(target, "SwaptionVTSMaxSwapTenor", QuantLibNode::SwaptionVTSMaxSwapTenor);
Nan::SetMethod(target, "SwaptionVTSBusinessDayConvention", QuantLibNode::SwaptionVTSBusinessDayConvention);
Nan::SetMethod(target, "SwaptionVTSOptionDateFromTenor", QuantLibNode::SwaptionVTSOptionDateFromTenor);
Nan::SetMethod(target, "SwaptionVTSSwapLength", QuantLibNode::SwaptionVTSSwapLength);
Nan::SetMethod(target, "SwaptionVTSSwapLength2", QuantLibNode::SwaptionVTSSwapLength2);
Nan::SetMethod(target, "SwaptionVTSMatrixOptionDates", QuantLibNode::SwaptionVTSMatrixOptionDates);
Nan::SetMethod(target, "SwaptionVTSMatrixOptionTenors", QuantLibNode::SwaptionVTSMatrixOptionTenors);
Nan::SetMethod(target, "SwaptionVTSMatrixSwapTenors", QuantLibNode::SwaptionVTSMatrixSwapTenors);
Nan::SetMethod(target, "SwaptionVTSMatrixLocate", QuantLibNode::SwaptionVTSMatrixLocate);
Nan::SetMethod(target, "SwaptionVTSatmStrike", QuantLibNode::SwaptionVTSatmStrike);
Nan::SetMethod(target, "SwaptionVTSatmStrike2", QuantLibNode::SwaptionVTSatmStrike2);
Nan::SetMethod(target, "SparseSabrParameters", QuantLibNode::SparseSabrParameters);
Nan::SetMethod(target, "DenseSabrParameters", QuantLibNode::DenseSabrParameters);
Nan::SetMethod(target, "MarketVolCube", QuantLibNode::MarketVolCube);
Nan::SetMethod(target, "VolCubeAtmCalibrated", QuantLibNode::VolCubeAtmCalibrated);
Nan::SetMethod(target, "RelinkableHandleYieldTermStructure", QuantLibNode::RelinkableHandleYieldTermStructure);
Nan::SetMethod(target, "DiscountCurve", QuantLibNode::DiscountCurve);
Nan::SetMethod(target, "ZeroCurve", QuantLibNode::ZeroCurve);
Nan::SetMethod(target, "ForwardCurve", QuantLibNode::ForwardCurve);
Nan::SetMethod(target, "FlatForward", QuantLibNode::FlatForward);
Nan::SetMethod(target, "ForwardSpreadedTermStructure", QuantLibNode::ForwardSpreadedTermStructure);
Nan::SetMethod(target, "ImpliedTermStructure", QuantLibNode::ImpliedTermStructure);
Nan::SetMethod(target, "InterpolatedYieldCurve", QuantLibNode::InterpolatedYieldCurve);
Nan::SetMethod(target, "TermStructureDayCounter", QuantLibNode::TermStructureDayCounter);
Nan::SetMethod(target, "TermStructureMaxDate", QuantLibNode::TermStructureMaxDate);
Nan::SetMethod(target, "TermStructureReferenceDate", QuantLibNode::TermStructureReferenceDate);
Nan::SetMethod(target, "TermStructureTimeFromReference", QuantLibNode::TermStructureTimeFromReference);
Nan::SetMethod(target, "TermStructureCalendar", QuantLibNode::TermStructureCalendar);
Nan::SetMethod(target, "TermStructureSettlementDays", QuantLibNode::TermStructureSettlementDays);
Nan::SetMethod(target, "YieldTSDiscount", QuantLibNode::YieldTSDiscount);
Nan::SetMethod(target, "YieldTSForwardRate", QuantLibNode::YieldTSForwardRate);
Nan::SetMethod(target, "YieldTSForwardRate2", QuantLibNode::YieldTSForwardRate2);
Nan::SetMethod(target, "YieldTSZeroRate", QuantLibNode::YieldTSZeroRate);
Nan::SetMethod(target, "InterpolatedYieldCurveTimes", QuantLibNode::InterpolatedYieldCurveTimes);
Nan::SetMethod(target, "InterpolatedYieldCurveDates", QuantLibNode::InterpolatedYieldCurveDates);
Nan::SetMethod(target, "InterpolatedYieldCurveData", QuantLibNode::InterpolatedYieldCurveData);
Nan::SetMethod(target, "InterpolatedYieldCurveJumpTimes", QuantLibNode::InterpolatedYieldCurveJumpTimes);
Nan::SetMethod(target, "InterpolatedYieldCurveJumpDates", QuantLibNode::InterpolatedYieldCurveJumpDates);
Nan::SetMethod(target, "TimeSeries", QuantLibNode::TimeSeries);
Nan::SetMethod(target, "TimeSeriesFromIndex", QuantLibNode::TimeSeriesFromIndex);
Nan::SetMethod(target, "TimeSeriesFirstDate", QuantLibNode::TimeSeriesFirstDate);
Nan::SetMethod(target, "TimeSeriesLastDate", QuantLibNode::TimeSeriesLastDate);
Nan::SetMethod(target, "TimeSeriesSize", QuantLibNode::TimeSeriesSize);
Nan::SetMethod(target, "TimeSeriesEmpty", QuantLibNode::TimeSeriesEmpty);
Nan::SetMethod(target, "TimeSeriesDates", QuantLibNode::TimeSeriesDates);
Nan::SetMethod(target, "TimeSeriesValues", QuantLibNode::TimeSeriesValues);
Nan::SetMethod(target, "TimeSeriesValue", QuantLibNode::TimeSeriesValue);
Nan::SetMethod(target, "xlVersion", QuantLibNode::xlVersion);
Nan::SetMethod(target, "AddinVersion", QuantLibNode::AddinVersion);
Nan::SetMethod(target, "Version", QuantLibNode::Version);
Nan::SetMethod(target, "FunctionCount", QuantLibNode::FunctionCount);
Nan::SetMethod(target, "VanillaSwap", QuantLibNode::VanillaSwap);
Nan::SetMethod(target, "MakeVanillaSwap", QuantLibNode::MakeVanillaSwap);
Nan::SetMethod(target, "MakeIMMSwap", QuantLibNode::MakeIMMSwap);
Nan::SetMethod(target, "VanillaSwapFromSwapIndex", QuantLibNode::VanillaSwapFromSwapIndex);
Nan::SetMethod(target, "VanillaSwapFromSwapRateHelper", QuantLibNode::VanillaSwapFromSwapRateHelper);
Nan::SetMethod(target, "VanillaSwapFixedLegBPS", QuantLibNode::VanillaSwapFixedLegBPS);
Nan::SetMethod(target, "VanillaSwapFixedLegNPV", QuantLibNode::VanillaSwapFixedLegNPV);
Nan::SetMethod(target, "VanillaSwapFairRate", QuantLibNode::VanillaSwapFairRate);
Nan::SetMethod(target, "VanillaSwapFloatingLegBPS", QuantLibNode::VanillaSwapFloatingLegBPS);
Nan::SetMethod(target, "VanillaSwapFloatingLegNPV", QuantLibNode::VanillaSwapFloatingLegNPV);
Nan::SetMethod(target, "VanillaSwapFairSpread", QuantLibNode::VanillaSwapFairSpread);
Nan::SetMethod(target, "VanillaSwapType", QuantLibNode::VanillaSwapType);
Nan::SetMethod(target, "VanillaSwapNominal", QuantLibNode::VanillaSwapNominal);
Nan::SetMethod(target, "VanillaSwapFixedRate", QuantLibNode::VanillaSwapFixedRate);
Nan::SetMethod(target, "VanillaSwapFixedDayCount", QuantLibNode::VanillaSwapFixedDayCount);
Nan::SetMethod(target, "VanillaSwapSpread", QuantLibNode::VanillaSwapSpread);
Nan::SetMethod(target, "VanillaSwapFloatingDayCount", QuantLibNode::VanillaSwapFloatingDayCount);
Nan::SetMethod(target, "VanillaSwapPaymentConvention", QuantLibNode::VanillaSwapPaymentConvention);
Nan::SetMethod(target, "VanillaSwapFixedLegAnalysis", QuantLibNode::VanillaSwapFixedLegAnalysis);
Nan::SetMethod(target, "VanillaSwapFloatingLegAnalysis", QuantLibNode::VanillaSwapFloatingLegAnalysis);
Nan::SetMethod(target, "BlackConstantVol", QuantLibNode::BlackConstantVol);
Nan::SetMethod(target, "BlackVarianceSurface", QuantLibNode::BlackVarianceSurface);
Nan::SetMethod(target, "AbcdAtmVolCurve", QuantLibNode::AbcdAtmVolCurve);
Nan::SetMethod(target, "SabrVolSurface", QuantLibNode::SabrVolSurface);
Nan::SetMethod(target, "VolatilityTermStructureBusinessDayConvention", QuantLibNode::VolatilityTermStructureBusinessDayConvention);
Nan::SetMethod(target, "VolatilityTermStructureOptionDateFromTenor", QuantLibNode::VolatilityTermStructureOptionDateFromTenor);
Nan::SetMethod(target, "VolatilityTermStructureMinStrike", QuantLibNode::VolatilityTermStructureMinStrike);
Nan::SetMethod(target, "VolatilityTermStructureMaxStrike", QuantLibNode::VolatilityTermStructureMaxStrike);
Nan::SetMethod(target, "BlackAtmVolCurveAtmVol", QuantLibNode::BlackAtmVolCurveAtmVol);
Nan::SetMethod(target, "BlackAtmVolCurveAtmVol2", QuantLibNode::BlackAtmVolCurveAtmVol2);
Nan::SetMethod(target, "BlackAtmVolCurveAtmVol3", QuantLibNode::BlackAtmVolCurveAtmVol3);
Nan::SetMethod(target, "BlackAtmVolCurveAtmVariance", QuantLibNode::BlackAtmVolCurveAtmVariance);
Nan::SetMethod(target, "BlackAtmVolCurveAtmVariance2", QuantLibNode::BlackAtmVolCurveAtmVariance2);
Nan::SetMethod(target, "BlackAtmVolCurveAtmVariance3", QuantLibNode::BlackAtmVolCurveAtmVariance3);
Nan::SetMethod(target, "BlackVolTermStructureBlackVol", QuantLibNode::BlackVolTermStructureBlackVol);
Nan::SetMethod(target, "BlackVolTermStructureBlackVariance", QuantLibNode::BlackVolTermStructureBlackVariance);
Nan::SetMethod(target, "BlackVolTermStructureBlackForwardVol", QuantLibNode::BlackVolTermStructureBlackForwardVol);
Nan::SetMethod(target, "BlackVolTermStructureBlackForwardVariance", QuantLibNode::BlackVolTermStructureBlackForwardVariance);
Nan::SetMethod(target, "AbcdAtmVolCurveOptionTenors", QuantLibNode::AbcdAtmVolCurveOptionTenors);
Nan::SetMethod(target, "AbcdAtmVolCurveOptionTenorsInInterpolation", QuantLibNode::AbcdAtmVolCurveOptionTenorsInInterpolation);
Nan::SetMethod(target, "AbcdAtmVolCurveOptionDates", QuantLibNode::AbcdAtmVolCurveOptionDates);
Nan::SetMethod(target, "AbcdAtmVolCurveOptionTimes", QuantLibNode::AbcdAtmVolCurveOptionTimes);
Nan::SetMethod(target, "AbcdAtmVolCurveRmsError", QuantLibNode::AbcdAtmVolCurveRmsError);
Nan::SetMethod(target, "AbcdAtmVolCurveMaxError", QuantLibNode::AbcdAtmVolCurveMaxError);
Nan::SetMethod(target, "AbcdAtmVolCurveA", QuantLibNode::AbcdAtmVolCurveA);
Nan::SetMethod(target, "AbcdAtmVolCurveB", QuantLibNode::AbcdAtmVolCurveB);
Nan::SetMethod(target, "AbcdAtmVolCurveC", QuantLibNode::AbcdAtmVolCurveC);
Nan::SetMethod(target, "AbcdAtmVolCurveD", QuantLibNode::AbcdAtmVolCurveD);
Nan::SetMethod(target, "AbcdAtmVolCurveKatOptionTenors", QuantLibNode::AbcdAtmVolCurveKatOptionTenors);
Nan::SetMethod(target, "AbcdAtmVolCurveK", QuantLibNode::AbcdAtmVolCurveK);
Nan::SetMethod(target, "VolatilitySpreads", QuantLibNode::VolatilitySpreads);
Nan::SetMethod(target, "VolatilitySpreads2", QuantLibNode::VolatilitySpreads2);
Nan::SetMethod(target, "AtmCurve", QuantLibNode::AtmCurve);
Nan::SetMethod(target, "SabrVolatility", QuantLibNode::SabrVolatility);
Nan::SetMethod(target, "PiecewiseConstantAbcdVariance", QuantLibNode::PiecewiseConstantAbcdVariance);
Nan::SetMethod(target, "MarketModelLmExtLinearExponentialVolModel", QuantLibNode::MarketModelLmExtLinearExponentialVolModel);
Nan::SetMethod(target, "PiecewiseConstantVarianceVariances", QuantLibNode::PiecewiseConstantVarianceVariances);
Nan::SetMethod(target, "PiecewiseConstantVarianceVolatilities", QuantLibNode::PiecewiseConstantVarianceVolatilities);
Nan::SetMethod(target, "PiecewiseConstantVarianceRateTimes", QuantLibNode::PiecewiseConstantVarianceRateTimes);
Nan::SetMethod(target, "PiecewiseConstantVarianceVariance", QuantLibNode::PiecewiseConstantVarianceVariance);
Nan::SetMethod(target, "PiecewiseConstantVarianceVolatility", QuantLibNode::PiecewiseConstantVarianceVolatility);
Nan::SetMethod(target, "PiecewiseConstantVarianceTotalVariance", QuantLibNode::PiecewiseConstantVarianceTotalVariance);
Nan::SetMethod(target, "PiecewiseConstantVarianceTotalVolatility", QuantLibNode::PiecewiseConstantVarianceTotalVolatility);
Nan::SetMethod(target, "PiecewiseYieldCurveMixedInterpolation", QuantLibNode::PiecewiseYieldCurveMixedInterpolation);
Nan::SetMethod(target, "BachelierCapFloorEngine", QuantLibNode::BachelierCapFloorEngine);
Nan::SetMethod(target, "BachelierCapFloorEngine2", QuantLibNode::BachelierCapFloorEngine2);
Nan::SetMethod(target, "BachelierBlackFormulaImpliedVol", QuantLibNode::BachelierBlackFormulaImpliedVol);
Nan::SetMethod(target, "DeleteObject", QuantLibNode::DeleteObject);
Nan::SetMethod(target, "DeleteObjects", QuantLibNode::DeleteObjects);
Nan::SetMethod(target, "DeleteAllObjects", QuantLibNode::DeleteAllObjects);
Nan::SetMethod(target, "ListObjectIDs", QuantLibNode::ListObjectIDs);
Nan::SetMethod(target, "ObjectPropertyNames", QuantLibNode::ObjectPropertyNames);
}
NODE_MODULE(quantlib, init)
| 87.414169
| 165
| 0.821203
|
quantlibnode
|
a060f63262b77064c704df214dca93a80cb7c929
| 410
|
cpp
|
C++
|
remove-element/solution.cpp
|
Javran/leetcode
|
f3899fe1424d3cda72f44102bab6dd95a7c7a320
|
[
"MIT"
] | 3
|
2018-05-08T14:08:50.000Z
|
2019-02-28T00:10:14.000Z
|
remove-element/solution.cpp
|
Javran/leetcode
|
f3899fe1424d3cda72f44102bab6dd95a7c7a320
|
[
"MIT"
] | null | null | null |
remove-element/solution.cpp
|
Javran/leetcode
|
f3899fe1424d3cda72f44102bab6dd95a7c7a320
|
[
"MIT"
] | null | null | null |
#include <vector>
class Solution {
public:
int removeElement(std::vector<int>& nums, int val) {
int newSz = 0;
// as we know newSz is always less or equal to i (implicit here)
// the write access should be fine
for (int n : nums) {
if (n != val) {
nums[newSz] = n;
++newSz;
}
}
return newSz;
}
};
| 22.777778
| 72
| 0.47561
|
Javran
|
a0612f0b5015f839d8c53e2de9d78fc53418444f
| 563
|
hpp
|
C++
|
include/openpose/core/cvMatToOpInput.hpp
|
noussquid/openpose
|
e60b5d385f5b26c27be9c2a3bcfddb6648480fc4
|
[
"MIT-CMU"
] | 7
|
2018-05-03T01:10:56.000Z
|
2021-01-12T10:39:47.000Z
|
include/openpose/core/cvMatToOpInput.hpp
|
clhne/openpose
|
29b6697d4c4afa919ac0b63c1ed80c5020cbe0df
|
[
"MIT-CMU"
] | null | null | null |
include/openpose/core/cvMatToOpInput.hpp
|
clhne/openpose
|
29b6697d4c4afa919ac0b63c1ed80c5020cbe0df
|
[
"MIT-CMU"
] | 6
|
2018-03-31T06:54:59.000Z
|
2021-08-18T12:10:42.000Z
|
#ifndef OPENPOSE_CORE_CV_MAT_TO_OP_INPUT_HPP
#define OPENPOSE_CORE_CV_MAT_TO_OP_INPUT_HPP
#include <opencv2/core/core.hpp> // cv::Mat
#include <openpose/core/common.hpp>
namespace op
{
class OP_API CvMatToOpInput
{
public:
std::vector<Array<float>> createArray(const cv::Mat& cvInputData,
const std::vector<double>& scaleInputToNetInputs,
const std::vector<Point<int>>& netInputSizes) const;
};
}
#endif // OPENPOSE_CORE_CV_MAT_TO_OP_INPUT_HPP
| 29.631579
| 98
| 0.634103
|
noussquid
|
a0613bf5354c09cdd9ab153af28f2572f48b9b28
| 37,947
|
cpp
|
C++
|
unittests/rem_rotation_test.cpp
|
kushnirenko/remprotocol
|
ec450227a40bb18527b473266b07b982efc1d093
|
[
"MIT"
] | null | null | null |
unittests/rem_rotation_test.cpp
|
kushnirenko/remprotocol
|
ec450227a40bb18527b473266b07b982efc1d093
|
[
"MIT"
] | null | null | null |
unittests/rem_rotation_test.cpp
|
kushnirenko/remprotocol
|
ec450227a40bb18527b473266b07b982efc1d093
|
[
"MIT"
] | null | null | null |
/**
* @file
* @copyright defined in eos/LICENSE.txt
*/
#include <eosio/chain/abi_serializer.hpp>
#include <eosio/testing/tester.hpp>
#include <Runtime/Runtime.h>
#include <fc/variant_object.hpp>
#include <boost/test/unit_test.hpp>
#include <contracts.hpp>
#ifdef NON_VALIDATING_TEST
#define TESTER tester
#else
#define TESTER validating_tester
#endif
using namespace eosio;
using namespace eosio::chain;
using namespace eosio::testing;
using namespace fc;
using mvo = fc::mutable_variant_object;
struct genesis_account {
account_name aname;
uint64_t initial_balance;
};
static std::vector<genesis_account> test_genesis( {
{N(b1), 100'000'000'0000ll},
{N(whale1), 70'000'000'0000ll},
{N(whale2), 40'000'000'0000ll},
{N(whale3), 20'000'000'0000ll},
{N(proda), 2'000'000'0000ll},
{N(prodb), 2'000'000'0000ll},
{N(prodc), 2'000'000'0000ll},
{N(prodd), 2'000'000'0000ll},
{N(prode), 2'000'000'0000ll},
{N(prodf), 2'000'000'0000ll},
{N(prodg), 2'000'000'0000ll},
{N(prodh), 2'000'000'0000ll},
{N(prodi), 2'000'000'0000ll},
{N(prodj), 2'000'000'0000ll},
{N(prodk), 2'000'000'0000ll},
{N(prodl), 2'000'000'0000ll},
{N(prodm), 2'000'000'0000ll},
{N(prodn), 2'000'000'0000ll},
{N(prodo), 2'000'000'0000ll},
{N(prodp), 2'000'000'0000ll},
{N(prodq), 2'000'000'0000ll},
{N(prodr), 2'000'000'0000ll},
{N(prods), 2'000'000'0000ll},
{N(prodt), 2'000'000'0000ll},
{N(produ), 2'000'000'0000ll},
{N(runnerup1), 1'000'000'0000ll},
{N(runnerup2), 1'000'000'0000ll},
{N(runnerup3), 1'000'000'0000ll},
{N(runnerup4), 1'000'000'0000ll},
{N(runnerup5), 1'000'000'0000ll},
{N(catchingup), 500'000'0000ll}
} );
class rotation_tester : public TESTER {
public:
rotation_tester();
void deploy_contract( bool call_init = true ) {
set_code( config::system_account_name, contracts::rem_system_wasm() );
set_abi( config::system_account_name, contracts::rem_system_abi().data() );
if( call_init ) {
base_tester::push_action(config::system_account_name, N(init),
config::system_account_name, mutable_variant_object()
("version", 0)
("core", CORE_SYM_STR)
);
}
const auto& accnt = control->db().get<account_object,by_name>( config::system_account_name );
abi_def abi;
BOOST_REQUIRE_EQUAL(abi_serializer::to_abi(accnt.abi, abi), true);
abi_ser.set_abi(abi, abi_serializer_max_time);
}
fc::variant get_global_state() {
vector<char> data = get_row_by_account( config::system_account_name, config::system_account_name, N(global), N(global) );
if (data.empty()) std::cout << "\nData is empty\n" << std::endl;
return data.empty() ? fc::variant() : abi_ser.binary_to_variant( "eosio_global_state", data, abi_serializer_max_time );
}
auto delegate_bandwidth( name from, name receiver, asset stake_quantity, uint8_t transfer = 1) {
auto r = base_tester::push_action(config::system_account_name, N(delegatebw), from, mvo()
("from", from )
("receiver", receiver)
("stake_quantity", stake_quantity)
("transfer", transfer)
);
produce_block();
return r;
}
void create_currency( name contract, name manager, asset maxsupply, const private_key_type* signer = nullptr ) {
auto act = mutable_variant_object()
("issuer", manager )
("maximum_supply", maxsupply );
base_tester::push_action(contract, N(create), contract, act );
}
auto issue( name contract, name manager, name to, asset amount ) {
auto r = base_tester::push_action( contract, N(issue), manager, mutable_variant_object()
("to", to )
("quantity", amount )
("memo", "")
);
produce_block();
return r;
}
auto set_privileged( name account ) {
auto r = base_tester::push_action(config::system_account_name, N(setpriv), config::system_account_name, mvo()("account", account)("is_priv", 1));
produce_block();
return r;
}
auto register_producer(name producer) {
auto r = base_tester::push_action(config::system_account_name, N(regproducer), producer, mvo()
("producer", name(producer))
("producer_key", get_public_key( producer, "active" ) )
("url", "" )
("location", 0 )
);
produce_block();
return r;
}
void votepro( account_name voter, vector<account_name> producers ) {
std::sort( producers.begin(), producers.end() );
base_tester::push_action(config::system_account_name, N(voteproducer), voter, mvo()
("voter", name(voter))
("proxy", name(0) )
("producers", producers)
);
produce_blocks();
};
void set_code_abi(const account_name& account, const vector<uint8_t>& wasm, const char* abi, const private_key_type* signer = nullptr) {
wdump((account));
set_code(account, wasm, signer);
set_abi(account, abi, signer);
if (account == config::system_account_name) {
const auto& accnt = control->db().get<account_object,by_name>( account );
abi_def abi_definition;
BOOST_REQUIRE_EQUAL(abi_serializer::to_abi(accnt.abi, abi_definition), true);
abi_ser.set_abi(abi_definition, abi_serializer_max_time);
}
produce_blocks();
}
uint32_t produce_blocks_until_schedule_is_changed(const uint32_t max_blocks) {
const auto current_version = control->active_producers().version;
uint32_t blocks_produced = 0;
while (control->active_producers().version == current_version && blocks_produced < max_blocks) {
produce_block();
blocks_produced++;
}
return blocks_produced;
}
abi_serializer abi_ser;
};
rotation_tester::rotation_tester() {
// Create rem.msig and rem.token
create_accounts({N(rem.msig), N(rem.token), N(rem.rex), N(rem.ram),
N(rem.ramfee), N(rem.stake), N(rem.bpay),
N(rem.spay), N(rem.vpay), N(rem.saving)});
// Set code for the following accounts:
// - rem (code: rem.bios) (already set by tester constructor)
// - rem.msig (code: rem.msig)
// - rem.token (code: rem.token)
set_code_abi(N(rem.msig),
contracts::rem_msig_wasm(),
contracts::rem_msig_abi().data()); //, &rem_active_pk);
set_code_abi(N(rem.token),
contracts::rem_token_wasm(),
contracts::rem_token_abi().data()); //, &rem_active_pk);
// Set privileged for rem.msig and rem.token
set_privileged(N(rem.msig));
set_privileged(N(rem.token));
// Verify rem.msig and rem.token is privileged
const auto &rem_msig_acc = get<account_metadata_object, by_name>(N(rem.msig));
BOOST_TEST(rem_msig_acc.is_privileged() == true);
const auto &rem_token_acc = get<account_metadata_object, by_name>(N(rem.token));
BOOST_TEST(rem_token_acc.is_privileged() == true);
// Create SYS tokens in rem.token, set its manager as rem
const auto max_supply = core_from_string("1000000000.0000");
const auto initial_supply = core_from_string("900000000.0000");
create_currency(N(rem.token), config::system_account_name, max_supply);
// Issue the genesis supply of 1 billion SYS tokens to rem.system
issue(N(rem.token), config::system_account_name, config::system_account_name, initial_supply);
// Create genesis accounts
for (const auto &account : test_genesis)
{
create_account(account.aname, config::system_account_name);
}
deploy_contract();
// Buy ram and stake cpu and net for each genesis accounts
for( const auto& account : test_genesis ) {
const auto stake_quantity = account.initial_balance - 1000;
const auto r = delegate_bandwidth(N(rem.stake), account.aname, asset(stake_quantity));
BOOST_REQUIRE( !r->except_ptr );
}
// register whales as producers
const auto whales_as_producers = { N(b1), N(whale1), N(whale2), N(whale3) };
for( const auto& producer : whales_as_producers ) {
register_producer(producer);
}
}
BOOST_AUTO_TEST_SUITE(rem_rotation_tests)
// Expected schedule versions:
// V1: top21[proda - prodt, produ], top25[], rotation[]
// V2: top21[proda - prodt, produ], top25[], rotation[]
// V3: top21[proda - prodt, produ], top25[], rotation[]
// ...
BOOST_FIXTURE_TEST_CASE( no_rotation_test, rotation_tester ) {
try {
const auto producer_candidates = std::vector< account_name >{
N(proda), N(prodb), N(prodc), N(prodd), N(prode), N(prodf), N(prodg),
N(prodh), N(prodi), N(prodj), N(prodk), N(prodl), N(prodm), N(prodn),
N(prodo), N(prodp), N(prodq), N(prodr), N(prods), N(prodt), N(produ)
};
// Register producers
for( auto pro : producer_candidates ) {
register_producer(pro);
}
votepro( N(b1), producer_candidates );
votepro( N(whale1), producer_candidates );
votepro( N(whale2), producer_candidates );
votepro( N(whale3), producer_candidates );
// Initial producers setup
{
produce_blocks(2);
const auto active_schedule = control->head_block_state()->active_schedule;
BOOST_REQUIRE(
std::equal( std::begin( producer_candidates ), std::end( producer_candidates ),
std::begin( active_schedule.producers ), std::end( active_schedule.producers ),
[]( const account_name& rhs, const producer_authority& lhs ) {
return rhs == lhs.producer_name;
}
)
);
}
const auto rotation_period = fc::hours(4);
// Next round
{
produce_min_num_of_blocks_to_spend_time_wo_inactive_prod(rotation_period); // skip 4 hours (default rotation time)
produce_blocks_until_schedule_is_changed(2000); // produce some blocks until new schedule (prev wait can leave as in a middle of schedule)
produce_blocks(2); // wait until schedule is accepted
const auto active_schedule = control->head_block_state()->active_schedule;
BOOST_REQUIRE(
std::equal( std::begin( producer_candidates ), std::end( producer_candidates ),
std::begin( active_schedule.producers ), std::end( active_schedule.producers ),
[]( const account_name& rhs, const producer_authority& lhs ) {
return rhs == lhs.producer_name;
}
)
);
}
// Next round
{
produce_min_num_of_blocks_to_spend_time_wo_inactive_prod(rotation_period); // skip 4 hours (default rotation time)
produce_blocks_until_schedule_is_changed(2000); // produce some blocks until new schedule (prev wait can leave as in a middle of schedule)
produce_blocks(2); // wait until schedule is accepted
const auto active_schedule = control->head_block_state()->active_schedule;
BOOST_REQUIRE(
std::equal( std::begin( producer_candidates ), std::end( producer_candidates ),
std::begin( active_schedule.producers ), std::end( active_schedule.producers ),
[]( const account_name& rhs, const producer_authority& lhs ) {
return rhs == lhs.producer_name;
}
)
);
}
} FC_LOG_AND_RETHROW()
}
// Expected schedule versions:
// V1: top21[proda - prodt, produ], top25[runnerup1-runnerup4], rotation[runnerup1, runnerup2, runnerup3, runnerup4, produ]
// V2: top21[proda - prodt, runnerup1], top25[runnerup1-runnerup4], rotation[runnerup2, runnerup3, runnerup4, produ, runnerup1]
// V3: top21[proda - prodt, runnerup2], top25[runnerup1-runnerup4], rotation[runnerup3, runnerup4, produ, runnerup1, runnerup2]
// V4: top21[proda - prodt, runnerup3], top25[runnerup1-runnerup4], rotation[runnerup4, produ, runnerup1, runnerup2, runnerup3]
// V5: top21[proda - prodt, runnerup4], top25[runnerup1-runnerup4], rotation[produ, runnerup1, runnerup2, runnerup3, runnerup4]
// V6: top21[proda - prodt, produ], top25[runnerup1-runnerup4], rotation[runnerup1, runnerup2, runnerup3, runnerup4, produ]
// ...
BOOST_FIXTURE_TEST_CASE( rotation_with_stable_top25, rotation_tester ) {
try {
auto producer_candidates = std::vector< account_name >{
N(proda), N(prodb), N(prodc), N(prodd), N(prode), N(prodf), N(prodg),
N(prodh), N(prodi), N(prodj), N(prodk), N(prodl), N(prodm), N(prodn),
N(prodo), N(prodp), N(prodq), N(prodr), N(prods), N(prodt), N(produ)
};
// Register producers
for( auto pro : producer_candidates ) {
register_producer(pro);
}
auto runnerups = std::vector< account_name >{
N(runnerup1), N(runnerup2), N(runnerup3), N(runnerup4)
};
// Register producers
for( auto pro : runnerups ) {
register_producer(pro);
}
votepro( N(b1), producer_candidates );
votepro( N(whale1), producer_candidates );
votepro( N(whale2), producer_candidates );
votepro( N(whale3), runnerups );
// After this voting producers table looks like this:
// Top21:
// proda-produ: (100'000'000'0000 + 70'000'000'0000 + 40'000'000'0000) / 21 = 10'000'000'0000
// Standby (22-24):
// runnerup1-runnerup3: 20'000'000'0000 / 3 = 6'600'000'0000
//
// So the first schedule should be proda-produ
{
produce_blocks(2);
const auto active_schedule = control->head_block_state()->active_schedule;
BOOST_REQUIRE(
std::equal( std::begin( producer_candidates ), std::end( producer_candidates ),
std::begin( active_schedule.producers ), std::end( active_schedule.producers ),
[]( const account_name& rhs, const producer_authority& lhs ) {
return rhs == lhs.producer_name;
}
)
);
}
const auto rotation_period = fc::hours(4);
// Next round should be included runnerup1 instead of produ
{
auto rota = producer_candidates;
rota.back() = N(runnerup1);
produce_min_num_of_blocks_to_spend_time_wo_inactive_prod(rotation_period); // skip 4 hours (default rotation time)
produce_blocks_until_schedule_is_changed(2000); // produce some blocks until new schedule (prev wait can leave as in a middle of schedule)
produce_blocks(2); // wait until schedule is accepted
const auto active_schedule = control->head_block_state()->active_schedule;
BOOST_REQUIRE(
std::equal( std::begin( rota ), std::end( rota ),
std::begin( active_schedule.producers ), std::end( active_schedule.producers ),
[]( const account_name& rhs, const producer_authority& lhs ) {
return rhs == lhs.producer_name;
}
)
);
}
// Next round should be included runnerup2 instead of runnerup1
{
auto rota = producer_candidates;
rota.back() = N(runnerup2);
produce_min_num_of_blocks_to_spend_time_wo_inactive_prod(rotation_period); // skip 4 hours (default rotation time)
produce_blocks_until_schedule_is_changed(2000); // produce some blocks until new schedule (prev wait can leave as in a middle of schedule)
produce_blocks(2); // wait until schedule is accepted
const auto active_schedule = control->head_block_state()->active_schedule;
BOOST_REQUIRE(
std::equal( std::begin( rota ), std::end( rota ),
std::begin( active_schedule.producers ), std::end( active_schedule.producers ),
[]( const account_name& rhs, const producer_authority& lhs ) {
return rhs == lhs.producer_name;
}
)
);
}
// Next round should be included runnerup3 instead of runnerup2
{
auto rota = producer_candidates;
rota.back() = N(runnerup3);
produce_min_num_of_blocks_to_spend_time_wo_inactive_prod(rotation_period); // skip 4 hours (default rotation time)
produce_blocks_until_schedule_is_changed(2000); // produce some blocks until new schedule (prev wait can leave as in a middle of schedule)
produce_blocks(2); // wait until schedule is accepted
const auto active_schedule = control->head_block_state()->active_schedule;
BOOST_REQUIRE(
std::equal( std::begin( rota ), std::end( rota ),
std::begin( active_schedule.producers ), std::end( active_schedule.producers ),
[]( const account_name& rhs, const producer_authority& lhs ) {
return rhs == lhs.producer_name;
}
)
);
}
// Next round should be included runnerup4 instead of runnerup3
{
auto rota = producer_candidates;
rota.back() = N(runnerup4);
produce_min_num_of_blocks_to_spend_time_wo_inactive_prod(rotation_period); // skip 4 hours (default rotation time)
produce_blocks_until_schedule_is_changed(2000); // produce some blocks until new schedule (prev wait can leave as in a middle of schedule)
produce_blocks(2); // wait until schedule is accepted
const auto active_schedule = control->head_block_state()->active_schedule;
BOOST_REQUIRE(
std::equal( std::begin( rota ), std::end( rota ),
std::begin( active_schedule.producers ), std::end( active_schedule.producers ),
[]( const account_name& rhs, const producer_authority& lhs ) {
return rhs == lhs.producer_name;
}
)
);
}
// Next round should be included produ instead of runnerup4
{
auto rota = producer_candidates;
rota.back() = N(produ);
produce_min_num_of_blocks_to_spend_time_wo_inactive_prod(rotation_period); // skip 4 hours (default rotation time)
produce_blocks_until_schedule_is_changed(2000); // produce some blocks until new schedule (prev wait can leave as in a middle of schedule)
produce_blocks(2); // wait until schedule is accepted
const auto active_schedule = control->head_block_state()->active_schedule;
BOOST_REQUIRE(
std::equal( std::begin( rota ), std::end( rota ),
std::begin( active_schedule.producers ), std::end( active_schedule.producers ),
[]( const account_name& rhs, const producer_authority& lhs ) {
return rhs == lhs.producer_name;
}
)
);
}
// Next round should be included runnerup1 instead of produ
{
auto rota = producer_candidates;
rota.back() = N(runnerup1);
produce_min_num_of_blocks_to_spend_time_wo_inactive_prod(rotation_period); // skip 4 hours (default rotation time)
produce_blocks_until_schedule_is_changed(2000); // produce some blocks until new schedule (prev wait can leave as in a middle of schedule)
produce_blocks(2); // wait until schedule is accepted
const auto active_schedule = control->head_block_state()->active_schedule;
BOOST_REQUIRE(
std::equal( std::begin( rota ), std::end( rota ),
std::begin( active_schedule.producers ), std::end( active_schedule.producers ),
[]( const account_name& rhs, const producer_authority& lhs ) {
return rhs == lhs.producer_name;
}
)
);
}
} FC_LOG_AND_RETHROW()
}
// Expected schedule versions:
// V1: top21[proda - produ], top25[runnerup1-runnerup4], rotation[runnerup1, runnerup2, runnerup3, runnerup4, produ]
// V2: top21[produ, proda - prods, runnerup1], top25[runnerup1-runnerup4], rotation[runnerup2, runnerup3, runnerup4, prodt, runnerup1]
// V3: top21[produ, proda - prods, runnerup2], top25[runnerup1-runnerup4], rotation[runnerup3, runnerup4, prodt, runnerup1, runnerup2]
// V4: top21[proda - prods, produ, runnerup3], top25[runnerup3, prodt, runnerup1, runnerup2], rotation[runnerup4, prodt, runnerup1, runnerup2, runnerup3]
BOOST_FIXTURE_TEST_CASE( top_25_reordered_test, rotation_tester ) {
try {
auto producer_candidates = std::vector< account_name >{
N(proda), N(prodb), N(prodc), N(prodd), N(prode), N(prodf), N(prodg),
N(prodh), N(prodi), N(prodj), N(prodk), N(prodl), N(prodm), N(prodn),
N(prodo), N(prodp), N(prodq), N(prodr), N(prods), N(prodt), N(produ),
N(runnerup1), N(runnerup2), N(runnerup3), N(runnerup4), N(runnerup5)
};
// Register producers
for( auto pro : producer_candidates ) {
register_producer(pro);
}
votepro( N(b1), producer_candidates );
votepro( N(whale1), producer_candidates);
votepro( N(whale2), producer_candidates );
votepro( N(whale3), producer_candidates );
// Initial schedule should be proda-produ
{
produce_blocks(2);
const auto active_schedule = control->head_block_state()->active_schedule;
BOOST_REQUIRE(
std::equal( std::begin( producer_candidates ), std::begin( producer_candidates ) + 21,
std::begin( active_schedule.producers ), std::end( active_schedule.producers ),
[]( const account_name& rhs, const producer_authority& lhs ) {
return rhs == lhs.producer_name;
}
)
);
}
const auto rotation_period = fc::hours(4);
// produ votes for himself reaching top1
// top21: produ, proda-prods
// top25: prodt, runnerup1-runnerup4
// prodt was in top25 of previous schedule so it will be rotated
{
// active schedule is sorted by name acutally
auto rota = std::vector< account_name >{
N(proda), N(prodb), N(prodc), N(prodd), N(prode), N(prodf), N(prodg),
N(prodh), N(prodi), N(prodj), N(prodk), N(prodl), N(prodm), N(prodn),
N(prodo), N(prodp), N(prodq), N(prodr), N(prods), N(produ), N(runnerup1)
};
votepro( N(produ), { N(produ) } );
produce_min_num_of_blocks_to_spend_time_wo_inactive_prod(rotation_period); // skip 4 hours (default rotation time)
produce_blocks_until_schedule_is_changed(2000); // produce some blocks until new schedule (prev wait can leave as in a middle of schedule)
produce_blocks(2); // wait until schedule is accepted
const auto active_schedule = control->head_block_state()->active_schedule;
BOOST_REQUIRE(
std::equal( std::begin( rota ), std::end( rota ),
std::begin( active_schedule.producers ), std::end( active_schedule.producers ),
[]( const account_name& rhs, const producer_authority& lhs ) {
return rhs == lhs.producer_name;
}
)
);
}
// Next round
{
// active schedule is sorted by name acutally
auto rota = std::vector< account_name >{
N(proda), N(prodb), N(prodc), N(prodd), N(prode), N(prodf), N(prodg),
N(prodh), N(prodi), N(prodj), N(prodk), N(prodl), N(prodm), N(prodn),
N(prodo), N(prodp), N(prodq), N(prodr), N(prods), N(produ), N(runnerup2)
};
produce_min_num_of_blocks_to_spend_time_wo_inactive_prod(rotation_period); // skip 4 hours (default rotation time)
produce_blocks_until_schedule_is_changed(2000); // produce some blocks until new schedule (prev wait can leave as in a middle of schedule)
produce_blocks(2); // wait until schedule is accepted
const auto active_schedule = control->head_block_state()->active_schedule;
BOOST_REQUIRE(
std::equal( std::begin( rota ), std::end( rota ),
std::begin( active_schedule.producers ), std::end( active_schedule.producers ),
[]( const account_name& rhs, const producer_authority& lhs ) {
return rhs == lhs.producer_name;
}
)
);
}
// proda-prods, produ, runnerup4 votes for themselves
// top21: proda-prods, produ, runnerup4
// top25: prodt, runnerup1-runnerup3
// runnerup4 was in top25 of previous schedule so it will be rotated
{
// active schedule is sorted by name acutally
auto rota = std::vector< account_name >{
N(proda), N(prodb), N(prodc), N(prodd), N(prode), N(prodf), N(prodg),
N(prodh), N(prodi), N(prodj), N(prodk), N(prodl), N(prodm), N(prodn),
N(prodo), N(prodp), N(prodq), N(prodr), N(prods), N(produ), N(runnerup4)
};
for( auto pro: rota ) {
votepro( pro, { pro } );
}
rota.back() = N(runnerup3);
produce_min_num_of_blocks_to_spend_time_wo_inactive_prod(rotation_period); // skip 4 hours (default rotation time)
produce_blocks_until_schedule_is_changed(2000); // produce some blocks until new schedule (prev wait can leave as in a middle of schedule)
produce_blocks(2); // wait until schedule is accepted
const auto active_schedule = control->head_block_state()->active_schedule;
BOOST_REQUIRE(
std::equal( std::begin( rota ), std::end( rota ),
std::begin( active_schedule.producers ), std::end( active_schedule.producers ),
[]( const account_name& rhs, const producer_authority& lhs ) {
return rhs == lhs.producer_name;
}
)
);
}
} FC_LOG_AND_RETHROW()
}
// Expected schedule versions:
// V1: top21[proda - prodt, produ], top25[runnerup1-runnerup4], rotation[runnerup1, runnerup2, runnerup3, runnerup4, produ]
// V2: top21[proda - prodt, runnerup5], top25[produ, runnerup1-runnerup3], rotation[runnerup5, runnerup1, runnerup2, runnerup3, produ]
// V3: top21[proda - prodt, runnerup5], top25[produ, runnerup1-runnerup3], rotation[runnerup1, runnerup2, runnerup3, produ, runnerup5]
BOOST_FIXTURE_TEST_CASE( new_top_21_test, rotation_tester ) {
try {
auto producer_candidates = std::vector< account_name >{
N(proda), N(prodb), N(prodc), N(prodd), N(prode), N(prodf), N(prodg),
N(prodh), N(prodi), N(prodj), N(prodk), N(prodl), N(prodm), N(prodn),
N(prodo), N(prodp), N(prodq), N(prodr), N(prods), N(prodt), N(produ),
N(runnerup1), N(runnerup2), N(runnerup3), N(runnerup4), N(runnerup5)
};
// Register producers
for( auto pro : producer_candidates ) {
register_producer(pro);
}
votepro( N(b1), producer_candidates );
votepro( N(whale1), producer_candidates);
votepro( N(whale2), producer_candidates );
votepro( N(whale3), producer_candidates );
// Initial schedule should be proda-produ
{
produce_blocks(2);
const auto active_schedule = control->head_block_state()->active_schedule;
BOOST_REQUIRE(
std::equal( std::begin( producer_candidates ), std::begin( producer_candidates ) + 21,
std::begin( active_schedule.producers ), std::end( active_schedule.producers ),
[]( const account_name& rhs, const producer_authority& lhs ) {
return rhs == lhs.producer_name;
}
)
);
}
const auto rotation_period = fc::hours(4);
// produ-prodt voted for themselves getting additional 2'000'000'0000 votes
// produ,runnerup1-runnerup4 did not voted for themselves
// runnerup5 voted for himselve getting additional 1'000'000'0000 votes
// top21: proda-prodt, runnerup5
// top25: produ, runnerup1-runnerup3
{
auto rota = std::vector< account_name >{
N(proda), N(prodb), N(prodc), N(prodd), N(prode), N(prodf), N(prodg),
N(prodh), N(prodi), N(prodj), N(prodk), N(prodl), N(prodm), N(prodn),
N(prodo), N(prodp), N(prodq), N(prodr), N(prods), N(prodt), N(runnerup5)
};
for (auto pro : rota) {
votepro(pro, { pro });
}
produce_min_num_of_blocks_to_spend_time_wo_inactive_prod(rotation_period); // skip 4 hours (default rotation time)
produce_blocks_until_schedule_is_changed(2000); // produce some blocks until new schedule (prev wait can leave as in a middle of schedule)
produce_blocks(2); // wait until schedule is accepted
const auto active_schedule = control->head_block_state()->active_schedule;
BOOST_REQUIRE(
std::equal( std::begin( rota ), std::end( rota ),
std::begin( active_schedule.producers ), std::end( active_schedule.producers ),
[]( const account_name& rhs, const producer_authority& lhs ) {
return rhs == lhs.producer_name;
}
)
);
}
{
auto rota = std::vector< account_name >{
N(proda), N(prodb), N(prodc), N(prodd), N(prode), N(prodf), N(prodg),
N(prodh), N(prodi), N(prodj), N(prodk), N(prodl), N(prodm), N(prodn),
N(prodo), N(prodp), N(prodq), N(prodr), N(prods), N(prodt), N(runnerup1)
};
produce_min_num_of_blocks_to_spend_time_wo_inactive_prod(rotation_period); // skip 4 hours (default rotation time)
produce_blocks_until_schedule_is_changed(2000); // produce some blocks until new schedule (prev wait can leave as in a middle of schedule)
produce_blocks(2); // wait until schedule is accepted
const auto active_schedule = control->head_block_state()->active_schedule;
// std::cout << "expected: " << std::endl;
// std::copy( std::begin( rota ), std::end( rota ), std::ostream_iterator< account_name >( std::cout, ", " ) );
// std::cout << "\nactual: " << std::endl;
// std::transform( std::begin( active_schedule.producers ), std::end( active_schedule.producers ), std::ostream_iterator< account_name >( std::cout, ", "), []( const auto& prod_key ){ return prod_key.producer_name; } );
BOOST_REQUIRE(
std::equal( std::begin( rota ), std::end( rota ),
std::begin( active_schedule.producers ), std::end( active_schedule.producers ),
[]( const account_name& rhs, const producer_authority& lhs ) {
return rhs == lhs.producer_name;
}
)
);
}
} FC_LOG_AND_RETHROW()
}
// Expected schedule versions:
// V1: top21[proda - prodt, produ], top25[runnerup1-runnerup4], rotation[runnerup1, runnerup2, runnerup3, runnerup4, produ]
// V2: top21[proda - prodt, runnerup5], top25[produ, runnerup1-runnerup3], rotation[runnerup5, runnerup1, runnerup2, runnerup3, produ]
// V3: top21[proda - prodt, runnerup5], top25[produ, runnerup1-runnerup3], rotation[runnerup1, runnerup2, runnerup3, produ, runnerup5]
BOOST_FIXTURE_TEST_CASE( new_active_prod_test, rotation_tester ) {
try {
auto producer_candidates = std::vector< account_name >{
N(proda), N(prodb), N(prodc), N(prodd), N(prode), N(prodf), N(prodg),
N(prodh), N(prodi), N(prodj), N(prodk), N(prodl), N(prodm), N(prodn),
N(prodo), N(prodp), N(prodq), N(prodr), N(prods), N(prodt), N(produ)
};
// Register producers
for( auto pro : producer_candidates ) {
register_producer(pro);
}
auto runnerups = std::vector< account_name >{
N(runnerup1), N(runnerup2), N(runnerup3), N(runnerup4)
};
// Register producers
for( auto pro : runnerups ) {
register_producer(pro);
}
register_producer(N(catchingup));
votepro( N(b1), producer_candidates );
votepro( N(whale1), producer_candidates );
votepro( N(whale2), producer_candidates );
votepro( N(whale3), runnerups );
votepro( N(catchingup), { N(catchingup) } );
// After this voting producers table looks like this:
// Top21:
// proda-produ: (100'000'000'0000 + 70'000'000'0000 + 40'000'000'0000) / 21 = 10'000'000'0000
// Standby (22-24):
// runnerup1-runnerup3: 20'000'000'0000 / 3 = 6'600'000'0000
//
// So the first schedule should be proda-produ
{
produce_blocks(2);
const auto active_schedule = control->head_block_state()->active_schedule;
BOOST_REQUIRE(
std::equal( std::begin( producer_candidates ), std::end( producer_candidates ),
std::begin( active_schedule.producers ), std::end( active_schedule.producers ),
[]( const account_name& rhs, const producer_authority& lhs ) {
return rhs == lhs.producer_name;
}
)
);
}
const auto rotation_period = fc::hours(4);
// Next round should be included runnerup1 instead of produ
{
auto rota = producer_candidates;
rota.back() = N(runnerup1);
produce_min_num_of_blocks_to_spend_time_wo_inactive_prod(rotation_period); // skip 4 hours (default rotation time)
produce_blocks_until_schedule_is_changed(2000); // produce some blocks until new schedule (prev wait can leave as in a middle of schedule)
produce_blocks(2); // wait until schedule is accepted
const auto active_schedule = control->head_block_state()->active_schedule;
BOOST_REQUIRE(
std::equal( std::begin( rota ), std::end( rota ),
std::begin( active_schedule.producers ), std::end( active_schedule.producers ),
[]( const account_name& rhs, const producer_authority& lhs ) {
return rhs == lhs.producer_name;
}
)
);
}
// catchingup reaching top1
{
producer_candidates.push_back(N(catchingup));
votepro( N(b1), producer_candidates );
votepro( N(whale1), producer_candidates );
votepro( N(whale2), producer_candidates );
produce_blocks_until_schedule_is_changed(2000);
produce_blocks(2);
auto rota = std::vector< account_name >{
N(catchingup), N(proda), N(prodb), N(prodc), N(prodd), N(prode), N(prodf),
N(prodg), N(prodh), N(prodi), N(prodj), N(prodk), N(prodl), N(prodm),
N(prodn), N(prodo), N(prodp), N(prodq), N(prodr), N(prods), N(runnerup1)
};
auto active_schedule = control->head_block_state()->active_schedule;
BOOST_REQUIRE(
std::equal( std::begin( rota ), std::end( rota ),
std::begin( active_schedule.producers ), std::end( active_schedule.producers ),
[]( const account_name& rhs, const producer_authority& lhs ) {
return rhs == lhs.producer_name;
}
)
);
auto standby = std::vector< account_name >{
N(prodt), N(produ), N(runnerup2), N(runnerup3)
};
auto actual_standby = get_global_state()["standby"].get_array();
BOOST_REQUIRE(
std::equal( std::begin( standby ), std::end( standby ),
std::begin( actual_standby ), std::end( actual_standby ),
[]( const account_name& rhs, const fc::variant& lhs ) {
return rhs == name{ lhs["first"].as_string() };
}
)
);
}
} FC_LOG_AND_RETHROW()
}
BOOST_AUTO_TEST_SUITE_END()
| 45.282816
| 231
| 0.584236
|
kushnirenko
|
a066e565e42e392490b7c5fe524de9689dc97351
| 3,866
|
cpp
|
C++
|
src/services/artifact.cpp
|
EmanuelHerrendorf/mapping-core
|
d28d85547e8ed08df37dad1da142594d3f07a366
|
[
"MIT"
] | null | null | null |
src/services/artifact.cpp
|
EmanuelHerrendorf/mapping-core
|
d28d85547e8ed08df37dad1da142594d3f07a366
|
[
"MIT"
] | 10
|
2018-03-02T13:58:32.000Z
|
2020-06-05T11:12:42.000Z
|
src/services/artifact.cpp
|
EmanuelHerrendorf/mapping-core
|
d28d85547e8ed08df37dad1da142594d3f07a366
|
[
"MIT"
] | 3
|
2018-02-26T14:01:43.000Z
|
2019-12-09T10:03:17.000Z
|
#include "services/httpservice.h"
#include "userdb/userdb.h"
#include "util/configuration.h"
#include "util/concat.h"
#include "util/exceptions.h"
#include "util/curl.h"
#include "util/timeparser.h"
#include <cstring>
#include <sstream>
#include <json/json.h>
/*
* This class provides access to the artifacts in the UserDB.
* Parameter request defines the type of request
*
* Operations:
* - request = create: Create a new artifact
* - parameters:
* - type
* - name
* - value
* - request = update: Update the value of an existing artifact
* - parameters:
* - type
* - name
* - value
* - request = get: get the value of a given artifact at a given time (latest version if not specified)
* - parameters:
* - username
* - type
* - name
* - time (optional)
* - request = list: list all artifacts of a given type
* - parmeters:
* - type
* - request = share: share an artifact with a given user
* - parameters:
* - username
* - type
* - name
*/
class ArtifactService : public HTTPService {
public:
using HTTPService::HTTPService;
virtual ~ArtifactService() = default;
struct ArtifactServiceException
: public std::runtime_error { using std::runtime_error::runtime_error; };
private:
virtual void run();
};
REGISTER_HTTP_SERVICE(ArtifactService, "artifact");
void ArtifactService::run() {
try {
std::string request = params.get("request");
auto session = UserDB::loadSession(params.get("sessiontoken"));
auto user = session->getUser();
if(request == "create") {
std::string type = params.get("type");
std::string name = params.get("name");
std::string value = params.get("value");
user.createArtifact(type, name, value);
response.sendSuccessJSON();
} else if(request == "update") {
std::string type = params.get("type");
std::string name = params.get("name");
std::string value = params.get("value");
auto artifact = user.loadArtifact(user.getUsername(), type, name);
artifact->updateValue(value);
response.sendSuccessJSON();
} else if(request == "get") {
std::string username = params.get("username");
std::string type = params.get("type");
std::string name = params.get("name");
std::string time = params.get("time", "9999-12-31T23:59:59");
auto timeParser = TimeParser::create(TimeParser::Format::ISO);
double timestamp = timeParser->parse(time);
auto artifact = user.loadArtifact(user.getUsername(), type, name);
std::string value = artifact->getArtifactVersion(timestamp)->getValue();
Json::Value json(Json::objectValue);
json["value"] = value;
response.sendSuccessJSON(json);
} else if(request == "list") {
std::string type = params.get("type");
auto artifacts = user.loadArtifactsOfType(type);
Json::Value jsonArtifacts(Json::arrayValue);
for(auto artifact : artifacts) {
Json::Value entry(Json::objectValue);
entry["user"] = artifact.getUser().getUsername();
entry["type"] = artifact.getType();
entry["name"] = artifact.getName();
jsonArtifacts.append(entry);
}
Json::Value json(Json::objectValue);
json["artifacts"] = jsonArtifacts;
response.sendSuccessJSON(json);
} else if(request == "share") {
std::string username = params.get("username");
std::string type = params.get("type");
std::string name = params.get("name");
std::string permission = params.get("permission", "");
auto artifact = user.loadArtifact(user.getUsername(), type, name);
if(permission == "user")
artifact->shareWithUser(permission);
else if(permission == "group")
artifact->shareWithGroup(permission);
else
throw ArtifactServiceException("ArtifactService: invalid permission target");
response.sendSuccessJSON();
}
}
catch (const std::exception &e) {
response.sendFailureJSON(e.what());
}
}
| 27.614286
| 103
| 0.665546
|
EmanuelHerrendorf
|
a06e6421664e57b4ebfcbb72a51ff87828a4c934
| 1,419
|
hpp
|
C++
|
include/Error.hpp
|
scribe-lang/scribe
|
28ee67cc5081aa3bdd0d4fc284c04738e3272687
|
[
"MIT"
] | 13
|
2021-12-28T17:54:05.000Z
|
2022-03-19T16:13:03.000Z
|
include/Error.hpp
|
scribelang/scribe
|
8b82ed839e290c1204928dcd196237c6cd6000ba
|
[
"MIT"
] | null | null | null |
include/Error.hpp
|
scribelang/scribe
|
8b82ed839e290c1204928dcd196237c6cd6000ba
|
[
"MIT"
] | null | null | null |
/*
MIT License
Copyright (c) 2022 Scribe Language Repositories
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.
*/
#ifndef ERROR_HPP
#define ERROR_HPP
#include "Core.hpp"
namespace sc
{
namespace lex
{
class Lexeme;
} // namespace lex
class Module;
class Stmt;
class ModuleLoc
{
Module *mod;
size_t line;
size_t col;
public:
ModuleLoc(Module *mod, const size_t &line, const size_t &col);
String getLocStr() const;
inline Module *getMod() const
{
return mod;
}
inline size_t getLine() const
{
return line;
}
inline size_t getCol() const
{
return col;
}
};
namespace err
{
void setMaxErrs(size_t max_err);
void out(Stmt *stmt, InitList<StringRef> err);
void out(const lex::Lexeme &tok, InitList<StringRef> err);
void out(const ModuleLoc &loc, InitList<StringRef> err);
// equivalent to out(), but for warnings
void outw(Stmt *stmt, InitList<StringRef> err);
void outw(const lex::Lexeme &tok, InitList<StringRef> err);
void outw(const ModuleLoc &loc, InitList<StringRef> err);
} // namespace err
} // namespace sc
#endif // ERROR_HPP
| 20.565217
| 78
| 0.735729
|
scribe-lang
|
a07c721942eee27a890fa710cd23d16785c9f452
| 6,498
|
cpp
|
C++
|
roomedit/owl-6.34/source/toolbox.cpp
|
Meridian59Kor/Meridian59
|
ab6d271c0e686250c104bd5c0886c91ec7cfa2b5
|
[
"FSFAP"
] | 119
|
2015-08-19T17:57:01.000Z
|
2022-03-30T01:41:51.000Z
|
roomedit/owl-6.34/source/toolbox.cpp
|
Meridian59Kor/Meridian59
|
ab6d271c0e686250c104bd5c0886c91ec7cfa2b5
|
[
"FSFAP"
] | 120
|
2015-01-01T13:02:04.000Z
|
2015-08-14T20:06:27.000Z
|
roomedit/owl-6.34/source/toolbox.cpp
|
Meridian59Kor/Meridian59
|
ab6d271c0e686250c104bd5c0886c91ec7cfa2b5
|
[
"FSFAP"
] | 46
|
2015-08-16T23:21:34.000Z
|
2022-02-05T01:08:22.000Z
|
//----------------------------------------------------------------------------
// ObjectWindows
// Copyright (c) 1992, 1996 by Borland International, All Rights Reserved
//
/// \file
/// Implementation of class TToolBox, a 2-d arrangement of TButtonGadgets.
//----------------------------------------------------------------------------
#include <owl/pch.h>
#include <owl/toolbox.h>
#include <owl/buttonga.h>
#include <owl/uimetric.h>
namespace owl {
OWL_DIAGINFO;
//
/// Constructs a TToolBox object with the specified number of columns and rows and
/// tiling direction. Overlaps the borders of the toolbox with those of the gadget
/// and sets ShrinkWrapWidth to true.
//
TToolBox::TToolBox(TWindow* parent,
int numColumns,
int numRows,
TTileDirection direction,
TModule* module)
:
TGadgetWindow(parent, direction, new TGadgetWindowFont, module)
{
NumRows = numRows;
NumColumns = numColumns;
// Make the gadget borders (if any) overlap the tool box's borders
//
Margins.Units = TMargins::BorderUnits;
Margins.Left = Margins.Right = 0;
Margins.Top = Margins.Bottom = 0;
ShrinkWrapWidth = true;
}
//
/// Overrides TGadget's Insert function and tells the button not to notch its corners.
///
/// Only TButtonGadgets or derived gadgets are supported.
//
void
TToolBox::Insert(TGadget& g, TPlacement placement, TGadget* sibling)
{
TGadgetWindow::Insert(g, placement, sibling);
// Notch the corners if it's a buttonGadget
//
TButtonGadget* bg = TYPESAFE_DOWNCAST(&g,TButtonGadget);
if (bg)
bg->SetNotchCorners(false);
}
//
/// Sets the direction of the tiling--either horizontal or vertical.
///
/// Swap the rows & columns count, and let our base class do the rest
//
void
TToolBox::SetDirection(TTileDirection direction)
{
TTileDirection dir = Direction;
if (dir != direction) {
int t = NumRows;
NumRows = NumColumns;
NumColumns = t;
}
TGadgetWindow::SetDirection(direction);
}
//
// Compute the numer of rows & columns, filling in rows OR columns if left
// unspecified using AS_MANY_AS_NEEDED (but not both).
//
void
TToolBox::ComputeNumRowsColumns(int& numRows, int& numColumns)
{
CHECK(NumRows != AS_MANY_AS_NEEDED || NumColumns != AS_MANY_AS_NEEDED);
numRows = NumRows == AS_MANY_AS_NEEDED ?
(NumGadgets + NumColumns - 1) / NumColumns :
NumRows;
numColumns = NumColumns == AS_MANY_AS_NEEDED ?
(NumGadgets + NumRows - 1) / NumRows :
NumColumns;
}
//
// Compute the cell size which is determined by the widest and the highest
// gadget
//
void
TToolBox::ComputeCellSize(TSize& cellSize)
{
cellSize.cx = cellSize.cy = 0;
for (TGadget* g = Gadgets; g; g = g->NextGadget()) {
TSize desiredSize(0, 0);
g->GetDesiredSize(desiredSize);
if (desiredSize.cx > cellSize.cx)
cellSize.cx = desiredSize.cx;
if (desiredSize.cy > cellSize.cy)
cellSize.cy = desiredSize.cy;
}
}
//
/// Overrides TGadget's GetDesiredSize function and computes the size of the cell by
/// calling GetMargins to get the margins.
//
void
TToolBox::GetDesiredSize(TSize& size)
{
// Get border sizes
//
int cxBorder = 0;
int cyBorder = 0;
int left, right, top, bottom;
GetMargins(Margins, left, right, top, bottom);
size.cx = left + right;
size.cy = top + bottom;
// Add in this window's border size if used
//
if (Attr.Style & WS_BORDER) {
size.cx += 2 * TUIMetric::CxBorder;
size.cy += 2 * TUIMetric::CyBorder;
}
TSize cellSize;
ComputeCellSize(cellSize);
int numRows, numColumns;
ComputeNumRowsColumns(numRows, numColumns);
size.cx += numColumns * cellSize.cx;
size.cy += numRows * cellSize.cy;
// Compensate for the gadgets overlapping if UI style does that
//
size.cx -= (numColumns - 1) * cxBorder;
size.cy -= (numRows - 1) * cyBorder;
}
//
/// Tiles the gadgets in the direction requested (horizontal or vertical). Derived
/// classes can adjust the spacing between gadgets.
///
/// Horizontal direction results in a row-major layout,
/// and vertical direction results in column-major layout
//
TRect
TToolBox::TileGadgets()
{
TSize cellSize;
ComputeCellSize(cellSize);
int numRows, numColumns;
ComputeNumRowsColumns(numRows, numColumns);
TRect innerRect;
GetInnerRect(innerRect);
TRect invalidRect;
invalidRect.SetEmpty();
if (Direction == Horizontal) {
// Row Major
//
int y = innerRect.top;
TGadget* g = Gadgets;
for (int r = 0; r < numRows; r++) {
int x = innerRect.left;
for (int c = 0; c < numColumns && g; c++) {
TRect bounds(TPoint(x, y), cellSize);
TRect originalBounds(g->GetBounds());
if (bounds != g->GetBounds()) {
g->SetBounds(bounds);
if (invalidRect.IsNull())
invalidRect = bounds;
else
invalidRect |= bounds;
if (originalBounds.TopLeft() != TPoint(0, 0))
invalidRect |= originalBounds;
}
x += cellSize.cx;
g = g->NextGadget();
}
y += cellSize.cy;
}
}
else {
// Column Major
//
int x = innerRect.left;
TGadget* g = Gadgets;
for (int c = 0; c < numColumns; c++) {
int y = innerRect.top;
for (int r = 0; r < numRows && g; r++) {
TRect bounds(TPoint(x, y), cellSize);
TRect originalBounds(g->GetBounds());
if (bounds != originalBounds) {
g->SetBounds(bounds);
if (invalidRect.IsNull())
invalidRect = bounds;
else
invalidRect |= bounds;
if (originalBounds.TopLeft() != TPoint(0, 0))
invalidRect |= originalBounds;
}
y += cellSize.cy;
g = g->NextGadget();
}
x += cellSize.cx;
}
}
return invalidRect;
}
//
/// Called when a change occurs in the size of the margins of the tool box or size
/// of the gadgets, LayoutSession gets the desired size and moves the window to
/// adjust to the desired change in size.
///
/// Assumes it is used as a client in a frame.
//
void
TToolBox::LayoutSession()
{
TGadgetWindow::LayoutSession();
TSize sz;
GetDesiredSize(sz);
SetWindowPos(0, 0,0, sz.cx, sz.cy, SWP_NOACTIVATE|SWP_NOMOVE|SWP_NOZORDER);
}
} // OWL namespace
/* ========================================================================== */
| 24.520755
| 86
| 0.609418
|
Meridian59Kor
|
a0816ebccf813b8477cc26c497a9d997686e8e4a
| 6,931
|
cpp
|
C++
|
src/training/ligature_table.cpp
|
docu9/tesseract
|
3501663a33f8eccaee78027613dc204a978ee8c1
|
[
"Apache-2.0"
] | 2
|
2020-10-24T09:37:45.000Z
|
2020-11-24T09:58:42.000Z
|
src/training/ligature_table.cpp
|
docu9/tesseract
|
3501663a33f8eccaee78027613dc204a978ee8c1
|
[
"Apache-2.0"
] | null | null | null |
src/training/ligature_table.cpp
|
docu9/tesseract
|
3501663a33f8eccaee78027613dc204a978ee8c1
|
[
"Apache-2.0"
] | 1
|
2020-11-30T14:09:28.000Z
|
2020-11-30T14:09:28.000Z
|
/**********************************************************************
* File: ligature_table.cpp
* Description: Class for adding and removing optional latin ligatures,
* conditional on codepoint support by a specified font
* (if specified).
* Author: Ranjith Unnikrishnan
* Created: Mon Nov 18 2013
*
* (C) Copyright 2013, 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 "ligature_table.h"
#include <utility>
#include "pango_font_info.h"
#include "tlog.h"
#include <tesseract/unichar.h>
#include "unicharset.h"
#include "unicode/errorcode.h" // from libicu
#include "unicode/normlzr.h" // from libicu
#include "unicode/unistr.h" // from libicu
#include "unicode/utypes.h" // from libicu
namespace tesseract {
static std::string EncodeAsUTF8(const char32 ch32) {
UNICHAR uni_ch(ch32);
return std::string(uni_ch.utf8(), uni_ch.utf8_len());
}
// Range of optional latin ligature characters in Unicode to build ligatures
// from. Note that this range does not contain the custom ligatures that we
// encode in the private use area.
const int kMinLigature = 0xfb00;
const int kMaxLigature = 0xfb17; // Don't put the wide Hebrew letters in.
/* static */
std::unique_ptr<LigatureTable> LigatureTable::instance_;
/* static */
LigatureTable* LigatureTable::Get() {
if (instance_ == nullptr) {
instance_.reset(new LigatureTable());
instance_->Init();
}
return instance_.get();
}
LigatureTable::LigatureTable() : min_lig_length_(0), max_lig_length_(0),
min_norm_length_(0), max_norm_length_(0) {}
void LigatureTable::Init() {
if (norm_to_lig_table_.empty()) {
for (char32 lig = kMinLigature; lig <= kMaxLigature; ++lig) {
// For each char in the range, convert to utf8, nfkc normalize, and if
// the strings are different put the both mappings in the hash_maps.
std::string lig8 = EncodeAsUTF8(lig);
icu::UnicodeString unicode_lig8(static_cast<UChar32>(lig));
icu::UnicodeString normed8_result;
icu::ErrorCode status;
icu::Normalizer::normalize(unicode_lig8, UNORM_NFKC, 0, normed8_result,
status);
std::string normed8;
normed8_result.toUTF8String(normed8);
// The icu::Normalizer maps the "LONG S T" ligature to "st". Correct that
// here manually so that AddLigatures() will work as desired.
if (lig8 == "\uFB05")
normed8 = "ſt";
int lig_length = lig8.length();
int norm_length = normed8.size();
if (normed8 != lig8 && lig_length > 1 && norm_length > 1) {
norm_to_lig_table_[normed8] = lig8;
lig_to_norm_table_[lig8] = normed8;
if (min_lig_length_ == 0 || lig_length < min_lig_length_)
min_lig_length_ = lig_length;
if (lig_length > max_lig_length_)
max_lig_length_ = lig_length;
if (min_norm_length_ == 0 || norm_length < min_norm_length_)
min_norm_length_ = norm_length;
if (norm_length > max_norm_length_)
max_norm_length_ = norm_length;
}
}
// Add custom extra ligatures.
for (int i = 0; UNICHARSET::kCustomLigatures[i][0] != nullptr; ++i) {
norm_to_lig_table_[UNICHARSET::kCustomLigatures[i][0]] =
UNICHARSET::kCustomLigatures[i][1];
int norm_length = strlen(UNICHARSET::kCustomLigatures[i][0]);
if (min_norm_length_ == 0 || norm_length < min_norm_length_)
min_norm_length_ = norm_length;
if (norm_length > max_norm_length_)
max_norm_length_ = norm_length;
lig_to_norm_table_[UNICHARSET::kCustomLigatures[i][1]] =
UNICHARSET::kCustomLigatures[i][0];
}
}
}
std::string LigatureTable::RemoveLigatures(const std::string& str) const {
std::string result;
UNICHAR::const_iterator it_begin = UNICHAR::begin(str.c_str(), str.length());
UNICHAR::const_iterator it_end = UNICHAR::end(str.c_str(), str.length());
char tmp[5];
int len;
for (UNICHAR::const_iterator it = it_begin; it != it_end; ++it) {
len = it.get_utf8(tmp);
tmp[len] = '\0';
LigHash::const_iterator lig_it = lig_to_norm_table_.find(tmp);
if (lig_it != lig_to_norm_table_.end()) {
result += lig_it->second;
} else {
result += tmp;
}
}
return result;
}
std::string LigatureTable::RemoveCustomLigatures(const std::string& str) const {
std::string result;
UNICHAR::const_iterator it_begin = UNICHAR::begin(str.c_str(), str.length());
UNICHAR::const_iterator it_end = UNICHAR::end(str.c_str(), str.length());
char tmp[5];
int len;
int norm_ind;
for (UNICHAR::const_iterator it = it_begin; it != it_end; ++it) {
len = it.get_utf8(tmp);
tmp[len] = '\0';
norm_ind = -1;
for (int i = 0;
UNICHARSET::kCustomLigatures[i][0] != nullptr && norm_ind < 0; ++i) {
if (!strcmp(tmp, UNICHARSET::kCustomLigatures[i][1])) {
norm_ind = i;
}
}
if (norm_ind >= 0) {
result += UNICHARSET::kCustomLigatures[norm_ind][0];
} else {
result += tmp;
}
}
return result;
}
std::string LigatureTable::AddLigatures(const std::string& str,
const PangoFontInfo* font) const {
std::string result;
int len = str.size();
int step = 0;
int i = 0;
for (i = 0; i < len - min_norm_length_ + 1; i += step) {
step = 0;
for (int liglen = max_norm_length_; liglen >= min_norm_length_; --liglen) {
if (i + liglen <= len) {
std::string lig_cand = str.substr(i, liglen);
LigHash::const_iterator it = norm_to_lig_table_.find(lig_cand);
if (it != norm_to_lig_table_.end()) {
tlog(3, "Considering %s -> %s\n", lig_cand.c_str(),
it->second.c_str());
if (font) {
// Test for renderability.
if (!font->CanRenderString(it->second.data(), it->second.length()))
continue; // Not renderable
}
// Found a match so convert it.
step = liglen;
result += it->second;
tlog(2, "Substituted %s -> %s\n", lig_cand.c_str(),
it->second.c_str());
break;
}
}
}
if (step == 0) {
result += str[i];
step = 1;
}
}
result += str.substr(i, len - i);
return result;
}
} // namespace tesseract
| 35.54359
| 80
| 0.620545
|
docu9
|
a081ee2288f180d2259a8eb2a234073c82f914f4
| 12,528
|
hpp
|
C++
|
FDPS-5.0g/src/memory_pool.hpp
|
subarutaro/GPLUM
|
89b1dadb08a0c6adcdc48879ddf2b7b0fb02912f
|
[
"MIT"
] | 2
|
2019-05-23T21:00:41.000Z
|
2019-10-03T18:05:20.000Z
|
FDPS-5.0g/src/memory_pool.hpp
|
subarutaro/GPLUM
|
89b1dadb08a0c6adcdc48879ddf2b7b0fb02912f
|
[
"MIT"
] | null | null | null |
FDPS-5.0g/src/memory_pool.hpp
|
subarutaro/GPLUM
|
89b1dadb08a0c6adcdc48879ddf2b7b0fb02912f
|
[
"MIT"
] | 10
|
2018-08-22T00:55:26.000Z
|
2022-02-28T23:21:42.000Z
|
#include<iostream>
#include<cstdlib>
#include<cassert>
#include<vector>
#if defined(PARTICLE_SIMULATOR_THREAD_PARALLEL) && defined(_OPENMP)
#include<omp.h>
#endif
namespace ParticleSimulator{
class MemoryPool{
private:
enum{
ALIGN_SIZE = 8,
N_SEGMENT_LIMIT = 10000,
};
typedef struct {
void * data;
size_t cap;
bool used;
void * ptr_data;
void * ptr_id_mpool;
} EmergencyBuffer;
MemoryPool(){}
~MemoryPool(){}
MemoryPool(const MemoryPool & mem);
MemoryPool & operator = (const MemoryPool & mem);
void * bottom_;
void * top_;
size_t cap_;
size_t size_;
size_t n_segment_;
size_t cap_per_seg_[N_SEGMENT_LIMIT];
bool used_per_seg_[N_SEGMENT_LIMIT];
void * ptr_data_per_seg_[N_SEGMENT_LIMIT];
std::vector<EmergencyBuffer> emerg_bufs_;
static MemoryPool & getInstance(){
static MemoryPool inst;
return inst;
}
static size_t getAlignSize(const size_t _size){
return (((_size-1)/ALIGN_SIZE)+1)*ALIGN_SIZE;
}
static bool isLastSegment(const int id_seg) {
if (id_seg < N_SEGMENT_LIMIT &&
getInstance().n_segment_ > 0 &&
(size_t)id_seg == getInstance().n_segment_-1) {
return true;
} else {
return false;
}
}
static bool inParallelRegion() {
#if defined(PARTICLE_SIMULATOR_THREAD_PARALLEL) && defined(_OPENMP)
const int n_thread = omp_get_num_threads();
#else
const int n_thread = 1;
#endif
if (n_thread > 1) return true;
else return false;
}
public:
static size_t getNSegment(){
return getInstance().n_segment_;
}
static size_t getSize(){
return getInstance().size_;
}
static void initialize(const size_t _cap){
getInstance().cap_ = _cap;
getInstance().size_ = 0;
getInstance().bottom_ = malloc(getInstance().cap_);
if (getInstance().bottom_ != NULL) {
getInstance().top_ = getInstance().bottom_;
getInstance().n_segment_ = 0;
for(size_t i=0; i<N_SEGMENT_LIMIT; i++){
getInstance().cap_per_seg_[i] = 0;
getInstance().used_per_seg_[i] = false;
}
} else {
std::cerr << "PS_ERROR: malloc failed. (function: " << __func__
<< ", line: " << __LINE__ << ", file: " << __FILE__
<< ")" <<std::endl;
#if defined(PARTICLE_SIMULATOR_MPI_PARALLEL)
MPI_Abort(MPI_COMM_WORLD,-1);
#endif
std::exit(-1);
}
}
static void reInitialize(const size_t size_add){
const size_t cap_old = getInstance().cap_;
const size_t cap_new = getInstance().getAlignSize( cap_old+size_add );
void * bottom_old = getInstance().bottom_;
void * bottom_new = malloc(cap_new);
if (bottom_new != NULL) {
getInstance().bottom_ = bottom_new;
const size_t diff = (size_t)getInstance().top_ - (size_t)bottom_old;
getInstance().top_ = (void*)((char*)bottom_new + diff);
getInstance().cap_ = cap_new;
memcpy(bottom_new, bottom_old, cap_old);
size_t cap_cum = 0;
for(size_t i=0; i<getInstance().n_segment_; i++){
void * p_new = (void*)((char*)bottom_new + cap_cum);
if (getInstance().used_per_seg_[i]) {
memcpy(getInstance().ptr_data_per_seg_[i], &p_new, sizeof(void*));
}
cap_cum += getInstance().cap_per_seg_[i];
}
if (bottom_old != NULL) free(bottom_old);
} else {
std::cerr << "PS_ERROR: malloc failed. (function: " << __func__
<< ", line: " << __LINE__ << ", file: " << __FILE__
<< ")" <<std::endl;
#if defined(PARTICLE_SIMULATOR_MPI_PARALLEL)
MPI_Abort(MPI_COMM_WORLD,-1);
#endif
std::exit(-1);
}
}
static void unifyMem() {
const int n_emerg_bufs = getInstance().emerg_bufs_.size();
if (!inParallelRegion() && n_emerg_bufs > 0) {
size_t size_add = 0;
for (int i=0; i<n_emerg_bufs; i++) {
if (getInstance().emerg_bufs_[i].used)
size_add += getInstance().emerg_bufs_[i].cap;
}
if (getInstance().cap_ < getInstance().size_ + size_add) {
reInitialize(size_add);
}
for (int i=0; i<n_emerg_bufs; i++) {
if (!getInstance().emerg_bufs_[i].used) continue;
void * data = getInstance().emerg_bufs_[i].data;
const size_t cap = getInstance().emerg_bufs_[i].cap;
void * ptr_data = getInstance().emerg_bufs_[i].ptr_data;
void * ptr_id_mpool = getInstance().emerg_bufs_[i].ptr_id_mpool;
void * top_prev = getInstance().top_;
// Copy a single emergency buffer to the segment at the tail
getInstance().top_ = (void *)((char*)getInstance().top_ + cap);
getInstance().size_ += cap;
getInstance().cap_per_seg_[getInstance().n_segment_] = cap;
getInstance().used_per_seg_[getInstance().n_segment_] = true;
getInstance().ptr_data_per_seg_[getInstance().n_segment_] = ptr_data;
const int id_mpool = getInstance().n_segment_;
getInstance().n_segment_++;
memcpy(top_prev, data, cap);
memcpy(ptr_data, &top_prev, sizeof(void *));
memcpy(ptr_id_mpool, &id_mpool, sizeof(int));
}
// Release emergency buffers
for (int i=0; i<n_emerg_bufs; i++) {
if (getInstance().emerg_bufs_[i].data != NULL)
free(getInstance().emerg_bufs_[i].data);
}
getInstance().emerg_bufs_.clear();
}
}
static void alloc(const size_t _size, int & _id_mpool, void * ptr_data, void *& ret){
if(_size <= 0) return;
unifyMem();
const size_t size_align = getAlignSize(_size);
size_t cap_cum = 0;
bool flag_break = false;
for(size_t i=0; i<getInstance().n_segment_; i++){
if( !getInstance().used_per_seg_[i] && getInstance().cap_per_seg_[i] >= size_align){
// insert to middle
getInstance().used_per_seg_[i] = true;
getInstance().ptr_data_per_seg_[i] = ptr_data;
_id_mpool = i;
ret = (void*)((char*)getInstance().bottom_ + cap_cum);
flag_break = true;
break;
}
cap_cum += getInstance().cap_per_seg_[i];
}
if(!flag_break){
// In this case, we add a new segment to the tail of the memory pool
assert(N_SEGMENT_LIMIT > getInstance().n_segment_+1);
// Delete the last segment first if _id_mpool points to the last segment.
if (isLastSegment(_id_mpool)) {
getInstance().n_segment_--;
getInstance().top_ = ((char*)getInstance().top_) - getInstance().cap_per_seg_[getInstance().n_segment_];
getInstance().size_ = getInstance().size_ - getInstance().cap_per_seg_[getInstance().n_segment_];
getInstance().cap_per_seg_[getInstance().n_segment_] = 0;
getInstance().used_per_seg_[getInstance().n_segment_] = false;
getInstance().ptr_data_per_seg_[getInstance().n_segment_] = NULL;
}
// Choose an operation mode
bool flag_realloc = false;
if (getInstance().cap_ < getInstance().size_ + size_align) flag_realloc = true;
bool flag_use_emerg_bufs = false;
if (flag_realloc && inParallelRegion()) flag_use_emerg_bufs = true;
// Add a new segment to the tail of the memory pool.
if (!flag_use_emerg_bufs) {
if(flag_realloc) reInitialize(size_align);
void * top_prev = getInstance().top_;
getInstance().top_ = ((char*)getInstance().top_) + size_align;
getInstance().size_ += size_align;
getInstance().cap_per_seg_[getInstance().n_segment_] = size_align;
getInstance().used_per_seg_[getInstance().n_segment_] = true;
getInstance().ptr_data_per_seg_[getInstance().n_segment_] = ptr_data;
_id_mpool = getInstance().n_segment_;
getInstance().n_segment_++;
ret = top_prev;
} else {
int n_emerg_bufs = getInstance().emerg_bufs_.size();
// Newly create an emergency buffer
const int idx = n_emerg_bufs;
n_emerg_bufs++;
getInstance().emerg_bufs_.reserve(n_emerg_bufs);
getInstance().emerg_bufs_.resize(n_emerg_bufs);
void * data = malloc(size_align);
if (data != NULL) {
getInstance().emerg_bufs_[idx].data = data;
getInstance().emerg_bufs_[idx].cap = size_align;
getInstance().emerg_bufs_[idx].used = true;
getInstance().emerg_bufs_[idx].ptr_data = ptr_data;
getInstance().emerg_bufs_[idx].ptr_id_mpool = &_id_mpool;
_id_mpool = idx + N_SEGMENT_LIMIT;
ret = getInstance().emerg_bufs_[idx].data;
} else {
std::cerr << "PS_ERROR: malloc failed. (function: " << __func__
<< ", line: " << __LINE__ << ", file: " << __FILE__
<< ")" <<std::endl;
#if defined(PARTICLE_SIMULATOR_MPI_PARALLEL)
MPI_Abort(MPI_COMM_WORLD,-1);
#endif
std::exit(-1);
}
}
}
}
static void freeMem(const int id_seg){
if(getInstance().cap_per_seg_[id_seg] <= 0) return;
if (id_seg < N_SEGMENT_LIMIT) {
getInstance().used_per_seg_[id_seg] = false;
if((size_t)id_seg == getInstance().n_segment_-1){
for(int i=id_seg; i>=0; i--){
if(getInstance().used_per_seg_[i] == true) break;
getInstance().size_ -= getInstance().cap_per_seg_[i];
getInstance().cap_per_seg_[i] = 0;
getInstance().ptr_data_per_seg_[i] = NULL;
getInstance().n_segment_--;
}
}
getInstance().top_ = ((char*)getInstance().bottom_) + getInstance().size_;
} else {
const int idx = id_seg - N_SEGMENT_LIMIT;
getInstance().emerg_bufs_[idx].used = false;
}
unifyMem();
}
static void dump(){
std::cerr<<"bottom_= "<<getInstance().bottom_<<std::endl;
std::cerr<<"top_= "<<getInstance().top_<<std::endl;
std::cerr<<"cap_= "<<getInstance().cap_<<std::endl;
std::cerr<<"size_= "<<getInstance().size_<<std::endl;
std::cerr<<"n_segment= "<<getInstance().n_segment_<<std::endl;
for(size_t i=0; i<getInstance().n_segment_; i++){
std::cerr<<"i= "<<i
<<" cap= "<<getInstance().cap_per_seg_[i]
<<" used= "<<getInstance().used_per_seg_[i]
<<std::endl;
}
}
};
}
| 45.064748
| 125
| 0.501117
|
subarutaro
|
a08335befa113d1a7b12dfe8517535383abdebbd
| 6,966
|
hpp
|
C++
|
includes/ConfigParser.hpp
|
majermou/webserv
|
65aaaf4f604ba86340e7d57eb3d2fda638708b3f
|
[
"MIT"
] | null | null | null |
includes/ConfigParser.hpp
|
majermou/webserv
|
65aaaf4f604ba86340e7d57eb3d2fda638708b3f
|
[
"MIT"
] | null | null | null |
includes/ConfigParser.hpp
|
majermou/webserv
|
65aaaf4f604ba86340e7d57eb3d2fda638708b3f
|
[
"MIT"
] | 1
|
2021-12-13T10:35:06.000Z
|
2021-12-13T10:35:06.000Z
|
#ifndef CONFIG_PARSER_HPP
#define CONFIG_PARSER_HPP
#include "ServerData.hpp"
#include "Webserv.hpp"
// fields identifiers fields definitions
// server file configuration requirements openings
#define SERVER_OP "server"
#define PORT_OP "listen"
#define HOST_OP "host"
#define SERVER_NAME_OP "server_name"
#define CLIENT_MAX_SIZE_BODY_OP "client_max_body_size"
#define ERROR_PAGE_OP "error_page"
#define ROOT_OP "root"
#define LOCATION_OP "location"
// location content fields identifiers
#define LOC_PATH "loc_path"
#define LOC_ROOT "root"
#define LOC_AUTOINDEX "autoindex"
#define LOC_INDEX "index"
#define LOC_ALLOWED_METHODS "allow_methods"
#define LOC_RETURN "return"
#define LOC_CGI "fastcgi_pass"
#define UPLOAD_LOC_ENABLE "upload_enable"
#define UPLOAD_LOC_STORE "upload_store"
#define NUMBER_OF_SERVER_PRIMITIVES 7
#define NUMBER_OF_LOCATION_PRIMITIVES 8
#define OPENNING_BRACE "{"
#define CLOSING_BRACE "}"
#define OPENNING_BRACKET '['
#define CLOSING_BRACKET ']'
#define PHP_EXTENTION ".php"
#define PYTHON_EXTENTION ".py"
#define LOCALHOST "127.0.0.1"
// error messages
#define ERROR_FILE "Could not open configuration file"
#define ERROR_FILE_EXTENSION \
"Configuration file has not the correct extension [.conf]"
#define ERROR_BRACES \
"Curly braces are not written well in the configuration file or a server " \
"identifier used with no definition"
#define ERROR_OPENING_BRACE_WITHOUT_SERVER_OR_LOC \
"Opening curly brace used without setting server or location identifier " \
"above it."
#define ERROR_DOUBLE_BRACE "Only one curly brace is allowed per line"
#define ERROR_BRACE_NOT_ALONE \
"The line which contains a curly brace must not contain something else: " \
"Error in this line -> "
#define ERROR_DEFINE_SERVER_INSIDE_SERVER \
"You can't define a server inside another server"
#define ERROR_EMPTY_SERVER_CONFIGURATION \
"A server must not have an empty configuration"
#define ERROR_INVALID_CONFIGURATION \
"This configuration file is invalid: ERROR in this line -> "
#define ERROR_EMPTY_CONFIGURATION \
"Your file does not contains any server configuration"
#define ERROR_MISSING_ELEMENTS " necessary missing elements: "
#define ERROR_MISSING_SEMICOLON "Missing a semicolon in this line: "
#define ERROR_DOUBLE_SEMICOLON \
"Should be only one semicolon at the end of this line: "
#define ERROR_PORT_NAN "The port value must be a positive number"
#define ERROR_CLIENT_BODY_SIZE_UNITY \
"The client max body size must end with 'm' (refers to megabytes) as its " \
"unity"
#define ERROR_CLIENT_BODY_SIZE_NAN \
"The value of client max body size must be a non-zero positive number"
#define ERROR_ERRPAGE_CODE_NAN \
"The value of an error page code must be a non-zero positive number"
#define ERROR_ALLOWED_METHODS_SYNTAX "Bad syntax for allowed methods in line: "
#define ERROR_ALLOWED_METHOD_METHOD_NOT_FOUND \
"This method is not one of the webserv allowed methods: [ GET, POST, " \
"DELETE ], Error in this line: "
#define ERROR_SERVER_DUPLICATE_FIELD "Duplicate server field in this line -> "
#define ERROR_LOCATION_DUPLICATE_FIELD \
"Duplicate location field in this line -> "
#define ERROR_EMPTY_LOCATION_CONFIG \
"The file configuration has an empty location configuration for this " \
"location-> "
#define ERROR_LOCATION_WITH_SEMICOLON \
"Location field does not end with a semicolon: error in this line -> "
#define ERROR_RETURN_CODE_NAN \
"The value of redirection code must be a non-zero positive number"
#define ERROR_CGI_EXTENSION_ERROR \
"The CGI extension is invalid, it must be in this format: *.extention , " \
"e.g. *.php, *.py, Error in this line: "
#define ERROR_CGI_NOT_FOUND \
"The fastcgi_pass field is not found after setting the cgi extension"
#define DID_YOU_MEAN "Did you mean "
#define IN_THIS_LINE " field in this line -> "
#define ERROR_DUPLICATE_SERVER_NAME \
"Try to use a unique name for each server: duplicate name -> "
#define ERROR_DUPLICATE_SERVER_HOST_AND_PORT \
"Two servers cannot have the same host and port, at least one must " \
"differ.duplicate host and port: "
#define ERROR_INVALID_IDENTIFIER "Invalid identifier: in this line -> "
#define CGI_NOT_SUPPORTED \
"Only these extensions are supported for CGI: [.php] and [.py], Error in " \
"this line:[ location "
class ConfigParser
{
private:
// attributes
char const *_filename;
std::vector<ServerData> _servers;
std::vector<std::string> _fileLines;
std::vector<int> _serversIndexing;
std::map<std::string, bool> _checked_primitives;
std::map<std::string, bool> _checked_location_primitives;
// methods
void _trim(std::string &);
std::vector<std::string> _split(std::string const &);
std::vector<std::string> _split(std::string const &, char);
bool _isSet(std::string const &, int (*func)(int));
std::string const &_removeDuplicateChar(std::string &, char const);
void _semicolonChecker(std::string &);
void _getFileContent();
void _indexServers();
int _isPrimitive(std::string const &);
int _isLocationPrimitive(std::string const &);
void _parseArguments(int ac, char *av[]);
// partial server fields parsers
int _portParser(size_t, ServerData &);
int _hostParser(size_t, ServerData &);
int _serverNameParser(size_t, ServerData &);
int _clientBodySizeParser(size_t, ServerData &);
int _errorPageParser(size_t, ServerData &);
int _rootDirParser(size_t, ServerData &);
// partial server location fields parsers
void _locationPathParser(size_t &, Location &);
void _locRootDirParser(size_t, Location &);
void _locAutoIndexParser(size_t, Location &);
void _locIndexParser(size_t, Location &);
void _locAllowedMethodsParser(size_t, Location &);
void _locRedirectionParser(size_t, Location &);
void _locUploadEnableParser(size_t, Location &);
void _locUploadLocationParser(size_t, Location &);
bool _isCGIsupportedExtension(std::string const &);
void _locCGIParser(size_t, Location &);
int _locationParser(size_t, ServerData &);
void _parseContent();
void addServer(ServerData const &);
public:
ConfigParser(int ac, char *av[]);
std::vector<ServerData> getServers() const;
~ConfigParser();
static std::string const primitives_openings[NUMBER_OF_SERVER_PRIMITIVES];
static std::string const
location_identifiers[NUMBER_OF_LOCATION_PRIMITIVES];
};
typedef int (ConfigParser::*ParserFuncPtr)(size_t, ServerData &);
typedef void (ConfigParser::*LocationFieldParserFuncPtr)(size_t, Location &);
#endif // !CONFIG_PARSER_HPP
| 40.5
| 80
| 0.715619
|
majermou
|
a08befae821f0be9f8724a9a6ca6be58539b3edb
| 551
|
cpp
|
C++
|
test/CErrRedirecter.cpp
|
asura/logger
|
3bbf95dd30adb32110855ac78d4055511bf43970
|
[
"MIT"
] | null | null | null |
test/CErrRedirecter.cpp
|
asura/logger
|
3bbf95dd30adb32110855ac78d4055511bf43970
|
[
"MIT"
] | 9
|
2019-09-15T21:29:20.000Z
|
2019-10-16T18:15:04.000Z
|
test/CErrRedirecter.cpp
|
asura/logger
|
3bbf95dd30adb32110855ac78d4055511bf43970
|
[
"MIT"
] | null | null | null |
#include "CErrRedirecter.h"
#include <cassert>
#include <cstring> // memset
#include <iostream>
CErrRedirecter::CErrRedirecter()
: m_locker(m_mutex)
, m_fp(open_memstream(&m_buffer, &m_size))
, m_buffer(nullptr)
, m_size(0)
, m_old(stderr)
{
if (!m_fp)
{
throw std::runtime_error("open_memstream failed");
}
assert(m_old != nullptr);
stderr = m_fp;
}
CErrRedirecter::~CErrRedirecter()
{
stderr = m_old;
std::fclose(m_fp);
if (m_buffer != nullptr)
{
free(m_buffer);
}
}
| 16.69697
| 58
| 0.607985
|
asura
|
a08cc2d0ce250e2de1602d71d894615a3108c1b4
| 13,519
|
cpp
|
C++
|
src/Framework/Graphics.cpp
|
Belfer/SFMLTemplate
|
7dcf4aa26239252597d681ca72888463cd4a54b0
|
[
"MIT"
] | null | null | null |
src/Framework/Graphics.cpp
|
Belfer/SFMLTemplate
|
7dcf4aa26239252597d681ca72888463cd4a54b0
|
[
"MIT"
] | null | null | null |
src/Framework/Graphics.cpp
|
Belfer/SFMLTemplate
|
7dcf4aa26239252597d681ca72888463cd4a54b0
|
[
"MIT"
] | null | null | null |
#include "Graphics.hpp"
#include <glad/glad.h>
#include <glm/gtc/type_ptr.hpp>
#include <iostream>
#define ASSERT(expr) assert(expr)
bool CheckGLError()
{
GLenum err;
while ((err = glGetError()) != GL_NO_ERROR)
switch (err)
{
case GL_INVALID_ENUM: std::cout << "GL_INVALID_ENUM" << std::endl; return false;
case GL_INVALID_VALUE: std::cout << "GL_INVALID_VALUE" << std::endl; return false;
case GL_INVALID_OPERATION: std::cout << "GL_INVALID_OPERATION" << std::endl; return false;
case GL_INVALID_FRAMEBUFFER_OPERATION: std::cout << "GL_INVALID_FRAMEBUFFER_OPERATION" << std::endl; return false;
case GL_OUT_OF_MEMORY: std::cout << "GL_OUT_OF_MEMORY" << std::endl; return false;
}
return true;
}
bool CheckShaderStatus(Shader shader, bool linked)
{
ASSERT(shader != 0);
int success;
char infoLog[512];
if (!linked)
{
glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(shader, 512, NULL, infoLog);
std::cout << "COMPILATION_FAILED:\n" << infoLog << std::endl;
}
}
else
{
glGetProgramiv(shader, GL_LINK_STATUS, &success);
if (!success)
{
glGetProgramInfoLog(shader, 512, NULL, infoLog);
std::cout << "LINKING_FAILED:\n" << infoLog << std::endl;
}
}
return success;
}
void Graphics::Initialize()
{
gladLoadGL();
}
void Graphics::SetViewport(float x, float y, float width, float height)
{
glViewport(x, y, width, height);
ASSERT(CheckGLError());
}
void Graphics::SetClearColor(float r, float g, float b, float a)
{
glClearColor(r, g, b, a);
ASSERT(CheckGLError());
}
void Graphics::SetClearDepth(float depth)
{
glClearDepth(depth);
ASSERT(CheckGLError());
}
void Graphics::SetClearStencil(unsigned int mask)
{
glStencilMask(mask);
ASSERT(CheckGLError());
}
void Graphics::ClearScreen(bool color, bool depth, bool stencil)
{
GLbitfield mask = 0;
mask |= color ? GL_COLOR_BUFFER_BIT : 0;
mask |= depth ? GL_DEPTH_BUFFER_BIT : 0;
mask |= stencil ? GL_STENCIL_BUFFER_BIT : 0;
glClear(mask);
ASSERT(CheckGLError());
}
void Graphics::SetCull(bool enable)
{
if (enable)
glEnable(GL_CULL_FACE);
else
glDisable(GL_CULL_FACE);
ASSERT(CheckGLError());
}
void Graphics::SetCullFace(CullFace face)
{
switch (face)
{
case CullFace::FRONT: glCullFace(GL_FRONT); break;
case CullFace::BACK: glCullFace(GL_BACK); break;
case CullFace::BOTH: glCullFace(GL_FRONT_AND_BACK); break;
}
ASSERT(CheckGLError());
}
void Graphics::SetFaceWinding(bool ccw)
{
if (ccw)
glFrontFace(GL_CCW);
else
glFrontFace(GL_CW);
ASSERT(CheckGLError());
}
void Graphics::SetBlend(bool enable)
{
if (enable)
glEnable(GL_BLEND);
else
glDisable(GL_BLEND);
ASSERT(CheckGLError());
}
void Graphics::SetBlendFunc(BlendFunc func)
{
switch (func)
{
case BlendFunc::ADD: glBlendFunc(GL_ONE, GL_ONE); break;
case BlendFunc::MULTIPLY: glBlendFunc(GL_DST_COLOR, GL_ZERO); break;
case BlendFunc::INTERPOLATE: glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); break;
}
ASSERT(CheckGLError());
}
void Graphics::SetDepthTest(bool enable)
{
if (enable)
glEnable(GL_DEPTH_TEST);
else
glDisable(GL_DEPTH_TEST);
ASSERT(CheckGLError());
}
void Graphics::SetDepthWrite(bool enable)
{
glDepthMask(enable);
ASSERT(CheckGLError());
}
void Graphics::SetDepthFunc(DepthFunc func)
{
switch (func)
{
case DepthFunc::NEVER: glDepthFunc(GL_NEVER); break;
case DepthFunc::LESS: glDepthFunc(GL_LESS); break;
case DepthFunc::EQUAL: glDepthFunc(GL_EQUAL); break;
case DepthFunc::LEQUAL: glDepthFunc(GL_LEQUAL); break;
case DepthFunc::GREATER: glDepthFunc(GL_GREATER); break;
case DepthFunc::NOTEQUAL: glDepthFunc(GL_NOTEQUAL); break;
case DepthFunc::GEQUAL: glDepthFunc(GL_GEQUAL); break;
case DepthFunc::ALWAYS: glDepthFunc(GL_ALWAYS); break;
}
ASSERT(CheckGLError());
}
void Graphics::SetSmoothing(bool enable)
{
if (enable)
{
glEnable(GL_LINE_SMOOTH);
glEnable(GL_POLYGON_SMOOTH);
}
else
{
glDisable(GL_LINE_SMOOTH);
glDisable(GL_POLYGON_SMOOTH);
}
ASSERT(CheckGLError());
}
Buffer Graphics::CreateBuffer(int bufferCount, int dataCount, const void* data, bool index, bool dynamic)
{
Buffer buffer;
glGenBuffers(bufferCount, &buffer);
if (index)
{
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, dataCount * sizeof(unsigned int), data, dynamic ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}
else
{
glBindBuffer(GL_ARRAY_BUFFER, buffer);
glBufferData(GL_ARRAY_BUFFER, dataCount * sizeof(float), data, dynamic ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
ASSERT(CheckGLError());
return buffer;
}
void Graphics::DeleteBuffer(int count, Buffer buffer)
{
ASSERT(buffer != 0);
glDeleteBuffers(count, &buffer);
buffer = 0;
ASSERT(CheckGLError());
}
void Graphics::UpdateBuffer(Buffer buffer, int count, const void* data, bool index)
{
ASSERT(buffer != 0);
// TODO
ASSERT(CheckGLError());
}
void Graphics::BindBuffer(Buffer buffer, bool index)
{
ASSERT(buffer != 0);
if (index)
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer);
else
glBindBuffer(GL_ARRAY_BUFFER, buffer);
ASSERT(CheckGLError());
}
void Graphics::DetachBuffer()
{
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
ASSERT(CheckGLError());
}
Shader Graphics::CreateShader(const char* vSrc, const char* pSrc, const char* gSrc)
{
ASSERT(vSrc != nullptr);
ASSERT(pSrc != nullptr);
Shader vShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vShader, 1, &vSrc, NULL);
glCompileShader(vShader);
ASSERT(CheckShaderStatus(vShader, false));
Shader pShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(pShader, 1, &pSrc, NULL);
glCompileShader(pShader);
ASSERT(CheckShaderStatus(pShader, false));
Shader program = glCreateProgram();
glAttachShader(program, vShader);
glAttachShader(program, pShader);
glLinkProgram(program);
ASSERT(CheckShaderStatus(program, true));
glDeleteShader(vShader);
glDeleteShader(pShader);
ASSERT(CheckGLError());
return program;
}
void Graphics::DeleteShader(Shader shader)
{
ASSERT(shader != 0);
glDeleteShader(shader);
ASSERT(CheckGLError());
}
void Graphics::BindShader(Shader shader, const std::vector<AttributeFormat>& attributeFormat)
{
ASSERT(shader != 0);
glUseProgram(shader);
int stride = 0;
for (int i = 0; i < attributeFormat.size(); ++i)
stride += attributeFormat[i].format;
stride *= sizeof(float);
int offset = 0;
for (int i = 0; i < attributeFormat.size(); ++i)
{
int loc = glGetAttribLocation(shader, attributeFormat[i].attribute.c_str());
if (loc != -1)
{
glEnableVertexAttribArray(loc);
glVertexAttribPointer(loc, attributeFormat[i].format, GL_FLOAT, GL_FALSE, stride, (void*)(sizeof(float) * offset));
}
offset += attributeFormat[i].format;
}
ASSERT(CheckGLError());
}
void Graphics::DetachShader()
{
glUseProgram(0);
ASSERT(CheckGLError());
}
void Graphics::SetUniform(Shader shader, const char* name, int count, int* i)
{
ASSERT(shader != 0);
glUniform1iv(glGetUniformLocation(shader, name), count, i);
ASSERT(CheckGLError());
}
void Graphics::SetUniform(Shader shader, const char* name, int count, float* f)
{
ASSERT(shader != 0);
glUniform1fv(glGetUniformLocation(shader, name), count, f);
ASSERT(CheckGLError());
}
void Graphics::SetUniform(Shader shader, const char* name, int count, glm::vec2* v2)
{
ASSERT(shader != 0);
glUniform2fv(glGetUniformLocation(shader, name), count, glm::value_ptr(v2[0]));
ASSERT(CheckGLError());
}
void Graphics::SetUniform(Shader shader, const char* name, int count, glm::vec3* v3)
{
ASSERT(shader != 0);
glUniform3fv(glGetUniformLocation(shader, name), count, glm::value_ptr(v3[0]));
ASSERT(CheckGLError());
}
void Graphics::SetUniform(Shader shader, const char* name, int count, glm::vec4* v4)
{
ASSERT(shader != 0);
glUniform4fv(glGetUniformLocation(shader, name), count, glm::value_ptr(v4[0]));
ASSERT(CheckGLError());
}
void Graphics::SetUniform(Shader shader, const char* name, int count, glm::mat2* m2)
{
ASSERT(shader != 0);
glUniformMatrix2fv(glGetUniformLocation(shader, name), count, GL_FALSE, glm::value_ptr(m2[0]));
ASSERT(CheckGLError());
}
void Graphics::SetUniform(Shader shader, const char* name, int count, glm::mat3* m3)
{
ASSERT(shader != 0);
glUniformMatrix3fv(glGetUniformLocation(shader, name), count, GL_FALSE, glm::value_ptr(m3[0]));
ASSERT(CheckGLError());
}
void Graphics::SetUniform(Shader shader, const char* name, int count, glm::mat4* m4)
{
ASSERT(shader != 0);
glUniformMatrix4fv(glGetUniformLocation(shader, name), count, GL_FALSE, glm::value_ptr(m4[0]));
ASSERT(CheckGLError());
}
void Graphics::DrawVertices(Primitive primitive, int offset, int count)
{
switch (primitive)
{
case Primitive::POINTS: glDrawArrays(GL_POINTS, offset, count); break;
case Primitive::LINES: glDrawArrays(GL_LINES, offset, count); break;
case Primitive::TRIANGLES: glDrawArrays(GL_TRIANGLES, offset, count); break;
}
ASSERT(CheckGLError());
}
void Graphics::DrawIndexed(Primitive primitive, int count)
{
switch (primitive)
{
case Primitive::POINTS: glDrawElements(GL_POINTS, count, GL_UNSIGNED_INT, 0); break;
case Primitive::LINES: glDrawElements(GL_LINES, count, GL_UNSIGNED_INT, 0); break;
case Primitive::TRIANGLES: glDrawElements(GL_TRIANGLES, count, GL_UNSIGNED_INT, 0); break;
}
ASSERT(CheckGLError());
}
Texture Graphics::CreateTexture(TextureFormat format, int count, int width, int height, const void* data, bool mipmap)
{
Texture texture;
glGenTextures(count, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
switch (format)
{
case TextureFormat::RBG24: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); break;
case TextureFormat::RBGA32: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); break;
}
if (mipmap) glGenerateMipmap(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, 0);
return texture;
ASSERT(CheckGLError());
}
void Graphics::DeleteTexture(int count, Texture texture)
{
ASSERT(texture != 0);
glDeleteTextures(count, &texture);
texture = 0;
ASSERT(CheckGLError());
}
void Graphics::FilterTexture(Texture texture, TextureWrap s, TextureWrap t, TextureFilter min, TextureFilter mag)
{
ASSERT(texture != 0);
glBindTexture(GL_TEXTURE_2D, texture);
switch (s)
{
case TextureWrap::REPEAT: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); break;
case TextureWrap::MIRROR: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT); break;
case TextureWrap::EDGE_CLAMP: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); break;
case TextureWrap::BORDER_CLAMP: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); break;
}
switch (t)
{
case TextureWrap::REPEAT: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); break;
case TextureWrap::MIRROR: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT); break;
case TextureWrap::EDGE_CLAMP: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); break;
case TextureWrap::BORDER_CLAMP: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); break;
}
switch (min)
{
case TextureFilter::NEAREST: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); break;
case TextureFilter::LINEAR: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); break;
case TextureFilter::NEAREST_NEAREST: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST); break;
case TextureFilter::NEAREST_LINEAR: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR); break;
case TextureFilter::LINEAR_NEAREST: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST); break;
case TextureFilter::LINEAR_LINEAR: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); break;
}
switch (mag)
{
case TextureFilter::NEAREST: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); break;
case TextureFilter::LINEAR: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); break;
}
glBindTexture(GL_TEXTURE_2D, 0);
ASSERT(CheckGLError());
}
void Graphics::BindTexture(Texture texture, int loc)
{
ASSERT(texture != 0);
glBindTexture(GL_TEXTURE_2D, texture);
glActiveTexture(GL_TEXTURE0 + loc);
ASSERT(CheckGLError());
}
void Graphics::DetachTexture()
{
glBindTexture(GL_TEXTURE_2D, 0);
ASSERT(CheckGLError());
}
| 26.984032
| 130
| 0.691767
|
Belfer
|
a08f5e9809d1100e7ef695a0a60945e07fd795bd
| 2,157
|
cpp
|
C++
|
jlp_gsegraf_june2017/jlp_Gsegraf.cpp
|
jlprieur/jlplib
|
6073d7a7eb76d916662b1f8a4eb54f345cf7c772
|
[
"MIT"
] | null | null | null |
jlp_gsegraf_june2017/jlp_Gsegraf.cpp
|
jlprieur/jlplib
|
6073d7a7eb76d916662b1f8a4eb54f345cf7c772
|
[
"MIT"
] | null | null | null |
jlp_gsegraf_june2017/jlp_Gsegraf.cpp
|
jlprieur/jlplib
|
6073d7a7eb76d916662b1f8a4eb54f345cf7c772
|
[
"MIT"
] | 1
|
2020-07-09T00:20:49.000Z
|
2020-07-09T00:20:49.000Z
|
/*****************************************************************************
* jlp_gsegraf.cpp
* JLP_Gsegraf class
*
* JLP
* Version 14/12/2016
*****************************************************************************/
#include "jlp_gsegraf.h" // JLP_Gsegraf
/****************************************************************************
* Constructors:
*****************************************************************************/
JLP_Gsegraf::JLP_Gsegraf(JLP_Gseg *jlp_gseg0,
char *parameter_file_0, char **save_filename_0,
int *close_flag_0)
{
char font_name0[64];
double font_size_date_time0, font_size_legend0, font_size_text0;
double font_size_tick_labels0, font_size_axis_labels0, font_size_title0;
strcpy(font_name0, "Sans");
// For safety:
jlp_gseg1 = NULL;
GSEG_InitializePlot(jlp_gseg0, parameter_file_0, save_filename_0, close_flag_0,
font_name0, &font_size_date_time0,
&font_size_legend0, &font_size_text0,
&font_size_tick_labels0, &font_size_axis_labels0,
&font_size_title0);
}
/****************************************************************************
* Constructor:
*****************************************************************************/
JLP_Gsegraf::JLP_Gsegraf(JLP_Gseg *jlp_gseg0,
char *parameter_file_0, char **save_filename_0,
int *close_flag_0, char *font_name0,
double *font_size_date_time0,
double *font_size_legend0,
double *font_size_text0,
double *font_size_tick_labels0,
double *font_size_axis_labels0,
double *font_size_title0)
{
// For safety:
jlp_gseg1 = NULL;
GSEG_InitializePlot(jlp_gseg0, parameter_file_0, save_filename_0, close_flag_0,
font_name0, font_size_date_time0,
font_size_legend0, font_size_text0,
font_size_tick_labels0, font_size_axis_labels0,
font_size_title0);
}
| 39.944444
| 80
| 0.481688
|
jlprieur
|
a0911081b67ccc9a9b81ca5d615c2d2706505d6d
| 380
|
cpp
|
C++
|
pg_answer/0c597d3b24c3432fba616e6cd7a05b3e.cpp
|
Guyutongxue/Introduction_to_Computation
|
062f688fe3ffb8e29cfaf139223e4994edbf64d6
|
[
"WTFPL"
] | 8
|
2019-10-09T14:33:42.000Z
|
2020-12-03T00:49:29.000Z
|
pg_answer/0c597d3b24c3432fba616e6cd7a05b3e.cpp
|
Guyutongxue/Introduction_to_Computation
|
062f688fe3ffb8e29cfaf139223e4994edbf64d6
|
[
"WTFPL"
] | null | null | null |
pg_answer/0c597d3b24c3432fba616e6cd7a05b3e.cpp
|
Guyutongxue/Introduction_to_Computation
|
062f688fe3ffb8e29cfaf139223e4994edbf64d6
|
[
"WTFPL"
] | null | null | null |
#include <iostream>
void moveDisk(int n, char src, char dest, char trans) {
if (n == 1) {
std::cout << src << "->" << dest << std::endl;
return;
}
moveDisk(n - 1, src, trans, dest);
std::cout << src << "->" << dest << std::endl;
moveDisk(n - 1, trans, dest, src);
}
int main() {
int n;
std::cin >> n;
moveDisk(n, 'A', 'C', 'B');
}
| 22.352941
| 55
| 0.476316
|
Guyutongxue
|
a091eb9f455024b9109bb0e7aa7947136856dbca
| 956
|
hpp
|
C++
|
Enginelib/src/components/textcomponent.hpp
|
kalsipp/vsxpanse
|
7887d234312283ce1ace03bed610642b0c6f96b1
|
[
"MIT"
] | null | null | null |
Enginelib/src/components/textcomponent.hpp
|
kalsipp/vsxpanse
|
7887d234312283ce1ace03bed610642b0c6f96b1
|
[
"MIT"
] | null | null | null |
Enginelib/src/components/textcomponent.hpp
|
kalsipp/vsxpanse
|
7887d234312283ce1ace03bed610642b0c6f96b1
|
[
"MIT"
] | null | null | null |
#pragma once
#include <string>
#include <SDL_ttf.h>
#include <cstdint>
#include "../basics/sprite.hpp"
#include "../basics/vector2d.hpp"
#include "../graphicsmanager.hpp"
#include "../gameobject.hpp"
#include "../filesystem/resourcearchive.hpp"
#include "../basics/helpers.hpp"
class TextComponent : public Component {
public:
TextComponent(GameObject *);
~TextComponent();
void initialize(ResourceFile * file, int size = 16);
void set_font_size(int);
std::string get_text();
void set_text(const std::string &);
void set_color(uint8_t, uint8_t, uint8_t, uint8_t = 0);
void render() final override;
private:
std::string m_text = "";
Sprite m_sprite;
TTF_Font * m_font = nullptr;
ResourceFile * m_font_source;
Vector2D m_scale = {1, 1};
double m_angle = 0;
bool m_centered = false;
SDL_RendererFlip m_flip = SDL_FLIP_NONE;
SDL_Color m_color = {255, 255, 255, 1};
const int default_font_size = 16;
const std::string m_default_font = "";
};
| 28.117647
| 56
| 0.722803
|
kalsipp
|
a09441f579cc07e3807baa174c1655b8583eecf1
| 8,293
|
hpp
|
C++
|
clients/include/testing_getrs_strided_batched.hpp
|
rkamd/hipBLAS
|
db7f14bf1a86cb77dec808721a7b18edc36aa3e5
|
[
"MIT"
] | null | null | null |
clients/include/testing_getrs_strided_batched.hpp
|
rkamd/hipBLAS
|
db7f14bf1a86cb77dec808721a7b18edc36aa3e5
|
[
"MIT"
] | null | null | null |
clients/include/testing_getrs_strided_batched.hpp
|
rkamd/hipBLAS
|
db7f14bf1a86cb77dec808721a7b18edc36aa3e5
|
[
"MIT"
] | null | null | null |
/* ************************************************************************
* Copyright (C) 2016-2022 Advanced Micro Devices, Inc. All rights reserved.
*
* 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 <fstream>
#include <iostream>
#include <stdlib.h>
#include <vector>
#include "testing_common.hpp"
template <typename T>
hipblasStatus_t testing_getrs_strided_batched(const Arguments& argus)
{
using U = real_t<T>;
bool FORTRAN = argus.fortran;
auto hipblasGetrsStridedBatchedFn
= FORTRAN ? hipblasGetrsStridedBatched<T, true> : hipblasGetrsStridedBatched<T, false>;
int N = argus.N;
int lda = argus.lda;
int ldb = argus.ldb;
int batch_count = argus.batch_count;
double stride_scale = argus.stride_scale;
hipblasStride strideA = size_t(lda) * N * stride_scale;
hipblasStride strideB = size_t(ldb) * 1 * stride_scale;
hipblasStride strideP = size_t(N) * stride_scale;
size_t A_size = strideA * batch_count;
size_t B_size = strideB * batch_count;
size_t Ipiv_size = strideP * batch_count;
// Check to prevent memory allocation error
if(N < 0 || lda < N || ldb < N || batch_count < 0)
{
return HIPBLAS_STATUS_INVALID_VALUE;
}
if(batch_count == 0)
{
return HIPBLAS_STATUS_SUCCESS;
}
// Naming: dK is in GPU (device) memory. hK is in CPU (host) memory
host_vector<T> hA(A_size);
host_vector<T> hX(B_size);
host_vector<T> hB(B_size);
host_vector<T> hB1(B_size);
host_vector<int> hIpiv(Ipiv_size);
host_vector<int> hIpiv1(Ipiv_size);
int info;
device_vector<T> dA(A_size);
device_vector<T> dB(B_size);
device_vector<int> dIpiv(Ipiv_size);
double gpu_time_used, hipblas_error;
hipblasLocalHandle handle(argus);
// Initial hA, hB, hX on CPU
srand(1);
hipblasOperation_t op = HIPBLAS_OP_N;
for(int b = 0; b < batch_count; b++)
{
T* hAb = hA.data() + b * strideA;
T* hXb = hX.data() + b * strideB;
T* hBb = hB.data() + b * strideB;
int* hIpivb = hIpiv.data() + b * strideP;
hipblas_init<T>(hAb, N, N, lda);
hipblas_init<T>(hXb, N, 1, ldb);
// scale A to avoid singularities
for(int i = 0; i < N; i++)
{
for(int j = 0; j < N; j++)
{
if(i == j)
hAb[i + j * lda] += 400;
else
hAb[i + j * lda] -= 4;
}
}
// Calculate hB = hA*hX;
cblas_gemm<T>(op, op, N, 1, N, (T)1, hAb, lda, hXb, ldb, (T)0, hBb, ldb);
// LU factorize hA on the CPU
info = cblas_getrf<T>(N, N, hAb, lda, hIpivb);
if(info != 0)
{
std::cerr << "LU decomposition failed" << std::endl;
return HIPBLAS_STATUS_INTERNAL_ERROR;
}
}
// Copy data from CPU to device
CHECK_HIP_ERROR(hipMemcpy(dA, hA, A_size * sizeof(T), hipMemcpyHostToDevice));
CHECK_HIP_ERROR(hipMemcpy(dB, hB, B_size * sizeof(T), hipMemcpyHostToDevice));
CHECK_HIP_ERROR(hipMemcpy(dIpiv, hIpiv, Ipiv_size * sizeof(int), hipMemcpyHostToDevice));
if(argus.unit_check || argus.norm_check)
{
/* =====================================================================
HIPBLAS
=================================================================== */
CHECK_HIPBLAS_ERROR(hipblasGetrsStridedBatchedFn(handle,
op,
N,
1,
dA,
lda,
strideA,
dIpiv,
strideP,
dB,
ldb,
strideB,
&info,
batch_count));
// copy output from device to CPU
CHECK_HIP_ERROR(hipMemcpy(hB1.data(), dB, B_size * sizeof(T), hipMemcpyDeviceToHost));
CHECK_HIP_ERROR(
hipMemcpy(hIpiv1.data(), dIpiv, Ipiv_size * sizeof(int), hipMemcpyDeviceToHost));
/* =====================================================================
CPU LAPACK
=================================================================== */
for(int b = 0; b < batch_count; b++)
{
cblas_getrs('N',
N,
1,
hA.data() + b * strideA,
lda,
hIpiv.data() + b * strideP,
hB.data() + b * strideB,
ldb);
}
hipblas_error = norm_check_general<T>('F', N, 1, ldb, strideB, hB, hB1, batch_count);
if(argus.unit_check)
{
U eps = std::numeric_limits<U>::epsilon();
double tolerance = N * eps * 100;
unit_check_error(hipblas_error, tolerance);
}
}
if(argus.timing)
{
hipStream_t stream;
CHECK_HIPBLAS_ERROR(hipblasGetStream(handle, &stream));
int runs = argus.cold_iters + argus.iters;
for(int iter = 0; iter < runs; iter++)
{
if(iter == argus.cold_iters)
gpu_time_used = get_time_us_sync(stream);
CHECK_HIPBLAS_ERROR(hipblasGetrsStridedBatchedFn(handle,
op,
N,
1,
dA,
lda,
strideA,
dIpiv,
strideP,
dB,
ldb,
strideB,
&info,
batch_count));
}
gpu_time_used = get_time_us_sync(stream) - gpu_time_used;
ArgumentModel<e_N, e_lda, e_stride_a, e_ldb, e_stride_b, e_batch_count>{}.log_args<T>(
std::cout,
argus,
gpu_time_used,
getrs_gflop_count<T>(N, 1),
ArgumentLogging::NA_value,
hipblas_error);
}
return HIPBLAS_STATUS_SUCCESS;
}
| 39.679426
| 95
| 0.450983
|
rkamd
|
90b587d331f36cf5ea2001c22923f69679ca578a
| 1,724
|
hpp
|
C++
|
src/backend/cpp/reach-tube.hpp
|
C2E2-Development-Team/C2E2-Tool
|
36631bfd75c0c0fb56389f13a9aba68cbed1680f
|
[
"MIT"
] | 1
|
2021-10-04T19:56:25.000Z
|
2021-10-04T19:56:25.000Z
|
src/backend/cpp/reach-tube.hpp
|
C2E2-Development-Team/C2E2-Tool
|
36631bfd75c0c0fb56389f13a9aba68cbed1680f
|
[
"MIT"
] | null | null | null |
src/backend/cpp/reach-tube.hpp
|
C2E2-Development-Team/C2E2-Tool
|
36631bfd75c0c0fb56389f13a9aba68cbed1680f
|
[
"MIT"
] | null | null | null |
/**
* \file reach-tube.hpp
* \class ReachTube
*
* \author parasara
* \author Lucas Brown
* \date July, 2014
* \date April 2, 2019
*
* \brief LMBTODO
*/
#ifndef REACHTUBE_H_
#define REACHTUBE_H_
#include <ppl.hh>
#include <stack>
#include <string>
#include <vector>
#include "annotation.hpp"
#include "point.hpp"
#include "rep-point.hpp"
class ReachTube
{
public:
ReachTube();
~ReachTube();
int getSize();
Point getUpperBound(int index);
Point getLowerBound(int index);
void parseInvariantTube(char const* filename, int hasMode);
void printReachTube(const std::string, int flag);
void clear(int from);
ReachTube bloatReachTube(std::vector<double> delta_array, Annotation annotation);
int getNextSetStack(std::stack<RepPoint>& itr_stack, RepPoint parent_rep_point);
void addGuards(std::vector<std::pair<std::NNC_Polyhedron, int> > guards);
double getMinCoordinate(int dim, int cur_mode);
double getMaxCoordinate(int dim, int cur_mode);
int checkIntersection(int cur_mode, Point cur_point,
std::vector<double> delta_array);
double getMinTime(int cur_mode, Point cur_point,
std::vector<double> delta_array);
int getDimensions();
void setDimensions(int val);
int getMode();
void setMode(int val); // Setting mode also sets the isReachTube bool
std::vector<int> getModeVec();
void setModeVec(std::vector<int> vec);
void addLowerBoundState(Point obj);
void addUpperBoundState(Point obj);
private:
int dimensions;
int isReachTube;
int reachTubeMode;
std::vector<int> color;
std::vector<int> mode;
std::vector<Point> upper_bound;
std::vector<Point> lower_bound;
};
#endif /* REACHTUBE_H_ */
| 24.628571
| 85
| 0.703016
|
C2E2-Development-Team
|
90b5ba3d3a99e64f0e3290bf7b22b5b06652c50b
| 10,615
|
cpp
|
C++
|
src/l_CollisionComponent.cpp
|
benzap/Kampf
|
9cf4fb0d6ec22bc35ade9b476d29df34902c6689
|
[
"Zlib"
] | 2
|
2018-05-13T05:27:29.000Z
|
2018-05-29T06:35:57.000Z
|
src/l_CollisionComponent.cpp
|
benzap/Kampf
|
9cf4fb0d6ec22bc35ade9b476d29df34902c6689
|
[
"Zlib"
] | null | null | null |
src/l_CollisionComponent.cpp
|
benzap/Kampf
|
9cf4fb0d6ec22bc35ade9b476d29df34902c6689
|
[
"Zlib"
] | null | null | null |
#include "l_CollisionComponent.hpp"
CollisionComponent* lua_pushcollisionComponent(
lua_State *L,
CollisionComponent* collisioncomponent = nullptr) {
if (collisioncomponent == nullptr) {
std::cerr << "Warning: CollisionComponent - this will not work, nullptr" << std::endl;
collisioncomponent = new CollisionComponent("");
}
CollisionComponent** collisioncomponentPtr = static_cast<CollisionComponent**>
(lua_newuserdata(L, sizeof(CollisionComponent*)));
//storing the address directly. Lua can be seen as a window,
//looking in at the engine. This could be a good source for a lot
//of problems.
*collisioncomponentPtr = collisioncomponent;
luaL_getmetatable(L, LUA_USERDATA_COLLISIONCOMPONENT);
lua_setmetatable(L, -2);
return collisioncomponent;
}
CollisionComponent* lua_tocollisionComponent(lua_State *L, int index) {
CollisionComponent* collisioncomponent = *static_cast<CollisionComponent**>
(luaL_checkudata(L, index, LUA_USERDATA_COLLISIONCOMPONENT));
if (collisioncomponent == NULL) {
luaL_error(L, "Provided userdata is not of type 'CollisionComponent'");
}
return collisioncomponent;
}
boolType lua_iscollisionComponent(lua_State* L, int index) {
if (lua_isuserdata(L, index)) {
auto chk = lua_isUserdataType(L, index, LUA_USERDATA_COLLISIONCOMPONENT);
return chk;
}
return false;
}
static int l_CollisionComponent_CollisionComponent(lua_State *L) {
stringType componentName = luaL_checkstring(L, 1);
boolType isParent = lua_toboolean(L, 2);
auto component = new CollisionComponent(
componentName,
!isParent);
lua_pushcollisionComponent(L, component);
return 1;
}
static int l_CollisionComponent_isCollisionComponent(lua_State *L) {
if (lua_iscollisionComponent(L, 1)) {
lua_pushboolean(L, 1);
}
else {
lua_pushboolean(L, 0);
}
return 1;
}
static const struct luaL_Reg l_CollisionComponent_Registry [] = {
{"CollisionComponent", l_CollisionComponent_CollisionComponent},
{"isCollisionComponent", l_CollisionComponent_isCollisionComponent},
{NULL, NULL}
};
static int l_CollisionComponent_gc(lua_State *L) {
return 0;
}
static int l_CollisionComponent_tostring(lua_State *L) {
auto component = lua_tocomponent(L, 1);
stringType msg = "Component:COLLISION:";
msg += component->getName();
lua_pushstring(L, msg.c_str());
return 1;
}
static int l_CollisionComponent_getFamily(lua_State *L) {
lua_pushstring(L, "COLLISION");
return 1;
}
static int l_CollisionComponent_createChild(lua_State *L) {
auto component = lua_tocomponent(L, 1);
stringType childComponentName = luaL_checkstring(L, 2);
auto childComponent = component->createChild(childComponentName);
CollisionComponent* childComponent_cast = static_cast<CollisionComponent*>
(childComponent);
lua_pushcollisionComponent(L, childComponent_cast);
return 1;
}
static int l_CollisionComponent_setPhysicsRelation(lua_State *L) {
auto component = lua_tocomponent(L, 1);
auto collisionComponent = static_cast<CollisionComponent*>
(component);
//get the physics component
auto p_component = lua_tocomponent(L, 2);
auto physicsComponent = static_cast<PhysicsComponent*>
(p_component);
collisionComponent->setPhysicsRelation(physicsComponent);
return 0;
}
static int l_CollisionComponent_getPhysicsRelation(lua_State *L) {
auto component = lua_tocomponent(L, 1);
auto collisionComponent = static_cast<CollisionComponent*>
(component);
auto p_component = collisionComponent->getPhysicsRelation();
if (p_component != nullptr) {
lua_pushphysicsComponent(L, p_component);
}
else {
lua_pushnil(L);
}
return 1;
}
static int l_CollisionComponent_setOffset(lua_State *L) {
auto component = lua_tocomponent(L, 1);
auto collisionComponent = static_cast<CollisionComponent*>
(component);
auto vector = lua_tovector(L, 2);
collisionComponent->setOffset(*vector);
return 0;
}
static int l_CollisionComponent_getOffset(lua_State *L) {
auto component = lua_tocomponent(L, 1);
auto collisionComponent = static_cast<CollisionComponent*>
(component);
auto vector = collisionComponent->getOffset();
lua_pushvector(L, new Vector3(vector));
return 1;
}
static int l_CollisionComponent_setOrigin(lua_State *L) {
auto component = lua_tocomponent(L, 1);
auto collisionComponent = static_cast<CollisionComponent*>
(component);
auto vector = lua_tovector(L, 2);
collisionComponent->setOrigin(*vector);
return 0;
}
static int l_CollisionComponent_getOrigin(lua_State *L) {
auto component = lua_tocomponent(L, 1);
auto collisionComponent = static_cast<CollisionComponent*>
(component);
auto vector = collisionComponent->getOrigin();
lua_pushvector(L, new Vector3(vector));
return 1;
}
static int l_CollisionComponent_setOrientation(lua_State *L) {
auto component = lua_tocomponent(L, 1);
auto collisionComponent = static_cast<CollisionComponent*>
(component);
auto quat = lua_toquaternion(L, 2);
collisionComponent->setOrientation(*quat);
return 0;
}
static int l_CollisionComponent_getOrientation(lua_State *L) {
auto component = lua_tocomponent(L, 1);
auto collisionComponent = static_cast<CollisionComponent*>
(component);
auto quat = collisionComponent->getOrientation();
lua_pushquaternion(L, new Quaternion(quat));
return 1;
}
static int l_CollisionComponent_setType(lua_State *L) {
auto component = lua_tocomponent(L, 1);
auto collisionComponent = static_cast<CollisionComponent*>
(component);
stringType typeString = luaL_checkstring(L, 2);
collisionComponent->setCollisionTypeString(typeString);
return 0;
}
static int l_CollisionComponent_getType(lua_State *L) {
auto component = lua_tocomponent(L, 1);
auto collisionComponent = static_cast<CollisionComponent*>
(component);\
auto typeString = collisionComponent->getCollisionTypeString();
lua_pushstring(L, typeString.c_str());
return 1;
}
static int l_CollisionComponent_setRadius(lua_State *L) {
auto component = lua_tocomponent(L, 1);
auto collisionComponent = static_cast<CollisionComponent*>
(component);
floatType floatValue = luaL_checknumber(L, 2);
collisionComponent->setRadius(floatValue);
return 0;
}
static int l_CollisionComponent_getRadius(lua_State *L) {
auto component = lua_tocomponent(L, 1);
auto collisionComponent = static_cast<CollisionComponent*>
(component);
floatType floatValue = collisionComponent->getRadius();
lua_pushnumber(L, floatValue);
return 1;
}
static int l_CollisionComponent_setWidth(lua_State *L) {
auto component = lua_tocomponent(L, 1);
auto collisionComponent = static_cast<CollisionComponent*>
(component);
floatType floatValue = luaL_checknumber(L, 2);
collisionComponent->setWidth(floatValue);
return 0;
}
static int l_CollisionComponent_getWidth(lua_State *L) {
auto component = lua_tocomponent(L, 1);
auto collisionComponent = static_cast<CollisionComponent*>
(component);
floatType floatValue = collisionComponent->getWidth();
lua_pushnumber(L, floatValue);
return 1;
}
static int l_CollisionComponent_setHeight(lua_State *L) {
auto component = lua_tocomponent(L, 1);
auto collisionComponent = static_cast<CollisionComponent*>
(component);
floatType floatValue = luaL_checknumber(L, 2);
collisionComponent->setHeight(floatValue);
return 0;
}
static int l_CollisionComponent_getHeight(lua_State *L) {
auto component = lua_tocomponent(L, 1);
auto collisionComponent = static_cast<CollisionComponent*>
(component);
floatType floatValue = collisionComponent->getHeight();
lua_pushnumber(L, floatValue);
return 1;
}
static int l_CollisionComponent_setVectorList(lua_State *L) {
auto component = lua_tocomponent(L, 1);
auto collisionComponent = static_cast<CollisionComponent*>
(component);
if (!lua_istable(L, 2)) {
luaL_error(L, "2nd argument must be a table of kf.Vector3's");
}
integerType tableLength = lua_objlen(L, 2);
std::vector<Vector3> vectorList;
for (int i = 0; i < tableLength; i++) {
lua_rawgeti(L, 2, i+1);
auto vector = lua_tovector(L, -1);
vectorList.push_back(*vector);
}
collisionComponent->setVectorList(vectorList);
return 0;
}
static int l_CollisionComponent_getVectorList(lua_State *L) {
auto component = lua_tocomponent(L, 1);
auto collisionComponent = static_cast<CollisionComponent*>
(component);
auto vectorList = collisionComponent->getVectorList();
lua_createtable(L, vectorList.size(), 0);
for(int i = 0; i < vectorList.size(); i++) {
auto vector = new Vector3(vectorList[i]);
lua_pushvector(L, vector);
lua_rawseti(L, -2, i+1);
}
return 1;
}
static const struct luaL_Reg l_CollisionComponent [] = {
{"__gc", l_CollisionComponent_gc},
{"__tostring", l_CollisionComponent_tostring},
{"getFamily", l_CollisionComponent_getFamily},
{"createChild", l_CollisionComponent_createChild},
{"setPhysicsRelation", l_CollisionComponent_setPhysicsRelation},
{"getPhysicsRelation", l_CollisionComponent_getPhysicsRelation},
{"setOffset", l_CollisionComponent_setOffset},
{"getOffset", l_CollisionComponent_getOffset},
{"setOrigin", l_CollisionComponent_setOrigin},
{"getOrigin", l_CollisionComponent_getOrigin},
{"setOrientation", l_CollisionComponent_setOrientation},
{"getOrientation", l_CollisionComponent_getOrientation},
{"setType", l_CollisionComponent_setType},
{"getType", l_CollisionComponent_getType},
{"setRadius", l_CollisionComponent_setRadius},
{"getRadius", l_CollisionComponent_getRadius},
{"setWidth", l_CollisionComponent_setWidth},
{"getWidth", l_CollisionComponent_getWidth},
{"setHeight", l_CollisionComponent_setHeight},
{"getHeight", l_CollisionComponent_getHeight},
{"setVectorList", l_CollisionComponent_setVectorList},
{"getVectorList", l_CollisionComponent_getVectorList},
{NULL, NULL}
};
int luaopen_collisionComponent(lua_State *L) {
//CollisionComponent
luaL_newmetatable(L, LUA_USERDATA_COLLISIONCOMPONENT);
lua_pushvalue(L, -1);
luaL_getmetatable(L, LUA_USERDATA_ABSTRACTCOMPONENT);
lua_setmetatable(L, -2);
lua_setfield(L, -2, "__index");
luaL_register(L, NULL, l_CollisionComponent);
lua_pop(L, 1);
luaL_register(L, KF_LUA_LIBNAME, l_CollisionComponent_Registry);
return 1;
}
| 32.166667
| 87
| 0.735751
|
benzap
|
90b7c22a322dade4043e073f3e786f5ff495fb1f
| 872
|
cpp
|
C++
|
app/Helper/GridHelper.cpp
|
LNAV/Sudoku_Solver_Cpp
|
431a5d0e370d3d5f7da33674601f3a57efd7032a
|
[
"Apache-2.0"
] | 1
|
2020-05-17T11:46:46.000Z
|
2020-05-17T11:46:46.000Z
|
app/Helper/GridHelper.cpp
|
LNAV/VeronixApp-Sudoku_Solver
|
431a5d0e370d3d5f7da33674601f3a57efd7032a
|
[
"Apache-2.0"
] | null | null | null |
app/Helper/GridHelper.cpp
|
LNAV/VeronixApp-Sudoku_Solver
|
431a5d0e370d3d5f7da33674601f3a57efd7032a
|
[
"Apache-2.0"
] | null | null | null |
/*
* GridHelper.cpp
*
* Created on: Jan 1, 2020
* Author: LavishK1
*/
#include "GridHelper.h"
namespace Veronix
{
namespace App
{
namespace helper
{
GridHelper::GridHelper()
{
}
GridHelper::~GridHelper()
{
}
bool GridHelper::findNewClue(sudosolver::container::GridContainer &grid)
{
//TODO
findNewClueInTable(grid.getRowContainer());
findNewClueInTable(grid.getColContainer());
findNewClueInTable(grid.getBoxContainer());
return true;
}
bool GridHelper::findNewClueInTable(sudosolver::container::TableContainer &table)
{
//TODO
for (int index = constants::valueZero; index < constants::squareSize; ++index)
findNewClueInTableRow(table[index]);
return true;
}
bool GridHelper::findNewClueInTableRow(sudosolver::container::TableRow &tableRow)
{
//TODO
return true;
}
} /* namespace helper */
} /* namespace App */
} /* namespace Veronix */
| 16.148148
| 81
| 0.723624
|
LNAV
|
90ba6086e7b70f03afbf53793d07c1e63289a1dd
| 6,351
|
cc
|
C++
|
src/rdf++/writer/nquads.cc
|
datagraph/librdf
|
6697c6a2bfeb00978118968ea88eabb1612c892c
|
[
"Unlicense"
] | 10
|
2015-12-23T05:17:49.000Z
|
2020-06-16T14:21:34.000Z
|
src/rdf++/writer/nquads.cc
|
datagraph/librdf
|
6697c6a2bfeb00978118968ea88eabb1612c892c
|
[
"Unlicense"
] | 3
|
2015-06-15T14:15:33.000Z
|
2016-01-17T19:18:09.000Z
|
src/rdf++/writer/nquads.cc
|
datagraph/librdf
|
6697c6a2bfeb00978118968ea88eabb1612c892c
|
[
"Unlicense"
] | 3
|
2015-02-14T23:16:01.000Z
|
2018-03-03T15:07:48.000Z
|
/* This is free and unencumbered software released into the public domain. */
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "nquads.h"
#include "../format.h"
#include "../quad.h"
#include "../term.h"
#include "../triple.h"
#include <cassert> /* for assert() */
#include <cstdio> /* for FILE, std::f*() */
#include <cstring> /* for std::strcmp() */
////////////////////////////////////////////////////////////////////////////////
namespace {
class implementation final : public rdf::writer::implementation {
FILE* _stream {nullptr};
bool _ntriples{false};
public:
implementation(FILE* stream,
const char* content_type,
const char* charset,
const char* base_uri);
virtual ~implementation() noexcept override;
virtual void configure(const char* key, const char* value) override;
virtual void begin() override;
virtual void finish() override;
virtual void write_triple(const rdf::triple& triple) override;
virtual void write_quad(const rdf::quad& quad) override;
virtual void write_comment(const char* comment) override;
virtual void flush() override;
protected:
void write_term(const rdf::term& term);
void write_escaped_iriref(const char* string);
void write_escaped_string(const char* string);
};
}
////////////////////////////////////////////////////////////////////////////////
rdf::writer::implementation*
rdf_writer_for_nquads(FILE* const stream,
const char* const content_type,
const char* const charset,
const char* const base_uri) {
return new implementation(stream, content_type, charset, base_uri);
}
////////////////////////////////////////////////////////////////////////////////
implementation::implementation(FILE* const stream,
const char* const content_type,
const char* const /*charset*/,
const char* const /*base_uri*/)
: _stream{stream} {
assert(stream != nullptr);
const rdf::format* const format = rdf::format::find_for_content_type(content_type);
assert(format);
if (std::strcmp(format->serializer_name, "ntriples") == 0) {
_ntriples = true;
}
}
implementation::~implementation() noexcept {}
////////////////////////////////////////////////////////////////////////////////
void
implementation::configure(const char* const /*key*/,
const char* const /*value*/) {
/* no configuration parameters supported at present */
}
void
implementation::begin() {}
void
implementation::finish() {}
void
implementation::write_triple(const rdf::triple& triple) {
assert(triple.subject);
write_term(*triple.subject);
std::fputc(' ', _stream);
assert(triple.predicate);
write_term(*triple.predicate);
std::fputc(' ', _stream);
assert(triple.object);
write_term(*triple.object);
std::fputc(' ', _stream);
std::fputs(".\n", _stream);
}
void
implementation::write_quad(const rdf::quad& quad) {
assert(quad.subject);
write_term(*quad.subject);
std::fputc(' ', _stream);
assert(quad.predicate);
write_term(*quad.predicate);
std::fputc(' ', _stream);
assert(quad.object);
write_term(*quad.object);
std::fputc(' ', _stream);
if (quad.context && !_ntriples) {
write_term(*quad.context);
std::fputc(' ', _stream);
}
std::fputs(".\n", _stream);
}
void
implementation::write_comment(const char* const comment) {
std::fprintf(_stream, "# %s\n", comment); // TODO: handle multi-line comments.
}
void
implementation::flush() {
std::fflush(_stream);
}
void
implementation::write_term(const rdf::term& term_) {
switch (term_.type) {
case rdf::term_type::uri_reference: {
const auto& term = dynamic_cast<const rdf::uri_reference&>(term_);
std::fputc('<', _stream);
write_escaped_iriref(term.string.c_str());
std::fputc('>', _stream);
break;
}
case rdf::term_type::blank_node: {
const auto& term = dynamic_cast<const rdf::blank_node&>(term_);
std::fprintf(_stream, "_:%s", term.string.c_str());
break;
}
case rdf::term_type::plain_literal: {
const auto& term = dynamic_cast<const rdf::plain_literal&>(term_);
std::fputc('"', _stream);
write_escaped_string(term.string.c_str());
std::fputc('"', _stream);
if (!term.language_tag.empty()) {
std::fprintf(_stream, "@%s", term.language_tag.c_str());
}
break;
}
case rdf::term_type::typed_literal: {
const auto& term = dynamic_cast<const rdf::typed_literal&>(term_);
std::fputc('"', _stream);
write_escaped_string(term.string.c_str());
std::fputs("\"^^<", _stream);
write_escaped_iriref(term.datatype_uri.c_str());
std::fputc('>', _stream);
break;
}
default: {
assert(false && "invalid term type for #write_term");
}
}
}
void
implementation::write_escaped_iriref(const char* string) {
// @see http://www.w3.org/TR/n-quads/#grammar-production-IRIREF
char c;
while ((c = *string++) != '\0') {
switch (c) {
// @see http://www.w3.org/TR/n-quads/#grammar-production-UCHAR
case '\x00'...'\x20':
case '<': case '>': case '"': case '{': case '}':
case '|': case '^': case '`': case '\\':
std::fprintf(_stream, "\\u%04X", c);
break;
default:
std::fputc(c, _stream); // TODO: implement UCHAR escaping
}
}
}
void
implementation::write_escaped_string(const char* string) {
// @see http://www.w3.org/TR/n-quads/#grammar-production-STRING_LITERAL_QUOTE
char c;
while ((c = *string++) != '\0') {
switch (c) {
// @see http://www.w3.org/TR/n-quads/#grammar-production-ECHAR
case '\t': std::fputs("\\t", _stream); break;
case '\b': std::fputs("\\b", _stream); break;
case '\n': std::fputs("\\n", _stream); break;
case '\r': std::fputs("\\r", _stream); break;
case '\f': std::fputs("\\f", _stream); break;
case '"': std::fputs("\\\"", _stream); break;
//case '\'': std::fputs("\\'", _stream); /* not needed */
case '\\': std::fputs("\\\\", _stream); break;
// @see http://www.w3.org/TR/n-quads/#grammar-production-UCHAR
default:
std::fputc(c, _stream); // TODO: implement UCHAR escaping
}
}
}
| 28.737557
| 85
| 0.585105
|
datagraph
|
90c0087c3162b691e8ec9d1d48204870220d6bdc
| 3,103
|
hpp
|
C++
|
include/NatSuite/Devices/FlashMode.hpp
|
RedBrumbler/virtuoso-codegen
|
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
|
[
"Unlicense"
] | null | null | null |
include/NatSuite/Devices/FlashMode.hpp
|
RedBrumbler/virtuoso-codegen
|
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
|
[
"Unlicense"
] | null | null | null |
include/NatSuite/Devices/FlashMode.hpp
|
RedBrumbler/virtuoso-codegen
|
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
|
[
"Unlicense"
] | null | null | null |
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: System.Enum
#include "System/Enum.hpp"
// Completed includes
// Type namespace: NatSuite.Devices
namespace NatSuite::Devices {
// Forward declaring type: FlashMode
struct FlashMode;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(::NatSuite::Devices::FlashMode, "NatSuite.Devices", "FlashMode");
// Type namespace: NatSuite.Devices
namespace NatSuite::Devices {
// Size: 0x4
#pragma pack(push, 1)
// Autogenerated type: NatSuite.Devices.FlashMode
// [TokenAttribute] Offset: FFFFFFFF
// [DocAttribute] Offset: 66BAAC
struct FlashMode/*, public ::System::Enum*/ {
public:
public:
// public System.Int32 value__
// Size: 0x4
// Offset: 0x0
int value;
// Field size check
static_assert(sizeof(int) == 0x4);
public:
// Creating value type constructor for type: FlashMode
constexpr FlashMode(int value_ = {}) noexcept : value{value_} {}
// Creating interface conversion operator: operator ::System::Enum
operator ::System::Enum() noexcept {
return *reinterpret_cast<::System::Enum*>(this);
}
// Creating conversion operator: operator int
constexpr operator int() const noexcept {
return value;
}
// [DocAttribute] Offset: 0x677EAC
// static field const value: static public NatSuite.Devices.FlashMode Off
static constexpr const int Off = 0;
// Get static field: static public NatSuite.Devices.FlashMode Off
static ::NatSuite::Devices::FlashMode _get_Off();
// Set static field: static public NatSuite.Devices.FlashMode Off
static void _set_Off(::NatSuite::Devices::FlashMode value);
// [DocAttribute] Offset: 0x677EE4
// static field const value: static public NatSuite.Devices.FlashMode On
static constexpr const int On = 1;
// Get static field: static public NatSuite.Devices.FlashMode On
static ::NatSuite::Devices::FlashMode _get_On();
// Set static field: static public NatSuite.Devices.FlashMode On
static void _set_On(::NatSuite::Devices::FlashMode value);
// [DocAttribute] Offset: 0x677F1C
// static field const value: static public NatSuite.Devices.FlashMode Auto
static constexpr const int Auto = 2;
// Get static field: static public NatSuite.Devices.FlashMode Auto
static ::NatSuite::Devices::FlashMode _get_Auto();
// Set static field: static public NatSuite.Devices.FlashMode Auto
static void _set_Auto(::NatSuite::Devices::FlashMode value);
// Get instance field reference: public System.Int32 value__
int& dyn_value__();
}; // NatSuite.Devices.FlashMode
#pragma pack(pop)
static check_size<sizeof(FlashMode), 0 + sizeof(int)> __NatSuite_Devices_FlashModeSizeCheck;
static_assert(sizeof(FlashMode) == 0x4);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
| 41.932432
| 94
| 0.70448
|
RedBrumbler
|
90c5c4d35c216fd5a4f689cbbb4f551bb9a5174f
| 3,313
|
cpp
|
C++
|
Code/Engine/GameEngine/VirtualReality/Implementation/DeviceTrackingComponent.cpp
|
fereeh/ezEngine
|
14e46cb2a1492812888602796db7ddd66e2b7110
|
[
"MIT"
] | null | null | null |
Code/Engine/GameEngine/VirtualReality/Implementation/DeviceTrackingComponent.cpp
|
fereeh/ezEngine
|
14e46cb2a1492812888602796db7ddd66e2b7110
|
[
"MIT"
] | null | null | null |
Code/Engine/GameEngine/VirtualReality/Implementation/DeviceTrackingComponent.cpp
|
fereeh/ezEngine
|
14e46cb2a1492812888602796db7ddd66e2b7110
|
[
"MIT"
] | null | null | null |
#include <GameEnginePCH.h>
#include <Core/WorldSerializer/WorldReader.h>
#include <Core/WorldSerializer/WorldWriter.h>
#include <Foundation/Configuration/Singleton.h>
#include <Foundation/Profiling/Profiling.h>
#include <GameEngine/VirtualReality/DeviceTrackingComponent.h>
#include <GameEngine/VirtualReality/StageSpaceComponent.h>
//////////////////////////////////////////////////////////////////////////
// clang-format off
EZ_BEGIN_STATIC_REFLECTED_ENUM(ezVRTransformSpace, 1)
EZ_BITFLAGS_CONSTANTS(ezVRTransformSpace::Local, ezVRTransformSpace::Global)
EZ_END_STATIC_REFLECTED_ENUM;
EZ_BEGIN_COMPONENT_TYPE(ezDeviceTrackingComponent, 1, ezComponentMode::Dynamic)
{
EZ_BEGIN_PROPERTIES
{
EZ_ENUM_ACCESSOR_PROPERTY("DeviceType", ezVRDeviceType, GetDeviceType, SetDeviceType),
EZ_ENUM_ACCESSOR_PROPERTY("TransformSpace", ezVRTransformSpace, GetTransformSpace, SetTransformSpace)
}
EZ_END_PROPERTIES;
EZ_BEGIN_ATTRIBUTES
{
new ezCategoryAttribute("Virtual Reality"),
}
EZ_END_ATTRIBUTES;
}
EZ_END_COMPONENT_TYPE
// clang-format on
ezDeviceTrackingComponent::ezDeviceTrackingComponent() = default;
ezDeviceTrackingComponent::~ezDeviceTrackingComponent() = default;
void ezDeviceTrackingComponent::SetDeviceType(ezEnum<ezVRDeviceType> type)
{
m_deviceType = type;
}
ezEnum<ezVRDeviceType> ezDeviceTrackingComponent::GetDeviceType() const
{
return m_deviceType;
}
void ezDeviceTrackingComponent::SetTransformSpace(ezEnum<ezVRTransformSpace> space)
{
m_space = space;
}
ezEnum<ezVRTransformSpace> ezDeviceTrackingComponent::GetTransformSpace() const
{
return m_space;
}
void ezDeviceTrackingComponent::SerializeComponent(ezWorldWriter& stream) const
{
SUPER::SerializeComponent(stream);
ezStreamWriter& s = stream.GetStream();
s << m_deviceType;
s << m_space;
}
void ezDeviceTrackingComponent::DeserializeComponent(ezWorldReader& stream)
{
SUPER::DeserializeComponent(stream);
// const ezUInt32 uiVersion = stream.GetComponentTypeVersion(GetStaticRTTI());
ezStreamReader& s = stream.GetStream();
s >> m_deviceType;
s >> m_space;
}
void ezDeviceTrackingComponent::Update()
{
if (ezVRInterface* pVRInterface = ezSingletonRegistry::GetSingletonInstance<ezVRInterface>())
{
ezVRDeviceID deviceID = pVRInterface->GetDeviceIDByType(m_deviceType);
if (deviceID != -1)
{
const ezVRDeviceState& state = pVRInterface->GetDeviceState(deviceID);
if (state.m_bPoseIsValid)
{
if (m_space == ezVRTransformSpace::Local)
{
GetOwner()->SetLocalPosition(state.m_vPosition);
GetOwner()->SetLocalRotation(state.m_qRotation);
}
else
{
ezTransform add;
add.SetIdentity();
if (const ezStageSpaceComponentManager* pStageMan = GetWorld()->GetComponentManager<ezStageSpaceComponentManager>())
{
if (const ezStageSpaceComponent* pStage = pStageMan->GetSingletonComponent())
{
add = pStage->GetOwner()->GetGlobalTransform();
}
}
ezTransform local(state.m_vPosition, state.m_qRotation);
GetOwner()->SetGlobalTransform(local * add);
}
}
}
}
}
EZ_STATICLINK_FILE(GameEngine, GameEngine_VirtualReality_Implementation_DeviceTrackingComponent);
| 29.318584
| 126
| 0.728041
|
fereeh
|
90c6154eb2f96f95ae35b71ae2cb9827cae4fa49
| 123
|
cpp
|
C++
|
dbmodel/persistent.cpp
|
arsee11/arseeulib
|
528afa07d182e76ce74255a53ee01d73c2fae66f
|
[
"BSD-2-Clause"
] | null | null | null |
dbmodel/persistent.cpp
|
arsee11/arseeulib
|
528afa07d182e76ce74255a53ee01d73c2fae66f
|
[
"BSD-2-Clause"
] | 1
|
2015-08-21T06:31:32.000Z
|
2015-08-21T06:32:06.000Z
|
dbmodel/persistent.cpp
|
arsee11/arseeulib
|
528afa07d182e76ce74255a53ee01d73c2fae66f
|
[
"BSD-2-Clause"
] | 1
|
2016-07-23T04:03:15.000Z
|
2016-07-23T04:03:15.000Z
|
//persistent.cpp
//copyright : Copyright (c) 2014 arsee.
//license : GNU GPL v2.
//author : arsee
#include "persistent.h"
| 17.571429
| 39
| 0.691057
|
arsee11
|
90c6fd3a1c859d2efea4b58afc025bca63b6c205
| 2,487
|
cpp
|
C++
|
src_R/culex.cpp
|
slwu89/culex-model
|
eee653b2b633b26b735034303e21e3a67341c119
|
[
"MIT"
] | null | null | null |
src_R/culex.cpp
|
slwu89/culex-model
|
eee653b2b633b26b735034303e21e3a67341c119
|
[
"MIT"
] | null | null | null |
src_R/culex.cpp
|
slwu89/culex-model
|
eee653b2b633b26b735034303e21e3a67341c119
|
[
"MIT"
] | null | null | null |
#include "culex.hpp"
// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::plugins(cpp14)]]
// ---------- stochastic model interface ----------
using culex_stochastic = culex<int>;
// [[Rcpp::export]]
Rcpp::XPtr<culex_stochastic> create_culex_stochastic(const int p, const std::vector<int>& tau_E, const std::vector<int>& tau_L, const std::vector<int>& tau_P, const double dt, const arma::Mat<double>& psi) {
return Rcpp::XPtr<culex_stochastic>(
new culex<int>(p, tau_E, tau_L, tau_P, dt, psi),
true
);
};
// [[Rcpp::export]]
void step_culex_stochastic(Rcpp::XPtr<culex_stochastic> mod, const Rcpp::List& parameters) {
mod->update(parameters);
}
// [[Rcpp::export]]
void set_A_stochastic(Rcpp::XPtr<culex_stochastic> mod, arma::Row<int> A) {
mod->A = A;
};
// [[Rcpp::export]]
arma::Row<int> get_A_stochastic(Rcpp::XPtr<culex_stochastic> mod) {
return mod->A;
};
// [[Rcpp::export]]
arma::Row<int> get_E_stochastic(Rcpp::XPtr<culex_stochastic> mod) {
return arma::sum(mod->E, 0);
};
// [[Rcpp::export]]
arma::Row<int> get_L_stochastic(Rcpp::XPtr<culex_stochastic> mod) {
return arma::sum(mod->L, 0);
};
// [[Rcpp::export]]
arma::Row<int> get_P_stochastic(Rcpp::XPtr<culex_stochastic> mod) {
return arma::sum(mod->P, 0);
};
// ---------- deterministic model interface ----------
using culex_deterministic = culex<double>;
// [[Rcpp::export]]
Rcpp::XPtr<culex_deterministic> create_culex_deterministic(const int p, const std::vector<int>& tau_E, const std::vector<int>& tau_L, const std::vector<int>& tau_P, const double dt, const arma::Mat<double>& psi) {
return Rcpp::XPtr<culex_deterministic>(
new culex<double>(p, tau_E, tau_L, tau_P, dt, psi),
true
);
};
// [[Rcpp::export]]
void step_culex_deterministic(Rcpp::XPtr<culex_deterministic> mod, const Rcpp::List& parameters) {
mod->update(parameters);
}
// [[Rcpp::export]]
void set_A_deterministic(Rcpp::XPtr<culex_deterministic> mod, arma::Row<double> A) {
mod->A = A;
};
// [[Rcpp::export]]
arma::Row<double> get_A_deterministic(Rcpp::XPtr<culex_deterministic> mod) {
return mod->A;
};
// [[Rcpp::export]]
arma::Row<double> get_E_deterministic(Rcpp::XPtr<culex_deterministic> mod) {
return arma::sum(mod->E, 0);
};
// [[Rcpp::export]]
arma::Row<double> get_L_deterministic(Rcpp::XPtr<culex_deterministic> mod) {
return arma::sum(mod->L, 0);
};
// [[Rcpp::export]]
arma::Row<double> get_P_deterministic(Rcpp::XPtr<culex_deterministic> mod) {
return arma::sum(mod->P, 0);
};
| 27.633333
| 213
| 0.676719
|
slwu89
|
90c7946c59987651ee16b40cd64210aaabe2a9ca
| 1,273
|
hpp
|
C++
|
include/virt_wrap/enums/Storage/VolResizeFlag.hpp
|
AeroStun/virthttp
|
d6ae9d752721aa5ecc74dbc2dbb54de917ba31ad
|
[
"Apache-2.0"
] | 7
|
2019-08-22T20:48:15.000Z
|
2021-12-31T16:08:59.000Z
|
include/virt_wrap/enums/Storage/VolResizeFlag.hpp
|
AeroStun/virthttp
|
d6ae9d752721aa5ecc74dbc2dbb54de917ba31ad
|
[
"Apache-2.0"
] | 10
|
2019-08-22T21:40:43.000Z
|
2020-09-03T14:21:21.000Z
|
include/virt_wrap/enums/Storage/VolResizeFlag.hpp
|
AeroStun/virthttp
|
d6ae9d752721aa5ecc74dbc2dbb54de917ba31ad
|
[
"Apache-2.0"
] | 2
|
2019-08-22T21:08:28.000Z
|
2019-08-23T21:31:56.000Z
|
#ifndef VIRTPP_ENUM_STORAGE_VOLRESIZEFLAG_HPP
#define VIRTPP_ENUM_STORAGE_VOLRESIZEFLAG_HPP
#include "../../StorageVol.hpp"
#include "virt_wrap/enums/Base.hpp"
#include "virt_wrap/utility.hpp"
#include <libvirt/libvirt-storage.h>
namespace virt {
class StorageVol::ResizeFlag : private VirtEnumStorage<virStorageVolResizeFlags>, public VirtEnumBase<ResizeFlag>, public EnumSetHelper<ResizeFlag> {
friend VirtEnumBase<ResizeFlag>;
friend EnumSetHelper<ResizeFlag>;
enum class Underlying {
ALLOCATE = VIR_STORAGE_VOL_RESIZE_ALLOCATE, /* force allocation of new size */
DELTA = VIR_STORAGE_VOL_RESIZE_DELTA, /* size is relative to current */
SHRINK = VIR_STORAGE_VOL_RESIZE_SHRINK, /* allow decrease in capacity */
} constexpr static default_value{};
protected:
constexpr static std::array values = {"allocate", "delta", "shrink"};
public:
using VirtEnumBase::VirtEnumBase;
constexpr static auto from_string(std::string_view sv) { return EnumSetHelper{}.from_string_base(sv); }
// using enum Underlying;
constexpr static auto ALLOCATE = Underlying::ALLOCATE;
constexpr static auto DELTA = Underlying::DELTA;
constexpr static auto SHRINK = Underlying::SHRINK;
};
} // namespace virt
#endif
| 38.575758
| 149
| 0.744698
|
AeroStun
|
90c9563d52c67684b1bee6efdd96acaca6843d38
| 13,863
|
cpp
|
C++
|
dev/Code/Tools/AssetProcessor/Builders/WwiseBuilder/Source/WwiseBuilderComponent.cpp
|
yuriy0/lumberyard
|
18ab07fd38492d88c34df2a3e061739d96747e13
|
[
"AML"
] | null | null | null |
dev/Code/Tools/AssetProcessor/Builders/WwiseBuilder/Source/WwiseBuilderComponent.cpp
|
yuriy0/lumberyard
|
18ab07fd38492d88c34df2a3e061739d96747e13
|
[
"AML"
] | null | null | null |
dev/Code/Tools/AssetProcessor/Builders/WwiseBuilder/Source/WwiseBuilderComponent.cpp
|
yuriy0/lumberyard
|
18ab07fd38492d88c34df2a3e061739d96747e13
|
[
"AML"
] | null | null | null |
/*
* All or portions of this file Copyright(c) Amazon.com, Inc.or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution(the "License").All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file.Do not
* remove or modify any license notices.This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include "WwiseBuilderComponent.h"
#include <AzCore/Debug/Trace.h>
#include <AzCore/IO/SystemFile.h>
#include <AzCore/JSON/rapidjson.h>
#include <AzCore/JSON/document.h>
#include <AzCore/Serialization/SerializeContext.h>
#include <AzFramework/IO/LocalFileIO.h>
#include <AzFramework/StringFunc/StringFunc.h>
namespace WwiseBuilder
{
const char WwiseBuilderWindowName[] = "WwiseBuilder";
namespace Internal
{
const char SoundbankExtension[] = ".bnk";
const char SoundbankDependencyFileExtension[] = ".bankdeps";
const char InitBankFullFileName[] = "init.bnk";
const char JsonDependencyKey[] = "dependencies";
AZ::Outcome<AZStd::string, AZStd::string> GetDependenciesFromMetadata(const rapidjson::Value& rootObject, AZStd::vector<AZStd::string>& fileNames)
{
if (!rootObject.IsObject())
{
return AZ::Failure(AZStd::string("The root of the metadata file is not an object. Please regenerate the metadata for this soundbank."));
}
// If the file doesn't define a dependency field, then there are no dependencies.
if (!rootObject.HasMember(JsonDependencyKey))
{
AZStd::string addingDefaultDependencyWarning = AZStd::string::format(
"Dependencies array does not exist. The file was likely manually edited. Registering a default "
"dependency on %s. Please regenerate the metadata for this bank.",
InitBankFullFileName);
return AZ::Success(addingDefaultDependencyWarning);
}
const rapidjson::Value& dependenciesArray = rootObject[JsonDependencyKey];
if (!dependenciesArray.IsArray())
{
return AZ::Failure(AZStd::string("Dependency field is not an array. Please regenerate the metadata for this soundbank."));
}
for (rapidjson::SizeType dependencyIndex = 0; dependencyIndex < dependenciesArray.Size(); ++dependencyIndex)
{
fileNames.push_back(dependenciesArray[dependencyIndex].GetString());
}
// The dependency array is empty, which likely means it was modified by hand. However, every bank is dependent
// on init.bnk (other than itself), so just force add it as a dependency here. and emit a warning.
if (fileNames.size() == 0)
{
AZStd::string addingDefaultDependencyWarning = AZStd::string::format(
"Dependencies array is empty. The file was likely manually edited. Registering a default "
"dependency on %s. Please regenerate the metadata for this bank.",
InitBankFullFileName);
return AZ::Success(addingDefaultDependencyWarning);
}
// Make sure init.bnk is in the dependency list. Force add it if it's not
else if (AZStd::find(fileNames.begin(), fileNames.end(), InitBankFullFileName) == fileNames.end())
{
AZStd::string addingDefaultDependencyWarning = AZStd::string::format(
"Dependencies does not contain the initialization bank. The file was likely manually edited to remove "
"it, however it is necessary for all banks to have the initialization bank loaded. Registering a "
"default dependency on %s. Please regenerate the metadata for this bank.",
InitBankFullFileName);
fileNames.push_back(InitBankFullFileName);
return AZ::Success(addingDefaultDependencyWarning);
}
return AZ::Success(AZStd::string());
}
}
BuilderPluginComponent::BuilderPluginComponent()
{
}
BuilderPluginComponent::~BuilderPluginComponent()
{
}
void BuilderPluginComponent::Init()
{
}
void BuilderPluginComponent::Activate()
{
// Register Wwise builder
AssetBuilderSDK::AssetBuilderDesc builderDescriptor;
builderDescriptor.m_name = "WwiseBuilderWorker";
builderDescriptor.m_patterns.push_back(AssetBuilderSDK::AssetBuilderPattern("*.bnk", AssetBuilderSDK::AssetBuilderPattern::PatternType::Wildcard));
builderDescriptor.m_patterns.push_back(AssetBuilderSDK::AssetBuilderPattern("*.wem", AssetBuilderSDK::AssetBuilderPattern::PatternType::Wildcard));
builderDescriptor.m_busId = WwiseBuilderWorker::GetUUID();
builderDescriptor.m_version = 2;
builderDescriptor.m_createJobFunction = AZStd::bind(&WwiseBuilderWorker::CreateJobs, &m_wwiseBuilder, AZStd::placeholders::_1, AZStd::placeholders::_2);
builderDescriptor.m_processJobFunction = AZStd::bind(&WwiseBuilderWorker::ProcessJob, &m_wwiseBuilder, AZStd::placeholders::_1, AZStd::placeholders::_2);
// (optimization) this builder does not emit source dependencies:
builderDescriptor.m_flags |= AssetBuilderSDK::AssetBuilderDesc::BF_EmitsNoDependencies;
m_wwiseBuilder.BusConnect(builderDescriptor.m_busId);
AssetBuilderSDK::AssetBuilderBus::Broadcast(&AssetBuilderSDK::AssetBuilderBus::Events::RegisterBuilderInformation, builderDescriptor);
}
void BuilderPluginComponent::Deactivate()
{
m_wwiseBuilder.BusDisconnect();
}
void BuilderPluginComponent::Reflect(AZ::ReflectContext* context)
{
}
WwiseBuilderWorker::WwiseBuilderWorker()
{
}
WwiseBuilderWorker::~WwiseBuilderWorker()
{
}
void WwiseBuilderWorker::ShutDown()
{
// This will be called on a different thread than the process job thread
m_isShuttingDown = true;
}
AZ::Uuid WwiseBuilderWorker::GetUUID()
{
return AZ::Uuid::CreateString("{85224E40-9211-4C05-9397-06E056470171}");
}
// This happens early on in the file scanning pass.
// This function should always create the same jobs and not do any checking whether the job is up to date.
void WwiseBuilderWorker::CreateJobs(const AssetBuilderSDK::CreateJobsRequest& request, AssetBuilderSDK::CreateJobsResponse& response)
{
if (m_isShuttingDown)
{
response.m_result = AssetBuilderSDK::CreateJobsResultCode::ShuttingDown;
return;
}
for (const AssetBuilderSDK::PlatformInfo& info : request.m_enabledPlatforms)
{
AssetBuilderSDK::JobDescriptor descriptor;
descriptor.m_jobKey = "Wwise";
descriptor.m_critical = true;
descriptor.SetPlatformIdentifier(info.m_identifier.c_str());
descriptor.m_priority = 0;
response.m_createJobOutputs.push_back(descriptor);
}
response.m_result = AssetBuilderSDK::CreateJobsResultCode::Success;
}
// The request will contain the CreateJobResponse you constructed earlier, including any keys and
// values you placed into the hash table
void WwiseBuilderWorker::ProcessJob(const AssetBuilderSDK::ProcessJobRequest& request, AssetBuilderSDK::ProcessJobResponse& response)
{
AZ_TracePrintf(AssetBuilderSDK::InfoWindow, "Starting Job.\n");
AZStd::string fileName;
AzFramework::StringFunc::Path::GetFullFileName(request.m_fullPath.c_str(), fileName);
if (m_isShuttingDown)
{
AZ_TracePrintf(AssetBuilderSDK::ErrorWindow, "Cancelled job %s because shutdown was requested.\n", request.m_fullPath.c_str());
response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Cancelled;
return;
}
else
{
response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Success;
AssetBuilderSDK::JobProduct jobProduct(request.m_fullPath);
// if the file is a bnk
AZStd::string requestExtension;
if (AzFramework::StringFunc::Path::GetExtension(request.m_fullPath.c_str(), requestExtension)
&& requestExtension == Internal::SoundbankExtension)
{
AssetBuilderSDK::ProductPathDependencySet dependencyPaths;
// Push assets back into the response's product list
// Assets you created in your temp path can be specified using paths relative to the temp path
// since that is assumed where you're writing stuff.
AZ::Outcome<AZStd::string, AZStd::string> gatherProductDependenciesResponse = GatherProductDependencies(request.m_fullPath, request.m_sourceFile, dependencyPaths);
if (!gatherProductDependenciesResponse.IsSuccess())
{
AZ_Error(WwiseBuilderWindowName, false, "Dependency gathering for %s failed. %s",
request.m_fullPath.c_str(), gatherProductDependenciesResponse.GetError().c_str());
}
else
{
if (gatherProductDependenciesResponse.GetValue().empty())
{
AZ_Warning(WwiseBuilderWindowName, false, gatherProductDependenciesResponse.GetValue().c_str());
}
jobProduct.m_pathDependencies = AZStd::move(dependencyPaths);
}
}
jobProduct.m_dependenciesHandled = true; // We've output the dependencies immediately above so it's OK to tell the AP we've handled dependencies
response.m_outputProducts.push_back(jobProduct);
}
}
AZ::Outcome<AZStd::string, AZStd::string> WwiseBuilderWorker::GatherProductDependencies(const AZStd::string& fullPath, const AZStd::string& relativePath, AssetBuilderSDK::ProductPathDependencySet& dependencies)
{
AZStd::string bankMetadataPath = fullPath;
AzFramework::StringFunc::Path::ReplaceExtension(bankMetadataPath, Internal::SoundbankDependencyFileExtension);
AZStd::string relativeSoundsPath = relativePath;
AzFramework::StringFunc::Path::StripFullName(relativeSoundsPath);
AZStd::string success_message;
// Look for the corresponding .bankdeps file next to the bank itself.
if (!AZ::IO::SystemFile::Exists(bankMetadataPath.c_str()))
{
// If this is the init bank, skip it. Otherwise, register the init bank as a dependency, and warn that a full
// dependency graph can't be created without a .bankdeps file for the bank.
AZStd::string requestFileName;
AzFramework::StringFunc::Path::GetFullFileName(fullPath.c_str(), requestFileName);
if (requestFileName != Internal::InitBankFullFileName)
{
success_message = AZStd::string::format("Failed to find the metadata file %s for soundbank %s. Full dependency information cannot be determined without the metadata file. Please regenerate the metadata for this soundbank.", bankMetadataPath.c_str(), fullPath.c_str());
}
return AZ::Success(success_message);
}
AZ::u64 fileSize = AZ::IO::SystemFile::Length(bankMetadataPath.c_str());
if (fileSize == 0)
{
return AZ::Failure(AZStd::string::format("Soundbank metadata file at path %s is an empty file. Please regenerate the metadata for this soundbank.", bankMetadataPath.c_str()));
}
AZStd::vector<char> buffer(fileSize + 1);
buffer[fileSize] = 0;
if (!AZ::IO::SystemFile::Read(bankMetadataPath.c_str(), buffer.data()))
{
return AZ::Failure(AZStd::string::format("Failed to read the soundbank metadata file at path %s. Please make sure the file is not open or being edited by another program.", bankMetadataPath.c_str()));
}
// load the file
rapidjson::Document bankMetadataDoc;
bankMetadataDoc.Parse(buffer.data());
if (bankMetadataDoc.GetParseError() != rapidjson::ParseErrorCode::kParseErrorNone)
{
return AZ::Failure(AZStd::string::format("Failed to parse soundbank metadata at path %s into JSON. Please regenerate the metadata for this soundbank.", bankMetadataPath.c_str()));
}
AZStd::vector<AZStd::string> wwiseFiles;
AZ::Outcome<AZStd::string, AZStd::string> gatherDependenciesResult = Internal::GetDependenciesFromMetadata(bankMetadataDoc, wwiseFiles);
if (!gatherDependenciesResult.IsSuccess())
{
return AZ::Failure(AZStd::string::format("Failed to gather dependencies for %s from metadata file %s. %s", fullPath.c_str(), bankMetadataPath.c_str(), gatherDependenciesResult.GetError().c_str()));
}
else if (!gatherDependenciesResult.GetValue().empty())
{
success_message = AZStd::string::format("Dependency information for %s was unavailable in the metadata file %s. %s", fullPath.c_str(), bankMetadataPath.c_str(), gatherDependenciesResult.GetValue().c_str());
}
// Register dependencies stored in the file to the job response. (they'll be relative to the bank itself.)
for (const AZStd::string& wwiseFile : wwiseFiles)
{
dependencies.emplace(relativeSoundsPath + wwiseFile, AssetBuilderSDK::ProductPathDependencyType::ProductFile);
}
return AZ::Success(success_message);
}
}
| 48.81338
| 284
| 0.664575
|
yuriy0
|
90d0e254fc7e7a06f064b22e46d16f60071924a9
| 21,526
|
cpp
|
C++
|
LTSDK/runtime/render/d3dmeshrendobj_skel.cpp
|
crskycode/msLTBImporter
|
be8a04c5365746c46a1d7804909e04a741d86b44
|
[
"MIT"
] | 3
|
2021-03-02T15:55:01.000Z
|
2021-10-21T07:11:17.000Z
|
LTSDK/runtime/render/d3dmeshrendobj_skel.cpp
|
crskycode/msLTBImporter
|
be8a04c5365746c46a1d7804909e04a741d86b44
|
[
"MIT"
] | 1
|
2021-09-27T02:38:49.000Z
|
2021-11-06T16:09:21.000Z
|
LTSDK/runtime/render/d3dmeshrendobj_skel.cpp
|
crskycode/msLTBImporter
|
be8a04c5365746c46a1d7804909e04a741d86b44
|
[
"MIT"
] | 1
|
2021-04-26T13:22:51.000Z
|
2021-04-26T13:22:51.000Z
|
// d3dmeshrendobj_skel.cpp
//#include "precompile.h"
#include "d3dmeshrendobj_skel.h"
//#include "renderstruct.h"
#include "ltb.h"
//#include "d3d_device.h"
//#include "d3d_texture.h"
//#include "d3d_renderstatemgr.h"
//#include "d3d_draw.h"
//#include "ltvertexshadermgr.h"
//#include "ltpixelshadermgr.h"
//#include "de_objects.h"
//#include "ltshaderdevicestateimp.h"
//#include "rendererconsolevars.h"
//#include "LTEffectImpl.h"
//#include "lteffectshadermgr.h"
#include <set>
#include <vector>
//IClientShell game client shell object.
//#include "iclientshell.h"
//static IClientShell *i_client_shell;
//define_holder(IClientShell, i_client_shell);
CD3DSkelMesh::CD3DSkelMesh()
{
Reset();
}
CD3DSkelMesh::~CD3DSkelMesh()
{
FreeAll();
}
// ------------------------------------------------------------------------
// CalcUsedNodes()
// specifically find the nodes that are used by the mesh AND are the most
// distal nodes in the set. We don't need interior nodes since the xform evaulation
// paths start at the leaves.
// NOTE : t.f fix
// This algorithm is actually in the packer, its here for models that are
// version 21 or less. This should be removed once all models are version 22.
// ------------------------------------------------------------------------
void CD3DSkelMesh::CalcUsedNodes( Model *pModel )
{
std::set<uint32> node_set ;
std::vector<uint32> node_list ;
for( uint32 iBoneSet = 0 ; iBoneSet < m_iBoneSetCount ; iBoneSet++ )
{
for( uint32 iBoneCnt = 0 ; iBoneCnt < 4 ; iBoneCnt++ )
{
node_set.insert( (uint32)m_pBoneSetArray[iBoneSet].BoneSetArray[iBoneCnt]);
}
}
std::set<uint32>::iterator set_it = node_set.begin();
// create set of terminal nodes for finding paths.
for( ; set_it != node_set.end() ; set_it++ )
{
uint32 iNode = *set_it ;
if( iNode == 255 ) continue ;
ModelNode *pModelNode = pModel->GetNode(iNode);
// check if children are in the set.
// if none of the children are in the set, add the node to the final list.
uint32 nChildren = pModelNode->m_Children.GetSize();
uint32 iChild ;
bool IsTerminalNode = true ;
for( iChild = 0 ; iChild < nChildren ; iChild++ )
{
// if we find a child that is in the set, quit the search.
if( node_set.find( pModelNode->m_Children[iChild]->m_NodeIndex ) != node_set.end() )
{
IsTerminalNode = false ;
continue ;
}
}
// if all the children didn't have a parent in the mesh's bone list, add this node
// as a terminal node.
if(IsTerminalNode)
{
node_list.push_back(*set_it);
}
}
// transfer the new information from here to the renderobject.
CreateUsedNodeList(node_list.size());
for( uint32 iNodeCnt =0 ; iNodeCnt < node_list.size() ; iNodeCnt++ )
{
m_pUsedNodeList[iNodeCnt] = node_list[iNodeCnt];
}
}
void CD3DSkelMesh::Reset()
{
// m_VBController.Reset();
m_iMaxBonesPerVert = 0;
m_iMaxBonesPerTri = 0;
m_iVertCount = 0;
m_iPolyCount = 0;
m_eRenderMethod = eD3DRenderDirect;
m_iBoneSetCount = 0;
m_pBoneSetArray = NULL;
m_VertType = eNO_WORLD_BLENDS;
// m_bSWVertProcessing = ((g_Device.GetDeviceCaps()->DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT) == 0) ? true : false;
m_bSWVSBuffers = false;
// Use software processing for shaders ?
// if ( g_Device.GetDeviceCaps()->VertexShaderVersion < D3DVS_VERSION(1,1) )
// m_bSWVSBuffers = true;
// in case software has been forced
// if ( g_CV_ForceSWVertProcess )
// m_bSWVertProcessing = true;
m_pIndexData = NULL;
m_bNonFixPipeData = false;
m_bReIndexedBones = false;
m_pReIndexedBoneList= NULL;
for (uint32 i = 0; i < 4; ++i)
m_pVertData[i] = NULL;
}
void CD3DSkelMesh::FreeAll()
{
// m_VBController.FreeAll();
if (m_pBoneSetArray)
{
delete[] m_pBoneSetArray;
m_pBoneSetArray = NULL;
}
if (m_pIndexData)
{
delete[] m_pIndexData;
m_pIndexData = NULL;
}
if (m_pReIndexedBoneList)
{
delete[] m_pReIndexedBoneList;
m_pReIndexedBoneList = NULL;
}
for (uint32 i = 0; i < 4; ++i)
{
if (m_pVertData[i])
{
delete[] m_pVertData[i];
m_pVertData[i] = NULL;
}
}
Reset();
}
bool CD3DSkelMesh::Load(ILTStream& File, LTB_Header& LTBHeader)
{
if (LTBHeader.m_iFileType != LTB_D3D_MODEL_FILE)
{
// OutputDebugString("Error: Wrong file type in CD3DSkelMesh::Load\n");
return false;
}
if (LTBHeader.m_iVersion != CD3D_LTB_LOAD_VERSION)
{
// OutputDebugString("Error: Wrong file version in CD3DSkelMesh::Load\n");
return false;
}
// Read in the basics...
uint32 iObjSize; File.Read(&iObjSize,sizeof(iObjSize));
File.Read(&m_iVertCount,sizeof(m_iVertCount));
File.Read(&m_iPolyCount,sizeof(m_iPolyCount));
File.Read(&m_iMaxBonesPerTri,sizeof(m_iMaxBonesPerTri));
File.Read(&m_iMaxBonesPerVert,sizeof(m_iMaxBonesPerVert));
File.Read(&m_bReIndexedBones,sizeof(m_bReIndexedBones));
File.Read(&m_VertStreamFlags[0],sizeof(uint32)*4);
// Are we using Matrix Palettes...
bool bUseMatrixPalettes;
File.Read(&bUseMatrixPalettes,sizeof(bUseMatrixPalettes));
if (bUseMatrixPalettes)
{
m_eRenderMethod = eD3DRenderMatrixPalettes;
return Load_MP(File);
}
else
{
m_eRenderMethod = eD3DRenderDirect;
return Load_RD(File);
}
}
bool CD3DSkelMesh::Load_RD(ILTStream& File)
{
// What type of Vert do we need?
switch (m_iMaxBonesPerTri)
{
case 1 : m_VertType = eNO_WORLD_BLENDS; break;
case 2 : m_VertType = eNONINDEXED_B1; break;
case 3 : m_VertType = eNONINDEXED_B2; break;
case 4 : m_VertType = eNONINDEXED_B3; break;
default : assert(0); return false;
}
// Read in our Verts...
for (uint32 i=0;i<4;++i)
{
if (!m_VertStreamFlags[i]) continue;
uint32 iVertexSize = 0; // Figure out the vertex size...
uint32 iVertFlags = 0;
uint32 iUVSets = 0;
GetVertexFlags_and_Size(m_VertType,m_VertStreamFlags[i],iVertFlags,iVertexSize,iUVSets,m_bNonFixPipeData);
uint32 iSize = iVertexSize * m_iVertCount; // Alloc the VertData...
LT_MEM_TRACK_ALLOC(m_pVertData[i] = new uint8[iSize],LT_MEM_TYPE_RENDERER);
File.Read(m_pVertData[i],iSize);
}
// Read in pIndexList...
LT_MEM_TRACK_ALLOC(m_pIndexData = new uint8[sizeof(uint16) * m_iPolyCount * 3],LT_MEM_TYPE_RENDERER);
File.Read(m_pIndexData,sizeof(uint16) * m_iPolyCount * 3);
// Allocate and read in the BoneSets...
File.Read(&m_iBoneSetCount,sizeof(m_iBoneSetCount));
LT_MEM_TRACK_ALLOC(m_pBoneSetArray = new BoneSetListItem[m_iBoneSetCount],LT_MEM_TYPE_RENDERER);
if (!m_pBoneSetArray)
return false;
File.Read(m_pBoneSetArray,sizeof(BoneSetListItem)*m_iBoneSetCount);
// Create the VBs and stuff...
ReCreateObject();
return true;
}
bool CD3DSkelMesh::Load_MP(ILTStream& File)
{
// Read in out Min/Max Bones (effecting this guy)...
File.Read(&m_iMinBone,sizeof(m_iMinBone));
File.Read(&m_iMaxBone,sizeof(m_iMaxBone));
// What type of Vert do we need?
switch (m_iMaxBonesPerVert)
{
case 2 : m_VertType = eINDEXED_B1; break;
case 3 : m_VertType = eINDEXED_B2; break;
case 4 : m_VertType = eINDEXED_B3; break;
default : assert(0); return false;
}
// If we are using re-indexed bones, read them in...
if (m_bReIndexedBones)
{
uint32 iBoneCount = 0;
File.Read(&iBoneCount,sizeof(iBoneCount));
assert(iBoneCount < 10000 && "Crazy bone count, checked your packed model format.");
LT_MEM_TRACK_ALLOC(m_pReIndexedBoneList = new uint32[iBoneCount],LT_MEM_TYPE_RENDERER);
File.Read(m_pReIndexedBoneList,sizeof(uint32)*iBoneCount);
}
// Read in our Verts...
for (uint32 i=0;i<4;++i)
{
if (!m_VertStreamFlags[i])
continue;
uint32 iVertexSize = 0; // Figure out the vertex size...
uint32 iVertFlags = 0;
uint32 iUVSets = 0;
GetVertexFlags_and_Size(m_VertType,m_VertStreamFlags[i],iVertFlags,iVertexSize,iUVSets,m_bNonFixPipeData);
uint32 iSize = iVertexSize * m_iVertCount; // Alloc the VertData...
LT_MEM_TRACK_ALLOC(m_pVertData[i] = new uint8[iSize],LT_MEM_TYPE_RENDERER);
File.Read(m_pVertData[i],iSize);
}
// Read in pIndexList...
LT_MEM_TRACK_ALLOC(m_pIndexData = new uint8[sizeof(uint16) * m_iPolyCount * 3],LT_MEM_TYPE_RENDERER);
File.Read(m_pIndexData,sizeof(uint16) * m_iPolyCount * 3);
// Create the VBs and stuff...
ReCreateObject();
return true;
}
// Create the VBs and stuff from our sys mem copies...
//void CD3DSkelMesh::ReCreateObject()
//{
// // Create our VB...
// for (uint32 i=0;i<4;++i)
// {
// if (!m_VertStreamFlags[i])
// continue;
//
// if (!m_VBController.CreateStream(i, m_iVertCount, m_VertStreamFlags[i], m_VertType, false, true, m_bSWVertProcessing))
// {
// FreeAll();
// return;
// }
// }
//
// if (!m_VBController.CreateIndexBuffer(m_iPolyCount*3,false,true,m_bSWVertProcessing))
// {
// FreeAll();
// return;
// }
//
// // Read in our Verts...
// for (i=0;i<4;++i)
// {
// if (!m_VertStreamFlags[i])
// continue;
//
// m_VBController.Lock((VertexBufferController::VB_TYPE)(VertexBufferController::eVERTSTREAM0 + i),false);
//
// uint8* pVertData = (uint8*)m_VBController.getVertexData(i);
// uint32 iSize = m_VBController.getVertexSize(i) * m_iVertCount;
// memcpy(pVertData,m_pVertData[i],iSize);
//
// m_VBController.UnLock((VertexBufferController::VB_TYPE)(VertexBufferController::eVERTSTREAM0 + i));
// }
//
// // Read in pIndexList...
// m_VBController.Lock(VertexBufferController::eINDEX,false);
// memcpy(m_VBController.getIndexData(),m_pIndexData,sizeof(uint16) * m_iPolyCount * 3);
// m_VBController.UnLock(VertexBufferController::eINDEX);
//}
// We're loosing focus, free the stuff...
//void CD3DSkelMesh::FreeDeviceObjects()
//{
// m_VBController.FreeAll(); // Free our VB...
//}
//inline int32 CD3DSkelMesh::SetTransformsToBoneSet(BoneSetListItem* pBoneSet,D3DMATRIX* pTransforms, int32 nNumMatrices)
//{
// for (int32 iCurrBone=0; iCurrBone < 4; ++iCurrBone)
// {
// if (pBoneSet->BoneSetArray[iCurrBone] == 0xFF)
// {
// /*
// D3DXMATRIX mMat;
// //D3DXMatrixIdentity(&mMat);
// ZeroMemory(&mMat, sizeof(D3DXMATRIX));
// g_RenderStateMgr.SetTransform(D3DTS_WORLDMATRIX(iCurrBone),&mMat);
// continue;
// */
//
// break;
// }
//
// g_RenderStateMgr.SetTransform(D3DTS_WORLDMATRIX(iCurrBone),&pTransforms[pBoneSet->BoneSetArray[iCurrBone]]);
// }
//
//
//
// if(nNumMatrices != iCurrBone)
// {
// if( g_CV_Use0WeightsForDisable )
// {
// // ATI requires 0 weights instead of disable
// switch (iCurrBone)
// {
// case 1:
// PD3DDEVICE->SetRenderState(D3DRS_VERTEXBLEND,D3DVBF_0WEIGHTS);
// break;
// case 2:
// PD3DDEVICE->SetRenderState(D3DRS_VERTEXBLEND,D3DVBF_1WEIGHTS);
// break;
// case 3:
// PD3DDEVICE->SetRenderState(D3DRS_VERTEXBLEND,D3DVBF_2WEIGHTS);
// break;
// case 4:
// PD3DDEVICE->SetRenderState(D3DRS_VERTEXBLEND,D3DVBF_3WEIGHTS);
// break;
// default:
// PD3DDEVICE->SetRenderState(D3DRS_VERTEXBLEND,D3DVBF_DISABLE);
// ASSERT(0);
// break;
// }
// }
// else
// {
// // but NVIDIA uses disable instead of 0 weights (only on 440MX)
// switch (iCurrBone)
// {
// case 2:
// PD3DDEVICE->SetRenderState(D3DRS_VERTEXBLEND,D3DVBF_1WEIGHTS);
// break;
// case 3:
// PD3DDEVICE->SetRenderState(D3DRS_VERTEXBLEND,D3DVBF_2WEIGHTS);
// break;
// case 4:
// PD3DDEVICE->SetRenderState(D3DRS_VERTEXBLEND,D3DVBF_3WEIGHTS);
// break;
// default:
// PD3DDEVICE->SetRenderState(D3DRS_VERTEXBLEND,D3DVBF_DISABLE);
// break;
// }
// }
// }
//
// return (iCurrBone-1);
//}
//inline uint32 CD3DSkelMesh::SetMatrixPalette(uint32 MinBone,uint32 MaxBone,D3DMATRIX* pTransforms)
//{
// for (uint32 i=MinBone;i<=MaxBone;++i)
// {
// if (m_bReIndexedBones)
// {
// g_RenderStateMgr.SetTransform(D3DTS_WORLDMATRIX(i),&pTransforms[m_pReIndexedBoneList[i]]);
// }
// else
// {
// g_RenderStateMgr.SetTransform(D3DTS_WORLDMATRIX(i),&pTransforms[i]);
// }
// }
//
// switch (m_iMaxBonesPerVert)
// {
// case 2 :
// {
// PD3DDEVICE->SetRenderState(D3DRS_VERTEXBLEND,D3DVBF_1WEIGHTS);
// break;
// }
// case 3 :
// {
// PD3DDEVICE->SetRenderState(D3DRS_VERTEXBLEND,D3DVBF_2WEIGHTS);
// break;
// }
// case 4 :
// {
// PD3DDEVICE->SetRenderState(D3DRS_VERTEXBLEND,D3DVBF_3WEIGHTS);
// break;
// }
// default:
// {
// PD3DDEVICE->SetRenderState(D3DRS_VERTEXBLEND,D3DVBF_DISABLE);
// }
// }
//
// return (MaxBone-MinBone);
//}
// THIS Function should be removed when we go to the full render object implementation - it's
// temporary on the path to full render objects. The D3D pipe render model path call this guy to do
// the transform and lighting stuff.
//void CD3DSkelMesh::Render(ModelInstance *pInstance, D3DMATRIX* pD3DTransforms, CD3DRenderStyle* pRenderStyle, uint32 iRenderPass)
//{
// switch (m_eRenderMethod)
// {
// case eD3DRenderDirect :
// { // We need to do the bone walk, but we can render direct (they've been pre-processed into triangle group/bone group order)...
// uint32 iCurrentPolyIndex = 0;
// int32 nNumActiveBones = -1;
// for( int32 iBoneSet = 0; (iBoneSet < (int32)m_iBoneSetCount) ; ++iBoneSet )
// {
// BoneSetListItem* pBoneSet = &m_pBoneSetArray[iBoneSet];
// nNumActiveBones = SetTransformsToBoneSet(pBoneSet,pD3DTransforms, nNumActiveBones);
//
// // Set the vertex shader constants.
// if (m_pVertexShader != NULL)
// {
// // Let the client set some constants.
// if (NULL != i_client_shell)
// {
// i_client_shell->OnVertexShaderSetConstants(m_pVertexShader, iRenderPass, pRenderStyle, pInstance,
// LTShaderDeviceStateImp::GetSingleton());
// }
//
// // Send the constants to the video card.
// LTVertexShaderMgr::GetSingleton().SetVertexShaderConstants(m_pVertexShader);
// }
//
// // Set the pixel shader constants.
// if (m_pPixelShader != NULL)
// {
// // Let the client set some constants.
// if (NULL != i_client_shell)
// {
// i_client_shell->OnPixelShaderSetConstants(m_pPixelShader, iRenderPass, pRenderStyle, pInstance,
// LTShaderDeviceStateImp::GetSingleton());
// }
//
// // Send the constants to the video card.
// LTPixelShaderMgr::GetSingleton().SetPixelShaderConstants(m_pPixelShader);
// }
//
// RSD3DOptions rsD3DOptions;
// pRenderStyle->GetDirect3D_Options(&rsD3DOptions);
// if(rsD3DOptions.bUseEffectShader)
// {
// LTEffectImpl* _pEffect = (LTEffectImpl*)LTEffectShaderMgr::GetSingleton().GetEffectShader(rsD3DOptions.EffectShaderID);
// ID3DXEffect* pEffect = _pEffect->GetEffect();
//
// if(pEffect)
// {
// i_client_shell->OnEffectShaderSetParams((LTEffectShader*)_pEffect, pRenderStyle, pInstance, LTShaderDeviceStateImp::GetSingleton());
// pEffect->SetInt("BoneCount", nNumActiveBones);
// pEffect->CommitChanges();
// }
//
// }
//
// m_VBController.Render( pBoneSet->iFirstVertIndex,
// iCurrentPolyIndex,
// pBoneSet->iVertCount,
// (pBoneSet->iIndexIntoIndexBuff - iCurrentPolyIndex)/3);
//
//
//
// iCurrentPolyIndex = pBoneSet->iIndexIntoIndexBuff;
//
// IncFrameStat(eFS_ModelRender_NumSkeletalRenderObjects, 1);
// }
//
// break;
// }
// case eD3DRenderMatrixPalettes :
// {
// uint32 nNumActiveBones = SetMatrixPalette(m_iMinBone,m_iMaxBone,pD3DTransforms);
//
// // Set the vertex shader constants.
// if (m_pVertexShader != NULL)
// {
// // Let the client set some constants.
// if (NULL != i_client_shell)
// {
// i_client_shell->OnVertexShaderSetConstants(m_pVertexShader, iRenderPass, pRenderStyle, pInstance,
// LTShaderDeviceStateImp::GetSingleton());
// }
//
// // Send the constants to the video card.
// LTVertexShaderMgr::GetSingleton().SetVertexShaderConstants(m_pVertexShader);
// }
//
// // Set the pixel shader constants.
// if (m_pPixelShader != NULL)
// {
// // Let the client set some constants.
// if (NULL != i_client_shell)
// {
// i_client_shell->OnPixelShaderSetConstants(m_pPixelShader, iRenderPass, pRenderStyle, pInstance,
// LTShaderDeviceStateImp::GetSingleton());
// }
//
// // Send the constants to the video card.
// LTPixelShaderMgr::GetSingleton().SetPixelShaderConstants(m_pPixelShader);
// }
//
// RSD3DOptions rsD3DOptions;
// pRenderStyle->GetDirect3D_Options(&rsD3DOptions);
// if(rsD3DOptions.bUseEffectShader)
// {
// LTEffectImpl* _pEffect = (LTEffectImpl*)LTEffectShaderMgr::GetSingleton().GetEffectShader(rsD3DOptions.EffectShaderID);
// ID3DXEffect* pEffect = _pEffect->GetEffect();
//
// if(pEffect)
// {
// i_client_shell->OnEffectShaderSetParams((LTEffectShader*)_pEffect, pRenderStyle, pInstance, LTShaderDeviceStateImp::GetSingleton());
// pEffect->SetInt("BoneCount", nNumActiveBones);
// pEffect->CommitChanges();
// }
//
// }
//
// m_VBController.Render(0,0,m_iVertCount,m_iPolyCount);
//
// break;
// }
// }
//}
//void CD3DSkelMesh::BeginRender(D3DMATRIX* pD3DTransforms, CD3DRenderStyle* pRenderStyle, uint32 iRenderPass)
//{
//
//// [dlj] remove this because DX9 doesn't have this bug
//
// // DX8 has bug with table fog with blended meshes...
//// PD3DDEVICE->GetRenderState(D3DRS_FOGTABLEMODE, &m_nPrevFogTableMode);
//// PD3DDEVICE->SetRenderState(D3DRS_FOGTABLEMODE, D3DFOG_NONE);
//// PD3DDEVICE->GetRenderState(D3DRS_FOGVERTEXMODE, &m_nPrevFogVertexMode);
//// PD3DDEVICE->SetRenderState(D3DRS_FOGVERTEXMODE, D3DFOG_LINEAR);
//
// // Do we need to do software vert processing...
// bool bSoftwareProcessing = m_bSWVertProcessing;
//
// // Check if we need to do software processing...
// switch (m_eRenderMethod)
// {
// case eD3DRenderDirect :
// if (m_iMaxBonesPerTri > g_Device.GetDeviceCaps()->MaxVertexBlendMatrices)
// {
// bSoftwareProcessing = true;
// }
// break;
// case eD3DRenderMatrixPalettes :
// // Note: I am multiplying by two because the spec sais, if you're doing normals as well, it's half of the cap sais...
// if ((m_iMaxBone-m_iMinBone)*2+1 > g_Device.GetDeviceCaps()->MaxVertexBlendMatrixIndex)
// {
// bSoftwareProcessing = true;
// }
// break;
// }
//
// // If not already software vertex processing then set
// if (!m_bSWVertProcessing && bSoftwareProcessing)
// {
// m_bSWVertProcessing = true;
// FreeDeviceObjects();
// ReCreateObject();
// }
//
//
// // If this pass has a vertex shader, use it.
// RSD3DRenderPass *pPass = pRenderStyle->GetRenderPass_D3DOptions(iRenderPass);
// if (NULL != pPass &&
// pPass->bUseVertexShader &&
// pPass->VertexShaderID != LTVertexShader::VERTEXSHADER_INVALID)
// {
// if ( m_bSWVSBuffers && !m_bSWVertProcessing )
// {
// m_bSWVertProcessing = true;
// FreeDeviceObjects();
// ReCreateObject();
// }
//
// // Store the pointer to the actual shader during rendering.
// m_pVertexShader = LTVertexShaderMgr::GetSingleton().GetVertexShader(pPass->VertexShaderID);
// if (m_pVertexShader != NULL)
// {
// // Install the shader.
// if (!LTVertexShaderMgr::GetSingleton().InstallVertexShader(m_pVertexShader))
// {
// m_pVertexShader = NULL;
// return;
// }
// }
// }
// else if (!m_VBController.getVertexFormat(0) || m_bNonFixPipeData)
// {
//
// RSD3DOptions rsD3DOptions;
// pRenderStyle->GetDirect3D_Options(&rsD3DOptions);
// if(!rsD3DOptions.bUseEffectShader)
// {
// return; // This is a non fixed function pipe VB - bail out...
// }
//
// //return; // This is a non fixed function pipe VB - bail out...
// }
// else if (FAILED(g_RenderStateMgr.SetVertexShader(m_VBController.getVertexFormat(0))))
// {
// return;
// }
//
// // If this pass has a pixel shader, use it.
// if (NULL != pPass &&
// pPass->bUsePixelShader &&
// pPass->PixelShaderID != LTPixelShader::PIXELSHADER_INVALID)
// {
// // Store the pointer to the actual shader during rendering.
// m_pPixelShader = LTPixelShaderMgr::GetSingleton().GetPixelShader(pPass->PixelShaderID);
// if (m_pPixelShader != NULL)
// {
// // Install the shader.
// if (!LTPixelShaderMgr::GetSingleton().InstallPixelShader(m_pPixelShader))
// {
// m_pPixelShader = NULL;
// return;
// }
// }
// }
//
//
// // We need software processing
// if(m_bSWVertProcessing)
// {
// PD3DDEVICE->SetSoftwareVertexProcessing(TRUE);
// }
//
//
// m_VBController.SetStreamSources();
//
// if(m_eRenderMethod == eD3DRenderMatrixPalettes)
// {
// PD3DDEVICE->SetRenderState(D3DRS_INDEXEDVERTEXBLENDENABLE, TRUE);
// }
//}
//void CD3DSkelMesh::EndRender()
//{
// if(m_eRenderMethod == eD3DRenderMatrixPalettes)
// {
// PD3DDEVICE->SetRenderState(D3DRS_INDEXEDVERTEXBLENDENABLE, FALSE);
// }
//
// if ( m_bSWVertProcessing )
// {
// // If we are running with hardware then turn back on hardware processing
// if ( (g_Device.GetDeviceCaps()->DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT) )
// {
//
// PD3DDEVICE->SetSoftwareVertexProcessing(FALSE);
// }
// }
//
// PD3DDEVICE->SetRenderState(D3DRS_VERTEXBLEND,D3DVBF_DISABLE);
//
//// [dlj] remove this because DX9 doesn't have this bug
//// PD3DDEVICE->SetRenderState(D3DRS_FOGTABLEMODE, m_nPrevFogTableMode);
//// PD3DDEVICE->SetRenderState(D3DRS_FOGVERTEXMODE, m_nPrevFogVertexMode);
//
// PD3DDEVICE->SetStreamSource(0, 0, 0, 0);
// PD3DDEVICE->SetIndices(0);
//
// // Uninstall the vertex shader.
// if (NULL != m_pVertexShader)
// {
// LTVertexShaderMgr::GetSingleton().UninstallVertexShader();
// m_pVertexShader = NULL;
// }
//
// // Uninstall the pixel shader.
// if (NULL != m_pPixelShader)
// {
// LTPixelShaderMgr::GetSingleton().UninstallPixelShader();
// m_pPixelShader = NULL;
// }
//
//
//}
| 28.855228
| 140
| 0.684242
|
crskycode
|
90d15e73d1e0a054bc627e6d4f321c3c255f2c21
| 5,224
|
hpp
|
C++
|
master/core/third/libtorrent/include/libtorrent/socket.hpp
|
importlib/klib
|
a59837857689d0e60d3df6d2ebd12c3160efa794
|
[
"MIT"
] | 4
|
2017-12-04T08:22:48.000Z
|
2019-10-26T21:44:59.000Z
|
master/core/third/libtorrent/include/libtorrent/socket.hpp
|
isuhao/klib
|
a59837857689d0e60d3df6d2ebd12c3160efa794
|
[
"MIT"
] | null | null | null |
master/core/third/libtorrent/include/libtorrent/socket.hpp
|
isuhao/klib
|
a59837857689d0e60d3df6d2ebd12c3160efa794
|
[
"MIT"
] | 4
|
2017-12-04T08:22:49.000Z
|
2018-12-27T03:20:31.000Z
|
/*
Copyright (c) 2003, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_SOCKET_HPP_INCLUDED
#define TORRENT_SOCKET_HPP_INCLUDED
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
// if building as Objective C++, asio's template
// parameters Protocol has to be renamed to avoid
// colliding with keywords
#ifdef __OBJC__
#define Protocol Protocol_
#endif
#include <asio/ip/tcp.hpp>
#include <asio/ip/udp.hpp>
#include <asio/io_service.hpp>
#include <asio/deadline_timer.hpp>
#include <asio/write.hpp>
#include <asio/strand.hpp>
#include <asio/time_traits.hpp>
#include <asio/basic_deadline_timer.hpp>
#ifdef __OBJC__
#undef Protocol
#endif
#include "libtorrent/io.hpp"
#include "libtorrent/time.hpp"
#ifdef _MSC_VER
#pragma warning(pop)
#endif
namespace libtorrent
{
/*
namespace asio = boost::asio;
using boost::asio::ipv4::tcp;
using boost::asio::ipv4::address;
using boost::asio::stream_socket;
using boost::asio::datagram_socket;
using boost::asio::socket_acceptor;
using boost::asio::io_service;
using boost::asio::ipv4::host_resolver;
using boost::asio::async_write;
using boost::asio::ipv4::host;
using boost::asio::deadline_timer;
*/
// namespace asio = ::asio;
using asio::ip::tcp;
using asio::ip::udp;
typedef asio::ip::tcp::socket stream_socket;
typedef asio::ip::address address;
typedef asio::ip::address_v4 address_v4;
typedef asio::ip::address_v6 address_v6;
typedef asio::ip::udp::socket datagram_socket;
typedef asio::ip::tcp::acceptor socket_acceptor;
typedef asio::io_service io_service;
using asio::async_write;
using asio::error_code;
typedef asio::basic_deadline_timer<libtorrent::ptime> deadline_timer;
inline std::ostream& print_endpoint(std::ostream& os, tcp::endpoint const& ep)
{
address const& addr = ep.address();
asio::error_code ec;
std::string a = addr.to_string(ec);
if (ec) return os;
if (addr.is_v6())
os << "[" << a << "]:";
else
os << a << ":";
os << ep.port();
return os;
}
namespace detail
{
template<class OutIt>
void write_address(address const& a, OutIt& out)
{
if (a.is_v4())
{
write_uint32(a.to_v4().to_ulong(), out);
}
else if (a.is_v6())
{
asio::ip::address_v6::bytes_type bytes
= a.to_v6().to_bytes();
std::copy(bytes.begin(), bytes.end(), out);
}
}
template<class InIt>
address read_v4_address(InIt& in)
{
unsigned long ip = read_uint32(in);
return asio::ip::address_v4(ip);
}
template<class InIt>
address read_v6_address(InIt& in)
{
typedef asio::ip::address_v6::bytes_type bytes_t;
bytes_t bytes;
for (bytes_t::iterator i = bytes.begin()
, end(bytes.end()); i != end; ++i)
*i = read_uint8(in);
return asio::ip::address_v6(bytes);
}
template<class Endpoint, class OutIt>
void write_endpoint(Endpoint const& e, OutIt& out)
{
write_address(e.address(), out);
write_uint16(e.port(), out);
}
template<class Endpoint, class InIt>
Endpoint read_v4_endpoint(InIt& in)
{
address addr = read_v4_address(in);
int port = read_uint16(in);
return Endpoint(addr, port);
}
template<class Endpoint, class InIt>
Endpoint read_v6_endpoint(InIt& in)
{
address addr = read_v6_address(in);
int port = read_uint16(in);
return Endpoint(addr, port);
}
}
struct v6only
{
v6only(bool enable): m_value(enable) {}
template<class Protocol>
int level(Protocol const&) const { return IPPROTO_IPV6; }
template<class Protocol>
int name(Protocol const&) const { return IPV6_V6ONLY; }
template<class Protocol>
int const* data(Protocol const&) const { return &m_value; }
template<class Protocol>
size_t size(Protocol const&) const { return sizeof(m_value); }
int m_value;
};
}
#endif // TORRENT_SOCKET_HPP_INCLUDED
| 26.927835
| 79
| 0.723966
|
importlib
|
90d288af6571d1f98c014630d861f60ffb33678a
| 11,628
|
cc
|
C++
|
pyxel/core/src/pyxelcore.cc
|
nnn1590/pyxel
|
fa1c5748f1e76d137fe157619584eadfbe0d45e7
|
[
"MIT"
] | null | null | null |
pyxel/core/src/pyxelcore.cc
|
nnn1590/pyxel
|
fa1c5748f1e76d137fe157619584eadfbe0d45e7
|
[
"MIT"
] | null | null | null |
pyxel/core/src/pyxelcore.cc
|
nnn1590/pyxel
|
fa1c5748f1e76d137fe157619584eadfbe0d45e7
|
[
"MIT"
] | null | null | null |
#include "pyxelcore.h"
#include "pyxelcore/audio.h"
#include "pyxelcore/graphics.h"
#include "pyxelcore/image.h"
#include "pyxelcore/input.h"
#include "pyxelcore/music.h"
#include "pyxelcore/resource.h"
#include "pyxelcore/sound.h"
#include "pyxelcore/system.h"
#include "pyxelcore/tilemap.h"
#define IMAGE reinterpret_cast<pyxelcore::Image*>(self)
#define TILEMAP reinterpret_cast<pyxelcore::Tilemap*>(self)
#define SOUND reinterpret_cast<pyxelcore::Sound*>(self)
#define MUSIC reinterpret_cast<pyxelcore::Music*>(self)
static pyxelcore::System* s_system = NULL;
static pyxelcore::Resource* s_resource = NULL;
static pyxelcore::Input* s_input = NULL;
static pyxelcore::Graphics* s_graphics = NULL;
static pyxelcore::Audio* s_audio = NULL;
//
// Constants
//
int32_t _get_constant_number(const char* name) {
return pyxelcore::GetConstantNumber(name);
}
void _get_constant_string(char* str, int32_t str_length, const char* name) {
strncpy(str, pyxelcore::GetConstantString(name).c_str(), str_length);
}
//
// System
//
int32_t width_getter() {
return s_system->Width();
}
int32_t height_getter() {
return s_system->Height();
}
int32_t frame_count_getter() {
return s_system->FrameCount();
}
void init(int32_t width,
int32_t height,
const char* caption,
int32_t scale,
const int32_t* palette,
int32_t fps,
int32_t border_width,
int32_t border_color) {
std::array<int32_t, pyxelcore::COLOR_COUNT> palette_color;
for (int32_t i = 0; i < pyxelcore::COLOR_COUNT; i++) {
palette_color[i] = palette[i];
}
s_system =
new pyxelcore::System(width, height, std::string(caption), scale,
palette_color, fps, border_width, border_color);
s_resource = s_system->Resource();
s_input = s_system->Input();
s_graphics = s_system->Graphics();
s_audio = s_system->Audio();
}
void run(void (*update)(), void (*draw)()) {
s_system->Run(update, draw);
}
void quit() {
s_system->Quit();
}
void flip() {
s_system->FlipScreen();
}
void show() {
s_system->ShowScreen();
}
void _drop_file_getter(char* str, int32_t str_length) {
strncpy(str, s_system->DropFile().c_str(), str_length);
}
void _caption(const char* caption) {
s_system->SetCaption(caption);
}
//
// Resource
//
void save(const char* filename) {
s_resource->SaveAsset(filename);
}
void load(const char* filename) {
s_resource->LoadAsset(filename);
}
//
// Input
//
int32_t mouse_x_getter() {
return s_input->MouseX();
}
int32_t mouse_y_getter() {
return s_input->MouseY();
}
int32_t btn(int32_t key) {
return s_input->IsButtonOn(key);
}
int32_t btnp(int32_t key, int32_t hold, int32_t period) {
return s_input->IsButtonPressed(key, hold, period);
}
int32_t btnr(int32_t key) {
return s_input->IsButtonReleased(key);
}
void mouse(int32_t visible) {
return s_input->SetMouseVisible(visible);
}
//
// Graphics
//
void* image(int32_t img, int32_t system) {
return s_graphics->GetImageBank(img, system);
}
void* tilemap(int32_t tm) {
return s_graphics->GetTilemapBank(tm);
}
void clip0() {
s_graphics->ResetClipArea();
}
void clip(int32_t x, int32_t y, int32_t w, int32_t h) {
s_graphics->SetClipArea(x, y, w, h);
}
void pal0() {
s_graphics->ResetPalette();
}
void pal(int32_t col1, int32_t col2) {
s_graphics->SetPalette(col1, col2);
}
void cls(int32_t col) {
s_graphics->ClearScreen(col);
}
void pix(int32_t x, int32_t y, int32_t col) {
s_graphics->DrawPoint(x, y, col);
}
void line(int32_t x1, int32_t y1, int32_t x2, int32_t y2, int32_t col) {
s_graphics->DrawLine(x1, y1, x2, y2, col);
}
void rect(int32_t x, int32_t y, int32_t w, int32_t h, int32_t col) {
s_graphics->DrawRectangle(x, y, w, h, col);
}
void rectb(int32_t x, int32_t y, int32_t w, int32_t h, int32_t col) {
s_graphics->DrawRectangleBorder(x, y, w, h, col);
}
void circ(int32_t x, int32_t y, int32_t r, int32_t col) {
s_graphics->DrawCircle(x, y, r, col);
}
void circb(int32_t x, int32_t y, int32_t r, int32_t col) {
s_graphics->DrawCircleBorder(x, y, r, col);
}
void blt(int32_t x,
int32_t y,
int32_t img,
int32_t u,
int32_t v,
int32_t w,
int32_t h,
int32_t colkey) {
s_graphics->DrawImage(x, y, img, u, v, w, h, colkey);
}
void bltm(int32_t x,
int32_t y,
int32_t tm,
int32_t u,
int32_t v,
int32_t w,
int32_t h,
int32_t colkey) {
s_graphics->DrawTilemap(x, y, tm, u, v, w, h, colkey);
}
void text(int32_t x, int32_t y, const char* s, int32_t col) {
s_graphics->DrawText(x, y, s, col);
}
//
// Audio
//
void* sound(int32_t snd, int32_t system) {
return s_audio->GetSoundBank(snd, system);
}
void* music(int32_t msc) {
return s_audio->GetMusicBank(msc);
}
int32_t play_pos(int32_t ch) {
return s_audio->GetPlayPos(ch);
}
void play1(int32_t ch, int32_t snd, int32_t loop) {
s_audio->PlaySound(ch, snd, loop);
}
void play(int32_t ch, int32_t* snd, int32_t snd_length, int32_t loop) {
pyxelcore::SoundIndexList sound_index_list;
for (int32_t i = 0; i < snd_length; i++) {
sound_index_list.push_back(snd[i]);
}
s_audio->PlaySound(ch, sound_index_list, loop);
}
void playm(int32_t msc, int32_t loop) {
s_audio->PlayMusic(msc, loop);
}
void stop(int32_t ch) {
s_audio->StopPlaying(ch);
}
//
// Image class
//
int32_t image_width_getter(void* self) {
return IMAGE->Width();
}
int32_t image_height_getter(void* self) {
return IMAGE->Height();
}
int32_t** image_data_getter(void* self) {
return IMAGE->Data();
}
int32_t image_get(void* self, int32_t x, int32_t y) {
return IMAGE->GetValue(x, y);
}
void image_set1(void* self, int32_t x, int32_t y, int32_t data) {
IMAGE->SetValue(x, y, data);
}
void image_set(void* self,
int32_t x,
int32_t y,
const char** data,
int32_t data_length) {
pyxelcore::ImageString image_string;
for (int32_t i = 0; i < data_length; i++) {
image_string.push_back(data[i]);
}
IMAGE->SetData(x, y, image_string);
}
void image_load(void* self, int32_t x, int32_t y, const char* filename) {
IMAGE->LoadImage(x, y, filename, s_system->PaletteColor());
}
void image_copy(void* self,
int32_t x,
int32_t y,
int32_t img,
int32_t u,
int32_t v,
int32_t w,
int32_t h) {
IMAGE->CopyImage(x, y, s_graphics->GetImageBank(img, true), u, v, w, h);
}
//
// Tilemap class
//
int32_t tilemap_width_getter(void* self) {
return TILEMAP->Width();
}
int32_t tilemap_height_getter(void* self) {
return TILEMAP->Height();
}
int32_t** tilemap_data_getter(void* self) {
return TILEMAP->Data();
}
int32_t tilemap_refimg_getter(void* self) {
return TILEMAP->ImageIndex();
}
void tilemap_refimg_setter(void* self, int32_t refimg) {
TILEMAP->ImageIndex(refimg);
}
int32_t tilemap_get(void* self, int32_t x, int32_t y) {
return TILEMAP->GetValue(x, y);
}
void tilemap_set1(void* self, int32_t x, int32_t y, int32_t data) {
TILEMAP->SetValue(x, y, data);
}
void tilemap_set(void* self,
int32_t x,
int32_t y,
const char** data,
int32_t data_length) {
pyxelcore::TilemapString tilemap_string;
for (int32_t i = 0; i < data_length; i++) {
tilemap_string.push_back(data[i]);
}
TILEMAP->SetData(x, y, tilemap_string);
}
void tilemap_copy(void* self,
int32_t x,
int32_t y,
int32_t tm,
int32_t u,
int32_t v,
int32_t w,
int32_t h) {
return TILEMAP->CopyTilemap(x, y, s_graphics->GetTilemapBank(tm), u, v, w, h);
}
//
// Sound class
//
int32_t* sound_note_getter(void* self) {
return SOUND->Note().data();
}
int32_t sound_note_length_getter(void* self) {
return SOUND->Note().size();
}
void sound_note_length_setter(void* self, int32_t length) {
SOUND->Note().resize(length);
}
int32_t* sound_tone_getter(void* self) {
return SOUND->Tone().data();
}
int32_t sound_tone_length_getter(void* self) {
return SOUND->Tone().size();
}
void sound_tone_length_setter(void* self, int32_t length) {
SOUND->Tone().resize(length);
}
int32_t* sound_volume_getter(void* self) {
return SOUND->Volume().data();
}
int32_t sound_volume_length_getter(void* self) {
return SOUND->Volume().size();
}
void sound_volume_length_setter(void* self, int32_t length) {
SOUND->Volume().resize(length);
}
int32_t* sound_effect_getter(void* self) {
return SOUND->Effect().data();
}
int32_t sound_effect_length_getter(void* self) {
return SOUND->Effect().size();
}
void sound_effect_length_setter(void* self, int32_t length) {
SOUND->Effect().resize(length);
}
int32_t sound_speed_getter(void* self) {
return SOUND->Speed();
}
void sound_speed_setter(void* self, int32_t speed) {
SOUND->Speed(speed);
}
void sound_set(void* self,
const char* note,
const char* tone,
const char* volume,
const char* effect,
int32_t speed) {
SOUND->Set(note, tone, volume, effect, speed);
}
void sound_set_note(void* self, const char* note) {
SOUND->SetNote(note);
}
void sound_set_tone(void* self, const char* tone) {
SOUND->SetTone(tone);
}
void sound_set_volume(void* self, const char* volume) {
SOUND->SetVolume(volume);
}
void sound_set_effect(void* self, const char* effect) {
SOUND->SetEffect(effect);
}
//
// Music class
//
int32_t* music_ch0_getter(void* self) {
return MUSIC->Channel0().data();
}
int32_t music_ch0_length_getter(void* self) {
return MUSIC->Channel0().size();
}
void music_ch0_length_setter(void* self, int32_t length) {
MUSIC->Channel0().resize(length);
}
int32_t* music_ch1_getter(void* self) {
return MUSIC->Channel1().data();
}
int32_t music_ch1_length_getter(void* self) {
return MUSIC->Channel1().size();
}
void music_ch1_length_setter(void* self, int32_t length) {
MUSIC->Channel1().resize(length);
}
int32_t* music_ch2_getter(void* self) {
return MUSIC->Channel2().data();
}
int32_t music_ch2_length_getter(void* self) {
return MUSIC->Channel2().size();
}
void music_ch2_length_setter(void* self, int32_t length) {
MUSIC->Channel2().resize(length);
}
int32_t* music_ch3_getter(void* self) {
return MUSIC->Channel3().data();
}
int32_t music_ch3_length_getter(void* self) {
return MUSIC->Channel3().size();
}
void music_ch3_length_setter(void* self, int32_t length) {
MUSIC->Channel3().resize(length);
}
void music_set(void* self,
const int32_t* ch0,
int32_t ch0_length,
const int32_t* ch1,
int32_t ch1_length,
const int32_t* ch2,
int32_t ch2_length,
const int32_t* ch3,
int32_t ch3_length) {
pyxelcore::SoundIndexList sound_index_list0;
for (int32_t i = 0; i < ch0_length; i++) {
sound_index_list0.push_back(ch0[i]);
}
pyxelcore::SoundIndexList sound_index_list1;
for (int32_t i = 0; i < ch1_length; i++) {
sound_index_list1.push_back(ch1[i]);
}
pyxelcore::SoundIndexList sound_index_list2;
for (int32_t i = 0; i < ch2_length; i++) {
sound_index_list2.push_back(ch2[i]);
}
pyxelcore::SoundIndexList sound_index_list3;
for (int32_t i = 0; i < ch3_length; i++) {
sound_index_list3.push_back(ch3[i]);
}
MUSIC->Set(sound_index_list0, sound_index_list1, sound_index_list2,
sound_index_list3);
}
| 22.19084
| 80
| 0.659013
|
nnn1590
|
90d37359d2d67674cff2dfbcec9d4f03602ef5e4
| 4,278
|
cpp
|
C++
|
SDKs/CryCode/3.8.1/CryEngine/CryEntitySystem/EntityAttributesProxy.cpp
|
amrhead/FireNET
|
34d439aa0157b0c895b20b2b664fddf4f9b84af1
|
[
"BSD-2-Clause"
] | 4
|
2017-12-18T20:10:16.000Z
|
2021-02-07T21:21:24.000Z
|
SDKs/CryCode/3.7.0/CryEngine/CryEntitySystem/EntityAttributesProxy.cpp
|
amrhead/FireNET
|
34d439aa0157b0c895b20b2b664fddf4f9b84af1
|
[
"BSD-2-Clause"
] | null | null | null |
SDKs/CryCode/3.7.0/CryEngine/CryEntitySystem/EntityAttributesProxy.cpp
|
amrhead/FireNET
|
34d439aa0157b0c895b20b2b664fddf4f9b84af1
|
[
"BSD-2-Clause"
] | 3
|
2019-03-11T21:36:15.000Z
|
2021-02-07T21:21:26.000Z
|
#include "stdafx.h"
#include "EntityAttributesProxy.h"
#include "Serialization/IArchive.h"
#include "Serialization/IArchiveHost.h"
namespace
{
struct SEntityAttributesSerializer
{
SEntityAttributesSerializer(TEntityAttributeArray& _attributes)
: attributes(_attributes)
{}
void Serialize(Serialization::IArchive& archive)
{
for(size_t iAttribute = 0, attributeCount = attributes.size(); iAttribute < attributeCount; ++ iAttribute)
{
IEntityAttribute* pAttribute = attributes[iAttribute].get();
if(pAttribute != NULL)
{
archive(*pAttribute, pAttribute->GetName(), pAttribute->GetLabel());
}
}
}
TEntityAttributeArray& attributes;
};
}
//////////////////////////////////////////////////////////////////////////
void CEntityAttributesProxy::ProcessEvent(SEntityEvent& event) {}
//////////////////////////////////////////////////////////////////////////
void CEntityAttributesProxy::Initialize(SComponentInitializer const& inititializer) {}
//////////////////////////////////////////////////////////////////////////
EEntityProxy CEntityAttributesProxy::GetType()
{
return ENTITY_PROXY_ATTRIBUTES;
}
//////////////////////////////////////////////////////////////////////////
void CEntityAttributesProxy::Release()
{
delete this;
}
//////////////////////////////////////////////////////////////////////////
void CEntityAttributesProxy::Done() {}
//////////////////////////////////////////////////////////////////////////
void CEntityAttributesProxy::Update(SEntityUpdateContext& context) {}
//////////////////////////////////////////////////////////////////////////
bool CEntityAttributesProxy::Init(IEntity* pEntity, SEntitySpawnParams& params)
{
if(m_attributes.empty() == true)
{
EntityAttributeUtils::CloneAttributes(params.pClass->GetEntityAttributes(), m_attributes);
}
return true;
}
//////////////////////////////////////////////////////////////////////////
void CEntityAttributesProxy::Reload(IEntity* pEntity, SEntitySpawnParams& params) {}
//////////////////////////////////////////////////////////////////////////
void CEntityAttributesProxy::SerializeXML(XmlNodeRef &entityNodeXML, bool loading)
{
if(loading == true)
{
if(XmlNodeRef attributesNodeXML = entityNodeXML->findChild("Attributes"))
{
SEntityAttributesSerializer serializer(m_attributes);
Serialization::LoadXmlNode(serializer, attributesNodeXML);
}
}
else
{
if(!m_attributes.empty())
{
SEntityAttributesSerializer serializer(m_attributes);
if(XmlNodeRef attributesNodeXML = Serialization::SaveXmlNode(serializer, "Attributes"))
{
entityNodeXML->addChild(attributesNodeXML);
}
}
}
}
//////////////////////////////////////////////////////////////////////////
void CEntityAttributesProxy::Serialize(TSerialize serialize) {}
//////////////////////////////////////////////////////////////////////////
bool CEntityAttributesProxy::NeedSerialize()
{
return false;
}
//////////////////////////////////////////////////////////////////////////
bool CEntityAttributesProxy::GetSignature(TSerialize signature)
{
return true;
}
//////////////////////////////////////////////////////////////////////////
void CEntityAttributesProxy::GetMemoryUsage(ICrySizer* pSizer) const
{
pSizer->AddObject(this, sizeof(*this));
}
//////////////////////////////////////////////////////////////////////////
void CEntityAttributesProxy::SetAttributes(const TEntityAttributeArray& attributes)
{
const size_t attributeCount = attributes.size();
m_attributes.resize(attributeCount);
for(size_t iAttribute = 0; iAttribute < attributeCount; ++ iAttribute)
{
IEntityAttribute* pSrc = attributes[iAttribute].get();
IEntityAttribute* pDst = m_attributes[iAttribute].get();
if((pDst != NULL) && (strcmp(pSrc->GetName(), pDst->GetName()) == 0))
{
Serialization::CloneBinary(*pDst, *pSrc);
}
else if(pSrc != NULL)
{
m_attributes[iAttribute] = pSrc->Clone();
}
}
}
//////////////////////////////////////////////////////////////////////////
TEntityAttributeArray& CEntityAttributesProxy::GetAttributes()
{
return m_attributes;
}
//////////////////////////////////////////////////////////////////////////
const TEntityAttributeArray& CEntityAttributesProxy::GetAttributes() const
{
return m_attributes;
}
| 29.708333
| 109
| 0.544647
|
amrhead
|
90d49e3ae32010fb49ec8e2a8d41b7d434131e69
| 30,420
|
cp
|
C++
|
MacOS/Sources/Application/Search/CSearchCriteriaLocal.cp
|
mulberry-mail/mulberry4-client
|
cdaae15c51dd759110b4fbdb2063d0e3d5202103
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
MacOS/Sources/Application/Search/CSearchCriteriaLocal.cp
|
mulberry-mail/mulberry4-client
|
cdaae15c51dd759110b4fbdb2063d0e3d5202103
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
MacOS/Sources/Application/Search/CSearchCriteriaLocal.cp
|
mulberry-mail/mulberry4-client
|
cdaae15c51dd759110b4fbdb2063d0e3d5202103
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
/*
Copyright (c) 2007 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 CSearchCriteriaLocal class
#include "CSearchCriteriaLocal.h"
#include "CDateControl.h"
#include "CFilterItem.h"
#include "CMulberryCommon.h"
#include "CPreferences.h"
#include "CRFC822.h"
#include "CSearchCriteriaContainer.h"
#include "CSearchStyle.h"
#include "CTextFieldX.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
// Menu items
enum
{
eCriteria_From = 1,
eCriteria_To,
eCriteria_CC,
eCriteria_Bcc,
eCriteria_Recipient,
eCriteria_Correspondent,
eCriteria_Sender,
eCriteria_DateSent,
eCriteria_DateReceived,
eCriteria_Subject,
eCriteria_Body,
eCriteria_Header,
eCriteria_Text,
eCriteria_Size,
eCriteria_Separator1,
eCriteria_Recent,
eCriteria_Seen,
eCriteria_Answered,
eCriteria_Flagged,
eCriteria_Deleted,
eCriteria_Draft,
eCriteria_Separator2,
eCriteria_Label1,
eCriteria_Label2,
eCriteria_Label3,
eCriteria_Label4,
eCriteria_Label5,
eCriteria_Label6,
eCriteria_Label7,
eCriteria_Label8,
eCriteria_Separator3,
eCriteria_Group,
eCriteria_Separator4,
eCriteria_SearchSet,
eCriteria_Separator5,
eCriteria_All,
eCriteria_Selected
};
enum
{
eAddressMethod_Contains = 1,
eAddressMethod_NotContains,
eAddressMethod_IsMe,
eAddressMethod_IsNotMe
};
enum
{
eDateMethod_Before = 1,
eDateMethod_On,
eDateMethod_After,
eDateMethod_Separator1,
eDateMethod_Is,
eDateMethod_IsNot,
eDateMethod_IsWithin,
eDateMethod_IsNotWithin
};
enum
{
eDateRelMethod_SentToday = 1,
eDateRelMethod_SentYesterday,
eDateRelMethod_SentWeek,
eDateRelMethod_Sent7Days,
eDateRelMethod_SentMonth,
eDateRelMethod_SentYear
};
enum
{
eDateWithin_Days = 1,
eDateWithin_Weeks,
eDateWithin_Months,
eDateWithin_Years
};
enum
{
eTextMethod_Contains = 1,
eTextMethod_NotContains
};
enum
{
eSizeMethod_Larger = 1,
eSizeMethod_Smaller
};
enum
{
eFlagMethod_Set = 1,
eFlagMethod_NotSet
};
enum
{
eSize_Bytes = 1,
eSize_KBytes,
eSize_MBytes
};
enum
{
eSearchSetMethod_Is = 1,
eSearchSetMethod_IsNot
};
enum
{
eMode_Or = 1,
eMode_And
};
// Default constructor
CSearchCriteriaLocal::CSearchCriteriaLocal()
{
}
// Constructor from stream
CSearchCriteriaLocal::CSearchCriteriaLocal(LStream *inStream)
: CSearchCriteria(inStream)
{
}
// Default destructor
CSearchCriteriaLocal::~CSearchCriteriaLocal()
{
}
// O T H E R M E T H O D S ____________________________________________________________________________
// Get details of sub-panes
void CSearchCriteriaLocal::FinishCreateSelf(void)
{
// Do inherited
CSearchCriteria::FinishCreateSelf();
// Get controls
mPopup1 = (LPopupButton*) FindPaneByID(paneid_SearchCriteriaPopup1);
mPopup2 = (LPopupButton*) FindPaneByID(paneid_SearchCriteriaPopup2);
mPopup3 = (LPopupButton*) FindPaneByID(paneid_SearchCriteriaPopup3);
mPopup4 = (LPopupButton*) FindPaneByID(paneid_SearchCriteriaPopup4);
mPopup5 = (LPopupButton*) FindPaneByID(paneid_SearchCriteriaPopup5);
mPopup6 = (LPopupButton*) FindPaneByID(paneid_SearchCriteriaPopup6);
mPopup7 = (LPopupButton*) FindPaneByID(paneid_SearchCriteriaPopup7);
mPopup8 = (LPopupButton*) FindPaneByID(paneid_SearchCriteriaPopup8);
mText1 = (CTextFieldX*) FindPaneByID(paneid_SearchCriteriaText1);
mText2 = (CTextFieldX*) FindPaneByID(paneid_SearchCriteriaText2);
mText3 = (CTextFieldX*) FindPaneByID(paneid_SearchCriteriaText3);
mDate = (CDateControl*) FindPaneByID(paneid_SearchCriteriaDate);
InitLabelNames();
// Link controls to this window
UReanimator::LinkListenerToBroadcasters(this,this,RidL_CSearchCriteriaLocalBtns);
}
// Handle buttons
void CSearchCriteriaLocal::ListenToMessage(
MessageT inMessage,
void *ioParam)
{
switch (inMessage)
{
case msg_SearchCriteriaPopup1:
OnSetCriteria(*(long*) ioParam);
break;
case msg_SearchCriteriaPopup2:
OnSetMethod(*(long*) ioParam);
break;
default:
CSearchCriteria::ListenToMessage(inMessage, ioParam);
break;
}
}
void CSearchCriteriaLocal::SetRules(bool rules)
{
mRules = rules;
// Remove select item from popup if not rules
if (!mRules)
{
mPopup1->DeleteMenuItem(eCriteria_Selected);
}
}
bool CSearchCriteriaLocal::DoActivate()
{
CTextFieldX* activate = NULL;
if (mText2->IsVisible())
activate = mText2;
else if (mText1->IsVisible())
activate = mText1;
else if (mText3->IsVisible())
activate = mText3;
if (activate)
{
activate->GetSuperCommander()->SetLatentSub(activate);
LCommander::SwitchTarget(activate);
activate->SelectAll();
return true;
}
else
return false;
}
long CSearchCriteriaLocal::ShowOrAnd(bool show)
{
if (show)
mPopup4->Show();
else
mPopup4->Hide();
return 0;
}
bool CSearchCriteriaLocal::IsOr() const
{
return (mPopup4->GetValue() == eMode_Or);
}
void CSearchCriteriaLocal::SetOr(bool use_or)
{
mPopup4->SetValue(use_or ? eMode_Or : eMode_And);
}
void CSearchCriteriaLocal::OnSetCriteria(long item1)
{
// Set popup menu for method and show/hide text field as approriate
bool method_refresh = false;
switch(item1)
{
case eCriteria_From:
case eCriteria_To:
case eCriteria_CC:
case eCriteria_Bcc:
case eCriteria_Recipient:
case eCriteria_Correspondent:
case eCriteria_Sender:
if (mPopup2->GetMenuID() != MENU_SearchAddressCriteria)
{
mPopup2->SetMenuID(MENU_SearchAddressCriteria);
mPopup2->SetValue(1);
}
mPopup2->Show();
mPopup2->Refresh();
method_refresh = true;
mPopup3->Hide();
mText1->Show();
mText2->Hide();
mText3->Hide();
mDate->Hide();
mPopup5->Hide();
mPopup6->Hide();
mPopup7->Hide();
mPopup8->Hide();
break;
case eCriteria_DateSent:
case eCriteria_DateReceived:
if (mPopup2->GetMenuID() != MENU_SearchDateCriteria)
{
mPopup2->SetMenuID(MENU_SearchDateCriteria);
mPopup2->SetValue(1);
}
mPopup2->Show();
mPopup2->Refresh();
method_refresh = true;
mPopup3->Hide();
mText1->Hide();
mText2->Hide();
mText3->Hide();
mDate->Show();
mPopup5->Hide();
mPopup6->Hide();
mPopup7->Hide();
mPopup8->Hide();
break;
case eCriteria_Subject:
case eCriteria_Body:
case eCriteria_Text:
if (mPopup2->GetMenuID() != MENU_SearchTestCriteria)
{
mPopup2->SetMenuID(MENU_SearchTestCriteria);
mPopup2->SetValue(1);
}
mPopup2->Show();
mPopup2->Refresh();
method_refresh = true;
mPopup3->Hide();
mText1->Show();
mText2->Hide();
mText3->Hide();
mDate->Hide();
mPopup5->Hide();
mPopup6->Hide();
mPopup7->Hide();
mPopup8->Hide();
break;
case eCriteria_Header:
mText2->SetText(cdstring::null_str);
mPopup2->Hide();
mPopup3->Hide();
mText1->Show();
mText2->Show();
mText3->Hide();
mDate->Hide();
mPopup5->Hide();
mPopup6->Hide();
mPopup7->Hide();
mPopup8->Hide();
break;
case eCriteria_Size:
if (mPopup2->GetMenuID() != MENU_SearchSizeCriteria)
{
mPopup2->SetMenuID(MENU_SearchSizeCriteria);
mPopup2->SetValue(1);
}
mPopup2->Show();
mPopup2->Refresh();
method_refresh = true;
mPopup3->Show();
mText1->Hide();
mText2->Hide();
mText3->Show();
mDate->Hide();
mPopup5->Hide();
mPopup6->Hide();
mPopup7->Hide();
mPopup8->Hide();
break;
case eCriteria_Recent:
case eCriteria_Seen:
case eCriteria_Answered:
case eCriteria_Flagged:
case eCriteria_Deleted:
case eCriteria_Draft:
case eCriteria_Label1:
case eCriteria_Label2:
case eCriteria_Label3:
case eCriteria_Label4:
case eCriteria_Label5:
case eCriteria_Label6:
case eCriteria_Label7:
case eCriteria_Label8:
if (mPopup2->GetMenuID() != MENU_SearchFlagCriteria)
{
mPopup2->SetMenuID(MENU_SearchFlagCriteria);
mPopup2->SetValue(1);
}
mText1->SetText(cdstring::null_str);
mPopup2->Show();
mPopup2->Refresh();
method_refresh = true;
mPopup3->Hide();
mText1->Hide();
mText2->Hide();
mText3->Hide();
mDate->Hide();
mPopup5->Hide();
mPopup6->Hide();
mPopup7->Hide();
mPopup8->Hide();
break;
case eCriteria_SearchSet:
mPopup2->Hide();
method_refresh = true;
mPopup3->Hide();
mText1->Hide();
mText2->Hide();
mText3->Hide();
mDate->Hide();
mPopup5->Hide();
mPopup6->Hide();
InitSearchSets();
mPopup7->Show();
mPopup8->Show();
break;
case eCriteria_Group:
case eCriteria_All:
case eCriteria_Selected:
mPopup2->Hide();
mPopup3->Hide();
mText1->Hide();
mText2->Hide();
mText3->Hide();
mDate->Hide();
mPopup5->Hide();
mPopup6->Hide();
mPopup7->Hide();
mPopup8->Hide();
break;
}
// Special for group display
if (item1 == eCriteria_Group)
MakeGroup(CFilterItem::eLocal);
else
RemoveGroup();
// Refresh method for new criteria
if (method_refresh)
OnSetMethod(mPopup2->GetValue());
}
void CSearchCriteriaLocal::OnSetMethod(long item)
{
// Show/hide text field as appropriate
switch(mPopup1->GetValue())
{
case eCriteria_From:
case eCriteria_To:
case eCriteria_CC:
case eCriteria_Bcc:
case eCriteria_Recipient:
case eCriteria_Correspondent:
case eCriteria_Sender:
switch(item)
{
case eAddressMethod_Contains:
case eAddressMethod_NotContains:
mText1->Show();
break;
case eAddressMethod_IsMe:
case eAddressMethod_IsNotMe:
mText1->Hide();
mText1->SetText(cdstring::null_str);
break;
}
break;
case eCriteria_DateSent:
case eCriteria_DateReceived:
switch(item)
{
case eDateMethod_Before:
case eDateMethod_On:
case eDateMethod_After:
mText3->Hide();
mDate->Show();
mPopup5->Hide();
mPopup6->Hide();
break;
case eDateMethod_Is:
case eDateMethod_IsNot:
mText3->Hide();
mDate->Hide();
mPopup5->Show();
mPopup6->Hide();
break;
case eDateMethod_IsWithin:
case eDateMethod_IsNotWithin:
mText3->Show();
mDate->Hide();
mPopup5->Hide();
mPopup6->Show();
break;
}
break;
default:
break;
}
}
void CSearchCriteriaLocal::InitLabelNames()
{
// Change name of labels
for(short i = eCriteria_Label1; i < eCriteria_Label1 + NMessage::eMaxLabels; i++)
{
::SetMenuItemTextUTF8(mPopup1->GetMacMenuH(), i, CPreferences::sPrefs->mLabels.GetValue()[i - eCriteria_Label1]->name);
}
}
void CSearchCriteriaLocal::InitSearchSets()
{
// Remove any existing items from main menu
short num_menu = ::CountMenuItems(mPopup7->GetMacMenuH());
for(short i = 1; i <= num_menu; i++)
::DeleteMenuItem(mPopup7->GetMacMenuH(), 1);
short index = 1;
for(CSearchStyleList::const_iterator iter = CPreferences::sPrefs->mSearchStyles.GetValue().begin();
iter != CPreferences::sPrefs->mSearchStyles.GetValue().end(); iter++, index++)
::AppendItemToMenu(mPopup7->GetMacMenuH(), index, (*iter)->GetName());
// Force max/min update
mPopup7->SetMenuMinMax();
mPopup7->SetValue(1);
mPopup7->Draw(NULL);
}
CSearchItem* CSearchCriteriaLocal::GetSearchItem() const
{
switch(mPopup1->GetValue())
{
case eCriteria_From:
return ParseAddress(CSearchItem::eFrom);
case eCriteria_To:
return ParseAddress(CSearchItem::eTo);
case eCriteria_CC:
return ParseAddress(CSearchItem::eCC);
case eCriteria_Bcc:
return ParseAddress(CSearchItem::eBcc);
case eCriteria_Recipient:
return ParseAddress(CSearchItem::eRecipient);
case eCriteria_Correspondent:
return ParseAddress(CSearchItem::eCorrespondent);
case eCriteria_Sender:
return ParseAddress(CSearchItem::eSender);
case eCriteria_DateSent:
return ParseDate(true);
case eCriteria_DateReceived:
return ParseDate(false);
case eCriteria_Subject:
return ParseText(CSearchItem::eSubject);
case eCriteria_Body:
return ParseText(CSearchItem::eBody);
case eCriteria_Text:
return ParseText(CSearchItem::eText);
case eCriteria_Header:
{
cdstring text1 = mText1->GetText();
cdstring text2 = mText2->GetText();
text2.trimspace();
// Strip trailing colon from header field
if (text2.compare_end(":"))
text2[text2.length() - 1] = 0;
// Look for '!' at start of header field as negate item
if (text2[0UL] == '!')
return new CSearchItem(CSearchItem::eNot, new CSearchItem(CSearchItem::eHeader, text2.c_str() + 1, text1));
else
return new CSearchItem(CSearchItem::eHeader, text2, text1);
}
case eCriteria_Size:
return ParseSize();
case eCriteria_Recent:
return ParseFlag(CSearchItem::eRecent, CSearchItem::eOld);
case eCriteria_Seen:
return ParseFlag(CSearchItem::eSeen, CSearchItem::eUnseen);
case eCriteria_Answered:
return ParseFlag(CSearchItem::eAnswered, CSearchItem::eUnanswered);
case eCriteria_Flagged:
return ParseFlag(CSearchItem::eFlagged, CSearchItem::eUnflagged);
case eCriteria_Deleted:
return ParseFlag(CSearchItem::eDeleted, CSearchItem::eUndeleted);
case eCriteria_Draft:
return ParseFlag(CSearchItem::eDraft, CSearchItem::eUndraft);
case eCriteria_Label1:
case eCriteria_Label2:
case eCriteria_Label3:
case eCriteria_Label4:
case eCriteria_Label5:
case eCriteria_Label6:
case eCriteria_Label7:
case eCriteria_Label8:
return ParseLabel(CSearchItem::eLabel, mPopup1->GetValue() - eCriteria_Label1);
case eCriteria_SearchSet:
{
cdstring style = ::GetPopupMenuItemTextUTF8(mPopup7);
const CSearchItem* found = CPreferences::sPrefs->mSearchStyles.GetValue().FindStyle(style)->GetSearchItem();
// May need to negate
if (mPopup8->GetValue() == eSearchSetMethod_Is)
return (found ? new CSearchItem(CSearchItem::eNamedStyle, style) : NULL);
else
return (found ? new CSearchItem(CSearchItem::eNot, new CSearchItem(CSearchItem::eNamedStyle, style)) : NULL);
}
case eCriteria_Group:
return mGroupItems->ConstructSearch();
case eCriteria_All:
return new CSearchItem(CSearchItem::eAll);
case eCriteria_Selected:
return new CSearchItem(CSearchItem::eSelected);
default:
return NULL;
}
}
CSearchItem* CSearchCriteriaLocal::ParseAddress(CSearchItem::ESearchType type) const
{
cdstring text = mText1->GetText();
switch(mPopup2->GetValue())
{
case eAddressMethod_Contains:
return new CSearchItem(type, text);
case eAddressMethod_NotContains:
return new CSearchItem(CSearchItem::eNot, new CSearchItem(type, text));
case eAddressMethod_IsMe:
return new CSearchItem(type);
case eAddressMethod_IsNotMe:
return new CSearchItem(CSearchItem::eNot, new CSearchItem(type));
default:
return NULL;
}
}
CSearchItem* CSearchCriteriaLocal::ParseDate(bool sent) const
{
switch(mPopup2->GetValue())
{
case eDateMethod_Before:
return new CSearchItem(sent ? CSearchItem::eSentBefore : CSearchItem::eBefore, mDate->GetDate());
case eDateMethod_On:
return new CSearchItem(sent ? CSearchItem::eSentOn : CSearchItem::eOn, mDate->GetDate());
case eDateMethod_After:
return new CSearchItem(sent ? CSearchItem::eSentSince : CSearchItem::eSince, mDate->GetDate());
// Look at relative date popup
case eDateMethod_Is:
case eDateMethod_IsNot:
{
bool is = (mPopup2->GetValue() == eDateMethod_Is);
// Set up types for different categories
CSearchItem::ESearchType typeToday = (sent ? CSearchItem::eSentOn : CSearchItem::eOn);
CSearchItem::ESearchType typeOther = (sent ? CSearchItem::eSentSince : CSearchItem::eSince);
CSearchItem::ESearchType typeNot = (sent ? CSearchItem::eSentBefore : CSearchItem::eBefore);
// Look at menu item chosen
switch(mPopup5->GetValue())
{
case eDateRelMethod_SentToday:
return new CSearchItem(is ? typeToday : typeNot, static_cast<unsigned long>(CSearchItem::eToday));
case eDateRelMethod_SentYesterday:
return new CSearchItem(is ? typeOther : typeNot, static_cast<unsigned long>(CSearchItem::eSinceYesterday));
case eDateRelMethod_SentWeek:
return new CSearchItem(is ? typeOther : typeNot, static_cast<unsigned long>(CSearchItem::eThisWeek));
case eDateRelMethod_Sent7Days:
return new CSearchItem(is ? typeOther : typeNot, static_cast<unsigned long>(CSearchItem::eWithin7Days));
case eDateRelMethod_SentMonth:
return new CSearchItem(is ? typeOther : typeNot, static_cast<unsigned long>(CSearchItem::eThisMonth));
case eDateRelMethod_SentYear:
return new CSearchItem(is ? typeOther : typeNot, static_cast<unsigned long>(CSearchItem::eThisYear));
default:
return NULL;
}
break;
}
// Look at relative date popup
case eDateMethod_IsWithin:
case eDateMethod_IsNotWithin:
{
bool is = (mPopup2->GetValue() == eDateMethod_IsWithin);
// Set up types for different categories
CSearchItem::ESearchType typeIs = (sent ? CSearchItem::eSentSince : CSearchItem::eSince);
CSearchItem::ESearchType typeIsNot = (sent ? CSearchItem::eSentBefore : CSearchItem::eBefore);
// Get numeric value
long size = mText3->GetNumber();
unsigned long within = (size > 0) ? size : 1;
if (within > 0x0000FFFF)
within = 0x0000FFFF;
// Look at menu item chosen
switch(mPopup6->GetValue())
{
case eDateWithin_Days:
return new CSearchItem(is ? typeIs : typeIsNot, static_cast<unsigned long>(CSearchItem::eWithinDays) | within);
case eDateWithin_Weeks:
return new CSearchItem(is ? typeIs : typeIsNot, static_cast<unsigned long>(CSearchItem::eWithinWeeks) | within);
case eDateWithin_Months:
return new CSearchItem(is ? typeIs : typeIsNot, static_cast<unsigned long>(CSearchItem::eWithinMonths) | within);
case eDateWithin_Years:
return new CSearchItem(is ? typeIs : typeIsNot, static_cast<unsigned long>(CSearchItem::eWithinYears) | within);
default:
return NULL;
}
break;
}
default:
return NULL;
}
}
CSearchItem* CSearchCriteriaLocal::ParseText(CSearchItem::ESearchType type) const
{
cdstring text = mText1->GetText();
if (mPopup2->GetValue() == eTextMethod_Contains)
return new CSearchItem(type, text);
else
return new CSearchItem(CSearchItem::eNot, new CSearchItem(type, text));
}
CSearchItem* CSearchCriteriaLocal::ParseSize() const
{
long size = mText3->GetNumber();
switch(mPopup3->GetValue())
{
case eSize_Bytes:
break;
case eSize_KBytes:
size *= 1024L;
break;
case eSize_MBytes:
size *= 1024L * 1024L;
break;
}
return new CSearchItem((mPopup2->GetValue() == eSizeMethod_Larger) ? CSearchItem::eLarger : CSearchItem::eSmaller, size);
}
CSearchItem* CSearchCriteriaLocal::ParseFlag(CSearchItem::ESearchType type1, CSearchItem::ESearchType type2) const
{
return new CSearchItem((mPopup2->GetValue() == eFlagMethod_Set) ? type1 : type2);
}
CSearchItem* CSearchCriteriaLocal::ParseLabel(CSearchItem::ESearchType type, unsigned long index) const
{
if (mPopup2->GetValue() == eFlagMethod_Set)
return new CSearchItem(type, index);
else
return new CSearchItem(CSearchItem::eNot, new CSearchItem(type, index));
}
void CSearchCriteriaLocal::SetSearchItem(const CSearchItem* spec, bool negate)
{
long popup1 = 1;
long popup2 = 1;
long popup3 = eSize_Bytes;
long popup5 = 1;
long popup6 = 1;
long popup7 = 1;
long popup8 = 1;
cdstring text1;
cdstring text2;
cdstring text3;
time_t date = ::time(NULL);
if (spec)
{
switch(spec->GetType())
{
case CSearchItem::eAll: // -
popup1 = eCriteria_All;
break;
case CSearchItem::eAnd: // CSearchItemList*
break;
case CSearchItem::eAnswered: // -
popup1 = eCriteria_Answered;
popup2 = eFlagMethod_Set;
break;
case CSearchItem::eBcc: // cdstring*
popup1 = eCriteria_Bcc;
if (spec->GetData())
text1 = *static_cast<const cdstring*>(spec->GetData());
popup2 = spec->GetData() ? (negate ? eAddressMethod_NotContains : eAddressMethod_Contains) :
(negate ? eAddressMethod_IsNotMe : eAddressMethod_IsMe);
break;
case CSearchItem::eBefore: // date
popup1 = eCriteria_DateReceived;
popup2 = GetDatePopup(spec, eDateMethod_Before, text1, text3, popup5, popup6);
date = reinterpret_cast<time_t>(spec->GetData());
break;
case CSearchItem::eBody: // cdstring*
popup1 = eCriteria_Body;
text1 = *static_cast<const cdstring*>(spec->GetData());
popup2 = negate ? eTextMethod_NotContains : eTextMethod_Contains;
break;
case CSearchItem::eCC: // cdstring*
popup1 = eCriteria_CC;
if (spec->GetData())
text1 = *static_cast<const cdstring*>(spec->GetData());
popup2 = spec->GetData() ? (negate ? eAddressMethod_NotContains : eAddressMethod_Contains) :
(negate ? eAddressMethod_IsNotMe : eAddressMethod_IsMe);
break;
case CSearchItem::eDeleted: // -
popup1 = eCriteria_Deleted;
popup2 = eFlagMethod_Set;
break;
case CSearchItem::eDraft: // -
popup1 = eCriteria_Draft;
popup2 = eFlagMethod_Set;
break;
case CSearchItem::eFlagged: // -
popup1 = eCriteria_Flagged;
popup2 = eFlagMethod_Set;
break;
case CSearchItem::eFrom: // cdstring*
popup1 = eCriteria_From;
if (spec->GetData())
text1 = *static_cast<const cdstring*>(spec->GetData());
popup2 = spec->GetData() ? (negate ? eAddressMethod_NotContains : eAddressMethod_Contains) :
(negate ? eAddressMethod_IsNotMe : eAddressMethod_IsMe);
break;
case CSearchItem::eGroup: // CSearchItemList*
popup1 = eCriteria_Group;
break;
case CSearchItem::eHeader: // cdstrpair*
popup1 = eCriteria_Header;
if (negate)
text2 = "!";
text2 += static_cast<const cdstrpair*>(spec->GetData())->first;
text1 = static_cast<const cdstrpair*>(spec->GetData())->second;
break;
case CSearchItem::eKeyword: // cdstring*
break;
case CSearchItem::eLabel: // unsigned long
{
unsigned long index = reinterpret_cast<unsigned long>(spec->GetData());
if (index >= NMessage::eMaxLabels)
index = 0;
popup1 = eCriteria_Label1 + index;
popup2 = negate ? eFlagMethod_NotSet : eFlagMethod_Set;
break;
}
case CSearchItem::eLarger: // long
popup1 = eCriteria_Size;
popup2 = eSizeMethod_Larger;
long size = reinterpret_cast<long>(spec->GetData());
if (size >= 1024L * 1024L)
{
size /= 1024L * 1024L;
popup3 = eSize_MBytes;
}
else if (size >= 1024L)
{
size /= 1024L;
popup3 = eSize_KBytes;
}
text3 = size;
break;
case CSearchItem::eNew: // -
break;
case CSearchItem::eNot: // CSearchItem*
// Do negated - can only be text based items
SetSearchItem(static_cast<const CSearchItem*>(spec->GetData()), true);
// Must exit now without changing any UI item since they have already been done
return;
case CSearchItem::eNumber: // ulvector* only - no key
break;
case CSearchItem::eOld: // -
popup1 = eCriteria_Recent;
popup2 = eFlagMethod_NotSet;
break;
case CSearchItem::eOn: // date
popup1 = eCriteria_DateReceived;
popup2 = GetDatePopup(spec, eDateMethod_On, text1, text3, popup5, popup6);
date = reinterpret_cast<time_t>(spec->GetData());
break;
case CSearchItem::eOr: // CSearchItemList*
break;
case CSearchItem::eRecent: // -
popup1 = eCriteria_Recent;
popup2 = eFlagMethod_Set;
break;
case CSearchItem::eSeen: // -
popup1 = eCriteria_Seen;
popup2 = eFlagMethod_Set;
break;
case CSearchItem::eSelected: // -
popup1 = eCriteria_Selected;
break;
case CSearchItem::eSentBefore: // date
popup1 = eCriteria_DateSent;
popup2 = GetDatePopup(spec, eDateMethod_Before, text1, text3, popup5, popup6);
date = reinterpret_cast<time_t>(spec->GetData());
break;
case CSearchItem::eSentOn: // date
popup1 = eCriteria_DateSent;
popup2 = GetDatePopup(spec, eDateMethod_On, text1, text3, popup5, popup6);
date = reinterpret_cast<time_t>(spec->GetData());
break;
case CSearchItem::eSentSince: // date
popup1 = eCriteria_DateSent;
popup2 = GetDatePopup(spec, eDateMethod_After, text1, text3, popup5, popup6);
date = reinterpret_cast<time_t>(spec->GetData());
break;
case CSearchItem::eSince: // date
popup1 = eCriteria_DateReceived;
popup2 = GetDatePopup(spec, eDateMethod_After, text1, text3, popup5, popup6);
date = reinterpret_cast<time_t>(spec->GetData());
break;
case CSearchItem::eSmaller: // long
popup1 = eCriteria_Size;
popup2 = eSizeMethod_Smaller;
size = reinterpret_cast<long>(spec->GetData());
if (size >= 1024L)
{
size /= 1024L;
popup3 = eSize_KBytes;
}
else if (size >= 1024L * 1024L)
{
size /= 1024L * 1024L;
popup3 = eSize_MBytes;
}
text3 = size;
break;
case CSearchItem::eSubject: // cdstring*
popup1 = eCriteria_Subject;
text1 = *static_cast<const cdstring*>(spec->GetData());
popup2 = negate ? eTextMethod_NotContains : eTextMethod_Contains;
break;
case CSearchItem::eText: // cdstring*
popup1 = eCriteria_Text;
text1 = *static_cast<const cdstring*>(spec->GetData());
popup2 = negate ? eTextMethod_NotContains : eTextMethod_Contains;
break;
case CSearchItem::eTo: // cdstring*
popup1 = eCriteria_To;
if (spec->GetData())
text1 = *static_cast<const cdstring*>(spec->GetData());
popup2 = spec->GetData() ? (negate ? eAddressMethod_NotContains : eAddressMethod_Contains) :
(negate ? eAddressMethod_IsNotMe : eAddressMethod_IsMe);
break;
case CSearchItem::eUID: // ulvector*
break;
case CSearchItem::eUnanswered: // -
popup1 = eCriteria_Answered;
popup2 = eFlagMethod_NotSet;
break;
case CSearchItem::eUndeleted: // -
popup1 = eCriteria_Deleted;
popup2 = eFlagMethod_NotSet;
break;
case CSearchItem::eUndraft: // -
popup1 = eCriteria_Draft;
popup2 = eFlagMethod_NotSet;
break;
case CSearchItem::eUnflagged: // -
popup1 = eCriteria_Flagged;
popup2 = eFlagMethod_NotSet;
break;
case CSearchItem::eUnkeyword: // cdstring*
break;
case CSearchItem::eUnseen: // -
popup1 = eCriteria_Seen;
popup2 = eFlagMethod_NotSet;
break;
case CSearchItem::eRecipient: // cdstring*
popup1 = eCriteria_Recipient;
if (spec->GetData())
text1 = *static_cast<const cdstring*>(spec->GetData());
popup2 = spec->GetData() ? (negate ? eAddressMethod_NotContains : eAddressMethod_Contains) :
(negate ? eAddressMethod_IsNotMe : eAddressMethod_IsMe);
break;
case CSearchItem::eCorrespondent: // cdstring*
popup1 = eCriteria_Correspondent;
if (spec->GetData())
text1 = *static_cast<const cdstring*>(spec->GetData());
popup2 = spec->GetData() ? (negate ? eAddressMethod_NotContains : eAddressMethod_Contains) :
(negate ? eAddressMethod_IsNotMe : eAddressMethod_IsMe);
break;
case CSearchItem::eSender: // cdstring*
popup1 = eCriteria_Sender;
if (spec->GetData())
text1 = *static_cast<const cdstring*>(spec->GetData());
popup2 = spec->GetData() ? (negate ? eAddressMethod_NotContains : eAddressMethod_Contains) :
(negate ? eAddressMethod_IsNotMe : eAddressMethod_IsMe);
break;
case CSearchItem::eNamedStyle: // -
popup1 = eCriteria_SearchSet;
popup7 = CPreferences::sPrefs->mSearchStyles.GetValue().FindIndexOf(*static_cast<const cdstring*>(spec->GetData())) + 1;
popup8 = negate ? eSearchSetMethod_IsNot : eSearchSetMethod_Is;
break;
default:;
}
}
mPopup1->SetValue(popup1);
mPopup2->SetValue(popup2);
mPopup3->SetValue(popup3);
mText1->SetText(text1);
mText2->SetText(text2);
mText3->SetText(text3);
mDate->SetDate(date);
mPopup5->SetValue(popup5);
mPopup6->SetValue(popup6);
mPopup7->SetValue(popup7);
mPopup8->SetValue(popup8);
// Set group contents
if ((spec != NULL) && (spec->GetType() == CSearchItem::eGroup))
mGroupItems->InitGroup(CFilterItem::eLocal, spec);
}
long CSearchCriteriaLocal::GetDatePopup(const CSearchItem* spec, long original, cdstring& text1, cdstring& text3, long& popup5, long& popup6) const
{
switch(reinterpret_cast<unsigned long>(spec->GetData()))
{
// Relative date
case CSearchItem::eToday:
case CSearchItem::eSinceYesterday:
case CSearchItem::eThisWeek:
case CSearchItem::eWithin7Days:
case CSearchItem::eThisMonth:
case CSearchItem::eThisYear:
{
// Set relative popup
switch(reinterpret_cast<unsigned long>(spec->GetData()))
{
case CSearchItem::eToday:
default:
popup5 = eDateRelMethod_SentToday;
return (original == eDateMethod_On) ? eDateMethod_Is : eDateMethod_IsNot;
case CSearchItem::eSinceYesterday:
popup5 = eDateRelMethod_SentYesterday;
return (original == eDateMethod_After) ? eDateMethod_Is : eDateMethod_IsNot;
case CSearchItem::eThisWeek:
popup5 = eDateRelMethod_SentWeek;
return (original == eDateMethod_After) ? eDateMethod_Is : eDateMethod_IsNot;
case CSearchItem::eWithin7Days:
popup5 = eDateRelMethod_Sent7Days;
return (original == eDateMethod_After) ? eDateMethod_Is : eDateMethod_IsNot;
case CSearchItem::eThisMonth:
popup5 = eDateRelMethod_SentMonth;
return (original == eDateMethod_After) ? eDateMethod_Is : eDateMethod_IsNot;
case CSearchItem::eThisYear:
popup5 = eDateRelMethod_SentYear;
return (original == eDateMethod_After) ? eDateMethod_Is : eDateMethod_IsNot;
}
}
default:;
}
switch(reinterpret_cast<unsigned long>(spec->GetData()) & CSearchItem::eWithinMask)
{
// Relative date
case CSearchItem::eWithinDays:
case CSearchItem::eWithinWeeks:
case CSearchItem::eWithinMonths:
case CSearchItem::eWithinYears:
{
unsigned long within = reinterpret_cast<unsigned long>(spec->GetData()) & CSearchItem::eWithinValueMask;
// Set relative popup
switch(reinterpret_cast<unsigned long>(spec->GetData()) & CSearchItem::eWithinMask)
{
case CSearchItem::eWithinDays:
default:
popup6 = eDateWithin_Days;
text3 = within;
return (original == eDateMethod_After) ? eDateMethod_IsWithin : eDateMethod_IsNotWithin;
case CSearchItem::eWithinWeeks:
popup6 = eDateWithin_Weeks;
text3 = within;
return (original == eDateMethod_After) ? eDateMethod_IsWithin : eDateMethod_IsNotWithin;
case CSearchItem::eWithinMonths:
popup6 = eDateWithin_Months;
text3 = within;
return (original == eDateMethod_After) ? eDateMethod_IsWithin : eDateMethod_IsNotWithin;
case CSearchItem::eWithinYears:
popup6 = eDateWithin_Years;
text3 = within;
return (original == eDateMethod_After) ? eDateMethod_IsWithin : eDateMethod_IsNotWithin;
}
}
default:;
}
// Standard date
text1 = spec->GenerateDate(false);
return original;
}
| 26.429192
| 147
| 0.724918
|
mulberry-mail
|
90d554c1623d331c06660d1d43126e3b7abd061f
| 1,655
|
cpp
|
C++
|
Interface/ViewDeath.cpp
|
SnipeDragon/darkspace
|
b6a1fa0a29d3559b158156e7b96935bd0a832ee3
|
[
"MIT"
] | 1
|
2016-05-22T21:28:29.000Z
|
2016-05-22T21:28:29.000Z
|
Interface/ViewDeath.cpp
|
SnipeDragon/darkspace
|
b6a1fa0a29d3559b158156e7b96935bd0a832ee3
|
[
"MIT"
] | null | null | null |
Interface/ViewDeath.cpp
|
SnipeDragon/darkspace
|
b6a1fa0a29d3559b158156e7b96935bd0a832ee3
|
[
"MIT"
] | null | null | null |
/*
ViewDeath.cpp
(c)2000 Palestar, Richard Lyle
*/
#include "Debug/Assert.h"
#include "Interface/GameDocument.h"
#include "DarkSpace/Constants.h"
#include "Interface/ViewDeath.h"
//----------------------------------------------------------------------------
IMPLEMENT_FACTORY( ViewDeath, WindowView::View );
REGISTER_FACTORY_KEY( ViewDeath, 4096729882495776647 );
ViewDeath::ViewDeath()
{
// Construct your view class
}
//----------------------------------------------------------------------------
void ViewDeath::onActivate()
{
//{{BEGIN_DATA_INIT
m_pObserveWindow = WidgetCast<NodeWindow>( window()->findNode( "ObserveWindow" ) );
m_pTextMessage = WidgetCast<WindowText>( window()->findNode( "TextMessage" ) );
//END_DATA_INIT}}
// restore the normal cursor in case they were rotating their view on death
setCursorState( POINTER );
}
void ViewDeath::onDeactivate()
{
// called before this view is destroyed
}
void ViewDeath::onUpdate( float t )
{
}
bool ViewDeath::onMessage( const Message & msg )
{
//{{BEGIN_MSG_MAP
MESSAGE_MAP( WB_BUTTONUP, 1501550643, onButtonExit);
MESSAGE_MAP( WB_BUTTONUP, 1507228051, onButtonOkay);
//END_MSG_MAP}}
return false;
}
void ViewDeath::onDocumentUpdate()
{
// document data has changed, update this view if needed
}
void ViewDeath::onRender( RenderContext & context, const RectInt & window )
{}
//----------------------------------------------------------------------------
bool ViewDeath::onButtonOkay(const Message & msg)
{
document()->setScene( "SelectShip" );
return true;
}
bool ViewDeath::onButtonExit(const Message & msg)
{
document()->setScene( "Main" );
return true;
}
| 21.776316
| 84
| 0.627795
|
SnipeDragon
|
90debecb1d3764b8d598bed91b713e680c3747fe
| 3,027
|
cpp
|
C++
|
PALIN.cpp
|
YourGoodFriendSP/SPOJ-solutions
|
f8b14cad3452628c2c8e17ee44ec0ba2f70bb518
|
[
"MIT"
] | 3
|
2020-10-02T15:01:06.000Z
|
2022-01-15T15:32:25.000Z
|
PALIN.cpp
|
YourGoodFriendSP/SPOJ-solutions
|
f8b14cad3452628c2c8e17ee44ec0ba2f70bb518
|
[
"MIT"
] | null | null | null |
PALIN.cpp
|
YourGoodFriendSP/SPOJ-solutions
|
f8b14cad3452628c2c8e17ee44ec0ba2f70bb518
|
[
"MIT"
] | null | null | null |
#include<bits/stdc++.h>
using namespace std ;
typedef long long ll ;
string add(string &s){
int carry=0 ;
string ans(s.size()+1,'0') ;
int m=s.size() ;
for(int i=m-1;i>=0;i--){
int num=0 ;
if(i==m-1){
num=1 ;
}
int sum=(s[i]-'0')+carry+num ;
s[i]=sum%10 +'0' ;
carry=sum/10 ;
num=0 ;
}
if(carry==1){
s='1'+s ;
}
return s ;
}
string reverseStr(string& str)
{
int n = str.length();
for (int i = 0; i < n / 2; i++)
swap(str[i], str[n - i - 1]);
return str ;
}
void copyPaste(string &s,int i,int j){
for(int k=i;k>=0;k--){
s[j]=s[k] ;
j++ ;
}
cout<<s<<"\n" ;
}
void addAndMirror(string &q,int z){
string s1=add(q) ;
int n=s1.size() ;
string s4=s1 ;
string s2=reverseStr(s4) ;
string s3 ;
if(z==0)
s3=s1+s2 ;
else{
string s5=s2.substr(1) ;
s3=s1+s5 ;
}
cout<<s3<<"\n" ;
}
void forEvenString(string &s){
int z=0 ;
int n=s.size() ;
int i=(n/2)-1 ;
int j=(n/2) ;
int flag=0;
while(i>=0 && j<=n-1){
if(s[i]==s[j]){
i-- ;
j++ ;
}
else{
flag++ ;
int a=s[i]-'0' ;
int b=s[j]-'0' ;
if(a<b){
string r=s.substr(0,n/2);
addAndMirror(r,z) ;
return ;
}
else{
copyPaste(s,i,j) ;
return ;
}
}
}
if(flag==0&&i<0&&j>n-1){
string r=s.substr(0,n/2) ;
addAndMirror(r,z) ;
return ;
}
}
void forOddString(string &s){
int z=1 ;
int n=s.size() ;
int j=n/2 ;
int i=n/2 ;
int flag=0;
while(i>=0 && j<=n-1){
if(s[i]==s[j]){
i-- ;
j++ ;
}
else{
flag++ ;
int a=s[i]-'0' ;
int b=s[j]-'0' ;
if(a<b){
string m=s.substr(0,(n/2)+1) ;
addAndMirror(m,z) ;
return ;
}
else{
copyPaste(s,i,j) ;
return ;
}
}
}
if(flag==0&&i<0&&j>n-1){
string r=s.substr(0,(n/2)+1) ;
addAndMirror(r,z) ;
return ;
}
}
void traverse(string &s){
int a=s.size() ;
if(a%2==0){
forEvenString(s) ;
}
else
{
forOddString(s) ;
}
}
bool ifAll9(string &s){
bool flag=0 ;
for(int i=0;i<s.size();i++)
{
if(s[i]!='9'){
flag=1 ;
}
}
if(flag==0)
{ string a1=add(s) ;
string a2=add(a1) ;
cout<<a2<<"\n" ;
return 1 ;
}
return 0 ;
}
void findPalin(string &s){
bool m=ifAll9(s) ;
if(m==0)
traverse(s) ;
}
void ifAll0(string &s){
bool flag=0 ;
for(int i=0;i<s.size();i++)
{
if(s[i]!='0'){
flag=1 ;
}
}
if(flag==0)
{
cout<<"1" ;
return ;
}
}
void solve(){
string s ;
cin>>s ;
ifAll0(s) ;
string s2 ;
for(int i=0;i<s.size();i++){
if(s[i]!='0'){
s2=s.substr(i) ;
break ;
}
}
findPalin(s2) ;
}
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin) ;
freopen("output.txt", "w", stdout) ;
#endif
int y ;
cin>>y ;
//y=1;
while(y--){
solve() ;
}
}
| 11.870588
| 39
| 0.435745
|
YourGoodFriendSP
|
90df261d1b5b28ef3d6404ee8efb50d3a4f5f409
| 6,520
|
cpp
|
C++
|
Stikboldt/_MyPrefabs/Objects/PF_Character.cpp
|
Kair0z/StikBoldt-PC
|
5d978aa6b67e9f3a140136f2f0b766061e765c74
|
[
"MIT"
] | null | null | null |
Stikboldt/_MyPrefabs/Objects/PF_Character.cpp
|
Kair0z/StikBoldt-PC
|
5d978aa6b67e9f3a140136f2f0b766061e765c74
|
[
"MIT"
] | null | null | null |
Stikboldt/_MyPrefabs/Objects/PF_Character.cpp
|
Kair0z/StikBoldt-PC
|
5d978aa6b67e9f3a140136f2f0b766061e765c74
|
[
"MIT"
] | 1
|
2021-09-23T06:21:53.000Z
|
2021-09-23T06:21:53.000Z
|
#include "stdafx.h"
#include "PF_Character.h"
#include "Components.h"
#include "Prefabs.h"
#include "GameScene.h"
#include "PhysxManager.h"
#include "PhysxProxy.h"
#include "ControllerComponent.h"
PF_Character::PF_Character(float radius, float height, float moveSpeed, float maxJumpHeight, float maxSlopeAngle, float maxMoveSpeed, float drag) :
m_Radius(radius),
m_Height(height),
m_MoveSpeed(moveSpeed),
m_pCamera(nullptr),
m_pController(nullptr),
m_TotalPitch(0),
m_TotalYaw(0),
m_RotationSpeed(90.f),
m_SlopeMax{cosf(maxSlopeAngle)},
m_MaxJumpHeight{maxJumpHeight},
m_GravityEnabled{true},
//Running
m_MaxRunVelocity(maxMoveSpeed),
m_TerminalVelocity(20),
m_Gravity(9.81f),
m_RunAccelerationTime(0.3f),
m_JumpAccelerationTime(0.8f),
m_RunAcceleration(m_MaxRunVelocity/m_RunAccelerationTime),
m_JumpAcceleration(m_Gravity/m_JumpAccelerationTime),
m_RunVelocity(0),
m_JumpVelocity(0),
m_Velocity(0,0,0),
m_HorVelocity{},
m_VertVelocity{},
m_Acceleration{},
m_Drag{drag}
{}
void PF_Character::Initialize(const GameContext& gameContext)
{
using namespace physx;
using namespace DirectX;
UNREFERENCED_PARAMETER(gameContext);
//TODO: Create controller
PxMaterial* pMat = PhysxManager::GetInstance()->GetPhysics()->createMaterial(1.f, 1.f, 0.f);
m_pController = new ControllerComponent{ pMat, m_Radius, m_Height, m_MaxJumpHeight, m_SlopeMax };
AddComponent(m_pController);
}
void PF_Character::PostInitialize(const GameContext& gameContext)
{
using namespace DirectX;
UNREFERENCED_PARAMETER(gameContext);
}
void PF_Character::Update(const GameContext& gameContext)
{
// Set acceleration to zero, input sets it to something else if needed && Lose the accumulated velocity
LoseHorVelocity(gameContext);
m_IsGrounded = m_pController->IsGrounded();
if (m_GravityEnabled && !m_IsGrounded)
{
ApplyAcceleration(0.f, -1.f, 0.f , m_Gravity, gameContext);
}
// Processes movement based on velocity & acceleration
ConsumeVelocity(gameContext);
m_Acceleration = {};
}
void PF_Character::SetMaxSlopeAngle(const float angle)
{
m_SlopeMax = cosf(angle);
}
void PF_Character::ViewMyCamera(bool enabled)
{
if (m_pCamera && enabled)
{
m_pCamera->SetActive();
}
}
void PF_Character::EnableGravity(const bool enabled)
{
m_GravityEnabled = enabled;
}
bool PF_Character::IsGrounded() const
{
return m_IsGrounded;
}
bool PF_Character::GravityIsEnabled() const
{
return m_GravityEnabled;
}
void PF_Character::SimpleMove(const DirectX::XMFLOAT3& direction, float amountPerSecond, const GameContext& gameContext, bool useLocalAxes)
{
using namespace DirectX;
float dt = gameContext.pGameTime->GetElapsed();
XMVECTOR finalDisplacement;
if (!useLocalAxes) finalDisplacement = XMLoadFloat3(&direction);
else
{
XMVECTOR forward = XMLoadFloat3(&GetTransform()->GetForward());
XMVECTOR right = XMLoadFloat3(&GetTransform()->GetRight());
XMVECTOR up = XMLoadFloat3(&GetTransform()->GetUp());
XMVECTOR localDirectionVec = forward * direction.z + right * direction.x + up * direction.y;
finalDisplacement = localDirectionVec;
}
finalDisplacement *= amountPerSecond;
finalDisplacement = XMVector2ClampLength(finalDisplacement, 0.f, m_MaxRunVelocity);
finalDisplacement *= dt;
XMFLOAT3 displacementFloats;
DirectX::XMStoreFloat3(&displacementFloats, finalDisplacement);
m_pController->Move({ displacementFloats });
}
void PF_Character::SimpleRotateHorizontal(bool goRight, float amountPerSecond, const GameContext& gameContext)
{
using namespace DirectX;
XMFLOAT3 rot;
float amount = amountPerSecond * gameContext.pGameTime->GetElapsed();
rot = { 0.0f, goRight ? -amount : amount, 0.0f };
m_pController->GetTransform()->Rotate(XMLoadFloat3(&rot), true);
}
#pragma region Acceleration
void PF_Character::ApplyAcceleration(const DirectX::XMVECTOR& direction, float power, const GameContext&)
{
using namespace DirectX;
XMFLOAT3 vector;
XMStoreFloat3(&vector, direction);
if (vector.x == 0.f && vector.y == 0.f && vector.z == 0.0f) return; // If zerovector, don't do anything...
XMStoreFloat3(&m_Acceleration, XMVector3NormalizeEst(direction) * power);
}
void PF_Character::ApplyAcceleration(const DirectX::XMFLOAT3& direction, float power, const GameContext& gameContext)
{
ApplyAcceleration(DirectX::XMLoadFloat3(&direction), power, gameContext);
}
void PF_Character::ApplyAcceleration(float x, float y, float z, float power, const GameContext& gameContext)
{
ApplyAcceleration(DirectX::XMFLOAT3{ x, y, z }, power, gameContext);
}
#pragma endregion
void PF_Character::LoseHorVelocity(const GameContext& gameContext)
{
if (m_Acceleration.x != 0.f || m_Acceleration.y != 0.f || m_Acceleration.z != 0.f) return;
using namespace DirectX;
XMFLOAT2 horVelocityLengthXYZ;
XMStoreFloat2(&horVelocityLengthXYZ, XMVector2Length(XMLoadFloat2(&m_HorVelocity)));
float length = horVelocityLengthXYZ.x;
gameContext;
float newLength = length - m_Drag * gameContext.pGameTime->GetElapsed();
if (newLength < 0.f)
{
newLength = 0.f;
m_HorVelocity = {};
return;
}
XMVECTOR newHorVelocity = XMVectorScale(XMVector2NormalizeEst(XMLoadFloat2(&m_HorVelocity)), newLength);
XMStoreFloat2(&m_HorVelocity, newHorVelocity);
}
void PF_Character::ConsumeVelocity(const GameContext& gameContext)
{
using namespace DirectX;
// Get Velocity & splits
XMVECTOR horVelocity = XMLoadFloat2(&m_HorVelocity);
float vertVelocity = m_VertVelocity;
// Get Acceleration & splits
XMFLOAT2 horAcc = XMFLOAT2{ m_Acceleration.x, m_Acceleration.z }; // HOR == x & z, not x & y
XMVECTOR horAcceleration = XMLoadFloat2(&horAcc);
float vertAcceleration = m_Acceleration.y;
// DT:
float dt = gameContext.pGameTime->GetElapsed();
// Increase velocity with acceleration:
horVelocity += horAcceleration * dt;
horVelocity = XMVector2ClampLength(horVelocity, 0.0f, m_MaxRunVelocity);
vertVelocity += vertAcceleration * dt;
// Update velocity:
XMStoreFloat2(&m_HorVelocity, horVelocity); // horizontal
m_VertVelocity = vertVelocity; // vertical
// Horizontal displace:
XMVECTOR finalHorDisplacement = XMVector2ClampLength(horVelocity * dt, 0.f, m_MaxRunVelocity);
XMFLOAT2 finalHorDisplace;
XMStoreFloat2(&finalHorDisplace, finalHorDisplacement);
// Vertical displace: (not clamped!)
float finalVertDisplacement;
finalVertDisplacement = vertVelocity * dt;
// Merge displacement:
XMFLOAT3 fullDisplacement = { finalHorDisplace.x, finalVertDisplacement, finalHorDisplace.y };
// Move
m_pController->Move(fullDisplacement);
}
| 27.744681
| 148
| 0.767331
|
Kair0z
|
90df8d71df2361262733892562797810024c14ba
| 1,133
|
cpp
|
C++
|
codex.test/test_object_pool.cpp
|
codex-tk/old_ref_codex
|
c0d5a87b991cc2c48fab2902b5e10b8339cecb91
|
[
"MIT"
] | null | null | null |
codex.test/test_object_pool.cpp
|
codex-tk/old_ref_codex
|
c0d5a87b991cc2c48fab2902b5e10b8339cecb91
|
[
"MIT"
] | null | null | null |
codex.test/test_object_pool.cpp
|
codex-tk/old_ref_codex
|
c0d5a87b991cc2c48fab2902b5e10b8339cecb91
|
[
"MIT"
] | null | null | null |
#include <gtest/gtest.h>
#include <codex/convenience/object_pool.hpp>
#include "gprintf.hpp"
class pooled_object : public codex::object_pool< pooled_object >{
private:
void* _dummy;
};
TEST( object_pool , single ) {
pooled_object* first_object = new pooled_object();
delete first_object;
pooled_object* second_object = new pooled_object();
ASSERT_EQ( first_object , second_object );
}
TEST( object_pool , many ) {
std::set< pooled_object* > pooled_objects;
for( int i = 0 ; i < 1024 ; ++i ) {
pooled_object* po = new pooled_object();
ASSERT_TRUE( pooled_objects.find( po ) == pooled_objects.end());
pooled_objects.insert( po );
}
for ( auto it : pooled_objects) {
delete it;
}
std::vector< pooled_object* > pooled_objects0;
for( int i = 0 ; i < 1024 ; ++i ) {
pooled_object* po = new pooled_object();
ASSERT_TRUE( pooled_objects.find( po ) != pooled_objects.end());
pooled_objects.erase( po );
pooled_objects0.push_back(po);
}
while ( !pooled_objects0.empty()){
pooled_object* po = pooled_objects0.back();
pooled_objects0.pop_back();
delete po;
}
}
| 24.106383
| 68
| 0.673433
|
codex-tk
|
90e106faae0b34c0c50fb77d7ed1557cf83b14d8
| 15,625
|
hxx
|
C++
|
src/factor_unsym.hxx
|
tasseff/SyLVER
|
35cb652ece05447ddf12e530e97428078446eaf4
|
[
"BSD-3-Clause"
] | 9
|
2019-07-02T12:46:22.000Z
|
2021-07-08T11:54:46.000Z
|
src/factor_unsym.hxx
|
tasseff/SyLVER
|
35cb652ece05447ddf12e530e97428078446eaf4
|
[
"BSD-3-Clause"
] | 2
|
2020-03-23T22:55:52.000Z
|
2020-03-24T11:15:16.000Z
|
src/factor_unsym.hxx
|
tasseff/SyLVER
|
35cb652ece05447ddf12e530e97428078446eaf4
|
[
"BSD-3-Clause"
] | 5
|
2019-06-10T11:11:14.000Z
|
2020-03-22T02:38:12.000Z
|
/// @file
/// @copyright 2016- The Science and Technology Facilities Council (STFC)
/// @author Florent Lopez
#pragma once
// SyVLER
#include "NumericFront.hxx"
#include "tasks/tasks_unsym.hxx"
// STD
#include <limits>
// SSIDS
#include "ssids/cpu/cpu_iface.hxx"
#include "ssids/cpu/Workspace.hxx"
namespace sylver {
namespace splu {
template <typename T, typename PoolAlloc>
void factor_front_unsym_app(
struct spral::ssids::cpu::cpu_factor_options& options,
spldlt::NumericFront<T, PoolAlloc> &node,
std::vector<spral::ssids::cpu::Workspace>& workspaces) {
// typedef typename std::allocator_traits<PoolAlloc>::template rebind_alloc<int> IntAlloc;
typedef typename spldlt::NumericFront<T, PoolAlloc>::IntAlloc IntAlloc;
int m = node.get_nrow(); // Frontal matrix order
int n = node.get_ncol(); // Number of fully-summed rows/columns
int nr = node.get_nr(); // number of block rows
int nc = node.get_nc(); // number of fully-summed block columns
size_t contrib_dimn = m-n;
int blksz = node.blksz;
ColumnData<T, IntAlloc>& cdata = *node.cdata; // Column data
T u = options.u; // Threshold parameter
node.nelim = 0; //
for (int k = 0; k < /*1*/ nc; ++k) {
BlockUnsym<T>& dblk = node.get_block_unsym(k, k);
int *rperm = &node.perm [k*blksz];
int *cperm = &node.cperm[k*blksz];
factor_block_unsym_app_task(dblk, rperm, cperm, cdata);
// Compute L factor
for (int i = 0; i < k; ++i) {
// Super-diagonal block
BlockUnsym<T>& lblk = node.get_block_unsym(i, k);
appyU_block_app_task(dblk, u, lblk, cdata);
}
for (int i = k+1; i < nr; ++i) {
// Sub-diagonal block
BlockUnsym<T>& lblk = node.get_block_unsym(i, k);
appyU_block_app_task(dblk, u, lblk, cdata);
}
adjust_unsym_app_task(k, cdata, node.nelim); // Update nelim in node
// Restore failed entries
for (int i = 0; i < nr; ++i) {
BlockUnsym<T>& blk = node.get_block_unsym(i, k);
restore_block_unsym_app_task(k, blk, cdata);
}
// Compute U factor
for (int j = 0; j < k; ++j) {
// Left-diagonal block
BlockUnsym<T>& ublk = node.get_block_unsym(k, j);
applyL_block_app_task(dblk, ublk, cdata, workspaces);
}
for (int j = k+1; j < nr; ++j) {
// Right-diagonal block
BlockUnsym<T>& ublk = node.get_block_unsym(k, j);
applyL_block_app_task(dblk, ublk, cdata, workspaces);
}
// continue;
// Update previously failed entries
// Note: we include the diagonal block which might have some
// failed (and restored) entries
for (int j = 0; j <= k; ++j) {
BlockUnsym<T>& ublk = node.get_block_unsym(k, j);
for (int i = 0; i <= k; ++i) {
BlockUnsym<T>& lblk = node.get_block_unsym(i, k);
BlockUnsym<T>& blk = node.get_block_unsym(i, j);
update_block_unsym_app_task(lblk, ublk, blk, cdata);
}
}
// Update uneliminated entries in L
for (int j = 0; j <= k; ++j) {
BlockUnsym<T>& ublk = node.get_block_unsym(k, j);
for (int i = k+1; i < nr; ++i) {
BlockUnsym<T>& lblk = node.get_block_unsym(i, k);
BlockUnsym<T>& blk = node.get_block_unsym(i, j);
update_block_unsym_app_task(lblk, ublk, blk, cdata);
}
}
// Update uneliminated entries in U
for (int j = k+1; j < nr; ++j) {
BlockUnsym<T>& ublk = node.get_block_unsym(k, j);
for (int i = 0; i <= k; ++i) {
BlockUnsym<T>& lblk = node.get_block_unsym(i, k);
BlockUnsym<T>& blk = node.get_block_unsym(i, j);
update_block_unsym_app_task(lblk, ublk, blk, cdata);
}
}
// Udpdate trailing submatrix
int en = (n-1)/blksz; // Last block-row/column in factors
for (int j = k+1; j < nr; ++j) {
BlockUnsym<T>& ublk = node.get_block_unsym(k, j);
for (int i = k+1; i < nr; ++i) {
// Loop if we are in the cb
if ((i > en) && (j > en)) continue;
BlockUnsym<T>& lblk = node.get_block_unsym(i, k);
BlockUnsym<T>& blk = node.get_block_unsym(i, j);
update_block_unsym_app_task(lblk, ublk, blk, cdata);
}
}
// Update contribution blocks
if (contrib_dimn>0) {
// Update contribution block
int rsa = n/blksz; // Last block-row/column in factors
for (int j = rsa; j < nr; ++j) {
BlockUnsym<T>& ublk = node.get_block_unsym(k, j);
for (int i = rsa; i < nr; ++i) {
BlockUnsym<T>& lblk = node.get_block_unsym(i, k);
spldlt::Tile<T, PoolAlloc>& cblk = node.get_contrib_block(i, j);
update_cb_block_unsym_app_task(lblk, ublk, cblk, cdata);
}
}
}
}
printf("[factor_front_unsym_app] first pass front.nelim = %d\n", node.nelim);
// Permute failed entries at the back of the marix
// permute_failed_unsym(node);
}
/// @param a_ij Pointer on block in lower triangular part
template <typename T>
void copy_failed_diag_unsym(
int m, int n, int rfrom, int cfrom,
T const* a, int lda, T *out, int ldout,
T *lout, int ldlout, T *uout, int lduout) {
if(out == a) return; // don't bother moving if memory is the same
// Copy failed entries
for (int j = cfrom, jout = 0; j < n; ++j, ++jout) {
for (int i = rfrom, iout = 0; i < m; ++i, ++iout) {
out[jout*ldout+iout] = a[j*lda+i];
}
}
// Copy L factors
for (int j = 0; j < cfrom; ++j) {
for (int i = rfrom, iout = 0; i < m; ++i, ++iout) {
lout[j*ldlout+iout] = a[j*lda+i];
}
}
// Copy U factor
for (int j = cfrom, jout = 0; j < n; ++j, ++jout) {
for (int i = 0; i < rfrom; ++i) {
uout[jout*lduout+i] = a[j*lda+i];
}
}
}
template <typename T>
void move_up_diag_unsym(
int m, int n, T const* a, int lda, T *out, int ldout) {
if(out == a) return; // don't bother moving if memory is the same
for (int j = 0; j < n; ++j) {
for (int i = 0; i < m; ++i) {
out[j*ldout+i] = a[j*lda+i];
}
}
}
template <typename T, typename PoolAlloc>
void permute_failed_unsym(
spldlt::NumericFront<T, PoolAlloc> &node) {
// Total number of eliminated rows/columns whithin node
int block_size = node.blksz;
int num_elim = node.nelim;
int n = node.get_ncol(); // Number of fully-summed rows/columns
// Number of block rows/columns in the fully-summed
int nblk = node.get_nc();
int nfail = n-num_elim; // Number of failed columns
// Factor entries
T *lcol = node.lcol;
int ldl = node.get_ldl();
// Column data
typedef typename spldlt::NumericFront<T, PoolAlloc>::IntAlloc IntAlloc;
ColumnData<T, IntAlloc>& cdata = *node.cdata; // Column data
// Permutation
int *rperm = node.perm;
int *cperm = node.cperm;
printf("[permute_failed_unsym] n = %d\n", n);
printf("[permute_failed_unsym] ldl = %d\n", ldl);
// std::vector<int, IntAlloc> failed_perm(n-num_elim, alloc);
std::vector<int> failed_perm (nfail);
std::vector<int> failed_cperm(nfail);
// Permute fail entries to the back of the matrix
for(int jblk=0, insert=0, fail_insert=0; jblk<nblk; jblk++) {
// int blk_n = get_ncol(jblk, n, blksz)
int blk_n = std::min(block_size, n-(jblk*block_size)); // Number of fully-summed within block
// Move back failed rows
cdata[jblk].move_back(
blk_n, &rperm[jblk*block_size],
&rperm[insert], &failed_perm[fail_insert]
);
// Move back failed columns
cdata[jblk].move_back(
blk_n, &cperm[jblk*block_size],
&cperm[insert], &failed_cperm[fail_insert]
);
insert += cdata[jblk].nelim;
fail_insert += blk_n - cdata[jblk].nelim;
}
for(int i=0; i < nfail; ++i) {
rperm[num_elim+i] = failed_perm [i];
cperm[num_elim+i] = failed_cperm[i];
}
std::vector<T> failed_diag(nfail*nfail);
std::vector<T> failed_lwr(nfail*num_elim);
std::vector<T> failed_upr(num_elim*nfail);
// Extract failed entries
// Square (diagonal) part
for (int jblk=0, jfail=0, jinsert=0; jblk<nblk; ++jblk) {
int blk_n = std::min(block_size, n-(jblk*block_size)); // Number of fully-summed within block
// printf("[permute_failed_unsym] jblk = %d, blk_n = %d\n", jblk, blk_n);
for (int iblk=0, ifail=0, iinsert=0; iblk<nblk; ++iblk) {
int blk_m = std::min(block_size, n-(iblk*block_size)); // Number of fully-summed within block
// printf("[permute_failed_unsym] iblk = %d, blk_m = %d\n", iblk, blk_m);
// printf("[permute_failed_unsym] iblk = %d, jblk = %d, iinsert = %d, jinsert = %d\n",
// iblk, jblk, iinsert, jinsert);
assert(iblk*block_size < n);
assert(jblk*block_size < n);
// assert(jfail < nfail);
// assert(ifail < nfail);
T *failed_diag_ptr = nullptr;
if (ifail < nfail && jfail < nfail)
failed_diag_ptr = &failed_diag[jfail*nfail+ifail];
copy_failed_diag_unsym(
blk_m, blk_n,
cdata[iblk].nelim, cdata[jblk].nelim,
&lcol[iblk*block_size+jblk*block_size*ldl],
ldl,
failed_diag_ptr, nfail,
&failed_lwr[ifail+jinsert*nfail], nfail,
&failed_upr[iinsert+jfail*num_elim], num_elim);
iinsert += cdata[iblk].nelim;
ifail += blk_m - cdata[iblk].nelim;
}
jinsert += cdata[jblk].nelim;
jfail += blk_n - cdata[jblk].nelim;
}
// Rectangular (sub-diagonal) part
// ...
// Move up eliminated entries
// Diagonal part
for (int jblk=0, jinsert=0; jblk<nblk; ++jblk) {
int blk_n = std::min(block_size, n-(jblk*block_size)); // Number of fully-summed within block
// printf("[permute_failed_unsym] jblk = %d, blk_n = %d\n", jblk, blk_n);
for (int iblk=0, iinsert=0; iblk<nblk; ++iblk) {
int blk_m = std::min(block_size, n-(iblk*block_size)); // Number of fully-summed within block
// printf("[permute_failed_unsym] iblk = %d, blk_m = %d\n", iblk, blk_m);
move_up_diag_unsym(
cdata[iblk].nelim, cdata[jblk].nelim,
&lcol[jblk*block_size*ldl+iblk*block_size], ldl,
&lcol[jinsert*ldl+iinsert], ldl);
iinsert += cdata[iblk].nelim;
}
jinsert += cdata[jblk].nelim;
}
// printf("[permute_failed_unsym] num_elim = %d, nfail = %d\n", num_elim, nfail);
// Copy failed entries back to factor entries
// L factor
for (int j = 0; j < num_elim; ++j) {
for (int i = 0; i < nfail; ++i) {
lcol[num_elim+i + j*ldl] = failed_lwr[i+j*nfail];
// lcol[num_elim+i + j*ldl] = std::numeric_limits<double>::quiet_NaN();
}
}
for (int j = 0; j < nfail; ++j) {
for (int i = 0; i < num_elim; ++i) {
lcol[i + (j+num_elim)*ldl] = failed_upr[i+j*num_elim];
// lcol[i + (j+num_elim)*ldl] = std::numeric_limits<double>::quiet_NaN();
}
for (int i = 0; i < nfail; ++i) {
lcol[i+num_elim + (j+num_elim)*ldl] = failed_diag[i+j*nfail];
// lcol[i+num_elim + (j+num_elim)*ldl] = std::numeric_limits<double>::quiet_NaN();
}
}
}
/// @brief Task-based front factorization routine using Restricted
/// Pivoting (RP)
/// @Note No delays, potentially unstable
template <typename T, typename PoolAlloc>
void factor_front_unsym_rp(
spldlt::NumericFront<T, PoolAlloc> &node,
std::vector<spral::ssids::cpu::Workspace>& workspaces) {
// Extract front info
int m = node.get_nrow(); // Frontal matrix order
int n = node.get_ncol(); // Number of fully-summed rows/columns
int nr = node.get_nr(); // number of block rows
int nc = node.get_nc(); // number of block columns
size_t contrib_dimn = m-n;
int blksz = node.blksz;
printf("[factor_front_unsym_rp] m = %d\n", m);
printf("[factor_front_unsym_rp] n = %d\n", n);
for(int k = 0; k < nc; ++k) {
BlockUnsym<T>& dblk = node.get_block_unsym(k, k);
int *perm = &node.perm[k*blksz];
factor_block_lu_pp_task(dblk, perm);
// Apply permutation
for (int j = 0; j < k; ++j) {
BlockUnsym<T>& rblk = node.get_block_unsym(k, j);
// Apply row permutation on left-diagonal blocks
apply_rperm_block_task(dblk, rblk, workspaces);
}
// Apply permutation and compute U factors
for (int j = k+1; j < nc; ++j) {
BlockUnsym<T>& ublk = node.get_block_unsym(k, j);
applyL_block_task(dblk, ublk, workspaces);
}
// Compute L factors
for (int i = k+1; i < nr; ++i) {
BlockUnsym<T>& lblk = node.get_block_unsym(i, k);
applyU_block_task(dblk, lblk);
}
int en = (n-1)/blksz; // Last block-row/column in factors
// Udpdate trailing submatrix
for (int j = k+1; j < nr; ++j) {
BlockUnsym<T>& ublk = node.get_block_unsym(k, j);
for (int i = k+1; i < nr; ++i) {
// Loop if we are in the cb
if ((i > en) && (j > en)) continue;
BlockUnsym<T>& lblk = node.get_block_unsym(i, k);
BlockUnsym<T>& blk = node.get_block_unsym(i, j);
update_block_lu_task(lblk, ublk, blk);
}
}
if (contrib_dimn>0) {
// Update contribution block
int rsa = n/blksz; // Last block-row/column in factors
for (int j = rsa; j < nr; ++j) {
BlockUnsym<T>& ublk = node.get_block_unsym(k, j);
for (int i = rsa; i < nr; ++i) {
BlockUnsym<T>& lblk = node.get_block_unsym(i, k);
spldlt::Tile<T, PoolAlloc>& cblk = node.get_contrib_block(i, j);
update_cb_block_lu_task(lblk, ublk, cblk);
}
}
}
}
// Note: we do not check for stability
node.nelim = n; // We eliminated all fully-summed rows/columns
node.ndelay_out = 0; // No delays
}
}} // End of namespace sylver::splu
| 34.955257
| 105
| 0.524416
|
tasseff
|
90e1080185a7008f59b9ecfc2909f120fb51b286
| 198
|
cpp
|
C++
|
net.ssa/itself/itself.cpp
|
ixray-team/xray-vss-archive
|
b245c8601dcefb505b4b51f58142da6769d4dc92
|
[
"Linux-OpenIB"
] | 1
|
2022-03-26T17:00:19.000Z
|
2022-03-26T17:00:19.000Z
|
net.ssa/itself/itself.cpp
|
ixray-team/xray-vss-archive
|
b245c8601dcefb505b4b51f58142da6769d4dc92
|
[
"Linux-OpenIB"
] | null | null | null |
net.ssa/itself/itself.cpp
|
ixray-team/xray-vss-archive
|
b245c8601dcefb505b4b51f58142da6769d4dc92
|
[
"Linux-OpenIB"
] | 1
|
2022-03-26T17:00:21.000Z
|
2022-03-26T17:00:21.000Z
|
extern"C"int printf(char*,...);char*S="extern%cC%cint printf(char*,...);char*S=%c%s%c;char*T=%c%s%c%s";char*T=";main(){printf(S,34,34,34,S,34,34,T,34,T);}";main(){printf(S,34,34,34,S,34,34,T,34,T);}
| 198
| 198
| 0.611111
|
ixray-team
|
90e6605e78f74ac2489927f867407deea660f7d3
| 2,487
|
cpp
|
C++
|
src/ciphers/vigenere.cpp
|
Cyclic3/CipheyCore
|
63cc5fa79b68602e92fd1e16abdbd16b53fcbc53
|
[
"MIT"
] | 35
|
2020-05-30T10:25:14.000Z
|
2022-03-09T05:46:28.000Z
|
src/ciphers/vigenere.cpp
|
Cyclic3/CipheyCore
|
63cc5fa79b68602e92fd1e16abdbd16b53fcbc53
|
[
"MIT"
] | 12
|
2020-08-01T16:52:49.000Z
|
2021-12-25T22:04:42.000Z
|
src/ciphers/vigenere.cpp
|
Cyclic3/CipheyCore
|
63cc5fa79b68602e92fd1e16abdbd16b53fcbc53
|
[
"MIT"
] | 14
|
2020-08-06T01:36:08.000Z
|
2022-02-02T09:53:18.000Z
|
#include "ciphey/ciphers.hpp"
#include "common.hpp"
#include <atomic>
#include <thread>
#include <future>
namespace ciphey::vigenere {
std::vector<crack_result<key_t>> crack(windowed_prob_table observed, prob_table const& expected,
group_t const& group, freq_t count, prob_t p_value) {
return detail::reducer<key_t, caesar::key_t, caesar::crack, group_t const&>::crack(observed, expected, count, p_value, group);
}
void encrypt(string_ref_t str, key_t const& key, group_t const& group) {
const auto inverse = invert_group(group);
size_t i = 0;
for (auto& c : str) {
// Ignore letters we cannot find
if (auto iter = inverse.find(c); iter != inverse.end()) {
c = group[(iter->second + key[i % key.size()]) % group.size()];
++i;
}
}
}
void decrypt(string_ref_t str, key_t const& key, group_t const& group) {
std::vector<size_t> inv_key(key.size());
for (size_t i = 0; i < key.size(); ++i)
inv_key[i] = group.size() - key[i];
encrypt(str, inv_key, group);
}
prob_t detect(windowed_prob_table const& observed, prob_table const& expected, freq_t count) {
if (count == 0)
return 0.;
prob_t acc = 1.;
for (auto& i : observed) {
// FIXME: work out the amount from the count, rather than just flooring it
acc *= caesar::detect(i, expected, count / observed.size());
}
return acc;
}
key_len_res likely_key_lens(string_const_ref_t input, prob_table const& expected,
domain_t const& domain, prob_t p_value) {
key_len_res ret;
ret.candidates.reserve(8);
// Dividing by 4 is a good guess of what is feasible to crack
for (size_t key_len = 2; key_len < input.size() / 8; ++key_len) {
ret.candidates.emplace_back();
auto& last = ret.candidates.back();
last.tab = windowed_freq_table(key_len);
// I don't think the extra write here has a significant effect of performance
ret.count_in_domain = freq_analysis(last.tab, input, domain);
auto observed = freq_conv(last.tab, ret.count_in_domain);
if (auto prob = detect(observed, expected, ret.count_in_domain); prob > p_value) {
last.len = key_len;
last.p_value = prob;
}
else
ret.candidates.pop_back();
}
std::sort(ret.candidates.rbegin(), ret.candidates.rend(), [](auto& a, auto& b) { return a.p_value < b.p_value; });
return ret;
}
}
| 32.723684
| 130
| 0.628468
|
Cyclic3
|
90e77fb2c6facb656eaed6c70b765736f455498a
| 131
|
cpp
|
C++
|
Source/Flopnite/Private/GameplayAbilities/FNGameplayAbility.cpp
|
BEASTSM96/flopnite-ue4
|
76193544a6b7fe6b969864e74409b6b5a43f3d7a
|
[
"MIT"
] | null | null | null |
Source/Flopnite/Private/GameplayAbilities/FNGameplayAbility.cpp
|
BEASTSM96/flopnite-ue4
|
76193544a6b7fe6b969864e74409b6b5a43f3d7a
|
[
"MIT"
] | null | null | null |
Source/Flopnite/Private/GameplayAbilities/FNGameplayAbility.cpp
|
BEASTSM96/flopnite-ue4
|
76193544a6b7fe6b969864e74409b6b5a43f3d7a
|
[
"MIT"
] | null | null | null |
// Fill out your copyright notice in the Description page of Project Settings.
#include "GameplayAbilities/FNGameplayAbility.h"
| 21.833333
| 78
| 0.801527
|
BEASTSM96
|
90e8850104d10e97d4aa5d749bc4be6afccf0770
| 5,530
|
cc
|
C++
|
src/sequence_batch.cc
|
vejnar/chromap
|
f0ff121845f727b2142f04983211233f27302d13
|
[
"MIT"
] | null | null | null |
src/sequence_batch.cc
|
vejnar/chromap
|
f0ff121845f727b2142f04983211233f27302d13
|
[
"MIT"
] | null | null | null |
src/sequence_batch.cc
|
vejnar/chromap
|
f0ff121845f727b2142f04983211233f27302d13
|
[
"MIT"
] | null | null | null |
#include "sequence_batch.h"
#include <tuple>
#include "utils.h"
namespace chromap {
constexpr uint8_t SequenceBatch::char_to_uint8_table_[256];
constexpr char SequenceBatch::uint8_to_char_table_[8];
void SequenceBatch::InitializeLoading(const std::string &sequence_file_path) {
sequence_file_ = gzopen(sequence_file_path.c_str(), "r");
if (sequence_file_ == NULL) {
ExitWithMessage("Cannot find sequence file" + sequence_file_path);
}
sequence_kseq_ = kseq_init(sequence_file_);
}
uint32_t SequenceBatch::LoadBatch() {
double real_start_time = GetRealTime();
uint32_t num_sequences = 0;
num_bases_ = 0;
for (uint32_t sequence_index = 0; sequence_index < max_num_sequences_;
++sequence_index) {
int length = kseq_read(sequence_kseq_);
while (length == 0) { // Skip the sequences of length 0
length = kseq_read(sequence_kseq_);
}
if (length > 0) {
kseq_t *sequence = sequence_batch_[sequence_index];
std::swap(sequence_kseq_->seq, sequence->seq);
ReplaceByEffectiveRange(sequence->seq);
std::swap(sequence_kseq_->name, sequence->name);
std::swap(sequence_kseq_->comment, sequence->comment);
if (sequence_kseq_->qual.l != 0) { // fastq file
std::swap(sequence_kseq_->qual, sequence->qual);
ReplaceByEffectiveRange(sequence->qual);
}
sequence->id = num_loaded_sequences_;
++num_loaded_sequences_;
++num_sequences;
num_bases_ += length;
} else {
if (length != -1) {
ExitWithMessage(
"Didn't reach the end of sequence file, which might be corrupted!");
}
// make sure to reach the end of file rather than meet an error
break;
}
}
if (num_sequences != 0) {
std::cerr << "Loaded sequence batch successfully in "
<< GetRealTime() - real_start_time << "s, ";
std::cerr << "number of sequences: " << num_sequences << ", ";
std::cerr << "number of bases: " << num_bases_ << ".\n";
} else {
std::cerr << "No more sequences.\n";
}
return num_sequences;
}
bool SequenceBatch::LoadOneSequenceAndSaveAt(uint32_t sequence_index) {
// double real_start_time = Chromap::GetRealTime();
bool no_more_sequence = false;
int length = kseq_read(sequence_kseq_);
while (length == 0) { // Skip the sequences of length 0
length = kseq_read(sequence_kseq_);
}
if (length > 0) {
kseq_t *sequence = sequence_batch_[sequence_index];
std::swap(sequence_kseq_->seq, sequence->seq);
ReplaceByEffectiveRange(sequence->seq);
std::swap(sequence_kseq_->name, sequence->name);
std::swap(sequence_kseq_->comment, sequence->comment);
sequence->id = num_loaded_sequences_;
++num_loaded_sequences_;
if (sequence_kseq_->qual.l != 0) { // fastq file
std::swap(sequence_kseq_->qual, sequence->qual);
ReplaceByEffectiveRange(sequence->qual);
}
} else {
if (length != -1) {
ExitWithMessage(
"Didn't reach the end of sequence file, which might be corrupted!");
}
// make sure to reach the end of file rather than meet an error
no_more_sequence = true;
}
return no_more_sequence;
}
uint32_t SequenceBatch::LoadAllSequences() {
double real_start_time = GetRealTime();
sequence_batch_.reserve(200);
uint32_t num_sequences = 0;
num_bases_ = 0;
int length = kseq_read(sequence_kseq_);
while (length >= 0) {
if (length == 0) { // Skip the sequences of length 0
continue;
} else if (length > 0) {
sequence_batch_.emplace_back((kseq_t *)calloc(1, sizeof(kseq_t)));
kseq_t *sequence = sequence_batch_.back();
std::swap(sequence_kseq_->seq, sequence->seq);
ReplaceByEffectiveRange(sequence->seq);
std::swap(sequence_kseq_->name, sequence->name);
std::swap(sequence_kseq_->comment, sequence->comment);
if (sequence_kseq_->qual.l != 0) { // fastq file
std::swap(sequence_kseq_->qual, sequence->qual);
ReplaceByEffectiveRange(sequence->qual);
}
sequence->id = num_loaded_sequences_;
++num_loaded_sequences_;
++num_sequences;
num_bases_ += length;
} else {
if (length != -1) {
ExitWithMessage(
"Didn't reach the end of sequence file, which might be corrupted!");
}
// make sure to reach the end of file rather than meet an error
break;
}
length = kseq_read(sequence_kseq_);
}
std::cerr << "Loaded all sequences successfully in "
<< GetRealTime() - real_start_time << "s, ";
std::cerr << "number of sequences: " << num_sequences << ", ";
std::cerr << "number of bases: " << num_bases_ << ".\n";
return num_sequences;
}
void SequenceBatch::FinalizeLoading() {
kseq_destroy(sequence_kseq_);
gzclose(sequence_file_);
}
void SequenceBatch::ReplaceByEffectiveRange(kstring_t &seq) {
if (effective_range_[0] == 0 && effective_range_[1] == -1 &&
effective_range_[2] == 1) {
return;
}
int i, j;
int start = effective_range_[0];
int end = effective_range_[1];
if (effective_range_[1] == -1) end = seq.l - 1;
for (i = 0; i < end - start + 1; ++i) {
seq.s[i] = seq.s[start + i];
}
seq.s[i] = '\0';
seq.l = end - start + 1;
if (effective_range_[2] == -1) {
for (i = 0; i < (int)seq.l; ++i) {
seq.s[i] = Uint8ToChar(((uint8_t)3) ^ (CharToUint8(seq.s[i])));
}
for (i = 0, j = seq.l - 1; i < j; ++i, --j) {
char tmp = seq.s[i];
seq.s[i] = seq.s[j];
seq.s[j] = tmp;
}
}
}
} // namespace chromap
| 33.113772
| 80
| 0.638336
|
vejnar
|
90e9d8dab498a49a5ba068712f0162adcd5dff1e
| 427
|
cpp
|
C++
|
main.cpp
|
pawbyte/semath
|
f292718f521d7f6d0d66307f06db854813907b6d
|
[
"MIT"
] | null | null | null |
main.cpp
|
pawbyte/semath
|
f292718f521d7f6d0d66307f06db854813907b6d
|
[
"MIT"
] | null | null | null |
main.cpp
|
pawbyte/semath
|
f292718f521d7f6d0d66307f06db854813907b6d
|
[
"MIT"
] | null | null | null |
#include "semath.h"
#include <iostream> //used to use std::cout to print messages
//Make sure to include both "semath.h" and "semath.cpp" in your project directory.
int main( int argc, char* args[] )
{
std::cout << "Result of <get_direction( 0, 0, 300, 300):" << get_direction( 0, 0, 300, 300) << ".\n";
std::cout << "Result of <get_distance( 0, 0, 300, 300):" << get_distance( 0, 0, 300, 300) << ".\n";
return 0;
}
| 32.846154
| 104
| 0.620609
|
pawbyte
|
90ee6174c7fbe76db6759d37259da311e516452e
| 441
|
hpp
|
C++
|
include/rive/animation/blend_animation.hpp
|
kariem2k/rive-cpp
|
f58c3b3d48ea03947a76971bce17e7f567cf0de0
|
[
"MIT"
] | 139
|
2020-08-17T20:10:24.000Z
|
2022-03-28T12:22:44.000Z
|
include/rive/animation/blend_animation.hpp
|
kariem2k/rive-cpp
|
f58c3b3d48ea03947a76971bce17e7f567cf0de0
|
[
"MIT"
] | 89
|
2020-08-28T16:41:01.000Z
|
2022-03-28T19:10:49.000Z
|
include/rive/animation/blend_animation.hpp
|
kariem2k/rive-cpp
|
f58c3b3d48ea03947a76971bce17e7f567cf0de0
|
[
"MIT"
] | 19
|
2020-10-19T00:54:40.000Z
|
2022-02-28T05:34:17.000Z
|
#ifndef _RIVE_BLEND_ANIMATION_HPP_
#define _RIVE_BLEND_ANIMATION_HPP_
#include "rive/generated/animation/blend_animation_base.hpp"
namespace rive
{
class LinearAnimation;
class BlendAnimation : public BlendAnimationBase
{
private:
LinearAnimation* m_Animation = nullptr;
public:
const LinearAnimation* animation() const { return m_Animation; }
StatusCode import(ImportStack& importStack) override;
};
} // namespace rive
#endif
| 24.5
| 66
| 0.800454
|
kariem2k
|
90ef8e39c9035771f1018e3261cac7bd5c5a6271
| 1,791
|
hpp
|
C++
|
src/main/generic_format/ast/string.hpp
|
foobar27/generic_format
|
a44ce919b9c296ce66c0b54a51a61c884ddb78dd
|
[
"BSL-1.0"
] | null | null | null |
src/main/generic_format/ast/string.hpp
|
foobar27/generic_format
|
a44ce919b9c296ce66c0b54a51a61c884ddb78dd
|
[
"BSL-1.0"
] | null | null | null |
src/main/generic_format/ast/string.hpp
|
foobar27/generic_format
|
a44ce919b9c296ce66c0b54a51a61c884ddb78dd
|
[
"BSL-1.0"
] | null | null | null |
/**
@file
@copyright
Copyright Sebastien Wagener 2014
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#pragma once
#include "generic_format/ast/base.hpp"
namespace generic_format::ast {
/** @brief A format representing a string which is serialized via its length followed by its data.
*
* @tparam LengthFormat the format used to serialize the length.
*/
template <IntegralFormat LengthFormat>
struct string : base<format_list<LengthFormat>> {
using native_type = std::string;
using length_format = LengthFormat;
using native_length_type = typename length_format::native_type;
static constexpr auto size = dynamic_size();
template <class RawWriter, class State>
void write(RawWriter& raw_writer, State& state, const std::string& s) const {
if (s.length() > std::numeric_limits<native_length_type>::max())
throw serialization_exception();
length_format().write(raw_writer, state, static_cast<native_length_type>(s.length()));
raw_writer(reinterpret_cast<const void*>(s.data()), s.length());
}
template <class RawReader, class State>
void read(RawReader& raw_reader, State& state, std::string& s) const {
native_length_type length;
length_format().read(raw_reader, state, length);
if (length > std::numeric_limits<std::size_t>::max())
throw deserialization_exception();
s = std::string(static_cast<std::size_t>(length), 0); // TODO(sw) we don't need to fill the string
raw_reader(const_cast<void*>(reinterpret_cast<const void*>(s.data())), s.length());
}
};
} // end namespace generic_format::ast
| 38.934783
| 106
| 0.683975
|
foobar27
|
90f1a4536dca3d15b69e4c3bab3d3f518eb2fca4
| 111,610
|
cpp
|
C++
|
OGDF/src/coin/Symphony/tm_func.cpp
|
shahnidhi/MetaCarvel
|
f3bea5fdbbecec4c9becc6bbdc9585a939eb5481
|
[
"MIT"
] | 13
|
2017-12-21T03:35:41.000Z
|
2022-01-31T13:45:25.000Z
|
OGDF/src/coin/Symphony/tm_func.cpp
|
shahnidhi/MetaCarvel
|
f3bea5fdbbecec4c9becc6bbdc9585a939eb5481
|
[
"MIT"
] | 7
|
2017-09-13T01:31:24.000Z
|
2021-12-14T00:31:50.000Z
|
OGDF/src/coin/Symphony/tm_func.cpp
|
shahnidhi/MetaCarvel
|
f3bea5fdbbecec4c9becc6bbdc9585a939eb5481
|
[
"MIT"
] | 15
|
2017-09-07T18:28:55.000Z
|
2022-01-18T14:17:43.000Z
|
/*===========================================================================*/
/* */
/* This file is part of the SYMPHONY MILP Solver Framework. */
/* */
/* SYMPHONY was jointly developed by Ted Ralphs (ted@lehigh.edu) and */
/* Laci Ladanyi (ladanyi@us.ibm.com). */
/* */
/* (c) Copyright 2000-2011 Ted Ralphs. All Rights Reserved. */
/* */
/* This software is licensed under the Eclipse Public License. Please see */
/* accompanying file for terms. */
/* */
/*===========================================================================*/
#define COMPILING_FOR_TM
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#if !defined(_MSC_VER) && !defined(__MNO_CYGWIN) && defined(SIGHANDLER)
#include <signal.h>
#if !defined(HAS_SRANDOM)
extern int srandom PROTO((unsigned seed));
#endif
#if !defined(HAS_RANDOM)
extern long random PROTO((void));
#endif
#endif
#ifdef _OPENMP
#include "omp.h"
#endif
#if !defined (_MSC_VER)
#include <unistd.h> /* this defines sleep() */
#endif
#include "sym_tm.h"
#include "sym_constants.h"
#include "sym_types.h"
#include "sym_macros.h"
#include "sym_messages.h"
#include "sym_proccomm.h"
#include "sym_timemeas.h"
#include "sym_pack_cut.h"
#include "sym_pack_array.h"
#ifdef COMPILE_IN_LP
#include "sym_lp.h"
#endif
#ifdef COMPILE_IN_TM
#include "sym_master.h"
#else
#include "sym_cp.h"
#endif
int c_count = 0;
/*===========================================================================*/
/*===========================================================================*\
* This file contains basic functions associated with the treemanager process
\*===========================================================================*/
/*===========================================================================*/
/*===========================================================================*\
* This function receives the intitial parameters and data and sets up
* the tree manager data structures, etc.
\*===========================================================================*/
int tm_initialize(tm_prob *tm, base_desc *base, node_desc *rootdesc)
{
#ifndef COMPILE_IN_TM
int r_bufid, bytes, msgtag, i;
#endif
FILE *f = NULL;
tm_params *par;
bc_node *root = (bc_node *) calloc(1, sizeof(bc_node));
#ifdef COMPILE_IN_LP
int i;
#else
#ifdef COMPILE_IN_TM
int i;
#endif
int s_bufid;
#endif
int *termcodes = NULL;
#if !defined(_MSC_VER) && !defined(__MNO_CYGWIN) && defined(SIGHANDLER)
signal(SIGINT, sym_catch_c);
#endif
par = &tm->par;
#ifdef _OPENMP
tm->rpath =
(bc_node ***) calloc(par->max_active_nodes, sizeof(bc_node **));
tm->rpath_size = (int *) calloc(par->max_active_nodes, sizeof(int));
tm->bpath =
(branch_desc **) calloc(par->max_active_nodes, sizeof(branch_desc *));
tm->bpath_size = (int *) calloc(par->max_active_nodes, sizeof(int));
termcodes = (int *) calloc(par->max_active_nodes, sizeof(int));
#else
tm->rpath = (bc_node ***) calloc(1, sizeof(bc_node **));
tm->rpath_size = (int *) calloc(1, sizeof(int));
tm->bpath = (branch_desc **) calloc(1, sizeof(branch_desc *));
tm->bpath_size = (int *) calloc(1, sizeof(int));
termcodes = (int *) calloc(1, sizeof(int));
#endif
/*------------------------------------------------------------------------*\
* Receives data from the master
\*------------------------------------------------------------------------*/
#ifdef COMPILE_IN_TM
tm->bvarnum = base->varnum;
tm->bcutnum = base->cutnum;
#else
r_bufid = receive_msg(ANYONE, TM_DATA);
bufinfo(r_bufid, &bytes, &msgtag, &tm->master);
receive_char_array((char *)par, sizeof(tm_params));
receive_char_array(&tm->has_ub, 1);
if (tm->has_ub)
receive_dbl_array(&tm->ub, 1);
receive_char_array(&tm->has_ub_estimate, 1);
if (tm->has_ub_estimate)
receive_dbl_array(&tm->ub_estimate, 1);
READ_STR_LIST(par->lp_mach_num, MACH_NAME_LENGTH,
par->lp_machs[0], par->lp_machs);
READ_STR_LIST(par->cg_mach_num, MACH_NAME_LENGTH,
par->cg_machs[0], par->cg_machs);
READ_STR_LIST(par->cp_mach_num, MACH_NAME_LENGTH,
par->cp_machs[0], par->cp_machs);
receive_int_array(&tm->bvarnum, 1);
receive_int_array(&tm->bcutnum, 1);
#ifdef TRACE_PATH
receive_int_array(&tm->feas_sol_size, 1);
if (tm->feas_sol_size){
tm->feas_sol = (int *) calloc (tm->feas_sol_size, sizeof(int));
receive_int_array(tm->feas_sol, tm->feas_sol_size);
}
#endif
freebuf(r_bufid);
#endif
SRANDOM(par->random_seed);
#ifdef COMPILE_IN_LP
#ifdef _OPENMP
omp_set_dynamic(FALSE);
omp_set_num_threads(par->max_active_nodes);
#else
par->max_active_nodes = 1;
#endif
tm->active_nodes = (bc_node **) calloc(par->max_active_nodes, sizeof(bc_node *));
#ifndef COMPILE_IN_TM
tm->lpp = (lp_prob **)
malloc(par->max_active_nodes * sizeof(lp_prob *));
for (i = 0; i < par->max_active_nodes; i++){
tm->lpp[i] = (lp_prob *) calloc(1, sizeof(lp_prob));
tm->lpp[i]->proc_index = i;
}
#ifdef COMPILE_IN_CG
tm->cgp = (cg_prob **) malloc(par->max_active_nodes * sizeof(cg_prob *));
for (i = 0; i < par->max_active_nodes; i++)
tm->lpp[i]->cgp = tm->cgp[i] = (cg_prob *) calloc(1, sizeof(cg_prob));
par->use_cg = FALSE;
#endif
#endif
#pragma omp parallel for shared(tm)
for (i = 0; i < par->max_active_nodes; i++){
if ((termcodes[i] = lp_initialize(tm->lpp[i], 0)) < 0){
printf("LP initialization failed with error code %i in thread %i\n\n",
termcodes[i], i);
}
tm->lpp[i]->tm = tm;
}
tm->lp.free_num = par->max_active_nodes;
for (i = 0; i < par->max_active_nodes; i++){
if (termcodes[i] < 0){
int tmp = termcodes[i];
FREE(termcodes);
return(tmp);
}
}
#else
tm->active_nodes =
(bc_node **) malloc(par->max_active_nodes * sizeof(bc_node *));
/*------------------------------------------------------------------------*\
* Start the lp, cg processes and send cg tid's to the lp's.
* Also, start the cp, sp processes.
\*------------------------------------------------------------------------*/
tm->lp = start_processes(tm, par->max_active_nodes, par->lp_exe,
par->lp_debug, par->lp_mach_num, par->lp_machs);
#endif
#pragma omp critical (cut_pool)
if (!tm->cuts){
tm->cuts = (cut_data **) malloc(BB_BUNCH * sizeof(cut_data *));
}
if (par->use_cg){
#ifndef COMPILE_IN_CG
tm->cg = start_processes(tm, par->max_active_nodes, par->cg_exe,
par->cg_debug, par->cg_mach_num, par->cg_machs);
#ifdef COMPILE_IN_LP
for (i = 0; i < par->max_active_nodes; i++)
tm->lpp[i]->cut_gen = tm->cg.procs[i];
#else
for (i = 0; i < tm->lp.procnum; i++){
s_bufid = init_send(DataInPlace);
send_int_array(tm->cg.procs + i, 1);
send_msg(tm->lp.procs[i], LP__CG_TID_INFO);
}
#endif
#endif
}
if (par->max_cp_num){
#ifdef COMPILE_IN_CP
#ifndef COMPILE_IN_TM
tm->cpp = (cut_pool **) malloc(par->max_cp_num * sizeof(cut_pool *));
#endif
for (i = 0; i < par->max_cp_num; i++){
#ifndef COMPILE_IN_TM
tm->cpp[i] = (cut_pool *) calloc(1, sizeof(cut_pool));
#endif
cp_initialize(tm->cpp[i], tm->master);
}
tm->cp.free_num = par->max_cp_num;
tm->cp.procnum = par->max_cp_num;
tm->cp.free_ind = (int *) malloc(par->max_cp_num * ISIZE);
for (i = par->max_cp_num - 1; i >= 0; i--)
tm->cp.free_ind[i] = i;
#else
tm->cp = start_processes(tm, par->max_cp_num, par->cp_exe,
par->cp_debug, par->cp_mach_num, par->cp_machs);
#endif
tm->nodes_per_cp = (int *) calloc(tm->par.max_cp_num, ISIZE);
tm->active_nodes_per_cp = (int *) calloc(tm->par.max_cp_num, ISIZE);
}else{
#ifdef COMPILE_IN_CP
tm->cpp = (cut_pool **) calloc(1, sizeof(cut_pool *));
#endif
}
/*------------------------------------------------------------------------*\
* Receive the root node and send out initial data to the LP processes
\*------------------------------------------------------------------------*/
FREE(termcodes);
if (tm->par.warm_start){
if (!tm->rootnode){
if (!(f = fopen(tm->par.warm_start_tree_file_name, "r"))){
printf("Error reading warm start file %s\n\n",
tm->par.warm_start_tree_file_name);
return(ERROR__READING_WARM_START_FILE);
}
read_tm_info(tm, f);
}else{
free(root);
root = tm->rootnode;
}
read_subtree(tm, root, f);
if (f)
fclose(f);
if (!tm->rootnode){
if (!read_tm_cut_list(tm, tm->par.warm_start_cut_file_name)){
printf("Error reading warm start file %s\n\n",
tm->par.warm_start_cut_file_name);
return(ERROR__READING_WARM_START_FILE);
}
}
tm->rootnode = root;
if(root->node_status != NODE_STATUS__WARM_STARTED)
root->node_status = NODE_STATUS__ROOT;
}else{
#ifdef COMPILE_IN_TM
(tm->rootnode = root)->desc = *rootdesc;
/* Copy the root description in case it is still needed */
root->desc.uind.list = (int *) malloc(rootdesc->uind.size*ISIZE);
memcpy((char *)root->desc.uind.list, (char *)rootdesc->uind.list,
rootdesc->uind.size*ISIZE);
root->bc_index = tm->stat.created++;
root->lower_bound = -MAXDOUBLE;
tm->stat.tree_size++;
insert_new_node(tm, root);
tm->phase = 0;
tm->lb = 0;
#else
r_bufid = receive_msg(tm->master, TM_ROOT_DESCRIPTION);
receive_node_desc(tm, root);
if (root->desc.cutind.size > 0){ /* Hey we got cuts, too! Unpack them. */
unpack_cut_set(tm, 0, 0, NULL);
}
freebuf(r_bufid);
#endif
#ifdef TRACE_PATH
root->optimal_path = TRUE;
#endif
}
return(FUNCTION_TERMINATED_NORMALLY);
}
/*===========================================================================*/
/*===========================================================================*\
* This is the main loop that solves the problem
\*===========================================================================*/
int solve(tm_prob *tm)
{
#ifndef COMPILE_IN_LP
int r_bufid;
#endif
int termcode = 0;
double start_time = tm->start_time;
double no_work_start, ramp_up_tm = 0, ramp_down_time = 0;
char ramp_down = FALSE, ramp_up = TRUE;
double then, then2, then3, now;
double timeout2 = 30, timeout3 = tm->par.logging_interval, timeout4 = 10;
/*------------------------------------------------------------------------*\
* The Main Loop
\*------------------------------------------------------------------------*/
no_work_start = wall_clock(NULL);
termcode = TM_UNFINISHED;
for (; tm->phase <= 1; tm->phase++){
if (tm->phase == 1 && !tm->par.warm_start){
if ((termcode = tasks_before_phase_two(tm)) ==
FUNCTION_TERMINATED_NORMALLY){
termcode = TM_FINISHED; /* Continue normally */
}
}
then = wall_clock(NULL);
then2 = wall_clock(NULL);
then3 = wall_clock(NULL);
#pragma omp parallel default(shared)
{
#ifdef _OPENMP
int i, thread_num = omp_get_thread_num();
#else
int i, thread_num = 0;
#endif
while (tm->active_node_num > 0 || tm->samephase_candnum > 0){
/*------------------------------------------------------------------*\
* while there are nodes being processed or while there are nodes
* waiting to be processed, continue to execute this loop
\*------------------------------------------------------------------*/
i = NEW_NODE__STARTED;
while (tm->lp.free_num > 0 && (tm->par.time_limit >= 0.0 ?
(wall_clock(NULL) - start_time < tm->par.time_limit) : TRUE) &&
(tm->par.node_limit >= 0 ?
tm->stat.analyzed < tm->par.node_limit : TRUE) &&
((tm->has_ub && (tm->par.gap_limit >= 0.0)) ?
fabs(100*(tm->ub-tm->lb)/tm->ub) > tm->par.gap_limit : TRUE)
&& !(tm->par.find_first_feasible && tm->has_ub) && c_count <= 0){
if (tm->samephase_candnum > 0){
#pragma omp critical (tree_update)
i = start_node(tm, thread_num);
}else{
i = NEW_NODE__NONE;
}
if (i != NEW_NODE__STARTED)
break;
if (ramp_up){
ramp_up_tm += (wall_clock(NULL) -
no_work_start) * (tm->lp.free_num + 1);
}
if (ramp_down){
ramp_down_time += (wall_clock(NULL) -
no_work_start) * (tm->lp.free_num + 1);
}
if (!tm->lp.free_num){
ramp_down = FALSE;
ramp_up = FALSE;
}else if (ramp_up){
no_work_start = wall_clock(NULL);
}else{
ramp_down = TRUE;
no_work_start = wall_clock(NULL);
}
#ifdef COMPILE_IN_LP
#ifdef _OPENMP
if (tm->par.verbosity > 0)
printf("Thread %i now processing node %i\n", thread_num,
tm->lpp[thread_num]->bc_index);
#endif
if(tm->par.node_selection_rule == DEPTH_FIRST_THEN_BEST_FIRST &&
tm->has_ub){
tm->par.node_selection_rule = LOWEST_LP_FIRST;
}
switch(process_chain(tm->lpp[thread_num])){
case FUNCTION_TERMINATED_NORMALLY:
break;
case ERROR__NO_BRANCHING_CANDIDATE:
termcode = TM_ERROR__NO_BRANCHING_CANDIDATE;
break;
case ERROR__ILLEGAL_RETURN_CODE:
termcode = TM_ERROR__ILLEGAL_RETURN_CODE;
break;
case ERROR__NUMERICAL_INSTABILITY:
termcode = TM_ERROR__NUMERICAL_INSTABILITY;
break;
case ERROR__COMM_ERROR:
termcode = TM_ERROR__COMM_ERROR;
case ERROR__USER:
termcode = TM_ERROR__USER;
break;
case ERROR__DUAL_INFEASIBLE:
if(tm->lpp[thread_num]->bc_index < 1 ) {
termcode = TM_UNBOUNDED;
}else{
termcode = TM_ERROR__NUMERICAL_INSTABILITY;
}
break;
}
#endif
#pragma omp master
{
now = wall_clock(NULL);
if (now - then2 > timeout2){
if(tm->par.verbosity >= -1 ){
print_tree_status(tm);
}
then2 = now;
}
if (now - then3 > timeout3){
write_log_files(tm);
then3 = now;
}
}
}
if (c_count > 0){
termcode = TM_SIGNAL_CAUGHT;
c_count = 0;
break;
}
if (tm->par.time_limit >= 0.0 &&
wall_clock(NULL) - start_time > tm->par.time_limit &&
termcode != TM_FINISHED){
termcode = TM_TIME_LIMIT_EXCEEDED;
break;
}
if (tm->par.node_limit >= 0 && tm->stat.analyzed >=
tm->par.node_limit && termcode != TM_FINISHED){
if (tm->active_node_num + tm->samephase_candnum > 0){
termcode = TM_NODE_LIMIT_EXCEEDED;
}else{
termcode = TM_FINISHED;
}
break;
}
if (tm->par.find_first_feasible && tm->has_ub){
termcode = TM_FINISHED;
break;
}
if (i == NEW_NODE__ERROR){
termcode = SOMETHING_DIED;
break;
}
if (tm->has_ub && (tm->par.gap_limit >= 0.0)){
find_tree_lb(tm);
if (fabs(100*(tm->ub-tm->lb)/tm->ub) <= tm->par.gap_limit){
if (tm->lb < tm->ub){
termcode = TM_TARGET_GAP_ACHIEVED;
}else{
termcode = TM_FINISHED;
}
break;
}
}
if (i == NEW_NODE__NONE && tm->active_node_num == 0)
break;
#ifndef COMPILE_IN_LP
struct timeval timeout = {5, 0};
r_bufid = treceive_msg(ANYONE, ANYTHING, &timeout);
if (r_bufid && !process_messages(tm, r_bufid)){
find_tree_lb(tm);
termcode = SOMETHING_DIED;
break;
}
#endif
now = wall_clock(NULL);
if (now - then > timeout4){
if (!processes_alive(tm)){
find_tree_lb(tm);
termcode = SOMETHING_DIED;
break;
}
then = now;
}
#pragma omp master
{
for (i = 0; i < tm->par.max_active_nodes; i++){
if (tm->active_nodes[i]){
break;
}
}
if (i == tm->par.max_active_nodes){
tm->active_node_num = 0;
}
if (now - then2 > timeout2){
if(tm->par.verbosity >=0 ){
print_tree_status(tm);
}
then2 = now;
}
if (now - then3 > timeout3){
write_log_files(tm);
then3 = now;
}
}
}
}
if(termcode == TM_UNBOUNDED) break;
if (tm->samephase_candnum + tm->active_node_num == 0){
termcode = TM_FINISHED;
}
if (tm->nextphase_candnum == 0)
break;
if (termcode != TM_UNFINISHED)
break;
}
find_tree_lb(tm);
tm->comp_times.ramp_up_tm = ramp_up_tm;
tm->comp_times.ramp_down_time = ramp_down_time;
write_log_files(tm);
return(termcode);
}
/*===========================================================================*/
/*==========================================================================*\
* Write out the log files
\*==========================================================================*/
void write_log_files(tm_prob *tm)
{
#if !defined(COMPILE_IN_LP) || !defined(COMPILE_IN_CP)
int s_bufid;
#endif
if (tm->par.logging){
write_tm_info(tm, tm->par.tree_log_file_name, NULL, FALSE);
write_subtree(tm->rootnode, tm->par.tree_log_file_name, NULL, TRUE,
tm->par.logging);
if (tm->par.logging != VBC_TOOL)
write_tm_cut_list(tm, tm->par.cut_log_file_name, FALSE);
}
if (tm->par.max_cp_num > 0 && tm->par.cp_logging){
#if defined(COMPILE_IN_LP) && defined(COMPILE_IN_CP)
write_cp_cut_list(tm->cpp[0], tm->cpp[0]->par.log_file_name,
FALSE);
#else
s_bufid = init_send(DataInPlace);
send_msg(tm->cp.procs[0], WRITE_LOG_FILE);
#endif
}
}
/*===========================================================================*/
/*==========================================================================*\
* Prints out the current size of the tree and the gap *
\*==========================================================================*/
void print_tree_status(tm_prob *tm)
{
double elapsed_time;
double obj_ub = SYM_INFINITY, obj_lb = -SYM_INFINITY;
#ifdef SHOULD_SHOW_MEMORY_USAGE
int i;
int pid;
int tmp_int;
long unsigned vsize;
char tmp_str[100], proc_filename[100];
FILE *proc_file;
double vsize_in_mb;
#endif
#if 0
int *widths;
double *gamma;
int last_full_level = 0, max_width = 0, num_nodes_estimate = 1;
int first_waist_level = 0, last_waist_level = 0, waist_level = 0;
double average_node_time, estimated_time_remaining, user_time = 0.0;
widths = (int *) calloc (tm->stat.max_depth + 1, ISIZE);
gamma = (double *) calloc (tm->stat.max_depth + 1, DSIZE);
calculate_widths(tm->rootnode, widths);
last_full_level = tm->stat.max_depth;
for (i = tm->stat.max_depth - 1; i > 0; i--){
if ((double)(widths[i])/(double)(widths[i - 1]) < 2){
last_full_level = i - 1;
}
if (widths[i] > max_width){
max_width = widths[i];
last_waist_level = i;
first_waist_level = i;
}
if (widths[i] == max_width){
first_waist_level = i;
}
}
waist_level = (first_waist_level + last_waist_level)/2;
for (i = 0; i < tm->stat.max_depth; i++){
if (i < last_full_level){
gamma[i] = 2.0;
}else if (i < waist_level){
gamma[i] = 2.0 - (double)((i - last_full_level + 1))/
(double)((waist_level - last_full_level + 1));
}else{
gamma[i] = 1.0 - (double)(i - waist_level + 1)/
(double)(tm->stat.max_depth - waist_level + 1);
}
}
for (i = 1; i < tm->stat.max_depth; i++){
gamma[i] *= gamma[i - 1];
num_nodes_estimate += (int)(gamma[i] + 0.5);
}
elapsed_time = wall_clock(NULL) - tm->start_time;
average_node_time = elapsed_time/tm->stat.analyzed;
estimated_time_remaining =
MAX(average_node_time*(num_nodes_estimate - tm->stat.analyzed), 0);
#else
elapsed_time = wall_clock(NULL) - tm->start_time;
#endif
#ifdef SHOULD_SHOW_MEMORY_USAGE
pid = getpid();
//printf("process id = %d\n",pid);
sprintf(proc_filename,"/proc/%d/stat",pid);
proc_file = fopen (proc_filename, "r");
fscanf (proc_file, "%d %s %s", &tmp_int, tmp_str, tmp_str);
for (i=0; i<19;i++) {
fscanf (proc_file, "%d", &tmp_int);
}
fscanf (proc_file, "%lu", &vsize);
fclose(proc_file);
//printf("vsize = %lu\n",vsize);
vsize_in_mb = vsize/1024.0/1024.0;
if (tm->stat.max_vsize<vsize_in_mb) {
tm->stat.max_vsize = vsize_in_mb;
}
printf("memory: %.2f MB ", vsize_in_mb);
#endif
printf("done: %i ", tm->stat.analyzed-tm->active_node_num);
printf("left: %i ", tm->samephase_candnum+tm->active_node_num);
if (tm->has_ub) {
if (tm->obj_sense == SYM_MAXIMIZE){
obj_lb = -tm->ub + tm->obj_offset;
printf("lb: %.2f ", obj_lb);
}else{
obj_ub = tm->ub + tm->obj_offset;
printf("ub: %.2f ", obj_ub);
}
} else {
if (tm->obj_sense == SYM_MAXIMIZE){
printf("lb: ?? ");
}else{
printf("ub: ?? ");
}
}
find_tree_lb(tm);
if(tm->lb > -SYM_INFINITY){
if (tm->obj_sense == SYM_MAXIMIZE){
obj_ub = -tm->lb + tm->obj_offset;
printf("ub: %.2f ", obj_ub);
}else{
obj_lb = tm->lb + tm->obj_offset;
printf("lb: %.2f ", obj_lb);
}
}else{
if (tm->obj_sense == SYM_MAXIMIZE){
printf("ub: ?? ");
}else{
printf("lb: ?? ");
}
}
if (tm->has_ub && tm->ub && tm->lb > -SYM_INFINITY){
printf("gap: %.2f ", fabs(100*(obj_ub-obj_lb)/obj_ub));
}
printf("time: %i\n", (int)(elapsed_time));
#if 0
printf("Estimated nodes remaining: %i\n", num_nodes_estimate);
printf("Estimated time remaining: %i\n",
(int)(estimated_time_remaining));
#endif
if (tm->par.vbc_emulation == VBC_EMULATION_FILE){
FILE *f;
#pragma omp critical(write_vbc_emulation_file)
if (!(f = fopen(tm->par.vbc_emulation_file_name, "a"))){
printf("\nError opening vbc emulation file\n\n");
}else{
PRINT_TIME(tm, f);
fprintf(f, "L %.2f \n", tm->lb);
fclose(f);
}
}else if (tm->par.vbc_emulation == VBC_EMULATION_LIVE){
printf("$L %.2f\n", tm->lb);
}
#if 0
FREE(widths);
FREE(gamma);
#endif
}
/*===========================================================================*/
void calculate_widths(bc_node *node, int* widths)
{
int i;
widths[node->bc_level] += 1;
for (i = 0; i < node->bobj.child_num; i ++){
calculate_widths(node->children[i], widths);
}
}
/*===========================================================================*/
/*===========================================================================*\
* This function picks the "best" node off the active node list
\*===========================================================================*/
int start_node(tm_prob *tm, int thread_num)
{
int lp_ind, get_next, ind;
bc_node *best_node = NULL;
double time;
time = wall_clock(NULL);
/*------------------------------------------------------------------------*\
* First choose the "best" node from the list of candidate nodes.
* If the list for the current phase is empty then we return NEW_NODE__NONE.
* Also, if the lower bound on the "best" node is above the current UB then
* we just move that node the list of next phase candidates.
\*------------------------------------------------------------------------*/
get_next = TRUE;
while (get_next){
if ((best_node = del_best_node(tm)) == NULL)
return(NEW_NODE__NONE);
if (best_node->node_status == NODE_STATUS__WARM_STARTED){
if(best_node->lower_bound >= MAXDOUBLE)
break;
}
/* if no UB yet or lb is lower than UB then go ahead */
if (!tm->has_ub ||
(tm->has_ub && best_node->lower_bound < tm->ub-tm->par.granularity))
break;
/* ok, so we do have an UB and lb is higher than the UB. */
/* in this switch we assume that there are only two phases! */
switch (((best_node->desc.nf_status) << 8) + tm->phase){
case (NF_CHECK_NOTHING << 8) + 0: /* prune these */
case (NF_CHECK_NOTHING << 8) + 1:
if(!tm->par.sensitivity_analysis){
if (tm->par.max_cp_num > 0 && best_node->cp){
#ifdef COMPILE_IN_CP
ind = best_node->cp;
#else
ind = find_process_index(&tm->cp, best_node->cp);
#endif
tm->nodes_per_cp[ind]--;
if (tm->nodes_per_cp[ind] + tm->active_nodes_per_cp[ind] == 0)
tm->cp.free_ind[tm->cp.free_num++] = ind;
}
best_node->node_status = NODE_STATUS__PRUNED;
best_node->feasibility_status = OVER_UB_PRUNED;
if (tm->par.verbosity > 0){
printf("++++++++++++++++++++++++++++++++++++++++++++++++++\n");
printf("+ TM: Pruning NODE %i LEVEL %i instead of sending it.\n",
best_node->bc_index, best_node->bc_level);
printf("++++++++++++++++++++++++++++++++++++++++++++++++++\n");
}
if (tm->par.keep_description_of_pruned == KEEP_ON_DISK_VBC_TOOL ||
tm->par.keep_description_of_pruned == KEEP_ON_DISK_FULL ||
tm->par.keep_description_of_pruned == DISCARD){
if (tm->par.keep_description_of_pruned ==
KEEP_ON_DISK_VBC_TOOL ||
tm->par.keep_description_of_pruned == KEEP_ON_DISK_FULL){
#pragma omp critical (write_pruned_node_file)
write_pruned_nodes(tm, best_node);
}
#if 0
if (tm->par.vbc_emulation == VBC_EMULATION_FILE_NEW) {
purge_pruned_nodes(tm, best_node, VBC_PRUNED_FATHOMED);
} else {
purge_pruned_nodes(tm, best_node, VBC_PRUNED);
}
#else
purge_pruned_nodes(tm, best_node, VBC_PRUNED);
#endif
}
break;
}
case (NF_CHECK_ALL << 8) + 1: /* work on these */
case (NF_CHECK_UNTIL_LAST << 8) + 1:
case (NF_CHECK_AFTER_LAST << 8) + 1:
get_next = FALSE;
break;
default:
/* i.e., phase == 0 and nf_status != NF_CHECK_NOTHING */
if (!(tm->par.colgen_strat[0] & FATHOM__GENERATE_COLS__RESOLVE)){
REALLOC(tm->nextphase_cand, bc_node *, tm->nextphase_cand_size,
tm->nextphase_candnum+1, BB_BUNCH);
tm->nextphase_cand[tm->nextphase_candnum++] = best_node;
}else{
get_next = FALSE;
}
break;
}
}
/* Assign a free lp process */
#ifdef COMPILE_IN_LP
lp_ind = thread_num;
#else
lp_ind = tm->lp.free_ind[--tm->lp.free_num];
best_node->lp = tm->lp.procs[lp_ind];
best_node->cg = tm->par.use_cg ? tm->cg.procs[lp_ind] : 0;
#endif
/* assign pools, too */
best_node->cp = assign_pool(tm, best_node->cp, &tm->cp,
tm->active_nodes_per_cp, tm->nodes_per_cp);
if (best_node->cp < 0) return(NEW_NODE__ERROR);
/* It's time to put together the node and send it out */
tm->active_nodes[lp_ind] = best_node;
tm->active_node_num++;
tm->stat.analyzed++;
send_active_node(tm,best_node,tm->par.colgen_strat[tm->phase],thread_num);
tm->comp_times.start_node += wall_clock(NULL) - time;
return(NEW_NODE__STARTED);
}
/*===========================================================================*/
/*===========================================================================*\
* Returns the "best" active node and deletes it from the list
\*===========================================================================*/
bc_node *del_best_node(tm_prob *tm)
{
bc_node **list = tm->samephase_cand;
int size = tm->samephase_candnum;
bc_node *temp = NULL, *best_node;
int pos, ch;
int rule = tm->par.node_selection_rule;
if (size == 0)
return(NULL);
best_node = list[1];
temp = list[1] = list[size];
tm->samephase_candnum = --size;
if (tm->par.verbosity > 10)
if (tm->samephase_candnum % 10 == 0)
printf("\nTM: tree size: %i , %i\n\n",
tm->samephase_candnum, tm->nextphase_candnum);
pos = 1;
while ((ch=2*pos) < size){
if (node_compar(rule, list[ch], list[ch+1]))
ch++;
if (node_compar(rule, list[ch], temp)){
list[pos] = temp;
return(best_node);
}
list[pos] = list[ch];
pos = ch;
}
if (ch == size){
if (node_compar(rule, temp, list[ch])){
list[pos] = list[ch];
pos = ch;
}
}
list[pos] = temp;
return(best_node);
}
/*===========================================================================*/
/*===========================================================================*\
* Insert a new active node into the active node list (kept as a binary tree)
\*===========================================================================*/
void insert_new_node(tm_prob *tm, bc_node *node)
{
int pos, ch, size = tm->samephase_candnum;
bc_node **list;
int rule = tm->par.node_selection_rule;
tm->samephase_candnum = pos = ++size;
if (tm->par.verbosity > 10)
if (tm->samephase_candnum % 10 == 0)
printf("\nTM: tree size: %i , %i\n\n",
tm->samephase_candnum, tm->nextphase_candnum);
REALLOC(tm->samephase_cand, bc_node *,
tm->samephase_cand_size, size + 1, BB_BUNCH);
list = tm->samephase_cand;
while ((ch=pos>>1) != 0){
if (node_compar(rule, list[ch], node)){
list[pos] = list[ch];
pos = ch;
}else{
break;
}
}
list[pos] = node;
}
/*===========================================================================*/
/*===========================================================================*\
* This is the node comparison function used to order the list of active
* Nodes are ordered differently depending on what the comparison rule is
\*===========================================================================*/
int node_compar(int rule, bc_node *node0, bc_node *node1)
{
switch(rule){
case LOWEST_LP_FIRST:
return(node1->lower_bound < node0->lower_bound ? 1:0);
case HIGHEST_LP_FIRST:
return(node1->lower_bound > node0->lower_bound ? 1:0);
case BREADTH_FIRST_SEARCH:
return(node1->bc_level < node0->bc_level ? 1:0);
case DEPTH_FIRST_SEARCH:
case DEPTH_FIRST_THEN_BEST_FIRST:
return(node1->bc_level > node0->bc_level ? 1:0);
}
return(0); /* fake return */
}
/*===========================================================================*/
/*===========================================================================*\
* Nodes by default inherit their parent's pools. However if there is a free
* pool then the node is moved over to the free pool.
\*===========================================================================*/
int assign_pool(tm_prob *tm, int oldpool, process_set *pools,
int *active_nodes_per_pool, int *nodes_per_pool)
{
int oldind = -1, ind, pool;
#ifndef COMPILE_IN_CP
int s_bufid, r_bufid;
struct timeval timeout = {5, 0};
#endif
if (pools->free_num == 0){
/* No change in the pool assigned to this node */
return(oldpool);
}
if (oldpool > 0){
#ifdef COMPILE_IN_CP
oldind = oldpool;
#else
oldind = find_process_index(pools, oldpool);
#endif
if (nodes_per_pool[oldind] == 1){
nodes_per_pool[oldind]--;
active_nodes_per_pool[oldind]++;
return(oldpool);
}
}
ind = pools->free_ind[--pools->free_num];
#ifdef COMPILE_IN_CP
pool = ind;
#else
pool = pools->procs[ind];
#endif
if (! oldpool){
/* If no pool is assigned yet then just assign the free one */
active_nodes_per_pool[ind] = 1;
return(pool);
}
/* finally when we really move the node from one pool to another */
nodes_per_pool[oldind]--;
active_nodes_per_pool[ind] = 1;
#ifdef COMPILE_IN_CP
/*FIXME: Multiple Pools won't work in shared memory mode until I fill this
in.*/
#else
s_bufid = init_send(DataInPlace);
send_int_array(&oldpool, 1);
send_msg(pool, POOL_YOU_ARE_USELESS);
s_bufid = init_send(DataInPlace);
send_int_array(&pool, 1);
send_msg(oldpool, POOL_COPY_YOURSELF);
freebuf(s_bufid);
do{
r_bufid = treceive_msg(pool, POOL_USELESSNESS_ACKNOWLEDGED, &timeout);
if (r_bufid == 0)
if (pstat(pool) != PROCESS_OK) return(NEW_NODE__ERROR);
}while (r_bufid == 0);
freebuf(r_bufid);
#endif
return(pool);
}
/*===========================================================================*/
/*===========================================================================*\
* Takes the branching object description and sets up data structures
* for the resulting children and adds them to the list of candidates.
\*===========================================================================*/
int generate_children(tm_prob *tm, bc_node *node, branch_obj *bobj,
double *objval, int *feasible, char *action,
int olddive, int *keep, int new_branching_cut)
{
node_desc *desc;
int np_cp = 0, np_sp = 0;
int dive = DO_NOT_DIVE, i;
bc_node *child;
int child_num;
#ifdef TRACE_PATH
int optimal_path = -1;
#endif
/* before we start to generate the children we must figure out if we'll
* dive so that we can put the kept child into the right location */
if (*keep >= 0 && (olddive == CHECK_BEFORE_DIVE || olddive == DO_DIVE))
dive = olddive == DO_DIVE ? DO_DIVE : shall_we_dive(tm, objval[*keep]);
node->children = (bc_node **) calloc(bobj->child_num, sizeof(bc_node *));
if (node->bc_level == tm->stat.max_depth)
tm->stat.max_depth++;
child_num = bobj->child_num;
#ifdef TRACE_PATH
if (node->optimal_path && tm->feas_sol_size){
for (i = 0; i < tm->feas_sol_size; i++)
if (tm->feas_sol[i] == bobj->name)
break;
if (i < tm->feas_sol_size)
optimal_path = 1;
else
optimal_path = 0;
printf("\n\nNode %i is on the optimal path\n\n",
tm->stat.tree_size + optimal_path);
}
#endif
for (i = 0; i < child_num; i++){
child = node->children[i] = (bc_node *) calloc(1, sizeof(bc_node));
child->bc_index = tm->stat.tree_size++;
child->bc_level = node->bc_level + 1;
child->lower_bound = objval[i];
#ifdef COMPILE_IN_LP
child->update_pc = bobj->is_est[i] ? TRUE : FALSE;
#endif
child->parent = node;
if (tm->par.verbosity > 10){
printf("Generating node %i from %i...\n", child->bc_index,
node->bc_index);
}
if (tm->par.vbc_emulation == VBC_EMULATION_FILE){
FILE *f;
#pragma omp critical(write_vbc_emulation_file)
if (!(f = fopen(tm->par.vbc_emulation_file_name, "a"))){
printf("\nError opening vbc emulation file\n\n");
}else{
PRINT_TIME(tm, f);
fprintf(f, "N %i %i %i\n", node->bc_index+1, child->bc_index+1,
feasible[i] ? VBC_FEAS_SOL_FOUND :
((dive != DO_NOT_DIVE && *keep == i) ?
VBC_ACTIVE_NODE : VBC_CAND_NODE));
fclose(f);
}
} else if (tm->par.vbc_emulation == VBC_EMULATION_FILE_NEW) {
FILE *f;
#pragma omp critical(write_vbc_emulation_file)
if (!(f = fopen(tm->par.vbc_emulation_file_name, "a"))){
printf("\nError opening vbc emulation file\n\n");
}else{
PRINT_TIME2(tm, f);
char reason[50];
char branch_dir = 'M';
sprintf (reason, "%s %i %i", "candidate", child->bc_index+1,
node->bc_index+1);
if (child->bc_index>0){
if (node->children[0]==child) {
branch_dir = node->bobj.sense[0];
/*branch_dir = 'L';*/
} else {
branch_dir = node->bobj.sense[1];
/*branch_dir = 'R';*/
}
if (branch_dir == 'G') {
branch_dir = 'R';
}
}
if (action[i] == PRUNE_THIS_CHILD_FATHOMABLE ||
action[i] == PRUNE_THIS_CHILD_INFEASIBLE){
sprintf(reason,"%s %c", reason, branch_dir);
}else{
sprintf(reason,"%s %c %f", reason, branch_dir,
child->lower_bound);
}
fprintf(f,"%s\n",reason);
fclose(f);
}
}else if (tm->par.vbc_emulation == VBC_EMULATION_LIVE){
printf("$N %i %i %i\n", node->bc_index+1, child->bc_index+1,
feasible[i] ? VBC_FEAS_SOL_FOUND :
((dive != DO_NOT_DIVE && *keep == i) ?
VBC_ACTIVE_NODE: VBC_CAND_NODE));
}
#ifdef TRACE_PATH
if (optimal_path == i)
child->optimal_path = TRUE;
#endif
tm->stat.created++;
#ifndef ROOT_NODE_ONLY
if (action[i] == PRUNE_THIS_CHILD ||
action[i] == PRUNE_THIS_CHILD_FATHOMABLE ||
action[i] == PRUNE_THIS_CHILD_INFEASIBLE ||
(tm->has_ub && tm->ub - tm->par.granularity < objval[i] &&
node->desc.nf_status == NF_CHECK_NOTHING)){
/* this last can happen if the TM got the new bound but it hasn't
* been propagated to the LP yet */
#else /*We only want to process the root node in this case - discard others*/
if (TRUE){
#endif
if (tm->par.verbosity > 0){
printf("++++++++++++++++++++++++++++++++++++++++++++++++++++\n");
printf("+ TM: Pruning NODE %i LEVEL %i while generating it.\n",
child->bc_index, child->bc_level);
printf("++++++++++++++++++++++++++++++++++++++++++++++++++++\n");
}
child->node_status = NODE_STATUS__PRUNED;
#ifdef TRACE_PATH
if (child->optimal_path){
printf("\n\nAttempting to prune the optimal path!!!!!!!!!\n\n");
sleep(600);
if (tm->par.logging){
write_tm_info(tm, tm->par.tree_log_file_name, NULL, FALSE);
write_subtree(tm->rootnode, tm->par.tree_log_file_name, NULL,
TRUE, tm->par.logging);
write_tm_cut_list(tm, tm->par.cut_log_file_name, FALSE);
}
exit(1);
}
#endif
if (tm->par.keep_description_of_pruned == DISCARD ||
tm->par.keep_description_of_pruned == KEEP_ON_DISK_VBC_TOOL){
child->parent = node;
if (tm->par.keep_description_of_pruned == KEEP_ON_DISK_VBC_TOOL)
#pragma omp critical (write_pruned_node_file)
write_pruned_nodes(tm, child);
if (tm->par.vbc_emulation == VBC_EMULATION_FILE_NEW) {
int vbc_node_pr_reason;
switch (action[i]) {
case PRUNE_THIS_CHILD_INFEASIBLE:
vbc_node_pr_reason = VBC_PRUNED_INFEASIBLE;
break;
case PRUNE_THIS_CHILD_FATHOMABLE:
vbc_node_pr_reason = VBC_PRUNED_FATHOMED;
break;
default:
vbc_node_pr_reason = VBC_PRUNED;
}
/* following is no longer needed because this care is taken
* care of in install_new_ub
*/
/*
if (feasible[i]) {
vbc_node_pr_reason = VBC_FEAS_SOL_FOUND;
}
*/
#pragma omp critical (tree_update)
purge_pruned_nodes(tm, child, vbc_node_pr_reason);
} else {
#pragma omp critical (tree_update)
purge_pruned_nodes(tm, child, feasible[i] ? VBC_FEAS_SOL_FOUND :
VBC_PRUNED);
}
if (--child_num == 0){
*keep = -1;
return(DO_NOT_DIVE);
}
if (*keep == child_num) *keep = i;
#ifdef TRACE_PATH
if (optimal_path == child_num) optimal_path = i;
#endif
action[i] = action[child_num];
objval[i] = objval[child_num];
feasible[i--] = feasible[child_num];
continue;
}
}else{
child->node_status = NODE_STATUS__CANDIDATE;
/* child->lp = child->cg = 0; zeroed out by calloc */
child->cp = node->cp;
}
#ifdef DO_TESTS
if (child->lower_bound < child->parent->lower_bound - .01){
printf("#######Error: Child's lower bound (%.3f) is less than ",
child->lower_bound);
printf("parent's (%.3f)\n", child->parent->lower_bound);
}
if (child->lower_bound < tm->rootnode->lower_bound - .01){
printf("#######Error: Node's lower bound (%.3f) is less than ",
child->lower_bound);
printf("root's (%.3f)\n", tm->rootnode->lower_bound);
}
#endif
/* child->children = NULL; zeroed out by calloc */
/* child->child_num = 0; zeroed out by calloc */
/* child->died = 0; zeroed out by calloc */
desc = &child->desc;
/* all this is set by calloc
* desc->uind.type = 0; WRT_PARENT and no change
* desc->uind.size = 0;
* desc->uind.added = 0;
* desc->uind.list = NULL;
* desc->not_fixed.type = 0; WRT_PARENT and no change
* desc->not_fixed.size = 0;
* desc->not_fixed.added = 0;
* desc->not_fixed.list = NULL;
* desc->cutind.type = 0; WRT_PARENT and no change
* desc->cutind.size = 0;
* desc->cutind.added = 0;
* desc->cutind.list = NULL;
* desc->basis.basis_exists = FALSE; This has to be validated!!!
* desc->basis.{[base,extra][rows,vars]}
.type = 0; WRT_PARENT and no change
.size = 0;
.list = NULL;
.stat = NULL;
*/
if (node->desc.basis.basis_exists){
desc->basis.basis_exists = TRUE;
}
/* If we have a non-base, new branching cut then few more things
might have to be fixed */
if (new_branching_cut && bobj->name >= 0){
/* Fix cutind and the basis description */
desc->cutind.size = 1;
desc->cutind.added = 1;
desc->cutind.list = (int *) malloc(ISIZE);
desc->cutind.list[0] = bobj->name;
if (desc->basis.basis_exists){
desc->basis.extrarows.size = 1;
desc->basis.extrarows.list = (int *) malloc(ISIZE);
desc->basis.extrarows.list[0] = bobj->name;
desc->basis.extrarows.stat = (int *) malloc(ISIZE);
desc->basis.extrarows.stat[0] = SLACK_BASIC;
}
}
desc->desc_size = node->desc.desc_size;
desc->desc = node->desc.desc;
desc->nf_status = node->desc.nf_status;
#ifdef SENSITIVITY_ANALYSIS
if (tm->par.sensitivity_analysis &&
action[i] != PRUNE_THIS_CHILD_INFEASIBLE){
child->duals = bobj->duals[i];
bobj->duals[i] = 0;
}
#endif
if (child->node_status != NODE_STATUS__PRUNED && feasible[i]){
if(tm->par.keep_description_of_pruned == KEEP_IN_MEMORY){
child->sol_size = bobj->sol_sizes[i];
child->sol_ind = bobj->sol_inds[i];
bobj->sol_inds[i]=0;
child->sol = bobj->solutions[i];
bobj->solutions[i] = 0;
child->feasibility_status = NOT_PRUNED_HAS_CAN_SOLUTION;
}
}
if (child->node_status == NODE_STATUS__PRUNED){
if(tm->par.keep_description_of_pruned == KEEP_IN_MEMORY){
child->feasibility_status = OVER_UB_PRUNED;
if (feasible[i]){
child->sol_size = bobj->sol_sizes[i];
child->sol_ind = bobj->sol_inds[i];
bobj->sol_inds[i] = 0;
child->sol = bobj->solutions[i];
bobj->solutions[i] = 0;
child->feasibility_status = FEASIBLE_PRUNED;
}
if (action[i] == PRUNE_THIS_CHILD_INFEASIBLE){
child->feasibility_status = INFEASIBLE_PRUNED;
}
}
#ifdef TRACE_PATH
if (child->optimal_path){
printf("\n\nAttempting to prune the optimal path!!!!!!!!!\n\n");
sleep(600);
if (tm->par.logging){
write_tm_info(tm, tm->par.tree_log_file_name, NULL, FALSE);
write_subtree(tm->rootnode, tm->par.tree_log_file_name, NULL,
TRUE, tm->par.logging);
write_tm_cut_list(tm, tm->par.cut_log_file_name, FALSE);
}
exit(1);
}
#endif
if (tm->par.keep_description_of_pruned == KEEP_ON_DISK_FULL ||
tm->par.keep_description_of_pruned == KEEP_ON_DISK_VBC_TOOL){
#pragma omp critical (write_pruned_node_file)
write_pruned_nodes(tm, child);
#pragma omp critical (tree_update)
if (tm->par.vbc_emulation== VBC_EMULATION_FILE_NEW) {
int vbc_node_pr_reason;
switch (action[i]) {
case PRUNE_THIS_CHILD_INFEASIBLE:
vbc_node_pr_reason = VBC_PRUNED_INFEASIBLE;
break;
case PRUNE_THIS_CHILD_FATHOMABLE:
vbc_node_pr_reason = VBC_PRUNED_FATHOMED;
break;
default:
vbc_node_pr_reason = VBC_PRUNED;
}
/* following is no longer needed because this care is taken
* care of in install_new_ub
*/
/*
if (feasible[i]) {
vbc_node_pr_reason = VBC_FEAS_SOL_FOUND;
}
*/
purge_pruned_nodes(tm, child, vbc_node_pr_reason);
} else {
purge_pruned_nodes(tm, child, feasible[i] ? VBC_FEAS_SOL_FOUND :
VBC_PRUNED);
}
if (--child_num == 0){
*keep = -1;
return(DO_NOT_DIVE);
}
if (*keep == child_num) *keep = i;
#ifdef TRACE_PATH
if (optimal_path == child_num) optimal_path = i;
#endif
action[i] = action[child_num];
objval[i] = objval[child_num];
feasible[i--] = feasible[child_num];
}
continue;
}
if (tm->phase == 0 &&
!(tm->par.colgen_strat[0] & FATHOM__GENERATE_COLS__RESOLVE) &&
(feasible[i] == LP_D_UNBOUNDED ||
(tm->has_ub && tm->ub - tm->par.granularity < child->lower_bound))){
/* it is kept for the next phase (==> do not dive) */
if (*keep == i)
dive = DO_NOT_DIVE;
REALLOC(tm->nextphase_cand, bc_node *,
tm->nextphase_cand_size, tm->nextphase_candnum+1, BB_BUNCH);
tm->nextphase_cand[tm->nextphase_candnum++] = child;
np_cp++;
np_sp++;
}else{
/* it will be processed in this phase (==> insert it if not kept) */
if (*keep != i || dive == DO_NOT_DIVE){
#pragma omp critical (tree_update)
insert_new_node(tm, child);
np_cp++;
np_sp++;
}
}
}
if (node->cp)
#ifdef COMPILE_IN_CP
tm->nodes_per_cp[node->cp] += np_cp;
#else
tm->nodes_per_cp[find_process_index(&tm->cp, node->cp)] += np_cp;
#endif
return(dive);
}
/*===========================================================================*/
/*===========================================================================*\
* Determines whether or not the LP process should keep one of the
* children resulting from branching or whether it should get a new node
* from the candidate list.
\*===========================================================================*/
char shall_we_dive(tm_prob *tm, double objval)
{
char dive;
int i, k;
double rand_num, average_lb;
double cutoff = 0;
double etol = 1e-3;
if (tm->par.time_limit >= 0.0 &&
wall_clock(NULL) - tm->start_time >= tm->par.time_limit){
return(FALSE);
}
if (tm->par.node_limit >= 0 && tm->stat.analyzed >= tm->par.node_limit){
return(FALSE);
}
if (tm->has_ub && (tm->par.gap_limit >= 0.0)){
find_tree_lb(tm);
if (100*(tm->ub-tm->lb)/(fabs(tm->ub)+etol) <= tm->par.gap_limit){
return(FALSE);
}
}
rand_num = ((double)(RANDOM()))/((double)(MAXINT));
if (tm->par.unconditional_dive_frac > 1 - rand_num){
dive = CHECK_BEFORE_DIVE;
}else{
switch(tm->par.diving_strategy){
case BEST_ESTIMATE:
if (tm->has_ub_estimate){
if (objval > tm->ub_estimate){
dive = DO_NOT_DIVE;
tm->stat.diving_halts++;
}else{
dive = CHECK_BEFORE_DIVE;
}
break;
}
case COMP_BEST_K:
average_lb = 0;
#pragma omp critical (tree_update)
for (k = 0, i = MIN(tm->samephase_candnum, tm->par.diving_k);
i > 0; i--)
if (tm->samephase_cand[i]->lower_bound < MAXDOUBLE/2){
average_lb += tm->samephase_cand[i]->lower_bound;
k++;
}
if (k){
average_lb /= k;
}else{
dive = CHECK_BEFORE_DIVE;
break;
}
if (fabs(average_lb) < etol) {
average_lb = (average_lb > 0) ? etol : -etol;
if (fabs(objval) < etol) {
objval = (objval > 0) ? etol : -etol;
}
}
if (fabs((objval/average_lb)-1) > tm->par.diving_threshold){
dive = DO_NOT_DIVE;
tm->stat.diving_halts++;
}else{
dive = CHECK_BEFORE_DIVE;
}
break;
case COMP_BEST_K_GAP:
average_lb = 0;
for (k = 0, i = MIN(tm->samephase_candnum, tm->par.diving_k);
i > 0; i--)
if (tm->samephase_cand[i]->lower_bound < MAXDOUBLE/2){
average_lb += tm->samephase_cand[i]->lower_bound;
k++;
}
if (k){
average_lb /= k;
}else{
dive = CHECK_BEFORE_DIVE;
break;
}
if (tm->has_ub)
cutoff = tm->par.diving_threshold*(tm->ub - average_lb);
else
cutoff = (1 + tm->par.diving_threshold)*average_lb;
if (objval > average_lb + cutoff){
dive = DO_NOT_DIVE;
tm->stat.diving_halts++;
}else{
dive = CHECK_BEFORE_DIVE;
}
break;
default:
printf("Unknown diving strategy -- diving by default\n");
dive = DO_DIVE;
break;
}
}
return(dive);
}
/*===========================================================================*/
/*===========================================================================*\
* This routine is entirely for saving memory. If there is no need to
* keep the description of the pruned nodes in memory, they are freed as
* soon as they are no longer needed. This can set off a chain reaction
* of other nodes that are no longer needed.
\*===========================================================================*/
int purge_pruned_nodes(tm_prob *tm, bc_node *node, int category)
{
int i, new_child_num;
branch_obj *bobj = &node->parent->bobj;
char reason[30];
char branch_dir = 'M';
if (tm->par.vbc_emulation != VBC_EMULATION_FILE_NEW &&
(category == VBC_PRUNED_INFEASIBLE || category == VBC_PRUNED_FATHOMED
|| category == VBC_IGNORE)) {
printf("Error in purge_pruned_nodes.");
printf("category refers to VBC_EMULATION_FILE_NEW");
printf("when it is not used.\n");
exit(456);
}
if (tm->par.vbc_emulation == VBC_EMULATION_FILE_NEW) {
switch (category) {
case VBC_PRUNED_INFEASIBLE:
sprintf(reason,"%s","infeasible");
sprintf(reason,"%s %i %i",reason, node->bc_index+1,
node->parent->bc_index+1);
if (node->bc_index>0) {
if (node->parent->children[0]==node) {
branch_dir = node->parent->bobj.sense[0];
/*branch_dir = 'L';*/
} else {
branch_dir = node->parent->bobj.sense[1];
/*branch_dir = 'R';*/
}
if (branch_dir == 'G') {
branch_dir = 'R';
}
}
sprintf(reason,"%s %c %s", reason, branch_dir, "\n");
break;
case VBC_PRUNED_FATHOMED:
sprintf(reason,"%s","fathomed");
sprintf(reason,"%s %i %i",reason, node->bc_index+1,
node->parent->bc_index+1);
if (node->bc_index>0) {
if (node->parent->children[0]==node) {
branch_dir = node->parent->bobj.sense[0];
/*branch_dir = 'L';*/
} else {
branch_dir = node->parent->bobj.sense[1];
/*branch_dir = 'R';*/
}
if (branch_dir == 'G') {
branch_dir = 'R';
}
}
sprintf(reason,"%s %c %s", reason, branch_dir, "\n");
break;
case VBC_FEAS_SOL_FOUND:
/* This case has already been dealt in install_new_ub(), hence
* commented out
*/
/* sprintf(reason,"%s","integer");
sprintf(reason,"%s %i %i",reason, node->bc_index+1,
node->parent->bc_index+1);
if (node->parent->children[0]==node) {
branch_dir = 'L';
} else {
branch_dir = 'R';
}
sprintf(reason,"%s %c %f\n", reason, branch_dir, tm->ub);
break;
*/
default:
category = VBC_IGNORE;
break;
}
}
if (node->parent == NULL){
return(1);
}
if (category == VBC_IGNORE) {
#if 0
PRINT(tm->par.verbosity, 1,
("ignoring vbc update in purge_pruned_nodes"));
#endif
} else if (tm->par.vbc_emulation == VBC_EMULATION_FILE){
FILE *f;
#pragma omp critical(write_vbc_emulation_file)
if (!(f = fopen(tm->par.vbc_emulation_file_name, "a"))){
printf("\nError opening vbc emulation file\n\n");
}else{
PRINT_TIME(tm, f);
fprintf(f, "P %i %i\n", node->bc_index+1, category);
fclose(f);
}
} else if (tm->par.vbc_emulation == VBC_EMULATION_LIVE){
printf("$P %i %i\n", node->bc_index+1, category);
} else if (tm->par.vbc_emulation == VBC_EMULATION_FILE_NEW) {
FILE *f;
#pragma omp critical(write_vbc_emulation_file)
if (!(f = fopen(tm->par.vbc_emulation_file_name, "a"))){
printf("\nError opening vbc emulation file\n\n");
}else{
PRINT_TIME2(tm, f);
fprintf(f, "%s", reason);
fclose(f);
}
}
if ((new_child_num = --bobj->child_num) == 0){
if (tm->par.vbc_emulation == VBC_EMULATION_FILE_NEW) {
purge_pruned_nodes(tm, node->parent, VBC_IGNORE);
} else {
purge_pruned_nodes(tm, node->parent, category);
}
}else{
for (i = 0; i <= bobj->child_num; i++){
if (node->parent->children[i] == node){
if (i == new_child_num){
node->parent->children[i] = NULL;
}else{
node->parent->children[i]=node->parent->children[new_child_num];
bobj->sense[i] = bobj->sense[new_child_num];
bobj->rhs[i] = bobj->rhs[new_child_num];
bobj->range[i] = bobj->range[new_child_num];
bobj->branch[i] = bobj->branch[new_child_num];
}
}
}
}
free_tree_node(node);
return(1);
}
/*===========================================================================*\
* This routine is for writing the pruned nodes to disk before deleting them
* from memory.
\*===========================================================================*/
int write_pruned_nodes(tm_prob *tm, bc_node *node)
{
FILE *f = NULL;
branch_obj *bobj = &node->parent->bobj;
if (tm->par.keep_description_of_pruned == KEEP_ON_DISK_FULL ||
tm->par.keep_description_of_pruned == KEEP_ON_DISK_VBC_TOOL){
if (!(f = fopen(tm->par.pruned_node_file_name, "a"))){
printf("\nError opening pruned node file\n\n");
return(0);
}
}
if (node->parent == NULL){
return(1);
}
if (bobj->child_num == 1){
write_pruned_nodes(tm, node->parent);
}
if (tm->par.keep_description_of_pruned == KEEP_ON_DISK_VBC_TOOL){
if (node->parent)
fprintf(f, "%i %i\n", node->parent->bc_index + 1, node->bc_index + 1);
fclose(f);
}else if (tm->par.keep_description_of_pruned == KEEP_ON_DISK_FULL){
write_node(node, tm->par.pruned_node_file_name, f, TRUE);
fclose(f);
}
return(1);
}
/*===========================================================================*/
/*===========================================================================*\
* Find the index of a particular process in a list
\*===========================================================================*/
int find_process_index(process_set *pset, int tid)
{
int i = pset->procnum-1, *procs = pset->procs;
for ( ; i >= 0 && procs[i] != tid; i--);
#ifdef DO_TESTS
if (i == -1){
printf("TM: process index not found !!!\n\n");
exit(-5);
}
#endif
return(i);
}
/*===========================================================================*/
void mark_lp_process_free(tm_prob *tm, int lp, int cp)
{
int ind;
if (tm->cp.procnum > 0){
#ifdef COMPILE_IN_CP
ind = cp;
#else
ind = find_process_index(&tm->cp, cp);
#endif
tm->active_nodes_per_cp[ind]--;
if (tm->nodes_per_cp[ind] + tm->active_nodes_per_cp[ind] == 0)
tm->cp.free_ind[tm->cp.free_num++] = ind;
}
tm->active_nodes[lp] = NULL;
tm->lp.free_ind[tm->lp.free_num++] = lp;
tm->active_node_num--;
}
/*===========================================================================*/
int add_cut_to_list(tm_prob *tm, cut_data *cut)
{
#pragma omp critical (cut_pool)
{
REALLOC(tm->cuts, cut_data *, tm->allocated_cut_num, tm->cut_num + 1,
(tm->cut_num / tm->stat.created + 5) * BB_BUNCH);
cut->name = tm->cut_num;
tm->cuts[tm->cut_num++] = cut;
}
return(cut->name);
}
/*===========================================================================*/
/*===========================================================================*\
* Installs a new upper bound and cleans up the candidate list
\*===========================================================================*/
void install_new_ub(tm_prob *tm, double new_ub, int opt_thread_num,
int bc_index, char branching, int feasible){
bc_node *node, *temp, **list;
int rule, pos, prev_pos, last, i;
tm->has_ub = TRUE;
tm->ub = new_ub;
#ifdef COMPILE_IN_LP
tm->opt_thread_num = opt_thread_num;
#endif
if (tm->par.vbc_emulation == VBC_EMULATION_FILE){
FILE *f;
#pragma omp critical(write_vbc_emulation_file)
if (!(f = fopen(tm->par.vbc_emulation_file_name, "a"))){
printf("\nError opening vbc emulation file\n\n");
}else{
PRINT_TIME(tm, f);
fprintf(f, "U %.2f\n", new_ub);
fclose(f);
}
}else if (tm->par.vbc_emulation == VBC_EMULATION_LIVE){
printf("$U %.2f\n", new_ub);
}else if (tm->par.vbc_emulation == VBC_EMULATION_FILE_NEW &&
(feasible == IP_FEASIBLE || feasible == IP_HEUR_FEASIBLE)){
FILE *f;
// char reason[30];
char branch_dir = 'M';
if (!(f = fopen(tm->par.vbc_emulation_file_name, "a"))){
printf("\nError opening vbc emulation file\n\n");
}else if ((feasible == IP_FEASIBLE && branching) ||
(feasible == IP_HEUR_FEASIBLE)) {
#pragma omp critical(write_vbc_emulation_file)
PRINT_TIME2(tm, f);
fprintf(f, "%s %f %i\n", "heuristic", new_ub, bc_index+1);
}else if (feasible == IP_FEASIBLE && !branching){
node = tm->active_nodes[opt_thread_num];
if (node->bc_index>0) {
if (node->parent->children[0]==node) {
branch_dir = node->parent->bobj.sense[0];
/*branch_dir = 'L';*/
} else {
branch_dir = node->parent->bobj.sense[1];
/*branch_dir = 'R';*/
}
if (branch_dir == 'G') {
branch_dir = 'R';
}
}
PRINT_TIME2(tm, f);
if (node->bc_index){
fprintf (f, "%s %i %i %c %f\n", "integer", node->bc_index+1,
node->parent->bc_index+1, branch_dir, new_ub);
}else{
fprintf (f, "%s %i %i %c %f\n", "integer", 1, 0, 'M', new_ub);
}
}
if (f){
fclose(f);
}
}
/* Remove nodes that can now be fathomed from the list */
#pragma omp critical (tree_update)
{
rule = tm->par.node_selection_rule;
list = tm->samephase_cand;
char has_exchanged = FALSE;
for (last = i = tm->samephase_candnum; i > 0; i--){
has_exchanged = FALSE;
node = list[i];
if (tm->has_ub &&
node->lower_bound >= tm->ub-tm->par.granularity){
if (i != last){
list[i] = list[last];
for (prev_pos = i, pos = i/2; pos >= 1;
prev_pos = pos, pos /= 2){
if (node_compar(rule, list[pos], list[prev_pos])){
temp = list[prev_pos];
list[prev_pos] = list[pos];
list[pos] = temp;
has_exchanged = TRUE;
}else{
break;
}
}
}
tm->samephase_cand[last] = NULL;
last--;
if (tm->par.verbosity > 0){
printf("+++++++++++++++++++++++++++++++++++++++++++++++++++\n");
printf("+ TM: Pruning NODE %i LEVEL %i after new incumbent.\n",
node->bc_index, node->bc_level);
printf("+++++++++++++++++++++++++++++++++++++++++++++++++++\n");
}
if (tm->par.keep_description_of_pruned == DISCARD ||
tm->par.keep_description_of_pruned ==
KEEP_ON_DISK_VBC_TOOL){
if (tm->par.keep_description_of_pruned ==
KEEP_ON_DISK_VBC_TOOL)
#pragma omp critical (write_pruned_node_file)
write_pruned_nodes(tm, node);
if (tm->par.vbc_emulation == VBC_EMULATION_FILE_NEW) {
purge_pruned_nodes(tm, node,
VBC_PRUNED_FATHOMED);
} else {
purge_pruned_nodes(tm, node, VBC_PRUNED);
}
}
}
if (has_exchanged) {
/*
* if exchanges have taken place, node[i] should be
* checked again for pruning
*/
i++;
}
}
tm->samephase_candnum = last;
}
}
/*===========================================================================*/
/*===========================================================================*\
* This routine takes the description of the node after processing and
* compares it to the description before processing. Then it updates
* data structures appropriately. The other functions below are all
* related to this one.
\*===========================================================================*/
void merge_descriptions(node_desc *old_node, node_desc *new_node)
{
if (old_node->basis.basis_exists && new_node->basis.basis_exists){
merge_base_stat(&old_node->basis.basevars, &new_node->basis.basevars);
merge_extra_array_and_stat(&old_node->uind, &old_node->basis.extravars,
&new_node->uind, &new_node->basis.extravars);
merge_base_stat(&old_node->basis.baserows, &new_node->basis.baserows);
merge_extra_array_and_stat(&old_node->cutind,&old_node->basis.extrarows,
&new_node->cutind,&new_node->basis.extrarows);
}else{
old_node->basis = new_node->basis;
merge_arrays(&old_node->uind, &new_node->uind);
merge_arrays(&old_node->cutind, &new_node->cutind);
#ifdef COMPILE_IN_LP
memset((char *)&(new_node->basis), 0, sizeof(basis_desc));
#endif
}
old_node->nf_status = new_node->nf_status;
if (new_node->nf_status == NF_CHECK_AFTER_LAST ||
new_node->nf_status == NF_CHECK_UNTIL_LAST){
merge_arrays(&old_node->not_fixed, &new_node->not_fixed);
}else{
FREE(old_node->not_fixed.list);
}
}
/*===========================================================================*/
void merge_base_stat(double_array_desc *dad, double_array_desc *moddad)
{
if (moddad->type == EXPLICIT_LIST){
FREE(dad->list);
FREE(dad->stat);
*dad = *moddad;
#ifdef COMPILE_IN_LP
moddad->stat = NULL;
#endif
return;
}
/* we've got a diff list against the old list */
if (moddad->size > 0) { /* if there is a change */
if (dad->type == EXPLICIT_LIST){
/* just overwrite the changes */
int i;
int *oldstat = dad->stat;
int newsize = moddad->size;
int *newlist = moddad->list;
int *newstat = moddad->stat;
for (i = newsize - 1; i >= 0; i--)
oldstat[newlist[i]] = newstat[i];
}else{
merge_double_array_descs(dad, moddad);
}
}
}
/*===========================================================================*/
void merge_extra_array_and_stat(array_desc *ad, double_array_desc *dad,
array_desc *modad, double_array_desc *moddad)
{
if (moddad->type != WRT_PARENT){
/* If moddad is explicit then just use it */
FREE(dad->list);
FREE(dad->stat);
*dad = *moddad;
#ifdef COMPILE_IN_LP
moddad->stat = NULL;
#endif
}else{
/* So moddad is WRT. Then dad must be WRT, too!! */
/* First throw out from dad everything that's just been deleted */
int newdeled = modad->size - modad->added;
int *newtodel = modad->list + modad->added;
int i, j, k, nextdel;
if (newdeled > 0 && dad->size > 0){
int dsize = dad->size;
int *dlist = dad->list;
int *dstat = dad->stat;
k = j = 0;
for (i = 0; i < newdeled; ){
nextdel = newtodel[i];
for (; j < dsize && dlist[j] < nextdel; ){
dlist[k] = dlist[j];
dstat[k++] = dstat[j++];
}
if (j == dsize){
break;
}else{ /* in this case dlist[j] >= nextdel */
i++;
if (dlist[j] == nextdel)
j++;
}
}
while (j < dsize){
dlist[k] = dlist[j];
dstat[k++] = dstat[j++];
}
dad->size = k;
}
/* Now merge the remaining dad and moddad together */
merge_double_array_descs(dad, moddad);
}
/* dad is fine now. Update ad */
merge_arrays(ad, modad);
}
/*===========================================================================*/
/*===========================================================================*\
* Merge the old and new changes together, in case of identical
* userindices the newer value overrides the older
\*===========================================================================*/
void merge_double_array_descs(double_array_desc *dad,
double_array_desc *moddad)
{
if (moddad->size != 0){
if (dad->size == 0){
*dad = *moddad;
#ifdef COMPILE_IN_LP
moddad->stat = moddad->list = NULL;
#endif
}else{
int i, j, k;
int oldsize = dad->size;
int *oldlist = dad->list;
int *oldstat = dad->stat;
int newsize = moddad->size;
int *newlist = moddad->list;
int *newstat = moddad->stat;
int *dlist = dad->list = (int *) malloc((oldsize+newsize) * ISIZE);
int *dstat = dad->stat = (int *) malloc((oldsize+newsize) * ISIZE);
for (k = 0, i = j = 0; i < oldsize && j < newsize; ){
if (oldlist[i] < newlist[j]){
dlist[k] = oldlist[i];
dstat[k++] = oldstat[i++];
}else{
if (oldlist[i] == newlist[j])
i++;
dlist[k] = newlist[j];
dstat[k++] = newstat[j++];
}
}
while (i < oldsize){
dlist[k] = oldlist[i];
dstat[k++] = oldstat[i++];
}
while (j < newsize){
dlist[k] = newlist[j];
dstat[k++] = newstat[j++];
}
dad->size = k;
FREE(oldlist);
FREE(oldstat);
FREE(moddad->list);
FREE(moddad->stat);
}
}
}
/*===========================================================================*/
void merge_arrays(array_desc *array, array_desc *adesc)
{
if (adesc->type != WRT_PARENT){
/* Replace the old with the new one */
FREE(array->list);
*array = *adesc;
#ifdef COMPILE_IN_LP
adesc->list = NULL;
#endif
return;
}
if (adesc->size == 0){
/* No change, leave the old description alone. */
return;
}
if (array->size == 0){
/* The old size is 0 (the new type is still WRT_PARENT).
If the old type was WRT_PARENT then we can simply replace it with
the new WRT_PARENT data.
If it was EXPLICIT_LIST with nothing in it, then... contradiction!
it would be shorter to explicitly list the new stuff then wrt an
empty explicit list. */
*array = *adesc;
#ifdef COMPILE_IN_LP
adesc->list = NULL;
#endif
}else{
/* OK, array is either WRT or EXP.
But!!! If array is EXP then array->added is set to array->size, so
we can handle it exactly as if it were WRT!
*/
/* Now comes the ugly part... we had an old WRT list and got a new
one wrt to the old (none of them is empty)... Create a correct one
now.
For extra vars/rows the basis status further complicates things.
If we had the basis stati stored as EXP, then we don't have to worry
about it, since we are going to receive an EXP. But if it was WRT
then we must delete the from the basis stati list the extras to be
deleted according to the new description! */
int i, j, k, *list;
int newsize = adesc->size;
int newadded = adesc->added;
int *newtoadd = adesc->list;
int newdeled = newsize - newadded;
int *newtodel = newtoadd + newadded;
int oldadded = array->added;
int *oldtoadd = array->list;
int olddeled = array->size - oldadded;
int *oldtodel = oldtoadd + oldadded;
/* cancel those both in oldtoadd and newdeled; also those both in
newtoadd and olddeled.
Then the unions of oldtoadd-newtodel and oldtodel-newtoadd will be
the correct list. */
/* First count the number of collisions and mark the colliding ones */
k = 0;
for (i = j = 0; i < oldadded && j < newdeled; ){
if (oldtoadd[i] < newtodel[j]) i++;
else if (oldtoadd[i] > newtodel[j]) j++;
else{
oldtoadd[i] = newtodel[j] = -1;
i++;
j++;
k++;
}
}
for (i = j = 0; i < newadded && j < olddeled; ){
if (newtoadd[i] < oldtodel[j]) i++;
else if (newtoadd[i] > oldtodel[j]) j++;
else{
newtoadd[i] = oldtodel[j] = -1;
i++;
j++;
k++;
}
}
array->size = array->size + newsize - 2 * k;
if (array->size == 0){
/* Nothing is left, great! */
array->added = 0;
FREE(adesc->list);
FREE(array->list);
}else{
array->list = list = (int *) malloc(array->size * ISIZE);
for (i = j = k = 0; i < oldadded && j < newadded; ){
if (oldtoadd[i] == -1) i++;
else if (newtoadd[j] == -1) j++;
else if (oldtoadd[i] < newtoadd[j]) list[k++] = oldtoadd[i++];
else /* can't be == */ list[k++] = newtoadd[j++];
}
for ( ; i < oldadded; i++)
if (oldtoadd[i] != -1) list[k++] = oldtoadd[i];
for ( ; j < newadded; j++)
if (newtoadd[j] != -1) list[k++] = newtoadd[j];
array->added = k;
for (i = j = 0; i < olddeled && j < newdeled; ){
if (oldtodel[i] == -1) i++;
else if (newtodel[j] == -1) j++;
else if (oldtodel[i] < newtodel[j]) list[k++] = oldtodel[i++];
else /* can't be == */ list[k++] = newtodel[j++];
}
for ( ; i < olddeled; i++)
if (oldtodel[i] != -1) list[k++] = oldtodel[i];
for ( ; j < newdeled; j++)
if (newtodel[j] != -1) list[k++] = newtodel[j];
FREE(adesc->list); /* adesc->list */
FREE(oldtoadd); /* the old array->list */
}
}
}
/*===========================================================================*/
/*===========================================================================*\
* This routine modifies a list of integers, by deleting those listed in
* todel and adding those listed in toadd. todel is a subset of iarray,
* toadd has no common element with iarray.
\*===========================================================================*/
void modify_list(array_desc *origad, array_desc *modad)
{
int j, k, l, nextdel;
int added = modad->added;
int *toadd = modad->list;
int deled = modad->size - modad->added;
int *todel = toadd + added;
int size = origad->size;
int *origlist = origad->list;
if (deled){
/* l is the location where we copy to; and k is where we copy from */
l = k = 0;
for (j = 0; j < deled; k++, j++){
nextdel = todel[j];
for (; origlist[k] != nextdel; origlist[l++] = origlist[k++]);
}
for (; k < size; origlist[l++] = origlist[k++]);
size = l;
}
if (added){
/* add toadd to origlist */
for (l = size+added-1, k = added-1, j = size-1; k >= 0 && j >= 0; ){
if (origlist[j] > toadd[k])
origlist[l--] = origlist[j--];
else
origlist[l--] = toadd[k--];
}
if (k >= 0)
memcpy(origlist, toadd, (k+1) * ISIZE);
size += added;
}
origad->size = size;
}
/*===========================================================================*/
void modify_list_and_stat(array_desc *origad, int *origstat,
array_desc *modad, double_array_desc *moddad)
{
int i, j, k, l, nextdel;
int added = modad->added;
int *toadd = modad->list;
int deled = modad->size - modad->added;
int *todel = toadd + added;
int size = origad->size;
int *origlist = origad->list;
/* First modify origad, and at the same time delete the appropriate entries
from origstat as well as insert phony ones where needed */
if (deled){
/* l is the location where we copy to; and k is where we copy from */
l = k = 0;
for (j = 0; j < deled; k++, j++){
nextdel = todel[j];
for (; origlist[k] != nextdel; ){
origstat[l] = origstat[k];
origlist[l++] = origlist[k++];
}
}
for (; k < size; ){
origstat[l] = origstat[k];
origlist[l++] = origlist[k++];
}
size = l;
}
if (added){
/* add toadd to origlist */
for (l = size+added-1, k = added-1, j = size-1; k >= 0 && j >= 0; )
if (origlist[j] > toadd[k]){
origstat[l] = origstat[j];
origlist[l--] = origlist[j--];
}else{
origstat[l] = INVALID_BASIS_STATUS;
origlist[l--] = toadd[k--];
}
if (k >= 0){
for ( ; k >= 0; ){
origstat[l] = INVALID_BASIS_STATUS;
origlist[l--] = toadd[k--];
}
}
size += added;
}
origad->size = size;
#ifdef DO_TM_BASIS_TESTS
if (origad->size == 0 && moddad->size > 0){
printf("TM: Problem with storing the basis!!\n\n");
exit(990);
}
#endif
/* Now adjust the basis stati */
if (origad->size > 0 && moddad->size > 0){
int *modlist = moddad->list;
int *modstat = moddad->stat;
for (i = moddad->size - 1, j = origad->size - 1; i >= 0 && j >= 0; j--){
if (origlist[j] == modlist[i])
origstat[j] = modstat[i--];
#ifdef DO_TM_BASIS_TESTS
else if (origlist[j] < modlist[i]){
printf("TM: Problem with storing the basis!!\n\n");
exit(990);
}
#endif
}
#ifdef DO_TM_BASIS_TESTS
if (i >= 0){
printf("TM: Problem with storing the basis!!\n\n");
exit(990);
}
#endif
}
#ifdef DO_TM_BASIS_TESTS
for (j = origad->size - 1; j >= 0; j--){
if (origstat[j] == INVALID_BASIS_STATUS){
printf("TM: Problem with storing the basis!!\n\n");
exit(990);
}
}
#endif
}
/*===========================================================================*/
/*===========================================================================*\
* Do some tasks before phase 2. Thes are:
* - price out variables in the root if requested
* - build up the samephase_cand binary tree
* - inform everyone about it
\*===========================================================================*/
int tasks_before_phase_two(tm_prob *tm)
{
#if !defined(COMPILE_IN_TM)||(defined(COMPILE_IN_TM)&&!defined(COMPILE_IN_LP))
int s_bufid;
#endif
#ifdef COMPILE_IN_LP
int num_threads = 1;
#else
int r_bufid, msgtag, bytes, sender, not_fixed_size;
#endif
int i;
bc_node *n;
int termcode = 0;
#ifdef COMPILE_IN_LP
#ifdef _OPENMP
num_threads = omp_get_num_threads();
#endif
for (i = 0; i < num_threads; i++){
free_node_desc(&tm->lpp[i]->desc);
tm->lpp[i]->phase = 1;
}
#else
/* Notify the LPs about the start of the second phase and get back the
timing data for the first phase */
s_bufid = init_send(DataInPlace);
msend_msg(tm->lp.procs, tm->lp.procnum, LP__SECOND_PHASE_STARTS);
#endif
if (tm->par.price_in_root && tm->has_ub){
/* put together a message and send it out to an LP process. At this
point tm->rootnode->{lp,cg,cp,sp} should still be set to wherever
it was first processed */
#ifdef DO_TESTS
if ((!tm->rootnode->lp) ||
(!tm->rootnode->cg && tm->par.use_cg) ||
(!tm->rootnode->cp && tm->cp.procnum > 0)){
printf("When trying to send root for repricing, the root doesn't\n");
printf(" have some process id correctly set!\n\n");
exit(-100);
}
#endif
send_active_node(tm, tm->rootnode, COLGEN_REPRICING, 0);
}
/* trim the tree */
tm->stat.leaves_before_trimming = tm->nextphase_candnum;
if (tm->par.trim_search_tree && tm->has_ub)
tm->stat.tree_size -= trim_subtree(tm, tm->rootnode);
/* while the LP is working, build up the samephase_cand binary tree */
REALLOC(tm->samephase_cand, bc_node *,
tm->samephase_cand_size, tm->nextphase_candnum + 1, BB_BUNCH);
for (i = 0; i < tm->nextphase_candnum; i++){
if ((n = tm->nextphase_cand[i])){
if (n->bc_index >= 0){
insert_new_node(tm, n);
}else{
free_tree_node(n);
}
}
}
tm->stat.leaves_after_trimming = tm->samephase_candnum;
if ((termcode = receive_lp_timing(tm)) < 0)
return(SOMETHING_DIED);
if (tm->par.price_in_root && tm->has_ub){
/* receive what the LP has to say, what is the new not_fixed list.
* also, incorporate that list into the not_fixed field of everything */
#ifdef COMPILE_IN_LP
switch(process_chain(tm->lpp[0])){
case FUNCTION_TERMINATED_NORMALLY:
break;
case ERROR__NO_BRANCHING_CANDIDATE:
return(TM_ERROR__NO_BRANCHING_CANDIDATE);
case ERROR__ILLEGAL_RETURN_CODE:
return(TM_ERROR__ILLEGAL_RETURN_CODE);
case ERROR__NUMERICAL_INSTABILITY:
return(TM_ERROR__NUMERICAL_INSTABILITY);
case ERROR__USER:
return(TM_ERROR__USER);
}
#else
char go_on;
int nsize, nf_status;
do{
r_bufid = receive_msg(tm->rootnode->lp, ANYTHING);
bufinfo(r_bufid, &bytes, &msgtag, &sender);
switch (msgtag){
case LP__NODE_DESCRIPTION:
n = (bc_node *) calloc(1, sizeof(bc_node));
receive_node_desc(tm, n);
tm->stat.root_lb = n->lower_bound;
if (n->node_status == NODE_STATUS__PRUNED){
/* Field day! Proved optimality! */
free_subtree(tm->rootnode);
tm->rootnode = n;
tm->samephase_candnum = tm->nextphase_candnum = 0;
return (FUNCTION_TERMINATED_NORMALLY);
}
/* Otherwise in 'n' we have the new description of the root node.
We don't care about the cuts, just the not fixed variables.
We got to pay attention to changes in uind and not_fixed.
We won't change the uind in root but put every change into
not_fixed.
The new not_fixed list will comprise of the vars added to uind
and whatever is in the new not_fixed. */
if (n->desc.uind.size > 0){
array_desc *uind = &n->desc.uind;
array_desc *ruind = &tm->rootnode->desc.uind;
int usize = uind->size;
int rusize = ruind->size;
int *ulist = uind->list;
int *rulist = ruind->list;
int j, k;
/* Kick out from uind those in root's uind */
for (i = 0, j = 0, k = 0; i < usize && j < rusize; ){
if (ulist[i] < rulist[j]){
/* a new element in uind */
ulist[k++] = ulist[i++];
}else if (ulist[i] < rulist[j]){
/* something got kicked out of ruind */
j++;
}else{ /* ulist[i] == rulist[j] */
/* It just stayed there peacefully */
i++; j++;
}
}
if (i < usize){
/* The rest are new */
for ( ; i < usize; i++, k++)
ulist[k] = ulist[i];
}
if ((usize = k) > 0){
if ((nsize = n->desc.not_fixed.size) == 0){
/* All we got is from uind */
n->desc.not_fixed.size = usize;
n->desc.not_fixed.list = ulist;
uind->list = NULL;
}else{
/* Now merge whatever is left in ulist with not_fixed.
Note that the two lists are disjoint. */
int *not_fixed = (int *) malloc((usize + nsize) * ISIZE);
int *nlist = n->desc.not_fixed.list;
for (not_fixed_size=i=j=k=0; i < usize && j < nsize;
not_fixed_size++){
if (ulist[i] < nlist[j]){
not_fixed[k++] = ulist[i++];
}else if (ulist[i] > nlist[j]){
not_fixed[k++] = nlist[j++];
}else{
not_fixed[k++] = nlist[j++];
i++;
}
}
if (i < usize)
memcpy(not_fixed+k, ulist+i, (usize-i)*ISIZE);
if (j < nsize)
memcpy(not_fixed+k, nlist+j, (nsize-j)*ISIZE);
FREE(nlist);
n->desc.not_fixed.size = not_fixed_size;
n->desc.not_fixed.list = not_fixed;
}
}
}
/* OK, now every new thingy is in n->desc.not_fixed */
nsize = n->desc.not_fixed.size;
if (nsize == 0){
/* Field day! Proved optimality!
Caveats:
This proves optimality, but the current tree may not contain
this proof, since the cuts used in pricing out might be
different from those originally in the root.
For now just accept this sad fact and report optimality.
Later, when the tree could be written out on disk, take care
of writing out BOTH root descriptions to prove optimality.
FIXME */
if (tm->par.keep_description_of_pruned){
/* We got to write it out here. */
}
free_tree_node(n);
tm->samephase_candnum = tm->nextphase_candnum = 0;
return(FUNCTION_TERMINATED_NORMALLY);
}else{
tm->rootnode->desc.not_fixed.list = n->desc.not_fixed.list;
n->desc.not_fixed.list = NULL;
if (nsize > tm->par.not_fixed_storage_size){
tm->rootnode->desc.not_fixed.size =
tm->par.not_fixed_storage_size;
nf_status = NF_CHECK_AFTER_LAST;
}else{
tm->rootnode->desc.not_fixed.size = nsize;
nf_status = NF_CHECK_UNTIL_LAST;
}
}
propagate_nf_status(tm->rootnode, nf_status);
tm->stat.nf_status = nf_status;
tm->stat.vars_not_priced = tm->rootnode->desc.not_fixed.size;
free_tree_node(n);
go_on = FALSE;
break;
case UPPER_BOUND:
process_ub_message(tm);
go_on = TRUE;
break;
case LP__CUT_NAMES_REQUESTED:
unpack_cut_set(tm, sender, 0, NULL);
go_on = TRUE;
break;
default: /* We shouldn't get anything else */
printf("Unexpected message at repricing! (%i)\n\n", msgtag);
return(ERROR__COMM_ERROR);
}
}while (go_on);
#endif
}
#ifdef COMPILE_IN_TM
if (tm->samephase_candnum > 0){
printf( "\n");
printf( "**********************************************\n");
printf( "* Branch and Cut First Phase Finished!!!! *\n");
printf( "* Now displaying stats and best solution... *\n");
printf( "**********************************************\n\n");
print_statistics(&(tm->comp_times), &(tm->stat), &(tm->lp_stat),
tm->ub, tm->lb, 0,
tm->start_time, wall_clock(NULL),
tm->obj_offset,
tm->obj_sense, tm->has_ub,NULL);
}
#else
/* Report to the master all kind of statistics */
s_bufid = init_send(DataInPlace);
send_char_array((char *)&tm->comp_times, sizeof(node_times));
send_char_array((char *)&tm->lp_stat, sizeof(lp_stat_desc));
send_dbl_array(&tm->lb, 1);
send_char_array((char *)&tm->stat, sizeof(tm_stat));
send_msg(tm->master, TM_FIRST_PHASE_FINISHED);
#endif
tm->nextphase_candnum = 0;
return(FUNCTION_TERMINATED_NORMALLY);
}
/*===========================================================================*/
/*===========================================================================*\
* For now we'll trim the tree only between phases when nothing is processed.
* Reason: It's kinda ugly to cut off a subtree when several of its nodes
* might be processed. Nevertheless, this should be done sooner or later.
*
* FIXME!
*
\*===========================================================================*/
int trim_subtree(tm_prob *tm, bc_node *n)
{
int i, deleted = 0, not_pruned = 0;
/* Theer isn't anything to do if this is a leaf. */
if (n->bobj.child_num == 0)
return(0);
/* There isn't anything to do if all children are pruned, and we are
better off to go down if only one is not pruned. */
for (i = n->bobj.child_num - 1; i >= 0; i--)
if (n->children[i]->node_status != NODE_STATUS__PRUNED)
if (++not_pruned > 1)
break;
if (not_pruned == 0)
return(0);
if (not_pruned == 1){
for (i = n->bobj.child_num - 1; i >= 0; i--)
if (n->children[i]->node_status != NODE_STATUS__PRUNED){
deleted = trim_subtree(tm, n->children[i]);
break;
}
return(deleted);
}
/* So there are at least two not pruned. */
for (i = n->bobj.child_num - 1; i >= 0; i--)
if (n->children[i]->lower_bound + tm->par.granularity < tm->ub)
break;
/* if all children have high objval */
if (i < 0){
/* put back this node into the nodes_per_... stuff */
if (tm->par.max_cp_num > 0 && n->cp)
#ifdef COMPILE_IN_CP
tm->nodes_per_cp[n->cp]++;
#else
tm->nodes_per_cp[find_process_index(&tm->cp, n->cp)]++;
#endif
/* also put the node on the nextphase list */
REALLOC(tm->nextphase_cand, bc_node *,
tm->nextphase_cand_size, tm->nextphase_candnum+1, BB_BUNCH);
tm->nextphase_cand[tm->nextphase_candnum++] = n;
/* get rid of the children */
for (i = n->bobj.child_num - 1; i >= 0; i--)
deleted += mark_subtree(tm, n->children[i]);
/* free the children description */
FREE(n->children);
n->bobj.child_num = 0;
#ifndef MAX_CHILDREN_NUM
FREE(n->bobj.sense);
FREE(n->bobj.rhs);
FREE(n->bobj.range);
FREE(n->bobj.branch);
#endif
FREE(n->bobj.solutions); //added by asm4
}else{
/* try to trim every child */
for (i = n->bobj.child_num - 1; i >= 0; i--)
deleted += trim_subtree(tm, n->children[i]);
}
return(deleted);
}
/*===========================================================================*/
int mark_subtree(tm_prob *tm, bc_node *n)
{
int i, deleted = 0;
/* mark the node trimmed */
if (n->bobj.child_num == 0){
/* if this was a leaf and it is not pruned,
delete it from the nodes_per_... stuff */
if (n->node_status != NODE_STATUS__PRUNED){
if (tm->par.max_cp_num > 0 && n->cp){
#ifdef COMPILE_IN_CP
i = n->cp;
#else
i = find_process_index(&tm->cp, n->cp);
#endif
tm->nodes_per_cp[i]--;
if (tm->nodes_per_cp[i] + tm->active_nodes_per_cp[i] == 0)
tm->cp.free_ind[tm->cp.free_num++] = i;
}
n->bc_index = -1;
}else{
/* if it was pruned already the free it now */
free_tree_node(n);
}
}else{
/* if non-leaf then process the children recursively and then free
the node */
for (i = n->bobj.child_num - 1; i >= 0; i--)
deleted += mark_subtree(tm, n->children[i]);
free_tree_node(n);
}
return(++deleted);
}
/*===========================================================================*/
void propagate_nf_status(bc_node *n, int nf_status)
{
int i;
for (i = n->bobj.child_num - 1; i >= 0; i--)
propagate_nf_status(n->children[i], nf_status);
n->desc.nf_status = nf_status;
}
/*===========================================================================*/
/*===========================================================================*\
* The functions below are for logging. They write out all necessary
* data to a file so that a warmstart can be made.
\*===========================================================================*/
int write_node(bc_node *node, char *file, FILE* f, char append)
{
int i;
char close = FALSE;
if (!f){
if (!(f = fopen(file, append ? "a" : "w"))){
printf("\nError opening node file\n\n");
return(0);
}
close = TRUE;
}
if (append)
fprintf(f, "\n");
fprintf(f, "NODE INDEX: %i\n", node->bc_index);
fprintf(f, "NODE LEVEL: %i\n", node->bc_level);
fprintf(f, "LOWER BOUND: %f\n", node->lower_bound);
fprintf(f, "NODE STATUS: %i\n", (int)node->node_status);
#ifdef TRACE_PATH
fprintf(f, "OPTIMAL PATH: %i\n", (int)node->optimal_path);
#endif
if (node->parent)
fprintf(f, "PARENT INDEX: %i\n", node->parent->bc_index);
else
fprintf(f, "PARENT INDEX: -1\n");
fprintf(f, "CHILDREN: %i %i %i\n", (int)node->bobj.type,
node->bobj.name, node->bobj.child_num);
for (i = 0; i < node->bobj.child_num; i++)
fprintf(f, "%i %c %f %f %i\n", node->children[i]->bc_index,
node->bobj.sense[i], node->bobj.rhs[i],
node->bobj.range[i], node->bobj.branch[i]);
fprintf(f, "NODE DESCRIPTION: %i\n", node->desc.nf_status);
fprintf(f, "USER INDICES: %i %i %i\n", (int)node->desc.uind.type,
node->desc.uind.size, node->desc.uind.added);
for (i = 0; i < node->desc.uind.size; i++)
fprintf(f, "%i\n", node->desc.uind.list[i]);
fprintf(f, "NOT FIXED: %i %i %i\n", (int)node->desc.not_fixed.type,
node->desc.not_fixed.size, node->desc.not_fixed.added);
for (i = 0; i < node->desc.not_fixed.size; i++)
fprintf(f, "%i\n", node->desc.not_fixed.list[i]);
fprintf(f, "CUT INDICES: %i %i %i\n", (int)node->desc.cutind.type,
node->desc.cutind.size, node->desc.cutind.added);
for (i = 0; i < node->desc.cutind.size; i++)
fprintf(f, "%i\n", node->desc.cutind.list[i]);
fprintf(f, "BASIS: %i\n", (int)node->desc.basis.basis_exists);
fprintf(f, "BASE VARIABLES: %i %i\n", (int)node->desc.basis.basevars.type,
node->desc.basis.basevars.size);
if (node->desc.basis.basevars.type == WRT_PARENT)
for (i = 0; i < node->desc.basis.basevars.size; i++)
fprintf(f, "%i %i\n", node->desc.basis.basevars.list[i],
node->desc.basis.basevars.stat[i]);
else
for (i = 0; i < node->desc.basis.basevars.size; i++)
fprintf(f, "%i\n", node->desc.basis.basevars.stat[i]);
fprintf(f, "EXTRA VARIABLES: %i %i\n", (int)node->desc.basis.extravars.type,
node->desc.basis.extravars.size);
if (node->desc.basis.extravars.type == WRT_PARENT)
for (i = 0; i < node->desc.basis.extravars.size; i++)
fprintf(f, "%i %i\n", node->desc.basis.extravars.list[i],
node->desc.basis.extravars.stat[i]);
else
for (i = 0; i < node->desc.basis.extravars.size; i++)
fprintf(f, "%i\n", node->desc.basis.extravars.stat[i]);
fprintf(f, "BASE ROWS: %i %i\n", (int)node->desc.basis.baserows.type,
node->desc.basis.baserows.size);
if (node->desc.basis.baserows.type == WRT_PARENT)
for (i = 0; i < node->desc.basis.baserows.size; i++)
fprintf(f, "%i %i\n", node->desc.basis.baserows.list[i],
node->desc.basis.baserows.stat[i]);
else
for (i = 0; i < node->desc.basis.baserows.size; i++)
fprintf(f, "%i\n", node->desc.basis.baserows.stat[i]);
fprintf(f, "EXTRA ROWS: %i %i\n", (int)node->desc.basis.extrarows.type,
node->desc.basis.extrarows.size);
if (node->desc.basis.extrarows.type == WRT_PARENT)
for (i = 0; i < node->desc.basis.extrarows.size; i++)
fprintf(f, "%i %i\n", node->desc.basis.extrarows.list[i],
node->desc.basis.extrarows.stat[i]);
else
for (i = 0; i < node->desc.basis.extrarows.size; i++)
fprintf(f, "%i\n", node->desc.basis.extrarows.stat[i]);
if (close)
fclose(f);
return(1);
}
/*===========================================================================*/
int read_node(tm_prob *tm, bc_node *node, FILE *f, int **children)
{
int i, parent = 0, tmp = 0;
char str1[10], str2[10];
if (f){
fscanf(f, "%s %s %i", str1, str2, &node->bc_index);
fscanf(f, "%s %s %i", str1, str2, &node->bc_level);
fscanf(f, "%s %s %lf", str1, str2, &node->lower_bound);
fscanf(f, "%s %s %i", str1, str2, &tmp);
node->node_status = (char)tmp;
#ifdef TRACE_PATH
fscanf(f, "%s %s %i\n", str1, str2, &tmp);
node->optimal_path = (char)tmp;
#endif
fscanf(f, "%s %s %i", str1, str2, &parent);
fscanf(f, "%s %i %i %i", str1, &tmp,
&node->bobj.name, &node->bobj.child_num);
node->bobj.type = (char)tmp;
if (node->bobj.child_num){
#ifndef MAX_CHILDREN_NUM
node->bobj.sense = malloc(node->bobj.child_num*sizeof(char));
node->bobj.rhs = (double *) malloc(node->bobj.child_num*DSIZE);
node->bobj.range = (double *) malloc(node->bobj.child_num*DSIZE);
node->bobj.branch = (int *) malloc(node->bobj.child_num*ISIZE);
#endif
*children = (int *) malloc(node->bobj.child_num*ISIZE);
for (i = 0; i < node->bobj.child_num; i++)
fscanf(f, "%i %c %lf %lf %i", *children+i, node->bobj.sense+i,
node->bobj.rhs+i, node->bobj.range+i, node->bobj.branch+i);
}
fscanf(f, "%s %s %i", str1, str2, &node->desc.nf_status);
fscanf(f, "%s %s %i %i %i", str1, str2, &tmp, &node->desc.uind.size,
&node->desc.uind.added);
node->desc.uind.type = (char)tmp;
if (node->desc.uind.size){
node->desc.uind.list = (int *) malloc(node->desc.uind.size*ISIZE);
for (i = 0; i < node->desc.uind.size; i++)
fscanf(f, "%i", node->desc.uind.list+i);
}
fscanf(f, "%s %s %i %i %i", str1, str2, &tmp,
&node->desc.not_fixed.size, &node->desc.not_fixed.added);
node->desc.not_fixed.type = (char)tmp;
if (node->desc.not_fixed.size){
node->desc.not_fixed.list =
(int *) malloc(node->desc.not_fixed.size*ISIZE);
for (i = 0; i < node->desc.not_fixed.size; i++)
fscanf(f, "%i", node->desc.not_fixed.list+i);
}
fscanf(f, "%s %s %i %i %i", str1, str2, &tmp,
&node->desc.cutind.size, &node->desc.cutind.added);
node->desc.cutind.type = (char)tmp;
if (node->desc.cutind.size){
node->desc.cutind.list = (int *) malloc(node->desc.cutind.size*ISIZE);
for (i = 0; i < node->desc.cutind.size; i++)
fscanf(f, "%i", node->desc.cutind.list+i);
}
fscanf(f, "%s %i", str1, &tmp);
node->desc.basis.basis_exists = (char)tmp;
fscanf(f, "%s %s %i %i", str1, str2, &tmp,
&node->desc.basis.basevars.size);
node->desc.basis.basevars.type = (char)tmp;
if (node->desc.basis.basevars.size){
node->desc.basis.basevars.stat =
(int *) malloc(node->desc.basis.basevars.size*ISIZE);
if (node->desc.basis.basevars.type == WRT_PARENT){
node->desc.basis.basevars.list =
(int *) malloc(node->desc.basis.basevars.size*ISIZE);
for (i = 0; i < node->desc.basis.basevars.size; i++)
fscanf(f, "%i %i", node->desc.basis.basevars.list+i,
node->desc.basis.basevars.stat+i);
}else{
for (i = 0; i < node->desc.basis.basevars.size; i++)
fscanf(f, "%i", node->desc.basis.basevars.stat+i);
}
}
fscanf(f, "%s %s %i %i", str1, str2, &tmp,
&node->desc.basis.extravars.size);
node->desc.basis.extravars.type = (char)tmp;
if (node->desc.basis.extravars.size){
node->desc.basis.extravars.stat =
(int *) malloc(node->desc.basis.extravars.size*ISIZE);
if (node->desc.basis.extravars.type == WRT_PARENT){
node->desc.basis.extravars.list =
(int *) malloc(node->desc.basis.extravars.size*ISIZE);
for (i = 0; i < node->desc.basis.extravars.size; i++)
fscanf(f, "%i %i", node->desc.basis.extravars.list+i,
node->desc.basis.extravars.stat+i);
}else{
for (i = 0; i < node->desc.basis.extravars.size; i++)
fscanf(f, "%i", node->desc.basis.extravars.stat+i);
}
}
fscanf(f, "%s %s %i %i", str1, str2, &tmp,
&node->desc.basis.baserows.size);
node->desc.basis.baserows.type = (char)tmp;
if (node->desc.basis.baserows.size){
node->desc.basis.baserows.stat =
(int *) malloc(node->desc.basis.baserows.size*ISIZE);
if (node->desc.basis.baserows.type == WRT_PARENT){
node->desc.basis.baserows.list =
(int *) malloc(node->desc.basis.baserows.size*ISIZE);
for (i = 0; i < node->desc.basis.baserows.size; i++)
fscanf(f, "%i %i", node->desc.basis.baserows.list+i,
node->desc.basis.baserows.stat+i);
}else{
for (i = 0; i < node->desc.basis.baserows.size; i++)
fscanf(f, "%i", node->desc.basis.baserows.stat+i);
}
}
fscanf(f, "%s %s %i %i", str1, str2, &tmp,
&node->desc.basis.extrarows.size);
node->desc.basis.extrarows.type = (char)tmp;
if (node->desc.basis.extrarows.size){
node->desc.basis.extrarows.stat =
(int *) malloc(node->desc.basis.extrarows.size*ISIZE);
if (node->desc.basis.extrarows.type == WRT_PARENT){
node->desc.basis.extrarows.list =
(int *) malloc(node->desc.basis.extrarows.size*ISIZE);
for (i = 0; i < node->desc.basis.extrarows.size; i++)
fscanf(f, "%i %i", node->desc.basis.extrarows.list+i,
node->desc.basis.extrarows.stat+i);
}else{
for (i = 0; i < node->desc.basis.extrarows.size; i++)
fscanf(f, "%i", node->desc.basis.extrarows.stat+i);
}
}
}
switch (node->node_status){
case NODE_STATUS__HELD:
REALLOC(tm->nextphase_cand, bc_node *,
tm->nextphase_cand_size, tm->nextphase_candnum+1, BB_BUNCH);
tm->nextphase_cand[tm->nextphase_candnum++] = node;
/* update the nodes_per_... stuff */
/* the active_nodes_per_... will be updated when the LP__IS_FREE
message comes */
if (node->cp)
#ifdef COMPILE_IN_CP
tm->nodes_per_cp[node->cp]++;
#else
tm->nodes_per_cp[find_process_index(&tm->cp, node->cp)]++;
#endif
break;
case NODE_STATUS__ROOT:
tm->rootnode = node;
break;
case NODE_STATUS__WARM_STARTED:
case NODE_STATUS__CANDIDATE:
#pragma omp critical (tree_update)
insert_new_node(tm, node);
break;
}
return(parent);
}
/*===========================================================================*/
int write_subtree(bc_node *root, char *file, FILE *f, char append, int logging)
{
int i;
char close = FALSE;
if (!f){
if (!(f = fopen(file, append ? "a" : "w"))){
printf("\nError opening subtree file\n\n");
return(0);
}
close = TRUE;
}
if (logging == VBC_TOOL){
if (root->parent)
fprintf(f, "%i %i\n", root->parent->bc_index + 1, root->bc_index + 1);
}else{
write_node(root, file, f, append);
}
for (i = 0; i < root->bobj.child_num; i++)
write_subtree(root->children[i], file, f, TRUE, logging);
if (close)
fclose(f);
return(1);
}
/*===========================================================================*/
int read_subtree(tm_prob *tm, bc_node *root, FILE *f)
{
int parent, i;
int *children;
parent = read_node(tm, root, f, &children);
if (f && root->bobj.child_num){
root->children = (bc_node **)
malloc(root->bobj.child_num*sizeof(bc_node *));
for (i = 0; i < root->bobj.child_num; i++){
root->children[i] = (bc_node *) calloc(1, sizeof(bc_node));
root->children[i]->parent = root;
}
}
for (i = 0; i < root->bobj.child_num; i++){
read_subtree(tm, root->children[i], f);
}
return(parent);
}
/*===========================================================================*/
int write_tm_cut_list(tm_prob *tm, char *file, char append)
{
FILE *f;
int i, j;
if (!(f = fopen(file, append ? "a" : "w"))){
printf("\nError opening cut file\n\n");
return(0);
}
fprintf(f, "CUTNUM: %i %i\n", tm->cut_num, tm->allocated_cut_num);
for (i = 0; i < tm->cut_num; i++){
fprintf(f, "%i %i %i %c %i %f %f\n", tm->cuts[i]->name,
tm->cuts[i]->size, (int)tm->cuts[i]->type, tm->cuts[i]->sense,
(int)tm->cuts[i]->branch, tm->cuts[i]->rhs, tm->cuts[i]->range);
for (j = 0; j < tm->cuts[i]->size; j++)
fprintf(f, "%i ", (int)tm->cuts[i]->coef[j]);
fprintf(f, "\n");
}
fclose(f);
return(1);
}
/*===========================================================================*/
int read_tm_cut_list(tm_prob *tm, char *file)
{
FILE *f;
int i, j, tmp1 = 0, tmp2 = 0;
char str[20];
if (!(f = fopen(file, "r"))){
printf("\nError opening cut file\n\n");
return(0);
}
fscanf(f, "%s %i %i", str, &tm->cut_num, &tm->allocated_cut_num);
tm->cuts = (cut_data **) malloc(tm->allocated_cut_num*sizeof(cut_data *));
for (i = 0; i < tm->cut_num; i++){
tm->cuts[i] = (cut_data *) malloc(sizeof(cut_data));
fscanf(f, "%i %i %i %c %i %lf %lf", &tm->cuts[i]->name,
&tm->cuts[i]->size, &tmp1, &tm->cuts[i]->sense,
&tmp2, &tm->cuts[i]->rhs, &tm->cuts[i]->range);
tm->cuts[i]->type = (char)tmp1;
tm->cuts[i]->branch = (char)tmp2;
tm->cuts[i]->coef = (char *) malloc(tm->cuts[i]->size*sizeof(char));
for (j = 0; j < tm->cuts[i]->size; j++){
fscanf(f, "%i ", &tmp1);
tm->cuts[i]->coef[j] = (char)tmp1;
}
}
fclose(f);
return(1);
}
/*===========================================================================*/
int write_tm_info(tm_prob *tm, char *file, FILE* f, char append)
{
char close = FALSE;
if (!f){
if (!(f = fopen(file, append ? "a" : "w"))){
printf("\nError opening TM info file\n\n");
return(0);
}
close = TRUE;
}
if (tm->par.logging == VBC_TOOL){
fprintf(f, "#TYPE: COMPLETE TREE\n");
fprintf(f, "#TIME: NOT\n");
fprintf(f, "#BOUNDS: NONE\n");
fprintf(f, "#INFORMATION: EXCEPTION\n");
fprintf(f, "#NODE_NUMBER: NONE\n");
if (close)
fclose(f);
return(1);
}
fprintf(f, "UPPER BOUND: ");
if (tm->has_ub)
fprintf(f, " %f\n", tm->ub);
else
fprintf(f, "\n");
fprintf(f, "LOWER BOUND: %f\n", tm->lb);
fprintf(f, "PHASE: %i\n", tm->phase);
fprintf(f, "ROOT LB: %f\n", tm->stat.root_lb);
fprintf(f, "MAX DEPTH: %i\n", tm->stat.max_depth);
fprintf(f, "CHAINS: %i\n", tm->stat.chains);
fprintf(f, "DIVING HALTS: %i\n", tm->stat.diving_halts);
fprintf(f, "TREE SIZE: %i\n", tm->stat.tree_size);
fprintf(f, "NODES CREATED: %i\n", tm->stat.created);
fprintf(f, "NODES ANALYZED: %i\n", tm->stat.analyzed);
fprintf(f, "LEAVES BEFORE: %i\n", tm->stat.leaves_before_trimming);
fprintf(f, "LEAVES AFTER: %i\n", tm->stat.leaves_after_trimming);
fprintf(f, "NF STATUS: %i\n", (int)tm->stat.nf_status);
fprintf(f, "TIMING:\n");
fprintf(f, " COMM: %f\n", tm->comp_times.communication);
fprintf(f, " LP: %f\n", tm->comp_times.lp);
fprintf(f, " SEPARATION: %f\n", tm->comp_times.separation);
fprintf(f, " FIXING: %f\n", tm->comp_times.fixing);
fprintf(f, " PRICING: %f\n", tm->comp_times.pricing);
fprintf(f, " BRANCHING: %f\n", tm->comp_times.strong_branching);
fprintf(f, " CUT POOL: %f\n", tm->comp_times.cut_pool);
fprintf(f, " REAL TIME: %f\n", wall_clock(NULL) - tm->start_time);
if (close)
fclose(f);
return(1);
}
/*===========================================================================*/
int read_tm_info(tm_prob *tm, FILE *f)
{
char str1[20], str2[20];
int tmp = 0;
double previous_elapsed_time = 0;
if (!f)
return(0);
fscanf(f, "%s %s", str1, str2);
if (fscanf(f, "%lf", &tm->ub) != 0)
tm->has_ub = TRUE;
fscanf(f, "%s %s %lf", str1, str2, &tm->lb);
fscanf(f, "%s %i", str1, &tm->phase);
fscanf(f, "%s %s %lf", str1, str2, &tm->stat.root_lb);
fscanf(f, "%s %s %i", str1, str2, &tm->stat.max_depth);
fscanf(f, "%s %i", str1, &tm->stat.chains);
fscanf(f, "%s %s %i", str1, str2, &tm->stat.diving_halts);
fscanf(f, "%s %s %i", str1, str2, &tm->stat.tree_size);
fscanf(f, "%s %s %i", str1, str2, &tm->stat.created);
fscanf(f, "%s %s %i", str1, str2, &tm->stat.analyzed);
fscanf(f, "%s %s %i", str1, str2, &tm->stat.leaves_before_trimming);
fscanf(f, "%s %s %i", str1, str2, &tm->stat.leaves_after_trimming);
fscanf(f, "%s %s %i", str1, str2, &tmp);
tm->stat.nf_status = (char)tmp;
fscanf(f, "%s", str1);
fscanf(f, "%s %lf", str1, &tm->comp_times.communication);
fscanf(f, "%s %lf", str1, &tm->comp_times.lp);
fscanf(f, "%s %lf", str1, &tm->comp_times.separation);
fscanf(f, "%s %lf", str1, &tm->comp_times.fixing);
fscanf(f, "%s %lf", str1, &tm->comp_times.pricing);
fscanf(f, "%s %lf", str1, &tm->comp_times.strong_branching);
fscanf(f, "%s %s %lf", str1, str2, &tm->comp_times.cut_pool);
fscanf(f, "%s %s %lf\n", str1, str2, &previous_elapsed_time);
tm->start_time -= previous_elapsed_time;
return(1);
}
/*===========================================================================*/
int write_base(base_desc *base, char *file, FILE *f, char append)
{
int i;
char close = FALSE;
if (!f){
if (!(f = fopen(file, append ? "a" : "w"))){
printf("\nError opening base file\n\n");
return(0);
}
close = TRUE;
}
fprintf(f, "BASE DESCRIPTION: %i %i\n", base->varnum, base->cutnum);
for (i = 0; i < base->varnum; i++)
fprintf(f, "%i\n", base->userind[i]);
if (close)
fclose(f);
return(1);
}
/*===========================================================================*/
int read_base(base_desc *base, FILE *f)
{
char str1[20], str2[20];
int i;
fscanf(f, "%s %s %i %i", str1, str2, &base->varnum, &base->cutnum);
base->userind = (int *) malloc(base->varnum*ISIZE);
for (i = 0; i < base->varnum; i++)
fscanf(f, "%i", base->userind+i);
return(1);
}
/*===========================================================================*/
/*===========================================================================*\
* Cleanup. Free the datastructure.
\*===========================================================================*/
void free_tm(tm_prob *tm)
{
int i;
cut_data **cuts = tm->cuts;
#ifdef _OPENMP
int num_threads = tm->par.max_active_nodes;
#else
int num_threads = 1;
#endif
#if defined(COMPILE_IN_TM) && defined(COMPILE_IN_LP)
for (i = 0; i < num_threads; i++)
free_lp(tm->lpp[i]);
FREE(tm->lpp);
#ifdef COMPILE_IN_CG
FREE(tm->cgp);
#endif
#endif
if (tm->par.lp_machs){
FREE(tm->par.lp_machs[0]);
FREE(tm->par.lp_machs);
}
if (tm->par.cg_machs){
FREE(tm->par.cg_machs[0]);
FREE(tm->par.cg_machs);
}
if (tm->par.cp_machs){
FREE(tm->par.cp_machs[0]);
FREE(tm->par.cp_machs);
}
FREE(tm->lp.procs);
FREE(tm->lp.free_ind);
FREE(tm->cg.procs);
FREE(tm->cg.free_ind);
FREE(tm->cp.procs);
FREE(tm->cp.free_ind);
FREE(tm->nodes_per_cp);
FREE(tm->active_nodes_per_cp);
FREE(tm->active_nodes);
FREE(tm->samephase_cand);
FREE(tm->nextphase_cand);
#ifndef COMPILE_IN_TM
/* Go over the tree and free the nodes */
free_subtree(tm->rootnode);
#endif
/* Go over the cuts stored and free them all */
#pragma omp critical (cut_pool)
if (cuts){
for (i = tm->cut_num - 1; i >= 0; i--)
if (cuts[i]){
FREE(cuts[i]->coef);
FREE(cuts[i]);
}
FREE(tm->cuts);
}
#pragma omp critical (tmp_memory)
{
FREE(tm->tmp.i);
FREE(tm->tmp.c);
FREE(tm->tmp.d);
}
/*get rid of the added pointers for sens.analysis*/
for (i = 0; i < num_threads; i++){
if(tm->rpath[i])
if(tm->rpath[i][0])
tm->rpath[i][0] = NULL;
FREE(tm->bpath[i]);
FREE(tm->rpath[i]);
}
FREE(tm->rpath);
FREE(tm->rpath_size);
FREE(tm->bpath);
FREE(tm->bpath_size);
if (tm->reduced_costs) {
for (i=0; i<tm->reduced_costs->num_rcs; i++) {
FREE(tm->reduced_costs->indices[i]);
FREE(tm->reduced_costs->values[i]);
FREE(tm->reduced_costs->lb[i]);
FREE(tm->reduced_costs->ub[i]);
}
FREE(tm->reduced_costs->indices);
FREE(tm->reduced_costs->values);
FREE(tm->reduced_costs->lb);
FREE(tm->reduced_costs->ub);
FREE(tm->reduced_costs->cnt);
FREE(tm->reduced_costs->obj);
FREE(tm->reduced_costs);
}
if (tm->pcost_down) {
FREE(tm->pcost_down);
FREE(tm->pcost_up);
FREE(tm->br_rel_down);
FREE(tm->br_rel_up);
FREE(tm->br_rel_cand_list);
FREE(tm->br_rel_down_min_level);
FREE(tm->br_rel_up_min_level);
}
FREE(tm);
}
/*===========================================================================*/
void free_subtree(bc_node *n)
{
int i;
if (n == NULL) return;
for (i = n->bobj.child_num - 1; i >= 0; i--)
free_subtree(n->children[i]);
free_tree_node(n);
}
/*===========================================================================*/
void free_tree_node(bc_node *n)
{
FREE(n->sol);
FREE(n->sol_ind);
#ifdef SENSITIVITY_ANALYSIS
FREE(n->duals);
#endif
FREE(n->children);
#ifndef MAX_CHILDREN_NUM
FREE(n->bobj.sense);
FREE(n->bobj.rhs);
FREE(n->bobj.range);
FREE(n->bobj.branch);
#endif
FREE(n->bobj.solutions); //added by asm4
FREE(n->desc.uind.list);
free_basis(&n->desc.basis);
FREE(n->desc.not_fixed.list);
FREE(n->desc.cutind.list);
FREE(n->desc.desc);
if (n->desc.bnd_change) {
FREE(n->desc.bnd_change->index);
FREE(n->desc.bnd_change->lbub);
FREE(n->desc.bnd_change->value);
FREE(n->desc.bnd_change);
}
FREE(n);
}
/*===========================================================================*/
void free_basis(basis_desc *basis)
{
FREE(basis->basevars.list);
FREE(basis->basevars.stat);
FREE(basis->extravars.list);
FREE(basis->extravars.stat);
FREE(basis->baserows.list);
FREE(basis->baserows.stat);
FREE(basis->extrarows.list);
FREE(basis->extrarows.stat);
}
/*===========================================================================*/
/*===========================================================================*\
* This function shuts down the treemanager
\*===========================================================================*/
int tm_close(tm_prob *tm, int termcode)
{
#ifndef COMPILE_IN_TM
int s_bufid;
#endif
#ifdef COMPILE_IN_LP
lp_prob **lp = tm->lpp;
#endif
#ifndef COMPILE_IN_CP
int r_bufid = 0, new_cuts;
struct timeval timeout = {5, 0};
double new_time;
#endif
int i;
#if defined(DO_TESTS) && 0
if (tm->cp.free_num != tm->cp.procnum)
printf(" Something is fishy! tm->cp.freenum != tm->cp.procnum\n");
#endif
if (tm->par.vbc_emulation == VBC_EMULATION_LIVE){
printf("$#END_OF_OUTPUT");
}
/*------------------------------------------------------------------------*\
* Kill the processes. Some of them will send back statistics.
\*------------------------------------------------------------------------*/
#ifndef COMPILE_IN_LP
stop_processes(&tm->lp);
#endif
#ifndef COMPILE_IN_CG
stop_processes(&tm->cg);
#endif
#ifndef COMPILE_IN_CP
stop_processes(&tm->cp);
#endif
/*------------------------------------------------------------------------*\
* Receive statistics from the cutpools
\*------------------------------------------------------------------------*/
#ifdef COMPILE_IN_CP
if (tm->cpp){
for (i = 0; i < tm->par.max_cp_num; i++){
tm->comp_times.cut_pool += tm->cpp[i]->cut_pool_time;
tm->stat.cuts_in_pool += tm->cpp[i]->cut_num;
tm->cpp[i]->msgtag = YOU_CAN_DIE;
cp_close(tm->cpp[i]);
}
FREE(tm->cpp);
}
#else
for (i = 0; i < tm->par.max_cp_num;){
r_bufid = treceive_msg(tm->cp.procs[i], POOL_TIME, &timeout);
if (r_bufid > 0){
receive_dbl_array(&new_time, 1);
receive_int_array(&new_cuts, 1);
tm->comp_times.cut_pool += new_time;
tm->stat.cuts_in_pool += new_cuts;
i++;
}else{
if (pstat(tm->cp.procs[i]) != PROCESS_OK)
i++;
}
}
freebuf(r_bufid);
#endif
/* Receive timing from the LPs */
if (receive_lp_timing(tm) < 0){
printf("\nWarning: problem receiving LP timing. LP process is dead\n\n");
}
#ifdef COMPILE_IN_LP
for (i = 0; i < tm->par.max_active_nodes; i ++){
lp_close(lp[i]);
}
#endif
tm->stat.root_lb = tm->rootnode->lower_bound;
find_tree_lb(tm);
return(termcode);
#ifndef COMPILE_IN_TM
/*------------------------------------------------------------------------*\
* Send back the statistics to the master
\*------------------------------------------------------------------------*/
s_bufid = init_send(DataInPlace);
send_char_array((char *)&tm->comp_times, sizeof(node_times));
send_char_array((char *)&tm->lp_stat, sizeof(lp_stat_desc));
send_dbl_array(&tm->lb, 1);
send_char_array((char *)&tm->stat, sizeof(tm_stat));
send_msg(tm->master, termcode);
freebuf(s_bufid);
free_tm(tm);
#endif
return(termcode);
}
/*===========================================================================*/
/*===========================================================================*/
#if !defined(_MSC_VER) && !defined(__MNO_CYGWIN) && defined(SIGHANDLER)
void sym_catch_c(int num)
{
sigset_t mask_set;
sigset_t old_set;
/* SIGTSTP ? */
signal(SIGINT, sym_catch_c);
char temp [MAX_LINE_LENGTH + 1];
sigfillset(&mask_set);
sigprocmask(SIG_SETMASK, &mask_set, &old_set);
strcpy(temp, "");
printf("\nDo you want to abort immediately, exit gracefully (from the current solve call only), or continue? [a/e/c]: ");
fflush(stdout);
fgets(temp, MAX_LINE_LENGTH, stdin);
if(temp[1] == '\n' && (temp[0] == 'a' || temp[0] == 'A')){
printf("\nTerminating...\n");
fflush(stdout);
exit(0);
}else if(temp[1] == '\n' && (temp[0] == 'e' || temp[0] == 'E')){
c_count++;
} else{
printf("\nContinuing...\n");
fflush(stdout);
c_count = 0;
}
}
#endif
/*===========================================================================*/
/*
* Find the lowerbound of the current branch-and-cut tree and save it in
* tm->lb
*/
int find_tree_lb(tm_prob *tm)
{
double lb = MAXDOUBLE;
bc_node **samephase_cand;
if (tm->samephase_candnum > 0 || tm->active_node_num > 0) {
if (tm->par.node_selection_rule == LOWEST_LP_FIRST) {
lb = tm->samephase_cand[1]->lower_bound; /* [0] is a dummy */
} else {
samephase_cand = tm->samephase_cand;
for (int i = tm->samephase_candnum; i >= 1; i--){
if (samephase_cand[i]->lower_bound < lb) {
lb = samephase_cand[i]->lower_bound;
}
}
}
} else {
/* there are no more nodes left. */
lb = tm->ub;
}
/*
if (lb >= MAXDOUBLE / 2){
lb = tm->ub;
}
*/
tm->lb = lb;
return 0;
}
/*===========================================================================*/
| 30.908336
| 124
| 0.549655
|
shahnidhi
|
90f2dca9d6b11de4df1169bed10f4969e9e66b68
| 1,231
|
cpp
|
C++
|
avs_dx/DxVisuals/Effects/Common/EffectListBase.factory.cpp
|
Const-me/vis_avs_dx
|
da1fd9f4323d7891dea233147e6ae16790ad9ada
|
[
"MIT"
] | 33
|
2019-01-28T03:32:17.000Z
|
2022-02-12T18:17:26.000Z
|
avs_dx/DxVisuals/Effects/Common/EffectListBase.factory.cpp
|
visbot/vis_avs_dx
|
03e55f8932a97ad845ff223d3602ff2300c3d1d4
|
[
"MIT"
] | 2
|
2019-11-18T17:54:58.000Z
|
2020-07-21T18:11:21.000Z
|
avs_dx/DxVisuals/Effects/Common/EffectListBase.factory.cpp
|
Const-me/vis_avs_dx
|
da1fd9f4323d7891dea233147e6ae16790ad9ada
|
[
"MIT"
] | 5
|
2019-02-16T23:00:11.000Z
|
2022-03-27T15:22:10.000Z
|
#include "stdafx.h"
#include <RootEffect.h>
#include "../List/EffectList.h"
class C_RenderListClass;
// Class factory is slightly more complex here: creating different classes depending on whether this effect is the root or just a list inside the preset.
template<> HRESULT createDxEffect<C_RenderListClass>( void* pState, const C_RBASE* pRBase )
{
const EffectListBase::AvsState* pStateBase = ( EffectListBase::AvsState* )pState;
if( pStateBase->isroot )
return EffectImpl<RootEffect>::create( pState, pRBase );
return EffectImpl<EffectList>::create( pState, pRBase );
};
// Similarly, need to implement two copies of metadata() method.
const char* const EffectImpl<RootEffect>::s_effectName = "RootEffect";
static const EffectBase::Metadata s_root{ "RootEffect", true };
const EffectBase::Metadata& RootEffect::metadata()
{
return s_root;
}
const char* const EffectImpl<EffectList>::s_effectName = "EffectList";
static const EffectBase::Metadata s_list{ "EffectList", true };
const EffectBase::Metadata& EffectList::metadata()
{
return s_list;
}
void clearListRenderers( const C_RBASE* pThis )
{
auto pl = dynamic_cast<EffectListBase*>( getDxEffect( pThis ) );
if( nullptr == pl )
return;
pl->clearRenders();
}
| 31.564103
| 153
| 0.753859
|
Const-me
|
90f4f719a45d230d38cb5086c765c04a18c45838
| 12,944
|
cpp
|
C++
|
NPlan/NPlan/view/TaskView.cpp
|
Avens666/NPlan
|
726411b053ded26ce6c1b8c280c994d4c1bac71a
|
[
"Apache-2.0"
] | 16
|
2018-08-30T11:27:14.000Z
|
2021-12-17T02:05:45.000Z
|
NPlan/NPlan/view/TaskView.cpp
|
Avens666/NPlan
|
726411b053ded26ce6c1b8c280c994d4c1bac71a
|
[
"Apache-2.0"
] | null | null | null |
NPlan/NPlan/view/TaskView.cpp
|
Avens666/NPlan
|
726411b053ded26ce6c1b8c280c994d4c1bac71a
|
[
"Apache-2.0"
] | 14
|
2018-08-30T12:13:56.000Z
|
2021-02-06T11:07:44.000Z
|
// File: TaskView.cpp
// Copyright: Copyright(C) 2013-2017 Wuhan KOTEI Informatics Co., Ltd. All rights reserved.
// Website: http://www.nuiengine.com
// Description: This code is part of NPlan Project (Powered by NUI Engine)
// Comments:
// Rev: 1
// Created: 2018/8/27
// Last edit: 2015/9/16
// Author: Chen Zhi and his team
// E-mail: cz_666@qq.com
// License: APACHE V2.0 (see license file)
#include "TimeBarView.h"
#include "boost/lexical_cast.hpp"
#include "AnimationThread.h"
#include "KSurfaceManager.h"
#include "KFontManager.h"
#include "TaskView.h"
#include "KTextMultiLineDrawable.h"
#include "boost/lexical_cast.hpp"
#include "MilestoneEditView.h"
#include "NMenu.h"
#include "KScreen.h"
#include "../NPlan.h"
using namespace std;
using namespace boost;
const static kn_int click_area_value = 10;
#ifdef WIN32
//句柄
extern HWND g_hWnd;
#endif
CTaskView::CTaskView(void)
{
m_p_task = NULL;
m_b_click = true;
m_b_move = true;
SetShieldMsg(false);
}
CTaskView::~CTaskView()
{
}
void CTaskView::setTaskBar(CTaskBarView_WEAK_PTR p)
{
m_p_taskbar = p;
}
CTaskBarView_PTR CTaskView::getTaskBar()
{
return m_p_taskbar.lock();
}
void CTaskView::OnDown(kn_int iScreenX, kn_int iScreenY, KMessageMouse* pMsg)
{
if (!m_p_parent.expired())
{
m_down_point.set(iScreenX, iScreenY);
m_down_point_offset.set(iScreenX - m_rect.left(), iScreenY - m_rect.top());
m_b_mouse_picked = true;
m_b_click = true;
setViewFocus();
}
}
void CTaskView::OnMove(kn_int iScreenX, kn_int iScreenY, KMessageMouse* pMsg)
{
if(m_b_mouse_picked && m_b_move)
{
kn_int move_x_offset = iScreenX - m_down_point.x();
kn_int move_y_offset = iScreenY -m_down_point.y();
if ((abs(move_x_offset) > click_area_value) || (abs(move_y_offset) > click_area_value))
{
m_b_click = false;
m_p_parent.lock()->changeViewLayerTop(shared_from_this());
KMessageDrag* msg = new KMessageDrag;
msg->m_p_drag_view = shared_from_this();
msg->m_drag_type = TASK_VIEW_DRAG;
msg->m_pos_x = iScreenX - m_down_point_offset.x();
msg->m_pos_y = iScreenY - m_down_point_offset.y();
if (move_y_offset > 0)
{
msg->m_wParam = DRAG_DOWNWARD;
}
else
{
msg->m_wParam = DRAG_UPWARD;
}
msg->m_lParam = move_y_offset;
GetScreen()->sendNUIMessage( KMSG_DRAG, msg );
m_down_point.set(iScreenX, iScreenY);
}
}
}
void CTaskView::OnUp(kn_int iScreenX, kn_int iScreenY, KMessageMouse* pMsg)
{
if(m_b_mouse_picked)
{
if (m_b_click)
{
m_task_click_sign.emit(shared_from_this());
}
else
{
kn_int m_move_lengthY = iScreenY - m_down_point.y();
KMessageDrag* msg = new KMessageDrag;
msg->m_p_drag_view = shared_from_this();
msg->m_drag_type = TASK_VIEW_DRAG_UP;
msg->m_pos_x = iScreenX;
msg->m_pos_y = iScreenY;
msg->m_lParam = m_move_lengthY;
GetScreen()->sendNUIMessage( KMSG_DRAG_UP, msg );
}
}
}
CNProjectTask* CTaskView::GetTask()
{
return m_p_task;
}
void CTaskView::init(CNProjectTask* task)
{
m_p_task = task;
//////背景
kn_string bk_file = _T("./resource/0");
int color = m_p_task->getColorType() ;
if (color >= 1 && color <=9)
{
bk_file += boost::lexical_cast<kn_string>( color);
}
else
{//不合法自动分配
kn_int color_type = (task->getVectorId() + 1)%9 + 1;
bk_file += boost::lexical_cast<kn_string>(color_type);
m_p_task->setColorType(color_type);
}
bk_file += _T(".9.png");
K9PatchImageDrawable_PTR bk_drawable(new K9PatchImageDrawable( getSurfaceManager()->GetSurface( bk_file), TRUE ));
// ((K9PatchImageDrawable_PTR)bk_drawable)->SizeToImage();
bk_drawable->SetRect(RERect::MakeXYWH(0, 0, m_rect.width(), m_rect.height()) );
setIconDrawable(bk_drawable);
/////icon
//kn_string icon_file = _T("./resource/task_icon");
//icon_file += boost::lexical_cast<kn_string>( (task->getVectorId() + 1)%8 +1);
//icon_file += _T(".png");
//KImageDrawable_PTR icon_da (new KImageDrawable( getSurfaceManager()->GetSurface( icon_file), TRUE ) );
//icon_da->SizeToImage();
//icon_da->SetRect(RERect::MakeXYWH(6, 6, icon_da->GetRect().width(), icon_da->GetRect().height()) );
//setIconDrawable(icon_da);
m_text_name = KTextMultiLineDrawable_PTR(new KTextMultiLineDrawable(RE_ColorWHITE, 16, REPaint::kLeft_Align) );
// m_text_name->SetRect(RERect::MakeXYWH(10 +icon_da->GetRect().width() , 10, m_rect.width() - 14 - icon_da->GetRect().width(), m_rect.height() ) );
// m_text_name->setBold(TRUE);
m_text_name->SetRect(RERect::MakeXYWH(36 , 12, m_rect.width() - 55, m_rect.height() - 32 ) );
m_text_name->setFont(GetFontManagerSingleton()->GetFontFromName("Microsoft YaHei"));
m_text_name->setMaxLine(3);
setTextDrawable(m_text_name);
// SetTextColor(SkColorSetARGBMacro(255,0,0,0), SkColorSetARGBMacro(255, 255, 255, 255), SkColorSetARGBMacro(255,0,0, 0), SkColorSetARGBMacro(255,0,0,0));
m_text_id = KTextDrawable_PTR(new KTextDrawable(_T(""), RE_ColorWHITE, 16, REPaint::kCenter_Align) );
//m_text_id->setBold(TRUE);
m_text_id->setFont(GetFontManagerSingleton()->GetFontFromName("Microsoft YaHei"));
m_text_id->SetRect(RERect::MakeXYWH(5 , 14, 20, 20 ) );
addDrawable(m_text_id);
//REPoint p1, p2;
//p1.set( )
//KLineShape* shape = new KLineShape(m_rect.width(), )
refreshInfo();
}
void CTaskView::setMode(bool b)
{
//if (m_mode == b)
//{
// return;
//}
if (b == MODE_BIG)
{//大模式
m_text_name->SetFontSize(16);
m_text_name->setMaxLine(3);
}
else
{
m_text_name->SetFontSize(12);
m_text_name->setMaxLine(2);
}
if (m_text_name->isOverroad())
{
setTip(m_text_name->GetText(),NO_TIMER,4000);
}
else
{
enableTip(FALSE);
}
}
void CTaskView::refreshInfo()
{
if (m_p_task)
{
kn_string str = m_p_task->getName();
m_text_name->SetText(str.c_str() );
m_text_name->autoMLine();
if (m_text_name->isOverroad())
{
setTip(m_text_name->GetText(),NO_TIMER,4000);
}
else
{
enableTip(FALSE);
}
if (m_p_task->getVectorId() < 9)
{
str = _T("0");
str += boost::lexical_cast<kn_string>(m_p_task->getVectorId() + 1);
}
else
{
str = boost::lexical_cast<kn_string>(m_p_task->getVectorId() + 1);
}
m_text_id->SetText(str.c_str() );
}
}
void CTaskView::OnRUp(kn_int iScreenX, kn_int iScreenY, KMessageMouse* pMsg)
{
//if ( m_p_task)
//{
// CMenuColor_PTR menu = CMenuColor_PTR(new CMenuColor );
// menu->Create(0,0, 38*3+12, 38*4+12);
// menu->init(this );
// menu->m_sign_menu_click.connect(this, &CTaskView::onMenu);
// //showmenu 传入view自身的相对坐标,这里取鼠标点击位置
// showMenu(menu, iScreenX - m_rect.x(), iScreenY - m_rect.y());
// InvalidateView();
//}
}
void CTaskView::onMenu(kn_int n)
{
//if (n>=1 && n <=9)
//{//换颜色
// kn_string bk_file = _T("./resource/0");
// bk_file += boost::lexical_cast<kn_string>( n );
// bk_file += _T(".9.png");
// K9PatchImageDrawable_PTR bk_drawable(new K9PatchImageDrawable( getSurfaceManager()->GetSurface( bk_file), TRUE ));
// // ((K9PatchImageDrawable_PTR)bk_drawable)->SizeToImage();
// bk_drawable->SetRect(RERect::MakeXYWH(0, 0, m_rect.width(), m_rect.height()) );
// setIconDrawable(bk_drawable);
//}
}
kn_int CTaskView::getTaskID()
{
return m_p_task->getVectorId();
}
void CTaskView::setNameText( const kn_string& name_text )
{
m_text_name->SetText(name_text);
}
REColor CTaskView::getBkColor()
{
kn_int color_type = m_p_task->getColorType();
switch (color_type)
{
case 1:
m_bk_color = ColorSetARGB(255, 63, 177, 225);
break;
case 2:
m_bk_color = ColorSetARGB(255, 104, 167, 155);
break;
case 3:
m_bk_color = ColorSetARGB(255, 201, 107, 107);
break;
case 4:
m_bk_color = ColorSetARGB(255, 203, 144, 68);
break;
case 5:
m_bk_color = ColorSetARGB(255, 95, 121, 184);
break;
case 6:
m_bk_color = ColorSetARGB(255, 63, 141, 163);
break;
case 7:
m_bk_color = ColorSetARGB(255, 177, 116, 85);
break;
case 8:
m_bk_color = ColorSetARGB(255, 115, 163, 107);
break;
case 9:
m_bk_color = ColorSetARGB(255, 174, 128, 187);
break;
default:
m_bk_color = ColorSetARGB(0, 0, 0, 0);
break;
}
return m_bk_color;
}
void CTaskView::setBMove( kn_bool bMove )
{
m_b_move = bMove;
}
kn_string CTaskView::getNameText()
{
return m_text_name->GetText();
}
///////////////////// CEventView ////////////////////////////
CEventView::CEventView(void)
{
m_p_data = NULL;
m_b_move = FALSE;
m_w = 25;
checkAlpha(TRUE);
}
CEventView::~CEventView()
{
}
CNProjectMileStone* CEventView::getMileStone()
{
return m_p_data;
}
void CEventView::init(CNProjectMileStone* data, CTimeBarView_PTR timebar)
{
//////背景
//K9PatchImageDrawable_PTR bk_drawable(new K9PatchImageDrawable( getSurfaceManager()->GetSurface( _T("./resource/task_btn_bk.9.png")), TRUE ));
//((K9PatchImageDrawable_PTR)bk_drawable)->SizeToImage();
//bk_drawable->SetRect(RERect::MakeXYWH(0, 0, m_rect.width(), m_rect.height()) );
//setBKDrawable(bk_drawable);
/////icon
//kn_string icon_file = _T("./resource/task_icon");
//icon_file += boost::lexical_cast<kn_string>( (task->getVectorId() + 1)%8 +1);
//icon_file += _T(".png");
K9PatchImageDrawable_PTR icon_da (new K9PatchImageDrawable( getSurfaceManager()->GetSurface( _T("./resource/event.9.png")), TRUE ) );
icon_da->SizeToImage();
RERect rect = icon_da->GetRect();
m_w = rect.width();
icon_da->SetRect(RERect::MakeXYWH(0, 0, rect.width(), m_rect.height()) );
setBKDrawable(icon_da);
checkAlpha(TRUE);
setCheckAlphaDrawable(icon_da);
m_info = KTextMultiLineDrawable_PTR(new KTextMultiLineDrawable( RE_ColorBLACK, 12, REPaint::kLeft_Align) );
// int line = m_info->getLine();
m_info->SetRect(RERect::MakeXYWH(rect.width()/2+3 + m_w/2, 15, 100, 14*2 ) );
m_info->setTextFrame(TRUE);
setTextDrawable(m_info);
m_time = KTextDrawable_PTR(new KTextDrawable(_T(""), RE_ColorBLACK, 12, REPaint::kLeft_Align) );
m_time->SetRect(RERect::MakeXYWH(rect.width()/2+3 + m_w/2, 1, 100, 14 ) );
m_time->setTextFrame(TRUE);
addDrawable(m_time);
m_event_id = KTextDrawable_PTR(new KTextDrawable(_T(""), ARGB(255,255,255,255), 12, REPaint::kLeft_Align) );
m_event_id->SetRect(RERect::MakeXYWH(10, 10, 16, 12 ) );
m_event_id->setBold(TRUE);
m_event_id->setFont(GetFontManagerSingleton()->GetFontFromName("Microsoft YaHei"));
// m_event_id->setTextFrame(TRUE);
addDrawable(m_event_id);
m_p_data = data;
m_timebar = timebar;
refreshInfo();
// enableMessage(TRUE);
}
void CEventView::refreshInfo()
{
if (m_p_data)
{
writeLock lock(m_lst_drawable_mutex);
kn_string str = m_p_data->getName();
m_info->SetText(str);
// m_info->autoMLine();
str = getTimeString(m_p_data->getTime(), FALSE);
m_time->SetText(str);
str = boost::lexical_cast<kn_string>(m_p_data->getId());
m_event_id->SetText(str);
}
}
void CEventView::syncTimeline(CTimeBarView_PTR tl)
{
if (m_p_data)
{
float x1;
x1 = tl->getTimePosition( m_p_data->getTime() );
RERect rect = tl->GetRect();
RERect rect2 = RERect::MakeXYWH(rect.left()+x1 - m_w/2, m_rect.top(), m_rect.width(), m_rect.height());
SetRect( rect2 );
}
}
void CEventView::OnMove(kn_int x, kn_int y, KMessageMouse* pMsg)
{
kn_bool b_update = FALSE;
if(m_b_mouse_picked)
{
if(m_b_move )
{
m_p_data->setTime( m_timebar->getPositisonTimeInt( x - m_timebar->GetRect().left() + m_mouse_x_offset, 10 ) );
b_update = TRUE;
}
}
if (b_update)
{
refreshInfo();
syncTimeline(m_timebar);
InvalidateView();
pMsg->setIdle(KMSG_RETURN_DILE);
}
}
void CEventView::OnDown(kn_int iScreenX, kn_int iScreenY, KMessageMouse* pMsg)
{
if ( iScreenX - m_rect.left() <m_w && iScreenY - m_rect.top() < m_w)
{//拖移
m_b_move = TRUE;
//m_mouse_x_offset 在于使bar和鼠标相对位置不动
m_mouse_x_offset = m_rect.left() + m_w/2 - iScreenX;
pMsg->setIdle(KMSG_RETURN_DILE);
}
}
void CEventView::OnUp(kn_int iScreenX, kn_int iScreenY, KMessageMouse* pMsg)
{
m_b_move = FALSE;
}
void CEventView::OnDClick(kn_int iScreenX, kn_int iScreenY, KMessageMouse* pMsg)
{
//tagRECT rect;
//GetWindowRect(g_hWnd,&rect);
//RERect rect;
int w = GetScreen()->GetWidth();
int h = GetScreen()->GetHeight();
MilestoneEditView_PTR pView = MilestoneEditView_PTR( new MilestoneEditView);
pView->Create(RERect::MakeXYWH((w-400)/2, (h-250)/2 , 400, 250));
pView->init(m_p_data );
GetParent()->AddView( pView );
InvalidateView();
kn_int i_result = pView->doModal();
if (i_result == KN_REUSLT_OK)
{
refreshInfo();
}
else if (i_result == KN_REUSLT_USER_DEL)
{
m_sign_btn_del.emit( shared_from_this() );
}
}
| 25.991968
| 155
| 0.663473
|
Avens666
|
90f6e6e7114705c60666c2713ba0172f4cf0b149
| 986
|
cpp
|
C++
|
BallCollision/Plane.cpp
|
Baeonex/BehavioursCollisions
|
c78cd1d5911b0caf632a11120686a09666526021
|
[
"MIT"
] | null | null | null |
BallCollision/Plane.cpp
|
Baeonex/BehavioursCollisions
|
c78cd1d5911b0caf632a11120686a09666526021
|
[
"MIT"
] | null | null | null |
BallCollision/Plane.cpp
|
Baeonex/BehavioursCollisions
|
c78cd1d5911b0caf632a11120686a09666526021
|
[
"MIT"
] | null | null | null |
#include "Plane.h"
Plane::Plane()
{
}
Plane::~Plane()
{
}
Plane::Plane(Vector2& p1, Vector2& p2)
{
auto v = p2 - p1;
v.normalise();
m_normal.x = -v.y;
m_normal.y = v.x;
m_d = -p1.dot(m_normal);
}
float Plane::distanceTo(const Vector2& p)
{
return p.dot(m_normal) + m_d;
}
Vector2 Plane::closestPoint(Vector2& p)
{
return p - m_normal * distanceTo(p);
}
ePlaneResult Plane::testSide(const Vector2& p)
{
float t = p.dot(m_normal) + m_d;
if (t < 0)
return ePlaneResult::BACK;
else if (t > 0)
return ePlaneResult::FRONT;
return ePlaneResult::INTERSECTS;
}
void Plane::collRes(Circle& circle)
{
Vector2 reflected;
reflected = 2 * m_normal * (m_normal.dot(circle.m_velocity));
circle.m_velocity -= reflected;
}
ePlaneResult Plane::testSide(const Circle& circle)
{
float t = distanceTo(circle.m_center);
if (t > circle.m_radius)
return ePlaneResult::FRONT;
else if (t < -circle.m_radius)
return ePlaneResult::BACK;
else
return ePlaneResult::INTERSECTS;
}
| 16.711864
| 62
| 0.684584
|
Baeonex
|
90f70620efe79b78697816e51e45dbbabb10b94f
| 15,520
|
cpp
|
C++
|
mod/bear/bear.cpp
|
littlegao233/bdlauncher
|
d765f1cd2bffed37e7f773f8120599f6e7cec732
|
[
"MIT"
] | 1
|
2020-01-12T11:40:30.000Z
|
2020-01-12T11:40:30.000Z
|
mod/bear/bear.cpp
|
mclauncherlinux/bdlauncher
|
9d7482786ba8be1e06fc7c81b448c5862e970870
|
[
"MIT"
] | null | null | null |
mod/bear/bear.cpp
|
mclauncherlinux/bdlauncher
|
9d7482786ba8be1e06fc7c81b448c5862e970870
|
[
"MIT"
] | null | null | null |
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include"aux.h"
#include<cstdio>
#include<list>
#include<forward_list>
#include<string>
#include<unordered_map>
#include<unordered_set>
#include"../cmdhelper.h"
#include<vector>
#include<Loader.h>
#include<MC.h>
#include"seral.hpp"
#include<unistd.h>
#include<cstdarg>
#include"base.h"
#include"../gui/gui.h"
#include<cmath>
#include<deque>
#include<dlfcn.h>
#include<string>
#include<aio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
using std::string;
using std::unordered_map;
using std::unordered_set;
#define min(a,b) ((a)<(b)?(a):(b))
#define max(a,b) ((a)>(b)?(a):(b))
#define dbg_printf(...) {}
//#define dbg_printf printf
extern "C" {
BDL_EXPORT void bear_init(std::list<string>& modlist);
}
extern void load_helper(std::list<string>& modlist);
static unordered_map<string,int> banlist;
static unordered_map<string,string> xuid_name;
static void save() {
char* bf;
int sz=maptomem(banlist,&bf,h_str2str,h_int2str);
mem2file("ban.db",bf,sz);
}
static void load() {
char* buf;
int sz;
struct stat tmp;
if(stat("ban.db",&tmp)==-1) {
save();
}
file2mem("ban.db",&buf,sz);
memtomap(banlist,buf,h_str2str_load,h_str2int);
}
static void save2() {
char* bf;
int sz=maptomem(xuid_name,&bf,h_str2str,h_str2str);
mem2file("banxuid.db",bf,sz);
}
static void load2() {
char* buf;
int sz;
struct stat tmp;
if(stat("banxuid.db",&tmp)==-1) {
save2();
}
file2mem("banxuid.db",&buf,sz);
memtomap(xuid_name,buf,h_str2str_load,h_str2str_load);
}
bool isBanned(const string& name) {
if(banlist.count(name)) {
int tm=banlist[name];
if(tm==0) return 1;
if(time(0)>tm) {
banlist.erase(name);
save();
return 0;
}
return 1;
}
return 0;
}
static int logfd;
static int logsz;
static void initlog() {
logfd=open("player.log",O_WRONLY|O_APPEND|O_CREAT,S_IRWXU);
logsz=lseek(logfd,0,SEEK_END);
}
static void async_log(const char* fmt,...) {
char buf[10240];
auto x=time(0);
va_list vl;
va_start(vl,fmt);
auto tim=strftime(buf,128,"[%Y-%m-%d %H:%M:%S] ",localtime(&x));
int s=vsprintf(buf+tim,fmt,vl)+tim;
write(1,buf,s);
write(logfd,buf,s);
va_end(vl);
}
THook(void*,_ZN20ServerNetworkHandler22_onClientAuthenticatedERK17NetworkIdentifierRK11Certificate,u64 t,NetworkIdentifier& a, Certificate& b){
string pn=ExtendedCertificate::getIdentityName(b);
string xuid=ExtendedCertificate::getXuid(b);
async_log("[JOIN]%s joined game with xuid <%s>\n",pn.c_str(),xuid.c_str());
if(!xuid_name.count(xuid)){
xuid_name[xuid]=pn;
save2();
}
if(isBanned(pn) || (xuid_name.count(xuid) && isBanned(xuid_name[xuid]))) {
string ban("§c你在当前服务器的黑名单内!");
getMC()->getNetEventCallback()->disconnectClient(a,ban,false);
return nullptr;
}
return original(t,a,b);
}
static bool hkc(ServerPlayer const * b,string& c) {
async_log("[CHAT]%s: %s\n",b->getName().c_str(),c.c_str());
return 1;
}
#include <sys/socket.h>
#include <arpa/inet.h>
ssize_t (*rori)(int socket, void * buffer, size_t length,
int flags, struct sockaddr * address,
socklen_t * address_len);
static ssize_t recvfrom_hook(int socket, void * buffer, size_t length,
int flags, struct sockaddr * address,
socklen_t * address_len) {
int rt=rori(socket,buffer,length,flags,address,address_len);
if(rt && ((char*)buffer)[0]==0x5) {
char buf[1024];
inet_ntop(AF_INET,&(((sockaddr_in*)address)->sin_addr),buf,*address_len);
async_log("[NETWORK] %s send conn\n",buf);
}
return rt;
}
static void oncmd(std::vector<string>& a,CommandOrigin const & b,CommandOutput &outp) {
ARGSZ(1)
if((int)b.getPermissionsLevel()>0) {
banlist[a[0]]=a.size()==1?0:(time(0)+atoi(a[1].c_str()));
runcmd(string("skick \"")+a[0]+"\" §c你号没了");
save();
auto x=getuser_byname(a[0]);
if(x){
xuid_name[x->getXUID()]=x->getName();
save2();
}
outp.success("§e玩家已封禁: "+a[0]);
}
}
static void oncmd2(std::vector<string>& a,CommandOrigin const & b,CommandOutput &outp) {
ARGSZ(1)
if((int)b.getPermissionsLevel()>0) {
banlist.erase(a[0]);
save();
outp.success("§e玩家已解封: "+a[0]);
}
}
//add custom
using std::unordered_set;
unordered_set<short> banitems,warnitems;
bool dbg_player;
int LOG_CHEST;
static bool handle_u(GameMode* a0,ItemStack * a1,BlockPos const* a2,BlockPos const* dstPos,Block const* a5) {
if(dbg_player){
sendText(a0->getPlayer(),"you use id "+std::to_string(a1->getId()));
}
if(LOG_CHEST && a5->getLegacyBlock()->getBlockItemId()==54){
async_log("[CHEST] %s open chest pos: %d %d %d\n",a0->getPlayer()->getName().c_str(),a2->x,a2->y,a2->z);
}
//printf("dbg use %s\n",a0->getPlayer()->getCarriedItem().toString().c_str());
if(a0->getPlayer()->getPlayerPermissionLevel()>1) return 1;
string sn=a0->getPlayer()->getName();
if(banitems.count(a1->getId())){
async_log("[ITEM] %s 使用高危物品(banned) %s pos: %d %d %d\n",sn.c_str(),a1->toString().c_str(),a2->x,a2->y,a2->z);
sendText(a0->getPlayer(),"§c无法使用违禁物品",JUKEBOX_POPUP);
return 0;
}
if(warnitems.count(a1->getId())){
async_log("[ITEM] %s 使用危险物品(warn) %s pos: %d %d %d\n",sn.c_str(),a1->toString().c_str(),a2->x,a2->y,a2->z);
return 1;
}
return 1;
}
static void handle_left(ServerPlayer* a1){
async_log("[LEFT] %s left game\n",a1->getName().c_str());
}
#include"rapidjson/document.h"
int FPushBlock,FExpOrb,FDest;
enum CheatType{
FLY,NOCLIP,INV,MOVE
};
static void notifyCheat(const string& name,CheatType x){
const char* CName[]={"FLY","NOCLIP","Creative","Teleport"};
async_log("[%s] detected for %s\n",CName[x],name.c_str());
string kick=string("skick \"")+name+"\" §c你号没了";
switch(x){
case FLY:
runcmd(kick);
break;
case NOCLIP:
runcmd(kick);
break;
case INV:
runcmd(kick);
break;
case MOVE:
runcmd(kick);
break;
}
}
THook(void*,_ZN5BlockC2EtR7WeakPtrI11BlockLegacyE,Block* a,unsigned short x,void* c){
auto ret=original(a,x,c);
if(FPushBlock){
auto* leg=a->getLegacyBlock();
if(a->isContainerBlock()) leg->addBlockProperty({0x1000000LL});
}
return ret;
}
unordered_map<string,clock_t> lastchat;
int FChatLimit;
static bool ChatLimit(ServerPlayer* p){
if(!FChatLimit || p->getPlayerPermissionLevel()>1) return true;
auto last=lastchat.find(p->getRealNameTag());
if(last!=lastchat.end()){
auto old=last->second;
auto now=clock();
last->second=now;
if(now-old<CLOCKS_PER_SEC*0.25) return false;
return true;
}else{
lastchat.insert({p->getRealNameTag(),clock()});
return true;
}
}
THook(void*,_ZN20ServerNetworkHandler6handleERK17NetworkIdentifierRK10TextPacket,ServerNetworkHandler* sh,NetworkIdentifier const& iden,Packet* pk){
ServerPlayer* p=sh->_getServerPlayer(iden,pk->getClientSubId());
if(p){
if(ChatLimit(p))
return original(sh,iden,pk);
}
return nullptr;
}
THook(void*,_ZN20ServerNetworkHandler6handleERK17NetworkIdentifierRK20CommandRequestPacket,ServerNetworkHandler* sh,NetworkIdentifier const& iden,Packet* pk){
ServerPlayer* p=sh->_getServerPlayer(iden,pk->getClientSubId());
if(p){
if(ChatLimit(p))
return original(sh,iden,pk);
}
return nullptr;
}
THook(void*,_ZN20ServerNetworkHandler6handleERK17NetworkIdentifierRK24SpawnExperienceOrbPacket,ServerNetworkHandler* sh,NetworkIdentifier const& iden,Packet* pk){
if(FExpOrb){
return nullptr;
}
return original(sh,iden,pk);
}
THook(void*,_ZNK15StartGamePacket5writeER12BinaryStream,void* this_,void* a){
//dirty patch to hide seed
access(this_,uint,40)=114514;
return original(this_,a);
}
static int limitLevel(int input, int max) {
if (input < 0)
return 0;
else if (input > max)
return 0;
return input;
}
struct Enchant {
enum Type : int {};
static std::vector<std::unique_ptr<Enchant>> mEnchants;
virtual ~Enchant();
virtual bool isCompatibleWith(Enchant::Type type);
virtual int getMinCost(int);
virtual int getMaxCost(int);
virtual int getMinLevel();
virtual int getMaxLevel();
virtual bool canEnchant(int) const;
};
struct EnchantmentInstance {
enum Enchant::Type type;
int level;
int getEnchantType() const;
int getEnchantLevel() const;
void setEnchantLevel(int);
};
//将外挂附魔无效
THook(int, _ZNK19EnchantmentInstance15getEnchantLevelEv, EnchantmentInstance* thi) {
int level2 = thi->level;
auto &enchant = Enchant::mEnchants[thi->type];
auto max = enchant->getMaxLevel();
auto result = limitLevel(level2, max);
if (result != level2) thi->level = result;
return result;
}
typedef unsigned long IHash;
static IHash MAKE_IHASH(ItemStack* a){
IHash res= a->getIdAuxEnchanted();
if(*a->getUserData()){
res^=(*(a->getUserData()))->hash()<<28;
}
return res;
}
struct VirtInv{
unordered_map<IHash,int> items;
bool bad;
VirtInv(Player& p){
bad=0;
}
void setBad(){
bad=1;
}
void addItem(IHash item,int count){
if(item==0) return;
int prev=items[item];
items[item]=prev+count;
}
void takeItem(IHash item,int count){
addItem(item,-count);
}
bool checkup(){
if(bad) return 1;
for(auto &i:items){
if(i.second<0){
return false;
}
}
return true;
}
void clear(){
items.clear();
bad=false;
}
};
//unordered_map<string,IHash> lastitem;
THook(unsigned long,_ZNK20InventoryTransaction11executeFullER6Playerb,void* _thi,Player &player, bool b){
if(player.getPlayerPermissionLevel()>1) return original(_thi,player,b);
const string& name=player.getName();
auto& a=*((unordered_map<InventorySource,vector<InventoryAction> >*)_thi);
for(auto& i:a){
for(auto& j:i.second){
if(i.first.getContainerId()==119){
//offhand chk
if((!j.getToItem()->isNull() && !j.getToItem()->isOffhandItem()) || (!j.getFromItem()->isNull() && !j.getFromItem()->isOffhandItem())){
notifyCheat(name,INV);
return 6;
}
}
if(banitems.count(j.getFromItem()->getId()) || banitems.count(j.getToItem()->getId())){
async_log("[ITEM] %s 使用高危物品(banned) %s %s\n",name.c_str(),j.getFromItem()->toString().c_str(),j.getToItem()->toString().c_str());
sendText(&player,"§c无法使用违禁物品",JUKEBOX_POPUP);
return 6;
}
/*
if(j.getSlot()==50 && i.first.getContainerId()==124){
//track this
auto hashf=MAKE_IHASH(j.getFromItem()),hasht=MAKE_IHASH(j.getToItem());
auto it=lastitem.find(name);
if(it==lastitem.end()){
lastitem[name]=hasht;
continue;
}else{
if(it->second!=hashf){
async_log("[ITEM] crafting hack detected for %s , %s\n",name.c_str(),j.getFromItem()->toString().c_str());
notifyCheat(name,INV);
return 6;
}
it->second=hasht;
}
}*/
//printf("cid %d flg %d src %d slot %u get %d %s %s hash %ld %ld\n",j.getSource().getContainerId(),j.getSource().getFlags(),j.getSource().getType(),j.getSlot(),i.first.getContainerId(),j.getFromItem()->toString().c_str(),j.getToItem()->toString().c_str(),MAKE_IHASH(j.getFromItem()),MAKE_IHASH(j.getToItem()));
}
}
return original(_thi,player,b);
}
using namespace rapidjson;
static void load_config(){
char buf[96*1024];
banitems.clear();warnitems.clear();
int fd=open("config/bear.json",O_RDONLY);
if(fd==-1){
printf("[BEAR] Cannot load config file!check your configs folder\n");
exit(0);
}
buf[read(fd,buf,96*1024-1)]=0;
close(fd);
Document d;
if(d.ParseInsitu(buf).HasParseError()){
printf("[ANTIBEAR] JSON ERROR!\n");
exit(1);
}
FPushBlock=d["FPushChest"].GetBool();
FExpOrb=d["FSpwanExp"].GetBool();
FDest=d["FDestroyCheck"].GetBool();
FChatLimit=d["FChatLimit"].GetBool();
LOG_CHEST=d.HasMember("LogChest")?d["LogChest"].GetBool():false;
auto&& x=d["banitems"].GetArray();
for(auto& i:x){
banitems.insert((short)i.GetInt());
}
auto&& y=d["warnitems"].GetArray();
for(auto& i:y){
warnitems.insert((short)i.GetInt());
}
}
string lastn;
clock_t lastcl;
int fd_count;
#include<ctime>
static int handle_dest(GameMode* a0,BlockPos const& a1,unsigned char a2) {
if(!FDest) return 1;
int pl=a0->getPlayer()->getPlayerPermissionLevel();
if(pl>1 || a0->getPlayer()->isCreative()) {
return 1;
}
const string& name=a0->getPlayer()->getName();
int x(a1.x),y(a1.y),z(a1.z);
Block& bk=*a0->getPlayer()->getBlockSource()->getBlock(a1);
int id=bk.getLegacyBlock()->getBlockItemId();
if(id==7 || id==416){
notifyCheat(name,CheatType::INV);
return 0;
}
if(name==lastn && clock()-lastcl<CLOCKS_PER_SEC*(10.0/1000)/*10ms*/) {
lastcl=clock();
fd_count++;
if(fd_count>=5){
fd_count=3;
return 0;
}
}else{
lastn=name;
lastcl=clock();
fd_count=0;
}
const Vec3& fk=a0->getPlayer()->getPos();
#define abs(x) ((x)<0?-(x):(x))
int dx=fk.x-x;
int dy=fk.y-y;
int dz=fk.z-z;
int d2=dx*dx+dy*dy+dz*dz;
if(d2>45) {
return 0;
}
return 1;
}
static void toggle_dbg(){
dbg_player=!dbg_player;
}
static void kick_cmd(std::vector<string>& a,CommandOrigin const & b,CommandOutput &outp) {
ARGSZ(1)
if((int)b.getPermissionsLevel()>0) {
if(a.size()==1) a.push_back("Kicked");
runcmd("kick \""+a[0]+"\" "+a[1]);
auto x=getuser_byname(a[0]);
if(x){
forceKickPlayer(*x);
outp.success("okay!");
}else{
outp.error("not found!");
}
}
}
static void bangui_cmd(std::vector<string>& a,CommandOrigin const & b,CommandOutput &outp) {
string nm=b.getName();
gui_ChoosePlayer((ServerPlayer*)b.getEntity(),"ban","ban",[nm](const string& dst){
auto sp=getplayer_byname(nm);
if(sp)
runcmdAs("ban \""+dst+"\"",sp);
});
}
void bear_init(std::list<string>& modlist) {
if(getenv("LOGCHEST")) LOG_CHEST=1;
load();
load2();
initlog();
register_cmd("ban",fp(oncmd),"封禁玩家",1);
register_cmd("unban",fp(oncmd2),"解除封禁",1);
register_cmd("reload_bear",fp(load_config),"Reload Configs for antibear",1);
register_cmd("bear_dbg",fp(toggle_dbg),"toggle debug item",1);
register_cmd("skick",fp(kick_cmd),"force kick",1);
register_cmd("bangui",fp(bangui_cmd),"封禁玩家GUI",1);
reg_useitemon(handle_u);
reg_player_left(handle_left);
reg_chat(hkc);
load_config();
rori=(typeof(rori))(MyHook(fp(recvfrom),fp(recvfrom_hook)));
printf("[ANTI-BEAR] Loaded V2019-11-25\n");
load_helper(modlist);
}
| 30.431373
| 318
| 0.611856
|
littlegao233
|
90f72a9dd022e250b6a9e1f2a7f37d170ee7ea44
| 6,059
|
cpp
|
C++
|
src/BasicRSVD.cpp
|
djanekovic/librsvd
|
83c626c749f2924ca6d7d49d3625c53c1f93a2c1
|
[
"MIT"
] | null | null | null |
src/BasicRSVD.cpp
|
djanekovic/librsvd
|
83c626c749f2924ca6d7d49d3625c53c1f93a2c1
|
[
"MIT"
] | null | null | null |
src/BasicRSVD.cpp
|
djanekovic/librsvd
|
83c626c749f2924ca6d7d49d3625c53c1f93a2c1
|
[
"MIT"
] | null | null | null |
#include <random>
#include <iostream>
#include <algorithm>
#include "Eigen/SVD"
// forward declaration for Eigen::internal::traits
namespace rsvd {
template<typename _MatrixType> class BasicRSVD;
}
namespace Eigen {
namespace internal {
template <typename _MatrixType>
struct traits<rsvd::BasicRSVD<_MatrixType>>: traits<_MatrixType>
{
using MatrixType = _MatrixType;
};
} // end namespace internal
} // end namespace Eigen
namespace rsvd {
using Matrix = Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>;
using Vector = Eigen::Matrix<double, Eigen::Dynamic, 1>;
template<typename ScalarType>
struct normal_distribution_functor
{
private:
ScalarType mean_, stddev_;
public:
normal_distribution_functor(ScalarType mean=0, ScalarType stddev=1):
mean_{mean}, stddev_{stddev} {}
ScalarType operator() () const {
static thread_local std::mt19937 generator;
std::normal_distribution<ScalarType> distribution(mean_, stddev_);
return distribution(generator);
}
};
/**
* Generate random matrix with full rank
*/
Matrix GenerateRandomMatrix(std::size_t m, std::size_t n)
{
return Matrix::Random(m, n);
}
/**
* Generate random matrix with rank k
*/
Matrix GenerateRandomMatrix(std::size_t m, std::size_t n, std::size_t k)
{
Matrix A = GenerateRandomMatrix(m, n);
Eigen::BDCSVD<Matrix> svd(A, Eigen::ComputeThinU | Eigen::ComputeThinV);
Vector singular_values = svd.singularValues();
singular_values.tail(std::min(m, n) - k).setZero();
return svd.matrixU() * singular_values.asDiagonal() * svd.matrixV().adjoint();
}
/**
* Generate symmetric random matrix with full rank
*/
Matrix GenerateRandomSymmetricMatrix(std::size_t m, std::size_t n)
{
Matrix A = GenerateRandomMatrix(m, n);
return A * A.adjoint();
}
/**
* Generate symmetric random matrix with rank k
*/
Matrix GenerateRandomSymmetricMatrix(std::size_t m, std::size_t n, std::size_t k)
{
Matrix A = GenerateRandomMatrix(m, n, k);
return A * A.adjoint();
}
template<typename _MatrixType>
class BasicRSVD: public Eigen::SVDBase<BasicRSVD<_MatrixType>> {
using Base = Eigen::SVDBase<BasicRSVD>;
using MatrixType = _MatrixType;
using Scalar = typename MatrixType::Scalar;
using RealScalar = typename Eigen::NumTraits<Scalar>::Real;
// real matrix
using MatrixXr = Eigen::Matrix<RealScalar, Eigen::Dynamic, Eigen::Dynamic>;
// complex matrix
using MatrixXc = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>;
MatrixXc Y, Q, B;
MatrixXr I;
Eigen::BDCSVD<MatrixType> small_svd;
Eigen::HouseholderQR<MatrixType> qr;
public:
BasicRSVD() {}
BasicRSVD(Eigen::Index rows, Eigen::Index cols, size_t target_rank, size_t oversampling)
{
allocate(rows, cols, target_rank, oversampling);
}
BasicRSVD(const MatrixType &matrix, size_t target_rank, size_t oversampling, size_t num_steps=1)
{
compute(matrix, target_rank, oversampling, num_steps);
}
BasicRSVD& compute(const MatrixType &matrix, size_t target_rank, size_t oversampling, size_t num_steps);
private:
void allocate(Eigen::Index rows, Eigen::Index cols, size_t target_rank, size_t oversampling);
};
template<typename MatrixType>
void BasicRSVD<MatrixType>::allocate(Eigen::Index rows, Eigen::Index cols, size_t target_rank, size_t oversampling)
{
// allocate is called before and we have nothing else to do
if ((Base::m_isAllocated) && Base::m_rows == rows && Base::m_cols == cols) {
return;
}
Base::m_rows = rows;
Base::m_cols = cols;
Base::m_isInitialized = false;
Base::m_isAllocated = true;
Base::m_computeThinU = true;
Base::m_computeThinV = true;
// we don't need V or singular values since we get those using small SVD
Base::m_matrixU.resize(rows, target_rank + oversampling);
Q = MatrixXc::Zero(rows, target_rank + oversampling);
Y = MatrixXc::Zero(rows, target_rank + oversampling);
B = MatrixXc::Zero(target_rank + oversampling, cols);
I = MatrixXr::Identity(rows, target_rank + oversampling);
small_svd = Eigen::BDCSVD<MatrixType>(target_rank + oversampling, cols, Eigen::ComputeThinU | Eigen::ComputeThinV);
qr = Eigen::HouseholderQR<MatrixType>(rows, target_rank + oversampling);
}
/**
* Compute randomized SVD of matrix A with target rank, oversampling and num_steps of power iterations.
*/
template<typename MatrixType>
BasicRSVD<MatrixType>& BasicRSVD<MatrixType>::compute(const MatrixType &A, size_t target_rank,
size_t oversampling, size_t num_steps)
{
allocate(A.rows(), A.cols(), target_rank, oversampling);
//Input matrix is mxn (m - num_rows, n - num_cols)
// form sample matrix Y with size (m x (k+p))
Y.noalias() = A * MatrixXr::NullaryExpr(A.cols(), target_rank + oversampling, normal_distribution_functor<RealScalar>());;
for (auto i = 0u; i < num_steps; i++) {
Y = (A * A.adjoint()) * Y;
}
// QR decomposition of matrix Y:
// - (m x k+p), (k+p, k+p)
// NOTE: we are computing this inplace
qr.compute(Y);
// generate thin Q
Q.noalias() = qr.householderQ() * I;
// Matrix B is (k+p x n)
B.noalias() = Q.adjoint() * A;
small_svd.compute(B);
Base::m_matrixU.noalias() = Q * small_svd.matrixU();
// TODO: it would be great if we could just use the memory from small_svd but we need
// to allocate here since SVDBase::matrixV() returns reference which we can't move.
Base::m_matrixV = small_svd.matrixV();
Base::m_singularValues = small_svd.singularValues();
Base::m_isInitialized = true;
return *this;
}
} // end namespace rsvd
void test_rsvd(const rsvd::Matrix &A)
{
rsvd::BasicRSVD<rsvd::Matrix> rsvd(A, 45, 0, 1);
rsvd::Matrix A_ = rsvd.matrixU() * rsvd.singularValues().asDiagonal() * rsvd.matrixV().adjoint();
std::cout << (A - A_).norm() << std::endl;
}
int main(void) {
rsvd::Matrix A = rsvd::GenerateRandomMatrix(1000, 100, 50);
test_rsvd(A);
}
| 28.852381
| 126
| 0.684271
|
djanekovic
|
90f8557d5a28f9b3b125147539f84c20ad8e8f1d
| 3,123
|
cpp
|
C++
|
GLEANKernel/GLEANLib/Utility Classes/Symbol_memory.cpp
|
dekieras/GLEANKernel
|
fac01f025b65273be96c5ea677c0ce192c570799
|
[
"MIT"
] | 1
|
2018-06-22T23:01:13.000Z
|
2018-06-22T23:01:13.000Z
|
GLEANKernel/GLEANLib/Utility Classes/Symbol_memory.cpp
|
dekieras/GLEANKernel
|
fac01f025b65273be96c5ea677c0ce192c570799
|
[
"MIT"
] | null | null | null |
GLEANKernel/GLEANLib/Utility Classes/Symbol_memory.cpp
|
dekieras/GLEANKernel
|
fac01f025b65273be96c5ea677c0ce192c570799
|
[
"MIT"
] | null | null | null |
#include "Symbol_memory.h"
#include "Utility_templates.h"
#include "Assert_throw.h"
#include <cstddef>
using std::vector;
using std::set;
using std::strcpy;
using std::size_t;
Symbol_memory * Symbol_memory::Symbol_memory_ptr = 0;
// A Meyers singleton would get automatically destructed, which is not
// a good idea because the individual Symbols might get destructed afterwards
// everything should get freed except for the final empty container
Symbol_memory& Symbol_memory::get_instance()
{
if(!Symbol_memory_ptr)
Symbol_memory_ptr = new Symbol_memory;
return *Symbol_memory_ptr;
}
// deallocate the memory for the c-strings and the vectors
void Symbol_memory::clear()
{
for_each(vec_rep_ptr_set.begin(), vec_rep_ptr_set.end(), Delete());
vec_rep_ptr_set.clear();
for(Str_rep_ptr_set_t::iterator it = str_rep_ptr_set.begin(); it != str_rep_ptr_set.end(); it++) {
Symbol_memory_Str_rep * p = *it;
delete[] p->cstr;
delete p;
}
// deallocate the set contents
str_rep_ptr_set.clear();
}
// return the pointer to the Symbol_memory_Str_rep if the cstring is already present,
// add the Symbol_memory_Str_rep if it isn't, and return the pointer
// len is supplied because it is already computed - to save time
Symbol_memory_Str_rep * Symbol_memory::find_or_insert(const char * p, int len)
{
Symbol_memory_Str_rep sr(0, p, 0);
Str_rep_ptr_set_t::iterator it = str_rep_ptr_set.find(&sr);
if (it == str_rep_ptr_set.end()) {
char * cp = new char[len + 1];
strcpy(cp, p);
Symbol_memory_Str_rep * str_rep_ptr = new Symbol_memory_Str_rep(1, cp, len);
str_rep_ptr_set.insert(str_rep_ptr);
return str_rep_ptr;
}
else {
Symbol_memory_Str_rep * str_rep_ptr = *it;
// increment the count
(str_rep_ptr->count)++;
return str_rep_ptr;
}
}
Symbol_memory_Vec_rep * Symbol_memory::find_or_insert(bool single_, const std::vector<GU::Point>& v_)
{
Symbol_memory_Vec_rep vr(0, single_, v_);
Vec_rep_ptr_set_t::iterator it = vec_rep_ptr_set.find(&vr);
if (it == vec_rep_ptr_set.end()) {
Symbol_memory_Vec_rep * vec_rep_ptr = new Symbol_memory_Vec_rep(1, single_, v_);
vec_rep_ptr_set.insert(vec_rep_ptr);
return vec_rep_ptr;
}
else {
Symbol_memory_Vec_rep * vec_rep_ptr = *it;
// increment the count
(vec_rep_ptr->count)++;
return vec_rep_ptr;
}
}
// decrement the reference count; remove it and free the memory if it was the last use
void Symbol_memory::remove_if_last(Symbol_memory_Str_rep * str_rep_ptr)
{
(str_rep_ptr->count)--;
if(str_rep_ptr->count == 0) {
// remove it from the set
Str_rep_ptr_set_t::iterator it = str_rep_ptr_set.find(str_rep_ptr);
Assert(it != str_rep_ptr_set.end());
str_rep_ptr_set.erase(it);
delete str_rep_ptr;
}
}
// decrement the reference count; remove it and free the memory if it was the last use
void Symbol_memory::remove_if_last(Symbol_memory_Vec_rep * vec_rep_ptr)
{
(vec_rep_ptr->count)--;
if(vec_rep_ptr->count == 0) {
// remove it from the set
Vec_rep_ptr_set_t::iterator it = vec_rep_ptr_set.find(vec_rep_ptr);
Assert(it != vec_rep_ptr_set.end());
vec_rep_ptr_set.erase(it);
delete vec_rep_ptr;
}
}
| 30.028846
| 101
| 0.742875
|
dekieras
|
90f9617cb98f3e9abfcd92e1b289eb640849219d
| 368
|
cpp
|
C++
|
ObjectOrientedProgrammingCodes-CPP/CPPWorkspace/AnagramDiff/main.cpp
|
srinivasamaringanti/ObjectOrientedProgrammingCodes
|
84a11cf63d852aa4537bdde3bd0867b9a0725d66
|
[
"MIT"
] | null | null | null |
ObjectOrientedProgrammingCodes-CPP/CPPWorkspace/AnagramDiff/main.cpp
|
srinivasamaringanti/ObjectOrientedProgrammingCodes
|
84a11cf63d852aa4537bdde3bd0867b9a0725d66
|
[
"MIT"
] | null | null | null |
ObjectOrientedProgrammingCodes-CPP/CPPWorkspace/AnagramDiff/main.cpp
|
srinivasamaringanti/ObjectOrientedProgrammingCodes
|
84a11cf63d852aa4537bdde3bd0867b9a0725d66
|
[
"MIT"
] | null | null | null |
#include <conio.h>
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
cout<< "Hello,World"<< std::endl;
string a{"btoe"};
string b{"aeeg"};
sort(a.begin(),a.end());
sort(b.begin(), b.end());
cout<<"A: "<<a<<endl;
cout<<"B: "<<b<<endl;
getch();
return 0;
}
| 16.727273
| 37
| 0.535326
|
srinivasamaringanti
|
90fd35a75b5da54e0b9fc346755bc13f376d0f33
| 713
|
cpp
|
C++
|
src/static_search/generic_search.cpp
|
ParBLiSS/cao-reptile
|
bb807b0578396f3ffe156a95e612ef16d5da167c
|
[
"Apache-2.0"
] | null | null | null |
src/static_search/generic_search.cpp
|
ParBLiSS/cao-reptile
|
bb807b0578396f3ffe156a95e612ef16d5da167c
|
[
"Apache-2.0"
] | null | null | null |
src/static_search/generic_search.cpp
|
ParBLiSS/cao-reptile
|
bb807b0578396f3ffe156a95e612ef16d5da167c
|
[
"Apache-2.0"
] | null | null | null |
/********************************************************************
*
* Generic Search program
*
* Frederik Rønn, June 2003, University of Copenhagen.
*
*********************************************************************/
#ifndef __GENERIC_SEARCH_CPP__
#define __GENERIC_SEARCH_CPP__
template <typename RandomIterator, typename T, typename LayoutPolicy>
bool generic_search(RandomIterator begin,
RandomIterator beyond,
LayoutPolicy policy,
const T& value) {
policy.initialize(begin, beyond);
while(policy.not_finished()) {
if (policy.node_contains(value)) {
return true;
}
else
policy.descend_tree(value);
}
return false;
}
#endif //__GENERIC_SEARCH_CPP__
| 24.586207
| 70
| 0.580645
|
ParBLiSS
|
29088612d5e6fc4de2a5d7458e3f5d91d05e94c9
| 14,145
|
cpp
|
C++
|
gui/MyCanvas.cpp
|
myirci/3d_circle_estimation
|
7161005ab14d510503310e0bb028fea5ad2a1389
|
[
"MIT"
] | 5
|
2020-07-16T18:59:05.000Z
|
2022-03-04T01:25:54.000Z
|
gui/MyCanvas.cpp
|
myirci/3d_circle_estimation
|
7161005ab14d510503310e0bb028fea5ad2a1389
|
[
"MIT"
] | null | null | null |
gui/MyCanvas.cpp
|
myirci/3d_circle_estimation
|
7161005ab14d510503310e0bb028fea5ad2a1389
|
[
"MIT"
] | 1
|
2021-04-08T13:49:32.000Z
|
2021-04-08T13:49:32.000Z
|
#include "MyCanvas.hpp"
#include "MyFrame.hpp"
#include "../geometry/Segment3D.hpp"
#include "../geometry/Circle3D.hpp"
#include "../data/teapot.hpp"
#include "../algorithm/algorithm.hpp"
#include "../utility/utility.hpp"
#include <sstream>
BEGIN_EVENT_TABLE(MyCanvas, wxScrolledWindow)
EVT_PAINT(MyCanvas::OnPaint)
EVT_LEFT_DOWN(MyCanvas::OnMouseLeftClick)
EVT_RIGHT_DOWN(MyCanvas::OnMouseRightClick)
EVT_MOTION(MyCanvas::OnMouseMove)
EVT_KEY_DOWN(MyCanvas::OnKeyDown)
EVT_SIZE(MyCanvas::OnResize)
END_EVENT_TABLE()
MyCanvas::MyCanvas(MyFrame* parent) :
wxScrolledWindow(parent,
wxID_ANY,
wxDefaultPosition,
wxDefaultSize,
wxHSCROLL | wxVSCROLL | wxFULL_REPAINT_ON_RESIZE),
m_parent(parent) {
wxSize size = m_parent->GetClientSize();
m_renderer.set_screen_width_and_height(size.GetWidth(), size.GetHeight());
m_render_mode = render_mode::two_dim;
m_renderer.gluPerspective(45.0, 1.0, 100.0);
SetBackgroundColour(wxColour(*wxWHITE));
Eigen::Vector3d normal(-1, 2, -3);
normal.normalize();
Circle3D circ(Eigen::Vector3d(1, 2, -8), // center
normal, // normal
1.0); // radius
std::cout << "Ground truth circle normal:\n " << normal << std::endl;
m_groud_truth_3DCircles.push_back(circ);
std::cout << "Ground truth circle center:\n" << circ.center << std::endl;
}
void MyCanvas::Estimate_3DCircles(estimation_algorithm method) {
if(method == estimation_algorithm::method_1) {
estimate_3d_circles_1();
}
else if(method == estimation_algorithm::method_2) {
estimate_3d_circles_2();
}
else if(method == estimation_algorithm::method_3) {
estimate_3d_circles_3();
}
else if(method == estimation_algorithm::method_4) {
estimate_3d_circles_4();
}
}
void MyCanvas::estimate_3d_circles_1() {
Eigen::Matrix4d mat = Eigen::Matrix4d::Identity();
m_renderer.get_projection_matrix(mat);
Circle3D circles[2];
circles[0].radius = 1.0;
circles[1].radius = 1.0;
int h{0}, w{0};
this->GetSize(&w, &h);
for(auto it = m_ellipses.begin(); it != m_ellipses.end(); ++it) {
it->calculate_algebraic_equation_in_normalized_device_coordinates(w, h);
// it->calculate_algebraic_equation_in_projected_coordinates(w, h, 1, deg2rad(45.0/2.0));
estimate_3D_circles_under_perspective_transformation_method_1(mat, *it, circles);
m_3DCircles.push_back(circles[0]);
m_3DCircles.push_back(circles[1]);
}
}
void MyCanvas::estimate_3d_circles_2() {
Circle3D circle[4];
circle[0].radius = 1.0;
circle[1].radius = 1.0;
circle[2].radius = 1.0;
circle[3].radius = 1.0;
int h{0}, w{0};
this->GetSize(&w, &h);
for(auto it = m_ellipses.begin(); it != m_ellipses.end(); ++it) {
it->calculate_algebraic_equation_in_projected_coordinates(w, h, 1, deg2rad(45.0/2.0));
estimate_3D_circles_under_perspective_transformation_method_2(*it, circle, -1);
if(circle[0].center(2) <= -1) {
m_3DCircles.push_back(circle[0]);
std::cout << "Circle-1: Valid" << std::endl;
}
if(circle[1].center(2) <= -1) {
m_3DCircles.push_back(circle[1]);
std::cout << "Circle-2: Valid" << std::endl;
}
if(circle[2].center(2) <= -1) {
m_3DCircles.push_back(circle[2]);
std::cout << "Circle-3: Valid" << std::endl;
}
if(circle[3].center(2) <= -1) {
m_3DCircles.push_back(circle[3]);
std::cout << "Circle-4: Valid" << std::endl;
}
}
}
void MyCanvas::estimate_3d_circles_3() {
Circle3D circle[8];
circle[0].radius = 1.0;
circle[1].radius = 1.0;
circle[2].radius = 1.0;
circle[3].radius = 1.0;
circle[4].radius = 1.0;
circle[5].radius = 1.0;
circle[6].radius = 1.0;
circle[7].radius = 1.0;
Eigen::Matrix4d mat = Eigen::Matrix4d::Identity();
m_renderer.get_pure_projection_matrix(mat);
Eigen::Matrix3d mat2;
mat2.row(0) = mat.block(0,0,1,3);
mat2.row(1) = mat.block(1,0,1,3);
mat2.row(2) = mat.block(3,0,1,3);
int h{0}, w{0};
this->GetSize(&w, &h);
for(auto it = m_ellipses.begin(); it != m_ellipses.end(); ++it) {
it->calculate_algebraic_equation_in_projected_coordinates(w, h, 1, deg2rad(45.0/2.0));
estimate_3D_circles_under_perspective_transformation_method_3(mat2, *it, circle);
m_3DCircles.push_back(circle[0]);
m_3DCircles.push_back(circle[1]);
m_3DCircles.push_back(circle[2]);
m_3DCircles.push_back(circle[3]);
m_3DCircles.push_back(circle[4]);
m_3DCircles.push_back(circle[5]);
m_3DCircles.push_back(circle[6]);
m_3DCircles.push_back(circle[7]);
}
}
void MyCanvas::estimate_3d_circles_4() {
Circle3D circle[4];
circle[0].radius = 1.0;
circle[1].radius = 1.0;
circle[2].radius = 1.0;
circle[3].radius = 1.0;
int h{0}, w{0};
this->GetSize(&w, &h);
for(auto it = m_ellipses.begin(); it != m_ellipses.end(); ++it) {
it->calculate_algebraic_equation_in_projected_coordinates(w, h, 1, deg2rad(45.0/2.0));
int count = estimate_3D_circles_under_perspective_transformation_method_4(*it, circle, -1);
if(count == 4) {
if(circle[0].center(2) <= -1) {
m_3DCircles.push_back(circle[0]);
std::cout << "Circle-1: Valid" << std::endl;
}
if(circle[1].center(2) <= -1) {
m_3DCircles.push_back(circle[1]);
std::cout << "Circle-2: Valid" << std::endl;
}
if(circle[2].center(2) <= -1) {
m_3DCircles.push_back(circle[2]);
std::cout << "Circle-3: Valid" << std::endl;
}
if(circle[3].center(2) <= -1) {
m_3DCircles.push_back(circle[3]);
std::cout << "Circle-4: Valid" << std::endl;
}
}
else if(count == 1) {
if(circle[0].center(2) <= -1) {
m_3DCircles.push_back(circle[0]);
std::cout << "Circle-1: Valid" << std::endl;
}
}
}
}
void MyCanvas::SetRenderingMode(render_mode mode) {
m_render_mode = mode;
Refresh();
}
void MyCanvas::OnPaint(wxPaintEvent& event) {
wxPaintDC dc(this);
dc.SetBrush(*wxTRANSPARENT_BRUSH);
SetupCoordinateFrame(dc);
if(m_render_mode == render_mode::two_dim) { Render2D(dc); }
else if(m_render_mode == render_mode::three_dim) { Render3D(dc); }
else if(m_render_mode == render_mode::both) { Render2D(dc);
Render3D(dc); }
}
void MyCanvas::Render2D(wxPaintDC& dc) {
dc.SetPen(*wxBLUE_PEN);
if(!m_ellipses.empty()) { RenderEllipses(dc); }
if(!m_points.empty()) { RenderEllipse(dc); }
}
void MyCanvas::Render3D(wxPaintDC& dc) {
dc.SetPen(wxPen(*wxRED, 3));
std::vector<Eigen::Vector3d> data;
for(auto it = m_3DCircles.begin(); it != m_3DCircles.end(); ++it) {
data.clear();
it->generate_data(data, 8);
m_renderer.render(data, dc);
}
dc.SetPen(wxPen(*wxCYAN, 3));
for(auto it = m_groud_truth_3DCircles.begin(); it != m_groud_truth_3DCircles.end(); ++it) {
data.clear();
it->generate_data(data, 100);
m_renderer.render(data, dc);
}
}
void MyCanvas::SetupCoordinateFrame(wxPaintDC& dc) {
wxSize size = m_parent->GetClientSize();
dc.SetAxisOrientation(true, true);
dc.SetDeviceOrigin(size.GetWidth()/2, size.GetHeight()/2);
dc.DrawLine(-size.GetWidth()/2,0,size.GetWidth()/2,0);
dc.DrawLine(0,-size.GetHeight()/2,0,size.GetHeight()/2);
}
void MyCanvas::RenderEllipse(wxPaintDC& dc) {
if(m_points.size() == 1) {
dc.DrawLine(m_points[0], m_mouse_pos);
Point2D<double> p0(m_points[0].x, m_points[0].y);
Point2D<double> center((m_points[0].x + m_mouse_pos.x)/2.0,
(m_points[0].y + m_mouse_pos.y)/2.0);
dc.DrawCircle(static_cast<int>(center.x),
static_cast<int>(center.y),
dist(p0, center));
}
else if(m_points.size() == 2) {
Point2D<double> p0(m_points[0].x, m_points[0].y);
Point2D<double> p1(m_points[1].x, m_points[1].y);
Point2D<double> center((p0.x + p1.x)/2, (p0.y + p1.y)/2);
double smajor_axis = dist(p0, center);
double sminor_axis = 0.0;
Vector2D<double> vec_mj = p1 - p0;
Vector2D<double> vec_mn(-vec_mj.y, vec_mj.x);
Vector2D<double> minor_unit = vec_mn.normalized();
Point2D<double> p2 = center - smajor_axis*minor_unit;
Point2D<double> p3 = center + smajor_axis*minor_unit;
Point2D<double> mouse_pos(m_mouse_pos.x, m_mouse_pos.y);
Vector2D<double> mouse_vec = mouse_pos - p2;
double ratio = vec_mn.dot(mouse_vec) / vec_mn.dot(vec_mn);
if(ratio >= 0.0 && ratio <= 1.0) {
Vector2D<double> proj_vec = (2*ratio*smajor_axis) * minor_unit;
Point2D<double> proj_point = p2 + proj_vec;
sminor_axis = dist(center, proj_point);
// draw a mini circle on the projection point
dc.DrawCircle(static_cast<int>(proj_point.x), static_cast<int>(proj_point.y), 2);
m_ellipse.center = Point2D<double>(center.x, center.y);
m_ellipse.semi_major_axis = smajor_axis;
m_ellipse.semi_minor_axis = sminor_axis;
if(vec_mj.y > 0) {
m_ellipse.rot_angle = std::acos(vec_mj.x/vec_mj.norm());
}
else {
m_ellipse.rot_angle = -std::acos(vec_mj.x/vec_mj.norm());
}
double data[80];
m_ellipse.generate_points_on_the_ellipse(40, data);
for(int i = 0; i < 78; i += 2) {
dc.DrawLine(static_cast<int>(data[i]),
static_cast<int>(data[i+1]),
static_cast<int>(data[i+2]),
static_cast<int>(data[i+3]));
}
dc.DrawLine(static_cast<int>(data[0]),
static_cast<int>(data[1]),
static_cast<int>(data[78]),
static_cast<int>(data[79]));
m_ellipse.points[2] = proj_point;
DisplayAlgebraicEquation();
}
// Draw the end points
dc.DrawCircle(static_cast<int>(p0.x), static_cast<int>(p0.y), 2);
dc.DrawCircle(static_cast<int>(p1.x), static_cast<int>(p1.y), 2);
dc.DrawCircle(static_cast<int>(center.x), static_cast<int>(center.y), 2);
dc.DrawCircle(static_cast<int>(p2.x), static_cast<int>(p2.y), 2);
dc.DrawCircle(static_cast<int>(p3.x), static_cast<int>(p3.y), 2);
// draw the major axis and minor axis guide line
dc.DrawLine(static_cast<int>(p0.x), static_cast<int>(p0.y),
static_cast<int>(p1.x), static_cast<int>(p1.y));
dc.SetPen(*wxBLACK_DASHED_PEN);
dc.DrawLine(static_cast<int>(p2.x), static_cast<int>(p2.y),
static_cast<int>(p3.x), static_cast<int>(p3.y));
}
else {
m_points.clear();
}
}
void MyCanvas::RenderEllipses(wxPaintDC& dc) {
const int num = 80;
const int size = num*2;
double data[size];
for(auto it = m_ellipses.begin(); it != m_ellipses.end(); ++it){
it->generate_points_on_the_ellipse(num, data);
for(int i = 0; i < size-2; i+= 2) {
dc.DrawLine(static_cast<int>(data[i]),
static_cast<int>(data[i+1]),
static_cast<int>(data[i+2]),
static_cast<int>(data[i+3]));
}
dc.DrawLine(static_cast<int>(data[0]),
static_cast<int>(data[1]),
static_cast<int>(data[size-2]),
static_cast<int>(data[size-1]));
}
}
void MyCanvas::DisplayAlgebraicEquation() {
m_ellipse.calculate_algebraic_equation_in_wxWidget_coordinates();
wxString str;
str << "(" << m_ellipse.coeff[0] << "xx) + "
<< "(" << m_ellipse.coeff[1] << "xy) + "
<< "(" << m_ellipse.coeff[2] << "yy) + "
<< "(" << m_ellipse.coeff[3] << "x) + "
<< "(" << m_ellipse.coeff[4] << "y) + "
<< "(" << m_ellipse.coeff[5] << ")";
m_parent->SetStatusText(str, 2);
wxString str2;
str2 << rad2deg(m_ellipse.rot_angle);
m_parent->SetStatusText(str2, 1);
}
void MyCanvas::OnMouseLeftClick(wxMouseEvent& event) {
m_points.push_back(DeviceToLogical(event.GetPosition()));
Refresh();
}
void MyCanvas::OnMouseRightClick(wxMouseEvent& event) {
if(m_points.size() == 2) {
m_ellipse.points[0] = Point2D<double>(m_points[0].x, m_points[0].y);
m_ellipse.points[1] = Point2D<double>(m_points[1].x, m_points[1].y);
m_ellipses.push_back(m_ellipse);
}
m_points.clear();
Refresh();
}
void MyCanvas::OnMouseMove(wxMouseEvent& event) {
m_mouse_pos = DeviceToLogical(event.GetPosition());
wxString str;
str << "(" << m_mouse_pos.x << ", " << m_mouse_pos.y << ")";
m_parent->SetStatusText(str, 0);
Refresh();
}
void MyCanvas::OnKeyDown(wxKeyEvent &event) {
if(event.GetKeyCode() == WXK_ESCAPE) {
m_points.clear();
m_ellipses.clear();
m_3DCircles.clear();
Refresh();
}
}
void MyCanvas::OnResize(wxSizeEvent& event) {
m_renderer.set_screen_width_and_height(event.GetSize().GetWidth(),
event.GetSize().GetHeight());
}
wxPoint MyCanvas::DeviceToLogical(const wxPoint& pt) {
wxSize size = m_parent->GetClientSize();
return wxPoint(pt.x - (size.GetWidth()-1)/2, (size.GetHeight()-1)/2 - pt.y);
}
wxPoint MyCanvas::LogicalToDevice(const wxPoint& pt) {
wxSize size = m_parent->GetClientSize();
return wxPoint(pt.x + (size.GetWidth()-1)/2, (size.GetHeight()-1)/2 - pt.y);
}
| 36.645078
| 99
| 0.584305
|
myirci
|
29088db725c733564a3ab404aaadbd702b53dc0b
| 465
|
hpp
|
C++
|
SDKUsage6/VBMapViewer-SKT/VbNavKit-iOS/Classes/vbCamera/vbRotateCameraControl.hpp
|
longxingtianxiaShuai/specialView
|
42fbdb1ee94fc0bd0c903e3c72c23808ec608139
|
[
"MIT"
] | 1
|
2020-11-21T03:54:34.000Z
|
2020-11-21T03:54:34.000Z
|
SDKUsage6/VBMapViewer-SKT/VbNavKit-iOS/Classes/vbCamera/vbRotateCameraControl.hpp
|
longxingtianxiaShuai/specialView
|
42fbdb1ee94fc0bd0c903e3c72c23808ec608139
|
[
"MIT"
] | null | null | null |
SDKUsage6/VBMapViewer-SKT/VbNavKit-iOS/Classes/vbCamera/vbRotateCameraControl.hpp
|
longxingtianxiaShuai/specialView
|
42fbdb1ee94fc0bd0c903e3c72c23808ec608139
|
[
"MIT"
] | 3
|
2017-12-14T00:52:03.000Z
|
2019-08-08T22:25:04.000Z
|
//
// vbRotateCameraControl.h
// VbNavKit-iOS
//
// Created by Dev4_Air on 13. 2. 7..
// Copyright (c) 2013년 dev4. All rights reserved.
//
#ifndef VbNavKit_iOS_vbRotateCameraControl_h
#define VbNavKit_iOS_vbRotateCameraControl_h
#include "vbCameraControl.hpp"
class vbRotateCameraControl : public vbCameraControl
{
public:
vbRotateCameraControl();
~vbRotateCameraControl();
public:
virtual Quaternion GetOrientation() = 0;
};
#endif
| 17.222222
| 52
| 0.729032
|
longxingtianxiaShuai
|
2908a8e881420630cf31cd4c76ccbd2eae643da3
| 1,768
|
cpp
|
C++
|
BasicGameFramework/Util/CSound.cpp
|
dlwlxns4/WitchHouse
|
7b2fd8acead69baa9b0850e0ddcb7520b32ef47e
|
[
"BSD-3-Clause"
] | null | null | null |
BasicGameFramework/Util/CSound.cpp
|
dlwlxns4/WitchHouse
|
7b2fd8acead69baa9b0850e0ddcb7520b32ef47e
|
[
"BSD-3-Clause"
] | null | null | null |
BasicGameFramework/Util/CSound.cpp
|
dlwlxns4/WitchHouse
|
7b2fd8acead69baa9b0850e0ddcb7520b32ef47e
|
[
"BSD-3-Clause"
] | null | null | null |
#include "CSound.h"
FMOD_SYSTEM* CSound::g_sound_system;
CSound::CSound(const char* path, bool loop) {
if (loop) {
FMOD_System_CreateSound(g_sound_system, path, FMOD_LOOP_NORMAL, 0, &m_sound);
}
else {
FMOD_System_CreateSound(g_sound_system, path, FMOD_DEFAULT, 0, &m_sound);
}
m_channel = nullptr;
m_volume = SOUND_DEFAULT;
}
CSound::~CSound() {
FMOD_Sound_Release(m_sound);
}
void CSound::Init() {
FMOD_System_Create(&g_sound_system);
FMOD_System_Init(g_sound_system, 32, FMOD_INIT_NORMAL, nullptr);
}
void CSound::Release() {
FMOD_System_Close(g_sound_system);
FMOD_System_Release(g_sound_system);
}
bool CSound::play() {
if (isPlay == false)
{
isPlay = true;
FMOD_System_PlaySound(g_sound_system, m_sound, nullptr, false, &m_channel);
return true;
}
return false;
}
void CSound::InfPlay()
{
FMOD_System_PlaySound(g_sound_system, m_sound, nullptr, false, &m_channel);
}
void CSound::pause() {
FMOD_Channel_SetPaused(m_channel, true);
}
void CSound::resume() {
isPlay = true;
FMOD_Channel_SetPaused(m_channel, false);
}
void CSound::stop() {
isPlay = false;
FMOD_Channel_Stop(m_channel);
}
void CSound::volumeUp() {
if (m_volume < SOUND_MAX) {
m_volume += SOUND_WEIGHT;
}
FMOD_Channel_SetVolume(m_channel, m_volume);
}
void CSound::volumeDown() {
if (m_volume > SOUND_MIN) {
m_volume -= SOUND_WEIGHT;
}
FMOD_Channel_SetVolume(m_channel, m_volume);
}
void CSound::volumeFadeUp()
{
isVolumeUp = true;
}
void CSound::SetVolume(float volume)
{
this->m_volume = volume;
}
void CSound::Update() {
FMOD_Channel_IsPlaying(m_channel, &m_bool);
if (m_bool) {
FMOD_System_Update(g_sound_system);
}
if (isVolumeUp)
{
volumeUp();
if (m_volume >= 1.0f)
{
isVolumeUp = false;
}
}
}
| 14.857143
| 79
| 0.70871
|
dlwlxns4
|
290a0054e7be1cf8c2404752c65901ae15016fb0
| 66,168
|
cc
|
C++
|
Validation/MtdValidation/plugins/Primary4DVertexValidation.cc
|
wonpoint4/cmssw
|
4095d8106ef881c8b3be12b696bc364ae911d01f
|
[
"Apache-2.0"
] | 2
|
2020-10-26T18:40:32.000Z
|
2021-04-10T16:33:25.000Z
|
Validation/MtdValidation/plugins/Primary4DVertexValidation.cc
|
gartung/cmssw
|
3072dde3ce94dcd1791d778988198a44cde02162
|
[
"Apache-2.0"
] | 30
|
2015-11-04T11:42:27.000Z
|
2021-12-01T07:56:34.000Z
|
Validation/MtdValidation/plugins/Primary4DVertexValidation.cc
|
gartung/cmssw
|
3072dde3ce94dcd1791d778988198a44cde02162
|
[
"Apache-2.0"
] | 8
|
2016-03-25T07:17:43.000Z
|
2021-07-08T17:11:21.000Z
|
#include <numeric>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include "FWCore/Framework/interface/Frameworkfwd.h"
#include "FWCore/Framework/interface/EDAnalyzer.h"
#include "FWCore/Framework/interface/ESHandle.h"
#include "DataFormats/Common/interface/ValidHandle.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/interface/EventSetup.h"
#include "FWCore/Framework/interface/MakerMacros.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "DataFormats/Math/interface/LorentzVector.h"
#include "DataFormats/Math/interface/Point3D.h"
// reco track and vertex
#include "DataFormats/TrackReco/interface/Track.h"
#include "DataFormats/TrackReco/interface/TrackFwd.h"
#include "DataFormats/VertexReco/interface/Vertex.h"
#include "DataFormats/VertexReco/interface/VertexFwd.h"
#include "RecoVertex/VertexPrimitives/interface/TransientVertex.h"
// TrackingParticle
#include "SimDataFormats/TrackingAnalysis/interface/TrackingParticle.h"
#include "SimDataFormats/Associations/interface/TrackToTrackingParticleAssociator.h"
#include "SimDataFormats/TrackingAnalysis/interface/TrackingParticleFwd.h"
#include "SimDataFormats/TrackingAnalysis/interface/TrackingVertexContainer.h"
// pile-up
#include "SimDataFormats/PileupSummaryInfo/interface/PileupSummaryInfo.h"
// associator
#include "SimTracker/VertexAssociation/interface/calculateVertexSharedTracks.h"
// vertexing
#include "RecoVertex/PrimaryVertexProducer/interface/TrackFilterForPVFinding.h"
// simulated vertex
#include "SimDataFormats/Associations/interface/VertexToTrackingVertexAssociator.h"
// DQM
#include "DQMServices/Core/interface/DQMEDAnalyzer.h"
#include "DQMServices/Core/interface/DQMStore.h"
#include "DataFormats/Math/interface/deltaR.h"
//class declaration
class Primary4DVertexValidation : public DQMEDAnalyzer {
typedef math::XYZTLorentzVector LorentzVector;
// auxiliary class holding simulated vertices
struct simPrimaryVertex {
simPrimaryVertex(double x1, double y1, double z1, double t1)
: x(x1),
y(y1),
z(z1),
t(t1),
ptsq(0),
closest_vertex_distance_z(-1.),
nGenTrk(0),
num_matched_reco_tracks(0),
average_match_quality(0.0) {
ptot.setPx(0);
ptot.setPy(0);
ptot.setPz(0);
ptot.setE(0);
p4 = LorentzVector(0, 0, 0, 0);
r = sqrt(x * x + y * y);
};
double x, y, z, r, t;
HepMC::FourVector ptot;
LorentzVector p4;
double ptsq;
double closest_vertex_distance_z;
int nGenTrk;
int num_matched_reco_tracks;
float average_match_quality;
EncodedEventId eventId;
TrackingVertexRef sim_vertex;
int OriginalIndex = -1;
unsigned int nwosmatch = 0; // number of recvertices dominated by this simevt (by wos)
unsigned int nwntmatch = 0; // number of recvertices dominated by this simevt (by nt)
std::vector<unsigned int> wos_dominated_recv; // list of dominated recv (by wos, size==nwosmatch)
std::map<unsigned int, double> wnt; // weighted number of tracks in recvtx (by index)
std::map<unsigned int, double> wos; // sum of wos in recvtx (by index) // oops -> this was int before 04-22
double sumwos = 0; // sum of wos in any recvtx
double sumwnt = 0; // sum of weighted tracks
unsigned int rec = NOT_MATCHED; // best match (NO_MATCH if not matched)
unsigned int matchQuality = 0; // quality flag
void addTrack(unsigned int irecv, double twos, double twt) {
sumwnt += twt;
if (wnt.find(irecv) == wnt.end()) {
wnt[irecv] = twt;
} else {
wnt[irecv] += twt;
}
sumwos += twos;
if (wos.find(irecv) == wos.end()) {
wos[irecv] = twos;
} else {
wos[irecv] += twos;
}
}
};
// auxiliary class holding reconstructed vertices
struct recoPrimaryVertex {
recoPrimaryVertex(double x1, double y1, double z1)
: x(x1),
y(y1),
z(z1),
pt(0),
ptsq(0),
closest_vertex_distance_z(-1.),
nRecoTrk(0),
num_matched_sim_tracks(0),
recVtx(nullptr) {
r = sqrt(x * x + y * y);
};
double x, y, z, r;
double pt;
double ptsq;
double closest_vertex_distance_z;
int nRecoTrk;
int num_matched_sim_tracks;
const reco::Vertex* recVtx;
reco::VertexBaseRef recVtxRef;
int OriginalIndex = -1;
std::map<unsigned int, double> wos; // simevent -> wos
std::map<unsigned int, double> wnt; // simevent -> weighted number of truth matched tracks
unsigned int wosmatch; // index of the simevent providing the largest contribution to wos
unsigned int wntmatch; // index of the simevent providing the highest number of tracks
double sumwos = 0; // total sum of wos of all truth matched tracks
double sumwnt = 0; // total weighted number of truth matchted tracks
double maxwos = 0; // largest wos sum from one sim event (wosmatch)
double maxwnt = 0; // largest weighted number of tracks from one sim event (ntmatch)
int maxwosnt = 0; // number of tracks from the simevt with highest wos
unsigned int sim = NOT_MATCHED; // best match (NO_MATCH if not matched)
unsigned int matchQuality = 0; // quality flag
bool is_real() { return (matchQuality > 0) && (matchQuality < 99); }
bool is_fake() { return (matchQuality <= 0) || (matchQuality >= 99); }
bool is_signal() { return (sim == 0); }
int split_from() {
if (is_real())
return -1;
if ((maxwos > 0) && (maxwos > 0.3 * sumwos))
return wosmatch;
return -1;
}
bool other_fake() { return (is_fake() & (split_from() < 0)); }
void addTrack(unsigned int iev, double twos, double wt) {
sumwnt += wt;
if (wnt.find(iev) == wnt.end()) {
wnt[iev] = wt;
} else {
wnt[iev] += wt;
}
sumwos += twos;
if (wos.find(iev) == wos.end()) {
wos[iev] = twos;
} else {
wos[iev] += twos;
}
}
};
public:
explicit Primary4DVertexValidation(const edm::ParameterSet&);
~Primary4DVertexValidation() override;
static void fillDescriptions(edm::ConfigurationDescriptions& descriptions);
void analyze(const edm::Event&, const edm::EventSetup&) override;
void bookHistograms(DQMStore::IBooker& i, edm::Run const&, edm::EventSetup const&) override;
private:
void matchReco2Sim(std::vector<recoPrimaryVertex>&,
std::vector<simPrimaryVertex>&,
const edm::ValueMap<float>&,
const edm::ValueMap<float>&,
const edm::Handle<reco::BeamSpot>&);
bool matchRecoTrack2SimSignal(const reco::TrackBaseRef&);
const edm::Ref<std::vector<TrackingParticle>>* getMatchedTP(const reco::TrackBaseRef&, const TrackingVertexRef&);
double timeFromTrueMass(double, double, double, double);
bool select(const reco::Vertex&, int level = 0);
std::vector<Primary4DVertexValidation::simPrimaryVertex> getSimPVs(const edm::Handle<TrackingVertexCollection>&);
std::vector<Primary4DVertexValidation::recoPrimaryVertex> getRecoPVs(const edm::Handle<edm::View<reco::Vertex>>&);
const bool mvaTPSel(const TrackingParticle&);
const bool mvaRecSel(const reco::TrackBase&, const reco::Vertex&, const double&, const double&);
// ----------member data ---------------------------
const std::string folder_;
static constexpr unsigned int NOT_MATCHED = 66666;
static constexpr double simUnit_ = 1e9; //sim time in s while reco time in ns
static constexpr double c_ = 2.99792458e1; //c in cm/ns
static constexpr double mvaL_ = 0.5; //MVA cuts for MVA categories
static constexpr double mvaH_ = 0.8;
static constexpr double selNdof_ = 4.;
static constexpr double maxRank_ = 8.;
static constexpr double maxTry_ = 10.;
static constexpr double zWosMatchMax_ = 1.;
static constexpr double etacutGEN_ = 4.; // |eta| < 4;
static constexpr double etacutREC_ = 3.; // |eta| < 3;
static constexpr double pTcut_ = 0.7; // PT > 0.7 GeV
static constexpr double deltaZcut_ = 0.1; // dz separation 1 mm
const double trackweightTh_;
const double mvaTh_;
const std::vector<double> lineDensityPar_;
const reco::RecoToSimCollection* r2s_;
const reco::SimToRecoCollection* s2r_;
edm::EDGetTokenT<reco::TrackCollection> RecTrackToken_;
edm::EDGetTokenT<std::vector<PileupSummaryInfo>> vecPileupSummaryInfoToken_;
edm::EDGetTokenT<TrackingParticleCollection> trackingParticleCollectionToken_;
edm::EDGetTokenT<TrackingVertexCollection> trackingVertexCollectionToken_;
edm::EDGetTokenT<reco::SimToRecoCollection> simToRecoAssociationToken_;
edm::EDGetTokenT<reco::RecoToSimCollection> recoToSimAssociationToken_;
edm::EDGetTokenT<reco::BeamSpot> RecBeamSpotToken_;
edm::EDGetTokenT<edm::View<reco::Vertex>> Rec4DVerToken_;
edm::EDGetTokenT<edm::ValueMap<int>> trackAssocToken_;
edm::EDGetTokenT<edm::ValueMap<float>> pathLengthToken_;
edm::EDGetTokenT<edm::ValueMap<float>> momentumToken_;
edm::EDGetTokenT<edm::ValueMap<float>> timeToken_;
edm::EDGetTokenT<edm::ValueMap<float>> t0SafePidToken_;
edm::EDGetTokenT<edm::ValueMap<float>> sigmat0SafePidToken_;
edm::EDGetTokenT<edm::ValueMap<float>> trackMVAQualToken_;
bool use_only_charged_tracks_;
bool debug_;
bool optionalPlots_;
//histogram declaration
MonitorElement* meMVATrackEffPtTot_;
MonitorElement* meMVATrackMatchedEffPtTot_;
MonitorElement* meMVATrackMatchedEffPtMtd_;
MonitorElement* meMVATrackEffEtaTot_;
MonitorElement* meMVATrackMatchedEffEtaTot_;
MonitorElement* meMVATrackMatchedEffEtaMtd_;
MonitorElement* meMVATrackResTot_;
MonitorElement* meMVATrackPullTot_;
MonitorElement* meTrackResTot_;
MonitorElement* meTrackPullTot_;
MonitorElement* meTrackRes_[3];
MonitorElement* meTrackPull_[3];
MonitorElement* meTrackResMass_[3];
MonitorElement* meTrackResMassTrue_[3];
MonitorElement* meMVATrackZposResTot_;
MonitorElement* meTrackZposResTot_;
MonitorElement* meTrackZposRes_[3];
MonitorElement* meTrack3DposRes_[3];
MonitorElement* meTimeRes_;
MonitorElement* meTimePull_;
MonitorElement* meTimeSignalRes_;
MonitorElement* meTimeSignalPull_;
MonitorElement* mePUvsRealV_;
MonitorElement* mePUvsOtherFakeV_;
MonitorElement* mePUvsSplitV_;
MonitorElement* meMatchQual_;
MonitorElement* meDeltaZrealreal_;
MonitorElement* meDeltaZfakefake_;
MonitorElement* meDeltaZfakereal_;
MonitorElement* meDeltaTrealreal_;
MonitorElement* meDeltaTfakefake_;
MonitorElement* meDeltaTfakereal_;
MonitorElement* meRecoPosInSimCollection_;
MonitorElement* meRecoPosInRecoOrigCollection_;
MonitorElement* meSimPosInSimOrigCollection_;
MonitorElement* meRecoPVPosSignal_;
MonitorElement* meRecoPVPosSignalNotHighestPt_;
MonitorElement* meRecoVtxVsLineDensity_;
MonitorElement* meRecVerNumber_;
MonitorElement* meRecPVZ_;
MonitorElement* meRecPVT_;
MonitorElement* meSimPVZ_;
//some tests
MonitorElement* meTrackResLowPTot_;
MonitorElement* meTrackResHighPTot_;
MonitorElement* meTrackPullLowPTot_;
MonitorElement* meTrackPullHighPTot_;
MonitorElement* meTrackResLowP_[3];
MonitorElement* meTrackResHighP_[3];
MonitorElement* meTrackPullLowP_[3];
MonitorElement* meTrackPullHighP_[3];
MonitorElement* meTrackResMassProtons_[3];
MonitorElement* meTrackResMassTrueProtons_[3];
MonitorElement* meTrackResMassPions_[3];
MonitorElement* meTrackResMassTruePions_[3];
};
// constructors and destructor
Primary4DVertexValidation::Primary4DVertexValidation(const edm::ParameterSet& iConfig)
: folder_(iConfig.getParameter<std::string>("folder")),
trackweightTh_(iConfig.getParameter<double>("trackweightTh")),
mvaTh_(iConfig.getParameter<double>("mvaTh")),
lineDensityPar_(iConfig.getParameter<std::vector<double>>("lineDensityPar")),
use_only_charged_tracks_(iConfig.getParameter<bool>("useOnlyChargedTracks")),
debug_(iConfig.getUntrackedParameter<bool>("debug")),
optionalPlots_(iConfig.getUntrackedParameter<bool>("optionalPlots")) {
vecPileupSummaryInfoToken_ = consumes<std::vector<PileupSummaryInfo>>(edm::InputTag(std::string("addPileupInfo")));
trackingParticleCollectionToken_ =
consumes<TrackingParticleCollection>(iConfig.getParameter<edm::InputTag>("SimTag"));
trackingVertexCollectionToken_ = consumes<TrackingVertexCollection>(iConfig.getParameter<edm::InputTag>("SimTag"));
simToRecoAssociationToken_ =
consumes<reco::SimToRecoCollection>(iConfig.getParameter<edm::InputTag>("TPtoRecoTrackAssoc"));
recoToSimAssociationToken_ =
consumes<reco::RecoToSimCollection>(iConfig.getParameter<edm::InputTag>("TPtoRecoTrackAssoc"));
RecTrackToken_ = consumes<reco::TrackCollection>(iConfig.getParameter<edm::InputTag>("mtdTracks"));
RecBeamSpotToken_ = consumes<reco::BeamSpot>(iConfig.getParameter<edm::InputTag>("offlineBS"));
Rec4DVerToken_ = consumes<edm::View<reco::Vertex>>(iConfig.getParameter<edm::InputTag>("offline4DPV"));
trackAssocToken_ = consumes<edm::ValueMap<int>>(iConfig.getParameter<edm::InputTag>("trackAssocSrc"));
pathLengthToken_ = consumes<edm::ValueMap<float>>(iConfig.getParameter<edm::InputTag>("pathLengthSrc"));
momentumToken_ = consumes<edm::ValueMap<float>>(iConfig.getParameter<edm::InputTag>("momentumSrc"));
timeToken_ = consumes<edm::ValueMap<float>>(iConfig.getParameter<edm::InputTag>("timeSrc"));
t0SafePidToken_ = consumes<edm::ValueMap<float>>(iConfig.getParameter<edm::InputTag>("t0SafePID"));
sigmat0SafePidToken_ = consumes<edm::ValueMap<float>>(iConfig.getParameter<edm::InputTag>("sigmat0SafePID"));
trackMVAQualToken_ = consumes<edm::ValueMap<float>>(iConfig.getParameter<edm::InputTag>("trackMVAQual"));
}
Primary4DVertexValidation::~Primary4DVertexValidation() {}
//
// member functions
//
void Primary4DVertexValidation::bookHistograms(DQMStore::IBooker& ibook,
edm::Run const& iRun,
edm::EventSetup const& iSetup) {
ibook.setCurrentFolder(folder_);
// --- histograms booking
meMVATrackEffPtTot_ = ibook.book1D("MVAEffPtTot", "Pt of tracks associated to LV; track pt [GeV] ", 110, 0., 11.);
meMVATrackEffEtaTot_ = ibook.book1D("MVAEffEtaTot", "Pt of tracks associated to LV; track eta ", 66, 0., 3.3);
meMVATrackMatchedEffPtTot_ =
ibook.book1D("MVAMatchedEffPtTot", "Pt of tracks associated to LV matched to TP; track pt [GeV] ", 110, 0., 11.);
meMVATrackMatchedEffPtMtd_ = ibook.book1D(
"MVAMatchedEffPtMtd", "Pt of tracks associated to LV matched to TP with time; track pt [GeV] ", 110, 0., 11.);
meMVATrackMatchedEffEtaTot_ =
ibook.book1D("MVAMatchedEffEtaTot", "Pt of tracks associated to LV matched to TP; track eta ", 66, 0., 3.3);
meMVATrackMatchedEffEtaMtd_ = ibook.book1D(
"MVAMatchedEffEtaMtd", "Pt of tracks associated to LV matched to TP with time; track eta ", 66, 0., 3.3);
meMVATrackResTot_ = ibook.book1D(
"MVATrackRes", "t_{rec} - t_{sim} for tracks from LV MVA sel.; t_{rec} - t_{sim} [ns] ", 120, -0.15, 0.15);
meTrackResTot_ = ibook.book1D("TrackRes", "t_{rec} - t_{sim} for tracks; t_{rec} - t_{sim} [ns] ", 120, -0.15, 0.15);
meTrackRes_[0] = ibook.book1D(
"TrackRes-LowMVA", "t_{rec} - t_{sim} for tracks with MVA < 0.5; t_{rec} - t_{sim} [ns] ", 100, -1., 1.);
meTrackRes_[1] = ibook.book1D(
"TrackRes-MediumMVA", "t_{rec} - t_{sim} for tracks with 0.5 < MVA < 0.8; t_{rec} - t_{sim} [ns] ", 100, -1., 1.);
meTrackRes_[2] = ibook.book1D(
"TrackRes-HighMVA", "t_{rec} - t_{sim} for tracks with MVA > 0.8; t_{rec} - t_{sim} [ns] ", 100, -1., 1.);
if (optionalPlots_) {
meTrackResMass_[0] = ibook.book1D(
"TrackResMass-LowMVA", "t_{rec} - t_{est} for tracks with MVA < 0.5; t_{rec} - t_{est} [ns] ", 100, -1., 1.);
meTrackResMass_[1] = ibook.book1D("TrackResMass-MediumMVA",
"t_{rec} - t_{est} for tracks with 0.5 < MVA < 0.8; t_{rec} - t_{est} [ns] ",
100,
-1.,
1.);
meTrackResMass_[2] = ibook.book1D(
"TrackResMass-HighMVA", "t_{rec} - t_{est} for tracks with MVA > 0.8; t_{rec} - t_{est} [ns] ", 100, -1., 1.);
meTrackResMassTrue_[0] = ibook.book1D(
"TrackResMassTrue-LowMVA", "t_{est} - t_{sim} for tracks with MVA < 0.5; t_{est} - t_{sim} [ns] ", 100, -1., 1.);
meTrackResMassTrue_[1] = ibook.book1D("TrackResMassTrue-MediumMVA",
"t_{est} - t_{sim} for tracks with 0.5 < MVA < 0.8; t_{est} - t_{sim} [ns] ",
100,
-1.,
1.);
meTrackResMassTrue_[2] = ibook.book1D("TrackResMassTrue-HighMVA",
"t_{est} - t_{sim} for tracks with MVA > 0.8; t_{est} - t_{sim} [ns] ",
100,
-1.,
1.);
}
meMVATrackPullTot_ =
ibook.book1D("MVATrackPull", "Pull for tracks from LV MAV sel.; (t_{rec}-t_{sim})/#sigma_{t}", 50, -5., 5.);
meTrackPullTot_ = ibook.book1D("TrackPull", "Pull for tracks; (t_{rec}-t_{sim})/#sigma_{t}", 100, -10., 10.);
meTrackPull_[0] =
ibook.book1D("TrackPull-LowMVA", "Pull for tracks with MVA < 0.5; (t_{rec}-t_{sim})/#sigma_{t}", 100, -10., 10.);
meTrackPull_[1] = ibook.book1D(
"TrackPull-MediumMVA", "Pull for tracks with 0.5 < MVA < 0.8; (t_{rec}-t_{sim})/#sigma_{t}", 100, -10., 10.);
meTrackPull_[2] =
ibook.book1D("TrackPull-HighMVA", "Pull for tracks with MVA > 0.8; (t_{rec}-t_{sim})/#sigma_{t}", 100, -10., 10.);
meMVATrackZposResTot_ = ibook.book1D(
"MVATrackZposResTot", "Z_{PCA} - Z_{sim} for tracks from LV MVA sel.;Z_{PCA} - Z_{sim} [cm] ", 50, -0.1, 0.1);
meTrackZposResTot_ =
ibook.book1D("TrackZposResTot", "Z_{PCA} - Z_{sim} for tracks;Z_{PCA} - Z_{sim} [cm] ", 50, -0.5, 0.5);
meTrackZposRes_[0] = ibook.book1D(
"TrackZposRes-LowMVA", "Z_{PCA} - Z_{sim} for tracks with MVA < 0.5;Z_{PCA} - Z_{sim} [cm] ", 50, -0.5, 0.5);
meTrackZposRes_[1] = ibook.book1D("TrackZposRes-MediumMVA",
"Z_{PCA} - Z_{sim} for tracks with 0.5 < MVA < 0.8 ;Z_{PCA} - Z_{sim} [cm] ",
50,
-0.5,
0.5);
meTrackZposRes_[2] = ibook.book1D(
"TrackZposRes-HighMVA", "Z_{PCA} - Z_{sim} for tracks with MVA > 0.8 ;Z_{PCA} - Z_{sim} [cm] ", 50, -0.5, 0.5);
meTrack3DposRes_[0] =
ibook.book1D("Track3DposRes-LowMVA",
"3dPos_{PCA} - 3dPos_{sim} for tracks with MVA < 0.5 ;3dPos_{PCA} - 3dPos_{sim} [cm] ",
50,
-0.5,
0.5);
meTrack3DposRes_[1] =
ibook.book1D("Track3DposRes-MediumMVA",
"3dPos_{PCA} - 3dPos_{sim} for tracks with 0.5 < MVA < 0.8 ;3dPos_{PCA} - 3dPos_{sim} [cm] ",
50,
-0.5,
0.5);
meTrack3DposRes_[2] =
ibook.book1D("Track3DposRes-HighMVA",
"3dPos_{PCA} - 3dPos_{sim} for tracks with MVA > 0.8;3dPos_{PCA} - 3dPos_{sim} [cm] ",
50,
-0.5,
0.5);
meTimeRes_ = ibook.book1D("TimeRes", "t_{rec} - t_{sim} ;t_{rec} - t_{sim} [ns] ", 40, -0.2, 0.2);
meTimePull_ = ibook.book1D("TimePull", "Pull; t_{rec} - t_{sim}/#sigma_{t rec}", 100, -10., 10.);
meTimeSignalRes_ =
ibook.book1D("TimeSignalRes", "t_{rec} - t_{sim} for signal ;t_{rec} - t_{sim} [ns] ", 40, -0.2, 0.2);
meTimeSignalPull_ =
ibook.book1D("TimeSignalPull", "Pull for signal; t_{rec} - t_{sim}/#sigma_{t rec}", 100, -10., 10.);
mePUvsRealV_ =
ibook.bookProfile("PUvsReal", "#PU vertices vs #real matched vertices;#PU;#real ", 100, 0, 300, 100, 0, 200);
mePUvsOtherFakeV_ = ibook.bookProfile(
"PUvsOtherFake", "#PU vertices vs #other fake matched vertices;#PU;#other fake ", 100, 0, 300, 100, 0, 20);
mePUvsSplitV_ =
ibook.bookProfile("PUvsSplit", "#PU vertices vs #split matched vertices;#PU;#split ", 100, 0, 300, 100, 0, 20);
meMatchQual_ = ibook.book1D("MatchQuality", "RECO-SIM vertex match quality; ", 8, 0, 8.);
meDeltaZrealreal_ = ibook.book1D("DeltaZrealreal", "#Delta Z real-real; |#Delta Z (r-r)| [cm]", 100, 0, 0.5);
meDeltaZfakefake_ = ibook.book1D("DeltaZfakefake", "#Delta Z fake-fake; |#Delta Z (f-f)| [cm]", 100, 0, 0.5);
meDeltaZfakereal_ = ibook.book1D("DeltaZfakereal", "#Delta Z fake-real; |#Delta Z (f-r)| [cm]", 100, 0, 0.5);
meDeltaTrealreal_ = ibook.book1D("DeltaTrealreal", "#Delta T real-real; |#Delta T (r-r)| [sigma]", 60, 0., 30.);
meDeltaTfakefake_ = ibook.book1D("DeltaTfakefake", "#Delta T fake-fake; |#Delta T (f-f)| [sigma]", 60, 0., 30.);
meDeltaTfakereal_ = ibook.book1D("DeltaTfakereal", "#Delta T fake-real; |#Delta T (f-r)| [sigma]", 60, 0., 30.);
if (optionalPlots_) {
meRecoPosInSimCollection_ = ibook.book1D(
"RecoPosInSimCollection", "Sim signal vertex index associated to Reco signal vertex; Sim PV index", 200, 0, 200);
meRecoPosInRecoOrigCollection_ =
ibook.book1D("RecoPosInRecoOrigCollection", "Reco signal index in OrigCollection; Reco index", 200, 0, 200);
meSimPosInSimOrigCollection_ =
ibook.book1D("SimPosInSimOrigCollection", "Sim signal index in OrigCollection; Sim index", 200, 0, 200);
}
meRecoPVPosSignal_ =
ibook.book1D("RecoPVPosSignal", "Position in reco collection of PV associated to sim signal", 200, 0, 200);
meRecoPVPosSignalNotHighestPt_ =
ibook.book1D("RecoPVPosSignalNotHighestPt",
"Position in reco collection of PV associated to sim signal not highest Pt",
200,
0,
200);
meRecoVtxVsLineDensity_ =
ibook.book1D("RecoVtxVsLineDensity", "#Reco vertices/mm/event; line density [#vtx/mm/event]", 160, 0., 4.);
meRecVerNumber_ = ibook.book1D("RecVerNumber", "RECO Vertex Number: Number of vertices", 50, 0, 250);
meRecPVZ_ = ibook.book1D("recPVZ", "Weighted #Rec vertices/mm", 400, -20., 20.);
meRecPVT_ = ibook.book1D("recPVT", "#Rec vertices/10 ps", 200, -1., 1.);
meSimPVZ_ = ibook.book1D("simPVZ", "Weighted #Sim vertices/mm", 400, -20., 20.);
//some tests
meTrackResLowPTot_ = ibook.book1D(
"TrackResLowP", "t_{rec} - t_{sim} for tracks with p < 2 GeV; t_{rec} - t_{sim} [ns] ", 70, -0.15, 0.15);
meTrackResLowP_[0] =
ibook.book1D("TrackResLowP-LowMVA",
"t_{rec} - t_{sim} for tracks with MVA < 0.5 and p < 2 GeV; t_{rec} - t_{sim} [ns] ",
100,
-1.,
1.);
meTrackResLowP_[1] =
ibook.book1D("TrackResLowP-MediumMVA",
"t_{rec} - t_{sim} for tracks with 0.5 < MVA < 0.8 and p < 2 GeV; t_{rec} - t_{sim} [ns] ",
100,
-1.,
1.);
meTrackResLowP_[2] =
ibook.book1D("TrackResLowP-HighMVA",
"t_{rec} - t_{sim} for tracks with MVA > 0.8 and p < 2 GeV; t_{rec} - t_{sim} [ns] ",
100,
-1.,
1.);
meTrackResHighPTot_ = ibook.book1D(
"TrackResHighP", "t_{rec} - t_{sim} for tracks with p > 2 GeV; t_{rec} - t_{sim} [ns] ", 70, -0.15, 0.15);
meTrackResHighP_[0] =
ibook.book1D("TrackResHighP-LowMVA",
"t_{rec} - t_{sim} for tracks with MVA < 0.5 and p > 2 GeV; t_{rec} - t_{sim} [ns] ",
100,
-1.,
1.);
meTrackResHighP_[1] =
ibook.book1D("TrackResHighP-MediumMVA",
"t_{rec} - t_{sim} for tracks with 0.5 < MVA < 0.8 and p > 2 GeV; t_{rec} - t_{sim} [ns] ",
100,
-1.,
1.);
meTrackResHighP_[2] =
ibook.book1D("TrackResHighP-HighMVA",
"t_{rec} - t_{sim} for tracks with MVA > 0.8 and p > 2 GeV; t_{rec} - t_{sim} [ns] ",
100,
-1.,
1.);
meTrackPullLowPTot_ =
ibook.book1D("TrackPullLowP", "Pull for tracks with p < 2 GeV; (t_{rec}-t_{sim})/#sigma_{t}", 100, -10., 10.);
meTrackPullLowP_[0] = ibook.book1D("TrackPullLowP-LowMVA",
"Pull for tracks with MVA < 0.5 and p < 2 GeV; (t_{rec}-t_{sim})/#sigma_{t}",
100,
-10.,
10.);
meTrackPullLowP_[1] = ibook.book1D("TrackPullLowP-MediumMVA",
"Pull for tracks with 0.5 < MVA < 0.8 and p < 2 GeV; (t_{rec}-t_{sim})/#sigma_{t}",
100,
-10.,
10.);
meTrackPullLowP_[2] = ibook.book1D("TrackPullLowP-HighMVA",
"Pull for tracks with MVA > 0.8 and p < 2 GeV; (t_{rec}-t_{sim})/#sigma_{t}",
100,
-10.,
10.);
meTrackPullHighPTot_ =
ibook.book1D("TrackPullHighP", "Pull for tracks with p > 2 GeV; (t_{rec}-t_{sim})/#sigma_{t}", 100, -10., 10.);
meTrackPullHighP_[0] = ibook.book1D("TrackPullHighP-LowMVA",
"Pull for tracks with MVA < 0.5 and p > 2 GeV; (t_{rec}-t_{sim})/#sigma_{t}",
100,
-10.,
10.);
meTrackPullHighP_[1] =
ibook.book1D("TrackPullHighP-MediumMVA",
"Pull for tracks with 0.5 < MVA < 0.8 and p > 2 GeV; (t_{rec}-t_{sim})/#sigma_{t}",
100,
-10.,
10.);
meTrackPullHighP_[2] = ibook.book1D("TrackPullHighP-HighMVA",
"Pull for tracks with MVA > 0.8 and p > 2 GeV; (t_{rec}-t_{sim})/#sigma_{t}",
100,
-10.,
10.);
if (optionalPlots_) {
meTrackResMassProtons_[0] =
ibook.book1D("TrackResMass-Protons-LowMVA",
"t_{rec} - t_{est} for proton tracks with MVA < 0.5; t_{rec} - t_{est} [ns] ",
100,
-1.,
1.);
meTrackResMassProtons_[1] =
ibook.book1D("TrackResMass-Protons-MediumMVA",
"t_{rec} - t_{est} for proton tracks with 0.5 < MVA < 0.8; t_{rec} - t_{est} [ns] ",
100,
-1.,
1.);
meTrackResMassProtons_[2] =
ibook.book1D("TrackResMass-Protons-HighMVA",
"t_{rec} - t_{est} for proton tracks with MVA > 0.8; t_{rec} - t_{est} [ns] ",
100,
-1.,
1.);
meTrackResMassTrueProtons_[0] =
ibook.book1D("TrackResMassTrue-Protons-LowMVA",
"t_{est} - t_{sim} for proton tracks with MVA < 0.5; t_{est} - t_{sim} [ns] ",
100,
-1.,
1.);
meTrackResMassTrueProtons_[1] =
ibook.book1D("TrackResMassTrue-Protons-MediumMVA",
"t_{est} - t_{sim} for proton tracks with 0.5 < MVA < 0.8; t_{est} - t_{sim} [ns] ",
100,
-1.,
1.);
meTrackResMassTrueProtons_[2] =
ibook.book1D("TrackResMassTrue-Protons-HighMVA",
"t_{est} - t_{sim} for proton tracks with MVA > 0.8; t_{est} - t_{sim} [ns] ",
100,
-1.,
1.);
meTrackResMassPions_[0] = ibook.book1D("TrackResMass-Pions-LowMVA",
"t_{rec} - t_{est} for pion tracks with MVA < 0.5; t_{rec} - t_{est} [ns] ",
100,
-1.,
1.);
meTrackResMassPions_[1] =
ibook.book1D("TrackResMass-Pions-MediumMVA",
"t_{rec} - t_{est} for pion tracks with 0.5 < MVA < 0.8; t_{rec} - t_{est} [ns] ",
100,
-1.,
1.);
meTrackResMassPions_[2] = ibook.book1D("TrackResMass-Pions-HighMVA",
"t_{rec} - t_{est} for pion tracks with MVA > 0.8; t_{rec} - t_{est} [ns] ",
100,
-1.,
1.);
meTrackResMassTruePions_[0] =
ibook.book1D("TrackResMassTrue-Pions-LowMVA",
"t_{est} - t_{sim} for pion tracks with MVA < 0.5; t_{est} - t_{sim} [ns] ",
100,
-1.,
1.);
meTrackResMassTruePions_[1] =
ibook.book1D("TrackResMassTrue-Pions-MediumMVA",
"t_{est} - t_{sim} for pion tracks with 0.5 < MVA < 0.8; t_{est} - t_{sim} [ns] ",
100,
-1.,
1.);
meTrackResMassTruePions_[2] =
ibook.book1D("TrackResMassTrue-Pions-HighMVA",
"t_{est} - t_{sim} for pion tracks with MVA > 0.8; t_{est} - t_{sim} [ns] ",
100,
-1.,
1.);
}
}
bool Primary4DVertexValidation::matchRecoTrack2SimSignal(const reco::TrackBaseRef& recoTrack) {
auto found = r2s_->find(recoTrack);
// reco track not matched to any TP
if (found == r2s_->end())
return false;
//// reco track matched to some TP from signal vertex
for (const auto& tp : found->val) {
if (tp.first->eventId().bunchCrossing() == 0 && tp.first->eventId().event() == 0)
return true;
}
// reco track not matched to any TP from signal vertex
return false;
}
const edm::Ref<std::vector<TrackingParticle>>* Primary4DVertexValidation::getMatchedTP(
const reco::TrackBaseRef& recoTrack, const TrackingVertexRef& vsim) {
auto found = r2s_->find(recoTrack);
// reco track not matched to any TP
if (found == r2s_->end())
return nullptr;
//matched TP equal to any TP of sim vertex
for (const auto& tp : found->val) {
if (std::find_if(vsim->daughterTracks_begin(), vsim->daughterTracks_end(), [&](const TrackingParticleRef& vtp) {
return tp.first == vtp;
}) != vsim->daughterTracks_end())
return &tp.first;
}
// reco track not matched to any TP from vertex
return nullptr;
}
double Primary4DVertexValidation::timeFromTrueMass(double mass, double pathlength, double momentum, double time) {
if (time > 0 && pathlength > 0 && mass > 0) {
double gammasq = 1. + momentum * momentum / (mass * mass);
double v = c_ * std::sqrt(1. - 1. / gammasq); // cm / ns
double t_est = time - (pathlength / v);
return t_est;
} else {
return -1;
}
}
bool Primary4DVertexValidation::select(const reco::Vertex& v, int level) {
/* level
0 !isFake && ndof>4 (default)
1 !isFake && ndof>4 && prob > 0.01
2 !isFake && ndof>4 && prob > 0.01 && ptmax2 > 0.4
*/
if (v.isFake())
return false;
if ((level == 0) && (v.ndof() > selNdof_))
return true;
/*if ((level == 1) && (v.ndof() > selNdof_) && (vertex_pxy(v) > 0.01))
return true;
if ((level == 2) && (v.ndof() > selNdof_) && (vertex_pxy(v) > 0.01) && (vertex_ptmax2(v) > 0.4))
return true;
if ((level == 3) && (v.ndof() > selNdof_) && (vertex_ptmax2(v) < 0.4))
return true;*/
return false;
}
/* Extract information form TrackingParticles/TrackingVertex and fill
* the helper class simPrimaryVertex with proper generation-level
* information */
std::vector<Primary4DVertexValidation::simPrimaryVertex> Primary4DVertexValidation::getSimPVs(
const edm::Handle<TrackingVertexCollection>& tVC) {
std::vector<Primary4DVertexValidation::simPrimaryVertex> simpv;
int current_event = -1;
int s = -1;
for (TrackingVertexCollection::const_iterator v = tVC->begin(); v != tVC->end(); ++v) {
//We keep only the first vertex from all the events at BX=0.
if (v->eventId().bunchCrossing() != 0)
continue;
if (v->eventId().event() != current_event) {
current_event = v->eventId().event();
} else {
continue;
}
s++;
if (std::abs(v->position().z()) > 1000)
continue; // skip junk vertices
// could be a new vertex, check all primaries found so far to avoid multiple entries
simPrimaryVertex sv(v->position().x(), v->position().y(), v->position().z(), v->position().t());
sv.eventId = v->eventId();
sv.sim_vertex = TrackingVertexRef(tVC, std::distance(tVC->begin(), v));
sv.OriginalIndex = s;
for (TrackingParticleRefVector::iterator iTrack = v->daughterTracks_begin(); iTrack != v->daughterTracks_end();
++iTrack) {
assert((**iTrack).eventId().bunchCrossing() == 0);
}
simPrimaryVertex* vp = nullptr; // will become non-NULL if a vertex is found and then point to it
for (std::vector<simPrimaryVertex>::iterator v0 = simpv.begin(); v0 != simpv.end(); v0++) {
if ((sv.eventId == v0->eventId) && (std::abs(sv.x - v0->x) < 1e-5) && (std::abs(sv.y - v0->y) < 1e-5) &&
(std::abs(sv.z - v0->z) < 1e-5)) {
vp = &(*v0);
break;
}
}
if (!vp) {
// this is a new vertex, add it to the list of sim-vertices
simpv.push_back(sv);
vp = &simpv.back();
}
// Loop over daughter track(s) as Tracking Particles
for (TrackingVertex::tp_iterator iTP = v->daughterTracks_begin(); iTP != v->daughterTracks_end(); ++iTP) {
auto momentum = (*(*iTP)).momentum();
const reco::Track* matched_best_reco_track = nullptr;
double match_quality = -1;
if (use_only_charged_tracks_ && (**iTP).charge() == 0)
continue;
if (s2r_->find(*iTP) != s2r_->end()) {
matched_best_reco_track = (*s2r_)[*iTP][0].first.get();
match_quality = (*s2r_)[*iTP][0].second;
}
vp->ptot.setPx(vp->ptot.x() + momentum.x());
vp->ptot.setPy(vp->ptot.y() + momentum.y());
vp->ptot.setPz(vp->ptot.z() + momentum.z());
vp->ptot.setE(vp->ptot.e() + (**iTP).energy());
vp->ptsq += ((**iTP).pt() * (**iTP).pt());
if (matched_best_reco_track) {
vp->num_matched_reco_tracks++;
vp->average_match_quality += match_quality;
}
} // End of for loop on daughters sim-particles
if (vp->num_matched_reco_tracks)
vp->average_match_quality /= static_cast<float>(vp->num_matched_reco_tracks);
if (debug_) {
edm::LogPrint("Primary4DVertexValidation")
<< "average number of associated tracks: " << vp->num_matched_reco_tracks / static_cast<float>(vp->nGenTrk)
<< " with average quality: " << vp->average_match_quality;
}
} // End of for loop on tracking vertices
// In case of no simulated vertices, break here
if (simpv.empty())
return simpv;
// Now compute the closest distance in z between all simulated vertex
// first initialize
auto prev_z = simpv.back().z;
for (simPrimaryVertex& vsim : simpv) {
vsim.closest_vertex_distance_z = std::abs(vsim.z - prev_z);
prev_z = vsim.z;
}
// then calculate
for (std::vector<simPrimaryVertex>::iterator vsim = simpv.begin(); vsim != simpv.end(); vsim++) {
std::vector<simPrimaryVertex>::iterator vsim2 = vsim;
vsim2++;
for (; vsim2 != simpv.end(); vsim2++) {
double distance = std::abs(vsim->z - vsim2->z);
// need both to be complete
vsim->closest_vertex_distance_z = std::min(vsim->closest_vertex_distance_z, distance);
vsim2->closest_vertex_distance_z = std::min(vsim2->closest_vertex_distance_z, distance);
}
}
return simpv;
}
/* Extract information form recoVertex and fill the helper class
* recoPrimaryVertex with proper reco-level information */
std::vector<Primary4DVertexValidation::recoPrimaryVertex> Primary4DVertexValidation::getRecoPVs(
const edm::Handle<edm::View<reco::Vertex>>& tVC) {
std::vector<Primary4DVertexValidation::recoPrimaryVertex> recopv;
int r = -1;
for (auto v = tVC->begin(); v != tVC->end(); ++v) {
r++;
// Skip junk vertices
if (std::abs(v->z()) > 1000)
continue;
if (v->isFake() || !v->isValid())
continue;
recoPrimaryVertex sv(v->position().x(), v->position().y(), v->position().z());
sv.recVtx = &(*v);
sv.recVtxRef = reco::VertexBaseRef(tVC, std::distance(tVC->begin(), v));
sv.OriginalIndex = r;
// this is a new vertex, add it to the list of reco-vertices
recopv.push_back(sv);
Primary4DVertexValidation::recoPrimaryVertex* vp = &recopv.back();
// Loop over daughter track(s)
for (auto iTrack = v->tracks_begin(); iTrack != v->tracks_end(); ++iTrack) {
auto momentum = (*(*iTrack)).innerMomentum();
if (momentum.mag2() == 0)
momentum = (*(*iTrack)).momentum();
vp->pt += std::sqrt(momentum.perp2());
vp->ptsq += (momentum.perp2());
vp->nRecoTrk++;
auto matched = r2s_->find(*iTrack);
if (matched != r2s_->end()) {
vp->num_matched_sim_tracks++;
}
} // End of for loop on daughters reconstructed tracks
} // End of for loop on tracking vertices
// In case of no reco vertices, break here
if (recopv.empty())
return recopv;
// Now compute the closest distance in z between all reconstructed vertex
// first initialize
auto prev_z = recopv.back().z;
for (recoPrimaryVertex& vreco : recopv) {
vreco.closest_vertex_distance_z = std::abs(vreco.z - prev_z);
prev_z = vreco.z;
}
for (std::vector<recoPrimaryVertex>::iterator vreco = recopv.begin(); vreco != recopv.end(); vreco++) {
std::vector<recoPrimaryVertex>::iterator vreco2 = vreco;
vreco2++;
for (; vreco2 != recopv.end(); vreco2++) {
double distance = std::abs(vreco->z - vreco2->z);
// need both to be complete
vreco->closest_vertex_distance_z = std::min(vreco->closest_vertex_distance_z, distance);
vreco2->closest_vertex_distance_z = std::min(vreco2->closest_vertex_distance_z, distance);
}
}
return recopv;
}
// ------------ method called to produce the data ------------
void Primary4DVertexValidation::matchReco2Sim(std::vector<recoPrimaryVertex>& recopv,
std::vector<simPrimaryVertex>& simpv,
const edm::ValueMap<float>& sigmat0,
const edm::ValueMap<float>& MVA,
const edm::Handle<reco::BeamSpot>& BS) {
for (auto vv : simpv) {
vv.wnt.clear();
vv.wos.clear();
}
for (auto rv : recopv) {
rv.wnt.clear();
rv.wos.clear();
}
for (unsigned int iv = 0; iv < recopv.size(); iv++) {
const reco::Vertex* vertex = recopv.at(iv).recVtx;
for (unsigned int iev = 0; iev < simpv.size(); iev++) {
double wnt = 0;
double wos = 0;
double evwnt = 0;
double evwos = 0;
double evnt = 0;
for (auto iTrack = vertex->tracks_begin(); iTrack != vertex->tracks_end(); ++iTrack) {
double pt = (*iTrack)->pt();
if (vertex->trackWeight(*iTrack) < trackweightTh_)
continue;
if (MVA[(*iTrack)] < mvaTh_)
continue;
auto tp_info = getMatchedTP(*iTrack, simpv.at(iev).sim_vertex);
if (tp_info != nullptr) {
double dz2_beam = pow((*BS).BeamWidthX() * cos((*iTrack)->phi()) / tan((*iTrack)->theta()), 2) +
pow((*BS).BeamWidthY() * sin((*iTrack)->phi()) / tan((*iTrack)->theta()), 2);
double dz2 = pow((*iTrack)->dzError(), 2) + dz2_beam +
pow(0.0020, 2); // added 20 um, some tracks have crazy small resolutions
wos = vertex->trackWeight(*iTrack) / dz2;
wnt = vertex->trackWeight(*iTrack) * std::min(pt, 1.0);
if (sigmat0[(*iTrack)] > 0) {
double sigmaZ = (*BS).sigmaZ();
double sigmaT = sigmaZ / c_; // c in cm/ns
wos = wos / erf(sigmat0[(*iTrack)] / sigmaT);
}
simpv.at(iev).addTrack(iv, wos, wnt);
recopv.at(iv).addTrack(iev, wos, wnt);
evwos += wos;
evwnt += wnt;
evnt++;
}
} //RecoTracks loop
// require 2 tracks for a wos-match
if ((evwos > 0) && (evwos > recopv.at(iv).maxwos) && (evnt > 1)) {
recopv.at(iv).wosmatch = iev;
recopv.at(iv).maxwos = evwos;
recopv.at(iv).maxwosnt = evnt;
simpv.at(iev).wos_dominated_recv.push_back(iv);
simpv.at(iev).nwosmatch++;
}
// weighted track counting match, require at least one track
if ((evnt > 0) && (evwnt > recopv.at(iv).maxwnt)) {
recopv.at(iv).wntmatch = iev;
recopv.at(iv).maxwnt = evwnt;
}
} //TrackingVertex loop
} //RecoPrimaryVertex
//after filling infos, goes for the sim-reco match
for (auto& vrec : recopv) {
vrec.sim = NOT_MATCHED;
vrec.matchQuality = 0;
}
unsigned int iev = 0;
for (auto& vv : simpv) {
if (debug_) {
edm::LogPrint("Primary4DVertexValidation") << "iev: " << iev;
edm::LogPrint("Primary4DVertexValidation") << "wos_dominated_recv.size: " << vv.wos_dominated_recv.size();
}
for (unsigned int i = 0; i < vv.wos_dominated_recv.size(); i++) {
auto recov = vv.wos_dominated_recv.at(i);
if (debug_) {
edm::LogPrint("Primary4DVertexValidation")
<< "index of reco vertex: " << recov << " that has a wos: " << vv.wos.at(recov) << " at position " << i;
}
}
vv.rec = NOT_MATCHED;
vv.matchQuality = 0;
iev++;
}
//this tries a one-to-one match, taking simPV with highest wos if there are > 1 simPV candidates
for (unsigned int rank = 1; rank < maxRank_; rank++) {
for (unsigned int iev = 0; iev < simpv.size(); iev++) { //loop on SimPV
if (simpv.at(iev).rec != NOT_MATCHED)
continue;
if (simpv.at(iev).nwosmatch == 0)
continue;
if (simpv.at(iev).nwosmatch > rank)
continue;
unsigned int iv = NOT_MATCHED;
for (unsigned int k = 0; k < simpv.at(iev).wos_dominated_recv.size(); k++) {
unsigned int rec = simpv.at(iev).wos_dominated_recv.at(k);
auto vrec = recopv.at(rec);
if (vrec.sim != NOT_MATCHED)
continue; // already matched
if (std::abs(simpv.at(iev).z - vrec.z) > zWosMatchMax_)
continue; // insanely far away
if ((iv == NOT_MATCHED) || simpv.at(iev).wos.at(rec) > simpv.at(iev).wos.at(iv)) {
iv = rec;
}
}
if (iv !=
NOT_MATCHED) { //if the rec vertex has already been associated is possible that iv remains NOT_MATCHED at this point
recopv.at(iv).sim = iev;
simpv.at(iev).rec = iv;
recopv.at(iv).matchQuality = rank;
simpv.at(iev).matchQuality = rank;
}
}
}
//give vertices a chance that have a lot of overlap, but are still recognizably
//caused by a specific simvertex (without being classified as dominating)
//like a small peak sitting on the flank of a larger nearby peak
unsigned int ntry = 0;
while (ntry++ < maxTry_) {
unsigned nmatch = 0;
for (unsigned int iev = 0; iev < simpv.size(); iev++) {
if ((simpv.at(iev).rec != NOT_MATCHED) || (simpv.at(iev).wos.empty()))
continue;
// find a rec vertex for the NOT_MATCHED sim vertex
unsigned int rec = NOT_MATCHED;
for (auto rv : simpv.at(iev).wos) {
if ((rec == NOT_MATCHED) || (rv.second > simpv.at(iev).wos.at(rec))) {
rec = rv.first;
}
}
if (rec == NOT_MATCHED) { //try with wnt match
for (auto rv : simpv.at(iev).wnt) {
if ((rec == NOT_MATCHED) || (rv.second > simpv.at(iev).wnt.at(rec))) {
rec = rv.first;
}
}
}
if (rec == NOT_MATCHED)
continue;
if (recopv.at(rec).sim != NOT_MATCHED)
continue; // already gone
// check if the recvertex can be matched
unsigned int rec2sim = NOT_MATCHED;
for (auto sv : recopv.at(rec).wos) {
if (simpv.at(sv.first).rec != NOT_MATCHED)
continue; // already used
if ((rec2sim == NOT_MATCHED) || (sv.second > recopv.at(rec).wos.at(rec2sim))) {
rec2sim = sv.first;
}
}
if (iev == rec2sim) {
// do the match and assign lowest quality (i.e. max rank)
recopv.at(rec).sim = iev;
recopv.at(rec).matchQuality = maxRank_;
simpv.at(iev).rec = rec;
simpv.at(iev).matchQuality = maxRank_;
nmatch++;
}
} //sim loop
if (nmatch == 0) {
break;
}
} // ntry
}
void Primary4DVertexValidation::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) {
using edm::Handle;
using edm::View;
using std::cout;
using std::endl;
using std::vector;
using namespace reco;
std::vector<float> pileUpInfo_z;
// get the pileup information
edm::Handle<std::vector<PileupSummaryInfo>> puinfoH;
if (iEvent.getByToken(vecPileupSummaryInfoToken_, puinfoH)) {
for (auto const& pu_info : *puinfoH.product()) {
if (pu_info.getBunchCrossing() == 0) {
pileUpInfo_z = pu_info.getPU_zpositions();
break;
}
}
}
edm::Handle<TrackingParticleCollection> TPCollectionH;
iEvent.getByToken(trackingParticleCollectionToken_, TPCollectionH);
if (!TPCollectionH.isValid())
edm::LogWarning("Primary4DVertexValidation") << "TPCollectionH is not valid";
edm::Handle<TrackingVertexCollection> TVCollectionH;
iEvent.getByToken(trackingVertexCollectionToken_, TVCollectionH);
if (!TVCollectionH.isValid())
edm::LogWarning("Primary4DVertexValidation") << "TVCollectionH is not valid";
edm::Handle<reco::SimToRecoCollection> simToRecoH;
iEvent.getByToken(simToRecoAssociationToken_, simToRecoH);
if (simToRecoH.isValid())
s2r_ = simToRecoH.product();
else
edm::LogWarning("Primary4DVertexValidation") << "simToRecoH is not valid";
edm::Handle<reco::RecoToSimCollection> recoToSimH;
iEvent.getByToken(recoToSimAssociationToken_, recoToSimH);
if (recoToSimH.isValid())
r2s_ = recoToSimH.product();
else
edm::LogWarning("Primary4DVertexValidation") << "recoToSimH is not valid";
edm::Handle<reco::BeamSpot> BeamSpotH;
iEvent.getByToken(RecBeamSpotToken_, BeamSpotH);
if (!BeamSpotH.isValid())
edm::LogWarning("Primary4DVertexValidation") << "BeamSpotH is not valid";
std::vector<simPrimaryVertex> simpv; // a list of simulated primary MC vertices
simpv = getSimPVs(TVCollectionH);
//this bool check if first vertex in that with highest pT
bool signal_is_highest_pt =
std::max_element(simpv.begin(), simpv.end(), [](const simPrimaryVertex& lhs, const simPrimaryVertex& rhs) {
return lhs.ptsq < rhs.ptsq;
}) == simpv.begin();
std::vector<recoPrimaryVertex> recopv; // a list of reconstructed primary MC vertices
edm::Handle<edm::View<reco::Vertex>> recVtxs;
iEvent.getByToken(Rec4DVerToken_, recVtxs);
if (!recVtxs.isValid())
edm::LogWarning("Primary4DVertexValidation") << "recVtxs is not valid";
recopv = getRecoPVs(recVtxs);
const auto& trackAssoc = iEvent.get(trackAssocToken_);
const auto& pathLength = iEvent.get(pathLengthToken_);
const auto& momentum = iEvent.get(momentumToken_);
const auto& time = iEvent.get(timeToken_);
const auto& t0Safe = iEvent.get(t0SafePidToken_);
const auto& sigmat0Safe = iEvent.get(sigmat0SafePidToken_);
const auto& mtdQualMVA = iEvent.get(trackMVAQualToken_);
//I have simPV and recoPV collections
matchReco2Sim(recopv, simpv, sigmat0Safe, mtdQualMVA, BeamSpotH);
//Loop on tracks
for (unsigned int iv = 0; iv < recopv.size(); iv++) {
const reco::Vertex* vertex = recopv.at(iv).recVtx;
for (unsigned int iev = 0; iev < simpv.size(); iev++) {
auto vsim = simpv.at(iev).sim_vertex;
bool selectedVtxMatching = recopv.at(iv).sim == iev && simpv.at(iev).rec == iv &&
simpv.at(iev).eventId.bunchCrossing() == 0 && simpv.at(iev).eventId.event() == 0 &&
recopv.at(iv).OriginalIndex == 0;
if (selectedVtxMatching && !recopv.at(iv).is_signal()) {
edm::LogWarning("Primary4DVertexValidation")
<< "Reco vtx leading match inconsistent: BX/ID " << simpv.at(iev).eventId.bunchCrossing() << " "
<< simpv.at(iev).eventId.event();
}
double vzsim = simpv.at(iev).z;
double vtsim = simpv.at(iev).t * simUnit_;
for (auto iTrack = vertex->tracks_begin(); iTrack != vertex->tracks_end(); ++iTrack) {
if (trackAssoc[*iTrack] == -1) {
LogTrace("mtdTracks") << "Extended track not associated";
continue;
}
if (vertex->trackWeight(*iTrack) < trackweightTh_)
continue;
bool selectRecoTrk = mvaRecSel(**iTrack, *vertex, t0Safe[*iTrack], sigmat0Safe[*iTrack]);
if (selectedVtxMatching && selectRecoTrk) {
meMVATrackEffPtTot_->Fill((*iTrack)->pt());
meMVATrackEffEtaTot_->Fill(std::abs((*iTrack)->eta()));
}
auto tp_info = getMatchedTP(*iTrack, vsim);
if (tp_info != nullptr) {
double mass = (*tp_info)->mass();
double tsim = (*tp_info)->parentVertex()->position().t() * simUnit_;
double tEst = timeFromTrueMass(mass, pathLength[*iTrack], momentum[*iTrack], time[*iTrack]);
double xsim = (*tp_info)->parentVertex()->position().x();
double ysim = (*tp_info)->parentVertex()->position().y();
double zsim = (*tp_info)->parentVertex()->position().z();
double xPCA = (*iTrack)->vx();
double yPCA = (*iTrack)->vy();
double zPCA = (*iTrack)->vz();
double dZ = zPCA - zsim;
double d3D = std::sqrt((xPCA - xsim) * (xPCA - xsim) + (yPCA - ysim) * (yPCA - ysim) + dZ * dZ);
// orient d3D according to the projection of RECO - SIM onto simulated momentum
if ((xPCA - xsim) * ((*tp_info)->px()) + (yPCA - ysim) * ((*tp_info)->py()) + dZ * ((*tp_info)->pz()) < 0.) {
d3D = -d3D;
}
bool selectTP = mvaTPSel(**tp_info);
if (selectedVtxMatching && selectRecoTrk && selectTP) {
meMVATrackZposResTot_->Fill((*iTrack)->vz() - vzsim);
meMVATrackMatchedEffPtTot_->Fill((*iTrack)->pt());
meMVATrackMatchedEffEtaTot_->Fill(std::abs((*iTrack)->eta()));
}
if (sigmat0Safe[*iTrack] == -1)
continue;
if (selectedVtxMatching && selectRecoTrk && selectTP) {
meMVATrackResTot_->Fill(t0Safe[*iTrack] - vtsim);
meMVATrackPullTot_->Fill((t0Safe[*iTrack] - vtsim) / sigmat0Safe[*iTrack]);
meMVATrackMatchedEffPtMtd_->Fill((*iTrack)->pt());
meMVATrackMatchedEffEtaMtd_->Fill(std::abs((*iTrack)->eta()));
}
meTrackResTot_->Fill(t0Safe[*iTrack] - tsim);
meTrackPullTot_->Fill((t0Safe[*iTrack] - tsim) / sigmat0Safe[*iTrack]);
meTrackZposResTot_->Fill(dZ);
if ((*iTrack)->p() <= 2) {
meTrackResLowPTot_->Fill(t0Safe[*iTrack] - tsim);
meTrackPullLowPTot_->Fill((t0Safe[*iTrack] - tsim) / sigmat0Safe[*iTrack]);
} else {
meTrackResHighPTot_->Fill(t0Safe[*iTrack] - tsim);
meTrackPullHighPTot_->Fill((t0Safe[*iTrack] - tsim) / sigmat0Safe[*iTrack]);
}
if (mtdQualMVA[(*iTrack)] < mvaL_) {
meTrackZposRes_[0]->Fill(dZ);
meTrack3DposRes_[0]->Fill(d3D);
meTrackRes_[0]->Fill(t0Safe[*iTrack] - tsim);
meTrackPull_[0]->Fill((t0Safe[*iTrack] - tsim) / sigmat0Safe[*iTrack]);
if (optionalPlots_) {
meTrackResMass_[0]->Fill(t0Safe[*iTrack] - tEst);
meTrackResMassTrue_[0]->Fill(tEst - tsim);
}
if ((*iTrack)->p() <= 2) {
meTrackResLowP_[0]->Fill(t0Safe[*iTrack] - tsim);
meTrackPullLowP_[0]->Fill((t0Safe[*iTrack] - tsim) / sigmat0Safe[*iTrack]);
} else if ((*iTrack)->p() > 2) {
meTrackResHighP_[0]->Fill(t0Safe[*iTrack] - tsim);
meTrackPullHighP_[0]->Fill((t0Safe[*iTrack] - tsim) / sigmat0Safe[*iTrack]);
}
if (optionalPlots_) {
if (std::abs((*tp_info)->pdgId()) == 2212) {
meTrackResMassProtons_[0]->Fill(t0Safe[*iTrack] - tEst);
meTrackResMassTrueProtons_[0]->Fill(tEst - tsim);
} else if (std::abs((*tp_info)->pdgId()) == 211) {
meTrackResMassPions_[0]->Fill(t0Safe[*iTrack] - tEst);
meTrackResMassTruePions_[0]->Fill(tEst - tsim);
}
}
} else if (mtdQualMVA[(*iTrack)] > mvaL_ && mtdQualMVA[(*iTrack)] < mvaH_) {
meTrackZposRes_[1]->Fill(dZ);
meTrack3DposRes_[1]->Fill(d3D);
meTrackRes_[1]->Fill(t0Safe[*iTrack] - tsim);
meTrackPull_[1]->Fill((t0Safe[*iTrack] - tsim) / sigmat0Safe[*iTrack]);
if (optionalPlots_) {
meTrackResMass_[1]->Fill(t0Safe[*iTrack] - tEst);
meTrackResMassTrue_[1]->Fill(tEst - tsim);
}
if ((*iTrack)->p() <= 2) {
meTrackResLowP_[1]->Fill(t0Safe[*iTrack] - tsim);
meTrackPullLowP_[1]->Fill((t0Safe[*iTrack] - tsim) / sigmat0Safe[*iTrack]);
} else if ((*iTrack)->p() > 2) {
meTrackResHighP_[1]->Fill(t0Safe[*iTrack] - tsim);
meTrackPullHighP_[1]->Fill((t0Safe[*iTrack] - tsim) / sigmat0Safe[*iTrack]);
}
if (optionalPlots_) {
if (std::abs((*tp_info)->pdgId()) == 2212) {
meTrackResMassProtons_[1]->Fill(t0Safe[*iTrack] - tEst);
meTrackResMassTrueProtons_[1]->Fill(tEst - tsim);
} else if (std::abs((*tp_info)->pdgId()) == 211) {
meTrackResMassPions_[1]->Fill(t0Safe[*iTrack] - tEst);
meTrackResMassTruePions_[1]->Fill(tEst - tsim);
}
}
} else if (mtdQualMVA[(*iTrack)] > mvaH_) {
meTrackZposRes_[2]->Fill(dZ);
meTrack3DposRes_[2]->Fill(d3D);
meTrackRes_[2]->Fill(t0Safe[*iTrack] - tsim);
meTrackPull_[2]->Fill((t0Safe[*iTrack] - tsim) / sigmat0Safe[*iTrack]);
if (optionalPlots_) {
meTrackResMass_[2]->Fill(t0Safe[*iTrack] - tEst);
meTrackResMassTrue_[2]->Fill(tEst - tsim);
}
if ((*iTrack)->p() <= 2) {
meTrackResLowP_[2]->Fill(t0Safe[*iTrack] - tsim);
meTrackPullLowP_[2]->Fill((t0Safe[*iTrack] - tsim) / sigmat0Safe[*iTrack]);
} else if ((*iTrack)->p() > 2) {
meTrackResHighP_[2]->Fill(t0Safe[*iTrack] - tsim);
meTrackPullHighP_[2]->Fill((t0Safe[*iTrack] - tsim) / sigmat0Safe[*iTrack]);
}
if (optionalPlots_) {
if (std::abs((*tp_info)->pdgId()) == 2212) {
meTrackResMassProtons_[2]->Fill(t0Safe[*iTrack] - tEst);
meTrackResMassTrueProtons_[2]->Fill(tEst - tsim);
} else if (std::abs((*tp_info)->pdgId()) == 211) {
meTrackResMassPions_[2]->Fill(t0Safe[*iTrack] - tEst);
meTrackResMassTruePions_[2]->Fill(tEst - tsim);
}
}
}
} //if tp_info != nullptr
}
}
}
int real = 0;
int fake = 0;
int other_fake = 0;
int split = 0;
auto puLineDensity = [&](double z) {
// gaussian parameterization of line density vs z, z in cm, parameters in mm
double argl = (z * 10. - lineDensityPar_[1]) / lineDensityPar_[2];
return lineDensityPar_[0] * exp(-0.5 * argl * argl);
};
meRecVerNumber_->Fill(recopv.size());
for (unsigned int ir = 0; ir < recopv.size(); ir++) {
meRecoVtxVsLineDensity_->Fill(puLineDensity(recopv.at(ir).z));
meRecPVZ_->Fill(recopv.at(ir).z, 1. / puLineDensity(recopv.at(ir).z));
if (recopv.at(ir).recVtx->tError() > 0.) {
meRecPVT_->Fill(recopv.at(ir).recVtx->t());
}
if (debug_) {
edm::LogPrint("Primary4DVertexValidation") << "************* IR: " << ir;
edm::LogPrint("Primary4DVertexValidation")
<< "z: " << recopv.at(ir).z << " corresponding to line density: " << puLineDensity(recopv.at(ir).z);
edm::LogPrint("Primary4DVertexValidation") << "is_real: " << recopv.at(ir).is_real();
edm::LogPrint("Primary4DVertexValidation") << "is_fake: " << recopv.at(ir).is_fake();
edm::LogPrint("Primary4DVertexValidation") << "is_signal: " << recopv.at(ir).is_signal();
edm::LogPrint("Primary4DVertexValidation") << "split_from: " << recopv.at(ir).split_from();
edm::LogPrint("Primary4DVertexValidation") << "other fake: " << recopv.at(ir).other_fake();
}
if (recopv.at(ir).is_real())
real++;
if (recopv.at(ir).is_fake())
fake++;
if (recopv.at(ir).other_fake())
other_fake++;
if (recopv.at(ir).split_from() != -1) {
split++;
}
}
if (debug_) {
edm::LogPrint("Primary4DVertexValidation") << "is_real: " << real;
edm::LogPrint("Primary4DVertexValidation") << "is_fake: " << fake;
edm::LogPrint("Primary4DVertexValidation") << "split_from: " << split;
edm::LogPrint("Primary4DVertexValidation") << "other fake: " << other_fake;
}
//fill vertices histograms here in a new loop
for (unsigned int is = 0; is < simpv.size(); is++) {
meSimPVZ_->Fill(simpv.at(is).z, 1. / puLineDensity(simpv.at(is).z));
if (is == 0 && optionalPlots_) {
meSimPosInSimOrigCollection_->Fill(simpv.at(is).OriginalIndex);
}
if (simpv.at(is).rec == NOT_MATCHED) {
if (debug_) {
edm::LogPrint("Primary4DVertexValidation") << "sim vertex: " << is << " is not matched with any reco";
}
continue;
}
for (unsigned int ir = 0; ir < recopv.size(); ir++) {
if (recopv.at(ir).sim == is && simpv.at(is).rec == ir) {
meTimeRes_->Fill(recopv.at(ir).recVtx->t() - simpv.at(is).t * simUnit_);
meTimePull_->Fill((recopv.at(ir).recVtx->t() - simpv.at(is).t * simUnit_) / recopv.at(ir).recVtx->tError());
mePUvsRealV_->Fill(simpv.size(), real);
mePUvsOtherFakeV_->Fill(simpv.size(), other_fake);
mePUvsSplitV_->Fill(simpv.size(), split);
meMatchQual_->Fill(recopv.at(ir).matchQuality - 0.5);
if (ir == 0) { //signal vertex plots
meTimeSignalRes_->Fill(recopv.at(ir).recVtx->t() - simpv.at(is).t * simUnit_);
meTimeSignalPull_->Fill((recopv.at(ir).recVtx->t() - simpv.at(is).t * simUnit_) /
recopv.at(ir).recVtx->tError());
if (optionalPlots_) {
meRecoPosInSimCollection_->Fill(recopv.at(ir).sim);
meRecoPosInRecoOrigCollection_->Fill(recopv.at(ir).OriginalIndex);
}
}
if (simpv.at(is).eventId.bunchCrossing() == 0 && simpv.at(is).eventId.event() == 0) {
if (!recopv.at(ir).is_signal()) {
edm::LogWarning("Primary4DVertexValidation")
<< "Reco vtx leading match inconsistent: BX/ID " << simpv.at(is).eventId.bunchCrossing() << " "
<< simpv.at(is).eventId.event();
}
meRecoPVPosSignal_->Fill(
recopv.at(ir).OriginalIndex); // position in reco vtx correction associated to sim signal
if (!signal_is_highest_pt) {
meRecoPVPosSignalNotHighestPt_->Fill(
recopv.at(ir).OriginalIndex); // position in reco vtx correction associated to sim signal
}
}
if (debug_) {
edm::LogPrint("Primary4DVertexValidation") << "*** Matching RECO: " << ir << "with SIM: " << is << " ***";
edm::LogPrint("Primary4DVertexValidation") << "Match Quality is " << recopv.at(ir).matchQuality;
edm::LogPrint("Primary4DVertexValidation") << "****";
}
}
}
}
//dz histos
for (unsigned int iv = 0; iv < recVtxs->size() - 1; iv++) {
if (recVtxs->at(iv).ndof() > selNdof_) {
double mindistance_realreal = 1e10;
for (unsigned int jv = iv; jv < recVtxs->size(); jv++) {
if ((!(jv == iv)) && select(recVtxs->at(jv))) {
double dz = recVtxs->at(iv).z() - recVtxs->at(jv).z();
double dtsigma = std::sqrt(recVtxs->at(iv).covariance(3, 3) + recVtxs->at(jv).covariance(3, 3));
double dt = (std::abs(dz) <= deltaZcut_ && dtsigma > 0.)
? (recVtxs->at(iv).t() - recVtxs->at(jv).t()) / dtsigma
: -9999.;
if (recopv.at(iv).is_real() && recopv.at(jv).is_real()) {
meDeltaZrealreal_->Fill(std::abs(dz));
if (dt != -9999.) {
meDeltaTrealreal_->Fill(std::abs(dt));
}
if (std::abs(dz) < std::abs(mindistance_realreal)) {
mindistance_realreal = dz;
}
} else if (recopv.at(iv).is_fake() && recopv.at(jv).is_fake()) {
meDeltaZfakefake_->Fill(std::abs(dz));
if (dt != -9999.) {
meDeltaTfakefake_->Fill(std::abs(dt));
}
}
}
}
double mindistance_fakereal = 1e10;
double mindistance_realfake = 1e10;
for (unsigned int jv = 0; jv < recVtxs->size(); jv++) {
if ((!(jv == iv)) && select(recVtxs->at(jv))) {
double dz = recVtxs->at(iv).z() - recVtxs->at(jv).z();
double dtsigma = std::sqrt(recVtxs->at(iv).covariance(3, 3) + recVtxs->at(jv).covariance(3, 3));
double dt = (std::abs(dz) <= deltaZcut_ && dtsigma > 0.)
? (recVtxs->at(iv).t() - recVtxs->at(jv).t()) / dtsigma
: -9999.;
if (recopv.at(iv).is_fake() && recopv.at(jv).is_real()) {
meDeltaZfakereal_->Fill(std::abs(dz));
if (dt != -9999.) {
meDeltaTfakereal_->Fill(std::abs(dt));
}
if (std::abs(dz) < std::abs(mindistance_fakereal)) {
mindistance_fakereal = dz;
}
}
if (recopv.at(iv).is_real() && recopv.at(jv).is_fake() && (std::abs(dz) < std::abs(mindistance_realfake))) {
mindistance_realfake = dz;
}
}
}
} //ndof
}
} // end of analyze
void Primary4DVertexValidation::fillDescriptions(edm::ConfigurationDescriptions& descriptions) {
edm::ParameterSetDescription desc;
desc.add<std::string>("folder", "MTD/Vertices");
desc.add<edm::InputTag>("TPtoRecoTrackAssoc", edm::InputTag("trackingParticleRecoTrackAsssociation"));
desc.add<edm::InputTag>("mtdTracks", edm::InputTag("trackExtenderWithMTD"));
desc.add<edm::InputTag>("SimTag", edm::InputTag("mix", "MergedTrackTruth"));
desc.add<edm::InputTag>("offlineBS", edm::InputTag("offlineBeamSpot"));
desc.add<edm::InputTag>("offline4DPV", edm::InputTag("offlinePrimaryVertices4D"));
desc.add<edm::InputTag>("trackAssocSrc", edm::InputTag("trackExtenderWithMTD:generalTrackassoc"))
->setComment("Association between General and MTD Extended tracks");
desc.add<edm::InputTag>("pathLengthSrc", edm::InputTag("trackExtenderWithMTD:generalTrackPathLength"));
desc.add<edm::InputTag>("momentumSrc", edm::InputTag("trackExtenderWithMTD:generalTrackp"));
desc.add<edm::InputTag>("timeSrc", edm::InputTag("trackExtenderWithMTD:generalTracktmtd"));
desc.add<edm::InputTag>("sigmaSrc", edm::InputTag("trackExtenderWithMTD:generalTracksigmatmtd"));
desc.add<edm::InputTag>("t0SafePID", edm::InputTag("tofPID:t0safe"));
desc.add<edm::InputTag>("sigmat0SafePID", edm::InputTag("tofPID:sigmat0safe"));
desc.add<edm::InputTag>("trackMVAQual", edm::InputTag("mtdTrackQualityMVA:mtdQualMVA"));
desc.add<bool>("useOnlyChargedTracks", true);
desc.addUntracked<bool>("debug", false);
desc.addUntracked<bool>("optionalPlots", false);
desc.add<double>("trackweightTh", 0.5);
desc.add<double>("mvaTh", 0.01);
//lineDensity parameters have been obtained by fitting the distribution of the z position of the vertices,
//using a 200k single mu ptGun sample (gaussian fit)
std::vector<double> lDP;
lDP.push_back(1.87);
lDP.push_back(0.);
lDP.push_back(42.5);
desc.add<std::vector<double>>("lineDensityPar", lDP);
descriptions.add("vertices4D", desc);
}
const bool Primary4DVertexValidation::mvaTPSel(const TrackingParticle& tp) {
bool match = false;
if (tp.status() != 1) {
return match;
}
match = tp.charge() != 0 && tp.pt() > pTcut_ && std::abs(tp.eta()) < etacutGEN_;
return match;
}
const bool Primary4DVertexValidation::mvaRecSel(const reco::TrackBase& trk,
const reco::Vertex& vtx,
const double& t0,
const double& st0) {
bool match = false;
match = trk.pt() > pTcut_ && std::abs(trk.eta()) < etacutREC_ && std::abs(trk.vz() - vtx.z()) <= deltaZcut_;
if (st0 > 0.) {
match = match && std::abs(t0 - vtx.t()) < 3. * st0;
}
return match;
}
DEFINE_FWK_MODULE(Primary4DVertexValidation);
| 43.936255
| 127
| 0.594683
|
wonpoint4
|
2910b48c65c0d930885115dfcc8110717ade834b
| 2,106
|
cpp
|
C++
|
src/async/streamsocket.cpp
|
abbyssoul/libcadence
|
c9a49d95df608497e9551f7d62169d0c78a48737
|
[
"Apache-2.0"
] | 2
|
2020-04-24T15:07:33.000Z
|
2020-06-12T07:01:53.000Z
|
src/async/streamsocket.cpp
|
abbyssoul/libcadence
|
c9a49d95df608497e9551f7d62169d0c78a48737
|
[
"Apache-2.0"
] | null | null | null |
src/async/streamsocket.cpp
|
abbyssoul/libcadence
|
c9a49d95df608497e9551f7d62169d0c78a48737
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright (C) Ivan Ryabov - All Rights Reserved
*
* Unauthorized copying of this file, via any medium is strictly prohibited.
* Proprietary and confidential.
*
* Written by Ivan Ryabov <abbyssoul@gmail.com>
*/
/*******************************************************************************
* @file: async/streamsocket.cpp
*******************************************************************************/
#include "cadence/async/streamsocket.hpp"
#include "streamsocket_impl.hpp"
using namespace Solace;
using namespace cadence;
using namespace cadence::async;
StreamSocket::StreamSocketImpl::~StreamSocketImpl() = default;
StreamSocket::~StreamSocket() = default;
StreamSocket::StreamSocket(EventLoop& ioContext, std::unique_ptr<StreamSocketImpl> impl) :
Channel(ioContext),
_pimpl(std::move(impl))
{ }
Future<void>
StreamSocket::asyncRead(ByteWriter& dest, size_type bytesToRead) {
return _pimpl->asyncRead(dest, bytesToRead);
}
Future<void>
StreamSocket::asyncWrite(ByteReader& src, size_type bytesToWrite) {
return _pimpl->asyncWrite(src, bytesToWrite);
}
Result<void, Error>
StreamSocket::read(ByteWriter& dest, size_type bytesToRead) {
return _pimpl->read(dest, bytesToRead);
}
Result<void, Error>
StreamSocket::write(ByteReader& src, size_type bytesToWrite) {
return _pimpl->write(src, bytesToWrite);
}
void StreamSocket::cancel() {
_pimpl->cancel();
}
void StreamSocket::close() {
_pimpl->close();
}
bool StreamSocket::isOpen() const {
return _pimpl->isOpen();
}
bool StreamSocket::isClosed() const{
return _pimpl->isClosed();
}
NetworkEndpoint StreamSocket::getLocalEndpoint() const {
return _pimpl->getLocalEndpoint();
}
NetworkEndpoint StreamSocket::getRemoteEndpoint() const {
return _pimpl->getRemoteEndpoint();
}
void StreamSocket::shutdown() {
_pimpl->shutdown();
}
Future<void>
StreamSocket::asyncConnect(NetworkEndpoint const& endpoint) {
return _pimpl->asyncConnect(endpoint);
}
Result<void, Error>
StreamSocket::connect(NetworkEndpoint const& endpoint) {
return _pimpl->connect(endpoint);
}
| 22.404255
| 90
| 0.681387
|
abbyssoul
|
2910d0bbe140a2abddcab117ae649081e429c159
| 1,915
|
cpp
|
C++
|
workshop 2020/Stl algorithms/3sum/main.cpp
|
wdjpng/soi
|
dd565587ae30985676f7f374093ec0687436b881
|
[
"MIT"
] | null | null | null |
workshop 2020/Stl algorithms/3sum/main.cpp
|
wdjpng/soi
|
dd565587ae30985676f7f374093ec0687436b881
|
[
"MIT"
] | null | null | null |
workshop 2020/Stl algorithms/3sum/main.cpp
|
wdjpng/soi
|
dd565587ae30985676f7f374093ec0687436b881
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <vector>
#include <map>
#include <limits>
#include <algorithm>
#define int long long
using namespace std;
signed main() {
int n;
cin >> n;
cin.tie(0);
ios_base::sync_with_stdio(false);
vector<int> tmpInput(n);
map<int, int>occurences;
for (int i = 0; i < n; ++i) {
cin >> tmpInput[i];
occurences[tmpInput[i]]++;
}
sort(tmpInput.begin(), tmpInput.end());
vector<pair<int, int>>input;//Value, occurences
input.push_back(make_pair(tmpInput[0], 1));
int offSet = 0;
for (int i = 1; i < n+offSet; ++i) {
if(input[i-1-offSet].first == tmpInput[i]){
input[i-1-offSet].second++;
offSet++;
n--;
} else{
input.push_back(make_pair(tmpInput[i], 1));
}
}
int combinationSum = 0;
for (int i = 0; i < n - 2; ++i) {
int curCombinations = 0;
int headIndex = i + 2;
for (int bIndex = i + 1; bIndex < n - 1; ++bIndex) {
if(headIndex==n){
break;
}
while (input[headIndex].first < input[i].first + input[bIndex].first && headIndex!=n-1) {
headIndex++;
}
if(headIndex==n){
break;
}
while (input[headIndex].first == input[i].first + input[bIndex].first) {
if(headIndex==n){
break;
}
curCombinations+=input[headIndex].second*input[bIndex].second*input[i].second;
headIndex++;
}
}
combinationSum += curCombinations;
}
for (int i = 0; i < n; ++i) {
if(input[i].second >= 2 && occurences[2*input[i].first]){
combinationSum+=occurences[2*input[i].first]*((input[i].second)*(input[i].second-1)/2);
}
}
cout << combinationSum << "\n";
}
| 24.551282
| 101
| 0.49295
|
wdjpng
|
2911155dca15a375accd81c489513c54a8c827c8
| 1,573
|
hpp
|
C++
|
doc/quickbook/oglplus/quickref/images/image.hpp
|
highfidelity/oglplus
|
c5fb7cc21869cb9555cfa2a7e28ea6bc6491d11e
|
[
"BSL-1.0"
] | 2
|
2017-06-09T00:28:35.000Z
|
2017-06-09T00:28:43.000Z
|
doc/quickbook/oglplus/quickref/images/image.hpp
|
highfidelity/oglplus
|
c5fb7cc21869cb9555cfa2a7e28ea6bc6491d11e
|
[
"BSL-1.0"
] | null | null | null |
doc/quickbook/oglplus/quickref/images/image.hpp
|
highfidelity/oglplus
|
c5fb7cc21869cb9555cfa2a7e28ea6bc6491d11e
|
[
"BSL-1.0"
] | 8
|
2017-01-30T22:06:41.000Z
|
2020-01-14T17:24:36.000Z
|
/*
* Copyright 2014-2015 Matus Chochlik. Distributed under the Boost
* Software License, Version 1.0. (See accompanying file
* LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
//[oglplus_images_Image
namespace oglplus {
namespace images {
class Image
{
public:
Image(const Image& that);
Image(Image&& tmp)
noexcept;
Image& operator = (Image&& tmp)
noexcept;
template <typename T>
Image(
GLsizei width,
GLsizei height,
GLsizei depth,
GLsizei channels,
const T* data
);
template <typename T>
Image(
GLsizei width,
GLsizei height,
GLsizei depth,
GLsizei channels,
const T* data,
__PixelDataFormat format,
__PixelDataInternalFormat internal
);
GLsizei Dimension(std::size_t i) const
noexcept; /*<
Returns the size of the i-th dimension of the image.
>*/
GLsizei Width(void) const
noexcept; /*<
Returns the width of the image.
>*/
GLsizei Height(void) const
noexcept; /*<
Returns the height of the image.
>*/
GLsizei Depth(void) const
noexcept; /*<
Returns the depth of the image.
>*/
GLsizei Channels(void) const
noexcept; /*<
Returns the number of channels.
>*/
__PixelDataType Type(void) const
noexcept;
__PixelDataFormat Format(void) const
noexcept;
__PixelDataInternalFormat InternalFormat(void) const
noexcept;
template <typename T>
const T* Data(void) const
noexcept;
const void* RawData(void) const
noexcept;
std::size_t DataSize(void) const
noexcept; /*<
Returns the size of data in bytes.
>*/
//TODO
};
} // namespace images
} // namespace oglplus
//]
| 16.557895
| 68
| 0.708837
|
highfidelity
|
291135aab35acc814617da41479d58d2ea8d9adb
| 299
|
cpp
|
C++
|
src/ast/Import.cpp
|
denisw/soyac
|
2531e16e8dfbfa966931b774f9d79af528d16ff9
|
[
"MIT"
] | 1
|
2019-06-17T07:16:01.000Z
|
2019-06-17T07:16:01.000Z
|
src/ast/Import.cpp
|
denisw/soyac
|
2531e16e8dfbfa966931b774f9d79af528d16ff9
|
[
"MIT"
] | null | null | null |
src/ast/Import.cpp
|
denisw/soyac
|
2531e16e8dfbfa966931b774f9d79af528d16ff9
|
[
"MIT"
] | null | null | null |
/*
* soyac - Soya Programming Language compiler
* Copyright (c) 2009 Denis Washington <dwashington@gmx.net>
*
* This file is distributed under the terms of the MIT license.
* See LICENSE.txt for details.
*/
#include "Import.hpp"
namespace soyac {
namespace ast
{
Import::Import()
{
}
}}
| 13.590909
| 63
| 0.695652
|
denisw
|
2911ba4bcd0e1dbf50934f958c59da2234e4ea66
| 520
|
cpp
|
C++
|
Hackerrank/apple-and-orange.cpp
|
ronayumik/Learning-c-
|
b754d5e6ce92f091f1175a866c99c49561e87f22
|
[
"MIT"
] | null | null | null |
Hackerrank/apple-and-orange.cpp
|
ronayumik/Learning-c-
|
b754d5e6ce92f091f1175a866c99c49561e87f22
|
[
"MIT"
] | 3
|
2019-04-13T16:27:37.000Z
|
2019-04-13T16:52:57.000Z
|
Hackerrank/apple-and-orange.cpp
|
ronayumik/Learning-c-
|
b754d5e6ce92f091f1175a866c99c49561e87f22
|
[
"MIT"
] | 1
|
2018-12-05T23:17:35.000Z
|
2018-12-05T23:17:35.000Z
|
#include<bits/stdc++.h>
using namespace std;
int s,t,b,a,m,n;
int apple, orange;
int temp;
void countApple(int pos){
if(pos+a<= t && pos+a >= s) apple++;
}
void countOrange(int pos){
if(pos+b<= t && pos+b >= s) orange++;
}
int main(){
cin >> s >> t >> a >> b >> m >> n;
apple=0;
orange=0;
for(int x=0;x<m;x++)
{
cin >> temp;
countApple(temp);
}
for(int x=0;x<n;x++)
{
cin >> temp;
countOrange(temp);
}
cout << apple << " " << orange << endl;
return 0;
}
| 14.444444
| 41
| 0.498077
|
ronayumik
|
29124957a1301654529a161d64a0868e67fea641
| 322
|
hpp
|
C++
|
openstudiocore/src/isomodel/ISOModelAPI.hpp
|
OpenStudioThailand/OpenStudio
|
4e2173955e687ef1b934904acc10939ac0bed52f
|
[
"MIT"
] | 1
|
2017-10-13T09:23:04.000Z
|
2017-10-13T09:23:04.000Z
|
openstudiocore/src/isomodel/ISOModelAPI.hpp
|
OpenStudioThailand/OpenStudio
|
4e2173955e687ef1b934904acc10939ac0bed52f
|
[
"MIT"
] | null | null | null |
openstudiocore/src/isomodel/ISOModelAPI.hpp
|
OpenStudioThailand/OpenStudio
|
4e2173955e687ef1b934904acc10939ac0bed52f
|
[
"MIT"
] | 1
|
2022-03-20T13:19:42.000Z
|
2022-03-20T13:19:42.000Z
|
#ifndef ISOMODEL_ISOMODELAPI_HPP
#define ISOMODEL_ISOMODELAPI_HPP
#if (_WIN32 || _MSC_VER) && SHARED_OS_LIBS
#ifdef openstudio_isomodel_EXPORTS
#define ISOMODEL_API __declspec(dllexport)
#else
#define ISOMODEL_API __declspec(dllimport)
#endif
#else
#define ISOMODEL_API
#endif
#endif
| 21.466667
| 48
| 0.736025
|
OpenStudioThailand
|
291384cb483441cff73b50373db6157e280152f1
| 12,672
|
cc
|
C++
|
caffe2/core/plan_executor_test.cc
|
Gamrix/pytorch
|
b5b158a6c6de94dfb983b447fa33fea062358844
|
[
"Intel"
] | null | null | null |
caffe2/core/plan_executor_test.cc
|
Gamrix/pytorch
|
b5b158a6c6de94dfb983b447fa33fea062358844
|
[
"Intel"
] | null | null | null |
caffe2/core/plan_executor_test.cc
|
Gamrix/pytorch
|
b5b158a6c6de94dfb983b447fa33fea062358844
|
[
"Intel"
] | null | null | null |
#ifndef ANDROID
#include <gtest/gtest.h>
#include "caffe2/core/init.h"
#include "caffe2/core/operator.h"
#include "caffe2/core/plan_executor.h"
namespace caffe2 {
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
TEST(PlanExecutorTest, EmptyPlan) {
PlanDef plan_def;
Workspace ws;
EXPECT_TRUE(ws.RunPlan(plan_def));
}
namespace {
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
static std::atomic<int> cancelCount{0};
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
static std::atomic<bool> stuckRun{false};
} // namespace
class StuckBlockingOp final : public Operator<CPUContext> {
public:
StuckBlockingOp(const OperatorDef& operator_def, Workspace* ws)
: Operator<CPUContext>(operator_def, ws) {}
bool RunOnDevice() override {
// StuckBlockingOp runs and notifies ErrorOp.
stuckRun = true;
while (!cancelled_) {
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
return true;
}
void Cancel() override {
LOG(INFO) << "cancelled StuckBlockingOp.";
cancelCount += 1;
cancelled_ = true;
}
private:
std::atomic<bool> cancelled_{false};
};
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
REGISTER_CPU_OPERATOR(StuckBlocking, StuckBlockingOp);
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
OPERATOR_SCHEMA(StuckBlocking).NumInputs(0).NumOutputs(0);
class NoopOp final : public Operator<CPUContext> {
public:
NoopOp(const OperatorDef& operator_def, Workspace* ws)
: Operator<CPUContext>(operator_def, ws) {}
bool RunOnDevice() override {
// notify Error op we've ran.
stuckRun = true;
return true;
}
};
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
REGISTER_CPU_OPERATOR(Noop, NoopOp);
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
OPERATOR_SCHEMA(Noop).NumInputs(0).NumOutputs(0);
class StuckAsyncOp final : public Operator<CPUContext> {
public:
StuckAsyncOp(const OperatorDef& operator_def, Workspace* ws)
: Operator<CPUContext>(operator_def, ws) {}
bool RunOnDevice() override {
// notify Error op we've ran.
stuckRun = true;
// explicitly don't call SetFinished so this gets stuck
return true;
}
void CancelAsyncCallback() override {
LOG(INFO) << "cancelled";
cancelCount += 1;
}
bool HasAsyncPart() const override {
return true;
}
};
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
REGISTER_CPU_OPERATOR(StuckAsync, StuckAsyncOp);
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
OPERATOR_SCHEMA(StuckAsync).NumInputs(0).NumOutputs(0);
class TestError : public std::exception {
const char* what() const noexcept override {
return "test error";
}
};
class ErrorOp final : public Operator<CPUContext> {
public:
ErrorOp(const OperatorDef& operator_def, Workspace* ws)
: Operator<CPUContext>(operator_def, ws) {}
bool RunOnDevice() override {
// Wait for StuckAsyncOp or StuckBlockingOp to run first.
while (!stuckRun) {
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
throw TestError();
return true;
}
};
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
REGISTER_CPU_OPERATOR(Error, ErrorOp);
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
OPERATOR_SCHEMA(Error).NumInputs(0).NumOutputs(0);
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
static std::atomic<int> blockingErrorRuns{0};
class BlockingErrorOp final : public Operator<CPUContext> {
public:
BlockingErrorOp(const OperatorDef& operator_def, Workspace* ws)
: Operator<CPUContext>(operator_def, ws) {}
bool RunOnDevice() override {
// First n op executions should block and then start throwing errors.
if (blockingErrorRuns.fetch_sub(1) >= 1) {
LOG(INFO) << "blocking";
while (true) {
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
std::this_thread::sleep_for(std::chrono::hours(10));
}
} else {
LOG(INFO) << "throwing";
throw TestError();
}
}
};
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
REGISTER_CPU_OPERATOR(BlockingError, BlockingErrorOp);
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
OPERATOR_SCHEMA(BlockingError).NumInputs(0).NumOutputs(0);
PlanDef parallelErrorPlan() {
PlanDef plan_def;
auto* stuck_net = plan_def.add_network();
stuck_net->set_name("stuck_net");
stuck_net->set_type("async_scheduling");
{
auto* op = stuck_net->add_op();
op->set_type("StuckAsync");
}
auto* error_net = plan_def.add_network();
error_net->set_name("error_net");
error_net->set_type("async_scheduling");
{
auto op = error_net->add_op();
op->set_type("Error");
}
auto* execution_step = plan_def.add_execution_step();
execution_step->set_concurrent_substeps(true);
{
auto* substep = execution_step->add_substep();
substep->add_network(stuck_net->name());
}
{
auto* substep = execution_step->add_substep();
substep->add_network(error_net->name());
}
return plan_def;
}
PlanDef parallelErrorPlanWithCancellableStuckNet() {
// Set a plan with two nets: one stuck net with blocking operator that never
// returns; one error net with error op that throws.
PlanDef plan_def;
auto* stuck_blocking_net = plan_def.add_network();
stuck_blocking_net->set_name("stuck_blocking_net");
{
auto* op = stuck_blocking_net->add_op();
op->set_type("StuckBlocking");
}
auto* error_net = plan_def.add_network();
error_net->set_name("error_net");
{
auto* op = error_net->add_op();
op->set_type("Error");
}
auto* execution_step = plan_def.add_execution_step();
execution_step->set_concurrent_substeps(true);
{
auto* substep = execution_step->add_substep();
substep->add_network(stuck_blocking_net->name());
}
{
auto* substep = execution_step->add_substep();
substep->add_network(error_net->name());
}
return plan_def;
}
PlanDef reporterErrorPlanWithCancellableStuckNet() {
// Set a plan with a concurrent net and a reporter net: one stuck net with
// blocking operator that never returns; one reporter net with error op
// that throws.
PlanDef plan_def;
auto* stuck_blocking_net = plan_def.add_network();
stuck_blocking_net->set_name("stuck_blocking_net");
{
auto* op = stuck_blocking_net->add_op();
op->set_type("StuckBlocking");
}
auto* error_net = plan_def.add_network();
error_net->set_name("error_net");
{
auto* op = error_net->add_op();
op->set_type("Error");
}
auto* execution_step = plan_def.add_execution_step();
execution_step->set_concurrent_substeps(true);
{
auto* substep = execution_step->add_substep();
substep->add_network(stuck_blocking_net->name());
}
{
auto* substep = execution_step->add_substep();
substep->set_run_every_ms(1);
substep->add_network(error_net->name());
}
return plan_def;
}
struct HandleExecutorThreadExceptionsGuard {
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
HandleExecutorThreadExceptionsGuard(int timeout = 60) {
globalInit({
"caffe2",
"--caffe2_handle_executor_threads_exceptions=1",
"--caffe2_plan_executor_exception_timeout=" +
caffe2::to_string(timeout),
});
}
~HandleExecutorThreadExceptionsGuard() {
globalInit({
"caffe2",
});
}
HandleExecutorThreadExceptionsGuard(
const HandleExecutorThreadExceptionsGuard&) = delete;
void operator=(const HandleExecutorThreadExceptionsGuard&) = delete;
private:
void globalInit(std::vector<std::string> args) {
std::vector<char*> args_ptrs;
for (auto& arg : args) {
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast,performance-inefficient-vector-operation)
args_ptrs.push_back(const_cast<char*>(arg.data()));
}
char** new_argv = args_ptrs.data();
int new_argc = args.size();
CAFFE_ENFORCE(GlobalInit(&new_argc, &new_argv));
}
};
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
TEST(PlanExecutorTest, ErrorAsyncPlan) {
HandleExecutorThreadExceptionsGuard guard;
cancelCount = 0;
PlanDef plan_def = parallelErrorPlan();
Workspace ws;
// NOLINTNEXTLINE(cppcoreguidelines-avoid-goto,hicpp-avoid-goto)
ASSERT_THROW(ws.RunPlan(plan_def), TestError);
ASSERT_EQ(cancelCount, 1);
}
// death tests not supported on mobile
#if !defined(CAFFE2_IS_XPLAT_BUILD) && !defined(C10_MOBILE)
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
TEST(PlanExecutorTest, BlockingErrorPlan) {
// TSAN doesn't play nicely with death tests
#if defined(__has_feature)
#if __has_feature(thread_sanitizer)
return;
#endif
#endif
// NOLINTNEXTLINE(cppcoreguidelines-avoid-goto,hicpp-avoid-goto)
ASSERT_DEATH(
[] {
HandleExecutorThreadExceptionsGuard guard(/*timeout=*/1);
PlanDef plan_def;
std::string plan_def_template = R"DOC(
network {
name: "net"
op {
type: "BlockingError"
}
}
execution_step {
num_concurrent_instances: 2
substep {
network: "net"
}
}
)DOC";
CAFFE_ENFORCE(
TextFormat::ParseFromString(plan_def_template, &plan_def));
Workspace ws;
blockingErrorRuns = 1;
ws.RunPlan(plan_def);
FAIL() << "shouldn't have reached this point";
}(),
"failed to stop concurrent workers after exception: test error");
}
#endif
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
TEST(PlanExecutorTest, ErrorPlanWithCancellableStuckNet) {
HandleExecutorThreadExceptionsGuard guard;
cancelCount = 0;
PlanDef plan_def = parallelErrorPlanWithCancellableStuckNet();
Workspace ws;
// NOLINTNEXTLINE(cppcoreguidelines-avoid-goto,hicpp-avoid-goto)
ASSERT_THROW(ws.RunPlan(plan_def), TestError);
ASSERT_EQ(cancelCount, 1);
}
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
TEST(PlanExecutorTest, ReporterErrorPlanWithCancellableStuckNet) {
HandleExecutorThreadExceptionsGuard guard;
cancelCount = 0;
PlanDef plan_def = reporterErrorPlanWithCancellableStuckNet();
Workspace ws;
// NOLINTNEXTLINE(cppcoreguidelines-avoid-goto,hicpp-avoid-goto)
ASSERT_THROW(ws.RunPlan(plan_def), TestError);
ASSERT_EQ(cancelCount, 1);
}
PlanDef shouldStopWithCancelPlan() {
// Set a plan with a looping net with should_stop_blob set and a concurrent
// net that throws an error. The error should cause should_stop to return
// false and end the concurrent net.
PlanDef plan_def;
auto* should_stop_net = plan_def.add_network();
{
auto* op = should_stop_net->add_op();
op->set_type("Noop");
}
should_stop_net->set_name("should_stop_net");
should_stop_net->set_type("async_scheduling");
auto* error_net = plan_def.add_network();
error_net->set_name("error_net");
{
auto* op = error_net->add_op();
op->set_type("Error");
}
auto* execution_step = plan_def.add_execution_step();
execution_step->set_concurrent_substeps(true);
{
auto* substep = execution_step->add_substep();
execution_step->set_concurrent_substeps(true);
substep->set_name("concurrent_should_stop");
substep->set_should_stop_blob("should_stop_blob");
auto* substep2 = substep->add_substep();
substep2->set_name("should_stop_net");
substep2->add_network(should_stop_net->name());
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
substep2->set_num_iter(10);
}
{
auto* substep = execution_step->add_substep();
substep->set_name("error_step");
substep->add_network(error_net->name());
}
return plan_def;
}
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
TEST(PlanExecutorTest, ShouldStopWithCancel) {
HandleExecutorThreadExceptionsGuard guard;
stuckRun = false;
PlanDef plan_def = shouldStopWithCancelPlan();
Workspace ws;
Blob* blob = ws.CreateBlob("should_stop_blob");
Tensor* tensor = BlobGetMutableTensor(blob, CPU);
const vector<int64_t>& shape{1};
tensor->Resize(shape);
tensor->mutable_data<bool>()[0] = false;
// NOLINTNEXTLINE(cppcoreguidelines-avoid-goto,hicpp-avoid-goto)
ASSERT_THROW(ws.RunPlan(plan_def), TestError);
ASSERT_TRUE(stuckRun);
}
} // namespace caffe2
#endif
| 28.997712
| 103
| 0.716619
|
Gamrix
|
291f66c1a11ea1d00b7755300b31946c36e2775a
| 2,631
|
cpp
|
C++
|
Script/src/StardustScript.cpp
|
IridescentRose/Stardust-Engine
|
ee6a6b5841c16dddf367564a92eb263827631200
|
[
"MIT"
] | 55
|
2020-10-07T01:54:49.000Z
|
2022-03-26T11:39:11.000Z
|
Script/src/StardustScript.cpp
|
IridescentRose/Ionia
|
ee6a6b5841c16dddf367564a92eb263827631200
|
[
"MIT"
] | 15
|
2020-05-30T18:22:50.000Z
|
2020-08-08T11:01:36.000Z
|
Script/src/StardustScript.cpp
|
IridescentRose/Ionia
|
ee6a6b5841c16dddf367564a92eb263827631200
|
[
"MIT"
] | 6
|
2020-10-22T11:09:47.000Z
|
2022-01-07T13:10:09.000Z
|
#include <StardustScript.h>
#include <Platform/Platform.h>
#if CURRENT_PLATFORM == PLATFORM_PSP
#include <pspdebug.h>
#define pspDebugScreenPrintf printf
#else
#include <stdio.h>
#endif
#include <iostream>
namespace Stardust::Scripting {
static int lua_plat_init(lua_State* L) {
int argc = lua_gettop(L);
if (argc != 0)
return luaL_error(L, "Argument error: Platform.init() takes no argument.");
Platform::initPlatform();
return 0;
}
static int lua_plat_exit(lua_State* L) {
int argc = lua_gettop(L);
if (argc != 0)
return luaL_error(L, "Argument error: Platform.exit() takes no argument.");
Platform::exitPlatform();
return 0;
}
#if CURRENT_PLATFORM == PLATFORM_PSP
static int lua_print(lua_State* L)
{
pspDebugScreenInit();
pspDebugScreenSetXY(0, 0);
int argc = lua_gettop(L);
int n;
for (n = 1; n <= argc; n++) pspDebugScreenPrintf("%s\n", lua_tostring(L, n));
return 0;
}
#endif
static int lua_plat_update(lua_State* L) {
int argc = lua_gettop(L);
if (argc != 0)
return luaL_error(L, "Argument error: Platform.update() takes no argument.");
Platform::platformUpdate();
return 0;
}
static int lua_plat_delay(lua_State* L) {
int argc = lua_gettop(L);
if (argc != 1)
return luaL_error(L, "Argument error: Platform.delay() takes 1 argument (millis).");
int x = static_cast<int>(luaL_checkinteger(L, 1));
Platform::delayForMS(x);
return 0;
}
static const luaL_Reg platformLib[] {
{"init", lua_plat_init},
{"update", lua_plat_update},
{"exit", lua_plat_exit},
{"delay", lua_plat_delay},
{0, 0}
};
void initPlatformLib(lua_State* L) {
lua_getglobal(L, "Platform");
if (lua_isnil(L, -1)) {
lua_pop(L, 1);
lua_newtable(L);
}
luaL_setfuncs(L, platformLib, 0);
lua_setglobal(L, "Platform");
}
int status;
lua_State* L;
void initScripting() {
status = 0;
L = luaL_newstate();
luaL_openlibs(L);
#if CURRENT_PLATFORM == PLATFORM_PSP
lua_register(L, "print", lua_print);
#endif
initPlatformLib(L);
initScriptInputLib(L);
initScriptLoggingLib(L);
initScriptRenderLib(L);
initScriptTextureLib(L);
initScriptNetDriverLib(L);
}
void loadScript(std::string path) {
status = luaL_loadfile(L, path.c_str());
}
void callScript() {
status = lua_pcall(L, 0, LUA_MULTRET, 0);
if (status != 0) {
printf("error: %s\n", lua_tostring(L, -1));
#if CURRENT_PLATFORM == PLATFORM_PSP
pspDebugScreenInit();
pspDebugScreenSetXY(0, 0);
pspDebugScreenPrintf("error: %s\n", lua_tostring(L, -1));
#endif
lua_pop(L, 1); // remove error message
}
}
void cleanupScripting() {
lua_close(L);
}
}
| 21.743802
| 87
| 0.675789
|
IridescentRose
|
292213e9f206445c7583d299e36938a70f06dccb
| 887
|
cpp
|
C++
|
dp/lis_seg/lis.cpp
|
Takumi1122/data-structure-algorithm
|
6b9f26e4dbba981f034518a972ecfc698b86d837
|
[
"MIT"
] | null | null | null |
dp/lis_seg/lis.cpp
|
Takumi1122/data-structure-algorithm
|
6b9f26e4dbba981f034518a972ecfc698b86d837
|
[
"MIT"
] | null | null | null |
dp/lis_seg/lis.cpp
|
Takumi1122/data-structure-algorithm
|
6b9f26e4dbba981f034518a972ecfc698b86d837
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (n); ++i)
using namespace std;
using ll = long long;
using P = pair<int, int>;
// 最長増加部分列
// 計算量 o(nlog(n))
/*
参考リンク
AIZU ONLINE JUDGE
https://onlinejudge.u-aizu.ac.jp/problems/DPL_1_D
LIS でも大活躍! DP の配列使いまわしテクニックを特集
https://qiita.com/drken/items/68b8503ad4ffb469624c
*/
const ll INF = 1LL << 60;
// 最長増加部分列の長さを求める
int LIS(const vector<ll> &a) {
int n = (int)a.size();
vector<ll> dp(n, INF);
rep(i, n) {
// dp[k] >= a[i] となる最小のイテレータを見つける
auto it = lower_bound(dp.begin(), dp.end(), a[i]);
// そこを a[i] で書き換える
*it = a[i];
}
// dp[k] < INF となる最大の k に対して k+1 が答え
// それは dp[k] >= INF となる最小の k に一致する
return lower_bound(dp.begin(), dp.end(), INF) - dp.begin();
}
int main() {
int n;
cin >> n;
vector<ll> a(n);
rep(i, n) cin >> a[i];
cout << LIS(a) << endl;
}
| 19.282609
| 61
| 0.57159
|
Takumi1122
|
2924fcd702a37f927efc9d3d452ce60b7c8a1f5d
| 2,085
|
cpp
|
C++
|
Socket/Communication.cpp
|
Kaptnik/CIS-687-RemoteTestHarness
|
3a1466d4b71cef7bee2791020a2902d3e658fb64
|
[
"MIT"
] | null | null | null |
Socket/Communication.cpp
|
Kaptnik/CIS-687-RemoteTestHarness
|
3a1466d4b71cef7bee2791020a2902d3e658fb64
|
[
"MIT"
] | null | null | null |
Socket/Communication.cpp
|
Kaptnik/CIS-687-RemoteTestHarness
|
3a1466d4b71cef7bee2791020a2902d3e658fb64
|
[
"MIT"
] | null | null | null |
/////////////////////////////////////////////////////////////////////////////
// Communication.cpp - A class that encapsulates both a Sender and Receiver//
// ver 1.0 //
// Karthik Umashankar, CSE687 - Object Oriented Design, Summer 2018 //
/////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "Communication.h"
#include "IncomingMessageHandler.h"
using namespace Sockets;
// Constructor to set port to listen on
Communication::Communication(size_t port) : _receiver(port)
{
ProcessContext = Sockets::CONTEXT::SERVER;
}
// Constructor to set port to listen on & the context
Communication::Communication(size_t port, Sockets::CONTEXT context) : _receiver(port)
{
this->ProcessContext = context;
}
// Start the sender and the receiver
void Communication::Start()
{
IncomingMessageHandler *handler = new IncomingMessageHandler();
handler->SetContext(ProcessContext);
handler->SetSendMessageQueue(_sender.GetQueue());
handler->SetRecvMessageQueue(_receiver.GetQueue());
handler->SetTestRequestQueue(_testRequestQPtr);
handler->SetReadyWorkerQueue(_readyWorkerQPtr);
_sender.Start();
_receiver.Start(*handler);
}
// Stop the sender and the receiver
void Communication::Stop()
{
_receiver.Stop();
_sender.Stop();
}
// Set the test request queue
void Communication::SetTestRequestQueue(BlockingQueue<Message>* queuePointer)
{
_testRequestQPtr = queuePointer;
}
// Set the ready worker queue
void Communication::SetReadyWorkerQueue(BlockingQueue<Message>* queuePointer)
{
_readyWorkerQPtr = queuePointer;
}
// Fetch a pointer to the receiver queue
BlockingQueue<Message>* Communication::GetReceiverQueue()
{
return _receiver.GetQueue();
}
// Queue up a message in the sender's blocking queue
void Communication::DeliverMessage(Message message)
{
_sender.DeliverMessage(message);
}
// DeQueue a message from the receiver's blocking queue
Message Communication::CollectMessage()
{
return _receiver.CollectMessage();
}
| 28.561644
| 86
| 0.680576
|
Kaptnik
|
29286c1d6014c8c05b9951746e2f0781c259ccb7
| 5,274
|
cpp
|
C++
|
example/cluster.cpp
|
apppur/canna
|
bdcce4f16be56da40445fec79959b6bc90003573
|
[
"MIT"
] | null | null | null |
example/cluster.cpp
|
apppur/canna
|
bdcce4f16be56da40445fec79959b6bc90003573
|
[
"MIT"
] | null | null | null |
example/cluster.cpp
|
apppur/canna
|
bdcce4f16be56da40445fec79959b6bc90003573
|
[
"MIT"
] | null | null | null |
#include <pthread.h>
#include <stdio.h>
#include <string>
#include <vector>
#include <queue>
#include "canna_core.h"
#include "canna_random.h"
#include "zmq.hpp"
#define CLIENTS_NUM 10
#define WORKERS_NUM 5
#define WORKER_READY "READY"
static char *self;
static int serial = 0;
static void * client_task(void *args)
{
zmq::context_t context(1);
zmq::socket_t client(context, ZMQ_REQ);
char client_ipc[64] = {0};
sprintf(client_ipc, "ipc://%s-localfe.ipc", self);
client.connect(client_ipc);
zmq::socket_t monitor(context, ZMQ_PUSH);
char monitor_ipc[64] = {0};
sprintf(monitor_ipc, "ipc://%s-monitor.ipc", self);
monitor.connect(monitor_ipc);
while (true) {
canna_sleep(CANNA_RAND(5));
int burst = CANNA_RAND(15);
while (burst--) {
canna_send(client, "WORK");
zmq::pollitem_t pollset[1] = {{(void *)client, 0, ZMQ_POLLIN, 0}};
zmq::poll(pollset, 1, -1);
if (pollset[0].revents & ZMQ_POLLIN) {
std::string reply = canna_recv(client);
canna_send(monitor, reply);
} else {
canna_send(monitor, "E: CLIENT EXIT - lost task");
}
}
}
return nullptr;
}
static void * worker_task(void *args)
{
zmq::context_t context(1);
zmq::socket_t work(context, ZMQ_REQ);
//char uuid[16] = {0};
//sprintf(uuid, "work:%d", serial++);
//work.setsockopt(ZMQ_IDENTITY, uuid, 16);
char work_ipc[64] = {0};
sprintf(work_ipc, "ipc://%s-localbe.ipc", self);
work.connect(work_ipc);
canna_send(work, WORKER_READY);
while (true) {
std::string msg = canna_recv(work);
canna_sleep(CANNA_RAND(2));
}
return nullptr;
}
int main(int argc, char **argv)
{
if (argc < 2) {
printf("usage: cluster me {you} \n");
return 0;
}
self = argv[1];
printf("I: preparing broker at %s...\n", self);
zmq::context_t context(1);
zmq::socket_t localfe(context, ZMQ_ROUTER);
char localfe_ipc[64] = {0};
sprintf(localfe_ipc, "ipc://%s-localfe.ipc", self);
localfe.bind(localfe_ipc);
zmq::socket_t localbe(context, ZMQ_ROUTER);
char localbe_ipc[64] = {0};
sprintf(localbe_ipc, "ipc://%s-localbe.ipc", self);
localbe.bind(localbe_ipc);
zmq::socket_t cloudfe(context, ZMQ_ROUTER);
cloudfe.setsockopt(ZMQ_IDENTITY, self, strlen(self));
char cloudfe_ipc[64] = {0};
sprintf(cloudfe_ipc, "ipc://%s-cloud.ipc", self);
cloudfe.bind(cloudfe_ipc);
zmq::socket_t cloudbe(context, ZMQ_ROUTER);
cloudbe.setsockopt(ZMQ_IDENTITY, self, strlen(self));
char cloudbe_ipc[64] = {0};
sprintf(cloudbe_ipc, "ipc://%s-cloudbe.ipc", self);
for (int i = 2; i < argc; i++) {
char *peer = argv[i];
char peer_ipc[64] = {0};
sprintf(peer_ipc, "ipc://%s-cloud.ipc", peer);
printf("I: connecting to cloud frontend at '%s'\n", peer);
cloudbe.connect(peer_ipc);
}
zmq::socket_t statebe(context, ZMQ_PUB);
char statebe_ipc[64] = {0};
sprintf(statebe_ipc, "ipc://%s-state.ipc", self);
statebe.bind(statebe_ipc);
zmq::socket_t statefe(context, ZMQ_SUB);
const char *filter = "";
statefe.setsockopt(ZMQ_SUBSCRIBE, filter, strlen(filter));
for (int i = 2; i < argc; i++) {
char *peer = argv[i];
char peer_ipc[64] = {0};
sprintf(peer_ipc, "ipc://%s-state.ipc", peer);
statefe.connect(peer_ipc);
}
zmq::socket_t monitor(context, ZMQ_PULL);
char monitor_ipc[64] = {0};
sprintf(monitor_ipc, "ipc://%s-monitor.ipc", self);
monitor.bind(monitor_ipc);
for (int i = 0; i < WORKERS_NUM; i++) {
pthread_t pid;
pthread_create(&pid, nullptr, worker_task, nullptr);
}
for (int i = 0; i < CLIENTS_NUM; i++) {
pthread_t pid;
pthread_create(&pid, nullptr, client_task, nullptr);
}
std::queue<std::string> worker_queue;
while (true) {
zmq::pollitem_t pollset[] = {
{(void *)localbe, 0, ZMQ_POLLIN, 0},
{(void *)cloudbe, 0, ZMQ_POLLIN, 0},
{(void *)statefe, 0, ZMQ_POLLIN, 0},
{(void *)monitor, 0, ZMQ_POLLIN, 0},
};
if (worker_queue.size()) {
zmq::poll(pollset, 4, -1);
} else {
zmq::poll(pollset, 4, 1000);
}
if (pollset[0].revents & ZMQ_POLLIN) {
canna_dump(localbe);
std::string identity = canna_recv(localbe);
worker_queue.push(identity);
std::string empty = canna_recv(localbe);
std::string msg = canna_recv(localbe);
/*
if (msg == "READY") {
canna_sendmore(localbe, identity);
canna_sendmore(localbe, "");
canna_send(localbe, "GO");
}
*/
} else if (pollset[1].revents & ZMQ_POLLIN) {
canna_dump(cloudbe);
}
if (pollset[2].revents & ZMQ_POLLIN) {
}
if (pollset[3].revents & ZMQ_POLLIN) {
std::string status = canna_recv(monitor);
printf("%s\n", status.c_str());
}
canna_sleep(5000);
canna_send(cloudbe, "CLOUD");
}
}
| 28.354839
| 78
| 0.569776
|
apppur
|
2929d38f9a77d4eac67e50c5c8ca24b3d587cc12
| 3,007
|
cpp
|
C++
|
big-sort-lib/src/visualm.cpp
|
mvodya/BigSortCollection
|
d7b217d3ba8d712629c3b856bfb3e426525ca8b2
|
[
"MIT"
] | null | null | null |
big-sort-lib/src/visualm.cpp
|
mvodya/BigSortCollection
|
d7b217d3ba8d712629c3b856bfb3e426525ca8b2
|
[
"MIT"
] | null | null | null |
big-sort-lib/src/visualm.cpp
|
mvodya/BigSortCollection
|
d7b217d3ba8d712629c3b856bfb3e426525ca8b2
|
[
"MIT"
] | null | null | null |
#include "bigsortlib/visualm.h"
using namespace sortlib;
// Error callback for GLFW
void VisualModule::error_callback(int error, const char* description) {
printf("Error: %s\n", description);
}
// Key events callback from GLFW
void VisualModule::key_callback(GLFWwindow* window, int key, int scancode,
int action, int mods) {
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GLFW_TRUE);
}
// Main loop
void VisualModule::loop() {
while (!glfwWindowShouldClose(window)) {
int width, height;
glfwGetFramebufferSize(window, &width, &height);
glViewport(0, 0, width, height);
glClear(GL_COLOR_BUFFER_BIT);
// Draw circle
drawCircle();
glfwSwapBuffers(window);
glfwPollEvents();
}
// If loop end - remove this object
delete this;
}
// Color function
Color VisualModule::toColor(int& value) {
float r, g, b;
Color c;
// Calculate 3 color chanels by simple integer value
if (value > RT * 6) {
c.r = 1.0f;
c.b = 0;
c.g = 1.0f - (float)std::clamp(value - RT * 6, 0, RT) / RT;
} else if (value > RT * 4) {
c.r = (float)std::clamp(value - RT * 4, 0, RT) / RT;
c.b = 0;
c.g = 1.0f;
} else if (value > RT * 3) {
c.r = 0;
c.b = 1.0f - (float)std::clamp(value - RT * 3, 0, RT) / RT;
c.g = 1.0f;
} else if (value > RT * 2) {
c.r = 0;
c.b = 1.0f;
c.g = (float)std::clamp(value - RT * 2, 0, RT) / RT;
} else if (value > RT) {
c.r = 1.0f - (float)std::clamp(value - RT, 0, RT) / RT;
c.b = 1.0f;
c.g = 0;
} else if (value >= 0) {
c.r = 1.0f;
c.b = (float)std::clamp(value, 0, RT) / RT;
c.g = 0;
}
return c;
}
// Draw color circle
void VisualModule::drawCircle() {
// Crawling all items in a circle
for (int i = 0; i < size_; i++) {
glLineWidth(2.5);
// Set color
Color color = toColor(arr_[i]);
glColor3f(color.r, color.g, color.b);
// Draw line from center
glBegin(GL_LINES);
glVertex3f(0.0f, 0.0f, 0.0f);
glVertex3f(cos((float)i * PI / (size_ / 2)),
sin((float)i * PI / (size_ / 2)), 0.0);
glEnd();
}
}
VisualModule::VisualModule(std::string title, Function f, int* arr, int size) {
// Write pointer to function
function = f;
// Set array
arr_ = arr;
// Set size
size_ = size;
// Set GLFW error callback
glfwSetErrorCallback(error_callback);
// Init GLFW
if (!glfwInit()) exit(EXIT_FAILURE);
// Create window
window = glfwCreateWindow(640, 640, title.c_str(), NULL, NULL);
if (!window) {
glfwTerminate();
exit(EXIT_FAILURE);
}
// Set GLFW key events callback
glfwSetKeyCallback(window, key_callback);
glfwMakeContextCurrent(window);
glfwSwapInterval(1);
// Start function thread
thrFunction = new std::thread(function);
thrFunction->detach();
// Start main loop
loop();
}
VisualModule::~VisualModule() {
// Remove windows
glfwDestroyWindow(window);
// Stop GLFW
glfwTerminate();
}
| 24.25
| 79
| 0.602594
|
mvodya
|
29314c05f43ced8bb37ef5c5e05c2e3be6232407
| 13,126
|
hpp
|
C++
|
include/thread_pool.hpp
|
diharaw/dwThreadPool
|
cc21bf479f305897cd7e41ffc5c8968abb05455e
|
[
"MIT"
] | 25
|
2017-01-25T05:57:24.000Z
|
2021-11-21T18:29:27.000Z
|
include/thread_pool.hpp
|
diharaw/dwThreadPool
|
cc21bf479f305897cd7e41ffc5c8968abb05455e
|
[
"MIT"
] | null | null | null |
include/thread_pool.hpp
|
diharaw/dwThreadPool
|
cc21bf479f305897cd7e41ffc5c8968abb05455e
|
[
"MIT"
] | 5
|
2017-05-02T22:32:40.000Z
|
2021-09-21T19:42:59.000Z
|
#pragma once
#include <functional>
#include <thread>
#include <vector>
#include <atomic>
#include <algorithm>
#include <condition_variable>
#define MAX_TASKS 1024u
#define MAX_DEPENDENCIES 16u
#define MAX_CONTINUATIONS 16u
#define MASK MAX_TASKS - 1u
#define TASK_SIZE_BYTES 128
namespace dw
{
// -----------------------------------------------------------------------------------------------------------------------------------
class Semaphore
{
public:
Semaphore() : m_signal(false) {}
inline void notify()
{
std::unique_lock<std::mutex> lock(m_mutex);
m_signal = true;
m_condition.notify_all();
}
inline void wait()
{
std::unique_lock<std::mutex> lock(m_mutex);
m_condition.wait(lock, [&] { return m_signal; });
m_signal = false;
}
private:
Semaphore(const Semaphore &);
Semaphore & operator = (const Semaphore &);
std::mutex m_mutex;
std::condition_variable m_condition;
bool m_signal;
};
// -----------------------------------------------------------------------------------------------------------------------------------
struct Task
{
std::function<void(void*)> function;
char data[TASK_SIZE_BYTES];
std::atomic<uint16_t> num_pending;
uint16_t num_continuations;
uint16_t num_dependencies;
Task* dependencies[MAX_DEPENDENCIES];
Task* continuations[MAX_CONTINUATIONS];
};
// -----------------------------------------------------------------------------------------------------------------------------------
template <typename T>
inline T* task_data(Task* task)
{
return (T*)(&task->data[0]);
}
// -----------------------------------------------------------------------------------------------------------------------------------
struct WorkQueue
{
std::mutex m_critical_section;
Task m_task_pool[MAX_TASKS];
Task* m_task_queue[MAX_TASKS];
uint32_t m_front;
uint32_t m_back;
uint32_t m_num_tasks;
std::atomic<uint32_t> m_num_pending_tasks;
// -----------------------------------------------------------------------------------------------------------------------------------
WorkQueue()
{
m_num_tasks = 0;
m_num_pending_tasks = 0;
m_front = 0;
m_back = 0;
}
// -----------------------------------------------------------------------------------------------------------------------------------
~WorkQueue() {}
// -----------------------------------------------------------------------------------------------------------------------------------
Task* allocate()
{
uint32_t task_index = m_num_tasks++;
return &m_task_pool[task_index & (MAX_TASKS - 1u)];
}
// -----------------------------------------------------------------------------------------------------------------------------------
void push(Task* task)
{
std::lock_guard<std::mutex> lock(m_critical_section);
m_task_queue[m_back & MASK] = task;
++m_back;
m_num_pending_tasks++;
}
// -----------------------------------------------------------------------------------------------------------------------------------
Task* pop()
{
std::lock_guard<std::mutex> lock(m_critical_section);
const uint32_t job_count = m_back - m_front;
if (job_count <= 0)
return nullptr;
--m_back;
return m_task_queue[m_back & MASK];
}
// -----------------------------------------------------------------------------------------------------------------------------------
bool has_pending_tasks()
{
return (m_num_pending_tasks != 0);
}
// -----------------------------------------------------------------------------------------------------------------------------------
bool empty()
{
return (m_front == 0 && m_back == 0);
}
};
// -----------------------------------------------------------------------------------------------------------------------------------
struct WorkerThread
{
Semaphore m_wakeup;
Semaphore m_done;
std::thread m_thread;
// -----------------------------------------------------------------------------------------------------------------------------------
WorkerThread() {}
// -----------------------------------------------------------------------------------------------------------------------------------
WorkerThread(const WorkerThread &) {}
// -----------------------------------------------------------------------------------------------------------------------------------
~WorkerThread()
{
wakeup();
m_thread.join();
}
// -----------------------------------------------------------------------------------------------------------------------------------
void wakeup()
{
m_wakeup.notify();
}
};
// -----------------------------------------------------------------------------------------------------------------------------------
class ThreadPool
{
public:
// -----------------------------------------------------------------------------------------------------------------------------------
ThreadPool()
{
m_shutdown = false;
// get number of logical threads on CPU
m_num_logical_threads = std::thread::hardware_concurrency();
m_num_worker_threads = m_num_logical_threads;
initialize_workers();
}
// -----------------------------------------------------------------------------------------------------------------------------------
ThreadPool(uint32_t workers)
{
m_shutdown = false;
// get number of logical threads on CPU
m_num_logical_threads = std::thread::hardware_concurrency();
m_num_worker_threads = std::min(workers, m_num_logical_threads);
initialize_workers();
}
// -----------------------------------------------------------------------------------------------------------------------------------
~ThreadPool()
{
m_shutdown = true;
m_worker_threads.clear();
}
// -----------------------------------------------------------------------------------------------------------------------------------
inline Task* allocate()
{
Task* task_ptr = m_queue.allocate();
task_ptr->num_pending = 1;
task_ptr->num_continuations = 0;
task_ptr->num_dependencies = 0;
return task_ptr;
}
// -----------------------------------------------------------------------------------------------------------------------------------
inline void define_dependency(Task* child, Task* parent)
{
if (parent && child)
child->dependencies[child->num_dependencies++] = parent;
}
// -----------------------------------------------------------------------------------------------------------------------------------
inline void define_continuation(Task* parent, Task* continuation)
{
if (parent && continuation)
{
if (parent->num_continuations < MAX_CONTINUATIONS)
{
parent->continuations[parent->num_continuations] = continuation;
parent->num_continuations++;
}
}
}
// -----------------------------------------------------------------------------------------------------------------------------------
inline void enqueue(Task* task)
{
if (task)
{
m_queue.push(task);
for(uint32_t i = 0; i < m_num_worker_threads; i++)
{
WorkerThread& thread = m_worker_threads[i];
thread.wakeup();
}
}
}
// -----------------------------------------------------------------------------------------------------------------------------------
inline bool is_done(Task* task)
{
return task->num_pending == 0;
}
// -----------------------------------------------------------------------------------------------------------------------------------
inline void wait_for_all()
{
while (m_queue.has_pending_tasks())
{
Task* task = m_queue.pop();
if (task)
run_task(task);
}
}
// -----------------------------------------------------------------------------------------------------------------------------------
inline void wait_for_one(Task* pending_task)
{
while (pending_task->num_pending > 0)
{
Task* task = m_queue.pop();
if (task)
run_task(task);
}
}
// -----------------------------------------------------------------------------------------------------------------------------------
inline uint32_t num_logical_threads()
{
return m_num_logical_threads;
}
// -----------------------------------------------------------------------------------------------------------------------------------
inline uint32_t num_worker_threads()
{
return m_num_worker_threads;
}
// -----------------------------------------------------------------------------------------------------------------------------------
private:
// -----------------------------------------------------------------------------------------------------------------------------------
inline void initialize_workers()
{
// spawn worker threads
m_worker_threads.resize(m_num_worker_threads);
for (uint32_t i = 0; i < m_num_worker_threads; i++)
m_worker_threads[i].m_thread = std::thread(&ThreadPool::worker, this, i);
}
// -----------------------------------------------------------------------------------------------------------------------------------
inline void worker(uint32_t index)
{
WorkerThread& worker_thread = m_worker_threads[index];
while (!m_shutdown)
{
Task* task = m_queue.pop();
if (!task)
{
worker_thread.m_done.notify();
worker_thread.m_wakeup.wait();
}
else
run_task(task);
}
}
// -----------------------------------------------------------------------------------------------------------------------------------
inline void run_task(Task* task)
{
// Wait untill all of dependent tasks are done
wait_for_dependencies(task);
// Execute the current task
task->function(task->data);
// Submit continuation tasks.
for (uint32_t i = 0; i < task->num_continuations; i++)
enqueue(task->continuations[i]);
if (task->num_pending > 0)
task->num_pending--;
if (m_queue.m_num_pending_tasks > 0)
m_queue.m_num_pending_tasks--;
}
// -----------------------------------------------------------------------------------------------------------------------------------
inline void wait_for_dependencies(Task* task)
{
if (task->num_dependencies > 0)
{
for (uint32_t i = 0; i < task->num_dependencies; i++)
{
while (task->dependencies[i]->num_pending > 0)
{
Task* wait_task = m_queue.pop();
if (wait_task)
run_task(wait_task);
}
}
}
}
// -----------------------------------------------------------------------------------------------------------------------------------
private:
bool m_shutdown;
uint32_t m_num_logical_threads;
WorkQueue m_queue;
std::vector<WorkerThread> m_worker_threads;
uint32_t m_num_worker_threads;
};
} // namespace dw
| 32.897243
| 135
| 0.30192
|
diharaw
|
a09599afe4816fdb13c6ccd94d5cc5f7c097eb16
| 3,229
|
cpp
|
C++
|
example/decomp/main.cpp
|
pdobrowo/libcs2
|
25d8bfeadcf3eff6be34caa85000a00e41b3b57e
|
[
"MIT"
] | null | null | null |
example/decomp/main.cpp
|
pdobrowo/libcs2
|
25d8bfeadcf3eff6be34caa85000a00e41b3b57e
|
[
"MIT"
] | null | null | null |
example/decomp/main.cpp
|
pdobrowo/libcs2
|
25d8bfeadcf3eff6be34caa85000a00e41b3b57e
|
[
"MIT"
] | null | null | null |
/**
* Copyright (c) 2015-2019 Przemysław Dobrowolski
*
* This file is part of the Configuration Space Library (libcs2), a library
* for creating configuration spaces of various motion planning problems.
*
* 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 "../../plugin/decomp/decomp3f.h"
#include "cs2/plugin.h"
#include "cs2/timer.h"
#include <cstdio>
#include <cstdlib>
void load_mesh(struct decompmesh3f_s *m, const char *fp)
{
int vs, fs, i, j;
FILE *f = fopen(fp, "r");
if (!f)
return;
if (fscanf(f, "%*s%d%d%*d",&vs,&fs) != 2)
return;
m->v = (struct cs2_vec3f_s *)malloc(sizeof(struct cs2_vec3f_s) * vs);
m->vs = vs;
for (i = 0; i < vs; ++i)
if (fscanf(f, "%lf%lf%lf", &m->v[i].x, &m->v[i].y, &m->v[i].z) != 3)
return;
m->f = (struct decompface3f_s *)malloc(sizeof(struct decompface3f_s) * fs);
m->fs = fs;
for (i = 0; i < fs; ++i)
{
int is;
if (fscanf(f, "%d", &is) != 1)
return;
m->f[i].i = (size_t *)malloc(sizeof(size_t) * is);
m->f[i].is = is;
for (j = 0; j < is; ++j)
{
double x;
if (fscanf(f, "%lf", &x) != 1)
return;
m->f[i].i[j] = x;
}
}
fclose(f);
}
int main()
{
// decomp
cs2_plugin_ldpath(".");
void *pl = cs2_plugin_load("libdecomp.so");
if (!pl)
{
printf("missing plugin\n");
return 1;
}
decomp3f_init_f pl_init = (decomp3f_init_f)cs2_plugin_func(pl, DECOMP3F_INIT_F_SYM);
decomp3f_make_f pl_make = (decomp3f_make_f)cs2_plugin_func(pl, DECOMP3F_MAKE_F_SYM);
decomp3f_clear_f pl_clear = (decomp3f_clear_f)cs2_plugin_func(pl, DECOMP3F_CLEAR_F_SYM);
struct decomp3f_s d;
struct decompmesh3f_s dm;
load_mesh(&dm, "../data/mushroom.off");
pl_init(&d);
uint64_t start = cs2_timer_usec();
pl_make(&d, &dm);
uint64_t end = cs2_timer_usec();
printf("decomposition took %lu usecs; sub-meshes: %d\n", static_cast<unsigned long>(end - start), static_cast<int>(d.ms));
pl_clear(&d);
cs2_plugin_unload(pl);
free(dm.f);
free(dm.v);
return 0;
}
| 27.598291
| 126
| 0.631155
|
pdobrowo
|
a09719e6e27cd69a7d37181d29ea9ed037e9205f
| 2,866
|
cpp
|
C++
|
src/scan.cpp
|
Licmeth/pixiple
|
1871124ef2d9d2384cb384095f14d71c5664f62b
|
[
"MIT"
] | 50
|
2019-01-24T16:23:05.000Z
|
2021-12-29T17:38:07.000Z
|
src/scan.cpp
|
Licmeth/pixiple
|
1871124ef2d9d2384cb384095f14d71c5664f62b
|
[
"MIT"
] | 5
|
2016-12-26T16:54:38.000Z
|
2018-09-28T23:59:26.000Z
|
src/scan.cpp
|
Licmeth/pixiple
|
1871124ef2d9d2384cb384095f14d71c5664f62b
|
[
"MIT"
] | 13
|
2019-08-03T07:41:02.000Z
|
2022-03-10T05:59:40.000Z
|
#include "shared.h"
#include "image.h"
#include "window.h"
#include "shared/com.h"
#include <filesystem>
#include <string>
#include <vector>
#include <ShlObj.h>
static bool is_image(const std::wstring& filename) {
const std::wstring extensions[] {
L".jpg", L".jpe", L".jpeg",
L".png", L".gif", L".bmp"
L".tif", L".tiff",
L".jxr", L".hdp", L".wdp"};
for (const auto& e : extensions) {
if (filename.length() >= e.length()) {
auto filename_e = filename.substr(filename.length() - e.length(), e.length());
if (_wcsicmp(filename_e.c_str(), e.c_str()) == 0)
return true;
}
}
return false;
}
std::vector<std::filesystem::path> scan(Window& window, const std::vector<ComPtr<IShellItem>>& shell_items) {
window.add_edge(0);
window.add_edge(0);
window.add_edge(1);
window.add_edge(1);
window.add_edge(0.5f);
window.add_edge();
window.add_edge();
window.add_edge();
const auto mx = 12.0f;
const auto my = 8.0f;
const auto margin = D2D1::RectF(mx, my, mx, my);
const auto background = Colour{0xfff8f8f8};
window.add_pane(0, 5, 2, 4, margin, false, true, background);
window.set_progressbar_progress(0, -1.0f);
window.add_pane(0, 4, 2, 6, margin, false, true, background);
window.set_text(1, L"Scanning folders for images", {}, true);
window.add_pane(0, 6, 2, 7, margin, false, true, background);
window.add_button(2, 0, L"Cancel");
window.add_pane(0, 1, 2, 5, margin, false, false, background);
window.add_pane(0, 7, 2, 3, margin, false, false, background);
std::vector<std::filesystem::path> paths;
auto items = shell_items;
while (!items.empty()) {
auto item = items.back();
items.pop_back();
SFGAOF a;
er = item->GetAttributes(
SFGAO_HIDDEN | SFGAO_FILESYSANCESTOR | SFGAO_FOLDER | SFGAO_FILESYSTEM, &a);
// skip if not file or folder or if hidden
if (!(a & SFGAO_FILESYSTEM || a & SFGAO_FILESYSANCESTOR) || a & SFGAO_HIDDEN)
continue;
if (a & SFGAO_FOLDER) {
// folder
ComPtr<IEnumShellItems> item_enum;
er = item->BindToHandler(nullptr, BHID_EnumItems, IID_PPV_ARGS(&item_enum));
ComPtr<IShellItem> i;
while (item_enum->Next(1, &i, nullptr) == S_OK)
items.push_back(i);
} else {
// file
LPWSTR path;
er = item->GetDisplayName(SIGDN_FILESYSPATH, &path);
if (is_image(path))
paths.push_back(path);
CoTaskMemFree(path);
}
while (window.has_event()) {
auto e = window.get_event();
if (e.type == Event::Type::quit || e.type == Event::Type::button)
return {};
}
}
window.set_text(1, L"Removing duplicate paths", {}, true);
window.has_event();
std::sort(paths.begin(), paths.end());
paths.erase(std::unique(paths.begin(), paths.end()), paths.end());
window.set_text(1, L"", {}, true);
window.has_event();
return paths;
}
| 27.037736
| 110
| 0.634682
|
Licmeth
|
a0a146e2ea796883df57f49876eed2eb8fc153e3
| 480
|
cpp
|
C++
|
CS Academy/CS Academy - Travel Distance.cpp
|
akash246/Competitive-Programming-Solutions
|
68db69ba8a771a433e5338bc4e837a02d3f89823
|
[
"MIT"
] | 28
|
2017-11-08T11:52:11.000Z
|
2021-07-16T06:30:02.000Z
|
CS Academy/CS Academy - Travel Distance.cpp
|
akash246/Competitive-Programming-Solutions
|
68db69ba8a771a433e5338bc4e837a02d3f89823
|
[
"MIT"
] | null | null | null |
CS Academy/CS Academy - Travel Distance.cpp
|
akash246/Competitive-Programming-Solutions
|
68db69ba8a771a433e5338bc4e837a02d3f89823
|
[
"MIT"
] | 30
|
2017-09-01T09:14:27.000Z
|
2021-04-12T12:08:56.000Z
|
#include <iostream>
#include <string>
using namespace std;
int ABS(int n){
return n < 0 ? -1*n : n;
}
int main() {
string s;
cin>>s;
int r = 0;
int c = 0;
for(char ch : s){
if(ch == 'W'){
c--;
}
else if(ch == 'E'){
c++;
}
else if(ch == 'S'){
r++;
}
else{
r--;
}
}
cout<< ABS(r)+ABS(c) <<endl;
return 0;
}
| 13.333333
| 32
| 0.329167
|
akash246
|
a0a943b6d751922662c9f8c8d73eeba4399918b4
| 5,461
|
cpp
|
C++
|
src/game_api/script/usertypes/entities_activefloors_lua.cpp
|
jaythebusinessgoose/overlunky
|
12d8ee353fda01a53d2aa753b539319ed41d940e
|
[
"MIT"
] | 56
|
2020-11-17T06:13:55.000Z
|
2022-03-05T19:21:25.000Z
|
src/game_api/script/usertypes/entities_activefloors_lua.cpp
|
jaythebusinessgoose/overlunky
|
12d8ee353fda01a53d2aa753b539319ed41d940e
|
[
"MIT"
] | 99
|
2020-11-19T15:29:59.000Z
|
2022-03-28T21:12:50.000Z
|
src/game_api/script/usertypes/entities_activefloors_lua.cpp
|
jaythebusinessgoose/overlunky
|
12d8ee353fda01a53d2aa753b539319ed41d940e
|
[
"MIT"
] | 47
|
2020-11-20T03:34:52.000Z
|
2022-02-22T17:48:02.000Z
|
#include "entities_activefloors_lua.hpp"
#include "entities_activefloors.hpp"
#include <sol/sol.hpp>
namespace NEntitiesActiveFloors
{
void register_usertypes(sol::state& lua)
{
lua["Entity"]["as_crushtrap"] = &Entity::as<Crushtrap>;
lua["Entity"]["as_olmec"] = &Entity::as<Olmec>;
lua["Entity"]["as_woodenlogtrap"] = &Entity::as<WoodenlogTrap>;
lua["Entity"]["as_boulder"] = &Entity::as<Boulder>;
lua["Entity"]["as_pushblock"] = &Entity::as<PushBlock>;
lua["Entity"]["as_boneblock"] = &Entity::as<BoneBlock>;
lua["Entity"]["as_chainedpushblock"] = &Entity::as<ChainedPushBlock>;
lua["Entity"]["as_lightarrowplatform"] = &Entity::as<LightArrowPlatform>;
lua["Entity"]["as_fallingplatform"] = &Entity::as<FallingPlatform>;
lua["Entity"]["as_unchainedspikeball"] = &Entity::as<UnchainedSpikeBall>;
lua["Entity"]["as_drill"] = &Entity::as<Drill>;
lua["Entity"]["as_thinice"] = &Entity::as<ThinIce>;
lua["Entity"]["as_elevator"] = &Entity::as<Elevator>;
lua["Entity"]["as_clambase"] = &Entity::as<ClamBase>;
lua["Entity"]["as_regenblock"] = &Entity::as<RegenBlock>;
lua["Entity"]["as_timedpowderkeg"] = &Entity::as<TimedPowderkeg>;
lua.new_usertype<Crushtrap>(
"Crushtrap",
"dirx",
&Crushtrap::dirx,
"diry",
&Crushtrap::diry,
"timer",
&Crushtrap::timer,
"bounce_back_timer",
&Crushtrap::bounce_back_timer,
sol::base_classes,
sol::bases<Entity, Movable>());
lua.new_usertype<Olmec>(
"Olmec",
"target_uid",
&Olmec::target_uid,
"attack_phase",
&Olmec::attack_phase,
"attack_timer",
&Olmec::attack_timer,
"ai_timer",
&Olmec::ai_timer,
"move_direction",
&Olmec::move_direction,
"jump_timer",
&Olmec::jump_timer,
"phase1_amount_of_bomb_salvos",
&Olmec::phase1_amount_of_bomb_salvos,
"unknown_attack_state",
&Olmec::unknown_attack_state,
"broken_floaters",
&Olmec::broken_floaters,
sol::base_classes,
sol::bases<Entity, Movable>());
lua.new_usertype<WoodenlogTrap>(
"WoodenlogTrap",
"ceiling_1_uid",
&WoodenlogTrap::ceiling_1_uid,
"ceiling_2_uid",
&WoodenlogTrap::ceiling_2_uid,
"falling_speed",
&WoodenlogTrap::falling_speed,
sol::base_classes,
sol::bases<Entity, Movable>());
lua.new_usertype<Boulder>(
"Boulder",
"is_rolling",
&Boulder::is_rolling,
sol::base_classes,
sol::bases<Entity, Movable>());
lua.new_usertype<PushBlock>(
"PushBlock",
"dust_particle",
&PushBlock::dust_particle,
"dest_pos_x",
&PushBlock::dest_pos_x,
sol::base_classes,
sol::bases<Entity, Movable>());
lua.new_usertype<BoneBlock>(
"BoneBlock",
sol::base_classes,
sol::bases<Entity, Movable>());
lua.new_usertype<ChainedPushBlock>(
"ChainedPushBlock",
"is_chained",
&ChainedPushBlock::is_chained,
sol::base_classes,
sol::bases<Entity, Movable, PushBlock>());
lua.new_usertype<LightArrowPlatform>(
"LightArrowPlatform",
"emitted_light",
&LightArrowPlatform::emitted_light,
sol::base_classes,
sol::bases<Entity, Movable>());
lua.new_usertype<FallingPlatform>(
"FallingPlatform",
"emitted_light",
&FallingPlatform::timer,
"timer",
&FallingPlatform::timer,
"shaking_factor",
&FallingPlatform::shaking_factor,
"y_pos",
&FallingPlatform::y_pos,
sol::base_classes,
sol::bases<Entity, Movable>());
lua.new_usertype<UnchainedSpikeBall>(
"UnchainedSpikeBall",
"bounce",
&UnchainedSpikeBall::bounce,
sol::base_classes,
sol::bases<Entity, Movable>());
lua.new_usertype<Drill>(
"Drill",
"top_chain_piece",
&Drill::top_chain_piece,
"trigger",
&Drill::trigger,
sol::base_classes,
sol::bases<Entity, Movable>());
lua.new_usertype<ThinIce>(
"ThinIce",
"strength",
&ThinIce::strength,
sol::base_classes,
sol::bases<Entity, Movable>());
lua.new_usertype<Elevator>(
"Elevator",
"emitted_light",
&Elevator::emitted_light,
"timer",
&Elevator::timer,
"moving_up",
&Elevator::moving_up,
sol::base_classes,
sol::bases<Entity, Movable>());
lua.new_usertype<ClamBase>(
"ClamBase",
"treasure_type",
&ClamBase::treasure_type,
"treasure_uid",
&ClamBase::treasure_uid,
"treasure_x_pos",
&ClamBase::treasure_x_pos,
"treasure_y_pos",
&ClamBase::treasure_y_pos,
"top_part_uid",
&ClamBase::top_part_uid,
sol::base_classes,
sol::bases<Entity, Movable>());
lua.new_usertype<RegenBlock>(
"RegenBlock",
"on_breaking",
&RegenBlock::on_breaking,
sol::base_classes,
sol::bases<Entity, Movable>());
lua.new_usertype<TimedPowderkeg>(
"TimedPowderkeg",
"timer",
&TimedPowderkeg::timer,
sol::base_classes,
sol::bases<Entity, Movable, PushBlock>());
}
} // namespace NEntitiesActiveFloors
| 29.203209
| 77
| 0.592749
|
jaythebusinessgoose
|
a0a9a49fb7cee4cc982a83c5c96147b1ce9a9eeb
| 7,121
|
cpp
|
C++
|
GameEngineArchitecture/source/Model.cpp
|
Cubes58/Team_NoName_GameEngine
|
5b1f75a61c43a1e1649b5a34a799aab65af70afd
|
[
"MIT"
] | null | null | null |
GameEngineArchitecture/source/Model.cpp
|
Cubes58/Team_NoName_GameEngine
|
5b1f75a61c43a1e1649b5a34a799aab65af70afd
|
[
"MIT"
] | null | null | null |
GameEngineArchitecture/source/Model.cpp
|
Cubes58/Team_NoName_GameEngine
|
5b1f75a61c43a1e1649b5a34a799aab65af70afd
|
[
"MIT"
] | null | null | null |
#include "Model.h"
#include <assimp/postprocess.h>
#include <stb_image/stb_image.h>
#include <iostream>
Model::Model(std::string p_FilePath) {
LoadModel(p_FilePath);
}
Model::Model(const std::string &p_FilePath, bool &p_ModelLoaded) {
p_ModelLoaded = LoadModel(p_FilePath);
}
void Model::Render(const unsigned int p_ShaderProgram) {
for (auto mesh : m_Meshes) {
mesh.Render(p_ShaderProgram);
}
}
bool Model::LoadModel(std::string p_FilePath) {
Assimp::Importer import;
const aiScene *scene = import.ReadFile(p_FilePath, aiProcess_Triangulate | aiProcess_FlipUVs);
if (!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) {
std::cout << "ERROR::ASSIMP::" << import.GetErrorString() << std::endl;
return false;
}
m_Directory = p_FilePath.substr(0, p_FilePath.find_last_of('/'));
ProcessNode(scene->mRootNode, scene);
return true;
}
void Model::ProcessNode(aiNode *p_Node, const aiScene *p_Scene) {
// Get the meshes of the node and add them to our vector.
for (int i = 0; i < p_Node->mNumMeshes; i++) {
int sceneMeshIndex = p_Node->mMeshes[i];
aiMesh* mesh = p_Scene->mMeshes[sceneMeshIndex];
m_Meshes.push_back(ProcessMesh(mesh, p_Scene));
}
// Recursively process the nodes of any children.
for (int i = 0; i < p_Node->mNumChildren; i++) {
ProcessNode(p_Node->mChildren[i], p_Scene);
}
}
Mesh Model::ProcessMesh(aiMesh *p_Mesh, const aiScene *p_Scene) {
// Data to fill.
std::vector<Vertex> vertices;
std::vector<unsigned int> indices;
std::vector<Texture> textures;
// Create enough space for the vertices and indices.
vertices.resize(p_Mesh->mNumVertices);
indices.resize(p_Mesh->mNumFaces * 3); // Imported as triangles.
// For each vertex of the mesh copy the data to out own mesh format.
for (unsigned int i = 0; i < p_Mesh->mNumVertices; i++) {
// All meshes should have vertices and normals.
vertices[i].m_Position = glm::vec3(p_Mesh->mVertices[i].x, p_Mesh->mVertices[i].y, p_Mesh->mVertices[i].z);
vertices[i].m_Normal = glm::vec3(p_Mesh->mNormals[i].x, p_Mesh->mNormals[i].y, p_Mesh->mNormals[i].z);
// Check if the mesh has texture coordinates.
if (p_Mesh->mTextureCoords[0]) {
vertices[i].m_TextureCoordinates = glm::vec2(p_Mesh->mTextureCoords[0][i].x, p_Mesh->mTextureCoords[0][i].y);
}
else {
vertices[i].m_TextureCoordinates = glm::vec2(0.0f, 0.0f);
}
}
// Save all the vertex indices in the indices vector.
for (int i = 0; i < p_Mesh->mNumFaces; i++) {
// Retrieve all indices of the face and store them in the indices vector.
for (int j = 0; j < p_Mesh->mFaces[i].mNumIndices; j++)
indices[3 * i + j] = p_Mesh->mFaces[i].mIndices[j];
}
// Get material textures (if there are any).
if (p_Mesh->mMaterialIndex >= 0) {
aiMaterial* material = p_Scene->mMaterials[p_Mesh->mMaterialIndex];
std::vector<Texture> diffuseMaps = LoadMaterialTextures(material, aiTextureType_DIFFUSE, "texture_diffuse");
std::vector<Texture> specularMaps = LoadMaterialTextures(material, aiTextureType_SPECULAR, "texture_specular");
std::vector<Texture> normalMaps = LoadMaterialTextures(material, aiTextureType_NORMALS, "texture_normal");
std::vector<Texture> heightMaps = LoadMaterialTextures(material, aiTextureType_HEIGHT, "texture_height");
// Put all the textures together in a single vector.
textures.insert(textures.end(), diffuseMaps.begin(), diffuseMaps.end());
textures.insert(textures.end(), specularMaps.begin(), specularMaps.end());
textures.insert(textures.end(), normalMaps.begin(), normalMaps.end());
textures.insert(textures.end(), heightMaps.begin(), heightMaps.end());
}
// Return the mesh data.
return Mesh(vertices, indices, textures);
}
std::vector<Texture> Model::LoadMaterialTextures(aiMaterial *p_Material, aiTextureType p_Type, std::string p_TypeName) {
std::vector<Texture> textures;
for (int i = 0; i < p_Material->GetTextureCount(p_Type); i++) {
aiString str;
p_Material->GetTexture(p_Type, i, &str);
bool b_loadedTexture = false;
for (auto texture : m_Textures) {
if (std::strcmp(texture.p_FilePath.C_Str(), str.C_Str()) == 0) {
textures.push_back(texture);
b_loadedTexture = true;
break;
}
}
if (!b_loadedTexture) {
// Setup a new texture.
Texture texture;
texture.m_ID = TextureFromFile(str.C_Str(), m_Directory);
texture.m_Type = p_TypeName;
texture.p_FilePath = str;
textures.push_back(texture);
m_Textures.push_back(texture); // Add to loaded textures.
}
}
return textures;
}
// Static function to load a texture using lightweight stb_image library.
unsigned int Model::TextureFromFile(const char *p_FilePath, const std::string &p_Directory, bool p_Gamma) {
std::string filename = std::string(p_FilePath);
filename = p_Directory + '/' + filename;
unsigned int textureID;
glGenTextures(1, &textureID);
int width, height, nrComponents;
unsigned char* textureData = stbi_load(filename.c_str(), &width, &height, &nrComponents, 0);
if (textureData) {
GLenum format;
if (nrComponents == 1)
format = GL_RED;
else if (nrComponents == 3)
format = GL_RGB;
else if (nrComponents == 4)
format = GL_RGBA;
glBindTexture(GL_TEXTURE_2D, textureID);
glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, textureData);
glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
stbi_image_free(textureData);
}
else {
std::cout << "Texture failed to load from: " << p_FilePath << std::endl;
stbi_image_free(textureData);
}
return textureID;
}
unsigned int Model::TextureCubeFromFile(std::vector<const char*> p_FilePath, const std::string & p_Directory, bool p_Gamma)
{
unsigned int l_textureID;
glGenTextures(1, &l_textureID);
glBindTexture(GL_TEXTURE_CUBE_MAP, l_textureID);
int l_ImageWidth, l_ImageHeight, l_NrComponents;
unsigned char* l_TextureData;
for (GLuint i = 0; i < p_FilePath.size(); i++)
{
l_TextureData = stbi_load(p_FilePath[i], &l_ImageWidth, &l_ImageHeight, &l_NrComponents, 0);
if (l_TextureData)
{
GLenum format;
if (l_NrComponents == 1)
format = GL_RED;
else if (l_NrComponents == 3)
format = GL_RGB;
else if (l_NrComponents == 4)
format = GL_RGBA;
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, format, l_ImageWidth, l_ImageHeight, 0, format, GL_UNSIGNED_BYTE, l_TextureData);
}
else
{
std::cout << "Texture failed to load from: " << p_FilePath[i] << std::endl;
}
stbi_image_free(l_TextureData);
}
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
return l_textureID;
}
| 35.078818
| 136
| 0.728409
|
Cubes58
|
a0ab9189b149658c98ac880cfd7f32e3c8c1c797
| 901
|
cpp
|
C++
|
src/rogue_game/display/player_display.cpp
|
tanacchi/rogue_game
|
fd8f655f95932513f6aa63e0c413bbe110a4418a
|
[
"MIT"
] | 10
|
2018-09-13T14:47:07.000Z
|
2022-01-10T11:46:12.000Z
|
src/rogue_game/display/player_display.cpp
|
tanacchi/rogue_game
|
fd8f655f95932513f6aa63e0c413bbe110a4418a
|
[
"MIT"
] | 13
|
2018-09-18T19:36:32.000Z
|
2020-11-12T16:26:22.000Z
|
src/rogue_game/display/player_display.cpp
|
tanacchi/rogue_game
|
fd8f655f95932513f6aa63e0c413bbe110a4418a
|
[
"MIT"
] | null | null | null |
#include <display/player_display.hpp>
#include <utility/point.hpp>
#include <character/player.hpp>
PlayerDisplay::PlayerDisplay(std::size_t x, std::size_t y,
std::size_t width, std::size_t height)
: DisplayPanel(x, y, width, height)
{
}
void PlayerDisplay::show(const Player& player)
{
werase(win_.get());
const auto& pos{player.position_};
const auto& dir{player.direction_};
mvwprintw(win_.get(), 0, 0, "Position: ");
mvwprintw(win_.get(), 1, 2, "x: %d", pos.get_x());
mvwprintw(win_.get(), 2, 2, "y: %d", pos.get_y());
mvwprintw(win_.get(), 3, 0, "Direction: ");
mvwprintw(win_.get(), 4, 2, "dx: %d", dir.get_x());
mvwprintw(win_.get(), 5, 2, "dy: %d", dir.get_y());
mvwprintw(win_.get(), 6, 0, "money: %d", player.money_);
mvwprintw(win_.get(), 7, 0, "HP: %d (max: %d)", player.hit_point_, player.max_hit_point_);
wrefresh(win_.get());
}
| 32.178571
| 92
| 0.624861
|
tanacchi
|
a0b3efc0567d853a1c4a45b3551140878fcc8554
| 44,404
|
cpp
|
C++
|
nao_dcm_robot/nao_dcm_driver/src/nao.cpp
|
costashatz/nao_dcm
|
b3fc8656e5e8cc4cd354effa203a8cdfd926bf7c
|
[
"BSD-3-Clause"
] | 10
|
2015-02-14T04:42:48.000Z
|
2022-02-28T17:35:38.000Z
|
nao_dcm_robot/nao_dcm_driver/src/nao.cpp
|
costashatz/nao_dcm
|
b3fc8656e5e8cc4cd354effa203a8cdfd926bf7c
|
[
"BSD-3-Clause"
] | 2
|
2015-03-09T14:59:00.000Z
|
2016-04-08T16:50:50.000Z
|
nao_dcm_robot/nao_dcm_driver/src/nao.cpp
|
costashatz/nao_dcm
|
b3fc8656e5e8cc4cd354effa203a8cdfd926bf7c
|
[
"BSD-3-Clause"
] | 6
|
2015-05-21T02:09:30.000Z
|
2021-04-27T14:26:58.000Z
|
/**
Copyright (c) 2014-2015, Konstantinos Chatzilygeroudis
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**/
#include <iostream>
#include "nao_dcm_driver/nao.h"
#include <alerror/alerror.h>
#include <alcommon/albroker.h>
#include <algorithm>
Nao::Nao(boost::shared_ptr<AL::ALBroker> broker, const string &name)
: AL::ALModule(broker,name),is_connected_(false)
{
setModuleDescription("Nao Robot Module");
functionName("brokerDisconnected", getName(), "Callback when broker disconnects!");
BIND_METHOD(Nao::brokerDisconnected);
}
Nao::~Nao()
{
if(is_connected_)
disconnect();
}
bool Nao::initialize()
{
// IMU Memory Keys
const char* imu[] = {"Device/SubDeviceList/InertialSensor/AngleX/Sensor/Value",
"Device/SubDeviceList/InertialSensor/AngleY/Sensor/Value",
"Device/SubDeviceList/InertialSensor/AngleZ/Sensor/Value",
"Device/SubDeviceList/InertialSensor/GyroscopeX/Sensor/Value",
"Device/SubDeviceList/InertialSensor/GyroscopeY/Sensor/Value",
"Device/SubDeviceList/InertialSensor/GyroscopeZ/Sensor/Value",
"Device/SubDeviceList/InertialSensor/AccelerometerX/Sensor/Value",
"Device/SubDeviceList/InertialSensor/AccelerometerY/Sensor/Value",
"Device/SubDeviceList/InertialSensor/AccelerometerZ/Sensor/Value"};
imu_names_ = vector<string>(imu, end(imu));
// Sonar Memory Keys
const char* sonar[] = {"Device/SubDeviceList/US/Left/Sensor/Value",
"Device/SubDeviceList/US/Left/Sensor/Value1",
"Device/SubDeviceList/US/Left/Sensor/Value2",
"Device/SubDeviceList/US/Left/Sensor/Value3",
"Device/SubDeviceList/US/Left/Sensor/Value4",
"Device/SubDeviceList/US/Left/Sensor/Value5",
"Device/SubDeviceList/US/Left/Sensor/Value6",
"Device/SubDeviceList/US/Left/Sensor/Value7",
"Device/SubDeviceList/US/Left/Sensor/Value8",
"Device/SubDeviceList/US/Left/Sensor/Value9",
"Device/SubDeviceList/US/Right/Sensor/Value",
"Device/SubDeviceList/US/Right/Sensor/Value1",
"Device/SubDeviceList/US/Right/Sensor/Value2",
"Device/SubDeviceList/US/Right/Sensor/Value3",
"Device/SubDeviceList/US/Right/Sensor/Value4",
"Device/SubDeviceList/US/Right/Sensor/Value5",
"Device/SubDeviceList/US/Right/Sensor/Value6",
"Device/SubDeviceList/US/Right/Sensor/Value7",
"Device/SubDeviceList/US/Right/Sensor/Value8",
"Device/SubDeviceList/US/Right/Sensor/Value9"};
sonar_names_ = vector<string>(sonar, end(sonar));
// Foot Contact Memory Keys
const char* fsr[] = {"Device/SubDeviceList/LFoot/FSR/FrontLeft/Sensor/Value",
"Device/SubDeviceList/LFoot/FSR/FrontRight/Sensor/Value",
"Device/SubDeviceList/LFoot/FSR/RearLeft/Sensor/Value",
"Device/SubDeviceList/LFoot/FSR/RearRight/Sensor/Value",
"Device/SubDeviceList/LFoot/FSR/TotalWeight/Sensor/Value",
"Device/SubDeviceList/RFoot/FSR/FrontLeft/Sensor/Value",
"Device/SubDeviceList/RFoot/FSR/FrontRight/Sensor/Value",
"Device/SubDeviceList/RFoot/FSR/RearLeft/Sensor/Value",
"Device/SubDeviceList/RFoot/FSR/RearRight/Sensor/Value",
"Device/SubDeviceList/RFoot/FSR/TotalWeight/Sensor/Value",
"Device/SubDeviceList/LFoot/FSR/CenterOfPressure/X/Sensor/Value",
"Device/SubDeviceList/LFoot/FSR/CenterOfPressure/Y/Sensor/Value",
"Device/SubDeviceList/RFoot/FSR/CenterOfPressure/X/Sensor/Value",
"Device/SubDeviceList/RFoot/FSR/CenterOfPressure/Y/Sensor/Value"};
fsr_names_ = vector<string>(fsr, end(fsr));
// Tactile Memory Keys
const char* tactile[] = {"Device/SubDeviceList/Head/Touch/Front/Sensor/Value",
"Device/SubDeviceList/Head/Touch/Middle/Sensor/Value",
"Device/SubDeviceList/Head/Touch/Rear/Sensor/Value",
"Device/SubDeviceList/LHand/Touch/Back/Sensor/Value",
"Device/SubDeviceList/LHand/Touch/Left/Sensor/Value",
"Device/SubDeviceList/LHand/Touch/Right/Sensor/Value",
"Device/SubDeviceList/RHand/Touch/Back/Sensor/Value",
"Device/SubDeviceList/RHand/Touch/Left/Sensor/Value",
"Device/SubDeviceList/RHand/Touch/Right/Sensor/Value"};
tactile_names_ = vector<string>(tactile, end(tactile));
// Bumper Memory Keys
const char* bumper[] = {"Device/SubDeviceList/LFoot/Bumper/Left/Sensor/Value",
"Device/SubDeviceList/LFoot/Bumper/Right/Sensor/Value",
"Device/SubDeviceList/RFoot/Bumper/Left/Sensor/Value",
"Device/SubDeviceList/RFoot/Bumper/Right/Sensor/Value"};
bumper_names_ = vector<string>(bumper, end(bumper));
// Battery Memory Keys
const char* battery[] = {"Device/SubDeviceList/Battery/Charge/Sensor/Value",
"Device/SubDeviceList/Battery/Temperature/Sensor/Value"};
battery_names_ = vector<string>(battery, end(battery));
// LED Memory Keys
const char* led[] = {"Device/SubDeviceList/ChestBoard/Led/Blue/Actuator/Value",
"Device/SubDeviceList/ChestBoard/Led/Green/Actuator/Value",
"Device/SubDeviceList/ChestBoard/Led/Red/Actuator/Value",
"Device/SubDeviceList/Ears/Led/Left/0Deg/Actuator/Value",
"Device/SubDeviceList/Ears/Led/Left/108Deg/Actuator/Value",
"Device/SubDeviceList/Ears/Led/Left/144Deg/Actuator/Value",
"Device/SubDeviceList/Ears/Led/Left/180Deg/Actuator/Value",
"Device/SubDeviceList/Ears/Led/Left/216Deg/Actuator/Value",
"Device/SubDeviceList/Ears/Led/Left/252Deg/Actuator/Value",
"Device/SubDeviceList/Ears/Led/Left/288Deg/Actuator/Value",
"Device/SubDeviceList/Ears/Led/Left/324Deg/Actuator/Value",
"Device/SubDeviceList/Ears/Led/Left/36Deg/Actuator/Value",
"Device/SubDeviceList/Ears/Led/Left/72Deg/Actuator/Value",
"Device/SubDeviceList/Ears/Led/Right/0Deg/Actuator/Value",
"Device/SubDeviceList/Ears/Led/Right/108Deg/Actuator/Value",
"Device/SubDeviceList/Ears/Led/Right/144Deg/Actuator/Value",
"Device/SubDeviceList/Ears/Led/Right/180Deg/Actuator/Value",
"Device/SubDeviceList/Ears/Led/Right/216Deg/Actuator/Value",
"Device/SubDeviceList/Ears/Led/Right/252Deg/Actuator/Value",
"Device/SubDeviceList/Ears/Led/Right/288Deg/Actuator/Value",
"Device/SubDeviceList/Ears/Led/Right/324Deg/Actuator/Value",
"Device/SubDeviceList/Ears/Led/Right/36Deg/Actuator/Value",
"Device/SubDeviceList/Ears/Led/Right/72Deg/Actuator/Value",
"Device/SubDeviceList/Face/Led/Blue/Left/0Deg/Actuator/Value",
"Device/SubDeviceList/Face/Led/Blue/Left/135Deg/Actuator/Value",
"Device/SubDeviceList/Face/Led/Blue/Left/180Deg/Actuator/Value",
"Device/SubDeviceList/Face/Led/Blue/Left/225Deg/Actuator/Value",
"Device/SubDeviceList/Face/Led/Blue/Left/270Deg/Actuator/Value",
"Device/SubDeviceList/Face/Led/Blue/Left/315Deg/Actuator/Value",
"Device/SubDeviceList/Face/Led/Blue/Left/45Deg/Actuator/Value",
"Device/SubDeviceList/Face/Led/Blue/Left/90Deg/Actuator/Value",
"Device/SubDeviceList/Face/Led/Blue/Right/0Deg/Actuator/Value",
"Device/SubDeviceList/Face/Led/Blue/Right/135Deg/Actuator/Value",
"Device/SubDeviceList/Face/Led/Blue/Right/180Deg/Actuator/Value",
"Device/SubDeviceList/Face/Led/Blue/Right/225Deg/Actuator/Value",
"Device/SubDeviceList/Face/Led/Blue/Right/270Deg/Actuator/Value",
"Device/SubDeviceList/Face/Led/Blue/Right/315Deg/Actuator/Value",
"Device/SubDeviceList/Face/Led/Blue/Right/45Deg/Actuator/Value",
"Device/SubDeviceList/Face/Led/Blue/Right/90Deg/Actuator/Value",
"Device/SubDeviceList/Face/Led/Green/Left/0Deg/Actuator/Value",
"Device/SubDeviceList/Face/Led/Green/Left/135Deg/Actuator/Value",
"Device/SubDeviceList/Face/Led/Green/Left/180Deg/Actuator/Value",
"Device/SubDeviceList/Face/Led/Green/Left/225Deg/Actuator/Value",
"Device/SubDeviceList/Face/Led/Green/Left/270Deg/Actuator/Value",
"Device/SubDeviceList/Face/Led/Green/Left/315Deg/Actuator/Value",
"Device/SubDeviceList/Face/Led/Green/Left/45Deg/Actuator/Value",
"Device/SubDeviceList/Face/Led/Green/Left/90Deg/Actuator/Value",
"Device/SubDeviceList/Face/Led/Green/Right/0Deg/Actuator/Value",
"Device/SubDeviceList/Face/Led/Green/Right/135Deg/Actuator/Value",
"Device/SubDeviceList/Face/Led/Green/Right/180Deg/Actuator/Value",
"Device/SubDeviceList/Face/Led/Green/Right/225Deg/Actuator/Value",
"Device/SubDeviceList/Face/Led/Green/Right/270Deg/Actuator/Value",
"Device/SubDeviceList/Face/Led/Green/Right/315Deg/Actuator/Value",
"Device/SubDeviceList/Face/Led/Green/Right/45Deg/Actuator/Value",
"Device/SubDeviceList/Face/Led/Green/Right/90Deg/Actuator/Value",
"Device/SubDeviceList/Face/Led/Red/Left/0Deg/Actuator/Value",
"Device/SubDeviceList/Face/Led/Red/Left/135Deg/Actuator/Value",
"Device/SubDeviceList/Face/Led/Red/Left/180Deg/Actuator/Value",
"Device/SubDeviceList/Face/Led/Red/Left/225Deg/Actuator/Value",
"Device/SubDeviceList/Face/Led/Red/Left/270Deg/Actuator/Value",
"Device/SubDeviceList/Face/Led/Red/Left/315Deg/Actuator/Value",
"Device/SubDeviceList/Face/Led/Red/Left/45Deg/Actuator/Value",
"Device/SubDeviceList/Face/Led/Red/Left/90Deg/Actuator/Value",
"Device/SubDeviceList/Face/Led/Red/Right/0Deg/Actuator/Value",
"Device/SubDeviceList/Face/Led/Red/Right/135Deg/Actuator/Value",
"Device/SubDeviceList/Face/Led/Red/Right/180Deg/Actuator/Value",
"Device/SubDeviceList/Face/Led/Red/Right/225Deg/Actuator/Value",
"Device/SubDeviceList/Face/Led/Red/Right/270Deg/Actuator/Value",
"Device/SubDeviceList/Face/Led/Red/Right/315Deg/Actuator/Value",
"Device/SubDeviceList/Face/Led/Red/Right/45Deg/Actuator/Value",
"Device/SubDeviceList/Face/Led/Red/Right/90Deg/Actuator/Value",
"Device/SubDeviceList/Head/Led/Front/Left/0/Actuator/Value",
"Device/SubDeviceList/Head/Led/Front/Left/1/Actuator/Value",
"Device/SubDeviceList/Head/Led/Front/Right/0/Actuator/Value",
"Device/SubDeviceList/Head/Led/Front/Right/1/Actuator/Value",
"Device/SubDeviceList/Head/Led/Middle/Left/0/Actuator/Value",
"Device/SubDeviceList/Head/Led/Middle/Right/0/Actuator/Value",
"Device/SubDeviceList/Head/Led/Rear/Left/0/Actuator/Value",
"Device/SubDeviceList/Head/Led/Rear/Left/1/Actuator/Value",
"Device/SubDeviceList/Head/Led/Rear/Left/2/Actuator/Value",
"Device/SubDeviceList/Head/Led/Rear/Right/0/Actuator/Value",
"Device/SubDeviceList/Head/Led/Rear/Right/1/Actuator/Value",
"Device/SubDeviceList/Head/Led/Rear/Right/2/Actuator/Value",
"Device/SubDeviceList/LFoot/Led/Blue/Actuator/Value",
"Device/SubDeviceList/LFoot/Led/Green/Actuator/Value",
"Device/SubDeviceList/LFoot/Led/Red/Actuator/Value",
"Device/SubDeviceList/RFoot/Led/Blue/Actuator/Value",
"Device/SubDeviceList/RFoot/Led/Green/Actuator/Value",
"Device/SubDeviceList/RFoot/Led/Red/Actuator/Value"};
led_names_ = vector<string>(led, end(led));
// Joints Initialization
const char* joint[] = {"HeadYaw",
"HeadPitch",
"LShoulderPitch",
"LShoulderRoll",
"LElbowYaw",
"LElbowRoll",
"LWristYaw",
"LHand",
"RShoulderPitch",
"RShoulderRoll",
"RElbowYaw",
"RElbowRoll",
"RWristYaw",
"RHand",
"LHipYawPitch",
"RHipYawPitch",
"LHipRoll",
"LHipPitch",
"LKneePitch",
"LAnklePitch",
"LAnkleRoll",
"RHipRoll",
"RHipPitch",
"RKneePitch",
"RAnklePitch",
"RAnkleRoll"};
joint_names_ = vector<string>(joint, end(joint));
for(vector<string>::iterator it=joint_names_.begin();it!=joint_names_.end();it++)
{
if((*it=="RHand" || *it=="LHand" || *it == "RWristYaw" || *it == "LWristYaw") && (body_type_ == "H21"))
{
joint_names_.erase(it);
it--;
continue;
}
joints_names_.push_back("Device/SubDeviceList/"+(*it)+"/Position/Sensor/Value");
if(*it!="RHipYawPitch")
{
joint_temperature_names_.push_back("Device/SubDeviceList/"+(*it)+"/Temperature/Sensor/Value");
}
}
number_of_joints_ = joint_names_.size();
// DCM Motion Commands Initialization
try
{
// Create Motion Command
commands_.arraySetSize(4);
commands_[0] = string("Joints");
commands_[1] = string("ClearAll");
commands_[2] = string("time-mixed");
commands_[3].arraySetSize(number_of_joints_);
// Create Joints Actuators Alias
AL::ALValue commandAlias;
commandAlias.arraySetSize(2);
commandAlias[0] = string("Joints");
commandAlias[1].arraySetSize(number_of_joints_);
for(int i=0;i<number_of_joints_;i++)
{
commandAlias[1][i] = string("Device/SubDeviceList/"+joint_names_[i]+"/Position/Actuator/Value");
commands_[3][i].arraySetSize(1);
commands_[3][i][0].arraySetSize(2);
}
dcm_proxy_.createAlias(commandAlias);
// Create Joints Hardness Alias
commandAlias[0] = string("JointsHardness");
commandAlias[1].arraySetSize(number_of_joints_-1);
int k = 0;
for(int i=0;i<number_of_joints_;i++)
{
if(joint_names_[i] == "RHipYawPitch")
{
k = -1;
i++;
}
commandAlias[1][i+k] = string("Device/SubDeviceList/"+joint_names_[i]+"/Hardness/Actuator/Value");
}
dcm_proxy_.createAlias(commandAlias);
// Create LEDs Alias
commandAlias[0] = string("Leds");
commandAlias[1].arraySetSize(89);
for(int i=0;i<89;i++)
{
commandAlias[1][i] = led_names_[i];
}
dcm_proxy_.createAlias(commandAlias);
}
catch(const AL::ALError& e)
{
ROS_ERROR("Could not initialize dcm aliases!\n\tTrace: %s",e.what());
return false;
}
// Turn Stiffness On
vector<float> stiff = vector<float>(number_of_joints_-1,1.0f);
vector<int> times = vector<int>(number_of_joints_-1,0);
DCMAliasTimedCommand("JointsHardness",stiff, times);
stiffnesses_enabled_ = true;
// Add diagnostic functions
diagnostic_.setHardwareID(string("Nao")+version_+body_type_);
diagnostic_.add("Joints Temperature", this, &Nao::checkTemperature);
diagnostic_.add("Battery", this, &Nao::checkBattery);
return true;
}
bool Nao::initializeControllers(controller_manager::ControllerManager& cm)
{
if(!initialize())
{
ROS_ERROR("Initialization method failed!");
return false;
}
// Initialize Controllers' Interfaces
joint_angles_.resize(number_of_joints_);
joint_velocities_.resize(number_of_joints_);
joint_efforts_.resize(number_of_joints_);
joint_commands_.resize(number_of_joints_);
try
{
for(int i=0;i<number_of_joints_;i++)
{
hardware_interface::JointStateHandle state_handle(joint_names_[i], &joint_angles_[i],
&joint_velocities_[i], &joint_efforts_[i]);
jnt_state_interface_.registerHandle(state_handle);
hardware_interface::JointHandle pos_handle(jnt_state_interface_.getHandle(joint_names_[i]),
&joint_commands_[i]);
jnt_pos_interface_.registerHandle(pos_handle);
}
registerInterface(&jnt_state_interface_);
registerInterface(&jnt_pos_interface_);
}
catch(const ros::Exception& e)
{
ROS_ERROR("Could not initialize hardware interfaces!\n\tTrace: %s",e.what());
return false;
}
ROS_INFO("Nao Module initialized!");
return true;
}
bool Nao::connect(const ros::NodeHandle nh)
{
// Initialize ROS nodes
node_handle_ = nh;
is_connected_ = false;
// Load ROS Parameters
loadParams();
// Needed for Error Checking
try
{
subscribeToMicroEvent("ClientDisconnected", "Nao", "brokerDisconnected");
}
catch (const AL::ALError& e)
{
ROS_ERROR("Could not subscribe to brokerDisconnected!\n\tTrace: %s",e.what());
}
// Initialize DCM Proxy
try
{
dcm_proxy_ = AL::DCMProxy(getParentBroker());
}
catch (const AL::ALError& e)
{
ROS_ERROR("Failed to connect to DCM Proxy!\n\tTrace: %s",e.what());
return false;
}
// Initialize Memory Proxy
try
{
memory_proxy_ = AL::ALMemoryProxy(getParentBroker());
}
catch (const AL::ALError& e)
{
ROS_ERROR("Failed to connect to Memory Proxy!\n\tTrace: %s",e.what());
return false;
}
is_connected_ = true;
// Subscribe/Publish ROS Topics/Services
subscribe();
// Initialize Controller Manager and Controllers
manager_ = new controller_manager::ControllerManager(this,node_handle_);
if(!initializeControllers(*manager_))
{
ROS_ERROR("Could not load controllers!");
return false;
}
ROS_INFO("Controllers successfully loaded!");
return true;
}
void Nao::disconnect()
{
if(!is_connected_)
return;
try
{
unsubscribeFromMicroEvent("ClientDisconnected", "Nao");
}
catch (const AL::ALError& e)
{
ROS_ERROR("Failed to unsubscribe from subscribed events!\n\tTrace: %s",e.what());
}
is_connected_ = false;
}
void Nao::subscribe()
{
// Subscribe/Publish ROS Topics/Services
cmd_vel_sub_ = node_handle_.subscribe(prefix_+"cmd_vel", topic_queue_, &Nao::commandVelocity, this);
imu_pub_ = node_handle_.advertise<sensor_msgs::Imu>(prefix_+"imu_data", topic_queue_);
sonar_left_pub_ = node_handle_.advertise<sensor_msgs::Range>(prefix_+"sonar_left", topic_queue_);
sonar_left_.header.frame_id = "LSonar_frame";
sonar_left_.radiation_type = sensor_msgs::Range::ULTRASOUND;
sonar_left_.field_of_view = 1.04719755f;
sonar_left_.min_range = 0.25;
sonar_left_.max_range = 2.55;
sonar_right_pub_ = node_handle_.advertise<sensor_msgs::Range>(prefix_+"sonar_right", topic_queue_);
sonar_right_.header.frame_id = "RSonar_frame";
sonar_right_.radiation_type = sensor_msgs::Range::ULTRASOUND;
sonar_right_.field_of_view = 1.04719755f;
sonar_right_.min_range = 0.25;
sonar_right_.max_range = 2.55;
sonar_switch_ = node_handle_.advertiseService<Nao, nao_dcm_msgs::BoolService::Request,
nao_dcm_msgs::BoolService::Response>(prefix_+"Sonar/Enable", &Nao::switchSonar, this);
fsrs_pub_ = node_handle_.advertise<nao_dcm_msgs::FSRs>(prefix_+"fsrs", topic_queue_);
fsrs_switch_ = node_handle_.advertiseService<Nao, nao_dcm_msgs::BoolService::Request,
nao_dcm_msgs::BoolService::Response>(prefix_+"FSRs/Enable", &Nao::switchFSR, this);
bumpers_pub_ = node_handle_.advertise<nao_dcm_msgs::Bumper>(prefix_+"bumpers", topic_queue_);
bumpers_switch_ = node_handle_.advertiseService<Nao, nao_dcm_msgs::BoolService::Request,
nao_dcm_msgs::BoolService::Response>(prefix_+"Bumpers/Enable", &Nao::switchBumper, this);
tactiles_pub_ = node_handle_.advertise<nao_dcm_msgs::Tactile>(prefix_+"tactiles", topic_queue_);
tactiles_switch_ = node_handle_.advertiseService<Nao, nao_dcm_msgs::BoolService::Request,
nao_dcm_msgs::BoolService::Response>(prefix_+"Tactiles/Enable", &Nao::switchTactile, this);
stiffness_pub_ = node_handle_.advertise<std_msgs::Float32>(prefix_+"stiffnesses", topic_queue_);
stiffness_.data = 1.0f;
stiffness_switch_ = node_handle_.advertiseService<Nao, nao_dcm_msgs::BoolService::Request,
nao_dcm_msgs::BoolService::Response>(prefix_+"Stiffnesses/Enable", &Nao::switchStiffnesses, this);
}
void Nao::loadParams()
{
ros::NodeHandle n_p("~");
// Load Server Parameters
n_p.param("Version", version_, string("V4"));
n_p.param("BodyType", body_type_, string("H25"));
n_p.param("TactilesEnabled", tactiles_enabled_, true);
n_p.param("BumpersEnabled", bumpers_enabled_, true);
n_p.param("SonarEnabled", sonar_enabled_, true);
n_p.param("FootContactsEnabled", foot_contacts_enabled_, true);
n_p.param("PublishIMU", imu_published_, true);
n_p.param("TopicQueue", topic_queue_, 50);
n_p.param("Prefix", prefix_, string("nao_dcm"));
prefix_ = prefix_+"/";
n_p.param("LowCommunicationFrequency", low_freq_, 10.0);
n_p.param("HighCommunicationFrequency", high_freq_, 100.0);
n_p.param("ControllerFrequency", controller_freq_, 15.0);
n_p.param("JointPrecision", joint_precision_, 0.00174532925);
n_p.param("OdomFrame", odom_frame_, string("odom"));
}
void Nao::brokerDisconnected(const string& event_name, const string &broker_name, const string& subscriber_identifier)
{
if(broker_name == "Nao Driver Broker")
is_connected_ = false;
}
void Nao::DCMTimedCommand(const string &key, const AL::ALValue &value, const int &timeOffset, const string &type)
{
try
{
// Create timed-command
AL::ALValue command;
command.arraySetSize(3);
command[0] = key;
command[1] = type;
command[2].arraySetSize(1);
command[2][0].arraySetSize(2);
command[2][0][0] = value;
command[2][0][1] = dcm_proxy_.getTime(timeOffset);
// Execute timed-command
dcm_proxy_.set(command);
}
catch(const AL::ALError& e)
{
ROS_ERROR("Could not execute DCM timed-command!\n\t%s\n\n\tTrace: %s", key.c_str(), e.what());
}
}
void Nao::DCMAliasTimedCommand(const string &alias, const vector<float> &values, const vector<int> &timeOffsets,
const string &type, const string &type2)
{
try
{
// Create Alias timed-command
AL::ALValue command;
command.arraySetSize(4);
command[0] = alias;
command[1] = type;
command[2] = type2;
command[3].arraySetSize(values.size());
int T = dcm_proxy_.getTime(0);
for(int i=0;i<values.size();i++)
{
command[3][i].arraySetSize(1);
command[3][i][0].arraySetSize(2);
command[3][i][0][0] = values[i];
command[3][i][0][1] = T+timeOffsets[i];
}
// Execute Alias timed-command
dcm_proxy_.setAlias(command);
}
catch(const AL::ALError& e)
{
ROS_ERROR("Could not execute DCM timed-command!\n\t%s\n\n\tTrace: %s", alias.c_str(), e.what());
}
}
void Nao::insertDataToMemory(const string &key, const AL::ALValue &value)
{
memory_proxy_.insertData(key,value);
}
AL::ALValue Nao::getDataFromMemory(const string &key)
{
return memory_proxy_.getData(key);
}
void Nao::subscribeToEvent(const string &name, const string &callback_module, const string &callback_method)
{
try
{
memory_proxy_.subscribeToEvent(name,callback_module,"",callback_method);
}
catch(const AL::ALError& e)
{
ROS_ERROR("Could not subscribe to event '%s'.\n\tTrace: %s",name.c_str(),e.what());
}
}
void Nao::subscribeToMicroEvent(const string &name, const string &callback_module,
const string &callback_method, const string &callback_message)
{
try
{
memory_proxy_.subscribeToMicroEvent(name,callback_module,callback_message,callback_method);
}
catch(const AL::ALError& e)
{
ROS_ERROR("Could not subscribe to micro-event '%s'.\n\tTrace: %s",name.c_str(),e.what());
}
}
void Nao::unsubscribeFromEvent(const string &name, const string &callback_module)
{
try
{
memory_proxy_.unsubscribeToEvent(name,callback_module);
}
catch(const AL::ALError& e)
{
ROS_ERROR("Could not unsubscribe from event '%s'.\n\tTrace: %s",name.c_str(),e.what());
}
}
void Nao::unsubscribeFromMicroEvent(const string &name, const string &callback_module)
{
try
{
memory_proxy_.unsubscribeToMicroEvent(name,callback_module);
}
catch(const AL::ALError& e)
{
ROS_ERROR("Could not unsubscribe from micro-event '%s'.\n\tTrace: %s",name.c_str(),e.what());
}
}
void Nao::raiseEvent(const string &name, const AL::ALValue &value)
{
try
{
memory_proxy_.raiseEvent(name,value);
}
catch(const AL::ALError& e)
{
ROS_ERROR("Could not raise event '%s'.\n\tTrace: %s",name.c_str(),e.what());
}
}
void Nao::raiseMicroEvent(const string &name, const AL::ALValue &value)
{
try
{
memory_proxy_.raiseMicroEvent(name,value);
}
catch(const AL::ALError& e)
{
ROS_ERROR("Could not raise micro-event '%s'.\n\tTrace: %s",name.c_str(),e.what());
}
}
void Nao::declareEvent(const string &name)
{
try
{
memory_proxy_.declareEvent(name);
}
catch(AL::ALError& e)
{
ROS_ERROR("Could not declare event '%s'.\n\tTrace: %s",name.c_str(),e.what());
}
}
void Nao::run()
{
boost::thread t1(&Nao::controllerLoop,this);
boost::thread t2(&Nao::lowCommunicationLoop,this);
boost::thread t3(&Nao::highCommunicationLoop,this);
t1.join();
t2.join();
t3.join();
}
void Nao::lowCommunicationLoop()
{
static ros::Rate rate(low_freq_);
while(ros::ok())
{
ros::Time time = ros::Time::now();
if(!is_connected_)
break;
publishBaseFootprint(time);
if(sonar_enabled_)
checkSonar();
if(foot_contacts_enabled_)
checkFSR();
if(tactiles_enabled_)
checkTactile();
if(bumpers_enabled_)
checkBumper();
if(stiffnesses_enabled_)
{
stiffness_.data = 1.0f;
}
else
{
stiffness_.data = 0.0f;
}
stiffness_pub_.publish(stiffness_);
diagnostic_.update();
rate.sleep();
}
}
void Nao::highCommunicationLoop()
{
static ros::Rate rate(high_freq_);
while(ros::ok())
{
ros::Time time = ros::Time::now();
if(!is_connected_)
break;
if(imu_published_)
publishIMU(time);
try
{
dcm_proxy_.ping();
}
catch(const AL::ALError& e)
{
ROS_ERROR("Could not ping DCM proxy.\n\tTrace: %s",e.what());
is_connected_ = false;
}
rate.sleep();
}
}
void Nao::controllerLoop()
{
static ros::Rate rate(controller_freq_+10.0);
while(ros::ok())
{
ros::Time time = ros::Time::now();
if(!is_connected_)
break;
readJoints();
manager_->update(time,ros::Duration(1.0f/controller_freq_));
writeJoints();
rate.sleep();
}
}
bool Nao::connected()
{
return is_connected_;
}
void Nao::commandVelocity(const geometry_msgs::TwistConstPtr &msg)
{
ROS_WARN("This function does nothing at the moment..");
}
void Nao::publishIMU(const ros::Time &ts)
{
vector<float> memData;
try
{
memData = memory_proxy_.getListData(imu_names_);
}
catch(const AL::ALError& e)
{
ROS_ERROR("Could not get IMU data from Nao.\n\tTrace: %s",e.what());
return;
}
if (memData.size() != imu_names_.size())
{
ROS_ERROR("IMU readings' size is not correct!");
return;
}
imu_.header.stamp = ts;
imu_.header.frame_id = "torso";
float angleX = memData[0];
float angleY = memData[1];
float angleZ = memData[2];
float gyroX = memData[3];
float gyroY = memData[4];
float gyroZ = memData[5];
float accX = memData[6];
float accY = memData[7];
float accZ = memData[8];
imu_.orientation = tf::createQuaternionMsgFromRollPitchYaw(angleX,angleY,angleZ);
imu_.angular_velocity.x = gyroX;
imu_.angular_velocity.y = gyroY;
imu_.angular_velocity.z = gyroZ;
imu_.linear_acceleration.x = accX;
imu_.linear_acceleration.y = accY;
imu_.linear_acceleration.z = accZ;
// covariances unknown
imu_.orientation_covariance[0] = 0;
imu_.angular_velocity_covariance[0] = 0;
imu_.linear_acceleration_covariance[0] = 0;
imu_pub_.publish(imu_);
}
void Nao::publishBaseFootprint(const ros::Time &ts)
{
string odom_frame, l_sole_frame, r_sole_frame, base_link_frame;
try {
odom_frame = base_footprint_listener_.resolve(odom_frame_);
l_sole_frame = base_footprint_listener_.resolve("l_sole");
r_sole_frame = base_footprint_listener_.resolve("r_sole");
base_link_frame = base_footprint_listener_.resolve("base_link");
}
catch(ros::Exception& e)
{
ROS_ERROR("%s",e.what());
return;
}
tf::StampedTransform tf_odom_to_base, tf_odom_to_left_foot, tf_odom_to_right_foot;
double temp_freq = 1.0f/(10.0*high_freq_);
if(!base_footprint_listener_.waitForTransform(odom_frame, l_sole_frame, ros::Time(0), ros::Duration(temp_freq)))
return;
try {
base_footprint_listener_.lookupTransform(odom_frame, l_sole_frame, ros::Time(0), tf_odom_to_left_foot);
base_footprint_listener_.lookupTransform(odom_frame, r_sole_frame, ros::Time(0), tf_odom_to_right_foot);
base_footprint_listener_.lookupTransform(odom_frame, base_link_frame, ros::Time(0), tf_odom_to_base);
}
catch (const tf::TransformException& ex){
ROS_ERROR("%s",ex.what());
return ;
}
tf::Vector3 new_origin = (tf_odom_to_right_foot.getOrigin() + tf_odom_to_left_foot.getOrigin())/2.0;
double height = std::min(tf_odom_to_left_foot.getOrigin().getZ(), tf_odom_to_right_foot.getOrigin().getZ());
new_origin.setZ(height);
double roll, pitch, yaw;
tf_odom_to_base.getBasis().getRPY(roll, pitch, yaw);
tf::Transform tf_odom_to_footprint(tf::createQuaternionFromYaw(yaw), new_origin);
tf::Transform tf_base_to_footprint = tf_odom_to_base.inverse() * tf_odom_to_footprint;
base_footprint_broadcaster_.sendTransform(tf::StampedTransform(tf_base_to_footprint, ts,
base_link_frame, "base_footprint"));
}
void Nao::readJoints()
{
vector<float> jointData;
try
{
jointData = memory_proxy_.getListData(joints_names_);
}
catch(const AL::ALError& e)
{
ROS_ERROR("Could not get joint data from Nao.\n\tTrace: %s",e.what());
return;
}
for(short i = 0; i<jointData.size(); i++)
{
joint_angles_[i] = jointData[i];
// Set commands to the read angles for when no command specified
joint_commands_[i] = jointData[i];
}
}
void Nao::writeJoints()
{
// Update joints only when actual command is issued
bool changed = false;
for(int i=0;i<number_of_joints_;i++)
{
if(fabs(joint_commands_[i]-joint_angles_[i])>joint_precision_)
{
changed = true;
break;
}
}
// Do not write joints if no change in joint values
if(!changed)
{
return;
}
try
{
int T = dcm_proxy_.getTime(0);
for(int i=0;i<number_of_joints_;i++)
{
commands_[3][i][0][0] = float(joint_commands_[i]);
commands_[3][i][0][1] = T+(int)(800.0f/controller_freq_);
}
dcm_proxy_.setAlias(commands_);
}
catch(const AL::ALError& e)
{
ROS_ERROR("Could not send joint commands to Nao.\n\tTrace: %s",e.what());
return;
}
}
bool Nao::switchSonar(nao_dcm_msgs::BoolService::Request &req, nao_dcm_msgs::BoolService::Response &res)
{
sonar_enabled_ = req.enable;
return true;
}
bool Nao::switchFSR(nao_dcm_msgs::BoolService::Request &req, nao_dcm_msgs::BoolService::Response &res)
{
foot_contacts_enabled_ = req.enable;
return true;
}
bool Nao::switchBumper(nao_dcm_msgs::BoolService::Request &req, nao_dcm_msgs::BoolService::Response &res)
{
bumpers_enabled_ = req.enable;
return true;
}
bool Nao::switchTactile(nao_dcm_msgs::BoolService::Request &req, nao_dcm_msgs::BoolService::Response &res)
{
tactiles_enabled_ = req.enable;
return true;
}
bool Nao::switchStiffnesses(nao_dcm_msgs::BoolService::Request &req, nao_dcm_msgs::BoolService::Response &res)
{
if(stiffnesses_enabled_!=req.enable && req.enable)
{
DCMAliasTimedCommand("JointsHardness",vector<float>(number_of_joints_,1.0f), vector<int>(number_of_joints_,0));
}
else if(stiffnesses_enabled_!=req.enable)
{
DCMAliasTimedCommand("JointsHardness",vector<float>(number_of_joints_,0.0f), vector<int>(number_of_joints_,0));
}
stiffnesses_enabled_ = req.enable;
}
void Nao::checkSonar()
{
// Send Sonar Wave
DCMTimedCommand("Device/SubDeviceList/US/Actuator/Value",4.0f,0);
// Read Sonar Values
AL::ALValue sonars;
try
{
sonars = memory_proxy_.getListData(sonar_names_);
}
catch(const AL::ALError& e)
{
ROS_ERROR("Could not get sonar values.\n\tTrace: %s",e.what());
return;
}
// Select closer object detected
float sonar_left = float(sonars[0]), sonar_right = float(sonars[10]);
for(short i=1;i<10;i++)
{
if(float(sonars[i])>=0.0f && float(sonars[i])<=2.55f && float(sonars[i])<sonar_left)
{
sonar_left = float(sonars[i]);
}
if(float(sonars[10+i])>=0.0f && float(sonars[10+i])<=2.55f && float(sonars[10+i])<sonar_right)
{
sonar_right = float(sonars[10+i]);
}
}
sonar_left_.range = sonar_left;
sonar_left_pub_.publish(sonar_left_);
sonar_right_.range = sonar_right;
sonar_right_pub_.publish(sonar_right_);
}
void Nao::checkFSR()
{
AL::ALValue fsrs;
try
{
fsrs = memory_proxy_.getListData(fsr_names_);
}
catch(const AL::ALError& e)
{
ROS_ERROR("Could not get FSR values.\n\tTrace: %s",e.what());
return;
}
fsrs_.LeftFrontLeft = float(fsrs[0]);
fsrs_.LeftFrontRight = float(fsrs[1]);
fsrs_.LeftRearLeft = float(fsrs[2]);
fsrs_.LeftRearRight = float(fsrs[3]);
fsrs_.LeftTotalWeight = float(fsrs[4]);
fsrs_.LeftCOPx = float(fsrs[10]);
fsrs_.LeftCOPy = float(fsrs[11]);
fsrs_.RightFrontLeft = float(fsrs[5]);
fsrs_.RightFrontRight = float(fsrs[6]);
fsrs_.RightRearLeft = float(fsrs[7]);
fsrs_.RightRearRight = float(fsrs[8]);
fsrs_.RightTotalWeight = float(fsrs[9]);
fsrs_.RightCOPx = float(fsrs[12]);
fsrs_.RightCOPy = float(fsrs[13]);
fsrs_pub_.publish(fsrs_);
}
void Nao::checkTactile()
{
AL::ALValue tactiles;
try
{
tactiles = memory_proxy_.getListData(tactile_names_);
}
catch(const AL::ALError& e)
{
ROS_ERROR("Could not get Tactile values.\n\tTrace: %s",e.what());
return;
}
tactiles_.HeadTouchFront = int(float(tactiles[0]));
tactiles_.HeadTouchMiddle = int(float(tactiles[1]));
tactiles_.HeadTouchRear = int(float(tactiles[2]));
tactiles_.LeftTouchBack = int(float(tactiles[3]));
tactiles_.LeftTouchLeft = int(float(tactiles[4]));
tactiles_.LeftTouchRight = int(float(tactiles[5]));
tactiles_.RightTouchBack = int(float(tactiles[6]));
tactiles_.RightTouchLeft = int(float(tactiles[7]));
tactiles_.RightTouchRight = int(float(tactiles[8]));
tactiles_pub_.publish(tactiles_);
}
void Nao::checkBumper()
{
AL::ALValue bumpers;
try
{
bumpers = memory_proxy_.getListData(bumper_names_);
}
catch(const AL::ALError& e)
{
ROS_ERROR("Could not get Tactile values.\n\tTrace: %s",e.what());
return;
}
bumpers_.LeftFootLeft = int(float(bumpers[0]));
bumpers_.LeftFootRight = int(float(bumpers[1]));
bumpers_.RightFootLeft = int(float(bumpers[2]));
bumpers_.RightFootRight = int(float(bumpers[3]));
bumpers_pub_.publish(bumpers_);
}
void Nao::checkTemperature(diagnostic_updater::DiagnosticStatusWrapper &stat)
{
AL::ALValue temps;
try
{
temps = memory_proxy_.getListData(joint_temperature_names_);
}
catch(const AL::ALError& e)
{
ROS_ERROR("Could not get Temperature values.\n\tTrace: %s",e.what());
return;
}
stat.summary(diagnostic_msgs::DiagnosticStatus::OK, "Joints Temperature: OK!");
for(short i=0;i<temps.getSize();i++)
{
if(float(temps[i])>=70.0f)
stat.summary(diagnostic_msgs::DiagnosticStatus::WARN, "Joints Temperature: WARNING!");
if(float(temps[i])>=85.0f)
stat.summary(diagnostic_msgs::DiagnosticStatus::ERROR, "Joints Temperature: CRITICAL!");
string joint_name = string(joint_temperature_names_[i]).erase(0,21);
short l = joint_name.find('/',joint_name.find('/'));
joint_name.erase(l,25);
stat.add(joint_name,temps[i]);
}
}
void Nao::checkBattery(diagnostic_updater::DiagnosticStatusWrapper &stat)
{
AL::ALValue batt;
try
{
batt = memory_proxy_.getListData(battery_names_);
}
catch(const AL::ALError& e)
{
ROS_ERROR("Could not get Battery values.\n\tTrace: %s",e.what());
return;
}
int status = 0;
string message = "Battery: "+boost::lexical_cast<string>(float(batt[0])*100.0f)+"\% charged! ";
if(float(batt[0])*100.0f<50.0f)
status = 1;
else if(float(batt[0])*100.0f<20.0f)
status = 2;
if(float(batt[1])>=60.0f)
{
status = 1;
message += "Temperature: WARNING!";
}
else if(float(batt[1])>=70.0f)
{
status = 2;
message += "Temperature: CRITICAL!";
}
else
{
message += "Temperature: OK!";
}
stat.summary(status,message);
stat.add("Battery Charge",float(batt[0])*100.0f);
stat.add("Battery Temperature", float(batt[1]));
}
| 38.848644
| 142
| 0.587064
|
costashatz
|
a0b4c2f1c8c4ede43931ff2b88bab70625ddb861
| 703
|
cpp
|
C++
|
sample-source/OPENCVBook/chapter03/3.6.1 Staturate Cast/saturate_cast.cpp
|
doukhee/opencv-study
|
b7e8a5c916070ebc762c33d7fe307b6fcf88abf4
|
[
"MIT"
] | null | null | null |
sample-source/OPENCVBook/chapter03/3.6.1 Staturate Cast/saturate_cast.cpp
|
doukhee/opencv-study
|
b7e8a5c916070ebc762c33d7fe307b6fcf88abf4
|
[
"MIT"
] | null | null | null |
sample-source/OPENCVBook/chapter03/3.6.1 Staturate Cast/saturate_cast.cpp
|
doukhee/opencv-study
|
b7e8a5c916070ebc762c33d7fe307b6fcf88abf4
|
[
"MIT"
] | null | null | null |
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main()
{
/**
* I(x, t)= min(max(round(r), 0),255)
* 포화 산술 연산 - 어떤 연산의 결과 값을 8비트로 저장을 한다고 할때,
* 8비트 제한 범위를 넘으면 () 또는 255 가운데 가까운 값을 사용하는 것이다.
* OpenCV에서는 행렬에 대해서 연산을 할 경우에는 기본적으로 포화 산술이 적용 된다.
*/
/* Matx 객체 선언 */
Matx<uchar, 2, 2> m1;
Matx<ushort, 2, 2> m2;
m1(0, 0) = -50;
m1(0, 1) = 300;
m1(1, 0) = saturate_cast<uchar>(-50);
m1(1, 1) = saturate_cast<uchar>(300);
m2(0, 0) = -50;
m2(0, 1) = 80000;
/* 포화 산술 연산을 적용 하는 것 */
m2(1, 0) = saturate_cast<unsigned short>(-50);
m2(1, 1) = saturate_cast<unsigned short>(80000);
cout<<"[m1]="<<endl<<m1<<endl;
cout<<"[m2]="<<endl<<m2<<endl;
return 0;
}
| 20.085714
| 53
| 0.578947
|
doukhee
|
a0b4e74e9aae6ad8bc56ad444e3d61562465cb85
| 2,356
|
cpp
|
C++
|
fuzz-tests/primes.cpp
|
deadpool2794/Cp
|
26eab96ef8ea336615fa8d6fadaa8e4d7d6f3a3c
|
[
"MIT"
] | 152
|
2019-04-09T18:26:41.000Z
|
2022-03-20T23:19:41.000Z
|
fuzz-tests/primes.cpp
|
deadpool2794/Cp
|
26eab96ef8ea336615fa8d6fadaa8e4d7d6f3a3c
|
[
"MIT"
] | 1
|
2020-12-29T03:02:22.000Z
|
2020-12-29T03:02:22.000Z
|
fuzz-tests/primes.cpp
|
deadpool2794/Cp
|
26eab96ef8ea336615fa8d6fadaa8e4d7d6f3a3c
|
[
"MIT"
] | 36
|
2019-11-28T09:27:01.000Z
|
2022-03-10T18:22:13.000Z
|
#include <bits/stdc++.h>
using namespace std;
#define rep(i, a, b) for(int i = a; i < int(b); ++i)
#define trav(a, v) for(auto& a : v)
#define all(x) x.begin(), x.end()
#define sz(x) (int)(x).size()
typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;
struct prime_sieve {
typedef unsigned char uchar;
typedef unsigned int uint;
static const int pregen = 3*5*7*11*13;
uint n, sqrtn;
uchar *isprime;
int *prime, primes; // prime[i] is i:th prime
bool is_prime(int n) { // primality check
if(n%2==0 || n<=2) return n==2;
return isprime[(n-3)>>4] & 1 << ((n-3) >> 1&7);
}
prime_sieve(int _n) : n(_n), sqrtn((int)ceil(sqrt(1.0*n))) {
int n0 = max(n>>4, (uint)pregen) + 1;
prime = new int[max(2775, (int)(1.12*n/log(1.0*n)))];
prime[0]=2; prime[1]=3; prime[2]=5;
prime[3]=7; prime[4]=11; prime[5]=13;
primes=6;
isprime = new uchar[n0];
memset(isprime, 255, n0);
for(int j=1,p=prime[j];j<6;p=prime[++j])
for(int i=(p*p-3)>>4,s=(p*p-3)>>1&7;
i<=pregen; i+= (s+=p)>>3, s&=7)
isprime[i] &= (uchar)~(1<<s);
for(int d=pregen, b=pregen+1; b<n0; b+=d,d<<=1)
memcpy(isprime+b,isprime+1,(n0<b+d)?n0-b:d);
for(uint p=17,i=0,s=7; p<n; p+=2, i+= ++s>>3, s&=7)
if(isprime[i]&1<<s) {
prime[primes++] = p;
if(p<sqrtn) {
int ii=i, ss=s+(p-1)*p/2;
for(uint pp=p*p; pp<n; pp+=p<<1, ss+=p) {
ii += ss>>3;
ss &=7;
isprime[ii] &= (uchar)~(1<<ss);
} } } } };
const int MAX_PR = 100000000;
#if 1
bitset<MAX_PR/2> isprime;
vi eratosthenes_sieve(int lim) {
isprime.set();
for (int i = 3; i*i < lim; i += 2) if (isprime[i >> 1])
for (int j = i*i; j < lim; j += 2*i) isprime[j >> 1] = 0;
vi pr;
if (lim >= 2) pr.push_back(2);
for (int i = 3; i < lim; i += 2)
if (isprime[i>>1]) pr.push_back(i);
return pr;
}
#else
bitset<MAX_PR> isprime;
vi eratosthenes_sieve(int lim) {
isprime.set(); isprime[0] = isprime[1] = 0;
for (int i = 4; i < lim; i += 2) isprime[i] = 0;
for (int i = 3; i*i < lim; i += 2) if (isprime[i])
for (int j = i*i; j < lim; j += i*2) isprime[j] = 0;
vi pr;
rep(i,2,lim) if (isprime[i]) pr.push_back(i);
return pr;
}
#endif
int main(int argc, char** argv) {
ll s = 0, s2 = 0;
prime_sieve ps(MAX_PR);
rep(i,0,ps.primes) s += ps.prime[i];
vi r = eratosthenes_sieve(MAX_PR);
trav(x, r) s2 += x;
cout << s << ' ' << s2 << endl;
}
| 25.89011
| 61
| 0.556452
|
deadpool2794
|
a0b58e750d7ea2bbcada23de261f787acfef5267
| 5,813
|
cpp
|
C++
|
digital/PreambleCorrelator.cpp
|
willcode/PothosComms
|
6c6ae8ccb6a9c996a67e2ca646aff79c74bb83fa
|
[
"BSL-1.0"
] | 14
|
2017-10-28T08:40:08.000Z
|
2022-03-19T06:08:55.000Z
|
digital/PreambleCorrelator.cpp
|
BelmY/PothosComms
|
9aa48b827b3813b3ba2b98773f3359b30ebce346
|
[
"BSL-1.0"
] | 22
|
2015-08-25T21:18:13.000Z
|
2016-12-31T02:23:47.000Z
|
digital/PreambleCorrelator.cpp
|
pothosware/pothos-comms
|
cff998cca2c9610d3e7e5480fd4fc692c13d3066
|
[
"BSL-1.0"
] | 13
|
2018-01-03T15:29:44.000Z
|
2022-03-19T06:09:00.000Z
|
// Copyright (c) 2015-2017 Josh Blum
// SPDX-License-Identifier: BSL-1.0
#include <Pothos/Framework.hpp>
#include <cstdint>
#include <complex>
#include <cassert>
#include <iostream>
//provide __popcnt()
#ifdef _MSC_VER
# include <intrin.h>
#elif __GNUC__
# define __popcnt __builtin_popcount
#else
# error "provide __popcnt() for this compiler"
#endif
/***********************************************************************
* |PothosDoc Preamble Correlator
*
* The Preamble Correlator searches an input symbol stream on port 0
* for a matching pattern and forwards the stream to output port 0
* with a label annotating the first symbol after the preamble match.
*
* This block supports operations on arbitrary symbol widths,
* and therefore it may be used operationally on a bit-stream,
* because a bit-stream is identically a symbol stream of N=1.
*
* http://en.wikipedia.org/wiki/Hamming_distance
*
* |category /Digital
* |keywords bit symbol preamble correlate
* |alias /blocks/preamble_correlator
*
* |param preamble A vector of symbols representing the preamble.
* The width of each preamble symbol must the intended input stream.
* |default [1]
*
* |param thresh[Threshold] The threshold hamming distance for preamble match detection.
* |default 0
*
* |param frameStartId[Frame Start ID] The label ID that marks the first symbol of a correlator match.
* |default "frameStart"
* |widget StringEntry()
*
* |factory /comms/preamble_correlator()
* |setter setPreamble(preamble)
* |setter setThreshold(thresh)
* |setter setFrameStartId(frameStartId)
**********************************************************************/
class PreambleCorrelator : public Pothos::Block
{
public:
static Block *make(void)
{
return new PreambleCorrelator();
}
PreambleCorrelator(void):
_threshold(0)
{
this->setupInput(0, typeid(unsigned char));
this->setupOutput(0, typeid(unsigned char), this->uid()); //unique domain because of buffer forwarding
//this->setupOutput(1, typeid(unsigned));
this->registerCall(this, POTHOS_FCN_TUPLE(PreambleCorrelator, setPreamble));
this->registerCall(this, POTHOS_FCN_TUPLE(PreambleCorrelator, getPreamble));
this->registerCall(this, POTHOS_FCN_TUPLE(PreambleCorrelator, setThreshold));
this->registerCall(this, POTHOS_FCN_TUPLE(PreambleCorrelator, getThreshold));
this->registerCall(this, POTHOS_FCN_TUPLE(PreambleCorrelator, setFrameStartId));
this->registerCall(this, POTHOS_FCN_TUPLE(PreambleCorrelator, getFrameStartId));
this->setPreamble(std::vector<unsigned char>(1, 1)); //initial update
this->setThreshold(1); //initial update
this->setFrameStartId("frameStart"); //initial update
}
void setPreamble(const std::vector<unsigned char> preamble)
{
if (preamble.empty()) throw Pothos::InvalidArgumentException("PreambleCorrelator::setPreamble()", "preamble cannot be empty");
_preamble = preamble;
}
std::vector<unsigned char> getPreamble(void) const
{
return _preamble;
}
void setThreshold(const unsigned threshold)
{
_threshold = threshold;
}
unsigned getThreshold(void) const
{
return _threshold;
}
void setFrameStartId(std::string id)
{
_frameStartId = id;
}
std::string getFrameStartId(void) const
{
return _frameStartId;
}
//! always use a circular buffer to avoid discontinuity over sliding window
Pothos::BufferManager::Sptr getInputBufferManager(const std::string &, const std::string &)
{
return Pothos::BufferManager::make("circular");
}
void work(void)
{
auto inputPort = this->input(0);
auto outputPort = this->output(0);
//auto outputDistance = this->output(1);
//require preamble size + 1 elements to perform processing
inputPort->setReserve(_preamble.size()+1);
auto buffer = inputPort->takeBuffer();
if (buffer.length <= (size_t) _preamble.size()) return;
//due to search window, the last preamble size elements are used
//consume and forward all processable elements of the input buffer
buffer.length -= _preamble.size();
inputPort->consume(buffer.length);
// Calculate Hamming distance at each position looking for match
// When a match is found a label is created after the preamble
unsigned char *in = buffer;
//auto distance = outputDistance->buffer().template as<unsigned *>();
for (size_t n = 0; n < buffer.length; n++)
{
unsigned dist = 0;
// Count the number of bits set
for (size_t i = 0; i < _preamble.size(); i++)
{
// A bit is set, so increment the distance
dist += __popcnt(_preamble[i] ^ in[n+i]);
}
// Emit a label if within the distance threshold
if (dist <= _threshold)
{
outputPort->postLabel(_frameStartId, Pothos::Object(), n + _preamble.size());
}
//distance[n] = dist;
}
//outputDistance->produce(N);
outputPort->postBuffer(std::move(buffer));
}
private:
unsigned _threshold;
std::string _frameStartId;
std::vector<unsigned char> _preamble;
};
/***********************************************************************
* registration
**********************************************************************/
static Pothos::BlockRegistry registerPreambleCorrelator(
"/comms/preamble_correlator", &PreambleCorrelator::make);
static Pothos::BlockRegistry registerPreambleCorrelatorOldPath(
"/blocks/preamble_correlator", &PreambleCorrelator::make);
| 34.194118
| 134
| 0.63616
|
willcode
|
a0bad0063e69e3863c1aa851d4a4bb70261e6ebc
| 1,209
|
cpp
|
C++
|
LeetCode/ThousandTwo/1417-reformat_the_string.cpp
|
Ginkgo-Biloba/Cpp-Repo1-VS
|
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
|
[
"Apache-2.0"
] | null | null | null |
LeetCode/ThousandTwo/1417-reformat_the_string.cpp
|
Ginkgo-Biloba/Cpp-Repo1-VS
|
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
|
[
"Apache-2.0"
] | null | null | null |
LeetCode/ThousandTwo/1417-reformat_the_string.cpp
|
Ginkgo-Biloba/Cpp-Repo1-VS
|
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
|
[
"Apache-2.0"
] | null | null | null |
#include "leetcode.hpp"
/* 1417. 重新格式化字符串
给你一个混合了数字和字母的字符串 s,其中的字母均为小写英文字母。
请你将该字符串重新格式化,使得任意两个相邻字符的类型都不同。
也就是说,字母后面应该跟着数字,而数字后面应该跟着字母。
请你返回 重新格式化后 的字符串;如果无法按要求重新格式化,则返回一个 空字符串 。
示例 1:
输入:s = "a0b1c2"
输出:"0a1b2c"
解释:"0a1b2c" 中任意两个相邻字符的类型都不同。 "a0b1c2", "0a1b2c", "0c2a1b" 也是满足题目要求的答案。
示例 2:
输入:s = "leetcode"
输出:""
解释:"leetcode" 中只有字母,所以无法满足重新格式化的条件。
示例 3:
输入:s = "1229857369"
输出:""
解释:"1229857369" 中只有数字,所以无法满足重新格式化的条件。
示例 4:
输入:s = "covid2019"
输出:"c2o0v1i9d"
示例 5:
输入:s = "ab123"
输出:"1a2b3"
提示:
1 <= s.length <= 500
s 仅由小写英文字母和/或数字组成。
*/
string reformat(string s)
{
vector<char> c, d;
for (char i : s)
{
if (isdigit(i))
d.push_back(i);
else
c.push_back(i);
}
s.clear();
if ((c.size() > d.size() + 1)
|| (d.size() > c.size() + 1))
return s;
if (c.size() > d.size())
{
s.push_back(c.back());
c.pop_back();
}
while (!d.empty() && !c.empty())
{
s.push_back(d.back());
s.push_back(c.back());
d.pop_back();
c.pop_back();
}
if (d.size())
s.push_back(d.back());
return s;
}
int main()
{
OutString(reformat("a0b1c2"));
OutString(reformat("leetcode"));
OutString(reformat("1229857369"));
OutString(reformat("covid2019"));
OutString(reformat("ab123"));
}
| 14.925926
| 70
| 0.629446
|
Ginkgo-Biloba
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.