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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a5a55785d16c0776771febb562ea2df534e17a29
| 1,573
|
cpp
|
C++
|
src/propertybrowser/propertymanager/charpropertymanager.cpp
|
bitdewy/Ya
|
9e075712b311a2403b4cc0ef5be24b05f523be3e
|
[
"BSD-3-Clause"
] | null | null | null |
src/propertybrowser/propertymanager/charpropertymanager.cpp
|
bitdewy/Ya
|
9e075712b311a2403b4cc0ef5be24b05f523be3e
|
[
"BSD-3-Clause"
] | null | null | null |
src/propertybrowser/propertymanager/charpropertymanager.cpp
|
bitdewy/Ya
|
9e075712b311a2403b4cc0ef5be24b05f523be3e
|
[
"BSD-3-Clause"
] | null | null | null |
/****************************************************************************
**
** BSD 3-Clause License
**
** Copyright (c) 2017, bitdewy
** All rights reserved.
**
****************************************************************************/
#include "charpropertymanager.h"
#include "private/charpropertymanager_p.h"
#include "private/propertymanagerutils_p.h"
CharPropertyManager::CharPropertyManager(QObject* parent) :
AbstractPropertyManager(parent),
impl_(new CharPropertyManagerPrivate)
{
impl_->charPropertyManagerPtr_ = this;
}
CharPropertyManager::~CharPropertyManager()
{
clear();
}
QChar CharPropertyManager::value(const Property* property) const
{
return impl_->values_.value(property, QChar());
}
QString CharPropertyManager::valueText(const Property* property) const
{
const auto it = impl_->values_.constFind(property);
if (it == impl_->values_.constEnd())
{
return QString();
}
const auto c = it.value();
return c.isNull() ? QString() : QString(c);
}
void CharPropertyManager::setValue(Property* property, const QChar& val)
{
setSimpleValue<const QChar&, QChar, CharPropertyManager>(impl_->values_, this,
&CharPropertyManager::propertyChanged,
&CharPropertyManager::valueChanged,
property, val);
}
void CharPropertyManager::initializeProperty(Property* property)
{
impl_->values_[property] = {};
}
void CharPropertyManager::uninitializeProperty(Property *property)
{
impl_->values_.remove(property);
}
| 26.661017
| 83
| 0.623013
|
bitdewy
|
a5a9c867cf4eda233717bc988bf4a5fd7b8a4292
| 561
|
cpp
|
C++
|
temp/c.cpp
|
tysm/cpsols
|
262212646203e516d1706edf962290de93762611
|
[
"MIT"
] | 4
|
2020-10-05T19:24:10.000Z
|
2021-07-15T00:45:43.000Z
|
temp/c.cpp
|
tysm/cpsols
|
262212646203e516d1706edf962290de93762611
|
[
"MIT"
] | null | null | null |
temp/c.cpp
|
tysm/cpsols
|
262212646203e516d1706edf962290de93762611
|
[
"MIT"
] | null | null | null |
#include <cpplib/stdinc.hpp>
int32_t main(){
desync();
int n, m, h;
cin >> n >> m >> h;
n--;
int sum = 0, hx;
for(int i=1; i<=m; ++i){
int x;
cin >> x;
if(i != h)
sum += x;
else
hx = x-1;
}
if(sum+hx< n)
cout << -1 << endl;
else{
double acc = 1, ans = 0;
for(int i=0; i<n; ++i){
ans += acc*(double)hx/(sum+hx);
acc *= (double)sum/(sum+hx);
sum--;
}
cout << ans << endl;
}
return 0;
}
| 18.7
| 43
| 0.354724
|
tysm
|
a5aa23843fee02aae0544ba7b1a526be89c1cecd
| 270
|
cpp
|
C++
|
tests/codegen/if_variable.cpp
|
xuchunmei000/bpftrace
|
44c6cbd4f8d40c64a74b4a3ffad22532c5c05385
|
[
"Apache-2.0"
] | 5,119
|
2018-10-08T15:19:24.000Z
|
2022-03-31T15:03:48.000Z
|
tests/codegen/if_variable.cpp
|
xuchunmei000/bpftrace
|
44c6cbd4f8d40c64a74b4a3ffad22532c5c05385
|
[
"Apache-2.0"
] | 1,568
|
2018-10-08T19:14:25.000Z
|
2022-03-31T01:44:41.000Z
|
tests/codegen/if_variable.cpp
|
xuchunmei000/bpftrace
|
44c6cbd4f8d40c64a74b4a3ffad22532c5c05385
|
[
"Apache-2.0"
] | 838
|
2018-10-08T20:16:47.000Z
|
2022-03-31T06:15:58.000Z
|
#include "common.h"
namespace bpftrace {
namespace test {
namespace codegen {
TEST(codegen, if_variable)
{
test("kprobe:f { if (pid > 10000) { $s = 10 } printf(\"s = %d\", $s); }",
NAME);
}
} // namespace codegen
} // namespace test
} // namespace bpftrace
| 15.882353
| 75
| 0.611111
|
xuchunmei000
|
a5aa33d3951374a6818c8cf07d6ab2da282b8942
| 992
|
cpp
|
C++
|
Algorithms/Warmup/time-conversion.cpp
|
vishu006/Hackerrank
|
927bc370b668aa568d17ee96ac2a3728568d437e
|
[
"CC-BY-4.0"
] | 1
|
2017-08-12T19:18:12.000Z
|
2017-08-12T19:18:12.000Z
|
Algorithms/Warmup/time-conversion.cpp
|
vishu006/Hackerrank
|
927bc370b668aa568d17ee96ac2a3728568d437e
|
[
"CC-BY-4.0"
] | null | null | null |
Algorithms/Warmup/time-conversion.cpp
|
vishu006/Hackerrank
|
927bc370b668aa568d17ee96ac2a3728568d437e
|
[
"CC-BY-4.0"
] | null | null | null |
// Author : Rajanikant Tenguria
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
string x;
cin>>x;
if (x[8]=='A'){
int y=int(x[0])-48;
int a=int(x[1])-48;
int b=10*y+a;
if(b>11){
cout<<b-12;
cout<<"0";
for (int i=2;i<8;i++){
cout<<x[i];
}
}
else{
for (int i=0;i<8;i++){
cout<<x[i];
}
}
}
else{
int y=int(x[0])-48;
int a=int(x[1])-48;
int b=10*y+a;
if(b==12){
for (int i=0;i<8;i++){
cout<<x[i];
}
}
else{
cout<<b+12;
for (int i=2;i<8;i++){
cout<<x[i];
}
}
}
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
return 0;
}
| 19.84
| 80
| 0.365927
|
vishu006
|
a5add4ca0e653a8ee608e04897de74ebb669a221
| 85,693
|
cc
|
C++
|
wrappers/7.0.0/vtkInformationWrap.cc
|
axkibe/node-vtk
|
900ad7b5500f672519da5aa24c99aa5a96466ef3
|
[
"BSD-3-Clause"
] | 6
|
2016-02-03T12:48:36.000Z
|
2020-09-16T15:07:51.000Z
|
wrappers/7.0.0/vtkInformationWrap.cc
|
axkibe/node-vtk
|
900ad7b5500f672519da5aa24c99aa5a96466ef3
|
[
"BSD-3-Clause"
] | 4
|
2016-02-13T01:30:43.000Z
|
2020-03-30T16:59:32.000Z
|
wrappers/7.0.0/vtkInformationWrap.cc
|
axkibe/node-vtk
|
900ad7b5500f672519da5aa24c99aa5a96466ef3
|
[
"BSD-3-Clause"
] | null | null | null |
/* this file has been autogenerated by vtkNodeJsWrap */
/* editing this might proof futile */
#define VTK_WRAPPING_CXX
#define VTK_STREAMS_FWD_ONLY
#include <nan.h>
#include "vtkObjectWrap.h"
#include "vtkInformationWrap.h"
#include "vtkInformationKeyWrap.h"
#include "vtkInformationDataObjectKeyWrap.h"
#include "vtkInformationDoubleVectorKeyWrap.h"
#include "vtkInformationVariantKeyWrap.h"
#include "vtkInformationVariantVectorKeyWrap.h"
#include "vtkInformationInformationKeyWrap.h"
#include "vtkInformationInformationVectorKeyWrap.h"
#include "vtkInformationIntegerKeyWrap.h"
#include "vtkInformationIntegerVectorKeyWrap.h"
#include "vtkInformationRequestKeyWrap.h"
#include "vtkInformationStringKeyWrap.h"
#include "vtkInformationStringVectorKeyWrap.h"
#include "vtkInformationUnsignedLongKeyWrap.h"
#include "vtkInformationKeyVectorKeyWrap.h"
#include "vtkInformationIdTypeKeyWrap.h"
#include "vtkInformationDoubleKeyWrap.h"
#include "vtkInformationIntegerPointerKeyWrap.h"
#include "vtkInformationObjectBaseKeyWrap.h"
#include "vtkInformationVectorWrap.h"
#include "vtkObjectBaseWrap.h"
#include "vtkDataObjectWrap.h"
#include "../../plus/plus.h"
using namespace v8;
extern Nan::Persistent<v8::Object> vtkNodeJsNoWrap;
Nan::Persistent<v8::FunctionTemplate> VtkInformationWrap::ptpl;
VtkInformationWrap::VtkInformationWrap()
{ }
VtkInformationWrap::VtkInformationWrap(vtkSmartPointer<vtkInformation> _native)
{ native = _native; }
VtkInformationWrap::~VtkInformationWrap()
{ }
void VtkInformationWrap::Init(v8::Local<v8::Object> exports)
{
Nan::SetAccessor(exports, Nan::New("vtkInformation").ToLocalChecked(), ConstructorGetter);
Nan::SetAccessor(exports, Nan::New("Information").ToLocalChecked(), ConstructorGetter);
}
void VtkInformationWrap::ConstructorGetter(
v8::Local<v8::String> property,
const Nan::PropertyCallbackInfo<v8::Value>& info)
{
InitPtpl();
info.GetReturnValue().Set(Nan::New(ptpl)->GetFunction());
}
void VtkInformationWrap::InitPtpl()
{
if (!ptpl.IsEmpty()) return;
v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
VtkObjectWrap::InitPtpl( );
tpl->Inherit(Nan::New<FunctionTemplate>(VtkObjectWrap::ptpl));
tpl->SetClassName(Nan::New("VtkInformationWrap").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);
Nan::SetPrototypeMethod(tpl, "Append", Append);
Nan::SetPrototypeMethod(tpl, "append", Append);
Nan::SetPrototypeMethod(tpl, "AppendUnique", AppendUnique);
Nan::SetPrototypeMethod(tpl, "appendUnique", AppendUnique);
Nan::SetPrototypeMethod(tpl, "Clear", Clear);
Nan::SetPrototypeMethod(tpl, "clear", Clear);
Nan::SetPrototypeMethod(tpl, "Copy", Copy);
Nan::SetPrototypeMethod(tpl, "copy", Copy);
Nan::SetPrototypeMethod(tpl, "CopyEntries", CopyEntries);
Nan::SetPrototypeMethod(tpl, "copyEntries", CopyEntries);
Nan::SetPrototypeMethod(tpl, "CopyEntry", CopyEntry);
Nan::SetPrototypeMethod(tpl, "copyEntry", CopyEntry);
Nan::SetPrototypeMethod(tpl, "Get", Get);
Nan::SetPrototypeMethod(tpl, "get", Get);
Nan::SetPrototypeMethod(tpl, "GetClassName", GetClassName);
Nan::SetPrototypeMethod(tpl, "getClassName", GetClassName);
Nan::SetPrototypeMethod(tpl, "GetKey", GetKey);
Nan::SetPrototypeMethod(tpl, "getKey", GetKey);
Nan::SetPrototypeMethod(tpl, "GetNumberOfKeys", GetNumberOfKeys);
Nan::SetPrototypeMethod(tpl, "getNumberOfKeys", GetNumberOfKeys);
Nan::SetPrototypeMethod(tpl, "GetRequest", GetRequest);
Nan::SetPrototypeMethod(tpl, "getRequest", GetRequest);
Nan::SetPrototypeMethod(tpl, "Has", Has);
Nan::SetPrototypeMethod(tpl, "has", Has);
Nan::SetPrototypeMethod(tpl, "IsA", IsA);
Nan::SetPrototypeMethod(tpl, "isA", IsA);
Nan::SetPrototypeMethod(tpl, "Length", Length);
Nan::SetPrototypeMethod(tpl, "length", Length);
Nan::SetPrototypeMethod(tpl, "Modified", Modified);
Nan::SetPrototypeMethod(tpl, "modified", Modified);
Nan::SetPrototypeMethod(tpl, "NewInstance", NewInstance);
Nan::SetPrototypeMethod(tpl, "newInstance", NewInstance);
Nan::SetPrototypeMethod(tpl, "Remove", Remove);
Nan::SetPrototypeMethod(tpl, "remove", Remove);
Nan::SetPrototypeMethod(tpl, "SafeDownCast", SafeDownCast);
Nan::SetPrototypeMethod(tpl, "safeDownCast", SafeDownCast);
Nan::SetPrototypeMethod(tpl, "Set", Set);
Nan::SetPrototypeMethod(tpl, "set", Set);
Nan::SetPrototypeMethod(tpl, "SetRequest", SetRequest);
Nan::SetPrototypeMethod(tpl, "setRequest", SetRequest);
#ifdef VTK_NODE_PLUS_VTKINFORMATIONWRAP_INITPTPL
VTK_NODE_PLUS_VTKINFORMATIONWRAP_INITPTPL
#endif
ptpl.Reset( tpl );
}
void VtkInformationWrap::New(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
if(!info.IsConstructCall())
{
Nan::ThrowError("Constructor not called in a construct call.");
return;
}
if(info.Length() == 0)
{
vtkSmartPointer<vtkInformation> native = vtkSmartPointer<vtkInformation>::New();
VtkInformationWrap* obj = new VtkInformationWrap(native);
obj->Wrap(info.This());
}
else
{
if(info[0]->ToObject() != vtkNodeJsNoWrap )
{
Nan::ThrowError("Parameter Error");
return;
}
}
info.GetReturnValue().Set(info.This());
}
void VtkInformationWrap::Append(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkInformationWrap *wrapper = ObjectWrap::Unwrap<VtkInformationWrap>(info.Holder());
vtkInformation *native = (vtkInformation *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationStringVectorKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationStringVectorKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationStringVectorKeyWrap>(info[0]->ToObject());
if(info.Length() > 1 && info[1]->IsString())
{
Nan::Utf8String a1(info[1]);
if(info.Length() != 2)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Append(
(vtkInformationStringVectorKey *) a0->native.GetPointer(),
*a1
);
return;
}
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationKeyVectorKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationKeyVectorKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationKeyVectorKeyWrap>(info[0]->ToObject());
if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkInformationUnsignedLongKeyWrap::ptpl))->HasInstance(info[1]))
{
VtkInformationUnsignedLongKeyWrap *a1 = ObjectWrap::Unwrap<VtkInformationUnsignedLongKeyWrap>(info[1]->ToObject());
if(info.Length() != 2)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Append(
(vtkInformationKeyVectorKey *) a0->native.GetPointer(),
(vtkInformationUnsignedLongKey *) a1->native.GetPointer()
);
return;
}
else if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkInformationObjectBaseKeyWrap::ptpl))->HasInstance(info[1]))
{
VtkInformationObjectBaseKeyWrap *a1 = ObjectWrap::Unwrap<VtkInformationObjectBaseKeyWrap>(info[1]->ToObject());
if(info.Length() != 2)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Append(
(vtkInformationKeyVectorKey *) a0->native.GetPointer(),
(vtkInformationObjectBaseKey *) a1->native.GetPointer()
);
return;
}
else if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkInformationStringVectorKeyWrap::ptpl))->HasInstance(info[1]))
{
VtkInformationStringVectorKeyWrap *a1 = ObjectWrap::Unwrap<VtkInformationStringVectorKeyWrap>(info[1]->ToObject());
if(info.Length() != 2)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Append(
(vtkInformationKeyVectorKey *) a0->native.GetPointer(),
(vtkInformationStringVectorKey *) a1->native.GetPointer()
);
return;
}
else if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkInformationStringKeyWrap::ptpl))->HasInstance(info[1]))
{
VtkInformationStringKeyWrap *a1 = ObjectWrap::Unwrap<VtkInformationStringKeyWrap>(info[1]->ToObject());
if(info.Length() != 2)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Append(
(vtkInformationKeyVectorKey *) a0->native.GetPointer(),
(vtkInformationStringKey *) a1->native.GetPointer()
);
return;
}
else if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkInformationIntegerVectorKeyWrap::ptpl))->HasInstance(info[1]))
{
VtkInformationIntegerVectorKeyWrap *a1 = ObjectWrap::Unwrap<VtkInformationIntegerVectorKeyWrap>(info[1]->ToObject());
if(info.Length() != 2)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Append(
(vtkInformationKeyVectorKey *) a0->native.GetPointer(),
(vtkInformationIntegerVectorKey *) a1->native.GetPointer()
);
return;
}
else if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkInformationIntegerKeyWrap::ptpl))->HasInstance(info[1]))
{
VtkInformationIntegerKeyWrap *a1 = ObjectWrap::Unwrap<VtkInformationIntegerKeyWrap>(info[1]->ToObject());
if(info.Length() != 2)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Append(
(vtkInformationKeyVectorKey *) a0->native.GetPointer(),
(vtkInformationIntegerKey *) a1->native.GetPointer()
);
return;
}
else if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkInformationInformationVectorKeyWrap::ptpl))->HasInstance(info[1]))
{
VtkInformationInformationVectorKeyWrap *a1 = ObjectWrap::Unwrap<VtkInformationInformationVectorKeyWrap>(info[1]->ToObject());
if(info.Length() != 2)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Append(
(vtkInformationKeyVectorKey *) a0->native.GetPointer(),
(vtkInformationInformationVectorKey *) a1->native.GetPointer()
);
return;
}
else if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkInformationInformationKeyWrap::ptpl))->HasInstance(info[1]))
{
VtkInformationInformationKeyWrap *a1 = ObjectWrap::Unwrap<VtkInformationInformationKeyWrap>(info[1]->ToObject());
if(info.Length() != 2)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Append(
(vtkInformationKeyVectorKey *) a0->native.GetPointer(),
(vtkInformationInformationKey *) a1->native.GetPointer()
);
return;
}
else if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkInformationDoubleVectorKeyWrap::ptpl))->HasInstance(info[1]))
{
VtkInformationDoubleVectorKeyWrap *a1 = ObjectWrap::Unwrap<VtkInformationDoubleVectorKeyWrap>(info[1]->ToObject());
if(info.Length() != 2)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Append(
(vtkInformationKeyVectorKey *) a0->native.GetPointer(),
(vtkInformationDoubleVectorKey *) a1->native.GetPointer()
);
return;
}
else if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkInformationDoubleKeyWrap::ptpl))->HasInstance(info[1]))
{
VtkInformationDoubleKeyWrap *a1 = ObjectWrap::Unwrap<VtkInformationDoubleKeyWrap>(info[1]->ToObject());
if(info.Length() != 2)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Append(
(vtkInformationKeyVectorKey *) a0->native.GetPointer(),
(vtkInformationDoubleKey *) a1->native.GetPointer()
);
return;
}
else if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkInformationDataObjectKeyWrap::ptpl))->HasInstance(info[1]))
{
VtkInformationDataObjectKeyWrap *a1 = ObjectWrap::Unwrap<VtkInformationDataObjectKeyWrap>(info[1]->ToObject());
if(info.Length() != 2)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Append(
(vtkInformationKeyVectorKey *) a0->native.GetPointer(),
(vtkInformationDataObjectKey *) a1->native.GetPointer()
);
return;
}
else if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkInformationKeyWrap::ptpl))->HasInstance(info[1]))
{
VtkInformationKeyWrap *a1 = ObjectWrap::Unwrap<VtkInformationKeyWrap>(info[1]->ToObject());
if(info.Length() != 2)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Append(
(vtkInformationKeyVectorKey *) a0->native.GetPointer(),
(vtkInformationKey *) a1->native.GetPointer()
);
return;
}
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationDoubleVectorKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationDoubleVectorKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationDoubleVectorKeyWrap>(info[0]->ToObject());
if(info.Length() > 1 && info[1]->IsNumber())
{
if(info.Length() != 2)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Append(
(vtkInformationDoubleVectorKey *) a0->native.GetPointer(),
info[1]->NumberValue()
);
return;
}
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationIntegerVectorKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationIntegerVectorKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationIntegerVectorKeyWrap>(info[0]->ToObject());
if(info.Length() > 1 && info[1]->IsInt32())
{
if(info.Length() != 2)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Append(
(vtkInformationIntegerVectorKey *) a0->native.GetPointer(),
info[1]->Int32Value()
);
return;
}
}
Nan::ThrowError("Parameter mismatch");
}
void VtkInformationWrap::AppendUnique(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkInformationWrap *wrapper = ObjectWrap::Unwrap<VtkInformationWrap>(info.Holder());
vtkInformation *native = (vtkInformation *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationKeyVectorKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationKeyVectorKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationKeyVectorKeyWrap>(info[0]->ToObject());
if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkInformationUnsignedLongKeyWrap::ptpl))->HasInstance(info[1]))
{
VtkInformationUnsignedLongKeyWrap *a1 = ObjectWrap::Unwrap<VtkInformationUnsignedLongKeyWrap>(info[1]->ToObject());
if(info.Length() != 2)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->AppendUnique(
(vtkInformationKeyVectorKey *) a0->native.GetPointer(),
(vtkInformationUnsignedLongKey *) a1->native.GetPointer()
);
return;
}
else if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkInformationObjectBaseKeyWrap::ptpl))->HasInstance(info[1]))
{
VtkInformationObjectBaseKeyWrap *a1 = ObjectWrap::Unwrap<VtkInformationObjectBaseKeyWrap>(info[1]->ToObject());
if(info.Length() != 2)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->AppendUnique(
(vtkInformationKeyVectorKey *) a0->native.GetPointer(),
(vtkInformationObjectBaseKey *) a1->native.GetPointer()
);
return;
}
else if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkInformationStringVectorKeyWrap::ptpl))->HasInstance(info[1]))
{
VtkInformationStringVectorKeyWrap *a1 = ObjectWrap::Unwrap<VtkInformationStringVectorKeyWrap>(info[1]->ToObject());
if(info.Length() != 2)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->AppendUnique(
(vtkInformationKeyVectorKey *) a0->native.GetPointer(),
(vtkInformationStringVectorKey *) a1->native.GetPointer()
);
return;
}
else if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkInformationStringKeyWrap::ptpl))->HasInstance(info[1]))
{
VtkInformationStringKeyWrap *a1 = ObjectWrap::Unwrap<VtkInformationStringKeyWrap>(info[1]->ToObject());
if(info.Length() != 2)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->AppendUnique(
(vtkInformationKeyVectorKey *) a0->native.GetPointer(),
(vtkInformationStringKey *) a1->native.GetPointer()
);
return;
}
else if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkInformationIntegerVectorKeyWrap::ptpl))->HasInstance(info[1]))
{
VtkInformationIntegerVectorKeyWrap *a1 = ObjectWrap::Unwrap<VtkInformationIntegerVectorKeyWrap>(info[1]->ToObject());
if(info.Length() != 2)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->AppendUnique(
(vtkInformationKeyVectorKey *) a0->native.GetPointer(),
(vtkInformationIntegerVectorKey *) a1->native.GetPointer()
);
return;
}
else if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkInformationIntegerKeyWrap::ptpl))->HasInstance(info[1]))
{
VtkInformationIntegerKeyWrap *a1 = ObjectWrap::Unwrap<VtkInformationIntegerKeyWrap>(info[1]->ToObject());
if(info.Length() != 2)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->AppendUnique(
(vtkInformationKeyVectorKey *) a0->native.GetPointer(),
(vtkInformationIntegerKey *) a1->native.GetPointer()
);
return;
}
else if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkInformationInformationVectorKeyWrap::ptpl))->HasInstance(info[1]))
{
VtkInformationInformationVectorKeyWrap *a1 = ObjectWrap::Unwrap<VtkInformationInformationVectorKeyWrap>(info[1]->ToObject());
if(info.Length() != 2)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->AppendUnique(
(vtkInformationKeyVectorKey *) a0->native.GetPointer(),
(vtkInformationInformationVectorKey *) a1->native.GetPointer()
);
return;
}
else if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkInformationInformationKeyWrap::ptpl))->HasInstance(info[1]))
{
VtkInformationInformationKeyWrap *a1 = ObjectWrap::Unwrap<VtkInformationInformationKeyWrap>(info[1]->ToObject());
if(info.Length() != 2)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->AppendUnique(
(vtkInformationKeyVectorKey *) a0->native.GetPointer(),
(vtkInformationInformationKey *) a1->native.GetPointer()
);
return;
}
else if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkInformationDoubleVectorKeyWrap::ptpl))->HasInstance(info[1]))
{
VtkInformationDoubleVectorKeyWrap *a1 = ObjectWrap::Unwrap<VtkInformationDoubleVectorKeyWrap>(info[1]->ToObject());
if(info.Length() != 2)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->AppendUnique(
(vtkInformationKeyVectorKey *) a0->native.GetPointer(),
(vtkInformationDoubleVectorKey *) a1->native.GetPointer()
);
return;
}
else if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkInformationDoubleKeyWrap::ptpl))->HasInstance(info[1]))
{
VtkInformationDoubleKeyWrap *a1 = ObjectWrap::Unwrap<VtkInformationDoubleKeyWrap>(info[1]->ToObject());
if(info.Length() != 2)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->AppendUnique(
(vtkInformationKeyVectorKey *) a0->native.GetPointer(),
(vtkInformationDoubleKey *) a1->native.GetPointer()
);
return;
}
else if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkInformationDataObjectKeyWrap::ptpl))->HasInstance(info[1]))
{
VtkInformationDataObjectKeyWrap *a1 = ObjectWrap::Unwrap<VtkInformationDataObjectKeyWrap>(info[1]->ToObject());
if(info.Length() != 2)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->AppendUnique(
(vtkInformationKeyVectorKey *) a0->native.GetPointer(),
(vtkInformationDataObjectKey *) a1->native.GetPointer()
);
return;
}
else if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkInformationKeyWrap::ptpl))->HasInstance(info[1]))
{
VtkInformationKeyWrap *a1 = ObjectWrap::Unwrap<VtkInformationKeyWrap>(info[1]->ToObject());
if(info.Length() != 2)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->AppendUnique(
(vtkInformationKeyVectorKey *) a0->native.GetPointer(),
(vtkInformationKey *) a1->native.GetPointer()
);
return;
}
}
Nan::ThrowError("Parameter mismatch");
}
void VtkInformationWrap::Clear(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkInformationWrap *wrapper = ObjectWrap::Unwrap<VtkInformationWrap>(info.Holder());
vtkInformation *native = (vtkInformation *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Clear();
}
void VtkInformationWrap::Copy(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkInformationWrap *wrapper = ObjectWrap::Unwrap<VtkInformationWrap>(info.Holder());
vtkInformation *native = (vtkInformation *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationWrap *a0 = ObjectWrap::Unwrap<VtkInformationWrap>(info[0]->ToObject());
if(info.Length() > 1 && info[1]->IsInt32())
{
if(info.Length() != 2)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Copy(
(vtkInformation *) a0->native.GetPointer(),
info[1]->Int32Value()
);
return;
}
}
Nan::ThrowError("Parameter mismatch");
}
void VtkInformationWrap::CopyEntries(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkInformationWrap *wrapper = ObjectWrap::Unwrap<VtkInformationWrap>(info.Holder());
vtkInformation *native = (vtkInformation *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationWrap *a0 = ObjectWrap::Unwrap<VtkInformationWrap>(info[0]->ToObject());
if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkInformationKeyVectorKeyWrap::ptpl))->HasInstance(info[1]))
{
VtkInformationKeyVectorKeyWrap *a1 = ObjectWrap::Unwrap<VtkInformationKeyVectorKeyWrap>(info[1]->ToObject());
if(info.Length() > 2 && info[2]->IsInt32())
{
if(info.Length() != 3)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->CopyEntries(
(vtkInformation *) a0->native.GetPointer(),
(vtkInformationKeyVectorKey *) a1->native.GetPointer(),
info[2]->Int32Value()
);
return;
}
}
}
Nan::ThrowError("Parameter mismatch");
}
void VtkInformationWrap::CopyEntry(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkInformationWrap *wrapper = ObjectWrap::Unwrap<VtkInformationWrap>(info.Holder());
vtkInformation *native = (vtkInformation *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationWrap *a0 = ObjectWrap::Unwrap<VtkInformationWrap>(info[0]->ToObject());
if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkInformationUnsignedLongKeyWrap::ptpl))->HasInstance(info[1]))
{
VtkInformationUnsignedLongKeyWrap *a1 = ObjectWrap::Unwrap<VtkInformationUnsignedLongKeyWrap>(info[1]->ToObject());
if(info.Length() > 2 && info[2]->IsInt32())
{
if(info.Length() != 3)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->CopyEntry(
(vtkInformation *) a0->native.GetPointer(),
(vtkInformationUnsignedLongKey *) a1->native.GetPointer(),
info[2]->Int32Value()
);
return;
}
}
else if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkInformationStringVectorKeyWrap::ptpl))->HasInstance(info[1]))
{
VtkInformationStringVectorKeyWrap *a1 = ObjectWrap::Unwrap<VtkInformationStringVectorKeyWrap>(info[1]->ToObject());
if(info.Length() > 2 && info[2]->IsInt32())
{
if(info.Length() != 3)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->CopyEntry(
(vtkInformation *) a0->native.GetPointer(),
(vtkInformationStringVectorKey *) a1->native.GetPointer(),
info[2]->Int32Value()
);
return;
}
}
else if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkInformationStringKeyWrap::ptpl))->HasInstance(info[1]))
{
VtkInformationStringKeyWrap *a1 = ObjectWrap::Unwrap<VtkInformationStringKeyWrap>(info[1]->ToObject());
if(info.Length() > 2 && info[2]->IsInt32())
{
if(info.Length() != 3)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->CopyEntry(
(vtkInformation *) a0->native.GetPointer(),
(vtkInformationStringKey *) a1->native.GetPointer(),
info[2]->Int32Value()
);
return;
}
}
else if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkInformationRequestKeyWrap::ptpl))->HasInstance(info[1]))
{
VtkInformationRequestKeyWrap *a1 = ObjectWrap::Unwrap<VtkInformationRequestKeyWrap>(info[1]->ToObject());
if(info.Length() > 2 && info[2]->IsInt32())
{
if(info.Length() != 3)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->CopyEntry(
(vtkInformation *) a0->native.GetPointer(),
(vtkInformationRequestKey *) a1->native.GetPointer(),
info[2]->Int32Value()
);
return;
}
}
else if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkInformationIntegerVectorKeyWrap::ptpl))->HasInstance(info[1]))
{
VtkInformationIntegerVectorKeyWrap *a1 = ObjectWrap::Unwrap<VtkInformationIntegerVectorKeyWrap>(info[1]->ToObject());
if(info.Length() > 2 && info[2]->IsInt32())
{
if(info.Length() != 3)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->CopyEntry(
(vtkInformation *) a0->native.GetPointer(),
(vtkInformationIntegerVectorKey *) a1->native.GetPointer(),
info[2]->Int32Value()
);
return;
}
}
else if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkInformationIntegerKeyWrap::ptpl))->HasInstance(info[1]))
{
VtkInformationIntegerKeyWrap *a1 = ObjectWrap::Unwrap<VtkInformationIntegerKeyWrap>(info[1]->ToObject());
if(info.Length() > 2 && info[2]->IsInt32())
{
if(info.Length() != 3)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->CopyEntry(
(vtkInformation *) a0->native.GetPointer(),
(vtkInformationIntegerKey *) a1->native.GetPointer(),
info[2]->Int32Value()
);
return;
}
}
else if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkInformationInformationVectorKeyWrap::ptpl))->HasInstance(info[1]))
{
VtkInformationInformationVectorKeyWrap *a1 = ObjectWrap::Unwrap<VtkInformationInformationVectorKeyWrap>(info[1]->ToObject());
if(info.Length() > 2 && info[2]->IsInt32())
{
if(info.Length() != 3)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->CopyEntry(
(vtkInformation *) a0->native.GetPointer(),
(vtkInformationInformationVectorKey *) a1->native.GetPointer(),
info[2]->Int32Value()
);
return;
}
}
else if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkInformationInformationKeyWrap::ptpl))->HasInstance(info[1]))
{
VtkInformationInformationKeyWrap *a1 = ObjectWrap::Unwrap<VtkInformationInformationKeyWrap>(info[1]->ToObject());
if(info.Length() > 2 && info[2]->IsInt32())
{
if(info.Length() != 3)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->CopyEntry(
(vtkInformation *) a0->native.GetPointer(),
(vtkInformationInformationKey *) a1->native.GetPointer(),
info[2]->Int32Value()
);
return;
}
}
else if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkInformationVariantVectorKeyWrap::ptpl))->HasInstance(info[1]))
{
VtkInformationVariantVectorKeyWrap *a1 = ObjectWrap::Unwrap<VtkInformationVariantVectorKeyWrap>(info[1]->ToObject());
if(info.Length() > 2 && info[2]->IsInt32())
{
if(info.Length() != 3)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->CopyEntry(
(vtkInformation *) a0->native.GetPointer(),
(vtkInformationVariantVectorKey *) a1->native.GetPointer(),
info[2]->Int32Value()
);
return;
}
}
else if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkInformationVariantKeyWrap::ptpl))->HasInstance(info[1]))
{
VtkInformationVariantKeyWrap *a1 = ObjectWrap::Unwrap<VtkInformationVariantKeyWrap>(info[1]->ToObject());
if(info.Length() > 2 && info[2]->IsInt32())
{
if(info.Length() != 3)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->CopyEntry(
(vtkInformation *) a0->native.GetPointer(),
(vtkInformationVariantKey *) a1->native.GetPointer(),
info[2]->Int32Value()
);
return;
}
}
else if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkInformationDoubleVectorKeyWrap::ptpl))->HasInstance(info[1]))
{
VtkInformationDoubleVectorKeyWrap *a1 = ObjectWrap::Unwrap<VtkInformationDoubleVectorKeyWrap>(info[1]->ToObject());
if(info.Length() > 2 && info[2]->IsInt32())
{
if(info.Length() != 3)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->CopyEntry(
(vtkInformation *) a0->native.GetPointer(),
(vtkInformationDoubleVectorKey *) a1->native.GetPointer(),
info[2]->Int32Value()
);
return;
}
}
else if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkInformationDataObjectKeyWrap::ptpl))->HasInstance(info[1]))
{
VtkInformationDataObjectKeyWrap *a1 = ObjectWrap::Unwrap<VtkInformationDataObjectKeyWrap>(info[1]->ToObject());
if(info.Length() > 2 && info[2]->IsInt32())
{
if(info.Length() != 3)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->CopyEntry(
(vtkInformation *) a0->native.GetPointer(),
(vtkInformationDataObjectKey *) a1->native.GetPointer(),
info[2]->Int32Value()
);
return;
}
}
else if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkInformationKeyWrap::ptpl))->HasInstance(info[1]))
{
VtkInformationKeyWrap *a1 = ObjectWrap::Unwrap<VtkInformationKeyWrap>(info[1]->ToObject());
if(info.Length() > 2 && info[2]->IsInt32())
{
if(info.Length() != 3)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->CopyEntry(
(vtkInformation *) a0->native.GetPointer(),
(vtkInformationKey *) a1->native.GetPointer(),
info[2]->Int32Value()
);
return;
}
}
}
Nan::ThrowError("Parameter mismatch");
}
void VtkInformationWrap::Get(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkInformationWrap *wrapper = ObjectWrap::Unwrap<VtkInformationWrap>(info.Holder());
vtkInformation *native = (vtkInformation *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationKeyVectorKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationKeyVectorKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationKeyVectorKeyWrap>(info[0]->ToObject());
if(info.Length() > 1 && info[1]->IsInt32())
{
vtkInformationKey * r;
if(info.Length() != 2)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->Get(
(vtkInformationKeyVectorKey *) a0->native.GetPointer(),
info[1]->Int32Value()
);
VtkInformationKeyWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkInformationKeyWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkInformationKeyWrap *w = new VtkInformationKeyWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
return;
}
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationDoubleVectorKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationDoubleVectorKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationDoubleVectorKeyWrap>(info[0]->ToObject());
if(info.Length() > 1 && info[1]->IsInt32())
{
double r;
if(info.Length() != 2)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->Get(
(vtkInformationDoubleVectorKey *) a0->native.GetPointer(),
info[1]->Int32Value()
);
info.GetReturnValue().Set(Nan::New(r));
return;
}
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationStringVectorKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationStringVectorKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationStringVectorKeyWrap>(info[0]->ToObject());
if(info.Length() > 1 && info[1]->IsInt32())
{
char const * r;
if(info.Length() != 2)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->Get(
(vtkInformationStringVectorKey *) a0->native.GetPointer(),
info[1]->Int32Value()
);
info.GetReturnValue().Set(Nan::New(r).ToLocalChecked());
return;
}
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationIntegerVectorKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationIntegerVectorKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationIntegerVectorKeyWrap>(info[0]->ToObject());
if(info.Length() > 1 && info[1]->IsInt32())
{
int r;
if(info.Length() != 2)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->Get(
(vtkInformationIntegerVectorKey *) a0->native.GetPointer(),
info[1]->Int32Value()
);
info.GetReturnValue().Set(Nan::New(r));
return;
}
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationDataObjectKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationDataObjectKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationDataObjectKeyWrap>(info[0]->ToObject());
vtkDataObject * r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->Get(
(vtkInformationDataObjectKey *) a0->native.GetPointer()
);
VtkDataObjectWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkDataObjectWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkDataObjectWrap *w = new VtkDataObjectWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationObjectBaseKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationObjectBaseKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationObjectBaseKeyWrap>(info[0]->ToObject());
vtkObjectBase * r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->Get(
(vtkInformationObjectBaseKey *) a0->native.GetPointer()
);
VtkObjectBaseWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkObjectBaseWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkObjectBaseWrap *w = new VtkObjectBaseWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationInformationVectorKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationInformationVectorKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationInformationVectorKeyWrap>(info[0]->ToObject());
vtkInformationVector * r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->Get(
(vtkInformationInformationVectorKey *) a0->native.GetPointer()
);
VtkInformationVectorWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkInformationVectorWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkInformationVectorWrap *w = new VtkInformationVectorWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationInformationKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationInformationKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationInformationKeyWrap>(info[0]->ToObject());
vtkInformation * r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->Get(
(vtkInformationInformationKey *) a0->native.GetPointer()
);
VtkInformationWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkInformationWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkInformationWrap *w = new VtkInformationWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationStringKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationStringKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationStringKeyWrap>(info[0]->ToObject());
char const * r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->Get(
(vtkInformationStringKey *) a0->native.GetPointer()
);
info.GetReturnValue().Set(Nan::New(r).ToLocalChecked());
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationUnsignedLongKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationUnsignedLongKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationUnsignedLongKeyWrap>(info[0]->ToObject());
unsigned int r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->Get(
(vtkInformationUnsignedLongKey *) a0->native.GetPointer()
);
info.GetReturnValue().Set(Nan::New(r));
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationDoubleKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationDoubleKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationDoubleKeyWrap>(info[0]->ToObject());
double r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->Get(
(vtkInformationDoubleKey *) a0->native.GetPointer()
);
info.GetReturnValue().Set(Nan::New(r));
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationIntegerKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationIntegerKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationIntegerKeyWrap>(info[0]->ToObject());
int r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->Get(
(vtkInformationIntegerKey *) a0->native.GetPointer()
);
info.GetReturnValue().Set(Nan::New(r));
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkInformationWrap::GetClassName(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkInformationWrap *wrapper = ObjectWrap::Unwrap<VtkInformationWrap>(info.Holder());
vtkInformation *native = (vtkInformation *)wrapper->native.GetPointer();
char const * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetClassName();
info.GetReturnValue().Set(Nan::New(r).ToLocalChecked());
}
void VtkInformationWrap::GetKey(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkInformationWrap *wrapper = ObjectWrap::Unwrap<VtkInformationWrap>(info.Holder());
vtkInformation *native = (vtkInformation *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationVariantVectorKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationVariantVectorKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationVariantVectorKeyWrap>(info[0]->ToObject());
vtkInformationKey * r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetKey(
(vtkInformationVariantVectorKey *) a0->native.GetPointer()
);
VtkInformationKeyWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkInformationKeyWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkInformationKeyWrap *w = new VtkInformationKeyWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationVariantKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationVariantKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationVariantKeyWrap>(info[0]->ToObject());
vtkInformationKey * r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetKey(
(vtkInformationVariantKey *) a0->native.GetPointer()
);
VtkInformationKeyWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkInformationKeyWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkInformationKeyWrap *w = new VtkInformationKeyWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationUnsignedLongKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationUnsignedLongKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationUnsignedLongKeyWrap>(info[0]->ToObject());
vtkInformationKey * r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetKey(
(vtkInformationUnsignedLongKey *) a0->native.GetPointer()
);
VtkInformationKeyWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkInformationKeyWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkInformationKeyWrap *w = new VtkInformationKeyWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationKeyWrap>(info[0]->ToObject());
vtkInformationKey * r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetKey(
(vtkInformationKey *) a0->native.GetPointer()
);
VtkInformationKeyWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkInformationKeyWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkInformationKeyWrap *w = new VtkInformationKeyWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationStringVectorKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationStringVectorKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationStringVectorKeyWrap>(info[0]->ToObject());
vtkInformationKey * r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetKey(
(vtkInformationStringVectorKey *) a0->native.GetPointer()
);
VtkInformationKeyWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkInformationKeyWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkInformationKeyWrap *w = new VtkInformationKeyWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationStringKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationStringKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationStringKeyWrap>(info[0]->ToObject());
vtkInformationKey * r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetKey(
(vtkInformationStringKey *) a0->native.GetPointer()
);
VtkInformationKeyWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkInformationKeyWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkInformationKeyWrap *w = new VtkInformationKeyWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationRequestKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationRequestKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationRequestKeyWrap>(info[0]->ToObject());
vtkInformationKey * r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetKey(
(vtkInformationRequestKey *) a0->native.GetPointer()
);
VtkInformationKeyWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkInformationKeyWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkInformationKeyWrap *w = new VtkInformationKeyWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationIntegerVectorKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationIntegerVectorKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationIntegerVectorKeyWrap>(info[0]->ToObject());
vtkInformationKey * r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetKey(
(vtkInformationIntegerVectorKey *) a0->native.GetPointer()
);
VtkInformationKeyWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkInformationKeyWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkInformationKeyWrap *w = new VtkInformationKeyWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationIntegerKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationIntegerKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationIntegerKeyWrap>(info[0]->ToObject());
vtkInformationKey * r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetKey(
(vtkInformationIntegerKey *) a0->native.GetPointer()
);
VtkInformationKeyWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkInformationKeyWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkInformationKeyWrap *w = new VtkInformationKeyWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationInformationVectorKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationInformationVectorKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationInformationVectorKeyWrap>(info[0]->ToObject());
vtkInformationKey * r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetKey(
(vtkInformationInformationVectorKey *) a0->native.GetPointer()
);
VtkInformationKeyWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkInformationKeyWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkInformationKeyWrap *w = new VtkInformationKeyWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationInformationKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationInformationKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationInformationKeyWrap>(info[0]->ToObject());
vtkInformationKey * r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetKey(
(vtkInformationInformationKey *) a0->native.GetPointer()
);
VtkInformationKeyWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkInformationKeyWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkInformationKeyWrap *w = new VtkInformationKeyWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationDoubleVectorKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationDoubleVectorKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationDoubleVectorKeyWrap>(info[0]->ToObject());
vtkInformationKey * r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetKey(
(vtkInformationDoubleVectorKey *) a0->native.GetPointer()
);
VtkInformationKeyWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkInformationKeyWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkInformationKeyWrap *w = new VtkInformationKeyWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationDoubleKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationDoubleKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationDoubleKeyWrap>(info[0]->ToObject());
vtkInformationKey * r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetKey(
(vtkInformationDoubleKey *) a0->native.GetPointer()
);
VtkInformationKeyWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkInformationKeyWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkInformationKeyWrap *w = new VtkInformationKeyWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationDataObjectKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationDataObjectKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationDataObjectKeyWrap>(info[0]->ToObject());
vtkInformationKey * r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetKey(
(vtkInformationDataObjectKey *) a0->native.GetPointer()
);
VtkInformationKeyWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkInformationKeyWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkInformationKeyWrap *w = new VtkInformationKeyWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkInformationWrap::GetNumberOfKeys(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkInformationWrap *wrapper = ObjectWrap::Unwrap<VtkInformationWrap>(info.Holder());
vtkInformation *native = (vtkInformation *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetNumberOfKeys();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkInformationWrap::GetRequest(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkInformationWrap *wrapper = ObjectWrap::Unwrap<VtkInformationWrap>(info.Holder());
vtkInformation *native = (vtkInformation *)wrapper->native.GetPointer();
vtkInformationRequestKey * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetRequest();
VtkInformationRequestKeyWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkInformationRequestKeyWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkInformationRequestKeyWrap *w = new VtkInformationRequestKeyWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
}
void VtkInformationWrap::Has(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkInformationWrap *wrapper = ObjectWrap::Unwrap<VtkInformationWrap>(info.Holder());
vtkInformation *native = (vtkInformation *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationDataObjectKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationDataObjectKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationDataObjectKeyWrap>(info[0]->ToObject());
int r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->Has(
(vtkInformationDataObjectKey *) a0->native.GetPointer()
);
info.GetReturnValue().Set(Nan::New(r));
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationObjectBaseKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationObjectBaseKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationObjectBaseKeyWrap>(info[0]->ToObject());
int r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->Has(
(vtkInformationObjectBaseKey *) a0->native.GetPointer()
);
info.GetReturnValue().Set(Nan::New(r));
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationInformationVectorKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationInformationVectorKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationInformationVectorKeyWrap>(info[0]->ToObject());
int r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->Has(
(vtkInformationInformationVectorKey *) a0->native.GetPointer()
);
info.GetReturnValue().Set(Nan::New(r));
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationInformationKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationInformationKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationInformationKeyWrap>(info[0]->ToObject());
int r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->Has(
(vtkInformationInformationKey *) a0->native.GetPointer()
);
info.GetReturnValue().Set(Nan::New(r));
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationStringKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationStringKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationStringKeyWrap>(info[0]->ToObject());
int r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->Has(
(vtkInformationStringKey *) a0->native.GetPointer()
);
info.GetReturnValue().Set(Nan::New(r));
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationKeyVectorKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationKeyVectorKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationKeyVectorKeyWrap>(info[0]->ToObject());
int r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->Has(
(vtkInformationKeyVectorKey *) a0->native.GetPointer()
);
info.GetReturnValue().Set(Nan::New(r));
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationVariantVectorKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationVariantVectorKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationVariantVectorKeyWrap>(info[0]->ToObject());
int r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->Has(
(vtkInformationVariantVectorKey *) a0->native.GetPointer()
);
info.GetReturnValue().Set(Nan::New(r));
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationDoubleVectorKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationDoubleVectorKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationDoubleVectorKeyWrap>(info[0]->ToObject());
int r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->Has(
(vtkInformationDoubleVectorKey *) a0->native.GetPointer()
);
info.GetReturnValue().Set(Nan::New(r));
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationUnsignedLongKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationUnsignedLongKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationUnsignedLongKeyWrap>(info[0]->ToObject());
int r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->Has(
(vtkInformationUnsignedLongKey *) a0->native.GetPointer()
);
info.GetReturnValue().Set(Nan::New(r));
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationIntegerPointerKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationIntegerPointerKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationIntegerPointerKeyWrap>(info[0]->ToObject());
int r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->Has(
(vtkInformationIntegerPointerKey *) a0->native.GetPointer()
);
info.GetReturnValue().Set(Nan::New(r));
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationStringVectorKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationStringVectorKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationStringVectorKeyWrap>(info[0]->ToObject());
int r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->Has(
(vtkInformationStringVectorKey *) a0->native.GetPointer()
);
info.GetReturnValue().Set(Nan::New(r));
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationIntegerVectorKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationIntegerVectorKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationIntegerVectorKeyWrap>(info[0]->ToObject());
int r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->Has(
(vtkInformationIntegerVectorKey *) a0->native.GetPointer()
);
info.GetReturnValue().Set(Nan::New(r));
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationVariantKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationVariantKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationVariantKeyWrap>(info[0]->ToObject());
int r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->Has(
(vtkInformationVariantKey *) a0->native.GetPointer()
);
info.GetReturnValue().Set(Nan::New(r));
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationDoubleKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationDoubleKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationDoubleKeyWrap>(info[0]->ToObject());
int r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->Has(
(vtkInformationDoubleKey *) a0->native.GetPointer()
);
info.GetReturnValue().Set(Nan::New(r));
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationIdTypeKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationIdTypeKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationIdTypeKeyWrap>(info[0]->ToObject());
int r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->Has(
(vtkInformationIdTypeKey *) a0->native.GetPointer()
);
info.GetReturnValue().Set(Nan::New(r));
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationIntegerKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationIntegerKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationIntegerKeyWrap>(info[0]->ToObject());
int r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->Has(
(vtkInformationIntegerKey *) a0->native.GetPointer()
);
info.GetReturnValue().Set(Nan::New(r));
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationRequestKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationRequestKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationRequestKeyWrap>(info[0]->ToObject());
int r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->Has(
(vtkInformationRequestKey *) a0->native.GetPointer()
);
info.GetReturnValue().Set(Nan::New(r));
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationKeyWrap>(info[0]->ToObject());
int r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->Has(
(vtkInformationKey *) a0->native.GetPointer()
);
info.GetReturnValue().Set(Nan::New(r));
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkInformationWrap::IsA(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkInformationWrap *wrapper = ObjectWrap::Unwrap<VtkInformationWrap>(info.Holder());
vtkInformation *native = (vtkInformation *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsString())
{
Nan::Utf8String a0(info[0]);
int r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->IsA(
*a0
);
info.GetReturnValue().Set(Nan::New(r));
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkInformationWrap::Length(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkInformationWrap *wrapper = ObjectWrap::Unwrap<VtkInformationWrap>(info.Holder());
vtkInformation *native = (vtkInformation *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationKeyVectorKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationKeyVectorKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationKeyVectorKeyWrap>(info[0]->ToObject());
int r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->Length(
(vtkInformationKeyVectorKey *) a0->native.GetPointer()
);
info.GetReturnValue().Set(Nan::New(r));
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationVariantVectorKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationVariantVectorKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationVariantVectorKeyWrap>(info[0]->ToObject());
int r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->Length(
(vtkInformationVariantVectorKey *) a0->native.GetPointer()
);
info.GetReturnValue().Set(Nan::New(r));
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationDoubleVectorKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationDoubleVectorKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationDoubleVectorKeyWrap>(info[0]->ToObject());
int r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->Length(
(vtkInformationDoubleVectorKey *) a0->native.GetPointer()
);
info.GetReturnValue().Set(Nan::New(r));
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationIntegerPointerKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationIntegerPointerKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationIntegerPointerKeyWrap>(info[0]->ToObject());
int r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->Length(
(vtkInformationIntegerPointerKey *) a0->native.GetPointer()
);
info.GetReturnValue().Set(Nan::New(r));
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationStringVectorKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationStringVectorKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationStringVectorKeyWrap>(info[0]->ToObject());
int r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->Length(
(vtkInformationStringVectorKey *) a0->native.GetPointer()
);
info.GetReturnValue().Set(Nan::New(r));
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationIntegerVectorKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationIntegerVectorKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationIntegerVectorKeyWrap>(info[0]->ToObject());
int r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->Length(
(vtkInformationIntegerVectorKey *) a0->native.GetPointer()
);
info.GetReturnValue().Set(Nan::New(r));
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkInformationWrap::Modified(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkInformationWrap *wrapper = ObjectWrap::Unwrap<VtkInformationWrap>(info.Holder());
vtkInformation *native = (vtkInformation *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationKeyWrap>(info[0]->ToObject());
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Modified(
(vtkInformationKey *) a0->native.GetPointer()
);
return;
}
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Modified();
}
void VtkInformationWrap::NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkInformationWrap *wrapper = ObjectWrap::Unwrap<VtkInformationWrap>(info.Holder());
vtkInformation *native = (vtkInformation *)wrapper->native.GetPointer();
vtkInformation * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->NewInstance();
VtkInformationWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkInformationWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkInformationWrap *w = new VtkInformationWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
}
void VtkInformationWrap::Remove(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkInformationWrap *wrapper = ObjectWrap::Unwrap<VtkInformationWrap>(info.Holder());
vtkInformation *native = (vtkInformation *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationKeyVectorKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationKeyVectorKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationKeyVectorKeyWrap>(info[0]->ToObject());
if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkInformationKeyWrap::ptpl))->HasInstance(info[1]))
{
VtkInformationKeyWrap *a1 = ObjectWrap::Unwrap<VtkInformationKeyWrap>(info[1]->ToObject());
if(info.Length() != 2)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Remove(
(vtkInformationKeyVectorKey *) a0->native.GetPointer(),
(vtkInformationKey *) a1->native.GetPointer()
);
return;
}
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationDataObjectKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationDataObjectKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationDataObjectKeyWrap>(info[0]->ToObject());
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Remove(
(vtkInformationDataObjectKey *) a0->native.GetPointer()
);
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationObjectBaseKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationObjectBaseKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationObjectBaseKeyWrap>(info[0]->ToObject());
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Remove(
(vtkInformationObjectBaseKey *) a0->native.GetPointer()
);
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationInformationVectorKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationInformationVectorKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationInformationVectorKeyWrap>(info[0]->ToObject());
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Remove(
(vtkInformationInformationVectorKey *) a0->native.GetPointer()
);
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationInformationKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationInformationKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationInformationKeyWrap>(info[0]->ToObject());
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Remove(
(vtkInformationInformationKey *) a0->native.GetPointer()
);
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationStringKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationStringKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationStringKeyWrap>(info[0]->ToObject());
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Remove(
(vtkInformationStringKey *) a0->native.GetPointer()
);
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationKeyVectorKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationKeyVectorKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationKeyVectorKeyWrap>(info[0]->ToObject());
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Remove(
(vtkInformationKeyVectorKey *) a0->native.GetPointer()
);
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationVariantVectorKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationVariantVectorKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationVariantVectorKeyWrap>(info[0]->ToObject());
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Remove(
(vtkInformationVariantVectorKey *) a0->native.GetPointer()
);
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationDoubleVectorKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationDoubleVectorKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationDoubleVectorKeyWrap>(info[0]->ToObject());
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Remove(
(vtkInformationDoubleVectorKey *) a0->native.GetPointer()
);
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationUnsignedLongKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationUnsignedLongKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationUnsignedLongKeyWrap>(info[0]->ToObject());
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Remove(
(vtkInformationUnsignedLongKey *) a0->native.GetPointer()
);
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationIntegerPointerKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationIntegerPointerKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationIntegerPointerKeyWrap>(info[0]->ToObject());
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Remove(
(vtkInformationIntegerPointerKey *) a0->native.GetPointer()
);
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationStringVectorKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationStringVectorKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationStringVectorKeyWrap>(info[0]->ToObject());
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Remove(
(vtkInformationStringVectorKey *) a0->native.GetPointer()
);
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationIntegerVectorKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationIntegerVectorKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationIntegerVectorKeyWrap>(info[0]->ToObject());
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Remove(
(vtkInformationIntegerVectorKey *) a0->native.GetPointer()
);
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationVariantKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationVariantKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationVariantKeyWrap>(info[0]->ToObject());
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Remove(
(vtkInformationVariantKey *) a0->native.GetPointer()
);
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationDoubleKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationDoubleKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationDoubleKeyWrap>(info[0]->ToObject());
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Remove(
(vtkInformationDoubleKey *) a0->native.GetPointer()
);
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationIdTypeKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationIdTypeKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationIdTypeKeyWrap>(info[0]->ToObject());
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Remove(
(vtkInformationIdTypeKey *) a0->native.GetPointer()
);
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationIntegerKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationIntegerKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationIntegerKeyWrap>(info[0]->ToObject());
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Remove(
(vtkInformationIntegerKey *) a0->native.GetPointer()
);
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationRequestKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationRequestKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationRequestKeyWrap>(info[0]->ToObject());
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Remove(
(vtkInformationRequestKey *) a0->native.GetPointer()
);
return;
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationKeyWrap>(info[0]->ToObject());
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Remove(
(vtkInformationKey *) a0->native.GetPointer()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkInformationWrap::SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkInformationWrap *wrapper = ObjectWrap::Unwrap<VtkInformationWrap>(info.Holder());
vtkInformation *native = (vtkInformation *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkObjectWrap::ptpl))->HasInstance(info[0]))
{
VtkObjectWrap *a0 = ObjectWrap::Unwrap<VtkObjectWrap>(info[0]->ToObject());
vtkInformation * r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->SafeDownCast(
(vtkObject *) a0->native.GetPointer()
);
VtkInformationWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkInformationWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkInformationWrap *w = new VtkInformationWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkInformationWrap::Set(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkInformationWrap *wrapper = ObjectWrap::Unwrap<VtkInformationWrap>(info.Holder());
vtkInformation *native = (vtkInformation *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationStringVectorKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationStringVectorKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationStringVectorKeyWrap>(info[0]->ToObject());
if(info.Length() > 1 && info[1]->IsString())
{
Nan::Utf8String a1(info[1]);
if(info.Length() > 2 && info[2]->IsInt32())
{
if(info.Length() != 3)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Set(
(vtkInformationStringVectorKey *) a0->native.GetPointer(),
*a1,
info[2]->Int32Value()
);
return;
}
}
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationStringKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationStringKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationStringKeyWrap>(info[0]->ToObject());
if(info.Length() > 1 && info[1]->IsString())
{
Nan::Utf8String a1(info[1]);
if(info.Length() != 2)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Set(
(vtkInformationStringKey *) a0->native.GetPointer(),
*a1
);
return;
}
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationDataObjectKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationDataObjectKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationDataObjectKeyWrap>(info[0]->ToObject());
if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkDataObjectWrap::ptpl))->HasInstance(info[1]))
{
VtkDataObjectWrap *a1 = ObjectWrap::Unwrap<VtkDataObjectWrap>(info[1]->ToObject());
if(info.Length() != 2)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Set(
(vtkInformationDataObjectKey *) a0->native.GetPointer(),
(vtkDataObject *) a1->native.GetPointer()
);
return;
}
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationObjectBaseKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationObjectBaseKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationObjectBaseKeyWrap>(info[0]->ToObject());
if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkObjectBaseWrap::ptpl))->HasInstance(info[1]))
{
VtkObjectBaseWrap *a1 = ObjectWrap::Unwrap<VtkObjectBaseWrap>(info[1]->ToObject());
if(info.Length() != 2)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Set(
(vtkInformationObjectBaseKey *) a0->native.GetPointer(),
(vtkObjectBase *) a1->native.GetPointer()
);
return;
}
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationInformationVectorKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationInformationVectorKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationInformationVectorKeyWrap>(info[0]->ToObject());
if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkInformationVectorWrap::ptpl))->HasInstance(info[1]))
{
VtkInformationVectorWrap *a1 = ObjectWrap::Unwrap<VtkInformationVectorWrap>(info[1]->ToObject());
if(info.Length() != 2)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Set(
(vtkInformationInformationVectorKey *) a0->native.GetPointer(),
(vtkInformationVector *) a1->native.GetPointer()
);
return;
}
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationInformationKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationInformationKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationInformationKeyWrap>(info[0]->ToObject());
if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkInformationWrap::ptpl))->HasInstance(info[1]))
{
VtkInformationWrap *a1 = ObjectWrap::Unwrap<VtkInformationWrap>(info[1]->ToObject());
if(info.Length() != 2)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Set(
(vtkInformationInformationKey *) a0->native.GetPointer(),
(vtkInformation *) a1->native.GetPointer()
);
return;
}
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationUnsignedLongKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationUnsignedLongKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationUnsignedLongKeyWrap>(info[0]->ToObject());
if(info.Length() > 1 && info[1]->IsUint32())
{
if(info.Length() != 2)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Set(
(vtkInformationUnsignedLongKey *) a0->native.GetPointer(),
info[1]->Uint32Value()
);
return;
}
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationDoubleVectorKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationDoubleVectorKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationDoubleVectorKeyWrap>(info[0]->ToObject());
if(info.Length() > 1 && info[1]->IsNumber())
{
if(info.Length() > 2 && info[2]->IsNumber())
{
if(info.Length() > 3 && info[3]->IsNumber())
{
if(info.Length() > 4 && info[4]->IsNumber())
{
if(info.Length() > 5 && info[5]->IsNumber())
{
if(info.Length() > 6 && info[6]->IsNumber())
{
if(info.Length() != 7)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Set(
(vtkInformationDoubleVectorKey *) a0->native.GetPointer(),
info[1]->NumberValue(),
info[2]->NumberValue(),
info[3]->NumberValue(),
info[4]->NumberValue(),
info[5]->NumberValue(),
info[6]->NumberValue()
);
return;
}
}
}
if(info.Length() != 4)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Set(
(vtkInformationDoubleVectorKey *) a0->native.GetPointer(),
info[1]->NumberValue(),
info[2]->NumberValue(),
info[3]->NumberValue()
);
return;
}
}
}
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationDoubleKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationDoubleKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationDoubleKeyWrap>(info[0]->ToObject());
if(info.Length() > 1 && info[1]->IsNumber())
{
if(info.Length() != 2)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Set(
(vtkInformationDoubleKey *) a0->native.GetPointer(),
info[1]->NumberValue()
);
return;
}
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationIntegerVectorKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationIntegerVectorKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationIntegerVectorKeyWrap>(info[0]->ToObject());
if(info.Length() > 1 && info[1]->IsInt32())
{
if(info.Length() > 2 && info[2]->IsInt32())
{
if(info.Length() > 3 && info[3]->IsInt32())
{
if(info.Length() > 4 && info[4]->IsInt32())
{
if(info.Length() > 5 && info[5]->IsInt32())
{
if(info.Length() > 6 && info[6]->IsInt32())
{
if(info.Length() != 7)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Set(
(vtkInformationIntegerVectorKey *) a0->native.GetPointer(),
info[1]->Int32Value(),
info[2]->Int32Value(),
info[3]->Int32Value(),
info[4]->Int32Value(),
info[5]->Int32Value(),
info[6]->Int32Value()
);
return;
}
}
}
if(info.Length() != 4)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Set(
(vtkInformationIntegerVectorKey *) a0->native.GetPointer(),
info[1]->Int32Value(),
info[2]->Int32Value(),
info[3]->Int32Value()
);
return;
}
}
}
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationIntegerKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationIntegerKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationIntegerKeyWrap>(info[0]->ToObject());
if(info.Length() > 1 && info[1]->IsInt32())
{
if(info.Length() != 2)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Set(
(vtkInformationIntegerKey *) a0->native.GetPointer(),
info[1]->Int32Value()
);
return;
}
}
else if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationRequestKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationRequestKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationRequestKeyWrap>(info[0]->ToObject());
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->Set(
(vtkInformationRequestKey *) a0->native.GetPointer()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkInformationWrap::SetRequest(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkInformationWrap *wrapper = ObjectWrap::Unwrap<VtkInformationWrap>(info.Holder());
vtkInformation *native = (vtkInformation *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkInformationRequestKeyWrap::ptpl))->HasInstance(info[0]))
{
VtkInformationRequestKeyWrap *a0 = ObjectWrap::Unwrap<VtkInformationRequestKeyWrap>(info[0]->ToObject());
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetRequest(
(vtkInformationRequestKey *) a0->native.GetPointer()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
| 33.486909
| 133
| 0.673906
|
axkibe
|
a5ae6638be528e85f34b267112c39cd0ebbff566
| 234
|
cpp
|
C++
|
Leetcode/1837.cpp
|
prameetu/CP_codes
|
41f8cfc188d2e08a8091bc5134247d05ba8a78f5
|
[
"MIT"
] | null | null | null |
Leetcode/1837.cpp
|
prameetu/CP_codes
|
41f8cfc188d2e08a8091bc5134247d05ba8a78f5
|
[
"MIT"
] | null | null | null |
Leetcode/1837.cpp
|
prameetu/CP_codes
|
41f8cfc188d2e08a8091bc5134247d05ba8a78f5
|
[
"MIT"
] | null | null | null |
//leetcode - 1837
// Sum of Digits in Base K
#include<bits/stdc++.h>
using namespace std;
int sumBase(int n, int k)
{
int ans(0);
while(n)
{
ans += n%k;
n = n/k;
}
return ans;
}
| 13
| 27
| 0.474359
|
prameetu
|
a5b2b548a83801ae31d9f88a3effd20f13e606b5
| 4,033
|
cpp
|
C++
|
backtracking/setCover.cpp
|
SiverPineValley/algo
|
29c75c6b226fdb15a3b6695e763ee49d4871094e
|
[
"Apache-2.0"
] | null | null | null |
backtracking/setCover.cpp
|
SiverPineValley/algo
|
29c75c6b226fdb15a3b6695e763ee49d4871094e
|
[
"Apache-2.0"
] | null | null | null |
backtracking/setCover.cpp
|
SiverPineValley/algo
|
29c75c6b226fdb15a3b6695e763ee49d4871094e
|
[
"Apache-2.0"
] | null | null | null |
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <set>
#include <functional>
#include <stack>
#include <cstring>
using namespace std;
// Array에서 사용할 Swap
#define SWAP(x, y, temp) ( temp=x, x=y, y=temp )
/*
각 Subset들의 개수를 세는 함수
*/
void calSets( vector<set<int>> s, int sNum, vector<int>* size )
{
// sort 하기 위해 Size를 채우기
for( int i = 0; i < sNum; i++ )
(*size)[i] = s[i].size();
}
/*
QuickSort 함수
*/
void quicksort( vector<set<int>>* s, int start, int end, vector<int>* size )
{
if ( start >= end ) {
return;
}
int key = start;
int i = start + 1, j = end, temp;
set<int> temps;
while( i <= j )
{
while( i <= end && (*size)[i] >= (*size)[key] )
i++;
while( j > start && (*size)[j] <= (*size)[key] )
j--;
if(i > j)
{
SWAP((*s)[j],(*s)[key],temps);
SWAP((*size)[j], (*size)[key], temp);
}
else
{
SWAP((*s)[i],(*s)[j],temps);
SWAP((*size)[i],(*size)[j],temp);
}
}
quicksort( s , start , j - 1, size );
quicksort( s, j + 1, end, size );
return;
}
/*
Subset들을 Sorting 하는 함수
*/
void sortSets( vector<set<int>>* s, int sNum, vector<int>* size )
{
calSets( *s, sNum, size );
quicksort( s, 0, sNum - 1, size );
};
struct Solution
{
vector<int> isS;
vector<int> setState;
int stage;
int cntState;
int cntSolved;
};
int main(void)
{
char buff[1024];
char *pch;
int uNum; // U Num
int sNum; // Subset Num
int bestSol = 99999999;
vector<set<int>> sets;
scanf("%d", &uNum);
scanf("%d\n", &sNum);
// 스택 생성
stack<Solution> solution;
if( uNum == sNum )
{
cout << "1";
return 0;
}
// 입력
// vector<set<int>> sets: vector는 subset을 담고, set은 각 원소들을 담는다.
// setSize는 각 Subset들의 Size를 담는다. isSol은 해결되었는지를 확인할 때.
// sst는 solution에 들어갈 state space tree의 각 상태
sets.resize(sNum);
vector<int> setSize;
setSize.resize(sNum, 0);
for (int i = 0; i < sNum; i++)
{
gets(buff);
pch = strtok(buff, " ");
while (pch != NULL)
{
sets[i].insert(atoi(pch));
pch = strtok(NULL, " ");
}
}
// 정렬
sortSets( &sets, sNum, &setSize );
// 알고리즘
Solution temp;
temp.isS.resize(uNum, 0);
temp.setState.resize(sNum, 0);
temp.stage = 0;
temp.cntState = 0;
temp.cntSolved = 0;
solution.push(temp);
temp.setState[0] = 1;
temp.cntState = 1;
for (auto f = sets[0].begin(); f != sets[0].end(); f++)
{
temp.isS[*f - 1] = 1;
temp.cntSolved++;
}
solution.push(temp);
while(!solution.empty())
{
temp = solution.top();
solution.pop();
vector<int> tempisS = temp.isS;
// 현재 State가 Leaf Node
if ( temp.stage == (sNum - 1) )
{
// Leaf가 Best Solution
if ( (bestSol > temp.cntState) && (temp.cntSolved == uNum) )
bestSol = temp.cntState;
}
// 현재 State가 Not Leaf Node
else
{
// Solution을 찾은 경우, BestSolution을 갱신하고 다음으로 넘어간다.
if( temp.cntSolved == uNum )
{
if( bestSol > temp.cntState )
bestSol = temp.cntState;
}
// Solution을 찾지 못한 경우, Stack에 양 쪽 노드를 Push한다.
else
{
// Pruning 1: bestSolution보다 cntState값이 같거나 커지면, 스택에 추가하지 않는다.
if( bestSol <= ( temp.cntState + 1 ) );
else{
temp.stage++;
// Pruning 2: 만약, sets[temp.stage].size() == 1이면, isSol의 남은 개수만큼 Sol에 더한다.
if( sets[temp.stage].size() == 1 )
{
int remain = (temp.cntState + uNum - temp.cntSolved);
if( bestSol > remain )
bestSol = remain;
}
else
{
int how = 0;
// 현재 추가된 Subset에 따라 isS 갱신한다.
for( auto it = sets[temp.stage].begin(); it != sets[temp.stage].end(); it++ )
{
if( tempisS[*it - 1] == 0 )
{
tempisS[*it - 1] = 1;
how++;
}
}
if( temp.stage != (sNum - 1) )
solution.push(temp);
// Pruning 3: 추가되는 set이 없으면, 왼쪽 Child는 생성하지 않는다.
if ( how != 0 )
{
temp.isS = tempisS;
temp.setState[temp.stage] = 1;
temp.cntState++;
temp.cntSolved += how;
solution.push(temp);
}
}
}
}
}
}
cout << bestSol;
return 0;
}
| 19.113744
| 83
| 0.547979
|
SiverPineValley
|
a5b3faeb8428232eda5bba0024247d8a7bb14053
| 3,269
|
cpp
|
C++
|
src/main/screens/notification_list.cpp
|
LeonMatthes/WatchyOS
|
d6a62695c8c7ca7fa26c13f4505b7f06b13e2fb9
|
[
"MIT"
] | 2
|
2022-01-22T07:30:28.000Z
|
2022-01-27T14:03:35.000Z
|
src/main/screens/notification_list.cpp
|
LeonMatthes/WatchyOS
|
d6a62695c8c7ca7fa26c13f4505b7f06b13e2fb9
|
[
"MIT"
] | 2
|
2022-02-02T14:22:44.000Z
|
2022-02-02T14:59:51.000Z
|
src/main/screens/notification_list.cpp
|
LeonMatthes/WatchyOS
|
d6a62695c8c7ca7fa26c13f4505b7f06b13e2fb9
|
[
"MIT"
] | 1
|
2022-02-02T20:52:20.000Z
|
2022-02-02T20:52:20.000Z
|
#include "notification_list.h"
#include "screens.h"
#include <cstddef>
#include <sstream>
#include <esp_attr.h>
#include <e_ink.h>
using namespace e_ink;
#include <event_queue.h>
#include <notifications.h>
#include <res/fonts/Inconsolata_Bold10pt7b.h>
#include <res/fonts/Inconsolata_Bold7pt7b.h>
#include <res/fonts/watchface_font8pt7b.h>
void displayNoNotifications() {
display.fillScreen(BG_COLOR);
auto headerHeight = screens::drawHeader();
display.setFont(&Inconsolata_Bold10pt7b);
display.setCursor(20, 100 + headerHeight / 2);
display.print("No notifications");
display.display();
display.hibernate();
}
void displayEndOfNotifications() {
display.fillScreen(BG_COLOR);
auto headerHeight = screens::drawHeader();
display.setFont(&Inconsolata_Bold10pt7b);
const char* line1 = "no more";
const char* line2 = "notifications";
int16_t x1, y1;
uint16_t w, h;
display.getTextBounds(line1, 10, 50, &x1, &y1, &w, &h);
display.setCursor(100 - w/2, (200 - headerHeight) / 2);
display.println(line1);
display.getTextBounds(line2, 10, 50, &x1, &y1, &w, &h);
display.setCursor(100 - w/2, display.getCursorY());
display.println(line2);
display.display();
display.hibernate();
}
void displayNotification(const Notification& notification) {
display.fillScreen(BG_COLOR);
auto headerHeight = screens::drawHeader();
const auto margin = 4;
display.drawBitmap(margin, headerHeight + margin, notification.icon20x20(), 20, 20, FG_COLOR);
display.setCursor(20 + 2 * margin, headerHeight + 20 + margin - 4);
display.setTextWrap(false);
display.setFont(&Inconsolata_Bold10pt7b);
display.println(notification.title.c_str());
display.setTextWrap(true);
display.setFont(&Inconsolata_Bold7pt7b);
display.println(notification.text.c_str());
std::ostringstream timeStream;
auto& when = notification.when;
timeStream << when.Hour / 10 << when.Hour % 10 << ":" << when.Minute / 10 << when.Minute % 10;
std::string time = timeStream.str();
display.setFont(&watchface_font8pt7b);
int16_t x1, y1;
uint16_t w, h;
display.getTextBounds(time.c_str(), 10, 50, &x1, &y1, &w, &h);
display.setCursor(100 - w / 2, 200 - margin);
display.print(time.c_str());
display.display();
display.hibernate();
}
screens::Screen notificationsScreen(bool wakeFromSleep) {
size_t index = 0;
while(true) {
auto notifications = Notification::all();
if(notifications.empty()) {
displayNoNotifications();
}
else if(index >= notifications.size()) {
index = notifications.size();
displayEndOfNotifications();
}
else {
displayNotification(*notifications[index]);
}
auto event = event_queue::queue.receive(30 * 1000 / portTICK_PERIOD_MS);
if(event) {
switch(*event) {
case event_queue::Event::BACK_BUTTON:
return screens::WATCHFACE;
case event_queue::Event::MENU_BUTTON:
// TODO
break;
case event_queue::Event::DOWN_BUTTON:
index++;
break;
case event_queue::Event::UP_BUTTON:
if(index == 0) {
return screens::WATCHFACE;
}
index--;
break;
}
}
else {
return screens::WATCHFACE;
}
}
}
| 25.146154
| 96
| 0.667177
|
LeonMatthes
|
a5b5806e67fbf11e74102992d8975b4e2c15d3a4
| 796
|
hh
|
C++
|
DezynePatterns/cyclic-io-pattern/src/cpp_impl/InputCpp.hh
|
dezyne/DezyneCommunity
|
08b33e13cbd36c1db5cbe94de0f51c207289eb4a
|
[
"MIT"
] | 5
|
2017-11-07T09:09:28.000Z
|
2021-12-15T05:34:46.000Z
|
DezynePatterns/cyclic-io-pattern/src/cpp_impl/InputCpp.hh
|
dezyne/DezyneCommunity
|
08b33e13cbd36c1db5cbe94de0f51c207289eb4a
|
[
"MIT"
] | 2
|
2019-05-22T10:12:23.000Z
|
2019-07-15T14:25:34.000Z
|
DezynePatterns/cyclic-io-pattern/src/cpp_impl/InputCpp.hh
|
dezyne/DezyneCommunity
|
08b33e13cbd36c1db5cbe94de0f51c207289eb4a
|
[
"MIT"
] | 5
|
2017-12-04T13:02:07.000Z
|
2021-12-15T05:33:53.000Z
|
#pragma once
#include "InputCpp.hh"
class InputCpp : public skel::InputCpp
{
public:
explicit InputCpp(const dzn::locator& dzn_locator) :
skel::InputCpp(dzn_locator),
_channel(nullptr),
state(IInput::eState::idle)
{
_previous = _channel;
}
void setChannel(bool* channel) { _channel = channel; }
void run()
{
if (_previous != *_channel)
{
_previous = _channel;
if (state == IInput::eState::active)
{
api.out.changed();
}
}
}
private:
void api_activate() override
{
state = IInput::eState::active;
}
void api_deactivate() override
{
state = IInput::eState::idle;
}
bool api_getValue() override
{
return _previous;
}
bool* _channel;
bool _previous;
IInput::eState::type state;
};
| 15.607843
| 56
| 0.614322
|
dezyne
|
a5c57a0d26939ba5a514f84d34d793836cee3472
| 11,365
|
cpp
|
C++
|
gerenciador.cpp
|
Mauriverti/trabalho3
|
b41493c938f7e0f08eb467c1bba474e88c1a8a3c
|
[
"MIT"
] | null | null | null |
gerenciador.cpp
|
Mauriverti/trabalho3
|
b41493c938f7e0f08eb467c1bba474e88c1a8a3c
|
[
"MIT"
] | null | null | null |
gerenciador.cpp
|
Mauriverti/trabalho3
|
b41493c938f7e0f08eb467c1bba474e88c1a8a3c
|
[
"MIT"
] | null | null | null |
#include "gerenciador.h"
Gerenciador::Gerenciador() {
}
string Gerenciador::getNomeDisco() {
return this->nomeDisco.toStdString();
}
void Gerenciador::setNomeDisco(string nome) {
this->nomeDisco = QString::fromStdString(nome);
}
void Gerenciador::abrirDisco(QString nome) {
QByteArray b = rw.lerArquivo(nome);
if (b == NULL) return;
this->nomeDisco = nome;
cout << endl << "Disco aberto com sucesso!";
if (checaFormato(b)) {
cout << endl << "Disco formatado";
disco.abrir(b, true);
} else {
cout << endl << "Disco NAO FORMATADO";
disco.abrir(b, false);
}
}
bool Gerenciador::checaFormato(QByteArray b) {
QString tipo = b.mid(0, 2);
if ( tipo == "BI" ) { // verifica o tipo do arquivo
return true;
}
return false;
}
void Gerenciador::formatarDisco(QString nome) {
this->disco.formatar();
QByteArray b = disco.toByteArray();
this->rw.gravaArquivo(nome, b);
cout << endl << "Disco Formatado";
}
void Gerenciador::criaDisco(QString nome, int tamanho, string tipoTamanho) {
int tamanhoEmKB = getTamanhoEmKBytes(tamanho, tipoTamanho);
QByteArray bytes = criaVetorVazio(tamanhoEmKB, true);
rw.gravaArquivo(nome, bytes);
}
void Gerenciador::exibirDiretorio(uint posicaoCluster) {
int statusCluster = disco.getFat().getPosicao(posicaoCluster);
if (statusCluster == 0) {
cout << endl << "ERRO: cluster vazio";
} else {
this->diretorioAtual = Diretorio(disco.getDados().getCluster(posicaoCluster));
this->diretorioAtual.exibeConteudo();
int opcao = -1;
while (opcao != 0) {
cout << endl << "0 - Voltar para menu principal";
cout << endl << "1 - Abrir pasta";
cout << endl << "2 - Voltar pasta";
cout << endl << "3 - Add arquivo";
cout << endl << "4 - Criar pasta";
cout << endl << "5 - Corrigir arquivo";
cout << endl << "6 - Mostrar toda a FAT";
cout << endl << "7 - Modificar FAT";
cout << endl << "8 - Mostrar conteudo da pasta atual";
cout << endl << "9 - Extrair arquivo";
cout << endl;
cin >> opcao;
switch (opcao) {
case 1: {
cout << "\tInforme o indice da pasta a ser aberta: ";
int indice;
cin >> indice;
QList<EntradaDiretorio> entradas = this->diretorioAtual.getEntradas();
EntradaDiretorio ed = entradas.at(indice);
uint fatPos = ed.getPrimeiroCluster();
this->exibirDiretorio(fatPos);
//this->entradas.a
// pegar endereco cluster de destino
// abrir endereco
break;
}
case 2: {
cout << endl;
this->exibirDiretorio(this->diretorioAtual.getClusterPai());
break;
}
case 3: {
cout << "Informe o nome do arquivo: ";
string arqNome;
cin >> arqNome;
QByteArray arq = rw.lerArquivo(QString::fromStdString(arqNome));
addArquivo(arq, arqNome);
this->salvaDisco();
break;
}
case 4: {
// informar nome
// achar cluster vazio
// criar nova pasta
// setar cluster
break;
}
case 5: {
QList<EntradaDiretorio> entradas = this->diretorioAtual.getEntradas();
for (EntradaDiretorio ed: entradas) {
if (ed.getEhArquivo()) {
if (this->validaArquivo(ed.getTamanhoArquivo(), ed.getPrimeiroCluster())) {
cout << endl << ed.getFullname().toStdString() << " esta OK!";
} else {
cout << endl << ed.getFullname().toStdString() << " esta Corrompido!";
}
}
}
cout << endl << endl;
// comecar a varrer arquivo
// verificar irregularidade
// verificar ciclo
// criar lista de inteiro com posicoes já acessadas
// verificar lista a cada insercao
// se ciclo aparece exatamente no ultimo cluster, CORRECAO
// se ciclo aparece apos o ultimo cluster necessario CORRECAO
// se ciclo aparece antes do ultimo cluster ERRO FATAL
// qtd de clusters > necessario CORRECAO
// qtd de clusters < necessario ERRO FATAL
break;
}
case 6: {
this->disco.mostraFat();
break;
}
case 7: {
cout << endl << "Informe a posicao e o valor que deseja alterar";
int pos, valor;
cout << endl << "Posicao: ";
cin >> pos;
cout << endl << "Valor: ";
cin >> valor;
this->disco.setPosicaoFat(pos, valor);
break;
}
case 8: {
QList<EntradaDiretorio> entradas = this->diretorioAtual.getEntradas();
for (EntradaDiretorio ed: entradas) {
cout << endl << ed.toString().toStdString();
}
break;
}
case 9: {
QString nomeArq;
cout << endl << "Informe o nome do arquivo que deseja extrair: ";
string nome;
cin >> nome;
nomeArq = QString::fromStdString(nome);
QList<EntradaDiretorio> entradas = this->diretorioAtual.getEntradas();
for (EntradaDiretorio ed: entradas) {
if (ed.getFullname() == nomeArq) {
this->extraiArquivo(ed);
break;
}
}
cout << endl << "Arquivo nao existe neste diretorio";
}
}
}
}
}
QByteArray Gerenciador::criaVetorVazio(int tamanho, bool emKb) {
QByteArray b;
if (emKb) {
// monta vetor de 1K vazio
char _1kb[1024];
for (int i = 0; i < 1024; i++) {
_1kb[i] = 0;
}
// cria vetor do tamanho especificado
for (int i = 0; i < tamanho/1024; i++) {
b.insert(i*1024, (char*) &_1kb , 1024);
}
} else {
char _1b = 0;
for (int i = 0; i < tamanho; i++) {
b.insert(i, (char*) &_1b, 1);
}
}
return b;
}
int Gerenciador::calculaCluster(int tamanhoArq) {
int numeroClusters = tamanhoArq/this->p.tamanhoCluster;
if (tamanhoArq%this->p.tamanhoCluster != 0) numeroClusters++;
return numeroClusters;
}
void Gerenciador::addArquivo(QByteArray arquivo, string nomeArquivo) {
int tamanhoArq = arquivo.size();
int qtdCluster = calculaCluster(tamanhoArq);
if (!this->disco.getFat().temEspaco(qtdCluster)) {
cout << endl << "Nao ha espaco suficiente no disco";
return;
}
QList<QByteArray> arquivoFragmentado = fragmentaArquivo(arquivo);
int posCluster = this->disco.getFat().achaPrimeiroLivre();
EntradaDiretorio ed = criaEntradaArquivo(arquivo, QString::fromStdString(nomeArquivo), posCluster);
this->diretorioAtual.addEntrada(ed);
this->atualizaDiretorio();
int posProxCluster;
for (int i = 0; i < qtdCluster; i++) {
this->disco.setPosicaoFat(posCluster, -1);
this->disco.setClusterDados(posCluster, arquivoFragmentado.at(i));
if (i <(qtdCluster-1)) {
posProxCluster = this->disco.getFat().achaPrimeiroLivre();
this->disco.setPosicaoFat(posCluster, posProxCluster);
posCluster = posProxCluster;
}
}
this->atualizaDiretorio();
}
QList<QByteArray> Gerenciador::fragmentaArquivo(QByteArray arquivo) {
QList<QByteArray> arquivoFragmentado;
int tamanho = arquivo.size();
int qtdCluster = calculaCluster(tamanho);
int pos = 0;
for (int i = 0; i < (qtdCluster-1); i++) {
QByteArray fragmento = arquivo.mid(pos, p.tamanhoCluster);
arquivoFragmentado.append(fragmento);
pos += p.tamanhoCluster;
}
QByteArray fragmentoFinal = arquivo.mid(pos);
fragmentoFinal = preencheCluster(fragmentoFinal, fragmentoFinal.size(), p.tamanhoCluster);
arquivoFragmentado.append(fragmentoFinal);
return arquivoFragmentado;
}
QByteArray Gerenciador::preencheCluster(QByteArray ba, int tamanhoAtual, int tamanhoFinal) {
int tamanho = tamanhoFinal-tamanhoAtual;
return ba.append(criaVetorVazio(tamanho, false));
}
EntradaDiretorio Gerenciador::criaEntradaArquivo(QByteArray arquivo, QString nomeArq, int cluster) {
int splitPos = nomeArq.lastIndexOf('.');
QString nome = nomeArq.left(splitPos);
QString extensao = nomeArq.mid(splitPos+1);
EntradaDiretorio ed(nome, extensao, arquivo.size(), cluster, true);
return ed;
}
bool Gerenciador::validaArquivo(uint tamanho, uint primeiroCluster) {
uint qtdCluster = this->calculaCluster(tamanho);
return this->disco.getFat().checaArquivo(primeiroCluster, qtdCluster);
}
void Gerenciador::salvaDisco() {
QByteArray disco;
disco = this->disco.toByteArray();
rw.gravaArquivo(this->nomeDisco, disco);
}
void Gerenciador::atualizaDiretorio() {
int pos = this->diretorioAtual.getClusterAtual();
QByteArray dir = this->diretorioAtual.toByteArray();
this->disco.setClusterDados(pos, dir);
}
void Gerenciador::extraiArquivo(EntradaDiretorio ed) {
QString nomeSaida = ed.getFullname();
QByteArray arquivoSaida;
int cluster = ed.getPrimeiroCluster();
while (cluster != -1) {
arquivoSaida.append(this->disco.getDados().getCluster(cluster));
cluster = this->disco.getFat().getPosicao(cluster);
}
arquivoSaida = arquivoSaida.mid(0, ed.getTamanhoArquivo()); // remove os bytes 0 no final do arquivo
this->rw.gravaArquivo(nomeSaida, arquivoSaida);
}
int Gerenciador::getTamanhoEmKBytes(int tamanho, string tipoTamanho) {
if (tipoTamanho == "MB") {
return tamanho * 1024 * 1024;
} else
if (tipoTamanho =="GB") {
return tamanho * 1024 * 1024 * 1024;
} else
// if (tipo == "KB")
return tamanho * 1024;
}
| 34.755352
| 108
| 0.519754
|
Mauriverti
|
a5c7d0857637e8ef2fbc3dacb801320c48feae30
| 9,454
|
hxx
|
C++
|
opencascade/SelectMgr_TriangularFrustum.hxx
|
mgreminger/OCP
|
92eacb99497cd52b419c8a4a8ab0abab2330ed42
|
[
"Apache-2.0"
] | null | null | null |
opencascade/SelectMgr_TriangularFrustum.hxx
|
mgreminger/OCP
|
92eacb99497cd52b419c8a4a8ab0abab2330ed42
|
[
"Apache-2.0"
] | null | null | null |
opencascade/SelectMgr_TriangularFrustum.hxx
|
mgreminger/OCP
|
92eacb99497cd52b419c8a4a8ab0abab2330ed42
|
[
"Apache-2.0"
] | null | null | null |
// Created on: 2014-05-22
// Created by: Varvara POSKONINA
// Copyright (c) 2005-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _SelectMgr_TriangularFrustum_HeaderFile
#define _SelectMgr_TriangularFrustum_HeaderFile
#include <SelectMgr_Frustum.hxx>
//! This class contains representation of triangular selecting frustum, created in case
//! of polyline selection, and algorithms for overlap detection between selecting frustum and sensitive entities.
//! Overlap detection tests are implemented according to the terms of separating axis theorem (SAT).
//! NOTE: the object of this class can be created only as part of SelectMgr_TriangularFrustumSet.
class SelectMgr_TriangularFrustum : public SelectMgr_Frustum<3>
{
public:
//! Auxiliary structure to define selection triangle
struct SelectionTriangle
{
gp_Pnt2d Points[3];
};
public:
//! Destructor.
Standard_EXPORT virtual ~SelectMgr_TriangularFrustum();
//! Initializes selection triangle by input points
Standard_EXPORT void Init (const gp_Pnt2d& theP1,
const gp_Pnt2d& theP2,
const gp_Pnt2d& theP3);
//! Creates new triangular frustum with bases of triangles with vertices theP1, theP2 and theP3
//! projections onto near and far view frustum planes (only for triangular frustums)
//! NOTE: it should be called after Init() method
Standard_EXPORT virtual void Build() Standard_OVERRIDE;
//! Returns FALSE (not applicable to this volume).
virtual Standard_Boolean IsScalable() const Standard_OVERRIDE { return false; }
//! Returns a copy of the frustum transformed according to the matrix given
Standard_EXPORT virtual Handle(SelectMgr_BaseIntersector) ScaleAndTransform (const Standard_Integer theScale,
const gp_GTrsf& theTrsf,
const Handle(SelectMgr_FrustumBuilder)& theBuilder) const Standard_OVERRIDE;
public: //! @name SAT Tests for different objects
//! SAT intersection test between defined volume and given axis-aligned box
Standard_EXPORT virtual Standard_Boolean OverlapsBox (const SelectMgr_Vec3& theMinPnt,
const SelectMgr_Vec3& theMaxPnt,
const SelectMgr_ViewClipRange& theClipRange,
SelectBasics_PickResult& thePickResult) const Standard_OVERRIDE;
//! Returns true if selecting volume is overlapped by axis-aligned bounding box
//! with minimum corner at point theMinPt and maximum at point theMaxPt
Standard_EXPORT virtual Standard_Boolean OverlapsBox (const SelectMgr_Vec3& theMinPt,
const SelectMgr_Vec3& theMaxPt,
Standard_Boolean* theInside) const Standard_OVERRIDE;
//! Intersection test between defined volume and given point
Standard_EXPORT virtual Standard_Boolean OverlapsPoint (const gp_Pnt& thePnt,
const SelectMgr_ViewClipRange& theClipRange,
SelectBasics_PickResult& thePickResult) const Standard_OVERRIDE;
//! Always returns FALSE (not applicable to this selector).
virtual Standard_Boolean OverlapsPoint (const gp_Pnt& ) const Standard_OVERRIDE
{
return Standard_False;
}
//! SAT intersection test between defined volume and given ordered set of points,
//! representing line segments. The test may be considered of interior part or
//! boundary line defined by segments depending on given sensitivity type
Standard_EXPORT virtual Standard_Boolean OverlapsPolygon (const TColgp_Array1OfPnt& theArrayOfPnts,
Select3D_TypeOfSensitivity theSensType,
const SelectMgr_ViewClipRange& theClipRange,
SelectBasics_PickResult& thePickResult) const Standard_OVERRIDE;
//! Checks if line segment overlaps selecting frustum
Standard_EXPORT virtual Standard_Boolean OverlapsSegment (const gp_Pnt& thePnt1,
const gp_Pnt& thePnt2,
const SelectMgr_ViewClipRange& theClipRange,
SelectBasics_PickResult& thePickResult) const Standard_OVERRIDE;
//! SAT intersection test between defined volume and given triangle. The test may
//! be considered of interior part or boundary line defined by triangle vertices
//! depending on given sensitivity type
Standard_EXPORT virtual Standard_Boolean OverlapsTriangle (const gp_Pnt& thePnt1,
const gp_Pnt& thePnt2,
const gp_Pnt& thePnt3,
Select3D_TypeOfSensitivity theSensType,
const SelectMgr_ViewClipRange& theClipRange,
SelectBasics_PickResult& thePickResult) const Standard_OVERRIDE;
//! Returns true if selecting volume is overlapped by sphere with center theCenter
//! and radius theRadius
Standard_EXPORT virtual Standard_Boolean OverlapsSphere (const gp_Pnt& theCenter,
const Standard_Real theRadius,
Standard_Boolean* theInside = NULL) const Standard_OVERRIDE;
//! Returns true if selecting volume is overlapped by sphere with center theCenter
//! and radius theRadius
Standard_EXPORT virtual Standard_Boolean OverlapsSphere (const gp_Pnt& theCenter,
const Standard_Real theRadius,
const SelectMgr_ViewClipRange& theClipRange,
SelectBasics_PickResult& thePickResult) const Standard_OVERRIDE;
//! Returns true if selecting volume is overlapped by cylinder (or cone) with radiuses theBottomRad
//! and theTopRad, height theHeight and transformation to apply theTrsf.
Standard_EXPORT virtual Standard_Boolean OverlapsCylinder (const Standard_Real theBottomRad,
const Standard_Real theTopRad,
const Standard_Real theHeight,
const gp_Trsf& theTrsf,
const SelectMgr_ViewClipRange& theClipRange,
SelectBasics_PickResult& thePickResult) const Standard_OVERRIDE;
//! Returns true if selecting volume is overlapped by cylinder (or cone) with radiuses theBottomRad
//! and theTopRad, height theHeight and transformation to apply theTrsf.
Standard_EXPORT virtual Standard_Boolean OverlapsCylinder (const Standard_Real theBottomRad,
const Standard_Real theTopRad,
const Standard_Real theHeight,
const gp_Trsf& theTrsf,
Standard_Boolean* theInside = NULL) const Standard_OVERRIDE;
public:
//! Nullifies the handle to corresponding builder instance to prevent memory leaks
Standard_EXPORT void Clear();
//! Stores plane equation coefficients (in the following form:
//! Ax + By + Cz + D = 0) to the given vector
Standard_EXPORT virtual void GetPlanes (NCollection_Vector<SelectMgr_Vec4>& thePlaneEquations) const Standard_OVERRIDE;
//! Dumps the content of me into the stream
Standard_EXPORT virtual void DumpJson (Standard_OStream& theOStream, Standard_Integer theDepth = -1) const Standard_OVERRIDE;
protected:
//! Creates an empty triangular frustum.
Standard_EXPORT SelectMgr_TriangularFrustum();
private:
void cacheVertexProjections (SelectMgr_TriangularFrustum* theFrustum) const;
protected:
SelectionTriangle mySelTriangle; //!< parameters of selection triangle (it is used to build triangle frustum)
public:
DEFINE_STANDARD_RTTIEXT(SelectMgr_TriangularFrustum, SelectMgr_Frustum<3>)
friend class SelectMgr_TriangularFrustumSet;
};
#endif // _SelectMgr_TriangularFrustum_HeaderFile
| 55.940828
| 155
| 0.628094
|
mgreminger
|
a5ca0fc2533e9031bfb9a0e419e2f0b0de107748
| 4,326
|
hpp
|
C++
|
mangrove_master/include/Inference/CheckTernaryMonotony.hpp
|
mangrove-univr/Mangrove
|
3d95096c7adfad5eb27625b020c222487e91ab4e
|
[
"MIT"
] | 1
|
2019-12-28T09:30:24.000Z
|
2019-12-28T09:30:24.000Z
|
mangrove_master/include/Inference/CheckTernaryMonotony.hpp
|
mangrove-univr/Mangrove
|
3d95096c7adfad5eb27625b020c222487e91ab4e
|
[
"MIT"
] | 1
|
2020-08-25T10:57:11.000Z
|
2020-08-25T10:57:11.000Z
|
mangrove_master/include/Inference/CheckTernaryMonotony.hpp
|
mangrove-univr/Mangrove
|
3d95096c7adfad5eb27625b020c222487e91ab4e
|
[
"MIT"
] | null | null | null |
#pragma once
#include "Inference/ResultCollector.hpp"
#include <chrono>
#include <random>
#include <iostream>
namespace mangrove {
template <int F_INDEX>
struct TEST_TERNARY_INVARIANT {
inline static void ApplyT (numeric_t x1, numeric_t x2_1, numeric_t x2_2,
int *monotony, int *commutative) {
using invariant = typename GET_INVARIANT<F_INDEX-1, NTtemplate>::type;
if (monotony[F_INDEX-1] != MonotonyProperty::NOMONOTONY) {
if (x2_2 < x2_1) std::swap(x2_1, x2_2);
numeric_t y1 = APPLY_FUN<1, invariant>::eval(x1, x2_1);
numeric_t y2 = APPLY_FUN<1, invariant>::eval(x1, x2_2);
if (std::isnan(y1) || std::isnan(y2))
__ERROR("F: " << F_INDEX << " unknown for num: " << x1);
if (y1 < y2)
monotony[F_INDEX-1] = (monotony[F_INDEX-1] == MonotonyProperty::INCREASING ||
monotony[F_INDEX-1] == MonotonyProperty::UNKNOWN)?
MonotonyProperty::INCREASING :
MonotonyProperty::NOMONOTONY;
else if (y1 > y2)
monotony[F_INDEX-1] = (monotony[F_INDEX-1] == MonotonyProperty::DECREASING ||
monotony[F_INDEX-1] == MonotonyProperty::UNKNOWN)?
MonotonyProperty::DECREASING :
MonotonyProperty::NOMONOTONY;
}
if (commutative[F_INDEX-1] != CommutativeProperty::NO) {
numeric_t y1 = APPLY_FUN<1, invariant>::eval(x1, x2_1);
numeric_t y1_r = APPLY_FUN<1, invariant>::eval(x2_1, x1);
numeric_t y2 = APPLY_FUN<1, invariant>::eval(x1, x2_2);
numeric_t y2_r = APPLY_FUN<1, invariant>::eval(x2_2, x1);
if ((y1 == y1_r) && (y2 == y2_r))
commutative[F_INDEX-1] = CommutativeProperty::YES;
else
commutative[F_INDEX-1] = CommutativeProperty::NO;
}
TEST_TERNARY_INVARIANT<F_INDEX - 1>::ApplyT(x1, x2_1, x2_2, monotony, commutative);
}
};
template <>
struct TEST_TERNARY_INVARIANT<0> {
inline static void ApplyT (numeric_t, numeric_t, numeric_t, int *, int *) {}
};
template <int F_INDEX>
void CheckTernaryMonotony(ResultCollector<numeric_t> & results, int variables) {
const int ITERATION_NUMBER = 20;
num2_t *unaryResult = static_cast<num2_t *> (results.getVectorResult<1>());
// init the monotony and commutative array
int* monotony = results.getTernaryMonotony();
int* commutative = results.getTernaryCommutative();
for (int i = 0; i < F_INDEX; ++i) {
monotony[i] = MonotonyProperty::UNKNOWN;
commutative[i] = CommutativeProperty::UNKNOWNC;
}
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
std::default_random_engine generator (seed);
for (int var_1 = 0; var_1 < variables; ++var_1) {
std::uniform_real_distribution<numeric_t> distribution_1(unaryResult[var_1][0],
unaryResult[var_1][1]);
for (int var_1_iter = 0; var_1_iter < ITERATION_NUMBER; ++var_1_iter) {
numeric_t x1 = distribution_1(generator);
for (int var_2 = var_1 + 1; var_2 < variables; ++var_2) {
std::uniform_real_distribution<numeric_t> distribution_2(unaryResult[var_2][0],
unaryResult[var_2][1]);
for (int var_2_iter = 0; var_2_iter < ITERATION_NUMBER; ++var_2_iter) {
numeric_t x2_2 = distribution_2(generator);
numeric_t x2_1 = distribution_2(generator);
TEST_TERNARY_INVARIANT<F_INDEX>::ApplyT(x1, x2_1, x2_2, monotony, commutative);
}
}
}
}
}
} //@mangrove
| 42.831683
| 102
| 0.51988
|
mangrove-univr
|
a5cd308b5b67dd34784988aad2a49d19e3ee9bda
| 3,086
|
cpp
|
C++
|
tests/unit/sdf/actions/delayfile.cpp
|
qedalab/vcd_assert
|
40da307e60600fc4a814d4bba4679001f49f4375
|
[
"BSD-2-Clause"
] | 1
|
2019-04-30T17:56:23.000Z
|
2019-04-30T17:56:23.000Z
|
tests/unit/sdf/actions/delayfile.cpp
|
qedalab/vcd_assert
|
40da307e60600fc4a814d4bba4679001f49f4375
|
[
"BSD-2-Clause"
] | null | null | null |
tests/unit/sdf/actions/delayfile.cpp
|
qedalab/vcd_assert
|
40da307e60600fc4a814d4bba4679001f49f4375
|
[
"BSD-2-Clause"
] | 4
|
2018-08-01T08:32:00.000Z
|
2019-12-18T06:34:33.000Z
|
#include "../types/delayfile.hpp"
#include <parse/test/parse.hpp>
using namespace Parse::Test;
#include <sdf/grammar/delayfile.hpp>
#include <sdf/actions/delayfile.hpp>
#include <sdf/types/delayfile.hpp>
#include <sdf/serialize/delayfile.hpp>
// using namespace SDF;
// using namespace SDF::Test;
// constexpr auto project_source_dir =
// Parse::Util::static_string(PROJECT_SOURCE_DIR);
// constexpr auto dro_gate_input_path_ =
// "" + project_source_dir + "/examples/basic_dro_success/";
// constexpr auto and_gate_input_path_ =
// "" + project_source_dir + "/examples/basic_dro_success/";
// constexpr auto dro_file_path_abs_ = dro_gate_input_path_ + "dro.v";
// constexpr auto and_file_path_abs_ = and_gate_input_path_ + "and.v";
#include <catch2/catch.hpp>
namespace SDF::Test{
TEST_CASE("SDF.Actions.Delayfile", "[SDF][Actions][Delayfile]") {
SECTION("Case 1: From test SDF file") {
const DelayFileView wanted = test_delayfile_1;
//Delayfile from test delayfile view
DelayFileTester dft = DelayFileTester();
auto test_delayfile_p = dft.get_test_delayfile(wanted);
//serialize test delayfile
std::string serialized;
serialize_delayfile(ranges::back_inserter(serialized), test_delayfile_p);
//parse serialized delayfile using DelayFileReader
DelayFileReader test_reader{};
require_parse<Grammar::delay_file, Actions::DelayFileAction>(
serialized, test_reader);
//get Delayfile from parse result
auto test_p = test_reader.release();
REQUIRE(test_p.operator bool());
// auto& test = ;
//compare delayfile from parse with original delayfile view.
catch_test_delayfile(test_delayfile_1, *test_p);
}
// SECTION("Case 2: From SDF examples") {
// SECTION("DRO gate SDF") {
// tao::pegtl::file_input<> input(dro_gate_input_path_.to_string());
// DelayFileReader test_reader{};
// require_parse<Grammar::delay_file, Actions::DelayFileAction>(
// serialized, test_reader);
// //get Delayfile from parse result
// auto test_p = test_reader.release();
// REQUIRE(test_p.operator bool());
// // auto& test = ;
// //compare delayfile from parse with original delayfile view.
// catch_test_delayfile(test_delayfile_1, *test_p);
// CHECK(test.num_cells() > 0);
// SDF::Test::catch_test_delayfile(test_delayfile_1, test);
// }
// SECTION("AND gate SDF") {
// tao::pegtl::file_input<> input(and_gate_input_path_.to_string());
// DelayFileReader test_reader{};
// require_parse<Grammar::delay_file, Actions::DelayFileAction>(
// serialized, test_reader);
// //get Delayfile from parse result
// auto test_p = test_reader.release();
// REQUIRE(test_p.operator bool());
// // auto& test = ;
// //compare delayfile from parse with original delayfile view.
// catch_test_delayfile(test_delayfile_1, *test_p);
// CHECK(test.num_cells() > 0);
// SDF::Test::catch_test_delayfile(test_delayfile_1, test);
// }
// }
}
}
| 30.254902
| 77
| 0.681141
|
qedalab
|
a5ce785045b6cc7415884e3c722a14f962db9b86
| 25,799
|
cpp
|
C++
|
lib/Runtimes/Tracer/Tracer.cpp
|
seec-team/seec
|
4b92456011e86b70f9d88833a95c1f655a21cf1a
|
[
"MIT"
] | 7
|
2018-06-25T12:06:13.000Z
|
2022-01-18T09:20:13.000Z
|
lib/Runtimes/Tracer/Tracer.cpp
|
seec-team/seec
|
4b92456011e86b70f9d88833a95c1f655a21cf1a
|
[
"MIT"
] | 20
|
2016-12-01T23:46:12.000Z
|
2019-08-11T02:41:04.000Z
|
lib/Runtimes/Tracer/Tracer.cpp
|
seec-team/seec
|
4b92456011e86b70f9d88833a95c1f655a21cf1a
|
[
"MIT"
] | 1
|
2020-10-19T03:20:05.000Z
|
2020-10-19T03:20:05.000Z
|
//===- lib/Runtimes/Tracer/Tracer.cpp -------------------------------------===//
//
// SeeC
//
// This file is distributed under The MIT License (MIT). See LICENSE.TXT for
// details.
//
//===----------------------------------------------------------------------===//
///
/// \file
///
//===----------------------------------------------------------------------===//
#include "PrintRunError.hpp"
#include "Tracer.hpp"
#include "seec/DSA/MemoryArea.hpp"
#include "seec/ICU/Resources.hpp"
#include "seec/Runtimes/MangleFunction.h"
#include "seec/Trace/TraceFormat.hpp"
#include "seec/Trace/TraceStorage.hpp"
#include "seec/Trace/TraceThreadMemCheck.hpp"
#include "seec/Util/IndexTypesForLLVMObjects.hpp"
#include "seec/Util/ModuleIndex.hpp"
#include "seec/wxWidgets/AugmentResources.hpp"
#include "seec/wxWidgets/Config.hpp"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Type.h"
#include "llvm/IRReader/IRReader.h"
#include "llvm/Bitcode/BitcodeReader.h"
#include "llvm/ExecutionEngine/GenericValue.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Threading.h"
#include "unicode/locid.h"
#include <cassert>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <thread>
#if (defined(__unix__) || (defined(__APPLE__) && defined(__MACH__)))
#include <dlfcn.h>
#elif defined(_WIN32)
#include <Windows.h>
#endif
#include "seec/Transforms/RecordExternal/RecordInfo.h" // needs <cstdint>
namespace seec {
namespace trace {
static constexpr char const *getTraceSizeLimitEnvVar() {
return "SEEC_TRACE_LIMIT";
}
//------------------------------------------------------------------------------
// ThreadEnvironment
//------------------------------------------------------------------------------
ThreadEnvironment::ThreadEnvironment(ProcessEnvironment &PE)
: Process(PE),
ThreadTracer(PE.getProcessListener(),
PE.getStreamAllocator()),
FunIndex(nullptr),
Stack()
{}
ThreadEnvironment::~ThreadEnvironment()
{}
void ThreadEnvironment::checkOutputSize()
{
if (!ThreadTracer.traceEnabled())
return;
auto const TotalSize = Process.getStreamAllocator().getTotalSize();
if (TotalSize > Process.getTraceSizeLimit()) {
llvm::errs() << "\nSeeC: Trace size limit reached!\n";
auto &ProcessListener = Process.getProcessListener();
ProcessListener.traceClose();
}
}
void ThreadEnvironment::pushFunction(llvm::Function *Fun) {
Stack.push_back(FunctionEnvironment{Fun});
FunIndex = Process.getModuleIndex().getFunctionIndex(Fun);
}
llvm::Function *ThreadEnvironment::popFunction() {
auto Fun = Stack.back();
Stack.pop_back();
FunIndex =
Stack.empty() ? nullptr
: Process.getModuleIndex().getFunctionIndex(Stack.back().Function);
return Fun.Function;
}
llvm::Instruction *ThreadEnvironment::getInstruction() const {
return getFunctionIndex()
.getInstruction(InstrIndexInFn{Stack.back().InstructionIndex});
}
//------------------------------------------------------------------------------
// ProcessEnvironment
//------------------------------------------------------------------------------
/// \brief Get the multiplier to use for a given byte multiple.
///
static uint64_t getMultiplierForBytes(char const *ForUnit)
{
struct LookupTy {
char const *Unit;
uint64_t Multiplier;
};
LookupTy LookupTable[] = {
{"KiB", 1024},
{"K" , 1024},
{"MiB", 1024*1024},
{"M" , 1024*1024},
{"GiB", 1024*1024*1024},
{"G" , 1024*1024*1024}
};
auto const LookupLength = sizeof(LookupTable) / sizeof(LookupTable[0]);
for (std::size_t i = 0; i < LookupLength; ++i)
if(std::strcmp(ForUnit, LookupTable[i].Unit) == 0)
return LookupTable[i].Multiplier;
return 1;
}
/// \brief Get the number of bytes represented by a string.
///
uint64_t getByteSizeFromEnvVar(char const * const EnvVarName,
char const * const StringValue)
{
char *Remainder = nullptr;
auto const Value = std::strtoull(StringValue, &Remainder, 10);
if (Remainder == StringValue) {
fprintf(stderr, "\nSeeC: Error parsing '%s'.\n", EnvVarName);
std::exit(EXIT_FAILURE);
}
// Ensure that the value fits in the given type.
auto const MaxValue = std::numeric_limits<uint64_t>::max();
if (Value > MaxValue) {
fprintf(stderr, "\nSeeC: Value of '%s' is too large.\n", EnvVarName);
fprintf(stderr, "\tMaximum = %s bytes.\n",
std::to_string(MaxValue).c_str());
std::exit(EXIT_FAILURE);
}
// Consume whitespace to find the units.
while (*Remainder && std::isblank(*Remainder))
++Remainder;
auto const Multiplier = getMultiplierForBytes(Remainder);
if (Multiplier <= 1)
return Value;
// Ensure that the final value fits in the given type.
if (MaxValue / Multiplier < Value) {
fprintf(stderr, "\nSeeC: Value of '%s' is too large.\n", EnvVarName);
fprintf(stderr, "\tMaximum = %s bytes.\n",
std::to_string(MaxValue).c_str());
std::exit(EXIT_FAILURE);
}
return Value * Multiplier;
}
/// \brief Get the size limit to use for thread event files.
///
/// NOTE: This function uses std::getenv() and thus is not thread-safe.
///
static offset_uint getUserTraceSizeLimit()
{
auto const EnvVarName = getTraceSizeLimitEnvVar();
if (auto const EnvVar = std::getenv(EnvVarName))
return getByteSizeFromEnvVar(EnvVarName, EnvVar);
return (1024 * 1024 * 1024); // 1GiB
}
ProcessEnvironment::ProcessEnvironment()
: Context(),
Mod(),
ModIndex(),
StreamAllocator(),
ICUResourceLoader(),
ProcessTracer(),
ThreadLookup(),
ThreadLookupMutex(),
InterceptorAddresses(),
TraceSizeLimit(getUserTraceSizeLimit()),
ProgramName()
{
// On windows, lookup the module's globals.
#if defined(_WIN32)
auto const ExeHdl = GetModuleHandle(nullptr);
assert(ExeHdl && "module handle for executable");
// TODO: split this and check that the pointer is non-NULL.
#define SEEC_GET_INFO_VAR(TYPE, NAME) \
TYPE const *NAME##Ptr = \
reinterpret_cast<TYPE const *>(GetProcAddress(ExeHdl, #NAME)); \
assert(NAME##Ptr && "info not found!"); \
TYPE const NAME = *NAME##Ptr;
#define SEEC_GET_INFO_PTR(TYPE, NAME) \
TYPE const NAME = reinterpret_cast<TYPE>(GetProcAddress(ExeHdl, #NAME)); \
assert(NAME && "info not found!");
SEEC_GET_INFO_PTR(char const *, SeeCInfoModuleIdentifier)
SEEC_GET_INFO_PTR(char const *, SeeCInfoModuleBitcode)
SEEC_GET_INFO_VAR(uint64_t, SeeCInfoModuleBitcodeLength)
SEEC_GET_INFO_PTR(void **, SeeCInfoFunctions)
SEEC_GET_INFO_PTR(void **, SeeCInfoGlobals)
SEEC_GET_INFO_PTR(char const *, __SeeC_ResourcePath__)
#undef SEEC_GET_INFO_VAR
#undef SEEC_GET_INFO_PTR
#endif
ICUResourceLoader.reset(new ResourceLoader(__SeeC_ResourcePath__));
// Parse the Module bitcode, which is stored in a global variable.
llvm::StringRef BitcodeRef {
SeeCInfoModuleBitcode,
static_cast<std::size_t>(SeeCInfoModuleBitcodeLength)
};
auto BitcodeBuffer = llvm::MemoryBuffer::getMemBuffer(BitcodeRef, "", false);
auto MaybeMod = llvm::parseBitcodeFile(BitcodeBuffer->getMemBufferRef(),
Context);
if (!MaybeMod) {
llvm::errs() << "\nSeeC: Failed to parse module bitcode.\n";
handleAllErrors(MaybeMod.takeError(),
[](llvm::ErrorInfoBase &EIB) {
llvm::errs() << EIB.message() << "\n";
});
exit(EXIT_FAILURE);
}
Mod = std::move(*MaybeMod);
// Create the output stream allocator.
auto MaybeOutput = OutputStreamAllocator::createOutputStreamAllocator();
if (MaybeOutput.assigned(0)) {
StreamAllocator = std::move(MaybeOutput.get<0>());
}
else {
llvm::errs() << "\nSeeC: Failed to create output stream allocator.\n";
if (MaybeOutput.assigned<seec::Error>())
llvm::errs() << MaybeOutput.get<seec::Error>();
exit(EXIT_FAILURE);
}
// Attempt to load ICU resources.
ICUResourceLoader->loadResource("Trace");
ICUResourceLoader->loadResource("RuntimeErrors");
// Write a copy of the Module's bitcode into the trace directory.
StreamAllocator->writeModule(BitcodeRef);
// Build ModIndex.
ModIndex.reset(new ModuleIndex(*Mod));
// Create the process tracer.
ProcessTracer.reset(new TraceProcessListener(*Mod,
*ModIndex,
*StreamAllocator));
// Setup runtime error printing.
ProcessTracer->setRunErrorCallback(
[this] (seec::runtime_errors::RunError const &Error,
llvm::Instruction const *Instruction)
{
return PrintRunError(Error, Instruction, *ModIndex);
});
// Give the listener the run-time locations of functions.
uint32_t FunIndex = 0;
for (auto &Fun: *Mod) {
if (Fun.isIntrinsic())
continue;
ProcessTracer->notifyFunction(FunIndex,
&Fun,
SeeCInfoFunctions[FunIndex]);
++FunIndex;
}
// Give the listener the run-time locations of globals.
uint32_t GlobalIndex = 0;
for (auto GlobalIt = Mod->global_begin(), GlobalEnd = Mod->global_end();
GlobalIt != GlobalEnd; ++GlobalIt) {
ProcessTracer->notifyGlobalVariable(GlobalIndex,
&*GlobalIt,
SeeCInfoGlobals[GlobalIndex]);
++GlobalIndex;
}
ProcessTracer->notifyGlobalVariablesComplete();
ProcessTracer->traceWriteProcessData();
#define SEEC__STR2(NAME) #NAME
#define SEEC__STR(NAME) SEEC__STR2(NAME)
// Find the location of all intercepted functions.
#if (defined(__unix__) || (defined(__APPLE__) && defined(__MACH__)))
#define SEEC_INTERCEPTED_FUNCTION(NAME) \
if (auto Ptr = dlsym(RTLD_DEFAULT, SEEC__STR(SEEC_MANGLE_FUNCTION(NAME)))) \
InterceptorAddresses.insert(reinterpret_cast<uintptr_t>(Ptr));
#include "seec/Runtimes/Tracer/InterceptedFunctions.def"
#elif defined(_WIN32)
auto const RTHdl = GetModuleHandle("seecRuntimeTracer");
#define SEEC_INTERCEPTED_FUNCTION(NAME) \
if (auto Ptr = GetProcAddress(RTHdl, SEEC__STR(SEEC_MANGLE_FUNCTION(NAME)))) \
InterceptorAddresses.insert(reinterpret_cast<uintptr_t>(Ptr));
#include "seec/Runtimes/Tracer/InterceptedFunctions.def"
#else
#error "Intercepted function locating not implemented for this platform."
#endif
#undef SEEC__STR2
#undef SEEC__STR
}
ProcessEnvironment::~ProcessEnvironment()
{
// Finalize the trace.
ThreadLookup.clear();
ProcessTracer.reset();
}
ThreadEnvironment *ProcessEnvironment::getOrCreateCurrentThreadEnvironment()
{
std::lock_guard<std::mutex> Lock{ThreadLookupMutex};
auto &ThreadEnvPtr = ThreadLookup[std::this_thread::get_id()];
if (!ThreadEnvPtr)
ThreadEnvPtr.reset(new ThreadEnvironment(getProcessEnvironment()));
return ThreadEnvPtr.get();
}
void ProcessEnvironment::setProgramName(llvm::StringRef Name)
{
ProgramName = llvm::sys::path::filename(Name);
StreamAllocator->updateTraceName(ProgramName);
}
//------------------------------------------------------------------------------
// getProcessEnvironment()
//------------------------------------------------------------------------------
ProcessEnvironment &getProcessEnvironment() {
static std::once_flag InitFlag;
static std::unique_ptr<ProcessEnvironment> ProcessEnv;
std::call_once(InitFlag, [&](){
ProcessEnv.reset(new ProcessEnvironment());
});
return *ProcessEnv;
}
//------------------------------------------------------------------------------
// getThreadEnvironment()
//------------------------------------------------------------------------------
ThreadEnvironment &getThreadEnvironment() {
#if __has_feature(cxx_thread_local)
// Keep a thread-local pointer to this thread's environment.
thread_local ThreadEnvironment *TE =
getProcessEnvironment().getOrCreateCurrentThreadEnvironment();
#else
// Keep a thread-local pointer to this thread's environment.
static __thread ThreadEnvironment *TE = nullptr;
if (!TE)
TE = getProcessEnvironment().getOrCreateCurrentThreadEnvironment();
#endif
assert(TE && "ThreadEnvironment not found!");
return *TE;
}
} // namespace trace (in seec)
} // namespace seec
extern "C" {
void SeeCRecordFunctionBegin(uint32_t Index) {
auto &ThreadEnv = seec::trace::getThreadEnvironment();
auto &ModIndex = seec::trace::getProcessEnvironment().getModuleIndex();
auto &Listener = ThreadEnv.getThreadListener();
auto F = ModIndex.getFunction(Index);
Listener.notifyFunctionBegin(Index, F);
ThreadEnv.pushFunction(F);
ThreadEnv.checkOutputSize();
}
void SeeCRecordFunctionEnd(uint32_t Index, uint32_t const RawIndex) {
auto const InstructionIndex = seec::InstrIndexInFn{RawIndex};
auto &ThreadEnv = seec::trace::getThreadEnvironment();
auto &Listener = ThreadEnv.getThreadListener();
auto const &FIndex = ThreadEnv.getFunctionIndex();
auto F = ThreadEnv.popFunction();
auto I = FIndex.getInstruction(InstructionIndex);
// Check F matches Index?
Listener.notifyFunctionEnd(Index, F, InstructionIndex, I);
ThreadEnv.checkOutputSize();
}
void SeeCRecordArgumentByVal(uint32_t Index, void *Address) {
auto &ThreadEnv = seec::trace::getThreadEnvironment();
auto &Listener = ThreadEnv.getThreadListener();
auto Arg = ThreadEnv.getFunctionIndex().getArgument(Index);
assert(Arg && "Expected Argument");
Listener.notifyArgumentByVal(Index, Arg, Address);
ThreadEnv.checkOutputSize();
}
void SeeCRecordArgs(int64_t ArgC, char **ArgV) {
auto &ThreadEnv = seec::trace::getThreadEnvironment();
auto &Listener = ThreadEnv.getThreadListener();
Listener.notifyArgs(ArgC, ArgV);
if (ArgC) {
auto &ProcessEnv = ThreadEnv.getProcessEnvironment();
ProcessEnv.setProgramName(ArgV[0]);
}
ThreadEnv.checkOutputSize();
}
void SeeCRecordEnv(char **EnvP) {
auto &ThreadEnv = seec::trace::getThreadEnvironment();
auto &Listener = ThreadEnv.getThreadListener();
Listener.notifyEnv(EnvP);
ThreadEnv.checkOutputSize();
}
void SeeCRecordSetInstruction(uint32_t const RawIndex) {
auto const Index = seec::InstrIndexInFn{RawIndex};
auto &ThreadEnv = seec::trace::getThreadEnvironment();
ThreadEnv.setInstructionIndex(Index);
}
void SeeCRecordPreAlloca(uint32_t const RawIndex,
uint64_t const ElemSize,
uint64_t const ElemCount)
{
auto const Index = seec::InstrIndexInFn{RawIndex};
auto &ThreadEnv = seec::trace::getThreadEnvironment();
ThreadEnv.setInstructionIndex(Index);
auto const Alloca = llvm::cast<llvm::AllocaInst>(ThreadEnv.getInstruction());
auto &Listener = ThreadEnv.getThreadListener();
Listener.notifyPreAlloca(Index, *Alloca, ElemSize, ElemCount);
}
void SeeCRecordPreLoad(uint32_t RawIndex, void *Address, uint64_t Size) {
auto const Index = seec::InstrIndexInFn{RawIndex};
auto &ThreadEnv = seec::trace::getThreadEnvironment();
ThreadEnv.setInstructionIndex(Index);
auto Load = llvm::dyn_cast<llvm::LoadInst>(ThreadEnv.getInstruction());
assert(Load && "Expected LoadInst");
auto &Listener = ThreadEnv.getThreadListener();
Listener.notifyPreLoad(Index, Load, Address, Size);
}
void SeeCRecordPostLoad(uint32_t RawIndex, void *Address, uint64_t Size) {
auto const Index = seec::InstrIndexInFn{RawIndex};
auto &ThreadEnv = seec::trace::getThreadEnvironment();
auto Load = llvm::dyn_cast<llvm::LoadInst>(ThreadEnv.getInstruction());
assert(Load && "Expected LoadInst");
auto &Listener = ThreadEnv.getThreadListener();
Listener.notifyPostLoad(Index, Load, Address, Size);
ThreadEnv.checkOutputSize();
}
void SeeCRecordPreStore(uint32_t RawIndex, void *Address, uint64_t Size) {
auto const Index = seec::InstrIndexInFn{RawIndex};
auto &ThreadEnv = seec::trace::getThreadEnvironment();
ThreadEnv.setInstructionIndex(Index);
auto Store = llvm::dyn_cast<llvm::StoreInst>(ThreadEnv.getInstruction());
assert(Store && "Expected StoreInst");
auto &Listener = ThreadEnv.getThreadListener();
Listener.notifyPreStore(Index, Store, Address, Size);
ThreadEnv.checkOutputSize();
}
void SeeCRecordPostStore(uint32_t RawIndex, void *Address, uint64_t Size) {
auto const Index = seec::InstrIndexInFn{RawIndex};
auto &ThreadEnv = seec::trace::getThreadEnvironment();
auto Store = llvm::dyn_cast<llvm::StoreInst>(ThreadEnv.getInstruction());
assert(Store && "Expected StoreInst");
auto &Listener = ThreadEnv.getThreadListener();
Listener.notifyPostStore(Index, Store, Address, Size);
ThreadEnv.checkOutputSize();
}
void SeeCRecordPreCall(uint32_t RawIndex, void *Address) {
auto const Index = seec::InstrIndexInFn{RawIndex};
auto &ThreadEnv = seec::trace::getThreadEnvironment();
ThreadEnv.setInstructionIndex(Index);
auto &ProcessEnv = seec::trace::getProcessEnvironment();
if (ProcessEnv.isInterceptedFunction(reinterpret_cast<uintptr_t>(Address))) {
ThreadEnv.setInstructionIsInterceptedCall();
}
else {
auto Call = llvm::dyn_cast<llvm::CallInst>(ThreadEnv.getInstruction());
assert(Call && "Expected CallInst");
auto &Listener = ThreadEnv.getThreadListener();
Listener.notifyPreCall(Index, Call, Address);
}
}
void SeeCRecordPostCall(uint32_t RawIndex, void *Address) {
auto const Index = seec::InstrIndexInFn{RawIndex};
auto &ThreadEnv = seec::trace::getThreadEnvironment();
if (!ThreadEnv.getInstructionIsInterceptedCall()) {
auto Call = llvm::dyn_cast<llvm::CallInst>(ThreadEnv.getInstruction());
assert(Call && "Expected CallInst");
auto &Listener = ThreadEnv.getThreadListener();
Listener.notifyPostCall(Index, Call, Address);
}
ThreadEnv.checkOutputSize();
}
void SeeCRecordPreCallIntrinsic(uint32_t RawIndex) {
auto const Index = seec::InstrIndexInFn{RawIndex};
auto &ThreadEnv = seec::trace::getThreadEnvironment();
ThreadEnv.setInstructionIndex(Index);
auto Call = llvm::dyn_cast<llvm::CallInst>(ThreadEnv.getInstruction());
assert(Call && "Expected CallInst");
auto &Listener = ThreadEnv.getThreadListener();
Listener.notifyPreCallIntrinsic(Index, Call);
}
void SeeCRecordPostCallIntrinsic(uint32_t RawIndex) {
auto const Index = seec::InstrIndexInFn{RawIndex};
auto &ThreadEnv = seec::trace::getThreadEnvironment();
auto Call = llvm::dyn_cast<llvm::CallInst>(ThreadEnv.getInstruction());
assert(Call && "Expected CallInst");
auto &Listener = ThreadEnv.getThreadListener();
Listener.notifyPostCallIntrinsic(Index, Call);
ThreadEnv.checkOutputSize();
}
void SeeCRecordPreDivide(uint32_t RawIndex) {
auto const Index = seec::InstrIndexInFn{RawIndex};
auto &ThreadEnv = seec::trace::getThreadEnvironment();
ThreadEnv.setInstructionIndex(Index);
auto BinOp = llvm::dyn_cast<llvm::BinaryOperator>(ThreadEnv.getInstruction());
assert(BinOp && "Expected BinaryOperator");
auto &Listener = ThreadEnv.getThreadListener();
Listener.notifyPreDivide(Index, BinOp);
}
void SeeCRecordUpdateVoid(uint32_t RawIndex) {
auto const Index = seec::InstrIndexInFn{RawIndex};
auto &ThreadEnv = seec::trace::getThreadEnvironment();
ThreadEnv.setInstructionIndex(Index);
if (ThreadEnv.getInstructionIsInterceptedCall())
return;
auto &Listener = ThreadEnv.getThreadListener();
Listener.notifyValue(Index, ThreadEnv.getInstruction());
ThreadEnv.checkOutputSize();
}
#define SEEC_RECORD_TYPED(NAME, TYPE) \
void SeeCRecordUpdate##NAME(uint32_t RawIndex, TYPE Value) { \
auto const Index = seec::InstrIndexInFn{RawIndex}; \
auto &ThreadEnv = seec::trace::getThreadEnvironment(); \
ThreadEnv.setInstructionIndex(Index); \
if (ThreadEnv.getInstructionIsInterceptedCall()) \
return; \
auto &Listener = ThreadEnv.getThreadListener(); \
Listener.notifyValue(Index, ThreadEnv.getInstruction(), Value); \
ThreadEnv.checkOutputSize(); \
} \
void SeeCRecordSetCurrent##NAME(TYPE Value) { \
auto &ThreadEnv = seec::trace::getThreadEnvironment(); \
auto &Listener = ThreadEnv.getThreadListener(); \
Listener.notifyValue(ThreadEnv.getInstructionIndex(), \
ThreadEnv.getInstruction(), \
Value); \
ThreadEnv.checkOutputSize(); \
}
SEEC_RECORD_TYPED(Pointer, void *)
SEEC_RECORD_TYPED(Int64, uint64_t)
SEEC_RECORD_TYPED(Int32, uint32_t)
SEEC_RECORD_TYPED(Int16, uint16_t)
SEEC_RECORD_TYPED(Int8, uint8_t)
SEEC_RECORD_TYPED(Float, float)
SEEC_RECORD_TYPED(Double, double)
SEEC_RECORD_TYPED(X86FP80, long double)
// UpdateFP128
// UpdatePPC128
#undef SEEC_RECORD_TYPED
void SEEC_MANGLE_FUNCTION(LockDynamicMemory)() {
auto &Listener = seec::trace::getThreadEnvironment().getThreadListener();
Listener.acquireDynamicMemoryLock();
}
void
SEEC_MANGLE_FUNCTION(RecordMalloc)
(void const * const Address, size_t const Size)
{
auto &Listener = seec::trace::getThreadEnvironment().getThreadListener();
Listener.recordMalloc(reinterpret_cast<uintptr_t>(Address), Size);
}
void SEEC_MANGLE_FUNCTION(RecordFree)(void const * const Address) {
auto &Listener = seec::trace::getThreadEnvironment().getThreadListener();
Listener.recordFreeAndClear(reinterpret_cast<uintptr_t>(Address));
}
void SEEC_MANGLE_FUNCTION(LockMemoryForWriting)() {
auto &Listener = seec::trace::getThreadEnvironment().getThreadListener();
Listener.acquireGlobalMemoryWriteLock();
}
void SEEC_MANGLE_FUNCTION(LockMemoryForReading)() {
auto &Listener = seec::trace::getThreadEnvironment().getThreadListener();
Listener.acquireGlobalMemoryReadLock();
}
char SEEC_MANGLE_FUNCTION(IsKnownMemoryCovering)(void const * const Start,
size_t const Size)
{
auto const Address = reinterpret_cast<uintptr_t>(Start);
return seec::trace::getThreadEnvironment()
.getThreadListener()
.isKnownMemoryRegionCovering(Address, Size);
}
void SEEC_MANGLE_FUNCTION(RemoveKnownMemory)(void const * const Start) {
auto const Address = reinterpret_cast<uintptr_t>(Start);
seec::trace::getThreadEnvironment()
.getThreadListener()
.removeKnownMemoryRegion(Address);
}
void SEEC_MANGLE_FUNCTION(AddKnownMemory)(void const * const Start,
size_t const Size,
char const Readable,
char const Writable)
{
auto const Address = reinterpret_cast<uintptr_t>(Start);
auto const Permission
= Readable ? (Writable ? seec::MemoryPermission::ReadWrite
: seec::MemoryPermission::ReadOnly)
: (Writable ? seec::MemoryPermission::WriteOnly
: seec::MemoryPermission::None);
seec::trace::getThreadEnvironment()
.getThreadListener()
.addKnownMemoryRegion(Address, Size, Permission);
}
void
SEEC_MANGLE_FUNCTION(RecordUntypedState)
(char const * const Data, size_t const Size)
{
auto &Listener = seec::trace::getThreadEnvironment().getThreadListener();
Listener.recordUntypedState(Data, Size);
}
void SEEC_MANGLE_FUNCTION(ReleaseLocks)() {
auto &Listener = seec::trace::getThreadEnvironment().getThreadListener();
Listener.exitPostNotification();
}
void SEEC_MANGLE_FUNCTION(SetPointerTargetNewValid)(void const * const Pointer)
{
auto &Thread = seec::trace::getThreadEnvironment().getThreadListener();
auto const Address = reinterpret_cast<uintptr_t>(Pointer);
auto const ActiveFn = Thread.getActiveFunction();
assert(ActiveFn);
auto const Area = seec::trace::getContainingMemoryArea(Thread, Address);
auto const Target = Area.assigned() ? Area.get<seec::MemoryArea>().start()
: Address;
ActiveFn->setPointerObject(ActiveFn->getActiveInstruction(),
Thread.getProcessListener()
.makePointerObject(Target));
}
void SEEC_MANGLE_FUNCTION(SetPointerTargetFromArgument)(unsigned const ArgNo)
{
auto const ActiveFn = seec::trace::getThreadEnvironment()
.getThreadListener()
.getActiveFunction();
assert(ActiveFn);
ActiveFn->transferArgPointerObjectToCall(ArgNo);
}
void SEEC_MANGLE_FUNCTION(CheckCStringRead)(size_t const Parameter,
char const * const CString)
{
using namespace seec::runtime_errors::format_selects;
auto &Env = seec::trace::getThreadEnvironment();
seec::trace::CStdLibChecker Checker {Env.getThreadListener(),
Env.getInstructionIndex(),
CStdFunction::userdefined};
Checker.checkCStringRead(Parameter, CString);
}
} // extern "C"
| 32.615676
| 80
| 0.656111
|
seec-team
|
a5d00e0de34eb91df41e4eff8d6d2902ae15fd93
| 1,336
|
cpp
|
C++
|
Contests/Codeforces/CF912/d.cpp
|
SYCstudio/OI
|
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
|
[
"MIT"
] | 4
|
2017-10-31T14:25:18.000Z
|
2018-06-10T16:10:17.000Z
|
Contests/Codeforces/CF912/d.cpp
|
SYCstudio/OI
|
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
|
[
"MIT"
] | null | null | null |
Contests/Codeforces/CF912/d.cpp
|
SYCstudio/OI
|
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
|
[
"MIT"
] | null | null | null |
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<queue>
#include<cmath>
using namespace std;
#define mem(Arr,x) memset(Arr,x,sizeof(Arr))
#define ld long double
const int maxN=10001;
const int F1[5]={0,0,0,1,-1};
const int F2[5]={0,1,-1,0,0};
const int inf=2147483647;
class Pos
{
public:
int x,y;
};
int n,m,R,K;
ld midn,midm;
int lx,ly,rx,ry;
ld midnn,midmm;
priority_queue<Pos> Q;
bool operator < (Pos A,Pos B)
{
return fabs((ld)A.x+0.5-midn)+fabs((ld)A.y+0.5-midm)>fabs((ld)B.x+0.5-midn)+fabs((ld)B.y+0.5-midm);
}
ld GetAns(Pos u);
int main()
{
int h=0,t=0;
cin>>n>>m>>R>>K;
lx=(n+1)/2;ly=(m+1)/2;
rx=(n+1)/2+(n%2==0);ry=(m+1)/2+(m%2==0);
midn=(ld)1.0*(lx+rx+1)/2;
midm=(ld)1.0*(ly+ry+1)/2;
cout<<midn<<" "<<midm<<endl;
for (int i=lx;i<=rx;i++) for (int j=ly;j<=ry;j++) Q.push((Pos){i,j});
for (int i=1;i<=K;i++)
{
Pos u=Q.top();Q.pop();
cout<<u.x<<" "<<u.y<<endl;
if (Q.empty())
{
lx--;ly--;rx++;ry++;
cout<<lx<<" "<<ly<<" "<<rx<<" "<<ry<<endl;
for (int j=max(lx,1);j<=min(rx,n);j++)
{
if (ly>=1) Q.push((Pos){j,ly});
if (ry<=m) Q.push((Pos){j,ry});
}
for (int j=max(ly,1);j<=min(ry,m);j++)
{
if (lx>=1) Q.push((Pos){lx,j});
if (rx<=n) Q.push((Pos){rx,j});
}
}
}
return 0;
}
ld GetAns(Pos u)
{
int l=u.x
}
| 18.054054
| 100
| 0.545659
|
SYCstudio
|
a5d0e7b600424ca694873f487010cad7eca3bff2
| 3,768
|
hpp
|
C++
|
src/backends/opengl/OpenglBuffer.hpp
|
AntonHakansson/KvantEngine
|
f101fc771a8e9eca8ced59a084b9be0169e95649
|
[
"MIT"
] | null | null | null |
src/backends/opengl/OpenglBuffer.hpp
|
AntonHakansson/KvantEngine
|
f101fc771a8e9eca8ced59a084b9be0169e95649
|
[
"MIT"
] | 2
|
2017-04-05T01:50:13.000Z
|
2017-08-10T00:58:26.000Z
|
src/backends/opengl/OpenglBuffer.hpp
|
AntonHakansson/KvantEngine
|
f101fc771a8e9eca8ced59a084b9be0169e95649
|
[
"MIT"
] | null | null | null |
#ifndef OPENGL_BUFFER_HPP_INCLUDED
#define OPENGL_BUFFER_HPP_INCLUDED
#include <vector>
#include "core/Context.hpp"
#include "core/Loader.hpp"
#include "utils/Checks.hpp"
namespace Kvant::graphics::opengl {
template <typename B> struct OpenglColorBuffer {
static int counter;
GLuint tex;
GLuint unit;
unsigned int width;
unsigned int height;
OpenglColorBuffer(const GraphicsContext<B> &ctx);
virtual ~OpenglColorBuffer();
virtual void create(unsigned int w, unsigned int h) {}
};
template <typename B> int OpenglColorBuffer<B>::counter = 0;
template <typename B>
OpenglColorBuffer<B>::OpenglColorBuffer(const GraphicsContext<B> &ctx) {
this->unit = OpenglColorBuffer<B>::counter++;
GL_CHECK(glGenTextures(1, &this->tex));
}
template <typename B> OpenglColorBuffer<B>::~OpenglColorBuffer() {
GL_CHECK(glDeleteTextures(1, &tex));
}
template <typename GRAPHICS>
struct OpenglRgbaBuffer : OpenglColorBuffer<GRAPHICS> {
OpenglRgbaBuffer(const GraphicsContext<GRAPHICS> &ctx)
: OpenglColorBuffer<GRAPHICS>(ctx) {}
virtual ~OpenglRgbaBuffer() {}
void create(unsigned int w, unsigned int h) override {
GL_CHECK(glBindTexture(GL_TEXTURE_2D, this->tex));
GL_CHECK(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA,
GL_UNSIGNED_BYTE, NULL));
GL_CHECK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST));
GL_CHECK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST));
this->width = w;
this->height = h;
}
};
template <typename GRAPHICS> class OpenglBaseBuffer {
public:
OpenglBaseBuffer() {}
virtual ~OpenglBaseBuffer() {}
unsigned int width() const { return _w; }
unsigned int height() const { return _h; }
void bind() const { GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, _buffer)); }
void bind_for_read() const {
GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, _buffer));
}
void bind_for_draw() const {
GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, _buffer));
}
void copy_depth_from(const OpenglBaseBuffer<GRAPHICS> &b) const {
b.bind_for_read();
bind_for_draw();
glBlitFramebuffer(0, 0, b.width(), b.height(), 0, 0, b.width(), b.height(),
GL_DEPTH_BUFFER_BIT, GL_NEAREST);
bind();
}
virtual void resize(unsigned int w, unsigned int h) {
_w = w;
_h = h;
}
protected:
GLuint _buffer = 0;
unsigned int _w, _h;
};
template <typename B> struct OpenglTexture : OpenglColorBuffer<B> {
OpenglTexture(const GraphicsContext<B> &ctx, std::string filename);
void create_texture(const char *filename);
};
template <typename B>
OpenglTexture<B>::OpenglTexture(const GraphicsContext<B> &ctx,
std::string filename)
: OpenglColorBuffer<B>(ctx) {
create_texture(filename.c_str());
}
template <typename B>
void OpenglTexture<B>::create_texture(const char *filename) {
unsigned char *img;
unsigned int ww, hh;
GL_CHECK(glBindTexture(GL_TEXTURE_2D, this->tex));
if (load_png_for_texture(&img, &ww, &hh, filename)) {
GL_CHECK(
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE));
GL_CHECK(
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE));
GL_CHECK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR));
GL_CHECK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR));
GL_CHECK(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, ww, hh, 0, GL_RGBA,
GL_UNSIGNED_BYTE, img));
free(img);
this->width = ww;
this->height = hh;
}
}
template <typename GRAPHICS>
class OpenglScreenBuffer : public OpenglBaseBuffer<GRAPHICS> {};
} // namespace Kvant::graphics::opengl
#endif // OPENGL_BUFFER_HPP_INCLUDED
| 30.144
| 80
| 0.711518
|
AntonHakansson
|
a5d40c64c9e77d24d58e51f957a1fe981eaac386
| 978
|
cpp
|
C++
|
Day9_MaximumWidthOfBinaryTree.cpp
|
SuYuxi/July-LeetCoding-Challenge
|
8a1b3893d4a5869bac483eefe97650e754e7298b
|
[
"MIT"
] | null | null | null |
Day9_MaximumWidthOfBinaryTree.cpp
|
SuYuxi/July-LeetCoding-Challenge
|
8a1b3893d4a5869bac483eefe97650e754e7298b
|
[
"MIT"
] | null | null | null |
Day9_MaximumWidthOfBinaryTree.cpp
|
SuYuxi/July-LeetCoding-Challenge
|
8a1b3893d4a5869bac483eefe97650e754e7298b
|
[
"MIT"
] | null | null | null |
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int widthOfBinaryTree(TreeNode* root) {
if(!root) return 0;
maxWidth = 0;
dfs(root, 0, 0);
return maxWidth;
}
void dfs(TreeNode* node, int depth, unsigned long order) {
if(left.size() == depth) left.emplace_back(order);
else left[depth] = min(left[depth], order);
maxWidth = max(maxWidth, order - left[depth] + 1);
if(node->left) dfs(node->left, depth + 1, 2 * order);
if(node->right) dfs(node->right, depth + 1, 2 * order + 1);
}
private:
vector<unsigned long> left;
unsigned long maxWidth;
};
| 30.5625
| 93
| 0.576687
|
SuYuxi
|
a5d9e0b684c88126bee2455d0224bfe6cadeea05
| 3,107
|
cpp
|
C++
|
anno/LabelDefinition.cpp
|
urobots-io/anno
|
8e240185e6fc0908687b15a39c892814a6bddee6
|
[
"MIT"
] | 9
|
2020-07-17T05:28:52.000Z
|
2022-03-03T18:26:12.000Z
|
anno/LabelDefinition.cpp
|
urobots-io/anno
|
8e240185e6fc0908687b15a39c892814a6bddee6
|
[
"MIT"
] | null | null | null |
anno/LabelDefinition.cpp
|
urobots-io/anno
|
8e240185e6fc0908687b15a39c892814a6bddee6
|
[
"MIT"
] | null | null | null |
// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++, C#, and Java: http://www.viva64.com
//
// Anno Labeling Tool
// 2020-2021 (c) urobots GmbH, https://urobots.io
#include "LabelDefinition.h"
#include "FileModel.h"
#include "PropertyDatabase.h"
#include <QRegularExpression>
using namespace std;
LabelDefinition::LabelDefinition(LabelType type, QObject *parent)
: QObject(parent)
, value_type(type) {
}
LabelDefinition::~LabelDefinition() {
}
std::shared_ptr<LabelCategory> LabelDefinition::CreateCategory(std::shared_ptr<LabelDefinition> definition, int value, const QString & name, const QColor & color) {
auto cat = shared_ptr<LabelCategory>(new LabelCategory(definition, value, name, color));
definition->categories.push_back(cat);
return cat;
}
std::shared_ptr<LabelCategory> LabelDefinition::GetCategory(int value) const {
for (auto c : categories) {
if (c->get_value() == value) {
return c;
}
}
return {};
}
void LabelDefinition::set_rendering_script(const QString script) {
rendering_script_ = script;
emit Changed();
}
void LabelDefinition::set_description(const QString description) {
description_ = description;
emit Changed();
}
void LabelDefinition::ConnectProperty(LabelProperty& prop, const std::string & name, bool inject_my_value) const {
auto it = shared_properties.find(name);
if (it != shared_properties.end()) {
prop.Connect(it->second, inject_my_value);
}
else {
prop.Disconnect();
}
}
double LabelDefinition::GetSharedPropertyValue(const std::string & name, double default_value) const {
auto it = shared_properties.find(name);
if (it != shared_properties.end()) {
auto def = it->second;
auto db_value = PropertyDatabase::Instance().GetCurrentValue(def->name, default_value);
return def->FromDatabaseValue(db_value);
}
return default_value;
}
set<int> LabelDefinition::GetMissingIndexes(const set<int>& existing_indexes) const {
set<int> result;
for (int i = 0; i < int(shared_labels.size()); ++i) {
if (!existing_indexes.count(i)) {
result.insert(i);
}
}
return result;
}
bool LabelDefinition::AllowedForFile(FileModel* file, int shared_index) const {
if (!file) {
return false;
}
if (!filename_filter.size()) {
return true;
}
auto filename = file->get_id();
if (shared_index < 0) {
for (int i = 0; i < int(filename_filter.size()); ++i) {
if (AllowedForFilename(filename, i)) {
return true;
}
}
return false;
}
else {
return AllowedForFilename(filename, shared_index);
}
}
bool LabelDefinition::AllowedForFilename(QString filename, int shared_index) const {
int index = min<int>(shared_index, int(filename_filter.size()) - 1);
QRegularExpression re(filename_filter[index].c_str());
QRegularExpressionMatch match = re.match(filename);
return match.hasMatch();
}
| 29.311321
| 164
| 0.668491
|
urobots-io
|
7774424b3dae089ee08c67ae44dfe55abf728814
| 8,539
|
cc
|
C++
|
fib.cc
|
yhirose/fiblang
|
af5b9dec8831e85119b214249942217e13877397
|
[
"MIT"
] | null | null | null |
fib.cc
|
yhirose/fiblang
|
af5b9dec8831e85119b214249942217e13877397
|
[
"MIT"
] | null | null | null |
fib.cc
|
yhirose/fiblang
|
af5b9dec8831e85119b214249942217e13877397
|
[
"MIT"
] | null | null | null |
//
// FibLang
// A Programming Language just for writing Fibonacci number program. :)
//
// Copyright (c) 2021 Yuji Hirose. All rights reserved. MIT License
// MIT License
//
#include <fstream>
#include <variant>
#include "peglib.h"
using namespace std;
using namespace peg;
using namespace peg::udl;
//-----------------------------------------------------------------------------
// Parser
//-----------------------------------------------------------------------------
shared_ptr<Ast> parse(const string& source, ostream& out) {
parser pg(R"(
# Syntax
START ← STATEMENTS
STATEMENTS ← (DEFINITION / EXPRESSION)*
DEFINITION ← 'def' Identifier '(' Identifier ')' EXPRESSION
EXPRESSION ← TERNARY
TERNARY ← CONDITION ('?' EXPRESSION ':' EXPRESSION)?
CONDITION ← INFIX (ConditionOperator INFIX)?
INFIX ← CALL (InfixOperator CALL)*
CALL ← PRIMARY ('(' EXPRESSION ')')?
PRIMARY ← FOR / Identifier / '(' EXPRESSION ')' / Number
FOR ← 'for' Identifier 'from' Number 'to' Number EXPRESSION
# Token
ConditionOperator ← '<'
InfixOperator ← '+' / '-'
Identifier ← !Keyword < [a-zA-Z][a-zA-Z0-9_]* >
Number ← < [0-9]+ >
Keyword ← 'def' / 'for' / 'from' / 'to'
%whitespace ← [ \t\r\n]*
%word ← [a-zA-Z]
)");
pg.log = [&](size_t ln, size_t col, const string& msg) {
out << ln << ":" << col << ": " << msg << endl;
};
pg.enable_ast();
shared_ptr<Ast> ast;
if (pg.parse(source, ast)) {
return AstOptimizer(true).optimize(ast);
}
return nullptr;
}
//-----------------------------------------------------------------------------
// Value
//-----------------------------------------------------------------------------
struct Value;
struct Environment;
struct Function {
string_view param;
function<Value(shared_ptr<Environment> env)> eval;
Function(string_view param,
function<Value(shared_ptr<Environment> env)>&& eval)
: param(param), eval(eval) {}
};
struct Value {
enum class Type { Nil, Bool, Long, Function };
Type type;
any v;
//variant<nullptr_t, bool, long, string_view, Function> v;
// Constructor
Value() : type(Type::Nil) {}
explicit Value(bool b) : type(Type::Bool), v(b) {}
explicit Value(long l) : type(Type::Long), v(l) {}
explicit Value(Function&& f) : type(Type::Function), v(f) {}
// Cast value
bool to_bool() const {
switch (type) {
case Type::Bool:
return any_cast<bool>(v);
case Type::Long:
return any_cast<long>(v) != 0;
default:
throw runtime_error("type error.");
}
}
long to_long() const {
switch (type) {
case Type::Long:
return any_cast<long>(v);
default:
throw runtime_error("type error.");
}
}
Function to_function() const {
switch (type) {
case Type::Function:
return any_cast<Function>(v);
default:
throw runtime_error("type error.");
}
}
// Comparison
bool operator<(const Value& rhs) const {
switch (type) {
case Type::Nil:
return false;
case Type::Bool:
return to_bool() < rhs.to_bool();
case Type::Long:
return to_long() < rhs.to_long();
default:
throw logic_error("invalid internal condition.");
}
// NOTREACHED
}
// String representation
string str() const {
switch (type) {
case Type::Nil:
return "nil";
case Type::Bool:
return to_bool() ? "true" : "false";
case Type::Long:
return std::to_string(to_long());
case Type::Function:
return "[function]";
default:
throw logic_error("invalid internal condition.");
}
}
};
//-----------------------------------------------------------------------------
// Environment
//-----------------------------------------------------------------------------
struct Environment {
shared_ptr<Environment> outer;
map<string_view, Value> values;
Environment(shared_ptr<Environment> outer = nullptr) : outer(outer) {}
const Value& get_value(string_view s) const {
if (values.find(s) != values.end()) {
return values.at(s);
} else if (outer) {
return outer->get_value(s);
}
throw runtime_error("undefined variable '" + string(s) + "'...");
}
void set_value(string_view s, Value&& val) { values.emplace(s, val); }
static shared_ptr<Environment> make_with_builtins() {
auto env = make_shared<Environment>();
env->set_value("puts"sv,
Value(Function("arg", [](shared_ptr<Environment> env) {
cout << env->get_value("arg").str() << endl;
return Value();
})));
return env;
}
};
//-----------------------------------------------------------------------------
// Interpreter
//-----------------------------------------------------------------------------
Value eval(const Ast& ast, shared_ptr<Environment> env) {
switch (ast.tag) {
// Rules
case "STATEMENTS"_: {
// (DEFINITION / EXPRESSION)*
if (!ast.nodes.empty()) {
auto it = ast.nodes.begin();
while (it != ast.nodes.end() - 1) {
eval(**it, env);
++it;
}
return eval(**it, env);
}
return Value();
}
case "DEFINITION"_: {
// 'def' Identifier '(' Identifier ')' EXPRESSION
auto name = ast.nodes[0]->token;
auto param = ast.nodes[1]->token;
auto body = ast.nodes[2];
env->set_value(
name, Value(Function(param, [=](shared_ptr<Environment> callEnv) {
return eval(*body, callEnv);
})));
return Value();
}
case "TERNARY"_: {
// CONDITION ('?' EXPRESSION ':' EXPRESSION)?
auto cond = eval(*ast.nodes[0], env).to_bool();
auto idx = cond ? 1 : 2;
return eval(*ast.nodes[idx], env);
}
case "CONDITION"_: {
// INFIX (ConditionOperator INFIX)?
auto lhs = eval(*ast.nodes[0], env);
auto rhs = eval(*ast.nodes[2], env);
auto ret = lhs < rhs;
return Value(ret);
}
case "INFIX"_: {
// CALL (InfixOperator CALL)*
auto l = eval(*ast.nodes[0], env).to_long();
for (size_t i = 1; i < ast.nodes.size(); i += 2) {
auto o = ast.nodes[i]->token;
auto r = eval(*ast.nodes[i + 1], env).to_long();
if (o == "+") {
l += r;
} else if (o == "-") {
l -= r;
}
}
return Value(l);
}
case "CALL"_: {
// PRIMARY ('(' EXPRESSION ')')?
auto name = ast.nodes[0]->token;
auto fn = env->get_value(name).to_function();
auto val = eval(*ast.nodes[1], env);
auto callEnv = make_shared<Environment>(env);
callEnv->set_value(fn.param, move(val));
try {
return fn.eval(callEnv);
} catch (const Value& e) {
return e;
}
}
case "FOR"_: {
// 'for' Identifier 'from' Number 'to' Number EXPRESSION
auto ident = ast.nodes[0]->token;
auto from = eval(*ast.nodes[1], env).to_long();
auto to = eval(*ast.nodes[2], env).to_long();
auto& expr = *ast.nodes[3];
for (auto i = from; i <= to; i++) {
auto call_env = make_shared<Environment>(env);
call_env->set_value(ident, Value(i));
eval(expr, call_env);
}
return Value();
}
// Tokens
case "Identifier"_: {
// !Keyword < [a-zA-Z][a-zA-Z0-9_]* >
return Value(env->get_value(ast.token));
}
case "Number"_: {
// < [0-9]+ >
return Value(ast.token_to_number<long>());
}
}
return Value();
}
//-----------------------------------------------------------------------------
// main
//-----------------------------------------------------------------------------
int main(int argc, const char** argv) {
if (argc < 2) {
cerr << "usage: fib [source file path]" << endl;
return -1;
}
ifstream f{argv[1]};
if (!f) {
cerr << "can't open the source file." << endl;
return -2;
}
auto s = string(istreambuf_iterator<char>(f), istreambuf_iterator<char>());
try {
auto ast = parse(s, cerr);
if (!ast) {
return -3;
}
// cerr << ast_to_s(ast) << endl;
auto env = Environment::make_with_builtins();
eval(*ast, env);
} catch (const exception& e) {
cerr << e.what() << endl;
return -4;
}
return 0;
}
| 26.936909
| 79
| 0.494437
|
yhirose
|
77759896e92425900c15df9621f476c1f3859cfb
| 10,769
|
hpp
|
C++
|
include/util/sorted.hpp
|
sourcechris/util
|
79f190df7b42130e28dfd8ac830241144c1b5fe7
|
[
"MIT"
] | null | null | null |
include/util/sorted.hpp
|
sourcechris/util
|
79f190df7b42130e28dfd8ac830241144c1b5fe7
|
[
"MIT"
] | null | null | null |
include/util/sorted.hpp
|
sourcechris/util
|
79f190df7b42130e28dfd8ac830241144c1b5fe7
|
[
"MIT"
] | 1
|
2021-06-07T20:41:23.000Z
|
2021-06-07T20:41:23.000Z
|
// SPDX-FileCopyrightText: 2021 Christian Göhring <mostsig@gmail.com>
// SPDX-License-Identifier: MIT
#ifndef THAT_THIS_UTIL_SORTED_HEADER_IS_ALREADY_INCLUDED
#define THAT_THIS_UTIL_SORTED_HEADER_IS_ALREADY_INCLUDED
#include <algorithm>
#include <array>
#include <forward_list>
#include <functional>
#include <list>
#include <memory>
#include <vector>
#ifdef UTIL_ASSERT
#include <util/assert.hpp>
#endif
namespace util {
/**
* A container of elements that are kept sorted.
*
* @snippet test/sorted.test.cpp sorted_ctor_ilist
* @tparam Container the type of container to keep sorted
* @tparam Compare A comparison function object which returns true if the first argument is less
* than (i.e. is ordered before) the second. The type must meet the requirements of Compare.
*/
template <class Container, class Compare = std::less<typename Container::value_type>>
class sorted {
public:
using value_type = typename Container::value_type;
using size_type = typename Container::size_type;
using const_reference = const value_type&;
using const_pointer = const value_type*;
using const_iterator = typename Container::const_iterator;
using is_forward_list =
std::is_same<Container, std::forward_list<value_type, typename Container::allocator_type>>;
using is_list =
std::is_same<Container, std::list<value_type, typename Container::allocator_type>>;
sorted() noexcept = default;
~sorted() = default;
sorted(const sorted&) = default;
sorted(sorted&&) noexcept = default;
auto operator=(const sorted&) -> sorted& = default;
auto operator=(sorted&&) noexcept -> sorted& = default;
template <class OtherContainer>
explicit sorted(const OtherContainer& container);
template <class InputIt>
sorted(InputIt begin, InputIt end);
sorted(std::initializer_list<value_type> ilist);
// element access
auto at(size_type pos) const -> const_reference;
auto operator[](size_type pos) const -> const_reference;
auto front() const -> const_reference;
auto back() const -> const_reference;
auto data() const noexcept -> const_pointer;
// iterators
auto begin() const noexcept -> const_iterator;
auto cbegin() const noexcept -> const_iterator;
auto end() const noexcept -> const_iterator;
auto cend() const noexcept -> const_iterator;
// capacity and size
auto empty() const noexcept -> bool;
auto size() const noexcept -> size_type;
auto max_size() const noexcept -> size_type;
auto capacity() const noexcept -> size_type;
void reserve(size_type new_cap);
void shrink_to_fit();
void resize(size_type count);
void resize(size_type count, const_reference value);
// modifiers
void clear() noexcept;
auto insert(const_reference value) -> const_iterator;
auto insert(value_type&& value) -> const_iterator;
auto insert(std::initializer_list<value_type> ilist) -> const_iterator;
template <class InputIt>
void insert(InputIt first, InputIt last);
template <class... Args>
auto emplace(Args&&... args) -> const_iterator;
auto erase(const_iterator pos) -> const_iterator;
auto erase(const_iterator first, const_iterator last) -> const_iterator;
void pop_back();
void pop_front();
void swap(sorted& other);
private:
Compare comp = Compare();
Container container;
};
template <class T, class Allocator = std::allocator<T>>
using sorted_forward_list = sorted<std::forward_list<T, Allocator>>;
template <class T, class Allocator = std::allocator<T>>
using sorted_list = sorted<std::list<T, Allocator>>;
template <class T, class Allocator = std::allocator<T>>
using sorted_vector = sorted<std::vector<T, Allocator>>;
/**
* Constructs a sorted container from a given container of elements.
*
* @snippet test/sorted.test.cpp sorted_ctor_container
* @tparam OtherContainer the type of the container to insert, can be the same as the underlying
* container of this sorted container
* @param container the container of elements to insert, must have begin() and end() methods
* returning input iterators
*/
template <class Container, class Compare>
template <class OtherContainer>
sorted<Container, Compare>::sorted(const OtherContainer& container)
: sorted(container.begin(), container.end()) {}
/**
* Constructs a sorted container from a given range of elements to insert.
*
* @snippet test/sorted.test.cpp sorted_ctor_iter
* @tparam InputIt the type of the input iterator
* @param begin the beginning iterator of the range of elements to insert
* @param end the iterator of the element one position after the last element
*/
template <class Container, class Compare>
template <class InputIt>
sorted<Container, Compare>::sorted(InputIt begin, InputIt end) {
if constexpr (is_forward_list::value) {
container.assign(begin, end);
container.sort(comp);
} else {
for (; begin != end; ++begin) {
container.insert(std::lower_bound(container.begin(), container.end(), *begin, comp),
*begin);
}
}
}
/**
* Constructs a sorted container from a given initializer list.
*
* @snippet test/sorted.test.cpp sorted_ctor_ilist
* @param ilist the list of elements to initalize the sorted container with
*/
template <class Container, class Compare>
sorted<Container, Compare>::sorted(std::initializer_list<value_type> ilist)
: sorted(std::begin(ilist), std::end(ilist)) {}
/**
* Returns a const reference to an element at the requested position with boundary checking.
*
* @snippet test/sorted.test.cpp sorted_at
* @param pos the position of the element to return
* @throw out_of_range if pos >= size()
* @return a const reference to the element at the requested position
*/
template <class Container, class Compare>
auto sorted<Container, Compare>::at(size_type pos) const -> const_reference {
if (pos >= size()) {
throw std::out_of_range{"pos is out of range"};
}
if constexpr (is_forward_list::value || is_list::value) {
auto it = container.begin();
while (pos--) {
++it;
}
return *it;
} else {
return container.at(pos);
}
}
/**
* Returns a const reference to an element at the requested position without boundary checking.
* Undefined behaviour if accessing a position >= size().
*
* @snippet test/sorted.test.cpp sorted_operator_square_brackets
* @param pos the position of the element to return
* @return a const reference to the element at the requested position
*/
template <class Container, class Compare>
auto sorted<Container, Compare>::operator[](size_type pos) const -> const_reference {
#ifdef UTIL_ASSERT
util_assert(pos < size());
#endif // UTIL_ASSERT
if constexpr (is_forward_list::value || is_list::value) {
auto it = container.begin();
while (pos--) {
++it;
}
return *it;
} else {
return container.operator[](pos);
}
}
template <class Container, class Compare>
auto sorted<Container, Compare>::front() const -> const_reference {
return container.front();
}
template <class Container, class Compare>
auto sorted<Container, Compare>::back() const -> const_reference {
return container.back();
}
template <class Container, class Compare>
auto sorted<Container, Compare>::data() const noexcept -> const_pointer {
return container.data();
}
/**
* Returns the count of elements in this sorted container.
*
* @snippet test/sorted.test.cpp sorted_size
* @return the number of contained elements
*/
template <class Container, class Compare>
auto sorted<Container, Compare>::size() const noexcept -> size_type {
if constexpr (is_forward_list::value) {
size_type size = 0;
for (auto it = container.begin(), end = container.end(); it != end; ++it) {
++size;
}
return size;
} else {
return container.size();
}
}
/**
* Returns the current available allocated space for elements of this sorted container.
*
* @snippet test/sorted.test.cpp sorted_capacity
*/
template <class Container, class Compare>
auto sorted<Container, Compare>::capacity() const noexcept -> size_type {
if constexpr (is_forward_list::value || is_list::value) {
return container.max_size();
} else {
return container.capacity();
}
}
/**
* Clears all elements from this sorted container.
*
* Invalidates any references, pointers, or iterators referring to contained elements. Any
* past-the-end iterators are also invalidated, but leaves the capacity() of the container
* unchanged.
*
* @snippet test/sorted.test.cpp sorted_clear
*/
template <class Container, class Compare>
void sorted<Container, Compare>::clear() noexcept {
container.clear();
}
/**
* Inserts an element into the sorted container.
*
* In contrast to the normal container's insert method, this insert does not take an additional
* position parameter. The position is determined by the sorting algorithm. The method invalidates
* any references, pointers, or iterators referring to contained elements. Any past-the-end
* iterators are also invalidated.
*
* @snippet test/sorted.test.cpp sorted_insert
* @param value the element to insert
* @return a const iterator to the inserted element
*/
template <class Container, class Compare>
auto sorted<Container, Compare>::insert(const_reference value) -> const_iterator {
if constexpr (is_forward_list::value) {
container.push_back(value);
container.sort(comp);
} else {
return const_iterator(
container.insert(std::lower_bound(container.begin(), container.end()), value, comp));
}
}
/**
* @see sorted<Container, Compare>::insert(const_reference value) ->
* const_iterator
*/
template <class Container, class Compare>
auto sorted<Container, Compare>::insert(value_type&& value) -> const_iterator {
if constexpr (is_forward_list::value) {
auto it = container.begin();
if (comp(value, *it)) {
container.push_front(std::move(value));
return container.cbegin();
}
for (auto next = ++container.begin(), end = container.end(); next != end; ++next, ++it) {
if (comp(value, *next)) {
return const_iterator(container.insert_after(it, std::move(value)));
}
}
return const_iterator(container.insert_after(it, std::move(value)));
} else {
return const_iterator(container.insert(
std::lower_bound(container.begin(), container.end(), std::move(value), comp),
std::move(value)));
}
}
} // namespace util
#endif // THAT_THIS_UTIL_SORTED_HEADER_IS_ALREADY_INCLUDED
| 33.548287
| 99
| 0.694865
|
sourcechris
|
77769a710f836504bd6def77d5b409fba8c7f64e
| 3,628
|
cc
|
C++
|
src/DataOutput/RestartableObject.cc
|
jmikeowen/Spheral
|
3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4
|
[
"BSD-Source-Code",
"BSD-3-Clause-LBNL",
"FSFAP"
] | 22
|
2018-07-31T21:38:22.000Z
|
2020-06-29T08:58:33.000Z
|
src/DataOutput/RestartableObject.cc
|
markguozhiming/spheral
|
bbb982102e61edb8a1d00cf780bfa571835e1b61
|
[
"BSD-Source-Code",
"BSD-3-Clause-LBNL",
"FSFAP"
] | 41
|
2020-09-28T23:14:27.000Z
|
2022-03-28T17:01:33.000Z
|
src/DataOutput/RestartableObject.cc
|
markguozhiming/spheral
|
bbb982102e61edb8a1d00cf780bfa571835e1b61
|
[
"BSD-Source-Code",
"BSD-3-Clause-LBNL",
"FSFAP"
] | 7
|
2019-12-01T07:00:06.000Z
|
2020-09-15T21:12:39.000Z
|
//---------------------------------Spheral++----------------------------------//
// RestartableObject
// This is an object that handles registering it's descendents with the
// RestartRegistrar. The idea here is you just inherit from this bad boy,
// and blamo you're restartable.
// This is intended solely for use making Python objects play in our restart
// setup -- please use the C++ centric methods in registerWithRestart.hh
// for C++ restarting.
//
// Created by JMO, Thu May 28 17:47:48 PDT 2009
//----------------------------------------------------------------------------//
#include "RestartableObject.hh"
#include "FileIO/FileIO.hh"
// These types are defined in our pybindgen generated code.
#ifndef _PyBindGenWrapperFlags_defined_
#define _PyBindGenWrapperFlags_defined_
typedef enum _PyBindGenWrapperFlags {
PYBINDGEN_WRAPPER_FLAG_NONE = 0,
PYBINDGEN_WRAPPER_FLAG_OBJECT_NOT_OWNED = (1<<0),
} PyBindGenWrapperFlags;
#endif
typedef struct {
PyObject_HEAD
Spheral::FileIO *obj;
PyObject *inst_dict;
PyBindGenWrapperFlags flags:8;
} PySpheralFileIO;
extern PyTypeObject PySpheralFileIO_Type;
namespace Spheral {
//------------------------------------------------------------------------------
// Constructor.
//------------------------------------------------------------------------------
RestartableObject::
RestartableObject(PyObject* self,
const unsigned priority):
mRestart(registerWithRestart(*this, priority)),
mSelf(self) {
}
//------------------------------------------------------------------------------
// Destructor.
//------------------------------------------------------------------------------
RestartableObject::
~RestartableObject() {
}
//------------------------------------------------------------------------------
// label
//------------------------------------------------------------------------------
std::string
RestartableObject::
label() const {
PyObject* pylabel = PyObject_CallMethod(mSelf, (char*) "label", NULL);
VERIFY2(pylabel != NULL,
"RestartableObject::label ERROR: must provide label method.");
VERIFY2(PyString_Check(pylabel),
"RestartableObject::label ERROR: label method must return a string.");
std::string result = PyString_AsString(pylabel);
Py_DECREF(pylabel);
return result;
}
//------------------------------------------------------------------------------
// dumpState
//------------------------------------------------------------------------------
void
RestartableObject::
dumpState(FileIO& file, const std::string pathName) const {
PySpheralFileIO* py_file = PyObject_GC_New(PySpheralFileIO, &PySpheralFileIO_Type);
py_file->inst_dict = NULL;
py_file->obj = &file;
PyObject* result = PyObject_CallMethod(mSelf, (char*) "dumpState", (char*) "Os", py_file, pathName.c_str());
VERIFY2(result != NULL,
"RestartableObject::dumpState ERROR encountered calling python dumpState method.");
}
//------------------------------------------------------------------------------
// restoreState
//------------------------------------------------------------------------------
void
RestartableObject::
restoreState(const FileIO& file, const std::string pathName) {
PySpheralFileIO* py_file = PyObject_GC_New(PySpheralFileIO, &PySpheralFileIO_Type);
py_file->inst_dict = NULL;
py_file->obj = const_cast<FileIO*>(&file);
PyObject* result = PyObject_CallMethod(mSelf, (char*) "restoreState", (char*) "Os", py_file, pathName.c_str());
VERIFY2(result != NULL,
"RestartableObject::restoreState ERROR encountered calling python restoreState method.");
}
}
| 37.402062
| 113
| 0.54548
|
jmikeowen
|
77779a2674b18d0efd2901918439a4b0c7221463
| 992
|
cpp
|
C++
|
BZOJ/3111/std.cpp
|
sjj118/OI-Code
|
964ea6e799d14010f305c7e4aee269d860a781f7
|
[
"MIT"
] | null | null | null |
BZOJ/3111/std.cpp
|
sjj118/OI-Code
|
964ea6e799d14010f305c7e4aee269d860a781f7
|
[
"MIT"
] | null | null | null |
BZOJ/3111/std.cpp
|
sjj118/OI-Code
|
964ea6e799d14010f305c7e4aee269d860a781f7
|
[
"MIT"
] | null | null | null |
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <iostream>
using namespace std;
#define inf 1000000000
const int maxn=120;
int n,m,k,ans,a[maxn][maxn],f[maxn][25][maxn],g[maxn][25][maxn][2],s[maxn][maxn];
int main(){
scanf("%d%d%d",&n,&m,&k);
k=k*2+1;
for (int i=1;i<=n;i++)
for (int j=1;j<=m;j++)
scanf("%d",&a[i][j]),s[i][j]=s[i-1][j]+a[i][j];
for (int i=1;i<=k;i++)
for (int j=1;j<=n;j++)
f[0][i][j]=g[0][i][j][0]=g[0][i][j][1]=-inf;
ans=-inf;
for (int i=1;i<=n;i++)
for (int j=1;j<=m;j++){
for (int p=1;p<=k;p++){
for (int h=i;h;h--)
f[j][p][h]=max(f[j-1][p][h],g[j-1][p-1][h][p%2])+s[i][j]-s[h-1][j];
g[j][p][1][0]=-inf;
for (int h=2;h<=i;h++)
g[j][p][h][0]=max(g[j][p][h-1][0],f[j][p][h-1]);
g[j][p][i][1]=-inf;
for (int h=i-1;h;h--)
g[j][p][h][1]=max(g[j][p][h+1][1],f[j][p][h+1]);
}
ans=max(ans,max(f[j][k][i],g[j][k][i][0]));
}
printf("%d",ans);
return 0;
}
| 26.105263
| 81
| 0.454637
|
sjj118
|
777f0c84ed9b688e6f9a2134a0f4c50c334b8220
| 1,016
|
hpp
|
C++
|
program/kmeans.hpp
|
yk-tanigawa/201503_clustering
|
43a11e707c08f1576e5765824c74330b6730e7e9
|
[
"MIT"
] | null | null | null |
program/kmeans.hpp
|
yk-tanigawa/201503_clustering
|
43a11e707c08f1576e5765824c74330b6730e7e9
|
[
"MIT"
] | 2
|
2015-02-26T16:52:41.000Z
|
2015-02-26T16:53:14.000Z
|
program/kmeans.hpp
|
yk-tanigawa/201503_clustering
|
43a11e707c08f1576e5765824c74330b6730e7e9
|
[
"MIT"
] | null | null | null |
#ifndef _UBLAS_
#define _UBLAS_
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/matrix_proxy.hpp>
#include <boost/numeric/ublas/io.hpp>
#endif
#ifndef _KMEANS_
#define _KMEANS_
using namespace boost::numeric::ublas;
using namespace boost::numeric;
double dist_xc /* データ点xとクラスタ中心c_jとの距離 */
(const ublas::matrix_row<const ublas::matrix<double> > x,
const ublas::matrix<double> c,
const unsigned int j)
{
double sum = 0;
for(unsigned int d = 0; d < x.size(); ++d){
sum += (x[d] - c(j,d)) * (x[d] - c(j,d));
}
return sqrt(sum);
}
double dist_cc /* クラスタ中心間の距離を計算 */
(const ublas::matrix<double> mat1, const unsigned int r1,
const ublas::matrix<double> mat2, const unsigned int r2)
{
if(mat1.size2() != mat2.size2()){
return -1;
}else{
double sum = 0;
for(unsigned int i = 0; i < mat1.size2(); ++i){
sum += (mat1(r1, i) - mat2(r2, i)) * (mat1(r1, i) - mat2(r2, i));
}
return sqrt(sum);
}
}
#endif
| 22.577778
| 71
| 0.644685
|
yk-tanigawa
|
777f9906eb214b6b704e9155b88c1faa227fe0b3
| 6,493
|
cpp
|
C++
|
Code/IntroGame/DemoScreens/DemoScreenParticleActors.cpp
|
EvGamer/midspace
|
c16f39d7e59ff4bf51dff9de1a135ddf321e2f32
|
[
"BSD-3-Clause"
] | 171
|
2015-01-08T10:35:56.000Z
|
2021-07-03T12:35:10.000Z
|
Code/IntroGame/DemoScreens/DemoScreenParticleActors.cpp
|
EvGamer/midspace
|
c16f39d7e59ff4bf51dff9de1a135ddf321e2f32
|
[
"BSD-3-Clause"
] | 11
|
2015-01-30T05:30:54.000Z
|
2017-04-08T23:34:33.000Z
|
Code/IntroGame/DemoScreens/DemoScreenParticleActors.cpp
|
EvGamer/midspace
|
c16f39d7e59ff4bf51dff9de1a135ddf321e2f32
|
[
"BSD-3-Clause"
] | 59
|
2015-02-01T03:43:00.000Z
|
2020-12-01T02:08:57.000Z
|
//////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2008-2014, Shane Liesegang
// 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 copyright holder nor the names of any
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "DemoScreenParticleActors.h"
DemoScreenParticleActors::DemoScreenParticleActors()
{
_isActive = false;
}
void DemoScreenParticleActors::Start()
{
pa = new ParticleActor();
pa->SetColor(1.0f, 1.0f, 1.0f); //Sets the initial color of the particles.
// Since the image file we'll be using already
// has a color, we set this to pure white.
pa->SetSize(Vector2(0.2f, 0.2f)); //The size of each particle, in GL units
pa->SetSprite("Resources/Images/Test.png"); //The image file we want to use (otherwise
// it'll just be colored squares).
pa->SetMaxParticles(500); //The maximum number of particles this system will ever handle.
pa->SetParticlesPerSecond(100.0f); //Emission Rate
pa->SetParticleLifetime(1.5f); //How long each particles lasts before disappearing
pa->SetSpread(MathUtil::Pi); //The angle in radians at which particles will be emitted.
pa->SetEndScale(2.0f); //If you want the particles to change size over their lifetimes
pa->SetEndColor(Color(1.0f, 1.0f, 1.0f, 0.0f)); //Our particles disappear over time
pa->SetSpeedRange(3.0f, 4.0f); //The minimum and maximum range of speeds (so you can have
// some variation).
pa->SetGravity(Vector2::Zero); //You can pull the particles in a particular direction (default is
// downwards, so zero it out if you need to).
theWorld.Add(pa);
_isActive = true; //lets the mouse events know that they should care
//Demo housekeeping below this point.
#pragma region Demo Housekeeping
t = new TextActor("Console", "Here's a ParticleActor. (Try moving and clicking the mouse!)");
t->SetPosition(0, 3.5);
t->SetAlignment(TXT_Center);
theWorld.Add(t);
t2 = new TextActor("Console", "Press [B] to change its properties.");
t2->SetPosition(0, 2.5);
t2->SetAlignment(TXT_Center);
theWorld.Add(t2);
TextActor *fileLoc = new TextActor("ConsoleSmall", "DemoScreenParticleActors.cpp");
fileLoc->SetPosition(MathUtil::ScreenToWorld(5, 763));
fileLoc->SetColor(.3f, .3f, .3f);
theWorld.Add(fileLoc);
_objects.push_back(fileLoc);
_objects.push_back(t);
_objects.push_back(t2);
_objects.push_back(pa);
#pragma endregion
}
void DemoScreenParticleActors::Update(float dt)
{
//This is the same kind of input processing we did in DemoScreenSimpleActor.cpp,
// but here we're playing with various properties of the particles.
if ((theController.IsConnected() && theController.IsBButtonDown()) || theInput.IsKeyDown('b'))
{
pa->SetColor(1.0f, 0.0f, 0.0f, .25f);
pa->SetSize(0.5f, 0.5f);
pa->SetGravity( Vector2::Zero );
pa->ClearSpriteInfo();
t->SetDisplayString("Now it's red and translucent. Press [Y].");
t2->SetDisplayString("");
}
if ((theController.IsConnected() && theController.IsYButtonDown()) || theInput.IsKeyDown('y'))
{
pa->SetColor(0,0,1,1);
pa->SetSize(0.5f, 0.5f);
Vector2 grav = Vector2(0.0f, -8.0f);
pa->SetGravity( grav );
pa->ClearSpriteInfo();
t->SetDisplayString("Now it's blue and has density. Press [X] for the coolest thing ever.");
t2->SetDisplayString("");
}
if ((theController.IsConnected() && theController.IsXButtonDown()) || theInput.IsKeyDown('x'))
{
pa->SetSize(4.0f, 4.0f);
pa->SetColor(1,1,1,1);
pa->SetGravity( Vector2::Zero );
pa->LoadSpriteFrames("Resources/Images/numbers/angel_01.png");
pa->PlaySpriteAnimation(0.5f, SAT_Loop, 0, 4);
t->SetDisplayString("That's right, animated textures. You love it.");
t2->SetDisplayString("");
}
}
void DemoScreenParticleActors::MouseMotionEvent(Vec2i screenCoordinates)
{
if (_isActive) //we only want to move around if this screen is currently active
{
pa->SetPosition(MathUtil::ScreenToWorld(screenCoordinates.X, screenCoordinates.Y));
}
}
void DemoScreenParticleActors::MouseDownEvent(Vec2i screenCoordinates, MouseButtonInput button)
{
if (_isActive)
{
// Create the particle actor via the Actor Definition system
ParticleActor *oneOff = (ParticleActor*)Actor::Create("particle_demo");
if (oneOff)
{
// Note we can still change properties of actors loaded as definitions
oneOff->SetColor(0, 0, 1);
oneOff->SetSprite("Resources/Images/triangle.png");
//We can set the position to where the mouse click happened.
oneOff->SetPosition(MathUtil::ScreenToWorld(screenCoordinates.X, screenCoordinates.Y));
//The system will remove itself from the world and deallocate its memory
// when the lifetime ends. (If it's 0.0, it's assumed to be infinite.)
oneOff->SetSystemLifetime(1.0f);
//Make sure to add it to the world!
theWorld.Add(oneOff);
}
}
}
void DemoScreenParticleActors::Stop()
{
DemoScreen::Stop();
// Now that DemoScreen cleaned up...
_isActive = false;
}
| 40.836478
| 98
| 0.703527
|
EvGamer
|
7783b630dbb68c531fc4febda0b67d0ef4e4fa65
| 23
|
cpp
|
C++
|
src/boardgame/move_list.cpp
|
edersasch/boardgames
|
48c24e6796d46e106723551688d2bb1c7d6aac36
|
[
"MIT"
] | 4
|
2019-04-17T09:19:31.000Z
|
2020-12-30T04:11:08.000Z
|
src/boardgame/move_list.cpp
|
edersasch/boardgames
|
48c24e6796d46e106723551688d2bb1c7d6aac36
|
[
"MIT"
] | 1
|
2019-04-16T20:04:01.000Z
|
2019-04-16T20:04:01.000Z
|
src/boardgame/move_list.cpp
|
edersasch/boardgames
|
48c24e6796d46e106723551688d2bb1c7d6aac36
|
[
"MIT"
] | 1
|
2019-04-15T09:21:01.000Z
|
2019-04-15T09:21:01.000Z
|
#include "move_list.h"
| 11.5
| 22
| 0.73913
|
edersasch
|
77848e1270c78f4820e603c71016029de5f4304e
| 1,544
|
hpp
|
C++
|
Sockets/Base/MSSocket.hpp
|
MihaelShevchuk/MSSocketLibrary
|
6ec75fea90221026a5a5ec302b56b93b83bfbf01
|
[
"BSD-2-Clause"
] | null | null | null |
Sockets/Base/MSSocket.hpp
|
MihaelShevchuk/MSSocketLibrary
|
6ec75fea90221026a5a5ec302b56b93b83bfbf01
|
[
"BSD-2-Clause"
] | null | null | null |
Sockets/Base/MSSocket.hpp
|
MihaelShevchuk/MSSocketLibrary
|
6ec75fea90221026a5a5ec302b56b93b83bfbf01
|
[
"BSD-2-Clause"
] | null | null | null |
//
// MSSocket.hpp
// MSSocketLibrary
//
// Created by Mihail Shevchuk on 15.01.18.
// Copyright © 2018 Mihail Shevchuk. All rights reserved.
//
#ifndef MSSocket_hpp
#define MSSocket_hpp
#include "MSErrorManager.hpp"
class MSSocket {
public:
MSSocket(MSEventType type, pChar ip, uint32_t port, uint32_t sizeBuffer);
MSSocket(MSEventType type, pChar serverPath, uint32_t sizeBuffer);
virtual ~MSSocket();
void SetReceiveMessageCallback(pFuncCallBack callback, pVoid manager) {
mReceiveMessageCallback = callback;
mReceiveMessageManager = manager;
}
void SetGenerateEventCallback(pFuncThrowEvent callback, pVoid manager) {
mGenerateEventCallback = callback;
mEventManager = manager;
}
virtual bool Connect();
bool Disconnect();
bool SendMessage(pVoid message, size_t size);
protected:
pVoid mReceiveMessageManager;
pVoid mEventManager;
pFuncCallBack mReceiveMessageCallback;
pFuncThrowEvent mGenerateEventCallback;
pChar mIp;
pChar mServerPath;
uint32_t mPort;
MSEventType mType;
int mSocketId;
void CreateReadDataThread();
void GenerateEvent(MSEvent event);
virtual void CreateSocket();
private:
uint32_t mSizeForRead;
pthread_t mReadDataThread;
pChar mReadDataBuffer;
void ReadData();
static void *ThreadBridge(pVoid object) {
MSSocket *socket = static_cast<MSSocket*>(object);
socket->ReadData();
return 0;
}
};
#endif /* MSSocket_hpp */
| 24.125
| 77
| 0.696891
|
MihaelShevchuk
|
7784b18f9934a659e614743e3a40f4325807d468
| 1,250
|
cc
|
C++
|
src/twpipe/ensemble.cc
|
hjian42/twpipe
|
d18e4a507f110a0d006aebc2f46553bd28c81db7
|
[
"MIT"
] | 31
|
2018-04-13T14:52:24.000Z
|
2021-08-02T07:13:07.000Z
|
src/twpipe/ensemble.cc
|
hjian42/twpipe
|
d18e4a507f110a0d006aebc2f46553bd28c81db7
|
[
"MIT"
] | 8
|
2018-07-05T01:58:20.000Z
|
2019-08-09T06:07:27.000Z
|
src/twpipe/ensemble.cc
|
hjian42/twpipe
|
d18e4a507f110a0d006aebc2f46553bd28c81db7
|
[
"MIT"
] | 6
|
2018-07-04T17:57:29.000Z
|
2022-01-15T17:47:50.000Z
|
#include "ensemble.h"
#include "json.hpp"
#include <iostream>
#include <fstream>
namespace twpipe {
const char* EnsembleInstance::id_name = "id";
const char* EnsembleInstance::category_name = "category";
const char* EnsembleInstance::prob_name = "prob";
EnsembleInstance::EnsembleInstance(unsigned id,
std::vector<unsigned>& categories,
std::vector<std::vector<float>>& probs) :
id(id),
categories(categories),
probs(probs) {
}
void EnsembleUtils::load_ensemble_instances(const std::string & path,
EnsembleInstances & instances) {
nlohmann::json payload;
std::ifstream ifs(path);
std::string buffer;
while (std::getline(ifs, buffer)) {
payload = nlohmann::json::parse(buffer.begin(), buffer.end());
unsigned id = payload.at(EnsembleInstance::id_name).get<unsigned>();
std::vector<unsigned> actions = payload.at(EnsembleInstance::category_name).get<std::vector<unsigned>>();
std::vector<std::vector<float>> probs = payload.at(EnsembleInstance::prob_name).get<std::vector<std::vector<float>>>();
instances.push_back(EnsembleInstance(id, actions, probs));
}
}
}
| 34.722222
| 124
| 0.6384
|
hjian42
|
77859fe085a63f10c2f76cd33b11a2609e04f5af
| 429
|
hh
|
C++
|
succosim/include/Analysis.hh
|
mattiasoldani/succosim_22_desy_preshower
|
d326bee8875c8f85b3730e20e9257b722a8f5313
|
[
"MIT"
] | null | null | null |
succosim/include/Analysis.hh
|
mattiasoldani/succosim_22_desy_preshower
|
d326bee8875c8f85b3730e20e9257b722a8f5313
|
[
"MIT"
] | null | null | null |
succosim/include/Analysis.hh
|
mattiasoldani/succosim_22_desy_preshower
|
d326bee8875c8f85b3730e20e9257b722a8f5313
|
[
"MIT"
] | null | null | null |
#ifndef ANALYSIS_HH
#define ANALYSIS_HH
using namespace std;
// header for all the analysis & data output stuff
// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
// select the output data file format here by including the proper header (only 1 at a time)
// note: CSV format does not support custom file path & name
// #include <g4csv.hh>
#include <g4root.hh>
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#endif
| 26.8125
| 92
| 0.67366
|
mattiasoldani
|
7787f43ff6163a0a9e65ed62ef42ee749fa5a99b
| 50,404
|
cpp
|
C++
|
vm/external_libs/llvm/lib/Target/ARM/ARMRegisterInfo.cpp
|
marnen/rubinius
|
05b3f9789d01bada0604a7f09921c956bc9487e7
|
[
"BSD-3-Clause"
] | 1
|
2016-05-08T16:58:14.000Z
|
2016-05-08T16:58:14.000Z
|
vm/external_libs/llvm/lib/Target/ARM/ARMRegisterInfo.cpp
|
taf2/rubinius
|
493bfa2351fc509ca33d3bb03991c2e9c2b6dafa
|
[
"BSD-3-Clause"
] | null | null | null |
vm/external_libs/llvm/lib/Target/ARM/ARMRegisterInfo.cpp
|
taf2/rubinius
|
493bfa2351fc509ca33d3bb03991c2e9c2b6dafa
|
[
"BSD-3-Clause"
] | null | null | null |
//===- ARMRegisterInfo.cpp - ARM Register Information -----------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the ARM implementation of the TargetRegisterInfo class.
//
//===----------------------------------------------------------------------===//
#include "ARM.h"
#include "ARMAddressingModes.h"
#include "ARMInstrInfo.h"
#include "ARMMachineFunctionInfo.h"
#include "ARMRegisterInfo.h"
#include "ARMSubtarget.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/CodeGen/MachineConstantPool.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineLocation.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/RegisterScavenging.h"
#include "llvm/Target/TargetFrameInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/ADT/BitVector.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Support/CommandLine.h"
#include <algorithm>
using namespace llvm;
static cl::opt<bool> ThumbRegScavenging("enable-thumb-reg-scavenging",
cl::Hidden,
cl::desc("Enable register scavenging on Thumb"));
unsigned ARMRegisterInfo::getRegisterNumbering(unsigned RegEnum) {
using namespace ARM;
switch (RegEnum) {
case R0: case S0: case D0: return 0;
case R1: case S1: case D1: return 1;
case R2: case S2: case D2: return 2;
case R3: case S3: case D3: return 3;
case R4: case S4: case D4: return 4;
case R5: case S5: case D5: return 5;
case R6: case S6: case D6: return 6;
case R7: case S7: case D7: return 7;
case R8: case S8: case D8: return 8;
case R9: case S9: case D9: return 9;
case R10: case S10: case D10: return 10;
case R11: case S11: case D11: return 11;
case R12: case S12: case D12: return 12;
case SP: case S13: case D13: return 13;
case LR: case S14: case D14: return 14;
case PC: case S15: case D15: return 15;
case S16: return 16;
case S17: return 17;
case S18: return 18;
case S19: return 19;
case S20: return 20;
case S21: return 21;
case S22: return 22;
case S23: return 23;
case S24: return 24;
case S25: return 25;
case S26: return 26;
case S27: return 27;
case S28: return 28;
case S29: return 29;
case S30: return 30;
case S31: return 31;
default:
assert(0 && "Unknown ARM register!");
abort();
}
}
ARMRegisterInfo::ARMRegisterInfo(const TargetInstrInfo &tii,
const ARMSubtarget &sti)
: ARMGenRegisterInfo(ARM::ADJCALLSTACKDOWN, ARM::ADJCALLSTACKUP),
TII(tii), STI(sti),
FramePtr((STI.useThumbBacktraces() || STI.isThumb()) ? ARM::R7 : ARM::R11) {
}
static inline
const MachineInstrBuilder &AddDefaultPred(const MachineInstrBuilder &MIB) {
return MIB.addImm((int64_t)ARMCC::AL).addReg(0);
}
static inline
const MachineInstrBuilder &AddDefaultCC(const MachineInstrBuilder &MIB) {
return MIB.addReg(0);
}
/// emitLoadConstPool - Emits a load from constpool to materialize the
/// specified immediate.
void ARMRegisterInfo::emitLoadConstPool(MachineBasicBlock &MBB,
MachineBasicBlock::iterator &MBBI,
unsigned DestReg, int Val,
unsigned Pred, unsigned PredReg,
const TargetInstrInfo *TII,
bool isThumb) const {
MachineFunction &MF = *MBB.getParent();
MachineConstantPool *ConstantPool = MF.getConstantPool();
Constant *C = ConstantInt::get(Type::Int32Ty, Val);
unsigned Idx = ConstantPool->getConstantPoolIndex(C, 2);
if (isThumb)
BuildMI(MBB, MBBI, TII->get(ARM::tLDRcp),DestReg).addConstantPoolIndex(Idx);
else
BuildMI(MBB, MBBI, TII->get(ARM::LDRcp), DestReg).addConstantPoolIndex(Idx)
.addReg(0).addImm(0).addImm(Pred).addReg(PredReg);
}
/// isLowRegister - Returns true if the register is low register r0-r7.
///
bool ARMRegisterInfo::isLowRegister(unsigned Reg) const {
using namespace ARM;
switch (Reg) {
case R0: case R1: case R2: case R3:
case R4: case R5: case R6: case R7:
return true;
default:
return false;
}
}
const unsigned*
ARMRegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const {
static const unsigned CalleeSavedRegs[] = {
ARM::LR, ARM::R11, ARM::R10, ARM::R9, ARM::R8,
ARM::R7, ARM::R6, ARM::R5, ARM::R4,
ARM::D15, ARM::D14, ARM::D13, ARM::D12,
ARM::D11, ARM::D10, ARM::D9, ARM::D8,
0
};
static const unsigned DarwinCalleeSavedRegs[] = {
ARM::LR, ARM::R7, ARM::R6, ARM::R5, ARM::R4,
ARM::R11, ARM::R10, ARM::R9, ARM::R8,
ARM::D15, ARM::D14, ARM::D13, ARM::D12,
ARM::D11, ARM::D10, ARM::D9, ARM::D8,
0
};
return STI.isTargetDarwin() ? DarwinCalleeSavedRegs : CalleeSavedRegs;
}
const TargetRegisterClass* const *
ARMRegisterInfo::getCalleeSavedRegClasses(const MachineFunction *MF) const {
static const TargetRegisterClass * const CalleeSavedRegClasses[] = {
&ARM::GPRRegClass, &ARM::GPRRegClass, &ARM::GPRRegClass,
&ARM::GPRRegClass, &ARM::GPRRegClass, &ARM::GPRRegClass,
&ARM::GPRRegClass, &ARM::GPRRegClass, &ARM::GPRRegClass,
&ARM::DPRRegClass, &ARM::DPRRegClass, &ARM::DPRRegClass, &ARM::DPRRegClass,
&ARM::DPRRegClass, &ARM::DPRRegClass, &ARM::DPRRegClass, &ARM::DPRRegClass,
0
};
return CalleeSavedRegClasses;
}
BitVector ARMRegisterInfo::getReservedRegs(const MachineFunction &MF) const {
// FIXME: avoid re-calculating this everytime.
BitVector Reserved(getNumRegs());
Reserved.set(ARM::SP);
Reserved.set(ARM::PC);
if (STI.isTargetDarwin() || hasFP(MF))
Reserved.set(FramePtr);
// Some targets reserve R9.
if (STI.isR9Reserved())
Reserved.set(ARM::R9);
return Reserved;
}
bool
ARMRegisterInfo::isReservedReg(const MachineFunction &MF, unsigned Reg) const {
switch (Reg) {
default: break;
case ARM::SP:
case ARM::PC:
return true;
case ARM::R7:
case ARM::R11:
if (FramePtr == Reg && (STI.isTargetDarwin() || hasFP(MF)))
return true;
break;
case ARM::R9:
return STI.isR9Reserved();
}
return false;
}
bool
ARMRegisterInfo::requiresRegisterScavenging(const MachineFunction &MF) const {
const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
return ThumbRegScavenging || !AFI->isThumbFunction();
}
/// hasFP - Return true if the specified function should have a dedicated frame
/// pointer register. This is true if the function has variable sized allocas
/// or if frame pointer elimination is disabled.
///
bool ARMRegisterInfo::hasFP(const MachineFunction &MF) const {
return NoFramePointerElim || MF.getFrameInfo()->hasVarSizedObjects();
}
// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
// not required, we reserve argument space for call sites in the function
// immediately on entry to the current function. This eliminates the need for
// add/sub sp brackets around call sites. Returns true if the call frame is
// included as part of the stack frame.
bool ARMRegisterInfo::hasReservedCallFrame(MachineFunction &MF) const {
const MachineFrameInfo *FFI = MF.getFrameInfo();
unsigned CFSize = FFI->getMaxCallFrameSize();
ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
// It's not always a good idea to include the call frame as part of the
// stack frame. ARM (especially Thumb) has small immediate offset to
// address the stack frame. So a large call frame can cause poor codegen
// and may even makes it impossible to scavenge a register.
if (AFI->isThumbFunction()) {
if (CFSize >= ((1 << 8) - 1) * 4 / 2) // Half of imm8 * 4
return false;
} else {
if (CFSize >= ((1 << 12) - 1) / 2) // Half of imm12
return false;
}
return !MF.getFrameInfo()->hasVarSizedObjects();
}
/// emitARMRegPlusImmediate - Emits a series of instructions to materialize
/// a destreg = basereg + immediate in ARM code.
static
void emitARMRegPlusImmediate(MachineBasicBlock &MBB,
MachineBasicBlock::iterator &MBBI,
unsigned DestReg, unsigned BaseReg, int NumBytes,
ARMCC::CondCodes Pred, unsigned PredReg,
const TargetInstrInfo &TII) {
bool isSub = NumBytes < 0;
if (isSub) NumBytes = -NumBytes;
while (NumBytes) {
unsigned RotAmt = ARM_AM::getSOImmValRotate(NumBytes);
unsigned ThisVal = NumBytes & ARM_AM::rotr32(0xFF, RotAmt);
assert(ThisVal && "Didn't extract field correctly");
// We will handle these bits from offset, clear them.
NumBytes &= ~ThisVal;
// Get the properly encoded SOImmVal field.
int SOImmVal = ARM_AM::getSOImmVal(ThisVal);
assert(SOImmVal != -1 && "Bit extraction didn't work?");
// Build the new ADD / SUB.
BuildMI(MBB, MBBI, TII.get(isSub ? ARM::SUBri : ARM::ADDri), DestReg)
.addReg(BaseReg, false, false, true).addImm(SOImmVal)
.addImm((unsigned)Pred).addReg(PredReg).addReg(0);
BaseReg = DestReg;
}
}
/// calcNumMI - Returns the number of instructions required to materialize
/// the specific add / sub r, c instruction.
static unsigned calcNumMI(int Opc, int ExtraOpc, unsigned Bytes,
unsigned NumBits, unsigned Scale) {
unsigned NumMIs = 0;
unsigned Chunk = ((1 << NumBits) - 1) * Scale;
if (Opc == ARM::tADDrSPi) {
unsigned ThisVal = (Bytes > Chunk) ? Chunk : Bytes;
Bytes -= ThisVal;
NumMIs++;
NumBits = 8;
Scale = 1; // Followed by a number of tADDi8.
Chunk = ((1 << NumBits) - 1) * Scale;
}
NumMIs += Bytes / Chunk;
if ((Bytes % Chunk) != 0)
NumMIs++;
if (ExtraOpc)
NumMIs++;
return NumMIs;
}
/// emitThumbRegPlusImmInReg - Emits a series of instructions to materialize
/// a destreg = basereg + immediate in Thumb code. Materialize the immediate
/// in a register using mov / mvn sequences or load the immediate from a
/// constpool entry.
static
void emitThumbRegPlusImmInReg(MachineBasicBlock &MBB,
MachineBasicBlock::iterator &MBBI,
unsigned DestReg, unsigned BaseReg,
int NumBytes, bool CanChangeCC,
const TargetInstrInfo &TII,
const ARMRegisterInfo& MRI) {
bool isHigh = !MRI.isLowRegister(DestReg) ||
(BaseReg != 0 && !MRI.isLowRegister(BaseReg));
bool isSub = false;
// Subtract doesn't have high register version. Load the negative value
// if either base or dest register is a high register. Also, if do not
// issue sub as part of the sequence if condition register is to be
// preserved.
if (NumBytes < 0 && !isHigh && CanChangeCC) {
isSub = true;
NumBytes = -NumBytes;
}
unsigned LdReg = DestReg;
if (DestReg == ARM::SP) {
assert(BaseReg == ARM::SP && "Unexpected!");
LdReg = ARM::R3;
BuildMI(MBB, MBBI, TII.get(ARM::tMOVr), ARM::R12)
.addReg(ARM::R3, false, false, true);
}
if (NumBytes <= 255 && NumBytes >= 0)
BuildMI(MBB, MBBI, TII.get(ARM::tMOVi8), LdReg).addImm(NumBytes);
else if (NumBytes < 0 && NumBytes >= -255) {
BuildMI(MBB, MBBI, TII.get(ARM::tMOVi8), LdReg).addImm(NumBytes);
BuildMI(MBB, MBBI, TII.get(ARM::tNEG), LdReg)
.addReg(LdReg, false, false, true);
} else
MRI.emitLoadConstPool(MBB, MBBI, LdReg, NumBytes, ARMCC::AL, 0,&TII,true);
// Emit add / sub.
int Opc = (isSub) ? ARM::tSUBrr : (isHigh ? ARM::tADDhirr : ARM::tADDrr);
const MachineInstrBuilder MIB = BuildMI(MBB, MBBI, TII.get(Opc), DestReg);
if (DestReg == ARM::SP || isSub)
MIB.addReg(BaseReg).addReg(LdReg, false, false, true);
else
MIB.addReg(LdReg).addReg(BaseReg, false, false, true);
if (DestReg == ARM::SP)
BuildMI(MBB, MBBI, TII.get(ARM::tMOVr), ARM::R3)
.addReg(ARM::R12, false, false, true);
}
/// emitThumbRegPlusImmediate - Emits a series of instructions to materialize
/// a destreg = basereg + immediate in Thumb code.
static
void emitThumbRegPlusImmediate(MachineBasicBlock &MBB,
MachineBasicBlock::iterator &MBBI,
unsigned DestReg, unsigned BaseReg,
int NumBytes, const TargetInstrInfo &TII,
const ARMRegisterInfo& MRI) {
bool isSub = NumBytes < 0;
unsigned Bytes = (unsigned)NumBytes;
if (isSub) Bytes = -NumBytes;
bool isMul4 = (Bytes & 3) == 0;
bool isTwoAddr = false;
bool DstNotEqBase = false;
unsigned NumBits = 1;
unsigned Scale = 1;
int Opc = 0;
int ExtraOpc = 0;
if (DestReg == BaseReg && BaseReg == ARM::SP) {
assert(isMul4 && "Thumb sp inc / dec size must be multiple of 4!");
NumBits = 7;
Scale = 4;
Opc = isSub ? ARM::tSUBspi : ARM::tADDspi;
isTwoAddr = true;
} else if (!isSub && BaseReg == ARM::SP) {
// r1 = add sp, 403
// =>
// r1 = add sp, 100 * 4
// r1 = add r1, 3
if (!isMul4) {
Bytes &= ~3;
ExtraOpc = ARM::tADDi3;
}
NumBits = 8;
Scale = 4;
Opc = ARM::tADDrSPi;
} else {
// sp = sub sp, c
// r1 = sub sp, c
// r8 = sub sp, c
if (DestReg != BaseReg)
DstNotEqBase = true;
NumBits = 8;
Opc = isSub ? ARM::tSUBi8 : ARM::tADDi8;
isTwoAddr = true;
}
unsigned NumMIs = calcNumMI(Opc, ExtraOpc, Bytes, NumBits, Scale);
unsigned Threshold = (DestReg == ARM::SP) ? 3 : 2;
if (NumMIs > Threshold) {
// This will expand into too many instructions. Load the immediate from a
// constpool entry.
emitThumbRegPlusImmInReg(MBB, MBBI, DestReg, BaseReg, NumBytes, true, TII, MRI);
return;
}
if (DstNotEqBase) {
if (MRI.isLowRegister(DestReg) && MRI.isLowRegister(BaseReg)) {
// If both are low registers, emit DestReg = add BaseReg, max(Imm, 7)
unsigned Chunk = (1 << 3) - 1;
unsigned ThisVal = (Bytes > Chunk) ? Chunk : Bytes;
Bytes -= ThisVal;
BuildMI(MBB, MBBI, TII.get(isSub ? ARM::tSUBi3 : ARM::tADDi3), DestReg)
.addReg(BaseReg, false, false, true).addImm(ThisVal);
} else {
BuildMI(MBB, MBBI, TII.get(ARM::tMOVr), DestReg)
.addReg(BaseReg, false, false, true);
}
BaseReg = DestReg;
}
unsigned Chunk = ((1 << NumBits) - 1) * Scale;
while (Bytes) {
unsigned ThisVal = (Bytes > Chunk) ? Chunk : Bytes;
Bytes -= ThisVal;
ThisVal /= Scale;
// Build the new tADD / tSUB.
if (isTwoAddr)
BuildMI(MBB, MBBI, TII.get(Opc), DestReg).addReg(DestReg).addImm(ThisVal);
else {
bool isKill = BaseReg != ARM::SP;
BuildMI(MBB, MBBI, TII.get(Opc), DestReg)
.addReg(BaseReg, false, false, isKill).addImm(ThisVal);
BaseReg = DestReg;
if (Opc == ARM::tADDrSPi) {
// r4 = add sp, imm
// r4 = add r4, imm
// ...
NumBits = 8;
Scale = 1;
Chunk = ((1 << NumBits) - 1) * Scale;
Opc = isSub ? ARM::tSUBi8 : ARM::tADDi8;
isTwoAddr = true;
}
}
}
if (ExtraOpc)
BuildMI(MBB, MBBI, TII.get(ExtraOpc), DestReg)
.addReg(DestReg, false, false, true)
.addImm(((unsigned)NumBytes) & 3);
}
static
void emitSPUpdate(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
int NumBytes, ARMCC::CondCodes Pred, unsigned PredReg,
bool isThumb, const TargetInstrInfo &TII,
const ARMRegisterInfo& MRI) {
if (isThumb)
emitThumbRegPlusImmediate(MBB, MBBI, ARM::SP, ARM::SP, NumBytes, TII, MRI);
else
emitARMRegPlusImmediate(MBB, MBBI, ARM::SP, ARM::SP, NumBytes,
Pred, PredReg, TII);
}
void ARMRegisterInfo::
eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
MachineBasicBlock::iterator I) const {
if (!hasReservedCallFrame(MF)) {
// If we have alloca, convert as follows:
// ADJCALLSTACKDOWN -> sub, sp, sp, amount
// ADJCALLSTACKUP -> add, sp, sp, amount
MachineInstr *Old = I;
unsigned Amount = Old->getOperand(0).getImm();
if (Amount != 0) {
ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
// We need to keep the stack aligned properly. To do this, we round the
// amount of space needed for the outgoing arguments up to the next
// alignment boundary.
unsigned Align = MF.getTarget().getFrameInfo()->getStackAlignment();
Amount = (Amount+Align-1)/Align*Align;
// Replace the pseudo instruction with a new instruction...
unsigned Opc = Old->getOpcode();
bool isThumb = AFI->isThumbFunction();
ARMCC::CondCodes Pred = isThumb
? ARMCC::AL : (ARMCC::CondCodes)Old->getOperand(1).getImm();
if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
// Note: PredReg is operand 2 for ADJCALLSTACKDOWN.
unsigned PredReg = isThumb ? 0 : Old->getOperand(2).getReg();
emitSPUpdate(MBB, I, -Amount, Pred, PredReg, isThumb, TII, *this);
} else {
// Note: PredReg is operand 3 for ADJCALLSTACKUP.
unsigned PredReg = isThumb ? 0 : Old->getOperand(3).getReg();
assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
emitSPUpdate(MBB, I, Amount, Pred, PredReg, isThumb, TII, *this);
}
}
}
MBB.erase(I);
}
/// emitThumbConstant - Emit a series of instructions to materialize a
/// constant.
static void emitThumbConstant(MachineBasicBlock &MBB,
MachineBasicBlock::iterator &MBBI,
unsigned DestReg, int Imm,
const TargetInstrInfo &TII,
const ARMRegisterInfo& MRI) {
bool isSub = Imm < 0;
if (isSub) Imm = -Imm;
int Chunk = (1 << 8) - 1;
int ThisVal = (Imm > Chunk) ? Chunk : Imm;
Imm -= ThisVal;
BuildMI(MBB, MBBI, TII.get(ARM::tMOVi8), DestReg).addImm(ThisVal);
if (Imm > 0)
emitThumbRegPlusImmediate(MBB, MBBI, DestReg, DestReg, Imm, TII, MRI);
if (isSub)
BuildMI(MBB, MBBI, TII.get(ARM::tNEG), DestReg)
.addReg(DestReg, false, false, true);
}
/// findScratchRegister - Find a 'free' ARM register. If register scavenger
/// is not being used, R12 is available. Otherwise, try for a call-clobbered
/// register first and then a spilled callee-saved register if that fails.
static
unsigned findScratchRegister(RegScavenger *RS, const TargetRegisterClass *RC,
ARMFunctionInfo *AFI) {
unsigned Reg = RS ? RS->FindUnusedReg(RC, true) : (unsigned) ARM::R12;
if (Reg == 0)
// Try a already spilled CS register.
Reg = RS->FindUnusedReg(RC, AFI->getSpilledCSRegisters());
return Reg;
}
void ARMRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
int SPAdj, RegScavenger *RS) const{
unsigned i = 0;
MachineInstr &MI = *II;
MachineBasicBlock &MBB = *MI.getParent();
MachineFunction &MF = *MBB.getParent();
ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
bool isThumb = AFI->isThumbFunction();
while (!MI.getOperand(i).isFrameIndex()) {
++i;
assert(i < MI.getNumOperands() && "Instr doesn't have FrameIndex operand!");
}
unsigned FrameReg = ARM::SP;
int FrameIndex = MI.getOperand(i).getIndex();
int Offset = MF.getFrameInfo()->getObjectOffset(FrameIndex) +
MF.getFrameInfo()->getStackSize() + SPAdj;
if (AFI->isGPRCalleeSavedArea1Frame(FrameIndex))
Offset -= AFI->getGPRCalleeSavedArea1Offset();
else if (AFI->isGPRCalleeSavedArea2Frame(FrameIndex))
Offset -= AFI->getGPRCalleeSavedArea2Offset();
else if (AFI->isDPRCalleeSavedAreaFrame(FrameIndex))
Offset -= AFI->getDPRCalleeSavedAreaOffset();
else if (hasFP(MF)) {
assert(SPAdj == 0 && "Unexpected");
// There is alloca()'s in this function, must reference off the frame
// pointer instead.
FrameReg = getFrameRegister(MF);
Offset -= AFI->getFramePtrSpillOffset();
}
unsigned Opcode = MI.getOpcode();
const TargetInstrDesc &Desc = MI.getDesc();
unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
bool isSub = false;
if (Opcode == ARM::ADDri) {
Offset += MI.getOperand(i+1).getImm();
if (Offset == 0) {
// Turn it into a move.
MI.setDesc(TII.get(ARM::MOVr));
MI.getOperand(i).ChangeToRegister(FrameReg, false);
MI.RemoveOperand(i+1);
return;
} else if (Offset < 0) {
Offset = -Offset;
isSub = true;
MI.setDesc(TII.get(ARM::SUBri));
}
// Common case: small offset, fits into instruction.
int ImmedOffset = ARM_AM::getSOImmVal(Offset);
if (ImmedOffset != -1) {
// Replace the FrameIndex with sp / fp
MI.getOperand(i).ChangeToRegister(FrameReg, false);
MI.getOperand(i+1).ChangeToImmediate(ImmedOffset);
return;
}
// Otherwise, we fallback to common code below to form the imm offset with
// a sequence of ADDri instructions. First though, pull as much of the imm
// into this ADDri as possible.
unsigned RotAmt = ARM_AM::getSOImmValRotate(Offset);
unsigned ThisImmVal = Offset & ARM_AM::rotr32(0xFF, RotAmt);
// We will handle these bits from offset, clear them.
Offset &= ~ThisImmVal;
// Get the properly encoded SOImmVal field.
int ThisSOImmVal = ARM_AM::getSOImmVal(ThisImmVal);
assert(ThisSOImmVal != -1 && "Bit extraction didn't work?");
MI.getOperand(i+1).ChangeToImmediate(ThisSOImmVal);
} else if (Opcode == ARM::tADDrSPi) {
Offset += MI.getOperand(i+1).getImm();
// Can't use tADDrSPi if it's based off the frame pointer.
unsigned NumBits = 0;
unsigned Scale = 1;
if (FrameReg != ARM::SP) {
Opcode = ARM::tADDi3;
MI.setDesc(TII.get(ARM::tADDi3));
NumBits = 3;
} else {
NumBits = 8;
Scale = 4;
assert((Offset & 3) == 0 &&
"Thumb add/sub sp, #imm immediate must be multiple of 4!");
}
if (Offset == 0) {
// Turn it into a move.
MI.setDesc(TII.get(ARM::tMOVr));
MI.getOperand(i).ChangeToRegister(FrameReg, false);
MI.RemoveOperand(i+1);
return;
}
// Common case: small offset, fits into instruction.
unsigned Mask = (1 << NumBits) - 1;
if (((Offset / Scale) & ~Mask) == 0) {
// Replace the FrameIndex with sp / fp
MI.getOperand(i).ChangeToRegister(FrameReg, false);
MI.getOperand(i+1).ChangeToImmediate(Offset / Scale);
return;
}
unsigned DestReg = MI.getOperand(0).getReg();
unsigned Bytes = (Offset > 0) ? Offset : -Offset;
unsigned NumMIs = calcNumMI(Opcode, 0, Bytes, NumBits, Scale);
// MI would expand into a large number of instructions. Don't try to
// simplify the immediate.
if (NumMIs > 2) {
emitThumbRegPlusImmediate(MBB, II, DestReg, FrameReg, Offset, TII, *this);
MBB.erase(II);
return;
}
if (Offset > 0) {
// Translate r0 = add sp, imm to
// r0 = add sp, 255*4
// r0 = add r0, (imm - 255*4)
MI.getOperand(i).ChangeToRegister(FrameReg, false);
MI.getOperand(i+1).ChangeToImmediate(Mask);
Offset = (Offset - Mask * Scale);
MachineBasicBlock::iterator NII = next(II);
emitThumbRegPlusImmediate(MBB, NII, DestReg, DestReg, Offset, TII, *this);
} else {
// Translate r0 = add sp, -imm to
// r0 = -imm (this is then translated into a series of instructons)
// r0 = add r0, sp
emitThumbConstant(MBB, II, DestReg, Offset, TII, *this);
MI.setDesc(TII.get(ARM::tADDhirr));
MI.getOperand(i).ChangeToRegister(DestReg, false, false, true);
MI.getOperand(i+1).ChangeToRegister(FrameReg, false);
}
return;
} else {
unsigned ImmIdx = 0;
int InstrOffs = 0;
unsigned NumBits = 0;
unsigned Scale = 1;
switch (AddrMode) {
case ARMII::AddrMode2: {
ImmIdx = i+2;
InstrOffs = ARM_AM::getAM2Offset(MI.getOperand(ImmIdx).getImm());
if (ARM_AM::getAM2Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
InstrOffs *= -1;
NumBits = 12;
break;
}
case ARMII::AddrMode3: {
ImmIdx = i+2;
InstrOffs = ARM_AM::getAM3Offset(MI.getOperand(ImmIdx).getImm());
if (ARM_AM::getAM3Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
InstrOffs *= -1;
NumBits = 8;
break;
}
case ARMII::AddrMode5: {
ImmIdx = i+1;
InstrOffs = ARM_AM::getAM5Offset(MI.getOperand(ImmIdx).getImm());
if (ARM_AM::getAM5Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
InstrOffs *= -1;
NumBits = 8;
Scale = 4;
break;
}
case ARMII::AddrModeTs: {
ImmIdx = i+1;
InstrOffs = MI.getOperand(ImmIdx).getImm();
NumBits = (FrameReg == ARM::SP) ? 8 : 5;
Scale = 4;
break;
}
default:
assert(0 && "Unsupported addressing mode!");
abort();
break;
}
Offset += InstrOffs * Scale;
assert((Offset & (Scale-1)) == 0 && "Can't encode this offset!");
if (Offset < 0 && !isThumb) {
Offset = -Offset;
isSub = true;
}
// Common case: small offset, fits into instruction.
MachineOperand &ImmOp = MI.getOperand(ImmIdx);
int ImmedOffset = Offset / Scale;
unsigned Mask = (1 << NumBits) - 1;
if ((unsigned)Offset <= Mask * Scale) {
// Replace the FrameIndex with sp
MI.getOperand(i).ChangeToRegister(FrameReg, false);
if (isSub)
ImmedOffset |= 1 << NumBits;
ImmOp.ChangeToImmediate(ImmedOffset);
return;
}
bool isThumSpillRestore = Opcode == ARM::tRestore || Opcode == ARM::tSpill;
if (AddrMode == ARMII::AddrModeTs) {
// Thumb tLDRspi, tSTRspi. These will change to instructions that use
// a different base register.
NumBits = 5;
Mask = (1 << NumBits) - 1;
}
// If this is a thumb spill / restore, we will be using a constpool load to
// materialize the offset.
if (AddrMode == ARMII::AddrModeTs && isThumSpillRestore)
ImmOp.ChangeToImmediate(0);
else {
// Otherwise, it didn't fit. Pull in what we can to simplify the immed.
ImmedOffset = ImmedOffset & Mask;
if (isSub)
ImmedOffset |= 1 << NumBits;
ImmOp.ChangeToImmediate(ImmedOffset);
Offset &= ~(Mask*Scale);
}
}
// If we get here, the immediate doesn't fit into the instruction. We folded
// as much as possible above, handle the rest, providing a register that is
// SP+LargeImm.
assert(Offset && "This code isn't needed if offset already handled!");
if (isThumb) {
if (Desc.isSimpleLoad()) {
// Use the destination register to materialize sp + offset.
unsigned TmpReg = MI.getOperand(0).getReg();
bool UseRR = false;
if (Opcode == ARM::tRestore) {
if (FrameReg == ARM::SP)
emitThumbRegPlusImmInReg(MBB, II, TmpReg, FrameReg,
Offset, false, TII, *this);
else {
emitLoadConstPool(MBB, II, TmpReg, Offset, ARMCC::AL, 0, &TII, true);
UseRR = true;
}
} else
emitThumbRegPlusImmediate(MBB, II, TmpReg, FrameReg, Offset, TII, *this);
MI.setDesc(TII.get(ARM::tLDR));
MI.getOperand(i).ChangeToRegister(TmpReg, false, false, true);
if (UseRR)
// Use [reg, reg] addrmode.
MI.addOperand(MachineOperand::CreateReg(FrameReg, false));
else // tLDR has an extra register operand.
MI.addOperand(MachineOperand::CreateReg(0, false));
} else if (Desc.mayStore()) {
// FIXME! This is horrific!!! We need register scavenging.
// Our temporary workaround has marked r3 unavailable. Of course, r3 is
// also a ABI register so it's possible that is is the register that is
// being storing here. If that's the case, we do the following:
// r12 = r2
// Use r2 to materialize sp + offset
// str r3, r2
// r2 = r12
unsigned ValReg = MI.getOperand(0).getReg();
unsigned TmpReg = ARM::R3;
bool UseRR = false;
if (ValReg == ARM::R3) {
BuildMI(MBB, II, TII.get(ARM::tMOVr), ARM::R12)
.addReg(ARM::R2, false, false, true);
TmpReg = ARM::R2;
}
if (TmpReg == ARM::R3 && AFI->isR3LiveIn())
BuildMI(MBB, II, TII.get(ARM::tMOVr), ARM::R12)
.addReg(ARM::R3, false, false, true);
if (Opcode == ARM::tSpill) {
if (FrameReg == ARM::SP)
emitThumbRegPlusImmInReg(MBB, II, TmpReg, FrameReg,
Offset, false, TII, *this);
else {
emitLoadConstPool(MBB, II, TmpReg, Offset, ARMCC::AL, 0, &TII, true);
UseRR = true;
}
} else
emitThumbRegPlusImmediate(MBB, II, TmpReg, FrameReg, Offset, TII, *this);
MI.setDesc(TII.get(ARM::tSTR));
MI.getOperand(i).ChangeToRegister(TmpReg, false, false, true);
if (UseRR) // Use [reg, reg] addrmode.
MI.addOperand(MachineOperand::CreateReg(FrameReg, false));
else // tSTR has an extra register operand.
MI.addOperand(MachineOperand::CreateReg(0, false));
MachineBasicBlock::iterator NII = next(II);
if (ValReg == ARM::R3)
BuildMI(MBB, NII, TII.get(ARM::tMOVr), ARM::R2)
.addReg(ARM::R12, false, false, true);
if (TmpReg == ARM::R3 && AFI->isR3LiveIn())
BuildMI(MBB, NII, TII.get(ARM::tMOVr), ARM::R3)
.addReg(ARM::R12, false, false, true);
} else
assert(false && "Unexpected opcode!");
} else {
// Insert a set of r12 with the full address: r12 = sp + offset
// If the offset we have is too large to fit into the instruction, we need
// to form it with a series of ADDri's. Do this by taking 8-bit chunks
// out of 'Offset'.
unsigned ScratchReg = findScratchRegister(RS, &ARM::GPRRegClass, AFI);
if (ScratchReg == 0)
// No register is "free". Scavenge a register.
ScratchReg = RS->scavengeRegister(&ARM::GPRRegClass, II, SPAdj);
int PIdx = MI.findFirstPredOperandIdx();
ARMCC::CondCodes Pred = (PIdx == -1)
? ARMCC::AL : (ARMCC::CondCodes)MI.getOperand(PIdx).getImm();
unsigned PredReg = (PIdx == -1) ? 0 : MI.getOperand(PIdx+1).getReg();
emitARMRegPlusImmediate(MBB, II, ScratchReg, FrameReg,
isSub ? -Offset : Offset, Pred, PredReg, TII);
MI.getOperand(i).ChangeToRegister(ScratchReg, false, false, true);
}
}
static unsigned estimateStackSize(MachineFunction &MF, MachineFrameInfo *MFI) {
const MachineFrameInfo *FFI = MF.getFrameInfo();
int Offset = 0;
for (int i = FFI->getObjectIndexBegin(); i != 0; ++i) {
int FixedOff = -FFI->getObjectOffset(i);
if (FixedOff > Offset) Offset = FixedOff;
}
for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) {
if (FFI->isDeadObjectIndex(i))
continue;
Offset += FFI->getObjectSize(i);
unsigned Align = FFI->getObjectAlignment(i);
// Adjust to alignment boundary
Offset = (Offset+Align-1)/Align*Align;
}
return (unsigned)Offset;
}
void
ARMRegisterInfo::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
RegScavenger *RS) const {
// This tells PEI to spill the FP as if it is any other callee-save register
// to take advantage the eliminateFrameIndex machinery. This also ensures it
// is spilled in the order specified by getCalleeSavedRegs() to make it easier
// to combine multiple loads / stores.
bool CanEliminateFrame = true;
bool CS1Spilled = false;
bool LRSpilled = false;
unsigned NumGPRSpills = 0;
SmallVector<unsigned, 4> UnspilledCS1GPRs;
SmallVector<unsigned, 4> UnspilledCS2GPRs;
ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
// Don't spill FP if the frame can be eliminated. This is determined
// by scanning the callee-save registers to see if any is used.
const unsigned *CSRegs = getCalleeSavedRegs();
const TargetRegisterClass* const *CSRegClasses = getCalleeSavedRegClasses();
for (unsigned i = 0; CSRegs[i]; ++i) {
unsigned Reg = CSRegs[i];
bool Spilled = false;
if (MF.getRegInfo().isPhysRegUsed(Reg)) {
AFI->setCSRegisterIsSpilled(Reg);
Spilled = true;
CanEliminateFrame = false;
} else {
// Check alias registers too.
for (const unsigned *Aliases = getAliasSet(Reg); *Aliases; ++Aliases) {
if (MF.getRegInfo().isPhysRegUsed(*Aliases)) {
Spilled = true;
CanEliminateFrame = false;
}
}
}
if (CSRegClasses[i] == &ARM::GPRRegClass) {
if (Spilled) {
NumGPRSpills++;
if (!STI.isTargetDarwin()) {
if (Reg == ARM::LR)
LRSpilled = true;
CS1Spilled = true;
continue;
}
// Keep track if LR and any of R4, R5, R6, and R7 is spilled.
switch (Reg) {
case ARM::LR:
LRSpilled = true;
// Fallthrough
case ARM::R4:
case ARM::R5:
case ARM::R6:
case ARM::R7:
CS1Spilled = true;
break;
default:
break;
}
} else {
if (!STI.isTargetDarwin()) {
UnspilledCS1GPRs.push_back(Reg);
continue;
}
switch (Reg) {
case ARM::R4:
case ARM::R5:
case ARM::R6:
case ARM::R7:
case ARM::LR:
UnspilledCS1GPRs.push_back(Reg);
break;
default:
UnspilledCS2GPRs.push_back(Reg);
break;
}
}
}
}
bool ForceLRSpill = false;
if (!LRSpilled && AFI->isThumbFunction()) {
unsigned FnSize = TII.GetFunctionSizeInBytes(MF);
// Force LR to be spilled if the Thumb function size is > 2048. This enables
// use of BL to implement far jump. If it turns out that it's not needed
// then the branch fix up path will undo it.
if (FnSize >= (1 << 11)) {
CanEliminateFrame = false;
ForceLRSpill = true;
}
}
bool ExtraCSSpill = false;
if (!CanEliminateFrame || hasFP(MF)) {
AFI->setHasStackFrame(true);
// If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
// Spill LR as well so we can fold BX_RET to the registers restore (LDM).
if (!LRSpilled && CS1Spilled) {
MF.getRegInfo().setPhysRegUsed(ARM::LR);
AFI->setCSRegisterIsSpilled(ARM::LR);
NumGPRSpills++;
UnspilledCS1GPRs.erase(std::find(UnspilledCS1GPRs.begin(),
UnspilledCS1GPRs.end(), (unsigned)ARM::LR));
ForceLRSpill = false;
ExtraCSSpill = true;
}
// Darwin ABI requires FP to point to the stack slot that contains the
// previous FP.
if (STI.isTargetDarwin() || hasFP(MF)) {
MF.getRegInfo().setPhysRegUsed(FramePtr);
NumGPRSpills++;
}
// If stack and double are 8-byte aligned and we are spilling an odd number
// of GPRs. Spill one extra callee save GPR so we won't have to pad between
// the integer and double callee save areas.
unsigned TargetAlign = MF.getTarget().getFrameInfo()->getStackAlignment();
if (TargetAlign == 8 && (NumGPRSpills & 1)) {
if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
unsigned Reg = UnspilledCS1GPRs[i];
// Don't spiil high register if the function is thumb
if (!AFI->isThumbFunction() || isLowRegister(Reg) || Reg == ARM::LR) {
MF.getRegInfo().setPhysRegUsed(Reg);
AFI->setCSRegisterIsSpilled(Reg);
if (!isReservedReg(MF, Reg))
ExtraCSSpill = true;
break;
}
}
} else if (!UnspilledCS2GPRs.empty() &&
!AFI->isThumbFunction()) {
unsigned Reg = UnspilledCS2GPRs.front();
MF.getRegInfo().setPhysRegUsed(Reg);
AFI->setCSRegisterIsSpilled(Reg);
if (!isReservedReg(MF, Reg))
ExtraCSSpill = true;
}
}
// Estimate if we might need to scavenge a register at some point in order
// to materialize a stack offset. If so, either spill one additiona
// callee-saved register or reserve a special spill slot to facilitate
// register scavenging.
if (RS && !ExtraCSSpill && !AFI->isThumbFunction()) {
MachineFrameInfo *MFI = MF.getFrameInfo();
unsigned Size = estimateStackSize(MF, MFI);
unsigned Limit = (1 << 12) - 1;
for (MachineFunction::iterator BB = MF.begin(),E = MF.end();BB != E; ++BB)
for (MachineBasicBlock::iterator I= BB->begin(); I != BB->end(); ++I) {
for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
if (I->getOperand(i).isFrameIndex()) {
unsigned Opcode = I->getOpcode();
const TargetInstrDesc &Desc = TII.get(Opcode);
unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
if (AddrMode == ARMII::AddrMode3) {
Limit = (1 << 8) - 1;
goto DoneEstimating;
} else if (AddrMode == ARMII::AddrMode5) {
unsigned ThisLimit = ((1 << 8) - 1) * 4;
if (ThisLimit < Limit)
Limit = ThisLimit;
}
}
}
DoneEstimating:
if (Size >= Limit) {
// If any non-reserved CS register isn't spilled, just spill one or two
// extra. That should take care of it!
unsigned NumExtras = TargetAlign / 4;
SmallVector<unsigned, 2> Extras;
while (NumExtras && !UnspilledCS1GPRs.empty()) {
unsigned Reg = UnspilledCS1GPRs.back();
UnspilledCS1GPRs.pop_back();
if (!isReservedReg(MF, Reg)) {
Extras.push_back(Reg);
NumExtras--;
}
}
while (NumExtras && !UnspilledCS2GPRs.empty()) {
unsigned Reg = UnspilledCS2GPRs.back();
UnspilledCS2GPRs.pop_back();
if (!isReservedReg(MF, Reg)) {
Extras.push_back(Reg);
NumExtras--;
}
}
if (Extras.size() && NumExtras == 0) {
for (unsigned i = 0, e = Extras.size(); i != e; ++i) {
MF.getRegInfo().setPhysRegUsed(Extras[i]);
AFI->setCSRegisterIsSpilled(Extras[i]);
}
} else {
// Reserve a slot closest to SP or frame pointer.
const TargetRegisterClass *RC = &ARM::GPRRegClass;
RS->setScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
RC->getAlignment()));
}
}
}
}
if (ForceLRSpill) {
MF.getRegInfo().setPhysRegUsed(ARM::LR);
AFI->setCSRegisterIsSpilled(ARM::LR);
AFI->setLRIsSpilledForFarJump(true);
}
}
/// Move iterator pass the next bunch of callee save load / store ops for
/// the particular spill area (1: integer area 1, 2: integer area 2,
/// 3: fp area, 0: don't care).
static void movePastCSLoadStoreOps(MachineBasicBlock &MBB,
MachineBasicBlock::iterator &MBBI,
int Opc, unsigned Area,
const ARMSubtarget &STI) {
while (MBBI != MBB.end() &&
MBBI->getOpcode() == Opc && MBBI->getOperand(1).isFrameIndex()) {
if (Area != 0) {
bool Done = false;
unsigned Category = 0;
switch (MBBI->getOperand(0).getReg()) {
case ARM::R4: case ARM::R5: case ARM::R6: case ARM::R7:
case ARM::LR:
Category = 1;
break;
case ARM::R8: case ARM::R9: case ARM::R10: case ARM::R11:
Category = STI.isTargetDarwin() ? 2 : 1;
break;
case ARM::D8: case ARM::D9: case ARM::D10: case ARM::D11:
case ARM::D12: case ARM::D13: case ARM::D14: case ARM::D15:
Category = 3;
break;
default:
Done = true;
break;
}
if (Done || Category != Area)
break;
}
++MBBI;
}
}
void ARMRegisterInfo::emitPrologue(MachineFunction &MF) const {
MachineBasicBlock &MBB = MF.front();
MachineBasicBlock::iterator MBBI = MBB.begin();
MachineFrameInfo *MFI = MF.getFrameInfo();
ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
bool isThumb = AFI->isThumbFunction();
unsigned VARegSaveSize = AFI->getVarArgsRegSaveSize();
unsigned NumBytes = MFI->getStackSize();
const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
if (isThumb) {
// Check if R3 is live in. It might have to be used as a scratch register.
for (MachineRegisterInfo::livein_iterator I =MF.getRegInfo().livein_begin(),
E = MF.getRegInfo().livein_end(); I != E; ++I) {
if (I->first == ARM::R3) {
AFI->setR3IsLiveIn(true);
break;
}
}
// Thumb add/sub sp, imm8 instructions implicitly multiply the offset by 4.
NumBytes = (NumBytes + 3) & ~3;
MFI->setStackSize(NumBytes);
}
// Determine the sizes of each callee-save spill areas and record which frame
// belongs to which callee-save spill areas.
unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
int FramePtrSpillFI = 0;
if (VARegSaveSize)
emitSPUpdate(MBB, MBBI, -VARegSaveSize, ARMCC::AL, 0, isThumb, TII, *this);
if (!AFI->hasStackFrame()) {
if (NumBytes != 0)
emitSPUpdate(MBB, MBBI, -NumBytes, ARMCC::AL, 0, isThumb, TII, *this);
return;
}
for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
unsigned Reg = CSI[i].getReg();
int FI = CSI[i].getFrameIdx();
switch (Reg) {
case ARM::R4:
case ARM::R5:
case ARM::R6:
case ARM::R7:
case ARM::LR:
if (Reg == FramePtr)
FramePtrSpillFI = FI;
AFI->addGPRCalleeSavedArea1Frame(FI);
GPRCS1Size += 4;
break;
case ARM::R8:
case ARM::R9:
case ARM::R10:
case ARM::R11:
if (Reg == FramePtr)
FramePtrSpillFI = FI;
if (STI.isTargetDarwin()) {
AFI->addGPRCalleeSavedArea2Frame(FI);
GPRCS2Size += 4;
} else {
AFI->addGPRCalleeSavedArea1Frame(FI);
GPRCS1Size += 4;
}
break;
default:
AFI->addDPRCalleeSavedAreaFrame(FI);
DPRCSSize += 8;
}
}
if (!isThumb) {
// Build the new SUBri to adjust SP for integer callee-save spill area 1.
emitSPUpdate(MBB, MBBI, -GPRCS1Size, ARMCC::AL, 0, isThumb, TII, *this);
movePastCSLoadStoreOps(MBB, MBBI, ARM::STR, 1, STI);
} else if (MBBI != MBB.end() && MBBI->getOpcode() == ARM::tPUSH)
++MBBI;
// Darwin ABI requires FP to point to the stack slot that contains the
// previous FP.
if (STI.isTargetDarwin() || hasFP(MF)) {
MachineInstrBuilder MIB =
BuildMI(MBB, MBBI, TII.get(isThumb ? ARM::tADDrSPi : ARM::ADDri),FramePtr)
.addFrameIndex(FramePtrSpillFI).addImm(0);
if (!isThumb) AddDefaultCC(AddDefaultPred(MIB));
}
if (!isThumb) {
// Build the new SUBri to adjust SP for integer callee-save spill area 2.
emitSPUpdate(MBB, MBBI, -GPRCS2Size, ARMCC::AL, 0, false, TII, *this);
// Build the new SUBri to adjust SP for FP callee-save spill area.
movePastCSLoadStoreOps(MBB, MBBI, ARM::STR, 2, STI);
emitSPUpdate(MBB, MBBI, -DPRCSSize, ARMCC::AL, 0, false, TII, *this);
}
// Determine starting offsets of spill areas.
unsigned DPRCSOffset = NumBytes - (GPRCS1Size + GPRCS2Size + DPRCSSize);
unsigned GPRCS2Offset = DPRCSOffset + DPRCSSize;
unsigned GPRCS1Offset = GPRCS2Offset + GPRCS2Size;
AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) + NumBytes);
AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
NumBytes = DPRCSOffset;
if (NumBytes) {
// Insert it after all the callee-save spills.
if (!isThumb)
movePastCSLoadStoreOps(MBB, MBBI, ARM::FSTD, 3, STI);
emitSPUpdate(MBB, MBBI, -NumBytes, ARMCC::AL, 0, isThumb, TII, *this);
}
if(STI.isTargetELF() && hasFP(MF)) {
MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() -
AFI->getFramePtrSpillOffset());
}
AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
}
static bool isCalleeSavedRegister(unsigned Reg, const unsigned *CSRegs) {
for (unsigned i = 0; CSRegs[i]; ++i)
if (Reg == CSRegs[i])
return true;
return false;
}
static bool isCSRestore(MachineInstr *MI, const unsigned *CSRegs) {
return ((MI->getOpcode() == ARM::FLDD ||
MI->getOpcode() == ARM::LDR ||
MI->getOpcode() == ARM::tRestore) &&
MI->getOperand(1).isFrameIndex() &&
isCalleeSavedRegister(MI->getOperand(0).getReg(), CSRegs));
}
void ARMRegisterInfo::emitEpilogue(MachineFunction &MF,
MachineBasicBlock &MBB) const {
MachineBasicBlock::iterator MBBI = prior(MBB.end());
assert((MBBI->getOpcode() == ARM::BX_RET ||
MBBI->getOpcode() == ARM::tBX_RET ||
MBBI->getOpcode() == ARM::tPOP_RET) &&
"Can only insert epilog into returning blocks");
MachineFrameInfo *MFI = MF.getFrameInfo();
ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
bool isThumb = AFI->isThumbFunction();
unsigned VARegSaveSize = AFI->getVarArgsRegSaveSize();
int NumBytes = (int)MFI->getStackSize();
if (!AFI->hasStackFrame()) {
if (NumBytes != 0)
emitSPUpdate(MBB, MBBI, NumBytes, ARMCC::AL, 0, isThumb, TII, *this);
} else {
// Unwind MBBI to point to first LDR / FLDD.
const unsigned *CSRegs = getCalleeSavedRegs();
if (MBBI != MBB.begin()) {
do
--MBBI;
while (MBBI != MBB.begin() && isCSRestore(MBBI, CSRegs));
if (!isCSRestore(MBBI, CSRegs))
++MBBI;
}
// Move SP to start of FP callee save spill area.
NumBytes -= (AFI->getGPRCalleeSavedArea1Size() +
AFI->getGPRCalleeSavedArea2Size() +
AFI->getDPRCalleeSavedAreaSize());
if (isThumb) {
if (hasFP(MF)) {
NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
// Reset SP based on frame pointer only if the stack frame extends beyond
// frame pointer stack slot or target is ELF and the function has FP.
if (NumBytes)
emitThumbRegPlusImmediate(MBB, MBBI, ARM::SP, FramePtr, -NumBytes,
TII, *this);
else
BuildMI(MBB, MBBI, TII.get(ARM::tMOVr), ARM::SP).addReg(FramePtr);
} else {
if (MBBI->getOpcode() == ARM::tBX_RET &&
&MBB.front() != MBBI &&
prior(MBBI)->getOpcode() == ARM::tPOP) {
MachineBasicBlock::iterator PMBBI = prior(MBBI);
emitSPUpdate(MBB, PMBBI, NumBytes, ARMCC::AL, 0, isThumb, TII, *this);
} else
emitSPUpdate(MBB, MBBI, NumBytes, ARMCC::AL, 0, isThumb, TII, *this);
}
} else {
// Darwin ABI requires FP to point to the stack slot that contains the
// previous FP.
if ((STI.isTargetDarwin() && NumBytes) || hasFP(MF)) {
NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
// Reset SP based on frame pointer only if the stack frame extends beyond
// frame pointer stack slot or target is ELF and the function has FP.
if (AFI->getGPRCalleeSavedArea2Size() ||
AFI->getDPRCalleeSavedAreaSize() ||
AFI->getDPRCalleeSavedAreaOffset()||
hasFP(MF)) {
if (NumBytes)
BuildMI(MBB, MBBI, TII.get(ARM::SUBri), ARM::SP).addReg(FramePtr)
.addImm(NumBytes)
.addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
else
BuildMI(MBB, MBBI, TII.get(ARM::MOVr), ARM::SP).addReg(FramePtr)
.addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
}
} else if (NumBytes) {
emitSPUpdate(MBB, MBBI, NumBytes, ARMCC::AL, 0, false, TII, *this);
}
// Move SP to start of integer callee save spill area 2.
movePastCSLoadStoreOps(MBB, MBBI, ARM::FLDD, 3, STI);
emitSPUpdate(MBB, MBBI, AFI->getDPRCalleeSavedAreaSize(), ARMCC::AL, 0,
false, TII, *this);
// Move SP to start of integer callee save spill area 1.
movePastCSLoadStoreOps(MBB, MBBI, ARM::LDR, 2, STI);
emitSPUpdate(MBB, MBBI, AFI->getGPRCalleeSavedArea2Size(), ARMCC::AL, 0,
false, TII, *this);
// Move SP to SP upon entry to the function.
movePastCSLoadStoreOps(MBB, MBBI, ARM::LDR, 1, STI);
emitSPUpdate(MBB, MBBI, AFI->getGPRCalleeSavedArea1Size(), ARMCC::AL, 0,
false, TII, *this);
}
}
if (VARegSaveSize) {
if (isThumb)
// Epilogue for vararg functions: pop LR to R3 and branch off it.
// FIXME: Verify this is still ok when R3 is no longer being reserved.
BuildMI(MBB, MBBI, TII.get(ARM::tPOP)).addReg(ARM::R3);
emitSPUpdate(MBB, MBBI, VARegSaveSize, ARMCC::AL, 0, isThumb, TII, *this);
if (isThumb) {
BuildMI(MBB, MBBI, TII.get(ARM::tBX_RET_vararg)).addReg(ARM::R3);
MBB.erase(MBBI);
}
}
}
unsigned ARMRegisterInfo::getRARegister() const {
return ARM::LR;
}
unsigned ARMRegisterInfo::getFrameRegister(MachineFunction &MF) const {
if (STI.isTargetDarwin() || hasFP(MF))
return (STI.useThumbBacktraces() || STI.isThumb()) ? ARM::R7 : ARM::R11;
else
return ARM::SP;
}
unsigned ARMRegisterInfo::getEHExceptionRegister() const {
assert(0 && "What is the exception register");
return 0;
}
unsigned ARMRegisterInfo::getEHHandlerRegister() const {
assert(0 && "What is the exception handler register");
return 0;
}
int ARMRegisterInfo::getDwarfRegNum(unsigned RegNum, bool isEH) const {
assert(0 && "What is the dwarf register number");
return -1;
}
#include "ARMGenRegisterInfo.inc"
| 36.314121
| 84
| 0.613463
|
marnen
|
779074fbbffbc7357b8cd6be45810012719a662a
| 1,861
|
cpp
|
C++
|
source/Ch05/Sajat/sajat_drill5.cpp
|
BuganBarna/UDProg-Introduction
|
506c61e41e8651371b02299602b521e4c3e267eb
|
[
"CC0-1.0"
] | null | null | null |
source/Ch05/Sajat/sajat_drill5.cpp
|
BuganBarna/UDProg-Introduction
|
506c61e41e8651371b02299602b521e4c3e267eb
|
[
"CC0-1.0"
] | null | null | null |
source/Ch05/Sajat/sajat_drill5.cpp
|
BuganBarna/UDProg-Introduction
|
506c61e41e8651371b02299602b521e4c3e267eb
|
[
"CC0-1.0"
] | null | null | null |
#include "std_lib_facilities.h"
int main()
try{
//cout << " Success!\n ";
//cout << " Success!\n";
//cout << " Success " << "!\n ";
//cout << "success" << '\n';
//int res = 7; vector<int> v(10); v[5] = res; cout << " Success!\n " ;
//vector<int> v(10); v[5] = 7; if (v[5]==7) cout << " Success!\n " ;
//bool cond=true; if (cond) cout << " Success!\n " ; else cout << " Fail!\n " ;
//bool c = true; if (c) cout << " Success!\n " ; else cout << " Fail!\n " ;
//string s = " ape " ; bool c ="fool"<s; if (!c) cout << " Success!\n " ;
//string s = " ape " ; if (s!= " fool " ) cout << " Success!\n " ;
//string s = " ape " ; if (s!= " fool " ) cout << " Success!\n " ;
//string s = " ape " ; if (s!= " fool " ) cout << " Success!\n " ;
//vector<char> v(5); for (int i=0; i<v.size(); ++i) ; cout << " Success!\n " ;
//vector<char> v(5); for (int i=0; i<=v.size(); ++i) ; cout << " Success!\n " ;
//string s = " Success!\n " ; for (int i=0; i<9; ++i) cout << s[i];
//if (true) cout << " Success!\n " ; else cout << " Fail!\n " ;
//int x = 2000; int c = x; if (c==2000) cout << " Success!\n " ;
//string s = " Success!\n " ; for (int i=0; i<9; ++i) cout << s[i];
//vector<int> v(5); for (int i=0; i<=v.size(); ++i) ; cout << " Success!\n " ;
//int i=0; int j = 9; while (i<10) ++i; if (j<i) cout << " Success!\n " ;
//double x = 4; double d = 17/(x-2); if (d==2*x+0.5) cout << " Success!\n " ;
//string s = " Success!\n " ; for (int i=0; i<=10; ++i) cout << s[i];
//int i=0; int j=9; while (i<10) ++i; if (j<i) cout << " Success!\n " ;
//double x = 4; double d = 5.0/(x-2); if(d==x/2.0+0.5)cout << " Success!\n " ;
//cout << " Success!\n " ;
return 0;
}
catch (exception& e) {
cerr << "error: " << e.what() << '\n';
keep_window_open();
return 1;
}
catch (...) {
cerr << "Oops: unknown exception!\n";
keep_window_open();
return 2;
}
| 42.295455
| 80
| 0.484686
|
BuganBarna
|
7791671bd3577ac27dbf86e718c0abcd5fc52105
| 9,945
|
cpp
|
C++
|
src/database.cpp
|
ZyperPL/TVCTL
|
a0ebd73fc1307c59a4846be3a12d1b30f031e185
|
[
"MIT"
] | null | null | null |
src/database.cpp
|
ZyperPL/TVCTL
|
a0ebd73fc1307c59a4846be3a12d1b30f031e185
|
[
"MIT"
] | null | null | null |
src/database.cpp
|
ZyperPL/TVCTL
|
a0ebd73fc1307c59a4846be3a12d1b30f031e185
|
[
"MIT"
] | null | null | null |
#include "database.h"
Database::Database()
{
}
Database::~Database()
{
for (size_t i = 0; i < this->list.size(); i++)
{
delete (this->list.at(i));
}
}
bool Database::addSeries(std::string data)
{
rapidxml::xml_document<> doc;
doc.parse<0>((char *)data.c_str());
rapidxml::xml_node<> *node = doc.first_node()->first_node("Series");
int seriesNumber = 0;
while (node != 0)
{
seriesNumber++;
node = node->next_sibling();
}
if (seriesNumber == 0) {
std::cerr << "Error: Not series not found!" << std::endl;
return false;
}
node = doc.first_node()->first_node("Series");
if (seriesNumber > 1)
{
seriesNumber = 0;
while (node != 0)
{
seriesNumber++;
std::cerr << seriesNumber << ") ";
std::cerr << node->first_node("SeriesName")->value() << " ";
//std::cout << node->first_node("FirstAired")->value() << " ";
//if (node->first_node("Network")) std::cout << "[" << node->first_node("Network")->value() << "]" << " ";
std::cerr << std::endl;
node = node->next_sibling();
}
std::cerr << std::endl << "Choose from 1-" << seriesNumber << ": ";
int seriesChosen = -1;
std::cin >> seriesChosen;
if (seriesChosen <= 0 || seriesChosen > seriesNumber)
{
std::cerr << "Wrong number!" << std::endl;
return false;
}
node = doc.first_node()->first_node("Series");
for (int i = 1; i < seriesChosen; ++i)
{
node = node->next_sibling();
}
}
std::string name = node->first_node("SeriesName")->value();
for (size_t i = 0; i < name.size(); i++)
{
if ((name.at(i) < '0' || name.at(i) > 'z') && name.at(i) != ' ')
{
name.replace(i, 1, "");
}
}
for (size_t i = 0; i < this->list.size(); ++i)
{
if ((*(this->list.at(i))).name == name)
{
std::cerr << "Error: Series already exist in database!" << std::endl;
return false;
}
}
std::string id = "";
id = node->first_node("seriesid")->value();
if (id.size() <= 0) id = node->first_node("id")->value();
if (id.size() <= 0)
{
std::cerr << "Error: Unknown series" << std::endl;
return false;
}
this->list.push_back(new Series(name, id));
doc.clear();
return true;
}
bool Database::update()
{
std::cerr << "Updating database..." << std::endl;
std::string url = "";
std::string data = "";
for (std::vector<Series*>::iterator it = this->list.begin();
it != this->list.end();
++it)
{
url = "";
url += "http://thetvdb.com/api/497EF9438959C2C2/series/";
url += (*it)->id;
url += "/all/en.xml";
data = Downloader::get(url);
if (data == "") return false;
std::vector<Episode*> episodes2;
rapidxml::xml_document<> doc;
doc.parse<0>((char *)data.c_str());
rapidxml::xml_node<> *node = NULL;
std::cerr << "Parsing episodes of " << (*it)->name << "..." << std::endl;
rapidxml::xml_node<> *extNode = doc.first_node();
if (!extNode) {
std::cerr << "ERROR: Wrong data.xml format!\n";
return false;
}
node = extNode->first_node("Episode");
while (node != 0)
{
std::string id = node->first_node("id")->value();
std::string name = node->first_node("EpisodeName")->value();
std::string season = node->first_node("SeasonNumber")->value();
std::string date = node->first_node("FirstAired")->value();
std::string number = node->first_node("EpisodeNumber")->value();
if (number.size() == 1) number = "0"+number;
if (season.size() == 1) season = "0"+season;
//std::cout << id << " " << name << " " << season << " " << date << std::endl;
//sscanf(date.c_str(), "%d-%d-%d", &(ep->year), &(ep->month), &(ep->day));
int year, month, day;
year = month = day = 9999;
if (date.find("-") != std::string::npos)
date = date.replace(date.find("-"), 1, " ");
if (date.find("-") != std::string::npos)
date = date.replace(date.find("-"), 1, " ");
std::stringstream(date) >> year >> month >> day;
if (year != 9999 && month != 9999 && day != 9999)
episodes2.push_back(new Episode(id, number, name, year, month, day, 0, season));
node = node->next_sibling("Episode");
}
/*for (size_t i = 0; i < (*it)->episodes.size(); i++)
{
std::cout << (*it)->episodes.at(i)->number << ")" << (*it)->episodes.at(i)->title << "| |" << (*it)->episodes.at(i)->day << "| |" << (*it)->episodes.at(i)->month << "| |" << (*it)->episodes.at(i)->year << std::endl;
}*/
std::sort(episodes2.begin(),
episodes2.end(),
[]
(Episode *a, Episode *b) -> bool
{
if (a->year != b->year)
{
return a->year < b->year;
} else
if (a->month != b->month)
{
return a->month < b->month;
} else
{
return a->day < b->day;
}
return false;
}
);
for (std::vector<Episode*>::iterator kt = episodes2.begin();
kt != episodes2.end();
kt++)
{
bool exist = false;
for (std::vector<Episode*>::iterator jt = (*it)->episodes.begin();
jt != (*it)->episodes.end();
jt++)
{
if ((*jt)->id == (*kt)->id)
{
exist = true;
break;
}
}
if (!exist)
{
std::cerr << "Adding new episode '" << (*kt)->title << "'..." << std::endl;
(*it)->episodes.push_back(new Episode(**kt));
}
}
for (std::vector<Episode*>::iterator kt = (*it)->episodes.end()-1;
kt != (*it)->episodes.begin()-1;
kt--)
{
bool exist = false;
for (std::vector<Episode*>::iterator jt = episodes2.begin();
jt != episodes2.end();
jt++)
{
if ((*jt)->id == (*kt)->id)
{
exist = true;
break;
}
}
if (!exist)
{
std::cerr << "Erasing episode " << (*kt)->id << "..." << std::endl;
(*it)->episodes.erase(kt);
}
}
for (size_t i = 0; i < episodes2.size(); i++)
{
delete episodes2.at(i);
}
}
return true;
}
void Database::save()
{
std::cerr << "Saving changes..." << std::endl;
rapidxml::xml_document<> doc;
for (std::vector<Series*>::iterator it = this->list.begin();
it != this->list.end();
++it)
{
rapidxml::xml_node<> *root = doc.allocate_node(rapidxml::node_element, "Series");
root->append_attribute(doc.allocate_attribute("id", (*it)->id.c_str()));
root->append_attribute(doc.allocate_attribute("name", (*it)->name.c_str()));
doc.append_node(root);
for (std::vector<Episode*>::iterator jt = (*it)->episodes.begin();
jt != (*it)->episodes.end();
++jt)
{
//std::cout << (*jt)->id << ":" << (*jt)->title << " "
// << (*jt)->season << "x" << (*jt)->number << " "
// << (*jt)->day << "-" << (*jt)->month << "-" << (*jt)->year << std::endl;
rapidxml::xml_node<> *c = doc.allocate_node(rapidxml::node_element, "Episode");
c->append_attribute(doc.allocate_attribute("id", doc.allocate_string((*jt)->id.c_str())) );
c->append_attribute(doc.allocate_attribute("title", doc.allocate_string((*jt)->title.c_str())) );
c->append_attribute(doc.allocate_attribute("season", doc.allocate_string((*jt)->season.c_str())) );
c->append_attribute(doc.allocate_attribute("number", doc.allocate_string((*jt)->number.c_str())) );
//std::cout << (*jt)->number << std::endl;
c->append_attribute(doc.allocate_attribute("day", doc.allocate_string(std::to_string((*jt)->day).c_str())) );
c->append_attribute(doc.allocate_attribute("month", doc.allocate_string(std::to_string((*jt)->month).c_str())) );
c->append_attribute(doc.allocate_attribute("year", doc.allocate_string(std::to_string((*jt)->year).c_str())) );
c->append_attribute(doc.allocate_attribute("seen", doc.allocate_string(std::to_string((*jt)->seen).c_str())) );
root->append_node(c);
}
}
std::string doc_str;
rapidxml::print(std::back_inserter(doc_str), doc, 0);
std::ofstream file;
file.open("data.xml");
file << doc_str;
file.close();
//std::cout << doc;
}
void Database::load(std::string fileName)
{
std::ifstream file;
file.open(fileName, std::ios::in);
if (!file) return;
//std::cerr << "Loading database..." << std::endl;
std::string data = "";
while (!file.eof())
{
char line[256];
file.getline(line, 256);
data += line;
}
file.close();
//std::cout << data;
rapidxml::xml_document<> doc;
doc.parse<0>((char *)data.c_str());
rapidxml::xml_node<> *node = doc.first_node();
while (node != 0)
{
std::string seriesId = node->last_attribute()->value();
std::string seriesName = node->first_attribute()->value();
this->list.push_back(new Series(seriesId, seriesName) );
rapidxml::xml_node<> *epNode = node->first_node("Episode");
while (epNode != 0)
{
std::string id = epNode->first_attribute("id")->value();
std::string title = epNode->first_attribute("title")->value();
std::string season = epNode->first_attribute("season")->value();
std::string number = epNode->first_attribute("number")->value();
int day = atoi(epNode->first_attribute("day")->value());
int month = atoi(epNode->first_attribute("month")->value());
int year = atoi(epNode->first_attribute("year")->value());
int seen = atoi(epNode->first_attribute("seen")->value());
this->list.back()->episodes.push_back(new Episode(id, number, title, year, month, day, seen, season) );
epNode = epNode->next_sibling("Episode");
}
node = node->next_sibling("Series");
}
}
std::vector<Series*> *Database::getList()
{
return &this->list;
}
| 28.826087
| 221
| 0.533937
|
ZyperPL
|
7791cb2049c025493a73c5008186d04d3cc81230
| 3,939
|
cpp
|
C++
|
1066.campus-bikes-ii.cpp
|
bsmsnd/LeetCode-CharlieChen
|
db72f0a3463c9e723aac800cdbe38218b36aa639
|
[
"MIT"
] | null | null | null |
1066.campus-bikes-ii.cpp
|
bsmsnd/LeetCode-CharlieChen
|
db72f0a3463c9e723aac800cdbe38218b36aa639
|
[
"MIT"
] | null | null | null |
1066.campus-bikes-ii.cpp
|
bsmsnd/LeetCode-CharlieChen
|
db72f0a3463c9e723aac800cdbe38218b36aa639
|
[
"MIT"
] | null | null | null |
/*
* @lc app=leetcode id=1066 lang=cpp
*
* [1066] Campus Bikes II
*/
// @lc code=start
// class Solution {
// public:
// int dist[12][12];
// int dp[1024][1024];
// // int N, M;
// int assignBikes(vector<vector<int>>& workers, vector<vector<int>>& bikes) {
// const int N = workers.size();
// const int M = bikes.size();
// queue<pair<int, int> > q;
// memset(dp, -1, sizeof(dp));
// for (int i = 0;i < N; i++)
// for (int j = 0;j < M; j++)
// {
// dist[i][j] = abs(workers[i][0] - bikes[j][0]) + abs(workers[i][1] - bikes[j][1]);
// dp[1 << i][1 << j] = dist[i][j];
// q.push(make_pair( (1 << i), (1 << j) ));
// }
// int n = N - 1;
// while(n--)
// {
// int m = q.size();
// for (int k = 0;k < m; k++)
// {
// int worker_state = q.front().first, bike_state = q.front().second;
// q.pop();
// for (int i = 0; i < N; i++)
// for (int j = 0;j < M; j++)
// if (((worker_state & (1 << i)) == 0) && ((bike_state & (1 << j)) == 0))
// {
// // cout << (worker_state & (1 << i)) << " " << (bike_state & (1 << j)) << endl;
// int new_worker_state = worker_state | (1 << i);
// int new_bike_state = bike_state | (1 << j);
// if (dp[new_worker_state][new_bike_state] == -1)
// {
// dp[new_worker_state][new_bike_state] = dp[worker_state][bike_state] + dist[i][j];
// q.push(make_pair(new_worker_state, new_bike_state));
// }
// else
// {
// dp[new_worker_state][new_bike_state] = min(dp[new_worker_state][new_bike_state], dp[worker_state][bike_state] + dist[i][j]);
// }
// }
// }
// }
// int best_ans = INT_MAX;
// int full_worker = (1 << N) - 1;
// for (int j = (1 << N)-1; j < (1 << M); j++)
// if (dp[full_worker][j] != -1)
// best_ans = min(best_ans, dp[full_worker][j]);
// return best_ans;
// }
// };
class Solution {
public:
int dist[12][12];
int assignBikes(vector<vector<int>>& workers, vector<vector<int>>& bikes) {
unordered_map<int, int> ans;
const int N = workers.size();
const int M = bikes.size();
for (int i = 0;i < N; i++)
for (int j = 0;j < M; j++)
dist[i][j] = abs(workers[i][0] - bikes[j][0]) + abs(workers[i][1] - bikes[j][1]);
for (int j = 0;j < M; j++)
ans[1 << j] = dist[0][j];
for (int i = 1; i < N; i++)
{
unordered_map<int, int> tmp;
// tmp.clear();
for (auto it = ans.begin(); it != ans.end(); it++)
for (int j = 0; j < M; j++)
if ((it->first & (1 << j)) == 0)
{
int new_state = it->first | (1 << j);
if (tmp.find(new_state) == tmp.end())
tmp[new_state] = it->second + dist[i][j];
else
tmp[new_state] = min(tmp[new_state], it->second + dist[i][j]);
}
swap(ans, tmp);
}
int best_ans = INT_MAX;
for (auto it = ans.begin(); it != ans.end(); it++)
best_ans = min(best_ans, it->second);
return best_ans;
}
};
// @lc code=end
| 37.514286
| 179
| 0.370145
|
bsmsnd
|
7795e0b81fa8628b39a413e6fd2280c73ad3e4a4
| 5,331
|
cpp
|
C++
|
PendingNameEngine/ModuleCamera3D.cpp
|
GuillemD/PendingNameEngine-3D
|
37454931f14b4b278de1d2898d032c822f754618
|
[
"MIT"
] | null | null | null |
PendingNameEngine/ModuleCamera3D.cpp
|
GuillemD/PendingNameEngine-3D
|
37454931f14b4b278de1d2898d032c822f754618
|
[
"MIT"
] | null | null | null |
PendingNameEngine/ModuleCamera3D.cpp
|
GuillemD/PendingNameEngine-3D
|
37454931f14b4b278de1d2898d032c822f754618
|
[
"MIT"
] | null | null | null |
#include "Globals.h"
#include "Application.h"
#include "ModuleCamera3D.h"
ModuleCamera3D::ModuleCamera3D(Application* app, bool start_enabled) : Module(start_enabled)
{
CalculateViewMatrix();
X = vec3(1.0f, 0.0f, 0.0f);
Y = vec3(0.0f, 1.0f, 0.0f);
Z = vec3(0.0f, 0.0f, 1.0f);
Position = vec3(0.0f, 0.0f, 5.0f);
Reference = vec3(0.0f, 0.0f, 0.0f);
Sensitivity = 0.40f;
}
ModuleCamera3D::~ModuleCamera3D()
{}
// -----------------------------------------------------------------
bool ModuleCamera3D::Start()
{
LOG("Setting up the camera");
bool ret = true;
return ret;
}
// -----------------------------------------------------------------
bool ModuleCamera3D::CleanUp()
{
LOG("Cleaning camera");
return true;
}
// -----------------------------------------------------------------
update_status ModuleCamera3D::Update(float dt)
{
if (ImGui::IsMouseHoveringAnyWindow())
return UPDATE_CONTINUE;
vec3 newPos(0, 0, 0);
float speed = 20.0f * dt;
if (App->input->GetKey(SDL_SCANCODE_LSHIFT) == KEY_REPEAT)
speed = 60.0f * dt;
if (App->input->GetMouseButton(SDL_BUTTON_RIGHT) == KEY_REPEAT)
{
if (App->input->GetKey(SDL_SCANCODE_Q) == KEY_REPEAT) newPos.y += speed; //UP
if (App->input->GetKey(SDL_SCANCODE_E) == KEY_REPEAT) newPos.y -= speed; //DOWN
if (App->input->GetKey(SDL_SCANCODE_W) == KEY_REPEAT) newPos -= Z * speed; //FORWARD
if (App->input->GetKey(SDL_SCANCODE_S) == KEY_REPEAT) newPos += Z * speed; //BACKWARD
if (App->input->GetKey(SDL_SCANCODE_A) == KEY_REPEAT) newPos -= X * speed; //LEFT
if (App->input->GetKey(SDL_SCANCODE_D) == KEY_REPEAT) newPos += X * speed; //RIGHT
Position += newPos;
Reference += newPos;
}
if (App->input->GetMouseZ() > 0)
{
newPos -= Z * speed; //ZOOM IN
Position += newPos;
Reference += newPos;
}
if (App->input->GetMouseZ() < 0) {
newPos += Z * speed;//ZOOM OUT
Position += newPos;
Reference += newPos;
}
// Mouse motion ----------------
if ((App->input->GetKey(SDL_SCANCODE_LALT) == KEY_REPEAT && App->input->GetMouseButton(SDL_BUTTON_LEFT))) //orbit around center
{
int dx = -App->input->GetMouseXMotion();
int dy = -App->input->GetMouseYMotion();
Position -= Reference;
if (dx != 0)
{
float DeltaX = (float)dx * Sensitivity;
X = rotate(X, DeltaX, vec3(0.0f, 1.0f, 0.0f));
Y = rotate(Y, DeltaX, vec3(0.0f, 1.0f, 0.0f));
Z = rotate(Z, DeltaX, vec3(0.0f, 1.0f, 0.0f));
}
if (dy != 0)
{
float DeltaY = (float)dy * Sensitivity;
Y = rotate(Y, DeltaY, X);
Z = rotate(Z, DeltaY, X);
if (Y.y < 0.0f)
{
Z = vec3(0.0f, Z.y > 0.0f ? 1.0f : -1.0f, 0.0f);
Y = cross(Z, X);
}
}
Position = Reference + Z * length(Position);
LookAt({ 0,0,0 });
}
if (App->input->GetKey(SDL_SCANCODE_F) == KEY_DOWN)
{
if (App->scene_loader->scene_objects.empty())
{
Position.x = 0.0f; Position.y = 10.0f; Position.z = 10.0f;
LookAt(vec3(0.0f, 3.0f, 0.0f));
}
else
{
Focus(App->scene_loader->scene_objects.front()->outside_box);
}
}
// Recalculate matrix -------------
CalculateViewMatrix();
return UPDATE_CONTINUE;
}
// -----------------------------------------------------------------
void ModuleCamera3D::Look(const vec3 &Position, const vec3 &Reference, bool RotateAroundReference)
{
this->Position = Position;
this->Reference = Reference;
Z = normalize(Position - Reference);
X = normalize(cross(vec3(0.0f, 1.0f, 0.0f), Z));
Y = cross(Z, X);
if (!RotateAroundReference)
{
this->Reference = this->Position;
this->Position += Z * 0.05f;
}
CalculateViewMatrix();
}
// -----------------------------------------------------------------
void ModuleCamera3D::LookAt(const vec3 &Spot)
{
Reference = Spot;
Z = normalize(Position - Reference);
X = normalize(cross(vec3(0.0f, 1.0f, 0.0f), Z));
Y = cross(Z, X);
CalculateViewMatrix();
}
// -----------------------------------------------------------------
void ModuleCamera3D::Move(const vec3 &Movement)
{
Position += Movement;
Reference += Movement;
CalculateViewMatrix();
}
void ModuleCamera3D::Focus(AABB& box)
{
/*Sphere tmp = box_focus.MinimalEnclosingSphere();
float radius = tmp.r;
float fov = DegToRad(60);
float camDistance = (radius * 2.0) / Tan(fov / 2.0);
Position = vec3(target - Position) * camDistance;*/
float3 cam_pos = box.CenterPoint();
vec3 target = { cam_pos.x, cam_pos.y, cam_pos.z }; //convert to be able to LookAt
cam_pos.x += box.Diagonal().x + box.HalfDiagonal().x;
cam_pos.z -= box.Diagonal().y + box.HalfDiagonal().y;
cam_pos.y += box.Diagonal().z + box.HalfDiagonal().z;
Position.x = cam_pos.x;
Position.y = cam_pos.y;
Position.z = cam_pos.z;
LookAt(target);
CalculateViewMatrix();
}
// -----------------------------------------------------------------
float* ModuleCamera3D::GetViewMatrix()
{
return &ViewMatrix;
}
// -----------------------------------------------------------------
void ModuleCamera3D::CalculateViewMatrix()
{
ViewMatrix = mat4x4(X.x, Y.x, Z.x, 0.0f, X.y, Y.y, Z.y, 0.0f, X.z, Y.z, Z.z, 0.0f, -dot(X, Position), -dot(Y, Position), -dot(Z, Position), 1.0f);
ViewMatrixInverse = inverse(ViewMatrix);
}
void ModuleCamera3D::ShowCameraConfiguration()
{
ImGui::Text("Camera x: %f", Position.x);
ImGui::Text("Camera y: %f", Position.y);
ImGui::Text("Camera z: %f", Position.z);
}
| 23.077922
| 147
| 0.575877
|
GuillemD
|
77a87c176ea569acdd576dd7abaf9b768be02a78
| 3,323
|
cpp
|
C++
|
src/dale/Form/Proc/Token/Token.cpp
|
ChengCat/dale
|
4a764895611679cd1670d9a43ffdbee136661759
|
[
"BSD-3-Clause"
] | 1,083
|
2015-03-18T09:42:49.000Z
|
2022-03-29T03:17:47.000Z
|
src/dale/Form/Proc/Token/Token.cpp
|
ChengCat/dale
|
4a764895611679cd1670d9a43ffdbee136661759
|
[
"BSD-3-Clause"
] | 195
|
2015-01-04T03:06:41.000Z
|
2022-03-18T18:16:27.000Z
|
src/dale/Form/Proc/Token/Token.cpp
|
ChengCat/dale
|
4a764895611679cd1670d9a43ffdbee136661759
|
[
"BSD-3-Clause"
] | 56
|
2015-03-18T20:02:13.000Z
|
2022-01-22T19:35:27.000Z
|
#include "Token.h"
#include <cstdio>
#include <string>
#include "../../../llvmUtils/llvmUtils.h"
#include "../../Literal/Literal.h"
using namespace dale::ErrorInst;
namespace dale {
void parseVariableLiteral(Context *ctx, llvm::BasicBlock *block,
Node *node, bool get_address,
Type *wanted_type, ParseResult *pr) {
Token *t = node->token;
Variable *var = ctx->getVariable(t->str_value.c_str());
if (!var) {
Error *e =
new Error(VariableNotInScope, node, t->str_value.c_str());
ctx->er->addError(e);
return;
}
llvm::IRBuilder<> builder(block);
if (get_address) {
pr->set(block, ctx->tr->getPointerType(var->type), var->value);
return;
}
/* Array-type variables. */
if (var->type->is_array) {
if (wanted_type && var->type->isEqualTo(wanted_type)) {
llvm::Value *array = builder.CreateLoad(var->value);
pr->set(block, var->type, array);
pr->value_is_lvalue = false;
} else {
llvm::Value *ptr_to_array = builder.CreateGEP(
var->value, ctx->nt->getTwoLLVMZeros());
pr->set(block,
ctx->tr->getPointerType(var->type->array_type),
ptr_to_array);
pr->address_of_value = var->value;
pr->value_is_lvalue = true;
pr->type_of_address_of_value =
ctx->tr->getPointerType(var->type);
}
return;
}
if (!var->value) {
Error *e = new Error(CannotDereferencePointerInContext, node);
ctx->er->addError(e);
return;
}
/* All other variables. */
pr->set(block, var->type,
llvm::cast<llvm::Value>(builder.CreateLoad(var->value)));
pr->address_of_value = var->value;
pr->value_is_lvalue = 1;
}
bool FormProcTokenParse(Units *units, Function *fn,
llvm::BasicBlock *block, Node *node,
bool get_address, bool prefixed_with_core,
Type *wanted_type, ParseResult *pr) {
Context *ctx = units->top()->ctx;
Token *t = node->token;
if (t->type == TokenType::Int) {
FormIntegerLiteralParse(ctx, wanted_type, block, t, pr);
return true;
} else if (t->type == TokenType::FloatingPoint) {
FormFloatingPointLiteralParse(ctx, wanted_type, block, t, pr);
return true;
}
if (t->type == TokenType::String) {
pr->set(pr->block, pr->type, NULL);
FormBoolLiteralParse(ctx, block, node, pr);
if (pr->getValue(ctx)) {
return true;
}
FormCharLiteralParse(ctx, block, node, pr);
if (pr->getValue(ctx)) {
return true;
}
parseVariableLiteral(ctx, block, node, get_address, wanted_type,
pr);
if (pr->getValue(ctx)) {
return true;
} else {
return false;
}
} else if (t->type == TokenType::StringLiteral) {
pr->set(pr->block, pr->type, NULL);
FormStringLiteralParse(units, ctx, block, node, pr);
return true;
} else {
Error *e = new Error(UnableToParseForm, node);
ctx->er->addError(e);
return false;
}
}
}
| 29.669643
| 72
| 0.543786
|
ChengCat
|
77aad21385da384b45e18359fea0eff151c200ad
| 6,998
|
hxx
|
C++
|
include/Mapper.hxx
|
broken-bytes/ControllerKit
|
1045d304c613455f3564d7d225b8a6ed90c8a48a
|
[
"MIT"
] | null | null | null |
include/Mapper.hxx
|
broken-bytes/ControllerKit
|
1045d304c613455f3564d7d225b8a6ed90c8a48a
|
[
"MIT"
] | null | null | null |
include/Mapper.hxx
|
broken-bytes/ControllerKit
|
1045d304c613455f3564d7d225b8a6ed90c8a48a
|
[
"MIT"
] | 1
|
2020-12-03T09:55:03.000Z
|
2020-12-03T09:55:03.000Z
|
#pragma once
#include <bitset>
#include <map>
#include <memory>
#include <winrt/Windows.Gaming.Input.h>
#include "ControllerKit.hxx"
using namespace winrt::Windows::Gaming::Input;
namespace BrokenBytes::ControllerKit::Mapping {
/// <summary>
/// Holds the raw bianry values for each DPad state on DualSense and Dualshock(3?)4 devices
/// </summary>
enum class DS_DPad_Bin {
Up = 0x00,
RightUp = 0x01,
Right = 0x02,
RightDown = 0x03,
Down = 0x04,
LeftDown = 0x05,
Left = 0x06,
LeftUp = 0x07,
None = 0x08
};
inline auto InputReportFromXBoxOne(const GamepadReading& input)->Internal::InputReport {
auto buttons = std::map<uint8_t, uint8_t>();
buttons.emplace(
static_cast<uint8_t>(A),
static_cast<uint8_t>(input.Buttons & GamepadButtons::A)
);
buttons.emplace(
static_cast<uint8_t>(B),
static_cast<uint8_t>(input.Buttons & GamepadButtons::B)
);
buttons.emplace(
static_cast<uint8_t>(X),
static_cast<uint8_t>(input.Buttons & GamepadButtons::X)
);
buttons.emplace(
static_cast<uint8_t>(Y),
static_cast<uint8_t>(input.Buttons & GamepadButtons::Y)
);
buttons.emplace(
static_cast<uint8_t>(LB),
static_cast<uint8_t>(input.Buttons & GamepadButtons::LeftShoulder)
);
buttons.emplace(
static_cast<uint8_t>(RB),
static_cast<uint8_t>(input.Buttons & GamepadButtons::RightShoulder)
);
buttons.emplace(
static_cast<uint8_t>(View),
static_cast<uint8_t>(input.Buttons & GamepadButtons::View)
);
buttons.emplace(
static_cast<uint8_t>(Menu),
static_cast<uint8_t>(input.Buttons & GamepadButtons::Menu)
);
buttons.emplace(
static_cast<uint8_t>(L3),
static_cast<uint8_t>(input.Buttons & GamepadButtons::LeftThumbstick)
);
buttons.emplace(
static_cast<uint8_t>(R3),
static_cast<uint8_t>(input.Buttons & GamepadButtons::RightThumbstick)
);
uint8_t dpad = 0;
dpad += static_cast<uint8_t>(input.Buttons & GamepadButtons::DPadLeft) * 1;
dpad += static_cast<uint8_t>(input.Buttons & GamepadButtons::DPadUp) * 2;
dpad += static_cast<uint8_t>(input.Buttons & GamepadButtons::DPadRight) * 4;
dpad += static_cast<uint8_t>(input.Buttons & GamepadButtons::DPadDown) * 8;
Internal::InputReport rep {
buttons,
{
Math::ConvertToUnsignedShort(input.LeftThumbstickX),
Math::ConvertToUnsignedShort(input.LeftThumbstickY)
},
{
Math::ConvertToUnsignedShort(input.RightThumbstickX),
Math::ConvertToUnsignedShort(input.RightThumbstickY)
},
Math::ConvertToUnsignedShort(input.LeftTrigger),
Math::ConvertToUnsignedShort(input.RightTrigger),
dpad
};
return rep;
}
inline auto InputReportFromXBoxSeries()->Internal::InputReport {
//return { };
}
inline auto InputReportFromDualShock4(unsigned char* input)->Internal::InputReport {
auto buttons = std::map<uint8_t, uint8_t>();
std::bitset<8> buff5(input[5]);
buttons.emplace(static_cast<uint8_t>(Cross), buff5[5]);
buttons.emplace(static_cast<uint8_t>(Square), buff5[4]);
buttons.emplace(static_cast<uint8_t>(Circle), buff5[6]);
buttons.emplace(static_cast<uint8_t>(Triangle), buff5[7]);
std::bitset<8> buff6(input[6]);
buttons.emplace(static_cast<uint8_t>(L1), buff6[0]);
buttons.emplace(static_cast<uint8_t>(R1), buff6[1]);
buttons.emplace(static_cast<uint8_t>(R2), buff6[2]);
buttons.emplace(static_cast<uint8_t>(L2), buff6[3]);
buttons.emplace(static_cast<uint8_t>(Share), buff6[4]);
buttons.emplace(static_cast<uint8_t>(Options), buff6[5]);
buttons.emplace(static_cast<uint8_t>(L3), buff6[6]);
buttons.emplace(static_cast<uint8_t>(R3), buff6[7]);
std::bitset<8> buff7(input[6]);
buttons.emplace(static_cast<uint8_t>(PS), buff6[0]);
buttons.emplace(static_cast<uint8_t>(TouchPad), buff6[1]);
ControllerKitDPadDirection dpad = DPadNone;
switch (input[5] & 0x000F) {
case static_cast<uint8_t>(DS_DPad_Bin::Up):
dpad = DPadUp;
break;
case static_cast<uint8_t>(DS_DPad_Bin::RightUp) :
dpad = DPadRightUp;
break;
case static_cast<uint8_t>(DS_DPad_Bin::Right) :
dpad = DPadRight;
break;
case static_cast<uint8_t>(DS_DPad_Bin::RightDown) :
dpad = DPadRightDown;
break;
case static_cast<uint8_t>(DS_DPad_Bin::Down) :
dpad = DPadDown;
break;
case static_cast<uint8_t>(DS_DPad_Bin::LeftDown):
dpad = DPadLeftDown;
break;
case static_cast<uint8_t>(DS_DPad_Bin::Left) :
dpad = DPadLeft;
break;
case static_cast<uint8_t>(DS_DPad_Bin::LeftUp) :
dpad = DPadLeftUp;
break;
case static_cast<uint8_t>(DS_DPad_Bin::None) :
dpad = DPadNone;
break;
}
Internal::InputReport report{
buttons,
{
input[1],
input[2]
},
{
input[3],
input[4]
},
input[8],
input[9],
static_cast<uint8_t>(dpad)
};
return report;
}
inline auto InputReportFromDualSense(unsigned char* input)->Internal::InputReport {
auto buttons = std::map<uint8_t, uint8_t>();
buttons.emplace(static_cast<uint8_t>(Cross), (bool)(input[8] & 0x20));
buttons.emplace(static_cast<uint8_t>(Square), (bool)(input[8] & 0x10));
buttons.emplace(static_cast<uint8_t>(Circle), (bool)(input[8] & 0x40));
buttons.emplace(static_cast<uint8_t>(Triangle), (bool)(input[8] & 0x80));
buttons.emplace(static_cast<uint8_t>(L1), (bool)(input[9] & 0x01));
buttons.emplace(static_cast<uint8_t>(R1), (bool)(input[9] & 0x02));
buttons.emplace(static_cast<uint8_t>(L2), (bool)(input[9] & 0x04));
buttons.emplace(static_cast<uint8_t>(R2), (bool)(input[9] & 0x08));
buttons.emplace(static_cast<uint8_t>(Create), (bool)(input[9] & 0x10));
buttons.emplace(static_cast<uint8_t>(Options), (bool)(input[9] & 0x20));
buttons.emplace(static_cast<uint8_t>(L3), (bool)(input[9] & 0x40));
buttons.emplace(static_cast<uint8_t>(R3), (bool)(input[9] & 0x80));
buttons.emplace(static_cast<uint8_t>(PS), (bool)(input[10] & 0x01));
buttons.emplace(static_cast<uint8_t>(PS_MUTE), (bool)(input[10] & 0x04));
buttons.emplace(static_cast<uint8_t>(TouchPad), (bool)(input[10] & 0x02));
ControllerKitDPadDirection dpad = DPadNone;
switch (input[8] & 0x000F) {
case static_cast<uint8_t>(DS_DPad_Bin::Up) :
dpad = DPadUp;
break;
case static_cast<uint8_t>(DS_DPad_Bin::RightUp) :
dpad = DPadRightUp;
break;
case static_cast<uint8_t>(DS_DPad_Bin::Right) :
dpad = DPadRight;
break;
case static_cast<uint8_t>(DS_DPad_Bin::RightDown) :
dpad = DPadRightDown;
break;
case static_cast<uint8_t>(DS_DPad_Bin::Down) :
dpad = DPadDown;
break;
case static_cast<uint8_t>(DS_DPad_Bin::LeftDown) :
dpad = DPadLeftDown;
break;
case static_cast<uint8_t>(DS_DPad_Bin::Left) :
dpad = DPadLeft;
break;
case static_cast<uint8_t>(DS_DPad_Bin::LeftUp) :
dpad = DPadLeftUp;
break;
case static_cast<uint8_t>(DS_DPad_Bin::None) :
dpad = DPadNone;
break;
}
Internal::InputReport report{
buttons,
{
input[1],
input[2]
},
{
input[3],
input[4]
},
input[5],
input[6],
static_cast<uint8_t>(dpad)
};
return report;
}
}
| 30.034335
| 92
| 0.698485
|
broken-bytes
|
77b3359f6740744239f4f502c8d07931b3ed1eec
| 994
|
cpp
|
C++
|
src/losses/MeanSquareLoss.cpp
|
AvocadoML/Avocado
|
9595cc5994d916f0ecb24873a5afa98437977fb5
|
[
"Apache-2.0"
] | null | null | null |
src/losses/MeanSquareLoss.cpp
|
AvocadoML/Avocado
|
9595cc5994d916f0ecb24873a5afa98437977fb5
|
[
"Apache-2.0"
] | null | null | null |
src/losses/MeanSquareLoss.cpp
|
AvocadoML/Avocado
|
9595cc5994d916f0ecb24873a5afa98437977fb5
|
[
"Apache-2.0"
] | null | null | null |
/*
* MeanSquareLoss.cpp
*
* Created on: Feb 16, 2021
* Author: Maciej Kozarzewski
*/
#include <Avocado/losses/MeanSquareLoss.hpp>
#include <Avocado/core/Scalar.hpp>
#include <Avocado/math/training.hpp>
#include <Avocado/utils/json.hpp>
#include <Avocado/utils/static_block.hpp>
namespace avocado
{
static_block
{
registerLossFunction(MeanSquareLoss());
}
Scalar MeanSquareLoss::getLoss(const Context &context, const Tensor &output, const Tensor &target) const
{
return math::calcLossFunction(context, LossType::MEAN_SQUARE_LOSS, output, target);
}
void MeanSquareLoss::getGradient(const Context &context, Tensor &gradient, const Tensor &output, const Tensor &target) const
{
math::calcLossGradient(context, LossType::MEAN_SQUARE_LOSS, 1, 1, gradient, output, target, false);
}
std::string MeanSquareLoss::name() const
{
return "MeanSquareLoss";
}
MeanSquareLoss* MeanSquareLoss::clone() const
{
return new MeanSquareLoss();
}
} /* namespace avocado */
| 24.243902
| 125
| 0.739437
|
AvocadoML
|
77b38b5f9951d4f59d7dffe1272a9e9c5fe7ee3d
| 516
|
hpp
|
C++
|
include/RED4ext/Types/generated/FunctionalTestsGameEngine.hpp
|
Sombra0xCC/RED4ext.SDK
|
218b411991ed0b7cb7acd5efdddd784f31c66f20
|
[
"MIT"
] | 1
|
2021-02-01T23:07:50.000Z
|
2021-02-01T23:07:50.000Z
|
include/RED4ext/Types/generated/FunctionalTestsGameEngine.hpp
|
Sombra0xCC/RED4ext.SDK
|
218b411991ed0b7cb7acd5efdddd784f31c66f20
|
[
"MIT"
] | null | null | null |
include/RED4ext/Types/generated/FunctionalTestsGameEngine.hpp
|
Sombra0xCC/RED4ext.SDK
|
218b411991ed0b7cb7acd5efdddd784f31c66f20
|
[
"MIT"
] | null | null | null |
#pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
#include <RED4ext/Common.hpp>
#include <RED4ext/REDhash.hpp>
#include <RED4ext/Types/generated/CGameEngine.hpp>
namespace RED4ext
{
struct FunctionalTestsGameEngine : CGameEngine
{
static constexpr const char* NAME = "FunctionalTestsGameEngine";
static constexpr const char* ALIAS = NAME;
uint8_t unk2C8[0x2F68 - 0x2C8]; // 2C8
};
RED4EXT_ASSERT_SIZE(FunctionalTestsGameEngine, 0x2F68);
} // namespace RED4ext
| 24.571429
| 68
| 0.765504
|
Sombra0xCC
|
77b8dad5cca440350383b113d361b111af2ac779
| 1,289
|
cpp
|
C++
|
eclipse/sdblib/src/SDBString.cpp
|
ccpgh/example1
|
2c84b56455ce1cacac69db20b4081fc9c073270d
|
[
"MIT"
] | null | null | null |
eclipse/sdblib/src/SDBString.cpp
|
ccpgh/example1
|
2c84b56455ce1cacac69db20b4081fc9c073270d
|
[
"MIT"
] | null | null | null |
eclipse/sdblib/src/SDBString.cpp
|
ccpgh/example1
|
2c84b56455ce1cacac69db20b4081fc9c073270d
|
[
"MIT"
] | null | null | null |
#include <algorithm>
#include <functional>
#include <cstring>
#include <memory>
#include "SDBString.h"
namespace sdblib {
std::string SDBString::ltrim(const std::string& string) {
std::string s{string};
s.erase(s.begin(), std::find_if(s.begin(), s.end(),
std::not1(std::ptr_fun<int, int>(std::isspace))));
return s;
}
std::string SDBString::rtrim(const std::string& string) {
std::string s{string};
s.erase(std::find_if(s.rbegin(), s.rend(),
std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
return s;
}
std::string SDBString::trim(const std::string& string) {
std::string s{string};
return ltrim(rtrim(s));
}
std::string SDBString::trim(const char* const string) {
std::string s{string};
return trim(s);
}
std::string SDBString::basename(const char* const string) {
if (!string ||
!std::strlen(string)) {
return "";
}
std::string s{string};
size_t position{s.find_last_of('/')};
if (position == std::string::npos) {
return s;
}
return s.substr(position + 1);
}
char* SDBString::clone(const std::string& string) {
const size_t length{string.length()};
char* buffer{new char[length+1]};
memset(buffer, 0, sizeof(char)*(length+1));
strncpy(buffer, string.c_str(), length);
return buffer;
}
}
| 21.131148
| 78
| 0.647789
|
ccpgh
|
77b98cd865fcc85db3290e37cecf2f64851a2165
| 3,454
|
hpp
|
C++
|
include/cppdevtk/config/architecture.hpp
|
CoSoSys/cppdevtk
|
99d6c3d328c05a55dae54e82fcbedad93d0cfaa0
|
[
"BSL-1.0",
"Apache-2.0"
] | null | null | null |
include/cppdevtk/config/architecture.hpp
|
CoSoSys/cppdevtk
|
99d6c3d328c05a55dae54e82fcbedad93d0cfaa0
|
[
"BSL-1.0",
"Apache-2.0"
] | null | null | null |
include/cppdevtk/config/architecture.hpp
|
CoSoSys/cppdevtk
|
99d6c3d328c05a55dae54e82fcbedad93d0cfaa0
|
[
"BSL-1.0",
"Apache-2.0"
] | null | null | null |
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// \file
///
/// \copyright Copyright (C) 2015 - 2020 CoSoSys Ltd <info@cososys.com>\n
/// Licensed under the Apache License, Version 2.0 (the "License");\n
/// you may not use this file except in compliance with the License.\n
/// You may obtain a copy of the License at\n
/// http://www.apache.org/licenses/LICENSE-2.0\n
/// Unless required by applicable law or agreed to in writing, software\n
/// distributed under the License is distributed on an "AS IS" BASIS,\n
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n
/// See the License for the specific language governing permissions and\n
/// limitations under the License.\n
/// Please see the file COPYING.
///
/// \authors Cristian ANITA <cristian.anita@cososys.com>, <cristian_anita@yahoo.com>
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#ifndef CPPDEVTK_CONFIG_ARCHITECTURE_HPP_INCLUDED_
#define CPPDEVTK_CONFIG_ARCHITECTURE_HPP_INCLUDED_
#include "features.hpp"
/// \defgroup config_architecture Architecture
/// \ingroup config
/// @{
/// \defgroup config_architecture_supported_architectures Supported Architectures
/// \sa https://sourceforge.net/p/predef/wiki/Architectures
/// @{
/// \brief X86 architecture.
///
/// Example:
/// \code
/// #if (CPPDEVTK_ARCHITECTURE_X86)
/// // X86 specific code
/// #endif
/// \endcode
#if (defined(i386) || defined(__i386) || defined(__i386__) || defined(_M_IX86))
# define CPPDEVTK_ARCHITECTURE_X86 1
#else
# define CPPDEVTK_ARCHITECTURE_X86 0
#endif
/// \brief X86_64 architecture.
///
/// Example:
/// \code
/// if (CPPDEVTK_ARCHITECTURE_X86_64)
/// // X86_64 specific code
/// #endif
/// \endcode
#if (defined(__amd64__) || defined(__amd64) || defined(__x86_64__) \
|| defined(__x86_64) || defined(_M_X64) || defined(_M_AMD64))
# define CPPDEVTK_ARCHITECTURE_X86_64 1
#else
# define CPPDEVTK_ARCHITECTURE_X86_64 0
#endif
/// \brief ARM architecture.
///
/// Example:
/// \code
/// if (CPPDEVTK_ARCHITECTURE_ARM)
/// // ARM specific code
/// #endif
/// \endcode
#if (defined(__arm__) || defined(_M_ARM))
# define CPPDEVTK_ARCHITECTURE_ARM 1
#else
# define CPPDEVTK_ARCHITECTURE_ARM 0
#endif
/// \brief ARM64 architecture.
///
/// Example:
/// \code
/// if (CPPDEVTK_ARCHITECTURE_ARM64)
/// // ARM64 specific code
/// #endif
/// \endcode
#ifdef __aarch64__
# define CPPDEVTK_ARCHITECTURE_ARM64 1
#else
# define CPPDEVTK_ARCHITECTURE_ARM64 0
#endif
/// \brief Current architecture.
///
/// Example:
/// \code
/// #if (CPPDEVTK_ARCHITECTURE_X86)
/// // X86 specific code
/// #elif (CPPDEVTK_ARCHITECTURE_X86_64)
/// // X86_64 specific code
/// #elif (CPPDEVTK_ARCHITECTURE_ARM)
/// // ARM specific code
/// #elif (CPPDEVTK_ARCHITECTURE_ARM64)
/// // ARM64 specific code
/// #else
/// # error "Unsupported architecture!!!"
/// #endif
/// \endcode
// Safety check.
#if (!(CPPDEVTK_ARCHITECTURE_X86 || CPPDEVTK_ARCHITECTURE_X86_64 \
|| CPPDEVTK_ARCHITECTURE_ARM || CPPDEVTK_ARCHITECTURE_ARM64))
# error "Unsupported architecture!!!"
#endif
/// @} // config_architecture_supported_architectures
/// @} // config_architecture
#endif // CPPDEVTK_CONFIG_ARCHITECTURE_HPP_INCLUDED_
| 28.545455
| 126
| 0.644181
|
CoSoSys
|
77c5503f7f07bc722fbdfc93fe3833bd108f0109
| 2,647
|
cpp
|
C++
|
src/db/block.cpp
|
WeeJang/fish-db
|
4dc50568e0f531c76b8f44e531d0db8e1f6d158a
|
[
"MIT"
] | 2
|
2017-12-12T07:54:38.000Z
|
2021-12-21T15:17:36.000Z
|
src/db/block.cpp
|
WeeJang/fish-db
|
4dc50568e0f531c76b8f44e531d0db8e1f6d158a
|
[
"MIT"
] | null | null | null |
src/db/block.cpp
|
WeeJang/fish-db
|
4dc50568e0f531c76b8f44e531d0db8e1f6d158a
|
[
"MIT"
] | null | null | null |
#include "block.h"
namespace db {
void BlockData::write(const char* p_data, size_t data_size) {
assert(data_size <= BLOCK_DATA_SIZE_LIMIT);
init();
memcpy(data_, p_data, data_size);
}
// NOTE: this
constexpr char Block::BLOCK_MAGIC_NUM[8];
void Block::dump(const std::string& filename) {
strcpy(magic_num_, BLOCK_MAGIC_NUM);
int fd = open(filename.c_str(), O_WRONLY | O_TRUNC | O_CREAT, 0666);
if (fd == -1) {
printf("open file %s failed !\n", filename.c_str());
exit(-1);
}
if (::write(fd, this, get_flexible_size_of_block()) == -1) {
printf("write file %s failed !\n", filename.c_str());
exit(-1);
}
close(fd);
}
//----------------------helper function---------------------//
std::unique_ptr<Block, std::function<void(Block*)>> create_block_by_raw_data(
const char* p_data, size_t data_size) {
assert(data_size <= BlockData::BLOCK_DATA_SIZE_LIMIT);
std::vector<uint32_t> offset_list;
offset_list.push_back(0);
for (size_t cur_data_pos = 0; cur_data_pos < data_size;) {
if (*(p_data + cur_data_pos) == '\n') {
offset_list.push_back(++cur_data_pos);
} else {
++cur_data_pos;
}
}
if (*(p_data + data_size - 1) == '\n') {
offset_list.pop_back();
}
size_t flexible_block_size =
sizeof(Block) +
(offset_list.size() - 1) * sizeof(Block::row_data_offset_type);
char* buf = (char*)malloc(flexible_block_size);
Block* p_block = new (buf) Block;
auto deleter = [buf](Block* p_block) {
p_block->~Block();
free(buf);
};
p_block->row_count(offset_list.size());
for (int i = 0; i < offset_list.size(); i++) {
p_block->insert_row_data_offset(i, offset_list[i]);
}
p_block->write(p_data, data_size);
// TODO : check_sum_
return std::unique_ptr<Block, std::function<void(Block*)>>(p_block, deleter);
}
std::unique_ptr<Block, std::function<void(Block*)>> load_from_disk_by_mmap(
const std::string filename) {
int fd = ::open(filename.c_str(), O_RDONLY, 0666);
if (fd == -1) {
printf("open file %s failed !\n", filename.c_str());
exit(-1);
}
struct stat file_st;
if (fstat(fd, &file_st) == -1) {
printf("get file state of %s failed!\n", filename.c_str());
exit(-1);
}
auto len = file_st.st_size;
Block* p_block = (Block*)mmap(nullptr, len, PROT_READ, MAP_SHARED, fd, 0);
if (p_block == nullptr || p_block == (void*)-1) {
printf("mmap file %s failed !\n", filename.c_str());
exit(-1);
}
auto deleter = [fd, len](Block* p_block) {
munmap(p_block, len);
close(fd);
};
return std::unique_ptr<Block, std::function<void(Block*)>>(p_block, deleter);
}
} // namespace db
| 29.087912
| 79
| 0.628636
|
WeeJang
|
77c731cf41282d3b347a67fc41ca33fb1a05b294
| 7,070
|
cpp
|
C++
|
sedit.cpp
|
Llewellynvdm/id3
|
b6413124856b1eb170f81b2f66cecf1f13235673
|
[
"BSD-2-Clause"
] | 108
|
2015-01-16T16:05:07.000Z
|
2022-03-31T12:13:51.000Z
|
sedit.cpp
|
Llewellynvdm/id3
|
b6413124856b1eb170f81b2f66cecf1f13235673
|
[
"BSD-2-Clause"
] | 26
|
2015-05-27T00:00:51.000Z
|
2022-02-20T15:03:44.000Z
|
sedit.cpp
|
Llewellynvdm/id3
|
b6413124856b1eb170f81b2f66cecf1f13235673
|
[
"BSD-2-Clause"
] | 11
|
2016-07-18T22:15:22.000Z
|
2022-03-13T00:45:31.000Z
|
#include <string>
#include <vector>
#include <algorithm>
#include <cwctype>
#include <cctype>
#include "sedit.h"
/*
copyright (c) 2006 squell <squell@alumina.nl>
use, modification, copying and distribution of this software is permitted
under the conditions described in the file 'COPYING'.
*/
using namespace std;
using namespace charset;
/*
<wctype.h> was added in the 1994 Amd. to C; __STDC_VERSION__ >= 199409L
It is therefore part of the C++ standard, but support varies; autoconf?
*/
#if defined(__FreeBSD__) && (__FreeBSD__ < 5) \
|| defined(__DJGPP__) || defined(__BORLANDC__)
# define to_upper toupper
# define to_lower tolower
# define is_(what, c) is##what(c)
#else
# define to_upper towupper
# define to_lower towlower
# define is_(what, c) isw##what(c)
#endif
namespace {
enum style { as_is, name, lowr, split };
struct filtered_char { // filter low-ascii
bool operator()(wchar_t c)
{ return c == '_' || is_(cntrl, c); }
};
struct both_space { // filter ascii space
bool operator()(wchar_t a, wchar_t b)
{ return is_(space, a) && is_(space, b); }
};
struct char_to_lower {
wchar_t operator()(wchar_t c)
{ return to_lower(c); }
};
// compress(" bla bla ") -> "bla bla"
void compress(wstring& s)
{
wstring::iterator p = unique(s.begin(), s.end(), both_space());
if(p != s.begin() && is_(space, p[-1])) --p;
s.erase(p, s.end());
if(s.length() > 0 && is_(space, s[0]))
s.erase(s.begin());
}
// noleadzero("(0300/0004)=0075") -> "300/4=75"
void noleadzero(wstring& s)
{
const wchar_t zero[] = L"0";
wstring::size_type p, q = 0;
do {
p = s.find_first_of(zero, q);
q = s.find_first_not_of(zero, p);
if(q == p)
return;
if(p == 0 || !is_(digit, s[p-1])) {
s.erase(p, q-p);
if(s.empty() || !is_(digit,s[p]))
s.insert(p, zero);
q = p+1;
}
} while(1);
}
// capitalize("hElLo wOrLd") -> "Hello World"
void capitalize(wstring& s)
{
bool new_w = true;
for(wstring::iterator p = s.begin(); p != s.end(); ++p) {
*p = new_w? to_upper(*p):to_lower(*p);
new_w = is_(space, *p) || !is_(alnum, *p) && new_w;
}
}
// padcamels("ReformatAStringLikeThis") -> "Reformat A String Like This"
void padcamels(wstring& s)
{
wstring::const_iterator p;
bool word = false;
wstring r;
for(p = s.begin(); p != s.end(); r.push_back(*p++)) {
if(is_(upper, *p) && word)
r.push_back(' ');
word = !is_(space, *p);
}
s.swap(r);
}
// padnumeric("(300/4)=75", 4) -> "0300/0004=0075"
void padnumeric(wstring& s, unsigned pad)
{
const wchar_t digits[] = L"0123456789";
wstring::size_type p, q = 0;
do {
p = s.find_first_of (digits, q);
q = s.find_first_not_of(digits, p);
wstring::size_type l = ((q==wstring::npos)? s.length() : q) - p;
if(q == p)
return;
if(l < pad) {
s.insert(p, pad-l, '0');
l = pad;
}
q = p + l;
} while(1);
}
wchar_t codepoint(wstring::const_iterator& p, wstring::const_iterator const q, int digits)
{
long val = 0;
for( ; digits-- && p < q; ++p) {
wchar_t c = to_upper(*p);
if(is_(digit, c)) c -= '0';
else if(c >= 'A' && c <= 'F') c -= 'A'-10;
else break;
val = val << 4 | (c&0xF);
}
return val;
}
} // end of anon. namespace
namespace stredit {
function::result format::edit(const wstring& format, bool atomic) const
{
conv<wchar_t> build;
build.reserve(format.length());
int validity = -true;
for(ptr p = format.begin(); p < format.end(); ) {
switch(wchar_t c = *p++) {
case '\\': // leaves trailing slashes
if(p != format.end()) switch(c = *p++) {
case '\\': c = '\\'; break;
case 'a': c = '\a'; break;
case 'b': c = '\b'; break;
case 'f': c = '\f'; break;
case 'n': c = '\n'; break; /* ?append carriage returns? */
case 'r': c = '\r'; break;
case 't': c = '\t'; break;
case 'v': c = '\v'; break;
case 'u': c = codepoint(p, format.end(), 4); break;
case 'U': c = codepoint(p, format.end(), 8); break;
}
default:
build += c;
break;
case prefix:
result subst = code(--p, format.end());
build += subst;
if(!subst) {
validity = validity > false;
continue;
}
}
if(!atomic) validity = true;
}
return result(build, validity);
}
function::result format::code(ptr& p, ptr end) const
{
vector<wstring> alt;
style caps = as_is;
bool raw = false;
unsigned num_pad = 0;
for(++p; p != end; ) {
switch(wchar_t c = *p++) {
case '_': raw = true; continue;
case '+': caps = name; continue;
case '-': caps = lowr; continue;
case '*': caps = split; continue;
case '#': ++num_pad; continue;
case prefix:
return conv<wchar_t>(1, prefix);
case '|': {
ptr q = matching(p-1, end);
if(alt.size() < 25) // artificial limit
alt.push_back(wstring(p, q));
if(q == end) break;
p = ++q;
continue;
}
default :
result subst = var(--p, end);
if(!subst.good()) for(unsigned i = 0; i < alt.size(); ++i)
if(result tmp = edit(alt[i], true)) {
subst = tmp;
break;
}
wstring s = conv<wchar_t>(subst);
if(!raw) { // remove gunk
replace_if(s.begin(), s.end(), filtered_char(), ' ');
compress(s);
}
if(caps == split)
padcamels(s);
if(caps == name)
capitalize(s);
if(caps == lowr)
transform(s.begin(), s.end(), s.begin(), char_to_lower());
if(num_pad > 0)
noleadzero(s);
padnumeric(s, num_pad);
return result(conv<wchar_t>(s), subst.good());
}
break;
}
return false;
}
format::ptr format::matching(ptr p, ptr end) const
{
unsigned nesting = 1, one = 1;
wchar_t delim = *p++;
while(p != end) {
switch(wchar_t c = *p++) {
case prefix: // start of nesting?
one = -one; break;
case '\\': // ignore escaped char
if(p == end) break;
++p;
default :
if(c == delim && (nesting-=one) == 0) return --p;
one = 1;
}
}
return p;
}
} // end namespace
| 26.984733
| 90
| 0.478784
|
Llewellynvdm
|
77cd6560740b74eb056658a8309fa7d61fb11c3a
| 3,516
|
cpp
|
C++
|
test/utils/Configuration.cpp
|
hpc/hxhim
|
1a2224a200cb5a9fae33da13720e68beb5bee746
|
[
"BSD-3-Clause"
] | 2
|
2020-11-25T17:45:58.000Z
|
2021-12-21T02:01:16.000Z
|
test/utils/Configuration.cpp
|
hpc/hxhim
|
1a2224a200cb5a9fae33da13720e68beb5bee746
|
[
"BSD-3-Clause"
] | null | null | null |
test/utils/Configuration.cpp
|
hpc/hxhim
|
1a2224a200cb5a9fae33da13720e68beb5bee746
|
[
"BSD-3-Clause"
] | 1
|
2021-10-11T19:54:05.000Z
|
2021-10-11T19:54:05.000Z
|
#include <sstream>
#include <gtest/gtest.h>
#include "utils/Configuration.hpp"
// Context for reading configuration from a string
class ConfigOnePair : public Config::Reader {
public:
ConfigOnePair(const std::string &src)
: Config::Reader(),
src(src)
{}
bool process(Config::Config &config) const {
std::string key, value;
if (std::stringstream(src) >> key >> value) {
config[key] = value;
return true;
}
return false;
}
private:
const std::string src;
};
TEST(ConfigSequence, add) {
Config::Sequence sequence;
ConfigOnePair first("KEY1 VALUE1");
EXPECT_EQ(sequence.add(&first), (std::size_t) 1);
ConfigOnePair second("KEY2 VALUE2");
EXPECT_EQ(sequence.add(&second), (std::size_t) 2);
// read the configuration
Config::Config config;
sequence.process(config);
EXPECT_EQ(config.size(), (std::size_t) 2);
EXPECT_EQ(config.at("KEY1"), "VALUE1");
EXPECT_EQ(config.at("KEY2"), "VALUE2");
}
TEST(ConfigSequence, reset) {
Config::Sequence sequence;
// add to first config reader
ConfigOnePair first("KEY1 VALUE1");
EXPECT_EQ(sequence.add(&first), (std::size_t) 1);
EXPECT_EQ(sequence.reset(), 0);
// add to second config reader (overwrites first)
ConfigOnePair second("KEY2 VALUE2");
EXPECT_EQ(sequence.add(&second), (std::size_t) 1);
EXPECT_EQ(sequence.reset(), 0);
// read the configuration
Config::Config config;
sequence.process(config);
EXPECT_EQ(config.size(), (std::size_t) 0);
}
TEST(ConfigSequence, overwrite) {
Config::Sequence sequence;
// add to first config reader
ConfigOnePair first("KEY VALUE1");
EXPECT_EQ(sequence.add(&first), (std::size_t) 1);
// add to second config reader (overwrites first)
ConfigOnePair second("KEY VALUE2");
EXPECT_EQ(sequence.add(&second), (std::size_t) 2);
// read the configuration
Config::Config config;
sequence.process(config);
EXPECT_EQ(config.size(), (std::size_t) 1);
EXPECT_EQ(config.at("KEY"), "VALUE2");
}
TEST(ConfigEnvironmentVar, usage) {
const std::string env_var = "TEST_ENV_VAR";
const std::string var = "TEST_VAR";
const std::string val = "VALUE";
Config::EnvironmentVar cve(env_var, var);
Config::Config config;
// remove the variable from the environment if it already exists
// doesn't affect anything unless the test executable is sourced,
// which should not be done
EXPECT_EQ(unsetenv(env_var.c_str()), 0);
// did not get anything
EXPECT_EQ(cve.process(config), false);
// set the environment variable
EXPECT_EQ(setenv(env_var.c_str(), val.c_str(), 1), 0);
// get the value from the environment
// val should be stored in var, not env_var
EXPECT_EQ(cve.process(config), true);
EXPECT_EQ(config.at(var), val);
}
// defined in src/utils/Configuration.cpp
bool parse_kv_stream(Config::Config &config, std::istream &stream);
TEST(Config, parse_kv_stream) {
Config::Config config;
// value with space in the middle and trailing whitespace
std::stringstream s1("KEY1 VALUE1 VALUE2 ");
EXPECT_EQ(parse_kv_stream(config, s1), true);
EXPECT_EQ(config.at("KEY1"), "VALUE1 VALUE2");
// key with no value
std::stringstream s2("KEY2 ");
EXPECT_EQ(parse_kv_stream(config, s2), true);
EXPECT_EQ(config.at("KEY2"), "");
}
| 27.685039
| 69
| 0.643629
|
hpc
|
77ce52941a47394c9e715143cdc9d25c574f6c93
| 542
|
cpp
|
C++
|
algo2.cpp
|
zyfjeff/utils_code
|
034b1a0ff9ae4f7cebafdd7cfa464cc52119ab24
|
[
"Apache-2.0"
] | null | null | null |
algo2.cpp
|
zyfjeff/utils_code
|
034b1a0ff9ae4f7cebafdd7cfa464cc52119ab24
|
[
"Apache-2.0"
] | null | null | null |
algo2.cpp
|
zyfjeff/utils_code
|
034b1a0ff9ae4f7cebafdd7cfa464cc52119ab24
|
[
"Apache-2.0"
] | 1
|
2020-02-21T17:16:50.000Z
|
2020-02-21T17:16:50.000Z
|
#include <cinttypes>
#include <iostream>
#include <vector>
using namespace std;
int main(int argc,char* argv[])
{
using IntVector = vector<int32_t>;
using IntVectorIterator = IntVector::iterator;
IntVector myVector{5,0};
int32_t value{0};
for(IntVectorIterator iter = myVector.begin();iter != myVector.end();++iter)
{
cout << "before The value is: " << *iter << endl;
*iter = value++;
}
for(IntVectorIterator iter = myVector.begin();iter != myVector.end();++iter)
{
cout << "after The value is: " << *iter << endl;
}
return 0;
}
| 20.074074
| 76
| 0.671587
|
zyfjeff
|
77ce69163fc01cb61bc487c0a282f69b98d495be
| 2,070
|
hpp
|
C++
|
test/TestDatastore.hpp
|
hpc/hxhim
|
1a2224a200cb5a9fae33da13720e68beb5bee746
|
[
"BSD-3-Clause"
] | 2
|
2020-11-25T17:45:58.000Z
|
2021-12-21T02:01:16.000Z
|
test/TestDatastore.hpp
|
hpc/hxhim
|
1a2224a200cb5a9fae33da13720e68beb5bee746
|
[
"BSD-3-Clause"
] | null | null | null |
test/TestDatastore.hpp
|
hpc/hxhim
|
1a2224a200cb5a9fae33da13720e68beb5bee746
|
[
"BSD-3-Clause"
] | 1
|
2021-10-11T19:54:05.000Z
|
2021-10-11T19:54:05.000Z
|
#ifndef TEST_DATASTORE_HPP
#define TEST_DATASTORE_HPP
#include <map>
#include "datastore/datastore.hpp"
const std::chrono::microseconds PUT_TIME(123);
const std::chrono::microseconds GET_TIME(456);
const uint64_t PUT_TIME_UINT64 = std::chrono::duration_cast<std::chrono::nanoseconds>(PUT_TIME).count();
const uint64_t GET_TIME_UINT64 = std::chrono::duration_cast<std::chrono::nanoseconds>(GET_TIME).count();
class TestDatastore : public Datastore::Datastore {
public:
TestDatastore(const int id)
: Datastore::Datastore(0, id, nullptr)
{}
private:
bool OpenImpl(const std::string &) { return true; }
void CloseImpl() {}
bool UsableImpl() const {return true; }
Message::Response::BPut *BPutImpl(Message::Request::BPut *req) {
Datastore::Datastore::Stats::Event event;
event.time.start = ::Stats::now();
event.count = 1;
event.time.end = event.time.start + PUT_TIME;
stats.puts.emplace_back(event);
Message::Response::BPut *res = construct<Message::Response::BPut>(req->count);
res->count = req->count;
for(std::size_t i = 0; i < req->count; i++) {
res->statuses[i] = DATASTORE_SUCCESS;
}
return res;
}
Message::Response::BGet *BGetImpl(Message::Request::BGet *) {
Datastore::Datastore::Stats::Event event;
event.time.start = ::Stats::now();
event.count = 1;
event.time.end = event.time.start + GET_TIME;
stats.gets.emplace_back(event);
return nullptr;
}
Message::Response::BGetOp *BGetOpImpl(Message::Request::BGetOp *) { return nullptr; }
Message::Response::BDelete *BDeleteImpl(Message::Request::BDelete *) { return nullptr; }
int WriteHistogramsImpl() { return DATASTORE_SUCCESS; }
std::size_t ReadHistogramsImpl(const ::Datastore::HistNames_t &) { return 0; }
int SyncImpl() { return DATASTORE_SUCCESS; }
};
#endif
| 35.084746
| 104
| 0.617391
|
hpc
|
77d57415ada825d8bcbb793de03e0056c4eea7e7
| 377
|
cpp
|
C++
|
TongueQT/TongueQT/src/ColorTable/Colortable.cpp
|
lrkk1234/TongueSimulation
|
347cf38452aa62d1173da1c4935f691456255e46
|
[
"MIT"
] | 2
|
2020-03-28T03:15:49.000Z
|
2020-09-09T02:54:33.000Z
|
TongueQT/TongueQT/src/ColorTable/Colortable.cpp
|
lrkk1234/TongueSimulation
|
347cf38452aa62d1173da1c4935f691456255e46
|
[
"MIT"
] | null | null | null |
TongueQT/TongueQT/src/ColorTable/Colortable.cpp
|
lrkk1234/TongueSimulation
|
347cf38452aa62d1173da1c4935f691456255e46
|
[
"MIT"
] | 2
|
2020-09-08T19:28:19.000Z
|
2021-07-25T00:35:26.000Z
|
#include "Colortable.h"
int getColor(int index, double* colors)
{
int tablesize = sizeof(colortable) / sizeof(float)/3;
index %= tablesize;
colors[0] = colortable[index * 3 + 0];
colors[1] = colortable[index * 3 + 1];
colors[2] = colortable[index * 3 + 2];
return 0;
}
int getColorSize()
{
int tablesize = sizeof(colortable) / sizeof(float) / 3;
return tablesize;
}
| 19.842105
| 56
| 0.668435
|
lrkk1234
|
77d636a01dd3ac962f7cc3689ccda991d9924013
| 20,444
|
hpp
|
C++
|
old.sets.hpp
|
JanX2/red-black-and-interval-trees
|
4b78646b63ac95dfaac5c3756cfd1ebf4d165a32
|
[
"BSD-3-Clause"
] | null | null | null |
old.sets.hpp
|
JanX2/red-black-and-interval-trees
|
4b78646b63ac95dfaac5c3756cfd1ebf4d165a32
|
[
"BSD-3-Clause"
] | 1
|
2018-10-30T21:19:23.000Z
|
2018-10-30T21:19:23.000Z
|
old.sets.hpp
|
JanX2/red-black-and-interval-trees
|
4b78646b63ac95dfaac5c3756cfd1ebf4d165a32
|
[
"BSD-3-Clause"
] | null | null | null |
// Note that until the bug in egcs-2.90.27 980315 (egcs-1.0.2 release)
// gets fixed this file needs to be compiled with -fguiding-decls.
// Trying to fix the warning caused by compiling without -fguiding-decls
// causes an internal compiler error.
#ifndef _INC_SETS_DOT_H
#define _INC_SETS_DOT_H
#include<stdio.h>
#include<stdlib.h>
#include<iostream.h>
#include<strstream.h>
#include<tcl.h>
#include<ctype.h>
// **********************************************************************
//
// See the html documentation for how to use these classes
//
// This file implements sets through tcl hash tables.
// See the html documentation accesed through ~/indev/lithas/docs/html/gui.html
// for information on how to use these data structures.
//
// **********************************************************************
// The SetDatabase is intended to be accessed only by the SetDatabaseHandle
// class. This allows an instance of SetDatabase to be pointed
// to by an aribtrary number of SetDatabaseHandle instances. When
// the last SetDatabaseHandle instance stops pointing to a database,
// the database deletes itself.
//
// The advantages of this approach are:
//
// (1) If more than one thing wants to point to a given database,
// we don't have to make copies of the database or jump through
// hoops to make sure memory is managed properly.
//
// (2) Passing the database around is much easier because no class
// that holds the database has to worry about who owns the
// database.
typedef Tcl_HashEntry * SetEntryToken;
const SetEntryToken STE_NULL_TOKEN = NULL;
template <class KeyClass, class ValueClass> class SetDatabaseHandle;
template <class KeyClass, class ValueClass> class SetDatabaseHandleIterator;
template <class KeyClass, class ValueClass>
class SetDatabase {
friend class SetDatabaseHandleIterator<KeyClass,ValueClass>;
friend class SetDatabaseHandle<KeyClass,ValueClass>;
friend inline void GrabDb(SetDatabase *);
friend inline void LetGoDb(SetDatabase *);
friend ostream & operator<<(ostream & s, const SetDatabase & d);
friend istream & operator>>(istream & s, SetDatabase & d);
public:
inline int GetKeyType() const {return databaseKeyType;}
inline int Size() const {return itemsInTable;}
// WARNING: DANGER: casting going on here
ValueClass Search( const KeyClass key, int * found) const
{
Tcl_HashEntry * entry =
Tcl_FindHashEntry((Tcl_HashTable*)(&hashTable), (char *) key);
if (entry == NULL) {
if (found != NULL) *found = 0;
return (ValueClass) NULL;
}
if (found != NULL) *found = 1;
return (ValueClass) Tcl_GetHashValue(entry);
}
void ForEachItemInSetDo(void (*function)(KeyClass key,ValueClass value))
{
Tcl_HashSearch searchPtr;
Tcl_HashEntry * currentEntry = Tcl_FirstHashEntry(&hashTable, &searchPtr);
while (currentEntry != NULL) {
KeyClass key = (KeyClass) Tcl_GetHashKey(&hashTable,currentEntry);
ValueClass value = (ValueClass ) Tcl_GetHashValue(currentEntry);
function(key,value);
currentEntry = Tcl_NextHashEntry(&searchPtr);
}
}
void ForEachItemInSetDo(void (*function)(KeyClass key,ValueClass value,
void * extraArg),
void * extraArgForFunction)
{
Tcl_HashSearch searchPtr;
Tcl_HashEntry * currentEntry = Tcl_FirstHashEntry(&hashTable, &searchPtr);
while (currentEntry != NULL) {
KeyClass key = (KeyClass) Tcl_GetHashKey(&hashTable,currentEntry);
ValueClass value = (ValueClass ) Tcl_GetHashValue(currentEntry);
function(key,value,extraArgForFunction);
currentEntry = Tcl_NextHashEntry(&searchPtr);
}
}
int Add( const KeyClass & key, const ValueClass object,
ValueClass * oldObject , SetEntryToken * token)
{
int notAlreadyInTable;
InvalidateIteratorsAttachedToThisDatabase();
*token = Tcl_CreateHashEntry(&hashTable, (char *) key, ¬AlreadyInTable);
if (notAlreadyInTable)
itemsInTable++;
else *oldObject = (ValueClass) Tcl_GetHashValue(*token);
Tcl_SetHashValue(*token,object);
return notAlreadyInTable;
}
int Add( const KeyClass & key, const ValueClass object, SetEntryToken * token)
{
int notAlreadyInTable;
InvalidateIteratorsAttachedToThisDatabase();
*token = Tcl_CreateHashEntry(&hashTable, (char *) key, ¬AlreadyInTable);
if (notAlreadyInTable)
itemsInTable++;
Tcl_SetHashValue(*token,object);
return notAlreadyInTable;
}
int Add( const KeyClass & key, const ValueClass object)
{
int notAlreadyInTable;
InvalidateIteratorsAttachedToThisDatabase();
Tcl_HashEntry * newEntry =
Tcl_CreateHashEntry(&hashTable, (char *) key, ¬AlreadyInTable);
if (notAlreadyInTable)
itemsInTable++;
Tcl_SetHashValue(newEntry,object);
return notAlreadyInTable;
}
void DeleteEntryForToken(SetEntryToken token)
{
InvalidateIteratorsAttachedToThisDatabase();
Tcl_DeleteHashEntry(token);
itemsInTable--;
}
ValueClass Delete( const KeyClass & key, int * found)
{
ValueClass returnValue = (ValueClass) NULL;
Tcl_HashEntry * entry = Tcl_FindHashEntry(&hashTable, (char *) key);
if (entry != NULL) {
InvalidateIteratorsAttachedToThisDatabase();
itemsInTable--;
returnValue = (ValueClass ) Tcl_GetHashValue(entry);
Tcl_DeleteHashEntry(entry);
if (found != NULL) *found = 1;
} else
if (found != NULL) *found = 0;
return returnValue;
}
protected:
SetDatabase(int typeOfKeys)
:numberOfHandlesToThisObject(0), _numberRefs(0),
databaseKeyType(typeOfKeys) ,
itemsInTable(0), _IDNumber(0)
{
Tcl_InitHashTable(&hashTable, typeOfKeys);
}
~SetDatabase()
{
Assert(_numberRefs == 0,"deleting database with references");
Tcl_DeleteHashTable(&hashTable);
}
bool MatchesIDNumber(const int IDNumber) {return IDNumber == _IDNumber;}
void InvalidateIteratorsAttachedToThisDatabase()
{
#ifdef CHECK_ASSUMPTIONS
_IDNumber++;
#endif
}
int numberOfHandlesToThisObject;
int _numberRefs;
Tcl_HashTable hashTable;
int databaseKeyType;
int itemsInTable;
private:
SetDatabase( const SetDatabase &); // no one should use this!
int _IDNumber;
};
template <class KeyClass, class ValueClass>
class SetDatabaseHandle {
friend class SetDatabaseHandleIterator<KeyClass,ValueClass>;
friend SetDatabaseHandle operator&(SetDatabaseHandle &,
SetDatabaseHandle &);
friend SetDatabaseHandle operator|(SetDatabaseHandle &,
SetDatabaseHandle &);
friend SetDatabaseHandle operator-(SetDatabaseHandle &,
SetDatabaseHandle &);
friend ostream& operator<<(ostream&,const SetDatabaseHandle<KeyClass,ValueClass>&);
friend istream& operator>>(istream&,SetDatabaseHandle<KeyClass,ValueClass>&);
public:
SetDatabaseHandle(int typeOfKeys)
:database(new SetDatabase<KeyClass,ValueClass>(typeOfKeys))
{
GrabDb(database);
}
SetDatabaseHandle(SetDatabase<KeyClass,ValueClass> * d)
:database(d)
{
GrabDb(d);
}
SetDatabaseHandle(SetDatabaseHandle * c)
:database(c->database)
{
GrabDb(c->database);
}
SetDatabaseHandle( const SetDatabaseHandle & c)
:database(c.database)
{
GrabDb(c.database);
}
~SetDatabaseHandle()
{
LetGoDb(database);
}
SetDatabaseHandle & operator=(const SetDatabaseHandle &);
bool operator==(const SetDatabaseHandle &);
bool operator!=(const SetDatabaseHandle &);
inline void ForEachItemInSetDo(void (*function)(KeyClass key,
ValueClass value))
{
database->ForEachItemInSetDo(function);
}
inline void ForEachItemInSetDo(void (*function)(KeyClass , ValueClass ,
void * extraArg),
void * extraArgForFunction)
{
database->ForEachItemInSetDo(function,extraArgForFunction);
}
inline int Size() const {return database->Size();}
inline ValueClass Search( const KeyClass object, int * found = NULL) const
{
return database->Search(object,found);
}
inline ValueClass Delete(KeyClass k,int * found = NULL)
{return database->Delete(k,found);}
inline void DeleteEntryForToken(SetEntryToken token)
{database->DeleteEntryForToken(token);}
inline int Add( const KeyClass & key, const ValueClass object)
{
return database->Add(key,object);
}
inline int Add
( const KeyClass & key, const ValueClass object, SetEntryToken * token)
{
return database->Add(key,object,token);
}
inline int Add
( const KeyClass & key, const ValueClass object,
ValueClass * oldObject, SetEntryToken * token)
{
return database->Add(key,object,oldObject,token);
}
protected:
// The LetGoDb function decrements the number of things pointing
// to s by 1. If the number of things pointing to s goes below
// 1, then s is delete'd. This handles the memory management
// for the SetDatabase class pointed to by the SetDatabaseHandles.
void LetGoDb(SetDatabase<KeyClass,ValueClass> * s){
if (--(s->numberOfHandlesToThisObject) < 1) delete s;}
// The Grab function increments the number of things pointing
// to s by 1. See the comment for the LetGoDb function for
// more information.
void GrabDb(SetDatabase<KeyClass,ValueClass> * s)
{s->numberOfHandlesToThisObject++;}
bool MatchesIDNumber(const int IDNumber) const
{return database->MatchesIDNumber(IDNumber);}
inline Tcl_HashTable * GetDatabaseHashTable(){return &(database->hashTable);}
SetDatabase<KeyClass,ValueClass> * database;
// these two routines are for maintaining a count of references
// to values inside the database, because the database should not
// be deleted if the number of refs != 0
void LetGoRef()
{database->_numberRefs--;}
void GrabRef()
{database->_numberRefs++;}
bool HasRef() const
{return (database->_numberRefs != 0);}
// indicate if this is the only handle
// may be needed to delete objects if this handle is about to die
bool OnlyHandle() const
{return (database->numberOfHandlesToThisObject == 1);}
};
/* **********************************************************************
*
* FUNCTION: AndDatabases
*
* INPUTS: smaller is the smaller Tcl_HashTable to and with larger
* larger is the larger Tcl_HashTable to and with smaller
* result is where the (smaller & larger) is stored.
*
* OUTPUT: none
*
* PURPOSE: This function goes through every item in smaller.
* Each item that is also present in larger is added
* to result. This function is meant to be used bye operator&.
*
* MODIFIED: Emin Martinian, emin@iname.com, Wed Jan 14 13:08:57 PST 1998
*
********************************************************************** */
template <class KeyClass, class ValueClass>
void AndDatabases(Tcl_HashTable * smaller,
Tcl_HashTable * larger,
SetDatabase<KeyClass,ValueClass> * result)
{
Tcl_HashSearch searchPtr;
Tcl_HashEntry * currentEntry = Tcl_FirstHashEntry(smaller, &searchPtr);
while (currentEntry != NULL) {
KeyClass key = (KeyClass) Tcl_GetHashKey(smaller,currentEntry);
if (NULL != Tcl_FindHashEntry(larger, (char *) key))
result->Add(key,(ValueClass) Tcl_GetHashValue(currentEntry));
currentEntry = Tcl_NextHashEntry(&searchPtr);
}
}
/* **********************************************************************
*
* FUNCTION: SubtractDatabases
*
* INPUTS: negative is the database to be subtracted from positive
* result is set to contain everything in positive that is
* not in negative.
*
* OUTPUT: none
*
* PURPOSE: This "Subtracts" everything in the negative hash table
* from the positive hash table and stores the result in
* result. This function is meant to be used by operator-.
*
* MODIFIED: Emin Martinian, emin@iname.com, Wed Jan 14 13:11:06 PST 1998
*
********************************************************************** */
template <class KeyClass, class ValueClass>
void SubtractDatabases(Tcl_HashTable * positive,
Tcl_HashTable * negative,
SetDatabase<KeyClass, ValueClass> * result)
{
Tcl_HashSearch searchPtr;
Tcl_HashEntry * currentEntry = Tcl_FirstHashEntry(positive, &searchPtr);
while (currentEntry != NULL) {
KeyClass key = (KeyClass) Tcl_GetHashKey(positive,currentEntry);
if (NULL == Tcl_FindHashEntry(negative, (char *) key))
result->Add(key,(ValueClass ) Tcl_GetHashValue(currentEntry));
currentEntry = Tcl_NextHashEntry(&searchPtr);
}
}
/* **********************************************************************
*
* FUNCTION: MergeDatabases
*
* INPUTS: Everything in the input hash table is put into the
* result database.
*
* OUTPUT: none
*
* PURPOSE: This puts everything in input into result to implement
* operator|.
*
* MODIFIED: Emin Martinian, emin@iname.com, Wed Jan 14 13:39:24 PST 1998
*
********************************************************************** */
template <class KeyClass, class ValueClass>
void MergeDatabases(Tcl_HashTable * input,
SetDatabase<KeyClass,ValueClass> * result)
{
Tcl_HashSearch searchPtr;
Tcl_HashEntry * currentEntry = Tcl_FirstHashEntry(input, &searchPtr);
while (currentEntry != NULL) {
result->Add((KeyClass) Tcl_GetHashKey(input,currentEntry),
(ValueClass ) Tcl_GetHashValue(currentEntry));
currentEntry = Tcl_NextHashEntry(&searchPtr);
}
}
/* **********************************************************************
*
* FUNCTION: operator|
*
* INPUTS: a and b are SetDatabaseHandles to combine
*
* OUTPUT: returns a SetDatabaseHandle containing everything in a and b.
*
* PURPOSE: This is used to implement a union of the two input sets.
*
* MODIFIED: Emin Martinian, emin@iname.com, Wed Jan 14 13:41:02 PST 1998
*
********************************************************************** */
template <class KeyClass, class ValueClass>
SetDatabaseHandle<KeyClass,ValueClass>
operator|(SetDatabaseHandle<KeyClass,ValueClass> & a,
SetDatabaseHandle<KeyClass,ValueClass> & b)
{
ASSUME(a.database->GetKeyType() == b.database->GetKeyType());
SetDatabaseHandle<KeyClass,ValueClass> result(a.database->GetKeyType());
MergeDatabases(a.GetDatabaseHashTable(),result.database);
MergeDatabases(b.GetDatabaseHashTable(),result.database);
return result;
}
/* **********************************************************************
*
* FUNCTION: operator&
*
* INPUTS: a and b are SetDatabaseHandles to intersect
*
* OUTPUT: returns a new SetDatabaseHandle containing the intersection
* of a nd b.
*
* PURPOSE: This is used to implement the intersection of two sets.
*
* MODIFIED: Emin Martinian, emin@iname.com, Wed Jan 14 13:42:27 PST 1998
*
********************************************************************** */
template <class KeyClass, class ValueClass>SetDatabaseHandle<KeyClass,ValueClass>
operator&(SetDatabaseHandle<KeyClass,ValueClass> & a,
SetDatabaseHandle<KeyClass,ValueClass> & b)
{
ASSUME(a.database->GetKeyType() == b.database->GetKeyType());
SetDatabaseHandle<KeyClass,ValueClass> result(a.database->GetKeyType());
if (a.database->Size() < b.database->Size())
AndDatabases(a.GetDatabaseHashTable(),
b.GetDatabaseHashTable(),
result.database);
else
AndDatabases(b.GetDatabaseHashTable(),
a.GetDatabaseHashTable(),
result.database);
return result;
}
/* **********************************************************************
*
* FUNCTION: operator-
*
* INPUTS: b is subtracted from a
*
* OUTPUT: Returns a new SetDatabaseHandle containing everything that
* is in a but not in b.
*
* PURPOSE: This implements subtraction of sets.
*
* MODIFIED: Emin Martinian, emin@iname.com, Wed Jan 14 13:43:31 PST 1998
*
********************************************************************** */
template <class KeyClass, class ValueClass>SetDatabaseHandle<KeyClass,ValueClass>
operator-(SetDatabaseHandle<KeyClass,ValueClass> &a,
SetDatabaseHandle<KeyClass,ValueClass> &b)
{
ASSUME(a.database->GetKeyType() == b.database->GetKeyType());
SetDatabaseHandle<KeyClass,ValueClass> result(a.database->GetKeyType());
SubtractDatabases(a.GetDatabaseHashTable(),
b.GetDatabaseHashTable(),
result.database);
return result;
}
template <class KeyClass, class ValueClass>
SetDatabaseHandle<KeyClass,ValueClass> &
SetDatabaseHandle<KeyClass,ValueClass>::operator=
(const SetDatabaseHandle<KeyClass,ValueClass> & other)
{
if (other.database != database) {
LetGoDb(database);
database = other.database;
GrabDb(database);
}
return *this;
}
template <class KeyClass, class ValueClass>
bool
SetDatabaseHandle<KeyClass,ValueClass>::operator==
(const SetDatabaseHandle<KeyClass,ValueClass> & other)
{
return (other.database == database);
}
template <class KeyClass, class ValueClass>
bool
SetDatabaseHandle<KeyClass,ValueClass>::operator!=
(const SetDatabaseHandle<KeyClass,ValueClass> & other)
{
return (other.database != database);
}
template <class KeyClass, class ValueClass>
ostream & operator<<(ostream & s, const SetDatabase<KeyClass,ValueClass> & d)
{
Tcl_HashSearch searchPtr;
Tcl_HashEntry * currentEntry =
Tcl_FirstHashEntry((Tcl_HashTable *) // this cast discards the const
&(d.hashTable), &searchPtr);
while (currentEntry != NULL) {
KeyClass key = Tcl_GetHashKey(&(d.hashTable),currentEntry);
s << "{{" << (KeyClass) key << "} ";
s << "{" << (ValueClass) Tcl_GetHashValue(currentEntry) << "}} " ;
currentEntry = Tcl_NextHashEntry(&searchPtr);
}
return s;
}
template <class KeyClass, class ValueClass>
ostream & operator<<(ostream & s, const SetDatabaseHandle<KeyClass,ValueClass> & h)
{
s << *(h.database);
return s;
}
template <class KeyClass, class ValueClass>
istream & operator>>(istream & s, SetDatabase<KeyClass,ValueClass> & d)
{
char c;
char ** mainArgv = NULL;
char ** subArgv = NULL;
int mainArgc, subArgc, notInteger, index;
char * inputString = NULL;
while ( (s >> c) && (isspace(c)) ); // eat up white space
if ( (!s) || (c != '{') ) goto stopBecauseOfError;
s.putback(c);
s.gets(&inputString);
if (!s) goto stopBecauseOfError;
if (TCL_OK != (Tcl_SplitList(NULL,inputString,&mainArgc,&mainArgv)))
goto stopBecauseOfError;
for (int i = 0; i < mainArgc; ++i) {
if ( (TCL_OK != (Tcl_SplitList(NULL,mainArgv[i],&subArgc,&subArgv)))
|| (subArgc != 2) ) goto stopBecauseOfError;
index = strtintOnlyCheck(subArgv[1],¬Integer);
if (notInteger || (! d.Add(subArgv[0], index))) goto stopBecauseOfError;
Tcl_Free((char*) subArgv);
subArgv = NULL;
}
delete [] inputString;
Tcl_Free( (char*) mainArgv);
return s;
stopBecauseOfError:
if (mainArgv != NULL) Tcl_Free( (char*) mainArgv);
if (subArgv != NULL) Tcl_Free( (char*) subArgv);
s.clear(ios::badbit); // set state of stream to bad;
if (inputString != NULL) delete [] inputString;
return s;
}
template <class KeyClass, class ValueClass>
istream & operator>>(istream & s, SetDatabaseHandle<KeyClass,ValueClass> & h)
{
s >> *(h.database);
return s;
}
template <class KeyType, class ValueType>
class SetDatabaseHandleIterator {
public:
SetDatabaseHandleIterator(SetDatabaseHandle<KeyType,ValueType> const & handle)
:_handle(handle), _IDNumber(handle.database->_IDNumber),
_currentHashEntry(Tcl_FirstHashEntry(&_handle.database->hashTable,&_searchPtr))
{ }
inline bool ItemsRemaining()
{
return _currentHashEntry != NULL;
}
inline KeyType GetCurrentKey()
{
ASSUME( ItemsRemaining() );
ASSUME( _handle.MatchesIDNumber(_IDNumber) );
return (KeyType) Tcl_GetHashKey(&_handle.database->hashTable,_currentHashEntry);
}
inline ValueType GetCurrentValue()
{
ASSUME( ItemsRemaining() );
ASSUME( _handle.MatchesIDNumber(_IDNumber) );
return (ValueType) Tcl_GetHashValue(_currentHashEntry);
}
KeyType operator++(int) // postfix operator
{
ASSUME(ItemsRemaining());
ASSUME( _handle.MatchesIDNumber(_IDNumber) );
KeyType returnValue =
(KeyType) Tcl_GetHashKey(&_handle.database->hashTable,_currentHashEntry);
_currentHashEntry = Tcl_NextHashEntry(&_searchPtr);
return returnValue;
}
protected:
const SetDatabaseHandle<KeyType,ValueType> & _handle;
int _IDNumber;
Tcl_HashSearch _searchPtr;
Tcl_HashEntry * _currentHashEntry;
};
#endif
| 31.117199
| 86
| 0.676042
|
JanX2
|
77da78662c025ba2b6db6c4ff67e4fdeadd85fb0
| 453
|
hpp
|
C++
|
src/include/XEUI/widgets/UIElement.hpp
|
devxkh/FrankE
|
72faca02759b54aaec842831f3c7a051e7cf5335
|
[
"MIT"
] | 11
|
2017-01-17T15:02:25.000Z
|
2020-11-27T16:54:42.000Z
|
src/include/XEUI/widgets/UIElement.hpp
|
devxkh/FrankE
|
72faca02759b54aaec842831f3c7a051e7cf5335
|
[
"MIT"
] | 9
|
2016-10-23T20:15:38.000Z
|
2018-02-06T11:23:17.000Z
|
src/include/XEUI/widgets/UIElement.hpp
|
devxkh/FrankE
|
72faca02759b54aaec842831f3c7a051e7cf5335
|
[
"MIT"
] | 2
|
2019-08-29T10:23:51.000Z
|
2020-04-03T06:08:34.000Z
|
#ifndef UI_ELEMENT_HPP
#define UI_ELEMENT_HPP
#include <XEOSConfig.hpp>
#include <XEUI/Object.hpp>
#include <XESystem/XEMemory/XEMemoryPrerequisites.hpp>
namespace XE {
namespace UI {
class UIElement : public Object
{
public:
UIElement(Uint32 id)
{
mID = id;
}
Uint32 getID(){ return mID; }
private:
Uint32 mID;
SYS::String mType; // Type button,submenu ..
UIElement* mParent; //parent Element
};
} // namespace UI
} // namespace XE
#endif
| 16.178571
| 54
| 0.719647
|
devxkh
|
77dc4d0f84511377a00b22287cf6d593d2ce2937
| 4,053
|
hpp
|
C++
|
slope/slope/math/quat.hpp
|
muleax/slope
|
254138703163705b57332fc7490dd2eea0082b57
|
[
"MIT"
] | 6
|
2022-02-05T23:28:12.000Z
|
2022-02-24T11:08:04.000Z
|
slope/slope/math/quat.hpp
|
muleax/slope
|
254138703163705b57332fc7490dd2eea0082b57
|
[
"MIT"
] | null | null | null |
slope/slope/math/quat.hpp
|
muleax/slope
|
254138703163705b57332fc7490dd2eea0082b57
|
[
"MIT"
] | null | null | null |
#pragma once
#include "slope/math/vector4.hpp"
namespace slope {
class mat33;
class mat44;
class quat {
public:
static quat rotation(const vec3& axis, float angle);
static quat shortest_arc(const vec3& from, const vec3& to, const vec3& spin_axis);
constexpr quat() : x(0.f), y(0.f), z(0.f), w(1.f) {}
constexpr quat(float x, float y, float z, float w) : x(x), y(y), z(z), w(w) {}
constexpr quat(const vec3& value, float w) : x(value.x), y(value.y), z(value.z), w(w) {}
explicit constexpr quat(const vec4& value) : x(value.x), y(value.y), z(value.z), w(value.w) {}
explicit quat(const mat33& matrix);
explicit quat(const mat44& matrix);
constexpr quat operator*(const quat& rhs) const;
constexpr quat& operator*=(const quat& value);
constexpr quat operator-() const { return { -x, -y, -z, -w }; }
friend constexpr vec3 operator*(const vec3& lhs, const quat& rhs);
friend constexpr vec4 operator*(const vec4& lhs, const quat& rhs);
constexpr bool operator==(const quat& value) const;
constexpr bool operator!=(const quat& value) const;
constexpr float& operator[](size_t index) { return data[index]; }
constexpr const float& operator[](size_t index) const { return data[index]; }
constexpr float length_squared() const { return sqr(x) + sqr(y) + sqr(z) + sqr(w); }
float length() const { return std::sqrt(length_squared()); }
quat normalized() const;
constexpr quat transposed() const { return { -x, -y, -z, w }; }
constexpr quat inverted() const;
bool is_finite() const;
constexpr bool equal(const quat& rhs, float epsilon = EQUALITY_EPSILON) const;
union {
struct {
float x, y, z, w;
};
float data[4]{};
};
};
quat slerp(const quat& from, quat to, float factor);
constexpr quat quat::operator*(const quat& rhs) const
{
float a = (w + x) * (rhs.w + rhs.x);
float b = (z - y) * (rhs.y - rhs.z);
float c = (x - w) * (rhs.y + rhs.z);
float d = (y + z) * (rhs.x - rhs.w);
float e = (x + z) * (rhs.x + rhs.y);
float f = (x - z) * (rhs.x - rhs.y);
float g = (w + y) * (rhs.w - rhs.z);
float h = (w - y) * (rhs.w + rhs.z);
return {
a - ( e + f + g + h) * 0.5f,
-c + ( e - f + g - h) * 0.5f,
-d + ( e - f - g + h) * 0.5f,
b + (-e - f + g + h) * 0.5f };
}
constexpr quat& quat::operator*=(const quat& value)
{
*this = *this * value;
return *this;
}
constexpr bool quat::operator==(const quat& value) const
{
return x == value.x && y == value.y && z == value.z && w == value.w;
}
constexpr bool quat::operator!=(const quat& value) const
{
return x != value.x || y != value.y || z != value.z || w != value.w;
}
constexpr vec3 operator*(const vec3& lhs, const quat& rhs)
{
vec3 a(rhs.x, rhs.y, rhs.z);
vec3 b(a.cross(lhs));
vec3 c(a.cross(b));
return lhs + ((b * rhs.w) + c) * 2.f;
}
constexpr vec4 operator*(const vec4& lhs, const quat& rhs)
{
return {vec3(lhs.x, lhs.y, lhs.z) * rhs, 0.f};
}
inline quat quat::normalized() const
{
float multiplier = 1.f / length();
return {x * multiplier, y * multiplier, z * multiplier, w * multiplier};
}
constexpr quat quat::inverted() const
{
float multiplier = 1.f / length_squared();
quat tr = transposed();
return {tr.x * multiplier, tr.y * multiplier, tr.z * multiplier, tr.w * multiplier};
}
constexpr bool quat::equal(const quat& rhs, float epsilon) const
{
return slope::equal(x, rhs.x, epsilon) &&
slope::equal(y, rhs.y, epsilon) &&
slope::equal(z, rhs.z, epsilon) &&
slope::equal(w, rhs.w, epsilon);
}
inline bool quat::is_finite() const
{
return std::isfinite(x) && std::isfinite(y) && std::isfinite(z) && std::isfinite(w);
}
} // slope
| 31.418605
| 106
| 0.551443
|
muleax
|
77e6ec459efd277db5f79e49a1018eeb50d78e65
| 2,419
|
cpp
|
C++
|
src/material.cpp
|
dylangentile/path_tracer
|
6393bb806a30e377f5d12ffc5f61b004f5a7ce8e
|
[
"MIT"
] | null | null | null |
src/material.cpp
|
dylangentile/path_tracer
|
6393bb806a30e377f5d12ffc5f61b004f5a7ce8e
|
[
"MIT"
] | null | null | null |
src/material.cpp
|
dylangentile/path_tracer
|
6393bb806a30e377f5d12ffc5f61b004f5a7ce8e
|
[
"MIT"
] | null | null | null |
#include "material.h"
#include "object.h"
Material::Material()
{
}
Material::~Material(){}
Color
Material::emitted(double u, double v, const Point3& p) const
{
return Color(0.0, 0.0, 0.0); //by default materials don't emit light
}
Lambertian::Lambertian(const Color& a) : m_albedo(a) {}
Lambertian::~Lambertian(){}
bool
Lambertian::scatter(const Ray& i_ray, const HitData& data, Color* attenuation, Ray* scattered) const
{
vec3 scatter_direction = data.normal + random_unit_vector();
*scattered = Ray(data.p, scatter_direction);
*attenuation = m_albedo;
return true;
}
Metal::Metal(const Color& a, double fuzz) : m_albedo(a), m_fuzz(fuzz < 1 ? fuzz : 1){}
Metal::~Metal(){}
bool
Metal::scatter(const Ray& i_ray, const HitData& data, Color* attenuation, Ray* scattered) const
{
vec3 reflected = reflect(unit_vector(i_ray.direction()), data.normal);
*scattered = Ray(data.p, reflected + m_fuzz*random_in_unit_sphere());
*attenuation = m_albedo;
return dot(scattered->direction(), data.normal) > 0;
}
Dielectric::Dielectric(double ri) : m_ref_idx(ri) {}
Dielectric::~Dielectric(){}
double schlick(double cosine, double ref_idx) {
auto r0 = (1-ref_idx) / (1+ref_idx);
r0 = r0*r0;
return r0 + (1-r0)*pow((1 - cosine),5);
}
bool
Dielectric::scatter(const Ray& i_ray, const HitData& data, Color* attenuation, Ray* scattered) const
{
*attenuation = Color(1.0, 1.0, 1.0);
double etai_over_etat = data.front_face ? (1.0 / m_ref_idx) : m_ref_idx;
vec3 unit_direction = unit_vector(i_ray.direction());
double cos_theta = fmin(dot(-unit_direction, data.normal), 1.0);
double sin_theta = std::sqrt(1.0 - cos_theta*cos_theta);
if (etai_over_etat * sin_theta > 1.0 ) {
vec3 reflected = reflect(unit_direction, data.normal);
*scattered = Ray(data.p, reflected);
return true;
}
double reflect_prob = schlick(cos_theta, etai_over_etat);
if (random_double() < reflect_prob)
{
vec3 reflected = reflect(unit_direction, data.normal);
*scattered = Ray(data.p, reflected);
return true;
}
vec3 refracted = refract(unit_direction, data.normal, etai_over_etat);
*scattered = Ray(data.p, refracted);
return true;
}
DiffuseLight::DiffuseLight(const Color& a) : m_color(a) {}
DiffuseLight::~DiffuseLight(){}
bool
DiffuseLight::scatter(const Ray&, const HitData&, Color*, Ray*) const
{
return false;
}
Color
DiffuseLight::emitted(double, double, const Point3&) const
{
return m_color;
}
| 25.197917
| 100
| 0.710624
|
dylangentile
|
77e7b26d510a83dde1d86b0bdbbadda9d386e9e0
| 511
|
hpp
|
C++
|
include/ananasgfx/ui/design/material/ButtonFlat.hpp
|
pcbaecker/ananasgfx
|
0637554bf82b990713314a24e4a6ead299be949a
|
[
"MIT"
] | 1
|
2019-01-28T13:48:17.000Z
|
2019-01-28T13:48:17.000Z
|
include/ananasgfx/ui/design/material/ButtonFlat.hpp
|
pcbaecker/ananasgfx
|
0637554bf82b990713314a24e4a6ead299be949a
|
[
"MIT"
] | 11
|
2019-01-28T13:59:36.000Z
|
2019-02-09T14:59:23.000Z
|
include/ananasgfx/ui/design/material/ButtonFlat.hpp
|
pcbaecker/ananasgfx
|
0637554bf82b990713314a24e4a6ead299be949a
|
[
"MIT"
] | null | null | null |
#ifndef UI_DESIGN_MATERIAL_BUTTONFLAT_H
#define UI_DESIGN_MATERIAL_BUTTONFLAT_H
#include <ananasgfx/ui/TextButton.hpp>
namespace ui::design::material {
class ButtonFlat : public ui::TextButton {
public:
std::optional<d2::Node *> getBackgroundBlur() noexcept override;
std::optional<d2::Node *> getBackgroundFocus() noexcept override;
d2::Label *getLabel() noexcept override;
densityPixel_t getOptimalHeight(densityPixel_t width) noexcept override;
};
}
#endif
| 24.333333
| 80
| 0.726027
|
pcbaecker
|
77ed2059f1f007c7044f711d64248fa69c18f8b2
| 478
|
cpp
|
C++
|
Algorithms/Cpp-bubble_sort.cpp
|
IffatAzam/Ds-algo
|
2a864f8c1ad71c50730431ebb8f9ba4825e89aaa
|
[
"MIT"
] | 6
|
2020-10-02T17:15:57.000Z
|
2020-10-11T21:09:28.000Z
|
Algorithms/Cpp-bubble_sort.cpp
|
IffatAzam/Ds-algo
|
2a864f8c1ad71c50730431ebb8f9ba4825e89aaa
|
[
"MIT"
] | 5
|
2020-10-02T15:01:12.000Z
|
2020-10-20T04:55:41.000Z
|
Algorithms/Cpp-bubble_sort.cpp
|
IffatAzam/Ds-algo
|
2a864f8c1ad71c50730431ebb8f9ba4825e89aaa
|
[
"MIT"
] | 28
|
2020-10-02T15:34:04.000Z
|
2020-10-29T03:29:08.000Z
|
#include <iostream>
#include <vector>
using namespace std;
vector<int> bubble_sort(vector<int> arr)
{
int n=arr.size();
for (int i = 0; i < n-1; i++)
{
for (int j = i + 1; j < n; j++)
{
if (arr[i] > arr[j])
{
int aux = arr[j];
arr[j] = arr[i];
arr[i] = aux;
}
}
}
return arr;
}
int main()
{
vector<int> arr = { 6, 3, 7, 1, 12, 5, 43, 21 ,8 ,9 };
arr=bubble_sort(arr);
for (int i = 0; i < arr.size(); i++)
cout << arr[i]<< ' ';
}
| 14.058824
| 55
| 0.481172
|
IffatAzam
|
77ed965e84bf66469c07af8082a8e32a67a12bcf
| 602
|
cpp
|
C++
|
src/URI_2061 - (4663412) - Accepted.cpp
|
miguelarauj1o/UOJ
|
eb195754829c42c3dcf1a68616e63da1386cb5a9
|
[
"MIT"
] | 80
|
2015-01-07T01:18:40.000Z
|
2021-05-04T15:23:18.000Z
|
src/URI_2061 - (4663412) - Accepted.cpp
|
miguelarauj1o/OJ
|
eb195754829c42c3dcf1a68616e63da1386cb5a9
|
[
"MIT"
] | 1
|
2019-01-07T01:13:32.000Z
|
2019-01-07T01:13:32.000Z
|
src/URI_2061 - (4663412) - Accepted.cpp
|
miguelarauj1o/OJ
|
eb195754829c42c3dcf1a68616e63da1386cb5a9
|
[
"MIT"
] | 28
|
2015-03-05T11:53:23.000Z
|
2020-07-05T15:50:42.000Z
|
#include <iostream>
#include <cstring>
using namespace std;
int main(int argc, char const *argv[]) {
int n, m, sum = 0;
string s;
cin >> n >> m;
sum = n;
for (int i = 0; i < m; i++) {
cin >> s;
if (s == "fechou") sum++;
else sum--;
}
cout << sum << endl;
return 0;
}#include <iostream>
#include <cstring>
using namespace std;
int main(int argc, char const *argv[]) {
int n, m, sum = 0;
string s;
cin >> n >> m;
sum = n;
for (int i = 0; i < m; i++) {
cin >> s;
if (s == "fechou") sum++;
else sum--;
}
cout << sum << endl;
return 0;
}
| 16.27027
| 41
| 0.498339
|
miguelarauj1o
|
77f36468b41e64c685ba3b62caac9c81f7d8e15d
| 587
|
cpp
|
C++
|
src/GameHost.cpp
|
nicoaw/netroids-prototype
|
ac8b4c75efc136fbd04f27bdb7cc028d5a02f06c
|
[
"MIT"
] | null | null | null |
src/GameHost.cpp
|
nicoaw/netroids-prototype
|
ac8b4c75efc136fbd04f27bdb7cc028d5a02f06c
|
[
"MIT"
] | null | null | null |
src/GameHost.cpp
|
nicoaw/netroids-prototype
|
ac8b4c75efc136fbd04f27bdb7cc028d5a02f06c
|
[
"MIT"
] | null | null | null |
#include "GameHost.h"
GameHost::GameHost()
: time(0)
{
bounds.max = glm::vec2(400.0f, 300.0f);
bounds.min = glm::vec2(-400.0f, -300.0f);
/*input.forward = false;
input.left = false;
input.right = false;*/
}
GameHost::~GameHost()
{
if (host != nullptr)
enet_host_destroy(host);
}
void GameHost::flush()
{
enet_host_flush(host);
}
void GameHost::service()
{
ENetEvent enetEvent;
while (enet_host_service(host, &enetEvent, 0))
handleNetEvent(enetEvent);
}
void GameHost::update(uint32_t time)
{
//ship.update(input, bounds, GameEngine::timestep());
++this->time;
}
| 14.675
| 54
| 0.67121
|
nicoaw
|
af7ebdd6ca1dc2a99dfd1371018700892e4d9eb4
| 2,530
|
hxx
|
C++
|
include/usagi/http/exception.hxx
|
usagi/usagi
|
2d57d21eeb92eadfdf4154a3e470aebfc3e388e5
|
[
"MIT"
] | 2
|
2016-11-20T04:59:17.000Z
|
2017-02-13T01:44:37.000Z
|
include/usagi/http/exception.hxx
|
usagi/usagi
|
2d57d21eeb92eadfdf4154a3e470aebfc3e388e5
|
[
"MIT"
] | 3
|
2015-09-28T12:00:02.000Z
|
2015-09-28T12:03:21.000Z
|
include/usagi/http/exception.hxx
|
usagi/usagi
|
2d57d21eeb92eadfdf4154a3e470aebfc3e388e5
|
[
"MIT"
] | 3
|
2017-07-02T06:09:47.000Z
|
2018-07-09T01:00:57.000Z
|
#pragma once
#include <stdexcept>
#include <string>
namespace usagi::http
{
struct http_error
: std::runtime_error
{
static constexpr unsigned redirection_count_over_value = 996u;
static constexpr unsigned response_has_no_location_header_value = 997u;
static constexpr unsigned response_has_no_status_code_value = 998u;
static constexpr unsigned response_has_no_separator_value = 999u;
const unsigned status = 0u;
explicit http_error( const unsigned http_status_code )
: std::runtime_error( "http error status: " + std::to_string( http_status_code ) )
, status( http_status_code )
{ }
auto client_error() const { return status >= 400u and status < 500u; }
auto bad_request() const { return status == 400u; }
auto unauthorized() const { return status == 401u; }
auto forbidden() const { return status == 403u; }
auto not_found() const { return status == 404u; }
auto request_timeout() const { return status == 408u; }
auto server_error() const { return status >= 500u and status < 600u; }
auto internal_server_error() const { return status == 500u; }
auto not_implemented() const { return status == 501u; }
auto bad_gateway() const { return status == 502u; }
auto service_unavailable() const { return status == 503u; }
auto gateway_timeout() const { return status == 504u; }
auto http_version_not_supported() const { return status == 505u; }
/// @brief 独自拡張コード: レスポンスが壊れていてヘッダーとボディーのスプリッターが無い場合に発行
auto response_has_no_separator() const
{ return status == response_has_no_separator_value; }
/// @brief 独自拡張コード: レスポンスが壊れていてステータスコードが無い場合に発行
auto response_has_no_status_code() const
{ return status == response_has_no_status_code_value; }
/// @brief 独自拡張コード: レスポンスが壊れていてリダイレクションにLocationヘッダーが無い場合に発行
auto response_has_no_location_header() const
{ return status == response_has_no_location_header_value; }
/// @brief 独自拡張コード: リダイレクション回数オーバーした場合に発行
auto redirection_count_over() const
{ return status == redirection_count_over_value; }
/// @brief リトライによって問題が発生しない可能性が高いエラーかどうか
auto could_retry() const
{
return request_timeout()
or internal_server_error()
or service_unavailable()
or gateway_timeout()
;
}
};
}
| 39.53125
| 88
| 0.647431
|
usagi
|
af7f33c21a06dae6922403607fb573c63d4ca03f
| 2,478
|
cc
|
C++
|
tests/sync/oneshot.cc
|
ddxy18/xyco
|
7682652f17b82e2370fa7af17635c5d0c470efe0
|
[
"MIT"
] | null | null | null |
tests/sync/oneshot.cc
|
ddxy18/xyco
|
7682652f17b82e2370fa7af17635c5d0c470efe0
|
[
"MIT"
] | 17
|
2021-10-30T06:10:46.000Z
|
2022-03-18T06:16:15.000Z
|
tests/sync/oneshot.cc
|
ddxy18/xyco
|
7682652f17b82e2370fa7af17635c5d0c470efe0
|
[
"MIT"
] | null | null | null |
#include "sync/oneshot.h"
#include <gtest/gtest.h>
#include <unistd.h>
#include <chrono>
#include <thread>
#include <utility>
#include "utils.h"
TEST(OneshotTest, success) {
TestRuntimeCtx::co_run([]() -> xyco::runtime::Future<void> {
auto [sender, receiver] = xyco::sync::oneshot::channel<int>();
auto send_result = co_await sender.send(1);
auto value = (co_await receiver.receive()).unwrap();
CO_ASSERT_EQ(send_result.is_ok(), true);
CO_ASSERT_EQ(value, 1);
});
}
TEST(OneshotTest, sender_close) {
TestRuntimeCtx::co_run([]() -> xyco::runtime::Future<void> {
auto [sender, receiver] = xyco::sync::oneshot::channel<int>();
sender.xyco::sync::oneshot::Sender<int>::~Sender();
auto value = (co_await receiver.receive());
CO_ASSERT_EQ(value.is_err(), true);
});
}
TEST(OneshotTest, receiver_close) {
TestRuntimeCtx::co_run([]() -> xyco::runtime::Future<void> {
auto [sender, receiver] = xyco::sync::oneshot::channel<int>();
receiver.xyco::sync::oneshot::Receiver<int>::~Receiver();
auto send_result = co_await sender.send(1);
CO_ASSERT_EQ(send_result.unwrap_err(), 1);
});
}
TEST(OneshotTest, send_twice) {
TestRuntimeCtx::co_run([]() -> xyco::runtime::Future<void> {
auto [sender, receiver] = xyco::sync::oneshot::channel<int>();
co_await sender.send(1);
auto send_twice_result = co_await sender.send(1);
CO_ASSERT_EQ(send_twice_result.is_err(), true);
});
}
TEST(OneshotTest, receive_twice) {
TestRuntimeCtx::co_run([]() -> xyco::runtime::Future<void> {
auto [sender, receiver] = xyco::sync::oneshot::channel<int>();
co_await sender.send(1);
co_await receiver.receive();
auto receive_twice_result = co_await receiver.receive();
CO_ASSERT_EQ(receive_twice_result.is_err(), true);
});
}
TEST(OneshotTest, receive_first) {
auto channel_pair = xyco::sync::oneshot::channel<int>();
int value = 0;
auto send_result = Result<void, int>::ok();
std::thread receive([&]() {
TestRuntimeCtx::co_run([&]() -> xyco::runtime::Future<void> {
value = (co_await channel_pair.second.receive()).unwrap();
});
});
std::this_thread::sleep_for(time_deviation); // wait receive pending
std::thread send([&]() {
TestRuntimeCtx::co_run([&]() -> xyco::runtime::Future<void> {
send_result = co_await channel_pair.first.send(1);
});
});
receive.join();
send.join();
ASSERT_EQ(value, 1);
ASSERT_EQ(send_result.is_ok(), true);
}
| 27.842697
| 71
| 0.658999
|
ddxy18
|
af7f9709d1dc21350c587768a1b21f5d62e9bc97
| 3,984
|
cpp
|
C++
|
src/aimp_dotnet/SDK/MusicLibrary/AimpFileList.cpp
|
Smartoteka/aimp_dotnet
|
544502b8d080c9280ba11917ef0cc3e8dec44234
|
[
"Apache-2.0"
] | 52
|
2015-04-14T14:39:30.000Z
|
2022-02-07T07:16:05.000Z
|
src/aimp_dotnet/SDK/MusicLibrary/AimpFileList.cpp
|
Smartoteka/aimp_dotnet
|
544502b8d080c9280ba11917ef0cc3e8dec44234
|
[
"Apache-2.0"
] | 11
|
2015-04-02T10:45:55.000Z
|
2022-02-03T07:21:53.000Z
|
src/aimp_dotnet/SDK/MusicLibrary/AimpFileList.cpp
|
Smartoteka/aimp_dotnet
|
544502b8d080c9280ba11917ef0cc3e8dec44234
|
[
"Apache-2.0"
] | 9
|
2015-04-05T18:25:57.000Z
|
2022-02-07T07:20:23.000Z
|
// ----------------------------------------------------
// AIMP DotNet SDK
// Copyright (c) 2014 - 2020 Evgeniy Bogdan
// https://github.com/martin211/aimp_dotnet
// Mail: mail4evgeniy@gmail.com
// ----------------------------------------------------
#include "Stdafx.h"
#include "AimpFileList.h"
using namespace AIMP::SDK;
AimpFileList::AimpFileList(IAIMPMLFileList* aimpObject) : AimpObject(aimpObject) {
}
ActionResult AimpFileList::Add(Object^ id, String^ fileName) {
IAIMPString* sFileName = AimpConverter::ToAimpString(fileName);
ActionResultType result = ActionResultType::Fail;
try {
result = CheckResult(InternalAimpObject->Add(&AimpConverter::ToNativeVariant(id), sFileName));
}
finally {
if (sFileName != nullptr) {
sFileName->Release();
sFileName = nullptr;
}
}
return ACTION_RESULT(result);
}
ActionResult AimpFileList::Clear() {
return ACTION_RESULT(CheckResult(InternalAimpObject->Clear()));
}
ActionResult AimpFileList::Delete(int index) {
return ACTION_RESULT(CheckResult(InternalAimpObject->Delete(index)));
}
ActionResult AimpFileList::Insert(int index, Object^ id, String^ fileName) {
IAIMPString* sFileName = AimpConverter::ToAimpString(fileName);
ActionResultType result = ActionResultType::Fail;
try {
result = CheckResult(InternalAimpObject->Insert(index, &AimpConverter::ToNativeVariant(id), sFileName));
}
finally {
if (sFileName != nullptr) {
sFileName->Release();
sFileName = nullptr;
}
}
return ACTION_RESULT(result);
}
int AimpFileList::GetCount() {
return InternalAimpObject->GetCount();
}
AimpActionResult<String^>^ AimpFileList::GetFileName(int index) {
IAIMPString* str = nullptr;
String^ fileName = nullptr;
ActionResultType result = ActionResultType::Fail;
try {
result = CheckResult(InternalAimpObject->GetFileName(index, &str));
if (result == ActionResultType::OK && str != nullptr) {
fileName = AimpConverter::ToManagedString(str);
}
}
finally {
if (str != nullptr) {
str->Release();
str = nullptr;
}
}
return gcnew AimpActionResult<String^>(result, fileName);
}
ActionResult AimpFileList::SetFileName(int index, String^ fileName) {
IAIMPString* sFileName = AimpConverter::ToAimpString(fileName);
ActionResultType result = ActionResultType::Fail;
try {
result = CheckResult(InternalAimpObject->SetFileName(index, sFileName));
}
finally {
if (sFileName != nullptr) {
sFileName->Release();
sFileName = nullptr;
}
}
return ACTION_RESULT(result);
}
AimpActionResult<Object^>^ AimpFileList::GetId(int index) {
VARIANT* idVar;
Object^ id = nullptr;
ActionResultType result = ActionResultType::Fail;
try {
result = CheckResult(InternalAimpObject->GetID(index, &idVar));
if (result == ActionResultType::OK) {
id = AimpConverter::FromVaiant(idVar);
}
}
finally {
idVar = nullptr;
}
return gcnew AimpActionResult<Object^>(result, id);
}
ActionResult AimpFileList::SetId(int index, Object^ id) {
return ACTION_RESULT(CheckResult(InternalAimpObject->SetID(index, &AimpConverter::ToNativeVariant(id))));
}
AimpActionResult<IAimpFileList^>^ AimpFileList::Clone() {
IAimpFileList^ list = nullptr;
IAIMPMLFileList* cloneList = nullptr;
ActionResultType res = ActionResultType::Fail;
try {
res = CheckResult(InternalAimpObject->Clone(reinterpret_cast<void**>(&cloneList)));
if (res == ActionResultType::OK) {
list = gcnew AimpFileList(cloneList);
}
}
finally {
if (cloneList != nullptr) {
cloneList->Release();
cloneList = nullptr;
}
}
return gcnew AimpActionResult<IAimpFileList^>(res, list);
}
| 27.102041
| 112
| 0.634287
|
Smartoteka
|
af863aa0c5412c7f5ca9f7159916a0a14fd4f706
| 5,658
|
cpp
|
C++
|
ws/ws_cobra_to_statsd.cpp
|
matt-deboer/IXWebSocket
|
779b1e6077e909f64e5ff2569876f29f4d33da46
|
[
"BSD-3-Clause"
] | null | null | null |
ws/ws_cobra_to_statsd.cpp
|
matt-deboer/IXWebSocket
|
779b1e6077e909f64e5ff2569876f29f4d33da46
|
[
"BSD-3-Clause"
] | null | null | null |
ws/ws_cobra_to_statsd.cpp
|
matt-deboer/IXWebSocket
|
779b1e6077e909f64e5ff2569876f29f4d33da46
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* ws_cobra_to_statsd.cpp
* Author: Benjamin Sergeant
* Copyright (c) 2019 Machine Zone, Inc. All rights reserved.
*/
#include <atomic>
#include <chrono>
#include <iostream>
#include <ixcobra/IXCobraConnection.h>
#include <spdlog/spdlog.h>
#include <sstream>
#include <thread>
#include <vector>
#ifndef _WIN32
#include <statsd_client.h>
#endif
namespace ix
{
// fields are command line argument that can be specified multiple times
std::vector<std::string> parseFields(const std::string& fields)
{
std::vector<std::string> tokens;
// Split by \n
std::string token;
std::stringstream tokenStream(fields);
while (std::getline(tokenStream, token))
{
tokens.push_back(token);
}
return tokens;
}
//
// Extract an attribute from a Json Value.
// extractAttr("foo.bar", {"foo": {"bar": "baz"}}) => baz
//
std::string extractAttr(const std::string& attr, const Json::Value& jsonValue)
{
// Split by .
std::string token;
std::stringstream tokenStream(attr);
Json::Value val(jsonValue);
while (std::getline(tokenStream, token, '.'))
{
val = val[token];
}
return val.asString();
}
int ws_cobra_to_statsd_main(const std::string& appkey,
const std::string& endpoint,
const std::string& rolename,
const std::string& rolesecret,
const std::string& channel,
const std::string& filter,
const std::string& host,
int port,
const std::string& prefix,
const std::string& fields,
bool verbose)
{
ix::CobraConnection conn;
conn.configure(
appkey, endpoint, rolename, rolesecret, ix::WebSocketPerMessageDeflateOptions(true));
conn.connect();
auto tokens = parseFields(fields);
// statsd client
// test with netcat as a server: `nc -ul 8125`
bool statsdBatch = true;
#ifndef _WIN32
statsd::StatsdClient statsdClient(host, port, prefix, statsdBatch);
#else
int statsdClient;
#endif
Json::FastWriter jsonWriter;
uint64_t msgCount = 0;
conn.setEventCallback([&conn,
&channel,
&filter,
&jsonWriter,
&statsdClient,
verbose,
&tokens,
&prefix,
&msgCount](ix::CobraConnectionEventType eventType,
const std::string& errMsg,
const ix::WebSocketHttpHeaders& headers,
const std::string& subscriptionId,
CobraConnection::MsgId msgId) {
if (eventType == ix::CobraConnection_EventType_Open)
{
spdlog::info("Subscriber connected");
for (auto it : headers)
{
spdlog::info("{}: {}", it.first, it.second);
}
}
if (eventType == ix::CobraConnection_EventType_Closed)
{
spdlog::info("Subscriber closed");
}
else if (eventType == ix::CobraConnection_EventType_Authenticated)
{
spdlog::info("Subscriber authenticated");
conn.subscribe(channel,
filter,
[&jsonWriter, &statsdClient, verbose, &tokens, &prefix, &msgCount](
const Json::Value& msg) {
if (verbose)
{
spdlog::info(jsonWriter.write(msg));
}
std::string id;
for (auto&& attr : tokens)
{
id += ".";
id += extractAttr(attr, msg);
}
spdlog::info("{} {}{}", msgCount++, prefix, id);
#ifndef _WIN32
statsdClient.count(id, 1);
#endif
});
}
else if (eventType == ix::CobraConnection_EventType_Subscribed)
{
spdlog::info("Subscriber: subscribed to channel {}", subscriptionId);
}
else if (eventType == ix::CobraConnection_EventType_UnSubscribed)
{
spdlog::info("Subscriber: unsubscribed from channel {}", subscriptionId);
}
else if (eventType == ix::CobraConnection_EventType_Error)
{
spdlog::error("Subscriber: error {}", errMsg);
}
else if (eventType == ix::CobraConnection_EventType_Published)
{
spdlog::error("Published message hacked: {}", msgId);
}
});
while (true)
{
std::chrono::duration<double, std::milli> duration(1000);
std::this_thread::sleep_for(duration);
}
return 0;
}
} // namespace ix
| 33.47929
| 98
| 0.454578
|
matt-deboer
|
af88b6e751960f69fa8adb0c1f3537c8e0d4b4e9
| 13,509
|
cc
|
C++
|
engine/game/gameBase.cc
|
ClayHanson/B4v21-Public-Repo
|
c812aa7bf2ecb267e02969c85f0c9c2a29be0d28
|
[
"MIT"
] | 1
|
2020-08-18T19:45:34.000Z
|
2020-08-18T19:45:34.000Z
|
engine/game/gameBase.cc
|
ClayHanson/B4v21-Launcher-Public-Repo
|
c812aa7bf2ecb267e02969c85f0c9c2a29be0d28
|
[
"MIT"
] | null | null | null |
engine/game/gameBase.cc
|
ClayHanson/B4v21-Launcher-Public-Repo
|
c812aa7bf2ecb267e02969c85f0c9c2a29be0d28
|
[
"MIT"
] | null | null | null |
//-----------------------------------------------------------------------------
// Torque Game Engine
// Copyright (C) GarageGames.com, Inc.
//-----------------------------------------------------------------------------
#include "platform/platform.h"
#include "game/gameBase.h"
#include "console/consoleTypes.h"
#include "console/consoleInternal.h"
#include "core/bitStream.h"
#include "sim/netConnection.h"
#include "game/gameConnection.h"
#include "math/mathIO.h"
#include "dgl/dgl.h"
//----------------------------------------------------------------------------
// Ghost update relative priority values
static F32 sUpFov = 1.0;
static F32 sUpDistance = 0.4;
static F32 sUpVelocity = 0.4;
static F32 sUpSkips = 0.2;
static F32 sUpOwnership = 0.2;
static F32 sUpInterest = 0.2;
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
IMPLEMENT_CO_DATABLOCK_V1(GameBaseData);
GameBaseData::GameBaseData()
{
category = "";
className = "";
packed = false;
}
bool GameBaseData::onAdd()
{
if (!Parent::onAdd())
return false;
// Link our object name to the datablock class name and
// then onto our C++ class name.
const char* name = getName();
if (name && name[0] && getClassRep()) {
bool linkSuccess = false;
Namespace *parent = getClassRep()->getNameSpace();
if (className && className[0] && dStricmp(className, parent->mName)) {
linkSuccess = Con::linkNamespaces(parent->mName,className);
if(linkSuccess)
linkSuccess = Con::linkNamespaces(className,name);
}
else
linkSuccess = Con::linkNamespaces(parent->mName,name);
if(linkSuccess)
mNameSpace = Con::lookupNamespace(name);
}
// If no className was specified, set it to our C++ class name
if (!className || !className[0])
className = getClassRep()->getClassName();
return true;
}
void GameBaseData::initPersistFields()
{
Parent::initPersistFields();
addField("category", TypeCaseString, Offset(category, GameBaseData));
addField("className", TypeString, Offset(className, GameBaseData));
}
bool GameBaseData::preload(bool server, char errorBuffer[256])
{
if (!Parent::preload(server, errorBuffer))
return false;
packed = false;
return true;
}
void GameBaseData::unpackData(BitStream* stream)
{
Parent::unpackData(stream);
packed = true;
}
//----------------------------------------------------------------------------
bool UNPACK_DB_ID(BitStream * stream, U32 & id)
{
if (stream->readFlag())
{
id = stream->readRangedU32(DataBlockObjectIdFirst,DataBlockObjectIdLast);
return true;
}
return false;
}
bool PACK_DB_ID(BitStream * stream, U32 id)
{
if (stream->writeFlag(id))
{
stream->writeRangedU32(id,DataBlockObjectIdFirst,DataBlockObjectIdLast);
return true;
}
return false;
}
bool PRELOAD_DB(U32 & id, SimDataBlock ** data, bool server, const char * clientMissing, const char * serverMissing)
{
if (server)
{
if (*data)
id = (*data)->getId();
else if (server && serverMissing)
{
Con::errorf(ConsoleLogEntry::General,serverMissing);
return false;
}
}
else
{
if (id && !Sim::findObject(id,*data) && clientMissing)
{
Con::errorf(ConsoleLogEntry::General,clientMissing);
return false;
}
}
return true;
}
//----------------------------------------------------------------------------
bool GameBase::gShowBoundingBox;
//----------------------------------------------------------------------------
IMPLEMENT_CO_NETOBJECT_V1(GameBase);
GameBase::GameBase()
{
mNetFlags.set(Ghostable);
mTypeMask |= GameBaseObjectType;
mProcessLink.next = mProcessLink.prev = this;
mAfterObject = 0;
mProcessTag = 0;
mLastDelta = 0;
mDataBlock = 0;
mProcessTick = true;
mNameTag = "";
mControllingClient = 0;
}
GameBase::~GameBase()
{
plUnlink();
}
//----------------------------------------------------------------------------
bool GameBase::onAdd()
{
if (!Parent::onAdd() || !mDataBlock)
return false;
if (isClientObject()) {
// Client datablock are initialized by the initial update
gClientProcessList.addObject(this);
}
else {
// Datablock must be initialized on the server
if (!onNewDataBlock(mDataBlock))
return false;
gServerProcessList.addObject(this);
}
return true;
}
void GameBase::onRemove()
{
plUnlink();
Parent::onRemove();
}
bool GameBase::onNewDataBlock(GameBaseData* dptr)
{
mDataBlock = dptr;
if (!mDataBlock)
return false;
setMaskBits(DataBlockMask);
return true;
}
void GameBase::inspectPostApply()
{
Parent::inspectPostApply();
setMaskBits(ExtendedInfoMask);
}
//----------------------------------------------------------------------------
void GameBase::processTick(const Move*)
{
mLastDelta = 0;
}
void GameBase::interpolateTick(F32 delta)
{
mLastDelta = delta;
}
void GameBase::advanceTime(F32)
{
}
//----------------------------------------------------------------------------
F32 GameBase::getUpdatePriority(CameraScopeQuery *camInfo, U32 updateMask, S32 updateSkips)
{
updateMask;
// Calculate a priority used to decide if this object
// will be updated on the client. All the weights
// are calculated 0 -> 1 Then weighted together at the
// end to produce a priority.
Point3F pos;
getWorldBox().getCenter(&pos);
pos -= camInfo->pos;
F32 dist = pos.len();
if (dist == 0.0f) dist = 0.001f;
pos *= 1.0f / dist;
// Weight based on linear distance, the basic stuff.
F32 wDistance = (dist < camInfo->visibleDistance)?
1.0f - (dist / camInfo->visibleDistance): 0.0f;
// Weight by field of view, objects directly in front
// will be weighted 1, objects behind will be 0
F32 dot = mDot(pos,camInfo->orientation);
bool inFov = dot > camInfo->cosFov;
F32 wFov = inFov? 1.0f: 0;
// Weight by linear velocity parallel to the viewing plane
// (if it's the field of view, 0 if it's not).
F32 wVelocity = 0.0f;
if (inFov)
{
Point3F vec;
mCross(camInfo->orientation,getVelocity(),&vec);
wVelocity = (vec.len() * camInfo->fov) /
(camInfo->fov * camInfo->visibleDistance);
if (wVelocity > 1.0f)
wVelocity = 1.0f;
}
// Weight by interest.
F32 wInterest;
if (getType() & PlayerObjectType)
wInterest = 0.75f;
else if (getType() & ProjectileObjectType)
{
// Projectiles are more interesting if they
// are heading for us.
wInterest = 0.30f;
F32 dot = -mDot(pos,getVelocity());
if (dot > 0.0f)
wInterest += 0.20 * dot;
}
else
{
if (getType() & ItemObjectType)
wInterest = 0.25f;
else
// Everything else is less interesting.
wInterest = 0.0f;
}
// Weight by updateSkips
F32 wSkips = updateSkips * 0.5;
// Calculate final priority, should total to about 1.0f
//
return
wFov * sUpFov +
wDistance * sUpDistance +
wVelocity * sUpVelocity +
wSkips * sUpSkips +
wInterest * sUpInterest;
}
void GameBase::drawBoundingBox(bool useRenderTransform)
{
const MatrixF & mat = useRenderTransform ? getRenderTransform() : getTransform();
Box3F wbox = useRenderTransform ? getRenderWorldBox() : mWorldBox;
glDisable(GL_DEPTH_TEST);
Point3F box;
glPushMatrix();
dglMultMatrix(&mat);
box = (mObjBox.min + mObjBox.max) * 0.5;
glTranslatef(box.x,box.y,box.z);
box = (mObjBox.max - mObjBox.min) * 0.5;
glScalef(box.x,box.y,box.z);
glColor3f(1, 0, 1);
dglWireCube(Point3F(1,1,1),Point3F(0,0,0));
glPopMatrix();
glPushMatrix();
box = (wbox.min + wbox.max) * 0.5;
glTranslatef(box.x,box.y,box.z);
box = (wbox.max - wbox.min) * 0.5;
glScalef(box.x,box.y,box.z);
glColor3f(0, 1, 1);
dglWireCube(Point3F(1,1,1),Point3F(0,0,0));
glPopMatrix();
glEnable(GL_DEPTH_TEST);
}
//----------------------------------------------------------------------------
bool GameBase::setDataBlock(GameBaseData* dptr)
{
if (isGhost() || isProperlyAdded()) {
if (mDataBlock != dptr)
return onNewDataBlock(dptr);
}
else
mDataBlock = dptr;
return true;
}
//--------------------------------------------------------------------------
void GameBase::scriptOnAdd()
{
// Script onAdd() must be called by the leaf class after
// everything is ready.
if (!isGhost())
Con::executef(mDataBlock,2,"onAdd",scriptThis());
}
void GameBase::scriptOnNewDataBlock()
{
// Script onNewDataBlock() must be called by the leaf class
// after everything is loaded.
if (!isGhost())
Con::executef(mDataBlock,2,"onNewDataBlock",scriptThis());
}
void GameBase::scriptOnRemove()
{
// Script onRemove() must be called by leaf class while
// the object state is still valid.
if (!isGhost() && mDataBlock)
Con::executef(mDataBlock,2,"onRemove",scriptThis());
}
//--------------------------------------------------------------------------
void GameBase::plUnlink()
{
mProcessLink.next->mProcessLink.prev = mProcessLink.prev;
mProcessLink.prev->mProcessLink.next = mProcessLink.next;
mProcessLink.next = mProcessLink.prev = this;
}
void GameBase::plLinkAfter(GameBase* obj)
{
// Link this after obj
mProcessLink.next = obj->mProcessLink.next;
mProcessLink.prev = obj;
obj->mProcessLink.next = this;
mProcessLink.next->mProcessLink.prev = this;
}
void GameBase::plLinkBefore(GameBase* obj)
{
// Link this before obj
mProcessLink.next = obj;
mProcessLink.prev = obj->mProcessLink.prev;
obj->mProcessLink.prev = this;
mProcessLink.prev->mProcessLink.next = this;
}
void GameBase::plJoin(GameBase* head)
{
GameBase *tail1 = head->mProcessLink.prev;
GameBase *tail2 = mProcessLink.prev;
tail1->mProcessLink.next = this;
mProcessLink.prev = tail1;
tail2->mProcessLink.next = head;
head->mProcessLink.prev = tail2;
}
//----------------------------------------------------------------------------
void GameBase::processAfter(GameBase* obj)
{
mAfterObject = obj;
if ((const GameBase*)obj->mAfterObject == this)
obj->mAfterObject = 0;
if (isGhost())
gClientProcessList.markDirty();
else
gServerProcessList.markDirty();
}
void GameBase::clearProcessAfter()
{
mAfterObject = 0;
}
//----------------------------------------------------------------------------
void GameBase::setControllingClient(GameConnection* client)
{
if (isClientObject())
{
if (mControllingClient)
Con::executef(this, 3, "setControl","0");
if (client)
Con::executef(this, 3, "setControl","1");
}
mControllingClient = client;
setMaskBits(ControlMask);
}
U32 GameBase::getPacketDataChecksum(GameConnection*)
{
return 0;
}
void GameBase::writePacketData(GameConnection*, BitStream*)
{
}
void GameBase::readPacketData(GameConnection*, BitStream*)
{
}
U32 GameBase::packUpdate(NetConnection *, U32 mask, BitStream *stream)
{
// Check the mask for the ScaleMask; if it's true, pass that in.
if (stream->writeFlag( mask & ScaleMask ) ) {
mathWrite( *stream, Parent::getScale() );
}
if (stream->writeFlag((mask & DataBlockMask) && mDataBlock != NULL)) {
stream->writeRangedU32(mDataBlock->getId(),
DataBlockObjectIdFirst,
DataBlockObjectIdLast);
}
// cafTODO: ControlMask
return 0;
}
void GameBase::unpackUpdate(NetConnection *con, BitStream *stream)
{
if (stream->readFlag()) {
VectorF scale;
mathRead( *stream, &scale );
setScale( scale );
}
if (stream->readFlag()) {
GameBaseData* dptr = 0;
SimObjectId id = stream->readRangedU32(DataBlockObjectIdFirst,
DataBlockObjectIdLast);
if (!Sim::findObject(id,dptr) || !setDataBlock(dptr))
con->setLastError("Invalid packet GameBase::unpackUpdate()");
}
}
//----------------------------------------------------------------------------
ConsoleMethod( GameBase, getDataBlock, S32, 2, 2, "()"
"Return the datablock this GameBase is using.")
{
return object->getDataBlock()? object->getDataBlock()->getId(): 0;
}
//----------------------------------------------------------------------------
ConsoleMethod(GameBase, setDataBlock, bool, 3, 3, "(DataBlock db)"
"Assign this GameBase to use the specified datablock.")
{
GameBaseData* data;
if (Sim::findObject(argv[2],data)) {
return object->setDataBlock(data);
}
Con::errorf("Could not find data block \"%s\"",argv[2]);
return false;
}
//----------------------------------------------------------------------------
IMPLEMENT_CONSOLETYPE(GameBaseData)
IMPLEMENT_GETDATATYPE(GameBaseData)
IMPLEMENT_SETDATATYPE(GameBaseData)
void GameBase::initPersistFields()
{
Parent::initPersistFields();
addGroup("Misc");
addField("nameTag", TypeCaseString, Offset(mNameTag, GameBase));
addField("dataBlock", TypeGameBaseDataPtr, Offset(mDataBlock, GameBase));
endGroup("Misc");
}
void GameBase::consoleInit()
{
#ifdef TORQUE_DEBUG
Con::addVariable("GameBase::boundingBox", TypeBool, &gShowBoundingBox);
#endif
}
| 26.028902
| 116
| 0.578873
|
ClayHanson
|
af89c1de559be83ecbc03f0d3be755ad7582c4bf
| 318
|
cpp
|
C++
|
src/vedaEMailClient/settings_account.cpp
|
vedatech/Veda_platform
|
5592cb0e43666b04df12eed1849a2a655de6feff
|
[
"MIT"
] | null | null | null |
src/vedaEMailClient/settings_account.cpp
|
vedatech/Veda_platform
|
5592cb0e43666b04df12eed1849a2a655de6feff
|
[
"MIT"
] | null | null | null |
src/vedaEMailClient/settings_account.cpp
|
vedatech/Veda_platform
|
5592cb0e43666b04df12eed1849a2a655de6feff
|
[
"MIT"
] | null | null | null |
#include "settings_account.h"
#include "ui_settings_account.h"
settings_account::settings_account(QWidget *parent) :
QWidget(parent),
ui(new Ui::settings_account)
{
ui->setupUi(this);
//beta
ui->clear_local_address_book_Button->hide();
}
settings_account::~settings_account()
{
delete ui;
}
| 17.666667
| 53
| 0.710692
|
vedatech
|
af8bd51ac60d96ba5167d9e684a6b64744e214e6
| 1,002
|
hpp
|
C++
|
libs/core/render/include/bksge/core/render/gl/detail/sampler.hpp
|
myoukaku/bksge
|
0f8b60e475a3f1709723906e4796b5e60decf06e
|
[
"MIT"
] | 4
|
2018-06-10T13:35:32.000Z
|
2021-06-03T14:27:41.000Z
|
libs/core/render/include/bksge/core/render/gl/detail/sampler.hpp
|
myoukaku/bksge
|
0f8b60e475a3f1709723906e4796b5e60decf06e
|
[
"MIT"
] | 566
|
2017-01-31T05:36:09.000Z
|
2022-02-09T05:04:37.000Z
|
libs/core/render/include/bksge/core/render/gl/detail/sampler.hpp
|
myoukaku/bksge
|
0f8b60e475a3f1709723906e4796b5e60decf06e
|
[
"MIT"
] | 1
|
2018-07-05T04:40:53.000Z
|
2018-07-05T04:40:53.000Z
|
/**
* @file sampler.hpp
*
* @brief Sampler クラスの定義
*
* @author myoukaku
*/
#ifndef BKSGE_CORE_RENDER_GL_DETAIL_SAMPLER_HPP
#define BKSGE_CORE_RENDER_GL_DETAIL_SAMPLER_HPP
#include <bksge/core/render/gl/detail/fwd/sampler_fwd.hpp>
#include <bksge/core/render/gl/detail/gl_h.hpp>
#include <bksge/core/render/fwd/sampler_fwd.hpp>
namespace bksge
{
namespace render
{
namespace gl
{
/**
* @brief Sampler を OpenGL で使えるように変換したクラス
*/
class Sampler
{
public:
explicit Sampler(bksge::Sampler const& sampler);
~Sampler();
void Bind(GLint location) const;
private:
// noncopyable
Sampler(Sampler const&) = delete;
Sampler& operator=(Sampler const&) = delete;
private:
::GLuint m_id;
};
} // namespace gl
} // namespace render
} // namespace bksge
#include <bksge/fnd/config.hpp>
#if defined(BKSGE_HEADER_ONLY)
#include <bksge/core/render/gl/detail/inl/sampler_inl.hpp>
#endif
#endif // BKSGE_CORE_RENDER_GL_DETAIL_SAMPLER_HPP
| 17.275862
| 59
| 0.699601
|
myoukaku
|
af8ca990220f75bca38fb154debb8ec8f7d3b3e9
| 390
|
cpp
|
C++
|
zerojudge_code/a007-1.cpp
|
SeanHsu-pub/zerojudge_practice
|
97061bb7e313541a46fbb2f9b7a401563ada3fda
|
[
"MIT"
] | null | null | null |
zerojudge_code/a007-1.cpp
|
SeanHsu-pub/zerojudge_practice
|
97061bb7e313541a46fbb2f9b7a401563ada3fda
|
[
"MIT"
] | null | null | null |
zerojudge_code/a007-1.cpp
|
SeanHsu-pub/zerojudge_practice
|
97061bb7e313541a46fbb2f9b7a401563ada3fda
|
[
"MIT"
] | null | null | null |
#include<bits/stdc++.h>
#define endl "\n"
using namespace std;
int main(void){
int n=0;
vector<int> a;
a.push_back(2);
for(int i=3; i<=2147483647; i++){
bool is=false;
for(int j=0; j<a.size(); j++){
if(i%a[j]==0){
is=true;
}
}
if(is==false){
a.push_back(i);
}
}
for(vector<int>::iterator it=a.begin(); it!=a.end(); it++){
cout << *it << endl;
}
return 0;
}
| 16.25
| 60
| 0.54359
|
SeanHsu-pub
|
af97284edc1e06cd209fe95b68d6ca65cc671169
| 999
|
hpp
|
C++
|
ares/n64/ai/ai.hpp
|
moon-chilled/Ares
|
909fb098c292f8336d0502dc677050312d8b5c81
|
[
"0BSD"
] | 7
|
2020-07-25T11:44:39.000Z
|
2021-01-29T13:21:31.000Z
|
ares/n64/ai/ai.hpp
|
jchw-forks/ares
|
d78298a1e95fd0ce65feabfd4f13b60e31210a7a
|
[
"0BSD"
] | null | null | null |
ares/n64/ai/ai.hpp
|
jchw-forks/ares
|
d78298a1e95fd0ce65feabfd4f13b60e31210a7a
|
[
"0BSD"
] | 1
|
2021-03-22T16:15:30.000Z
|
2021-03-22T16:15:30.000Z
|
//Audio Interface
struct AI : Thread, Memory::IO<AI> {
Node::Component node;
Node::Stream stream;
struct Debugger {
//debugger.cpp
auto load(Node::Object) -> void;
auto io(string_view) -> void;
struct Tracer {
Node::Notification io;
} tracer;
} debugger;
//ai.cpp
auto load(Node::Object) -> void;
auto unload() -> void;
auto main() -> void;
auto sample() -> void;
auto step(uint clocks) -> void;
auto power() -> void;
//io.cpp
auto readWord(u32 address) -> u32;
auto writeWord(u32 address, u32 data) -> void;
//serialization.cpp
auto serialize(serializer&) -> void;
struct FIFO {
uint24 address = 0;
} fifo[2];
struct IO {
uint1 dmaEnable = 0;
uint24 dmaAddress[2] = {};
uint18 dmaLength[2] = {};
uint2 dmaCount = 0;
uint14 dacRate = 0;
uint4 bitRate = 0;
} io;
struct DAC {
u32 frequency = 44100;
u32 precision = 16;
u32 period = 93'750'000 / 44'100;
} dac;
};
extern AI ai;
| 18.849057
| 48
| 0.595596
|
moon-chilled
|
af98550e21c78ddadca91514a494785f60806f6f
| 15,363
|
cpp
|
C++
|
src/data_manipulation.cpp
|
fenguoerbian/seurat
|
ca69686e741b3b0d72debd182dbacdb5e81e58c1
|
[
"MIT"
] | 1,507
|
2015-05-28T16:02:47.000Z
|
2022-03-31T22:08:42.000Z
|
src/data_manipulation.cpp
|
fenguoerbian/seurat
|
ca69686e741b3b0d72debd182dbacdb5e81e58c1
|
[
"MIT"
] | 5,186
|
2015-10-21T15:08:58.000Z
|
2022-03-31T23:38:29.000Z
|
src/data_manipulation.cpp
|
fenguoerbian/seurat
|
ca69686e741b3b0d72debd182dbacdb5e81e58c1
|
[
"MIT"
] | 857
|
2015-05-28T16:03:42.000Z
|
2022-03-31T10:04:51.000Z
|
#include <RcppEigen.h>
#include <progress.hpp>
#include <cmath>
#include <unordered_map>
#include <fstream>
#include <string>
#include <Rinternals.h>
using namespace Rcpp;
// [[Rcpp::depends(RcppEigen)]]
// [[Rcpp::depends(RcppProgress)]]
// [[Rcpp::export]]
Eigen::SparseMatrix<double> RunUMISampling(Eigen::SparseMatrix<double> data, int sample_val, bool upsample = false, bool display_progress=true){
Progress p(data.outerSize(), display_progress);
Eigen::VectorXd colSums = data.transpose() * Eigen::VectorXd::Ones(data.rows());
for (int k=0; k < data.outerSize(); ++k){
p.increment();
for (Eigen::SparseMatrix<double>::InnerIterator it(data, k); it; ++it){
double entry = it.value();
if( (upsample) || (colSums[k] > sample_val)){
entry = entry * double(sample_val) / colSums[k];
if (fmod(entry, 1) != 0){
double rn = R::runif(0,1);
if(fmod(entry, 1) <= rn){
it.valueRef() = floor(entry);
}
else{
it.valueRef() = ceil(entry);
}
}
else{
it.valueRef() = entry;
}
}
}
}
return(data);
}
// [[Rcpp::export]]
Eigen::SparseMatrix<double> RunUMISamplingPerCell(Eigen::SparseMatrix<double> data, NumericVector sample_val, bool upsample = false, bool display_progress=true){
Progress p(data.outerSize(), display_progress);
Eigen::VectorXd colSums = data.transpose() * Eigen::VectorXd::Ones(data.rows());
for (int k=0; k < data.outerSize(); ++k){
p.increment();
for (Eigen::SparseMatrix<double>::InnerIterator it(data, k); it; ++it){
double entry = it.value();
if( (upsample) || (colSums[k] > sample_val[k])){
entry = entry * double(sample_val[k]) / colSums[k];
if (fmod(entry, 1) != 0){
double rn = R::runif(0,1);
if(fmod(entry, 1) <= rn){
it.valueRef() = floor(entry);
}
else{
it.valueRef() = ceil(entry);
}
}
else{
it.valueRef() = entry;
}
}
}
}
return(data);
}
typedef Eigen::Triplet<double> T;
// [[Rcpp::export(rng = false)]]
Eigen::SparseMatrix<double> RowMergeMatrices(Eigen::SparseMatrix<double, Eigen::RowMajor> mat1, Eigen::SparseMatrix<double, Eigen::RowMajor> mat2, std::vector< std::string > mat1_rownames,
std::vector< std::string > mat2_rownames, std::vector< std::string > all_rownames){
// Set up hash maps for rowname based lookup
std::unordered_map<std::string, int> mat1_map;
for(unsigned int i = 0; i < mat1_rownames.size(); i++){
mat1_map[mat1_rownames[i]] = i;
}
std::unordered_map<std::string, int> mat2_map;
for(unsigned int i = 0; i < mat2_rownames.size(); i++){
mat2_map[mat2_rownames[i]] = i;
}
// set up tripletList for new matrix creation
std::vector<T> tripletList;
int num_rows = all_rownames.size();
int num_col1 = mat1.cols();
int num_col2 = mat2.cols();
tripletList.reserve(mat1.nonZeros() + mat2.nonZeros());
for(int i = 0; i < num_rows; i++){
std::string key = all_rownames[i];
if (mat1_map.count(key)){
for(Eigen::SparseMatrix<double, Eigen::RowMajor>::InnerIterator it1(mat1, mat1_map[key]); it1; ++it1){
tripletList.emplace_back(i, it1.col(), it1.value());
}
}
if (mat2_map.count(key)){
for(Eigen::SparseMatrix<double, Eigen::RowMajor>::InnerIterator it2(mat2, mat2_map[key]); it2; ++it2){
tripletList.emplace_back(i, num_col1 + it2.col(), it2.value());
}
}
}
Eigen::SparseMatrix<double> combined_mat(num_rows, num_col1 + num_col2);
combined_mat.setFromTriplets(tripletList.begin(), tripletList.end());
return combined_mat;
}
// [[Rcpp::export(rng = false)]]
Eigen::SparseMatrix<double> LogNorm(Eigen::SparseMatrix<double> data, int scale_factor, bool display_progress = true){
Progress p(data.outerSize(), display_progress);
Eigen::VectorXd colSums = data.transpose() * Eigen::VectorXd::Ones(data.rows());
for (int k=0; k < data.outerSize(); ++k){
p.increment();
for (Eigen::SparseMatrix<double>::InnerIterator it(data, k); it; ++it){
it.valueRef() = log1p(double(it.value()) / colSums[k] * scale_factor);
}
}
return data;
}
/* Performs column scaling and/or centering. Equivalent to using scale(mat, TRUE, apply(x,2,sd)) in R.
Note: Doesn't handle NA/NaNs in the same way the R implementation does, */
// [[Rcpp::export(rng = false)]]
NumericMatrix Standardize(Eigen::Map<Eigen::MatrixXd> mat, bool display_progress = true){
Progress p(mat.cols(), display_progress);
NumericMatrix std_mat(mat.rows(), mat.cols());
for(int i=0; i < mat.cols(); ++i){
p.increment();
Eigen::ArrayXd r = mat.col(i).array();
double colMean = r.mean();
double colSdev = sqrt((r - colMean).square().sum() / (mat.rows() - 1));
NumericMatrix::Column new_col = std_mat(_, i);
for(int j=0; j < new_col.size(); j++) {
new_col[j] = (r[j] - colMean) / colSdev;
}
}
return std_mat;
}
// [[Rcpp::export(rng = false)]]
Eigen::MatrixXd FastSparseRowScale(Eigen::SparseMatrix<double> mat, bool scale = true, bool center = true,
double scale_max = 10, bool display_progress = true){
mat = mat.transpose();
Progress p(mat.outerSize(), display_progress);
Eigen::MatrixXd scaled_mat(mat.rows(), mat.cols());
for (int k=0; k<mat.outerSize(); ++k){
p.increment();
double colMean = 0;
double colSdev = 0;
for (Eigen::SparseMatrix<double>::InnerIterator it(mat,k); it; ++it)
{
colMean += it.value();
}
colMean = colMean / mat.rows();
if (scale == true){
int nnZero = 0;
if(center == true){
for (Eigen::SparseMatrix<double>::InnerIterator it(mat,k); it; ++it)
{
nnZero += 1;
colSdev += pow((it.value() - colMean), 2);
}
colSdev += pow(colMean, 2) * (mat.rows() - nnZero);
}
else{
for (Eigen::SparseMatrix<double>::InnerIterator it(mat,k); it; ++it)
{
colSdev += pow(it.value(), 2);
}
}
colSdev = sqrt(colSdev / (mat.rows() - 1));
}
else{
colSdev = 1;
}
if(center == false){
colMean = 0;
}
Eigen::VectorXd col = Eigen::VectorXd(mat.col(k));
scaled_mat.col(k) = (col.array() - colMean) / colSdev;
for(int s=0; s<scaled_mat.col(k).size(); ++s){
if(scaled_mat(s,k) > scale_max){
scaled_mat(s,k) = scale_max;
}
}
}
return scaled_mat.transpose();
}
// [[Rcpp::export(rng = false)]]
Eigen::MatrixXd FastSparseRowScaleWithKnownStats(Eigen::SparseMatrix<double> mat, NumericVector mu, NumericVector sigma, bool scale = true, bool center = true,
double scale_max = 10, bool display_progress = true){
mat = mat.transpose();
Progress p(mat.outerSize(), display_progress);
Eigen::MatrixXd scaled_mat(mat.rows(), mat.cols());
for (int k=0; k<mat.outerSize(); ++k){
p.increment();
double colMean = 0;
double colSdev = 1;
if (scale == true){
colSdev = sigma[k];
}
if(center == true){
colMean = mu[k];
}
Eigen::VectorXd col = Eigen::VectorXd(mat.col(k));
scaled_mat.col(k) = (col.array() - colMean) / colSdev;
for(int s=0; s<scaled_mat.col(k).size(); ++s){
if(scaled_mat(s,k) > scale_max){
scaled_mat(s,k) = scale_max;
}
}
}
return scaled_mat.transpose();
}
/* Note: May not handle NA/NaNs in the same way the R implementation does, */
// [[Rcpp::export(rng = false)]]
Eigen::MatrixXd FastCov(Eigen::MatrixXd mat, bool center = true){
if (center) {
mat = mat.rowwise() - mat.colwise().mean();
}
Eigen::MatrixXd cov = (mat.adjoint() * mat) / double(mat.rows() - 1);
return(cov);
}
// [[Rcpp::export(rng = false)]]
Eigen::MatrixXd FastCovMats(Eigen::MatrixXd mat1, Eigen::MatrixXd mat2, bool center = true){
if(center){
mat1 = mat1.rowwise() - mat1.colwise().mean();
mat2 = mat2.rowwise() - mat2.colwise().mean();
}
Eigen::MatrixXd cov = (mat1.adjoint() * mat2) / double(mat1.rows() - 1);
return(cov);
}
/* Note: Faster than the R implementation but is not in-place */
// [[Rcpp::export(rng = false)]]
Eigen::MatrixXd FastRBind(Eigen::MatrixXd mat1, Eigen::MatrixXd mat2){
Eigen::MatrixXd mat3(mat1.rows() + mat2.rows(), mat1.cols());
mat3 << mat1, mat2;
return(mat3);
}
/* Calculates the row means of the logged values in non-log space */
// [[Rcpp::export(rng = false)]]
Eigen::VectorXd FastExpMean(Eigen::SparseMatrix<double> mat, bool display_progress){
int ncols = mat.cols();
Eigen::VectorXd rowmeans(mat.rows());
mat = mat.transpose();
if(display_progress == true){
Rcpp::Rcerr << "Calculating gene means" << std::endl;
}
Progress p(mat.outerSize(), display_progress);
for (int k=0; k<mat.outerSize(); ++k){
p.increment();
double rm = 0;
for (Eigen::SparseMatrix<double>::InnerIterator it(mat,k); it; ++it){
rm += expm1(it.value());
}
rm = rm / ncols;
rowmeans[k] = log1p(rm);
}
return(rowmeans);
}
/* use this if you know the row means */
// [[Rcpp::export(rng = false)]]
NumericVector SparseRowVar2(Eigen::SparseMatrix<double> mat,
NumericVector mu,
bool display_progress){
mat = mat.transpose();
if(display_progress == true){
Rcpp::Rcerr << "Calculating gene variances" << std::endl;
}
Progress p(mat.outerSize(), display_progress);
NumericVector allVars = no_init(mat.cols());
for (int k=0; k<mat.outerSize(); ++k){
p.increment();
double colSum = 0;
int nZero = mat.rows();
for (Eigen::SparseMatrix<double>::InnerIterator it(mat,k); it; ++it) {
nZero -= 1;
colSum += pow(it.value() - mu[k], 2);
}
colSum += pow(mu[k], 2) * nZero;
allVars[k] = colSum / (mat.rows() - 1);
}
return(allVars);
}
/* standardize matrix rows using given mean and standard deviation,
clip values larger than vmax to vmax,
then return variance for each row */
// [[Rcpp::export(rng = false)]]
NumericVector SparseRowVarStd(Eigen::SparseMatrix<double> mat,
NumericVector mu,
NumericVector sd,
double vmax,
bool display_progress){
if(display_progress == true){
Rcpp::Rcerr << "Calculating feature variances of standardized and clipped values" << std::endl;
}
mat = mat.transpose();
NumericVector allVars(mat.cols());
Progress p(mat.outerSize(), display_progress);
for (int k=0; k<mat.outerSize(); ++k){
p.increment();
if (sd[k] == 0) continue;
double colSum = 0;
int nZero = mat.rows();
for (Eigen::SparseMatrix<double>::InnerIterator it(mat,k); it; ++it)
{
nZero -= 1;
colSum += pow(std::min(vmax, (it.value() - mu[k]) / sd[k]), 2);
}
colSum += pow((0 - mu[k]) / sd[k], 2) * nZero;
allVars[k] = colSum / (mat.rows() - 1);
}
return(allVars);
}
/* Calculate the variance to mean ratio (VMR) in non-logspace (return answer in
log-space) */
// [[Rcpp::export(rng = false)]]
Eigen::VectorXd FastLogVMR(Eigen::SparseMatrix<double> mat, bool display_progress){
int ncols = mat.cols();
Eigen::VectorXd rowdisp(mat.rows());
mat = mat.transpose();
if(display_progress == true){
Rcpp::Rcerr << "Calculating gene variance to mean ratios" << std::endl;
}
Progress p(mat.outerSize(), display_progress);
for (int k=0; k<mat.outerSize(); ++k){
p.increment();
double rm = 0;
double v = 0;
int nnZero = 0;
for (Eigen::SparseMatrix<double>::InnerIterator it(mat,k); it; ++it){
rm += expm1(it.value());
}
rm = rm / ncols;
for (Eigen::SparseMatrix<double>::InnerIterator it(mat,k); it; ++it){
v += pow(expm1(it.value()) - rm, 2);
nnZero += 1;
}
v = (v + (ncols - nnZero) * pow(rm, 2)) / (ncols - 1);
rowdisp[k] = log(v/rm);
}
return(rowdisp);
}
/* Calculates the variance of rows of a matrix */
// [[Rcpp::export(rng = false)]]
NumericVector RowVar(Eigen::Map<Eigen::MatrixXd> x){
NumericVector out(x.rows());
for(int i=0; i < x.rows(); ++i){
Eigen::ArrayXd r = x.row(i).array();
double rowMean = r.mean();
out[i] = (r - rowMean).square().sum() / (x.cols() - 1);
}
return out;
}
/* Calculate the variance in non-logspace (return answer in non-logspace) */
// [[Rcpp::export(rng = false)]]
Eigen::VectorXd SparseRowVar(Eigen::SparseMatrix<double> mat, bool display_progress){
int ncols = mat.cols();
Eigen::VectorXd rowdisp(mat.rows());
mat = mat.transpose();
if(display_progress == true){
Rcpp::Rcerr << "Calculating gene variances" << std::endl;
}
Progress p(mat.outerSize(), display_progress);
for (int k=0; k<mat.outerSize(); ++k){
p.increment();
double rm = 0;
double v = 0;
int nnZero = 0;
for (Eigen::SparseMatrix<double>::InnerIterator it(mat,k); it; ++it){
rm += (it.value());
}
rm = rm / ncols;
for (Eigen::SparseMatrix<double>::InnerIterator it(mat,k); it; ++it){
v += pow((it.value()) - rm, 2);
nnZero += 1;
}
v = (v + (ncols - nnZero) * pow(rm, 2)) / (ncols - 1);
rowdisp[k] = v;
}
return(rowdisp);
}
//cols_idx should be 0-indexed
// [[Rcpp::export(rng = false)]]
Eigen::SparseMatrix<double> ReplaceColsC(Eigen::SparseMatrix<double> mat, NumericVector col_idx, Eigen::SparseMatrix<double> replacement){
int rep_idx = 0;
for(auto const &ci : col_idx){
mat.col(ci) = replacement.col(rep_idx);
rep_idx += 1;
}
return(mat);
}
template <typename S>
std::vector<size_t> sort_indexes(const std::vector<S> &v) {
// initialize original index locations
std::vector<size_t> idx(v.size());
std::iota(idx.begin(), idx.end(), 0);
std::stable_sort(idx.begin(), idx.end(),
[&v](size_t i1, size_t i2) {return v[i1] < v[i2];});
return idx;
}
// [[Rcpp::export(rng = false)]]
List GraphToNeighborHelper(Eigen::SparseMatrix<double> mat) {
mat = mat.transpose();
//determine the number of neighbors
int n = 0;
for(Eigen::SparseMatrix<double>::InnerIterator it(mat, 0); it; ++it) {
n += 1;
}
Eigen::MatrixXd nn_idx(mat.rows(), n);
Eigen::MatrixXd nn_dist(mat.rows(), n);
for (int k=0; k<mat.outerSize(); ++k){
int n_k = 0;
std::vector<double> row_idx;
std::vector<double> row_dist;
row_idx.reserve(n);
row_dist.reserve(n);
for (Eigen::SparseMatrix<double>::InnerIterator it(mat,k); it; ++it) {
if (n_k > (n-1)) {
Rcpp::stop("Not all cells have an equal number of neighbors.");
}
row_idx.push_back(it.row() + 1);
row_dist.push_back(it.value());
n_k += 1;
}
if (n_k != n) {
Rcpp::Rcout << n << ":::" << n_k << std::endl;
Rcpp::stop("Not all cells have an equal number of neighbors.");
}
//order the idx based on dist
std::vector<size_t> idx_order = sort_indexes(row_dist);
for(int i = 0; i < n; ++i) {
nn_idx(k, i) = row_idx[idx_order[i]];
nn_dist(k, i) = row_dist[idx_order[i]];
}
}
List neighbors = List::create(nn_idx, nn_dist);
return(neighbors);
}
| 33.03871
| 188
| 0.596303
|
fenguoerbian
|
af99fe7f95aae2d47ee282d24a85f696eceb1cda
| 2,237
|
cpp
|
C++
|
sakura_core/env/CTagJumpManager.cpp
|
HoppingTappy/sakura
|
a2db8d55911af12f8364c4ff744d5ded3ce5643b
|
[
"Zlib"
] | 953
|
2018-05-20T07:09:12.000Z
|
2022-03-30T13:23:38.000Z
|
sakura_core/env/CTagJumpManager.cpp
|
HoppingTappy/sakura
|
a2db8d55911af12f8364c4ff744d5ded3ce5643b
|
[
"Zlib"
] | 1,679
|
2018-05-21T05:44:34.000Z
|
2022-03-28T04:19:31.000Z
|
sakura_core/env/CTagJumpManager.cpp
|
HoppingTappy/sakura
|
a2db8d55911af12f8364c4ff744d5ded3ce5643b
|
[
"Zlib"
] | 190
|
2018-05-23T02:53:34.000Z
|
2022-03-11T08:35:54.000Z
|
/*! @file */
/*
2008.05.18 kobake CShareData から分離
*/
/*
Copyright (C) 2008, kobake
Copyright (C) 2018-2021, Sakura Editor Organization
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented;
you must not claim that you wrote the original software.
If you use this software in a product, an acknowledgment
in the product documentation would be appreciated but is
not required.
2. Altered source versions must be plainly marked as such,
and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#include "StdAfx.h"
#include "env/DLLSHAREDATA.h"
#include "CTagJumpManager.h"
/*!
@brief タグジャンプ情報の保存
タグジャンプするときに、タグジャンプ先の情報を保存する。
@param[in] pTagJump 保存するタグジャンプ情報
@retval true 保存成功
@retval false 保存失敗
@date 2004/06/21 新規作成
@date 2004/06/22 Moca 一杯になったら一番古い情報を削除しそこに新しい情報を入れる
*/
void CTagJumpManager::PushTagJump(const TagJump *pTagJump)
{
int i = m_pShareData->m_sTagJump.m_TagJumpTop + 1;
if( MAX_TAGJUMPNUM <= i ){
i = 0;
}
if( m_pShareData->m_sTagJump.m_TagJumpNum < MAX_TAGJUMPNUM ){
m_pShareData->m_sTagJump.m_TagJumpNum++;
}
m_pShareData->m_sTagJump.m_TagJump[i] = *pTagJump;
m_pShareData->m_sTagJump.m_TagJumpTop = i;
}
/*!
@brief タグジャンプ情報の参照
タグジャンプバックするときに、タグジャンプ元の情報を参照する。
@param[out] pTagJump 参照するタグジャンプ情報
@retval true 参照成功
@retval false 参照失敗
@date 2004/06/21 新規作成
@date 2004/06/22 Moca SetTagJump変更による修正
*/
bool CTagJumpManager::PopTagJump(TagJump *pTagJump)
{
if( 0 < m_pShareData->m_sTagJump.m_TagJumpNum ){
*pTagJump = m_pShareData->m_sTagJump.m_TagJump[m_pShareData->m_sTagJump.m_TagJumpTop--];
if( m_pShareData->m_sTagJump.m_TagJumpTop < 0 ){
m_pShareData->m_sTagJump.m_TagJumpTop = MAX_TAGJUMPNUM - 1;
}
m_pShareData->m_sTagJump.m_TagJumpNum--;
return true;
}
return false;
}
| 26.630952
| 90
| 0.750112
|
HoppingTappy
|
af9bf362f81065ad70a1ae3e61a68eb8a0aa224d
| 2,154
|
cpp
|
C++
|
wliotproxy-src-base/libVDIL/src/xml/SubProgramInternalBlocksParser.cpp
|
ooolms/wl_iot_framework
|
77f5d577105d505fd1c5a21940f29b72eb3391ea
|
[
"Apache-2.0"
] | null | null | null |
wliotproxy-src-base/libVDIL/src/xml/SubProgramInternalBlocksParser.cpp
|
ooolms/wl_iot_framework
|
77f5d577105d505fd1c5a21940f29b72eb3391ea
|
[
"Apache-2.0"
] | null | null | null |
wliotproxy-src-base/libVDIL/src/xml/SubProgramInternalBlocksParser.cpp
|
ooolms/wl_iot_framework
|
77f5d577105d505fd1c5a21940f29b72eb3391ea
|
[
"Apache-2.0"
] | null | null | null |
/*******************************************
Copyright 2017 OOO "LMS"
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 "VDIL/xml/SubProgramInternalBlocksParser.h"
#include "VDIL/core/SubProgram.h"
using namespace WLIOT;
using namespace WLIOTVDIL;
bool SubProgramInternalInputBlockXmlParser::blockFromXml(BaseBlock *block,
const QDomElement &blockElem,bool tryFixErrors)
{
SubProgramInternalInputBlock *b=(SubProgramInternalInputBlock*)block;
if(!blockElem.hasAttribute("sprg_output"))
if(!tryFixErrors)return false;
QString output=blockElem.attribute("sprg_output");
TypeAndDim td=b->ownerSubProgram()->outputs().value(output);
if(td.isValid())
b->setSubProgramOutput(output,td);
return true;
}
void SubProgramInternalInputBlockXmlParser::blockToXml(const BaseBlock *block,QDomElement &blockElem)
{
const SubProgramInternalInputBlock *b=(const SubProgramInternalInputBlock*)block;
blockElem.setAttribute("sprg_output",b->subProgramOutput());
}
bool SubProgramInternalOutputBlockXmlParser::blockFromXml(BaseBlock *block,
const QDomElement &blockElem,bool tryFixErrors)
{
SubProgramInternalOutputBlock *b=(SubProgramInternalOutputBlock*)block;
if(!blockElem.hasAttribute("sprg_input"))
if(!tryFixErrors)return false;
QString input=blockElem.attribute("sprg_input");
TypeAndDim td=b->ownerSubProgram()->inputs().value(input);
if(td.isValid())
b->setSubProgramInput(input,td);
return true;
}
void SubProgramInternalOutputBlockXmlParser::blockToXml(const BaseBlock *block,QDomElement &blockElem)
{
const SubProgramInternalOutputBlock *b=(const SubProgramInternalOutputBlock*)block;
blockElem.setAttribute("sprg_input",b->subProgramInput());
}
| 36.508475
| 102
| 0.788765
|
ooolms
|
afa9b0d667cdb05843073b61a1659cdf2b7f2423
| 3,105
|
cpp
|
C++
|
main.cpp
|
Qengineering/Face-detection-Landmark-Raspberry-Pi-32-64-bits
|
0ec1a6a5287aceab34d5f0f089ebd1f4052b13db
|
[
"BSD-3-Clause"
] | 3
|
2021-02-24T00:11:38.000Z
|
2021-02-24T18:28:28.000Z
|
main.cpp
|
Qengineering/Face-detection-Landmark-Raspberry-Pi-32-64-bits
|
0ec1a6a5287aceab34d5f0f089ebd1f4052b13db
|
[
"BSD-3-Clause"
] | null | null | null |
main.cpp
|
Qengineering/Face-detection-Landmark-Raspberry-Pi-32-64-bits
|
0ec1a6a5287aceab34d5f0f089ebd1f4052b13db
|
[
"BSD-3-Clause"
] | 1
|
2021-05-14T01:10:11.000Z
|
2021-05-14T01:10:11.000Z
|
#include <iostream>
#include <opencv2/opencv.hpp>
#include "FaceDetector.h"
using namespace std;
int main(int argc, char **argv)
{
float f;
float FPS[16];
int i, Fcnt=0;
cv::Mat frame;
const int max_side = 320;
//some timing
chrono::steady_clock::time_point Tbegin, Tend;
for(i=0;i<16;i++) FPS[i]=0.0;
Detector detector("face.param","face.bin");
cv::VideoCapture cap("Walks2.mp4");
if (!cap.isOpened()) {
cerr << "ERROR: Unable to open the camera" << endl;
return 0;
}
cout << "Start grabbing, press ESC on Live window to terminate" << endl;
while(1){
//get frame
// frame=cv::imread("11.jpg"); //if you want to run just one picture need to refresh frame before class detection
cap >> frame;
if (frame.empty()) {
cerr << "ERROR: Unable to grab from the camera" << endl;
break;
}
// scale
float long_side = std::max(frame.cols, frame.rows);
float scale = max_side/long_side;
cv::Mat img_scale;
cv::resize(frame, img_scale, cv::Size(frame.cols*scale, frame.rows*scale));
std::vector<bbox> boxes;
Tbegin = chrono::steady_clock::now();
detector.Detect(img_scale, boxes);
Tend = chrono::steady_clock::now();
// draw image
for (size_t j = 0; j < boxes.size(); ++j) {
cv::Rect rect(boxes[j].x1/scale, boxes[j].y1/scale, boxes[j].x2/scale - boxes[j].x1/scale, boxes[j].y2/scale - boxes[j].y1/scale);
cv::rectangle(frame, rect, cv::Scalar(0, 0, 255), 1, 8, 0);
// cv::putText(frame, cv::format("%f", boxes[j].s), cv::Size((boxes[j].x1/scale), boxes[j].y1/scale), cv::FONT_HERSHEY_COMPLEX, 0.5, cv::Scalar(0, 255, 255));
cv::circle(frame, cv::Point(boxes[j].point[0]._x / scale, boxes[j].point[0]._y / scale), 1, cv::Scalar(0, 0, 225), 3);
cv::circle(frame, cv::Point(boxes[j].point[1]._x / scale, boxes[j].point[1]._y / scale), 1, cv::Scalar(0, 255, 225), 3);
cv::circle(frame, cv::Point(boxes[j].point[2]._x / scale, boxes[j].point[2]._y / scale), 1, cv::Scalar(255, 0, 225), 3);
cv::circle(frame, cv::Point(boxes[j].point[3]._x / scale, boxes[j].point[3]._y / scale), 1, cv::Scalar(0, 255, 0), 3);
cv::circle(frame, cv::Point(boxes[j].point[4]._x / scale, boxes[j].point[4]._y / scale), 1, cv::Scalar(255, 0, 0), 3);
}
//calculate frame rate
f = chrono::duration_cast <chrono::milliseconds> (Tend - Tbegin).count();
if(f>0.0) FPS[((Fcnt++)&0x0F)]=1000.0/f;
for(f=0.0, i=0;i<16;i++){ f+=FPS[i]; }
cv::putText(frame, cv::format("FPS %0.2f", f/16),cv::Point(10,20),cv::FONT_HERSHEY_SIMPLEX,0.6, cv::Scalar(0, 0, 255));
//show output
// cv::imwrite("Result_11.jpg",frame); //in case you run only a jpg picture
cv::imshow("RPi 64 OS - 1,95 GHz - 2 Mb RAM", frame);
char esc = cv::waitKey(50);
if(esc == 27) break;
}
cv::destroyAllWindows();
return 0;
}
| 38.333333
| 169
| 0.561031
|
Qengineering
|
afad74146eedc9507cd1eeaee63132b546cb7f43
| 2,046
|
cpp
|
C++
|
Net/ThreadPool.cpp
|
Txhua/IOLoop
|
710fb914ac7fd65a874e2866f0f38ab38b7858f3
|
[
"Apache-2.0"
] | null | null | null |
Net/ThreadPool.cpp
|
Txhua/IOLoop
|
710fb914ac7fd65a874e2866f0f38ab38b7858f3
|
[
"Apache-2.0"
] | 2
|
2021-08-23T06:24:32.000Z
|
2021-08-23T06:27:31.000Z
|
Net/ThreadPool.cpp
|
Txhua/IOLoop
|
710fb914ac7fd65a874e2866f0f38ab38b7858f3
|
[
"Apache-2.0"
] | null | null | null |
#include "ThreadPool.h"
#include <assert.h>
#include <glog/logging.h>
namespace IOEvent
{
ThreadPool::ThreadPool(const std::string &name)
:name_(name),
maxQueueSize_(0),
runing_(false)
{
}
ThreadPool::~ThreadPool()
{
if (runing_)
{
stop();
}
}
void ThreadPool::setmaxQueueSize(int32_t max)
{
maxQueueSize_ = max;
}
void ThreadPool::start(int32_t threadNum)
{
assert(threads_.empty());
runing_ = true;
int32_t num = threadNum;
if (num <= 0)
{
num = std::thread::hardware_concurrency();
}
threads_.reserve(num);
for (auto i = 0; i < num; ++i)
{
threads_.push_back(std::make_unique<Thread>(std::bind(&ThreadPool::threadFunc, this), name_));
threads_[i]->start();
}
}
void ThreadPool::post(Task task)
{
std::unique_lock<std::mutex> lock(mutex_);
if (!runing_)
{
throw std::runtime_error("thread pool has stopped");
}
while ((maxQueueSize_ > 0 && maxQueueSize_ == queue_.size()))
{
notFull_.wait(lock, [&]()->bool
{
return queue_.size() < maxQueueSize_ || !runing_;
});
}
queue_.push_back(std::move(task));
notEmpty_.notify_one();
}
void ThreadPool::stop()
{
assert(runing_);
{
std::unique_lock<std::mutex> lock(mutex_);
runing_ = false;
notEmpty_.notify_all();
notFull_.notify_all();
}
for (auto &t : threads_)
{
t->joined();
}
}
ThreadPool::Task ThreadPool::take()
{
std::unique_lock<std::mutex> lock(mutex_);
while (queue_.empty() && runing_)
{
notEmpty_.wait(lock, [&]()->bool
{
return queue_.size() > 0;
});
}
Task task;
if (!queue_.empty())
{
task = std::move(queue_.front());
queue_.pop_front();
if (maxQueueSize_ > 0)
{
notFull_.notify_one();
}
}
return std::move(task);
}
void ThreadPool::threadFunc()
{
try
{
while (runing_)
{
Task task(take());
task();
}
}
catch (const std::exception &ex)
{
LOG(FATAL) << "exception caught in ThreadPool : " << name_.c_str() << " reason: " << ex.what();
}
}
}
| 17.193277
| 98
| 0.596774
|
Txhua
|
afaf420c56422e9a2bb396d248c2f85d4848be81
| 1,035
|
cpp
|
C++
|
LuckyPurchase/LuckyPurchase.cpp
|
HPCCS/Computation-Kernel-Dataset
|
5a184c7846c1abff39426a7f53fb837de8ba36e3
|
[
"MIT"
] | 1
|
2019-05-03T19:37:24.000Z
|
2019-05-03T19:37:24.000Z
|
LuckyPurchase/LuckyPurchase.cpp
|
HPCCS/Computation-Kernel-Dataset
|
5a184c7846c1abff39426a7f53fb837de8ba36e3
|
[
"MIT"
] | null | null | null |
LuckyPurchase/LuckyPurchase.cpp
|
HPCCS/Computation-Kernel-Dataset
|
5a184c7846c1abff39426a7f53fb837de8ba36e3
|
[
"MIT"
] | null | null | null |
// problem statement is in https://www.hackerrank.com/contests/w35/challenges/lucky-purchase/problem
#include <bits/stdc++.h>
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
freopen("../input_files/LuckyPurchase", "r", stdin);
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int n;
cin>>n;
string ans;
int m=1000000000;
int az=89;
while(n--){
string a;
int b;
cin>>a>>b;
bool ok=true;
int f=0,s=0,x=b;
az=89;
while(b)
{
int g=b%10;
if(g==4)
f++;
else if(g==7)
s++;
else
ok=false;
b=b/10;
}
if(ok&&f==s)
{
if(m>x)
{
m=x;
ans=a;
}
}
}
if(ans.size())
cout<<ans;
else
cout<<"-1";
return 0;
}
| 19.528302
| 100
| 0.439614
|
HPCCS
|
afaf790c6680da8ae9323b40e16a04b9b48f024f
| 693
|
hpp
|
C++
|
math/mod_sqrt.hpp
|
hotman78/cpplib
|
c2f85c8741cdd0b731a5aa828b28b38c70c8d699
|
[
"CC0-1.0"
] | null | null | null |
math/mod_sqrt.hpp
|
hotman78/cpplib
|
c2f85c8741cdd0b731a5aa828b28b38c70c8d699
|
[
"CC0-1.0"
] | null | null | null |
math/mod_sqrt.hpp
|
hotman78/cpplib
|
c2f85c8741cdd0b731a5aa828b28b38c70c8d699
|
[
"CC0-1.0"
] | null | null | null |
#include<tuple>
#include"mod_pow.hpp"
#include"../util/random_gen.hpp"
/**
* @brief ModSqrt
*/
long long mod_sqrt(long long a,long long mod){
if(mod==2||a==0)return a;
if(mod_pow(a,(mod-1)/2,mod)!=1)return -1;
if(mod%4==3)return mod_pow(a,(mod+1)/4,mod);
long long q=(mod-1),s=0;
while(q%2==0)q/=2,s++;
long long z=1;
RandomNumberGenerator rnd;
while(mod_pow(z=rnd(0,mod),(mod-1)/2,mod)!=mod-1);
long long c=mod_pow(z,q,mod),t=mod_pow(a,q,mod),r=mod_pow(a,(q+1)/2,mod),m=s;
while(m>1){
if(mod_pow(t,1<<(m-2),mod)==1)(c*=c)%=mod,--m;
else std::tie(c,t,r,m)=std::make_tuple(c*c%mod,c*c%mod*t%mod,c*r%mod,m-1);
}
return r%mod;
}
| 28.875
| 82
| 0.580087
|
hotman78
|
afb2c1e102f49c56caf64e4c4f1d6017528cdcc6
| 856
|
cpp
|
C++
|
examples/google-code-jam/hustsxh/b.cpp
|
rbenic-fer/progauthfp
|
d0fd96c31ab0aab1a9acdcb7c75f2b430f51c675
|
[
"MIT"
] | null | null | null |
examples/google-code-jam/hustsxh/b.cpp
|
rbenic-fer/progauthfp
|
d0fd96c31ab0aab1a9acdcb7c75f2b430f51c675
|
[
"MIT"
] | null | null | null |
examples/google-code-jam/hustsxh/b.cpp
|
rbenic-fer/progauthfp
|
d0fd96c31ab0aab1a9acdcb7c75f2b430f51c675
|
[
"MIT"
] | null | null | null |
#include <cstdio>
#include <iostream>
using namespace std;
int a[100][100];
bool check(int n, int m) {
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
bool col = false, row = false;
for (int k = 0; k < n; ++k) {
if (a[k][j] > a[i][j]) {
col = true;
}
}
for (int k = 0; k < m; ++k) {
if (a[i][k] > a[i][j]) {
row = true;
}
}
if (col && row) {
return false;
}
}
}
return true;
}
int solve() {
int n, m;
cin >> n >> m;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
cin >> a[i][j];
}
}
if(check(n, m)) {
cout << "YES" << endl;
} else {
cout << "NO" << endl;
}
return 0;
}
int main() {
int T;
freopen("B-large.in", "r", stdin);
freopen("B.out", "w", stdout);
cin >> T;
for (int t = 1; t <= T; ++t) {
cout << "Case #" << t << ": ";
solve();
}
}
| 15.563636
| 35
| 0.421729
|
rbenic-fer
|
afbcb634b16cb6fdd0f460d10b9741487ac6f087
| 7,519
|
cpp
|
C++
|
libairt/aerotoolsGimbalMessageProcessor.cpp
|
AiRT-Software/ocs
|
2d6056a1260ac9ac75cfd507fb1a77db3b26298a
|
[
"BSD-4-Clause"
] | 1
|
2019-02-07T12:24:51.000Z
|
2019-02-07T12:24:51.000Z
|
libairt/aerotoolsGimbalMessageProcessor.cpp
|
AiRT-Software/ocs
|
2d6056a1260ac9ac75cfd507fb1a77db3b26298a
|
[
"BSD-4-Clause"
] | null | null | null |
libairt/aerotoolsGimbalMessageProcessor.cpp
|
AiRT-Software/ocs
|
2d6056a1260ac9ac75cfd507fb1a77db3b26298a
|
[
"BSD-4-Clause"
] | 1
|
2020-07-06T10:33:10.000Z
|
2020-07-06T10:33:10.000Z
|
#include <cstring>
#include <cassert>
//#include "../atreyu/include/fcsmodule.h"
#include "aerotoolsGimbalMessageProcessor.h"
#include "stdMessage.h"
#ifdef TESTING
#include "dummySerial.h"
#else
#include "serial.h"
#endif
#include "log.h"
#include "utils.h"
#define MAX_MSG_LENGTH 64
#define SYNC1 0xb5
#define SYNC2 0xca
#define ID_INDEX 2U
#define LENGTH_INDEX 3U
#define PAYLOAD_INDEX 4U
#define MIN_MESSAGE_SIZE 5U
using airt::AeroToolsGimbalMessageProcessor;
using airt::StdMessage;
enum Commands
{
GOTO_ANGLE = 1,
SET_SPEED_DEPRECATED,
MOVE_PITCH,
MOVE_ROLL,
MOVE_YAW,
STOP_PITCH,
STOP_ROLL,
STOP_YAW,
STOP_ALL,
RC_MODE,
RC_FIX_MODE,
RC_NOROLL_MODE,
GOTO_ZERO
};
inline uint8_t airtToAerotools(uint8_t airtCommand)
{
return airtCommand - (airt::StdMessage::GIMBAL_GOTO_ANGLE - GOTO_ANGLE);
}
enum Notifications
{
};
// From Aerotools codes -> AiRT
// static unsigned char ATtoAirtCommands[]{
// 0,
// StdMessage::FCS_PING, // PING = 1,
// StdMessage::FCS_VERSION, // VERSION,
// StdMessage::FCS_CLEARALL, // CLEARALL,
// StdMessage::FCS_SETMODE, // SETMODE,
// StdMessage::FCS_GOTO, // GOTOWP,
// StdMessage::FCS_WP, // WP,
// StdMessage::FCS_ARM, // ARM,
// StdMessage::FCS_DISARM, // DISARM,
// StdMessage::FCS_TAKEOFF, // TAKEOFF,
// StdMessage::FCS_LAND, // LAND,
// StdMessage::FCS_POSITIONON, // POSITIONON,
// StdMessage::FCS_POSITIONOFF, // POSITIONOFF,
// StdMessage::FCS_SETSPEED, // SETSPEED
// StdMessage::FCS_CREATEMISSION
// };
AeroToolsGimbalMessageProcessor::AeroToolsGimbalMessageProcessor() : inbuffer(bufferCapacity), state(Status::FIRST_SYNC), discarded_bytes(0), payload_read_bytes(0)
{
static_assert(static_cast<uint8_t>(GOTO_ZERO) == 0xd, "Have you changed the Command enums? Make sure ATtoAirtCommands still works");
static_assert(static_cast<uint8_t>(StdMessage::GIMBAL_GOTO_ANGLE) - static_cast<uint8_t>(GOTO_ANGLE) ==
static_cast<uint8_t>(StdMessage::GIMBAL_GOTO_ZERO) - static_cast<uint8_t>(GOTO_ZERO),
"Have you changed the Command enum? Make sure ATtoAirtCommands still works");
}
bool AeroToolsGimbalMessageProcessor::ingest(unsigned char *data, unsigned int size)
{
if (size + inbuffer.size() > inbuffer.capacity())
return false;
inbuffer.insert(inbuffer.end(), data, data + size);
return true;
}
bool AeroToolsGimbalMessageProcessor::sendCommand(Serial &port, enum airt::GimbalMultiplexerCommandType c)
{
uint8_t airtCommand = static_cast<uint8_t>(c);
switch (airtCommand)
{
case StdMessage::GIMBAL_STOP_PITCH:
case StdMessage::GIMBAL_STOP_ROLL:
case StdMessage::GIMBAL_STOP_YAW:
case StdMessage::GIMBAL_STOP_ALL:
case StdMessage::GIMBAL_RC_MODE:
case StdMessage::GIMBAL_RC_FIX_MODE:
case StdMessage::GIMBAL_RC_NOROLL_MODE:
case StdMessage::GIMBAL_GOTO_ZERO:
return sendATCommand(port, airtToAerotools(airtCommand));
default:
return false;
}
}
bool AeroToolsGimbalMessageProcessor::sendATCommand(Serial &port, unsigned char c)
{
unsigned char msg[5]{SYNC1, SYNC2, 0x0, 0x0, 0x0};
msg[ID_INDEX] = c;
msg[MIN_MESSAGE_SIZE - 1] = msg[ID_INDEX];
Log::info("Sending to Gimbal non-payload command {}", c);
return port.write(msg, sizeof(msg)) == sizeof(msg);
}
bool AeroToolsGimbalMessageProcessor::sendATCommand(Serial &port, unsigned char c, unsigned char *payload, unsigned int size)
{
unsigned int totalMsgSize = size + MIN_MESSAGE_SIZE;
unsigned char buffer[MAX_MSG_LENGTH];
buffer[0] = SYNC1;
buffer[1] = SYNC2;
buffer[ID_INDEX] = c;
buffer[LENGTH_INDEX] = size;
memcpy(buffer + LENGTH_INDEX + 1, payload, size);
buffer[totalMsgSize - 1] = checksum(buffer);
Log::info("Sending to Gimbal command {} ({} bytes)", c, totalMsgSize);
return port.write(buffer, totalMsgSize) == totalMsgSize;
}
unsigned char AeroToolsGimbalMessageProcessor::checksum(unsigned char *msg)
{
assert(msg[0] == SYNC1);
assert(msg[1] == SYNC2);
unsigned int suma = msg[ID_INDEX] + msg[LENGTH_INDEX];
for (int i = 0; i < msg[LENGTH_INDEX]; i++)
{
suma += msg[i + LENGTH_INDEX + 1];
}
return (unsigned char)suma;
}
bool AeroToolsGimbalMessageProcessor::hasMessages()
{
if (state == Status::DONE)
return true;
return parse();
}
bool AeroToolsGimbalMessageProcessor::popMessage(unsigned char *buffer, const unsigned int max, unsigned int &size)
{
if (!hasMessages())
return false;
assert(message.size() < max);
translateNotification(buffer, max, size);
state = Status::FIRST_SYNC;
message.clear();
payload_read_bytes = 0;
return true;
}
void AeroToolsGimbalMessageProcessor::restart()
{
discarded_bytes += message.size();
message.clear();
state = Status::FIRST_SYNC;
payload_read_bytes = 0;
}
bool AeroToolsGimbalMessageProcessor::parse()
{
while (!inbuffer.empty() && state != Status::DONE)
{
unsigned char c = inbuffer[0];
inbuffer.pop_front();
message.push_back(c);
switch (state)
{
case Status::FIRST_SYNC:
if (c == SYNC1)
state = Status::SECOND_SYNC;
else
restart();
break;
case Status::SECOND_SYNC:
if (c == SYNC2)
state = Status::ID;
else
restart();
break;
case Status::ID:
state = Status::LENGTH;
break;
case Status::LENGTH:
if (c == 0)
state = Status::CHKSUM;
else
{
state = Status::PAYLOAD;
payload_read_bytes = 0;
}
break;
case Status::PAYLOAD:
payload_read_bytes++;
if (payload_read_bytes >= message[LENGTH_INDEX])
{
state = Status::CHKSUM;
}
break;
case Status::CHKSUM:
state = Status::DONE;
Log::info("Received msg from serial: {} ({} bytes)", message[ID_INDEX], message.size());
break;
case Status::DONE:
assert(false);
break;
}
}
return state == Status::DONE;
}
bool AeroToolsGimbalMessageProcessor::sendGotoAngle(Serial &port, float pitch, float roll, float yaw, float speedRadPerSec)
{
short int sipitch = static_cast<short int>((pitch * 180.0 / M_PI) + 0.5),
siroll = static_cast<short int>((roll * 180.0 / M_PI) + 0.5),
siyaw = static_cast<short int>((yaw * 180.0 / M_PI) + 0.5);
uint8_t bspeed = static_cast<uint8_t>((speedRadPerSec * 180.0 / M_PI) + 0.5f);
uint8_t buffer[7];
buffer[0] = sipitch >> 8;
buffer[1] = sipitch & 0xff;
buffer[2] = siroll >> 8;
buffer[3] = siroll & 0xff;
buffer[4] = siyaw >> 8;
buffer[5] = siyaw & 0xff;
buffer[6] = bspeed;
return sendATCommand(port, airtToAerotools(StdMessage::GIMBAL_GOTO_ANGLE), buffer, sizeof(buffer));
}
template <typename C>
void copyMessage(C *msg, unsigned char *buffer, unsigned int &size)
{
memcpy(buffer, msg, sizeof(C));
size = sizeof(C);
}
void AeroToolsGimbalMessageProcessor::translateNotification(unsigned char *buffer, const unsigned int max, unsigned int &size)
{
switch (message[ID_INDEX])
{
break;
}
}
| 28.266917
| 163
| 0.637053
|
AiRT-Software
|
afbe2948c86a6d57117993141ede06fed06951e9
| 179
|
cpp
|
C++
|
ural/1876.cpp
|
jffifa/algo-solution
|
af2400d6071ee8f777f9473d6a34698ceef08355
|
[
"MIT"
] | 5
|
2015-07-14T10:29:25.000Z
|
2016-10-11T12:45:18.000Z
|
ural/1876.cpp
|
jffifa/algo-solution
|
af2400d6071ee8f777f9473d6a34698ceef08355
|
[
"MIT"
] | null | null | null |
ural/1876.cpp
|
jffifa/algo-solution
|
af2400d6071ee8f777f9473d6a34698ceef08355
|
[
"MIT"
] | 3
|
2016-08-23T01:05:26.000Z
|
2017-05-28T02:04:20.000Z
|
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int a, b;
int main()
{
scanf("%d%d", &a, &b);
printf("%d\n", max(2*b+40, 2*a+39));
return 0;
}
| 12.785714
| 37
| 0.597765
|
jffifa
|
afc3b8d5f63225653ac6f6628d6338957f3037cd
| 10,458
|
cpp
|
C++
|
libraries/AXP192/AXP192.cpp
|
vanvuongngo/Maixduino
|
aa6543538ccfb54a89e9922dd38f5b4710a9c2a4
|
[
"Apache-2.0"
] | 195
|
2019-04-02T02:28:34.000Z
|
2022-03-23T07:45:31.000Z
|
libraries/AXP192/AXP192.cpp
|
vanvuongngo/Maixduino
|
aa6543538ccfb54a89e9922dd38f5b4710a9c2a4
|
[
"Apache-2.0"
] | 106
|
2019-04-03T12:27:01.000Z
|
2022-03-25T12:59:33.000Z
|
libraries/AXP192/AXP192.cpp
|
vanvuongngo/Maixduino
|
aa6543538ccfb54a89e9922dd38f5b4710a9c2a4
|
[
"Apache-2.0"
] | 101
|
2019-04-03T06:14:04.000Z
|
2022-03-15T06:31:58.000Z
|
#include "AXP192.h"
AXP192::AXP192()
{
}
void AXP192::begin(bool isInited)
{
if(!isInited){
Wire.begin((uint8_t) SDA, (uint8_t) SCL, 400000);
}
Write1Byte(0x46, 0xFF); //Clear interupts
Write1Byte(0x23, 0x08); //Set DC-DC2 (VCore) to 0V9
Write1Byte(0x33, 0xC0); //Set Bat Charging Voltage to 4V2, Current to 100mA
Write1Byte(0x36, 0x0C); //Set 128ms power on, 4s power off
Write1Byte(0x91, 0xF0); //Set GPIO0 (TFT_BL) (from 0x70 (min)) to 3V3 (max)
Write1Byte(0x90, 0x02); //Set GPIO0 to LDO mode
Write1Byte(0x28, 0xF0); //VDD2.8V net: LDO2 3.3V, VDD 1.5V net: LDO3 1.8V
Write1Byte(0x27, 0x2C); //VDD1.8V net: DC-DC3 1.8V
Write1Byte(0x12, 0xFF); //Enble all LDO/DC_DC and EXTEN
Write1Byte(0x23, 0x08); //VDD 0.9v net: DC-DC2 0.9V
Write1Byte(0x32, 0x46); //Enable bat detection
Write1Byte(0x39, 0xFC); //Disable Temp Protection (Sensor doesn't exist!)
Write1Byte(0x31, (Read8bit(0x31) & 0xf8) | (1 << 2)); // Set Power off voltage 3V0
fpioa_set_function(INTL_INT, (fpioa_function_t)(FUNC_GPIOHS0 + 26));
gpiohs_set_drive_mode(26, GPIO_DM_OUTPUT);
gpiohs_set_pin(26, GPIO_PV_HIGH); //Disable VBUS As Input, BAT->5V Boost->VBUS->Charing Cycle
msleep(20);
}
void AXP192::Write1Byte( uint8_t Addr , uint8_t Data )
{
Wire.beginTransmission(AXP_ADDR);
Wire.write(Addr);
Wire.write(Data);
Wire.endTransmission();
}
uint8_t AXP192::Read8bit( uint8_t Addr )
{
Wire.beginTransmission(AXP_ADDR);
Wire.write(Addr);
Wire.endTransmission();
Wire.requestFrom(AXP_ADDR, 1);
return Wire.read();
}
uint16_t AXP192::Read12Bit( uint8_t Addr)
{
uint16_t Data = 0;
uint8_t buf[2];
ReadBuff(Addr,2,buf);
Data = ((buf[0] << 4) + buf[1]);
return Data;
}
uint16_t AXP192::Read13Bit( uint8_t Addr)
{
uint16_t Data = 0;
uint8_t buf[2];
ReadBuff(Addr,2,buf);
Data = ((buf[0] << 5) + buf[1]);
return Data;
}
uint16_t AXP192::Read16bit( uint8_t Addr )
{
uint16_t ReData = 0;
Wire.beginTransmission(AXP_ADDR);
Wire.write(Addr);
Wire.endTransmission();
Wire.requestFrom(AXP_ADDR, 2);
for( int i = 0 ; i < 2 ; i++ )
{
ReData <<= 8;
ReData |= Wire.read();
}
return ReData;
}
uint32_t AXP192::Read24bit( uint8_t Addr )
{
uint32_t ReData = 0;
Wire.beginTransmission(AXP_ADDR);
Wire.write(Addr);
Wire.endTransmission();
Wire.requestFrom(AXP_ADDR, 3);
for( int i = 0 ; i < 3 ; i++ )
{
ReData <<= 8;
ReData |= Wire.read();
}
return ReData;
}
uint32_t AXP192::Read32bit( uint8_t Addr )
{
uint32_t ReData = 0;
Wire.beginTransmission(AXP_ADDR);
Wire.write(Addr);
Wire.endTransmission();
Wire.requestFrom(AXP_ADDR, 4);
for( int i = 0 ; i < 4 ; i++ )
{
ReData <<= 8;
ReData |= Wire.read();
}
return ReData;
}
void AXP192::ReadBuff( uint8_t Addr , uint8_t Size , uint8_t *Buff )
{
Wire.beginTransmission(AXP_ADDR);
Wire.write(Addr);
Wire.endTransmission();
Wire.requestFrom(AXP_ADDR, (int)Size);
for (int i = 0; i < Size; i++)
{
*( Buff + i ) = Wire.read();
}
}
void AXP192::ScreenBreath(uint8_t brightness)
{
if (brightness > 12)
{
brightness = 12;
}
uint8_t buf = Read8bit( 0x28 );
Write1Byte( 0x28 , ((buf & 0x0f) | (brightness << 4)) );
}
// Return True = Battery Exist
bool AXP192::GetBatState()
{
if( Read8bit(0x01) | 0x20 )
return true;
else
return false;
}
// Input Power Status
uint8_t AXP192::GetInputPowerStatus()
{
return Read8bit(0x00);
}
// Battery Charging Status
uint8_t AXP192::GetBatteryChargingStatus()
{
return Read8bit(0x01);
}
//---------coulombcounter_from_here---------
//enable: void EnableCoulombcounter(void);
//disable: void DisableCOulombcounter(void);
//stop: void StopCoulombcounter(void);
//clear: void ClearCoulombcounter(void);
//get charge data: uint32_t GetCoulombchargeData(void);
//get discharge data: uint32_t GetCoulombdischargeData(void);
//get coulomb val affter calculation: float GetCoulombData(void);
//------------------------------------------
void AXP192::EnableCoulombcounter(void)
{
Write1Byte( 0xB8 , 0x80 );
}
void AXP192::DisableCoulombcounter(void)
{
Write1Byte( 0xB8 , 0x00 );
}
void AXP192::StopCoulombcounter(void)
{
Write1Byte( 0xB8 , 0xC0 );
}
void AXP192::ClearCoulombcounter(void)
{
Write1Byte( 0xB8, Read8bit(0xB8) | 0x20); // Only set the Clear Flag
}
uint32_t AXP192::GetCoulombchargeData(void)
{
return Read32bit(0xB0);
}
uint32_t AXP192::GetCoulombdischargeData(void)
{
return Read32bit(0xB4);
}
float AXP192::GetCoulombData(void)
{
uint32_t coin = GetCoulombchargeData();
uint32_t coout = GetCoulombdischargeData();
uint32_t valueDifferent = 0;
bool bIsNegative = false;
if (coin > coout)
{ // Expected, in always more then out
valueDifferent = coin - coout;
}
else
{ // Warning: Out is more than In, the battery is not started at 0%
// just Flip the output sign later
bIsNegative = true;
valueDifferent = coout - coin;
}
//c = 65536 * current_LSB * (coin - coout) / 3600 / ADC rate
//Adc rate can be read from 84H, change this variable if you change the ADC reate
float ccc = (65536 * 0.5 * valueDifferent) / 3600.0 / 200.0; // Note the ADC has defaulted to be 200 Hz
if( bIsNegative )
ccc = 0.0 - ccc; // Flip it back to negative
return ccc;
}
//----------coulomb_end_at_here----------
uint8_t AXP192::GetWarningLeve(void)
{
Wire.beginTransmission(AXP_ADDR);
Wire.write(0x47);
Wire.endTransmission();
Wire.requestFrom(AXP_ADDR, 1);
uint8_t buf = Wire.read();
return (buf & 0x01);
}
void AXP192::SetSleep(void)
{
Write1Byte(0x31 , Read8bit(0x31) | ( 1 << 3)); // Turn on short press to wake up
Write1Byte(0x90 , Read8bit(0x90) | 0x07); // GPIO1 floating
Write1Byte(0x82, 0x00); // Disable ADCs
Write1Byte(0x12, Read8bit(0x12) & 0xA1); // Disable all outputs but DCDC1
}
// Return 0 = not press, 0x01 = long press(1.5s), 0x02 = short press
uint8_t AXP192::GetBtnPress()
{
uint8_t state = Read8bit(0x46); // IRQ 3 status.
if(state)
{
Write1Byte( 0x46 , 0x03 ); // Write 1 back to clear IRQ
}
return state;
}
// Low Volt Level 1, when APS Volt Output < 3.4496 V
// Low Volt Level 2, when APS Volt Output < 3.3992 V, then this flag is SET (0x01)
// Flag will reset once battery volt is charged above Low Volt Level 1
// Note: now AXP192 have the Shutdown Voltage of 3.0V (B100) Def in REG 31H
uint8_t AXP192::GetWarningLevel(void)
{
return Read8bit(0x47) & 0x01;
}
float AXP192::GetBatVoltage()
{
float ADCLSB = 1.1 / 1000.0;
uint16_t ReData = Read12Bit( 0x78 );
return ReData * ADCLSB;
}
float AXP192::GetBatCurrent()
{
float ADCLSB = 0.5;
uint16_t CurrentIn = Read13Bit( 0x7A );
uint16_t CurrentOut = Read13Bit( 0x7C );
return ( CurrentIn - CurrentOut ) * ADCLSB;
}
float AXP192::GetVinVoltage()
{
float ADCLSB = 1.7 / 1000.0;
uint16_t ReData = Read12Bit( 0x56 );
return ReData * ADCLSB;
}
float AXP192::GetVinCurrent()
{
float ADCLSB = 0.625;
uint16_t ReData = Read12Bit( 0x58 );
return ReData * ADCLSB;
}
float AXP192::GetVBusVoltage()
{
float ADCLSB = 1.7 / 1000.0;
uint16_t ReData = Read12Bit( 0x5A );
return ReData * ADCLSB;
}
float AXP192::GetVBusCurrent()
{
float ADCLSB = 0.375;
uint16_t ReData = Read12Bit( 0x5C );
return ReData * ADCLSB;
}
float AXP192::GetTempInAXP192()
{
float ADCLSB = 0.1;
const float OFFSET_DEG_C = -144.7;
uint16_t ReData = Read12Bit( 0x5E );
return OFFSET_DEG_C + ReData * ADCLSB;
}
float AXP192::GetBatPower()
{
float VoltageLSB = 1.1;
float CurrentLCS = 0.5;
uint32_t ReData = Read24bit( 0x70 );
return VoltageLSB * CurrentLCS * ReData/ 1000.0;
}
float AXP192::GetBatChargeCurrent()
{
float ADCLSB = 0.5;
uint16_t ReData = Read13Bit( 0x7A );
return ReData * ADCLSB;
}
float AXP192::GetAPSVoltage()
{
float ADCLSB = 1.4 / 1000.0;
uint16_t ReData = Read12Bit( 0x7E );
return ReData * ADCLSB;
}
float AXP192::GetBatCoulombInput()
{
uint32_t ReData = Read32bit( 0xB0 );
return ReData * 65536 * 0.5 / 3600 /25.0;
}
float AXP192::GetBatCoulombOut()
{
uint32_t ReData = Read32bit( 0xB4 );
return ReData * 65536 * 0.5 / 3600 /25.0;
}
// Can turn LCD Backlight OFF for power saving
void AXP192::SetLDO2( bool State )
{
uint8_t buf = Read8bit(0x12);
if( State == true )
{
buf = (1<<2) | buf;
}
else
{
buf = ~(1<<2) & buf;
}
Write1Byte( 0x12 , buf );
}
void AXP192::SetLDO3(bool State)
{
uint8_t buf = Read8bit(0x12);
if( State == true )
{
buf = (1<<3) | buf;
}
else
{
buf = ~(1<<3) & buf;
}
Write1Byte( 0x12 , buf );
}
// Not recommend to set charge current > 100mA, since Battery is only 80mAh.
// more then 1C charge-rate may shorten battery life-span.
void AXP192::SetChargeCurrent(uint8_t current)
{
uint8_t buf = Read8bit(0x33);
buf = (buf & 0xf0) | (current & 0x07);
Write1Byte(0x33, buf);
}
// Cut all power, except for LDO1 (RTC)
void AXP192::PowerOff()
{
Write1Byte(0x32, Read8bit(0x32) | 0x80); // MSB for Power Off
}
void AXP192::SetAdcState(bool state)
{
Write1Byte(0x82, state ? 0xff : 0x00); // Enable / Disable all ADCs
}
// AXP192 have a 6 byte storage, when the power is still valid, the data will not be lost
void AXP192::Read6BytesStorage( uint8_t *bufPtr )
{
// Address from 0x06 - 0x0B
Wire.beginTransmission(AXP_ADDR);
Wire.write(0x06);
Wire.endTransmission();
Wire.requestFrom(AXP_ADDR, 6);
for( int i = 0; i < 6; ++i )
{
bufPtr[i] = Wire.read();
}
}
// AXP192 have a 6 byte storage, when the power is still valid, the data will not be lost
void AXP192::Write6BytesStorage( uint8_t *bufPtr )
{
// Address from 0x06 - 0x0B
Wire.beginTransmission(AXP_ADDR);
Wire.write(0x06);
Wire.write(bufPtr[0]);
Wire.write(0x07);
Wire.write(bufPtr[1]);
Wire.write(0x08);
Wire.write(bufPtr[2]);
Wire.write(0x09);
Wire.write(bufPtr[3]);
Wire.write(0x0A);
Wire.write(bufPtr[4]);
Wire.write(0x0B);
Wire.write(bufPtr[5]);
Wire.endTransmission();
}
| 24.377622
| 108
| 0.633295
|
vanvuongngo
|
afc4bf4b963c5dd49becb5584f83ccf3439a8bed
| 3,896
|
cpp
|
C++
|
Java-and-C++/AnalyticFunctions/NthValue.cpp
|
vietnguyen1989/UDx-Examples
|
4b72aaa7402c93890500d37c1b888230cc6524e2
|
[
"BSD-3-Clause"
] | 12
|
2017-08-16T09:58:50.000Z
|
2020-05-08T12:03:57.000Z
|
Java-and-C++/AnalyticFunctions/NthValue.cpp
|
vietnguyen1989/UDx-Examples
|
4b72aaa7402c93890500d37c1b888230cc6524e2
|
[
"BSD-3-Clause"
] | 1
|
2021-04-21T21:39:03.000Z
|
2021-04-21T21:39:03.000Z
|
Java-and-C++/AnalyticFunctions/NthValue.cpp
|
vietnguyen1989/UDx-Examples
|
4b72aaa7402c93890500d37c1b888230cc6524e2
|
[
"BSD-3-Clause"
] | 15
|
2016-12-21T09:57:22.000Z
|
2021-11-25T22:30:24.000Z
|
/* Copyright (c) 2005 - 2016 Hewlett Packard Enterprise Development LP -*- C++ -*-*/
/*
* Description: Example User Defined Analytic Function nth_value to output the value of the nth row.
*
* Create Date: Mar 13, 2014
*/
#include "Vertica.h"
#include <sstream>
using namespace Vertica;
/*
* The analytic function nth_value(numeric a, int n) returns value "a" evaluated on
* the n-th row in the input partition defined by the OVER clause.
* This function generalizes the built-in analytic functions FIRST_VALUE and LAST_VALUE,
* which return the first value and last value, respectively, of an input partition.
*/
class NthValue : public AnalyticFunction
{
virtual void processPartition(ServerInterface &srvInterface,
AnalyticPartitionReader &inputReader,
AnalyticPartitionWriter &outputWriter)
{
try {
const SizedColumnTypes &inTypes = inputReader.getTypeMetaData();
std::vector<size_t> argCols; // Argument column indexes.
inTypes.getArgumentColumns(argCols);
vint nParam = 0;
// Two function arguments expected.
if (argCols.size() != 2 ||
!inTypes.getColumnType(argCols.at(0)).isNumeric() || // a argument
!inTypes.getColumnType(argCols.at(1)).isInt() || // n argument
(nParam = inputReader.getIntRef(argCols.at(1))) < 1) // n positive?
vt_report_error(1, "Two arguments (numeric, int) are expected with the second argument being a positive integer.");
vint currentRow = 1;
bool nthRowExists = false;
// Find the value of the n-th row.
do {
if (currentRow == nParam) {
nthRowExists = true;
break;
} else {
currentRow++;
}
} while (inputReader.next());
// Output the n-th value.
if (nthRowExists) {
do {
outputWriter.copyFromInput(0 /*dest*/, inputReader, argCols.at(0) /*src*/);
} while (outputWriter.next());
} else {
// The partition has less than n rows. Output NULL values.
do {
outputWriter.setNull(0);
} while (outputWriter.next());
}
} catch(std::exception& e) {
// Standard exception. Quit.
vt_report_error(0, "Exception while processing partition: [%s]", e.what());
}
}
};
class NthValueFactory : public AnalyticFunctionFactory
{
virtual void getPrototype(ServerInterface &srvInterface, ColumnTypes &argTypes, ColumnTypes &returnType)
{
argTypes.addNumeric(); // numeric expression.
argTypes.addInt(); // n-th row argument.
returnType.addNumeric();
}
virtual void getReturnType(ServerInterface &srvInterface,
const SizedColumnTypes &inputTypes,
SizedColumnTypes &outputTypes)
{
std::vector<size_t> argCols; // Argument column indexes.
inputTypes.getArgumentColumns(argCols);
// Two arguments are expected with optional Pby and Oby clauses.
if (argCols.size() != 2 || !inputTypes.getColumnType(argCols.at(0)).isNumeric())
vt_report_error(1, "Two arguments (numeric, int) are expected with the second argument being a positive integer.");
const VerticaType &vt = inputTypes.getColumnType(argCols.at(0));
outputTypes.addNumeric(vt.getNumericPrecision(), vt.getNumericScale());
}
virtual AnalyticFunction *createAnalyticFunction(ServerInterface &srvInterface)
{ return vt_createFuncObject<NthValue>(srvInterface.allocator); }
};
RegisterFactory(NthValueFactory);
| 39.755102
| 131
| 0.598563
|
vietnguyen1989
|
afc6ce2b22fd60ed9f924af7018858602daff4e2
| 3,389
|
hpp
|
C++
|
engine/includes/asset_importer/texture_importer.hpp
|
StuartDAdams/neon
|
d08a63b853801aec94390e50f2988d0217438061
|
[
"MIT"
] | 1
|
2019-08-22T14:43:18.000Z
|
2019-08-22T14:43:18.000Z
|
engine/includes/asset_importer/texture_importer.hpp
|
StuartDAdams/neon
|
d08a63b853801aec94390e50f2988d0217438061
|
[
"MIT"
] | null | null | null |
engine/includes/asset_importer/texture_importer.hpp
|
StuartDAdams/neon
|
d08a63b853801aec94390e50f2988d0217438061
|
[
"MIT"
] | null | null | null |
/*
===========================================================================
Moka Source Code
Copyright 2019 Stuart Adams. All rights reserved.
https://github.com/stuartdadams/moka
stuartdadams | linkedin.com/in/stuartdadams
This file is part of the Moka Real-Time Physically-Based Rendering Project.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
===========================================================================
*/
#pragma once
#include <filesystem>
#include <graphics/texture_handle.hpp>
namespace moka
{
/**
* \brief Load a texture from file into host memory.
* \param path The path to the texture you want to import.
* \param width This value will be re-assigned in the function to the width of the image.
* \param height This value will be re-assigned in the function to the height of the image.
* \param format This value will be re-assigned in the function to the format of the image.
* \param requested_format The format you wish the image to be imported with.
* \return The host image data - a heap-allocated array of bytes! Free this data after use using free_texture()
*/
std::byte* texture_load(
const std::filesystem::path& path,
int& width,
int& height,
host_format& format,
host_format requested_format = host_format::auto_detect);
/**
* \brief Load an HDR texture from file into host memory.
* \param path The path to the HDR texture you want to import.
* \param width This value will be re-assigned in the function to the width of the image.
* \param height This value will be re-assigned in the function to the height of the image.
* \param format This value will be re-assigned in the function to the format of the image.
* \param requested_format The format you wish the image to be imported with.
* \return The host image data - a heap-allocated array of floats! Free this data after use using free_texture()
*/
float* texture_load_hdr(
const std::filesystem::path& path,
int& width,
int& height,
host_format& format,
host_format requested_format = host_format::auto_detect);
/**
* \brief Free a heap-allocated buffer of host texture data.
* \param data The heap-allocated buffer of host texture data you wish to free.
*/
void free_texture(void* data);
} // namespace moka
| 45.186667
| 116
| 0.697551
|
StuartDAdams
|
afc888c91ca6936a0b4a9a6c029b9c2056c6c592
| 1,038
|
cpp
|
C++
|
src/gamebase/src/impl/graphics/LineProgram.cpp
|
TheMrButcher/opengl_lessons
|
76ac96c45773a54a85d49c6994770b0c3496303f
|
[
"MIT"
] | 1
|
2016-10-25T21:15:16.000Z
|
2016-10-25T21:15:16.000Z
|
src/gamebase/src/impl/graphics/LineProgram.cpp
|
TheMrButcher/gamebase
|
76ac96c45773a54a85d49c6994770b0c3496303f
|
[
"MIT"
] | 375
|
2016-06-04T11:27:40.000Z
|
2019-04-14T17:11:09.000Z
|
src/gamebase/src/impl/graphics/LineProgram.cpp
|
TheMrButcher/gamebase
|
76ac96c45773a54a85d49c6994770b0c3496303f
|
[
"MIT"
] | null | null | null |
/**
* Copyright (c) 2018 Slavnejshev Filipp
* This file is licensed under the terms of the MIT license.
*/
#include <stdafx.h>
#include <gamebase/impl/graphics/LineProgram.h>
#include "State.h"
#include "src/impl/global/Config.h"
namespace gamebase { namespace impl {
LineProgram::LineProgram()
: OneColorProgramBase(
"Line",
config().shadersPath + "Line.vs",
config().shadersPath + "Line.fs")
{
m_attrs.add("distance", 1);
m_attrs.add("extVec", 2);
}
void LineProgram::locateUniforms()
{
OneColorProgramBase::locateUniforms();
m_extScaleLocation = locateUniform("uExtScale");
}
void LineProgram::loadUniforms() const
{
OneColorProgramBase::loadUniforms();
const State& curState = state();
float extScale = 1.0f / (transform.matrix.scaleX() * curState.width);
glUniform1f(m_extScaleLocation, extScale);
}
const LineProgram& lineProgram()
{
const auto& program = state().programs.line;
program.activate();
program.resetUniforms();
return program;
}
} }
| 22.565217
| 73
| 0.684008
|
TheMrButcher
|
afcd5238b502b1281d4e74cb8bc0c9c3663229d0
| 41,674
|
cpp
|
C++
|
plugin_sa/game_sa/CTheScripts.cpp
|
gta-chaos-mod/plugin-sdk
|
e3bf176337774a2afc797a47825f81adde78e899
|
[
"Zlib"
] | 368
|
2015-01-01T21:42:00.000Z
|
2022-03-29T06:22:22.000Z
|
plugin_sa/game_sa/CTheScripts.cpp
|
SteepCheat/plugin-sdk
|
a17c5d933cb8b06e4959b370092828a6a7aa00ef
|
[
"Zlib"
] | 89
|
2016-05-08T06:42:36.000Z
|
2022-03-29T06:49:09.000Z
|
plugin_sa/game_sa/CTheScripts.cpp
|
SteepCheat/plugin-sdk
|
a17c5d933cb8b06e4959b370092828a6a7aa00ef
|
[
"Zlib"
] | 179
|
2015-02-03T23:41:17.000Z
|
2022-03-26T08:27:16.000Z
|
/*
Plugin-SDK (Grand Theft Auto San Andreas) source file
Authors: GTA Community. See more here
https://github.com/DK22Pac/plugin-sdk
Do not delete this comment block. Respect others' work!
*/
#include "CTheScripts.h"
PLUGIN_SOURCE_FILE
PLUGIN_VARIABLE bool &CTheScripts::DbgFlag = *reinterpret_cast<bool *>(GLOBAL_ADDRESS_BY_VERSION(0x859CF8, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE tScriptParam *CTheScripts::ScriptParams = reinterpret_cast<tScriptParam *>(GLOBAL_ADDRESS_BY_VERSION(0xA43C78, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE tScriptSwitchCase *CTheScripts::SwitchJumpTable = reinterpret_cast<tScriptSwitchCase *>(GLOBAL_ADDRESS_BY_VERSION(0xA43CF8, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE unsigned short &CTheScripts::NumberOfEntriesInSwitchTable = *reinterpret_cast<unsigned short *>(GLOBAL_ADDRESS_BY_VERSION(0xA43F50, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE void *&CTheScripts::SwitchDefaultAddress = *reinterpret_cast<void **>(GLOBAL_ADDRESS_BY_VERSION(0xA43F54, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE bool &CTheScripts::SwitchDefaultExists = *reinterpret_cast<bool *>(GLOBAL_ADDRESS_BY_VERSION(0xA43F58, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE int &CTheScripts::ValueToCheckInSwitchStatement = *reinterpret_cast<int *>(GLOBAL_ADDRESS_BY_VERSION(0xA43F5C, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE unsigned short &CTheScripts::NumberOfEntriesStillToReadForSwitch = *reinterpret_cast<unsigned short *>(GLOBAL_ADDRESS_BY_VERSION(0xA43F60, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE tScriptSequence *CTheScripts::ScriptSequenceTaskArray = reinterpret_cast<tScriptSequence *>(GLOBAL_ADDRESS_BY_VERSION(0xA43F68, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE unsigned short &CTheScripts::NumberOfScriptCheckpoints = *reinterpret_cast<unsigned short *>(GLOBAL_ADDRESS_BY_VERSION(0xA44068, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE tScriptCheckpoint *CTheScripts::ScriptCheckpointArray = reinterpret_cast<tScriptCheckpoint *>(GLOBAL_ADDRESS_BY_VERSION(0xA44070, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE tScriptEffectSystem *CTheScripts::ScriptEffectSystemArray = reinterpret_cast<tScriptEffectSystem *>(GLOBAL_ADDRESS_BY_VERSION(0xA44110, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE short &CTheScripts::CardStackPosition = *reinterpret_cast<short *>(GLOBAL_ADDRESS_BY_VERSION(0xA44210, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE short *CTheScripts::CardStack = reinterpret_cast<short *>(GLOBAL_ADDRESS_BY_VERSION(0xA44218, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE bool &CTheScripts::bDrawSubtitlesBeforeFade = *reinterpret_cast<bool *>(GLOBAL_ADDRESS_BY_VERSION(0xA44488, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE bool &CTheScripts::bDrawOddJobTitleBeforeFade = *reinterpret_cast<bool *>(GLOBAL_ADDRESS_BY_VERSION(0xA44489, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE bool &CTheScripts::bScriptHasFadedOut = *reinterpret_cast<bool *>(GLOBAL_ADDRESS_BY_VERSION(0xA4448A, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE bool &CTheScripts::bAddNextMessageToPreviousBriefs = *reinterpret_cast<bool *>(GLOBAL_ADDRESS_BY_VERSION(0xA4448B, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE int &CTheScripts::ForceRandomCarModel = *reinterpret_cast<int *>(GLOBAL_ADDRESS_BY_VERSION(0xA4448C, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE bool &CTheScripts::bDrawCrossHair = *reinterpret_cast<bool *>(GLOBAL_ADDRESS_BY_VERSION(0xA44490, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE bool &CTheScripts::bEnableCraneRelease = *reinterpret_cast<bool *>(GLOBAL_ADDRESS_BY_VERSION(0xA44494, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE bool &CTheScripts::bEnableCraneLower = *reinterpret_cast<bool *>(GLOBAL_ADDRESS_BY_VERSION(0xA44495, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE bool &CTheScripts::bEnableCraneRaise = *reinterpret_cast<bool *>(GLOBAL_ADDRESS_BY_VERSION(0xA44496, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE float &CTheScripts::fCameraHeadingStepWhenPlayerIsAttached = *reinterpret_cast<float *>(GLOBAL_ADDRESS_BY_VERSION(0xA44498, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE float &CTheScripts::fCameraHeadingWhenPlayerIsAttached = *reinterpret_cast<float *>(GLOBAL_ADDRESS_BY_VERSION(0xA4449C, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE bool &CTheScripts::bDisplayHud = *reinterpret_cast<bool *>(GLOBAL_ADDRESS_BY_VERSION(0xA444A0, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE bool &CTheScripts::HideAllFrontEndMapBlips = *reinterpret_cast<bool *>(GLOBAL_ADDRESS_BY_VERSION(0xA444A1, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE bool &CTheScripts::RadarShowBlipOnAllLevels = *reinterpret_cast<bool *>(GLOBAL_ADDRESS_BY_VERSION(0xA444A2, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE unsigned char &CTheScripts::RadarZoomValue = *reinterpret_cast<unsigned char *>(GLOBAL_ADDRESS_BY_VERSION(0xA444A3, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE bool &CTheScripts::bPlayerIsOffTheMap = *reinterpret_cast<bool *>(GLOBAL_ADDRESS_BY_VERSION(0xA444A4, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE char &CTheScripts::RiotIntensity = *reinterpret_cast<char *>(GLOBAL_ADDRESS_BY_VERSION(0xA444A5, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE bool &CTheScripts::bPlayerHasMetDebbieHarry = *reinterpret_cast<bool *>(GLOBAL_ADDRESS_BY_VERSION(0xA444A6, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE bool &CTheScripts::bDisplayNonMiniGameHelpMessages = *reinterpret_cast<bool *>(GLOBAL_ADDRESS_BY_VERSION(0xA444A7, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE bool &CTheScripts::bMiniGameInProgress = *reinterpret_cast<bool *>(GLOBAL_ADDRESS_BY_VERSION(0xA444A8, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE int &CTheScripts::ScriptPickupCycleIndex = *reinterpret_cast<int *>(GLOBAL_ADDRESS_BY_VERSION(0xA444AC, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE char &CTheScripts::FailCurrentMission = *reinterpret_cast<char *>(GLOBAL_ADDRESS_BY_VERSION(0xA444B0, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE bool &CTheScripts::bAlreadyRunningAMissionScript = *reinterpret_cast<bool *>(GLOBAL_ADDRESS_BY_VERSION(0xA444B1, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE unsigned int &CTheScripts::LargestNumberOfMissionScriptLocalVariables = *reinterpret_cast<unsigned int *>(GLOBAL_ADDRESS_BY_VERSION(0xA444B4, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE unsigned short &CTheScripts::NumberOfExclusiveMissionScripts = *reinterpret_cast<unsigned short *>(GLOBAL_ADDRESS_BY_VERSION(0xA444B8, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE unsigned short &CTheScripts::NumberOfMissionScripts = *reinterpret_cast<unsigned short *>(GLOBAL_ADDRESS_BY_VERSION(0xA444BC, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE unsigned int &CTheScripts::LargestMissionScriptSize = *reinterpret_cast<unsigned int *>(GLOBAL_ADDRESS_BY_VERSION(0xA444C0, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE unsigned int &CTheScripts::MainScriptSize = *reinterpret_cast<unsigned int *>(GLOBAL_ADDRESS_BY_VERSION(0xA444C4, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE char *CTheScripts::MultiScriptArray = reinterpret_cast<char *>(GLOBAL_ADDRESS_BY_VERSION(0xA444C8, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE bool &CTheScripts::bUsingAMultiScriptFile = *reinterpret_cast<bool *>(GLOBAL_ADDRESS_BY_VERSION(0xA447E8, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE int &CTheScripts::StoreVehicleIndex = *reinterpret_cast<int *>(GLOBAL_ADDRESS_BY_VERSION(0xA447EC, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE bool &CTheScripts::StoreVehicleWasRandom = *reinterpret_cast<bool *>(GLOBAL_ADDRESS_BY_VERSION(0xA447F0, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE unsigned short &CTheScripts::CommandsExecuted = *reinterpret_cast<unsigned short *>(GLOBAL_ADDRESS_BY_VERSION(0xA447F4, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE unsigned short &CTheScripts::ScriptsUpdated = *reinterpret_cast<unsigned short *>(GLOBAL_ADDRESS_BY_VERSION(0xA447F8, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE int *CTheScripts::ScriptConnectLodsObjects = reinterpret_cast<int *>(GLOBAL_ADDRESS_BY_VERSION(0xA44800, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE tScriptAttachedAnimGroup *CTheScripts::ScriptAttachedAnimGroups = reinterpret_cast<tScriptAttachedAnimGroup *>(GLOBAL_ADDRESS_BY_VERSION(0xA44850, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE int *CTheScripts::VehicleModelsBlockedByScript = reinterpret_cast<int *>(GLOBAL_ADDRESS_BY_VERSION(0xA448F0, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE int *CTheScripts::SuppressedVehicleModels = reinterpret_cast<int *>(GLOBAL_ADDRESS_BY_VERSION(0xA44940, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE CEntity **CTheScripts::InvisibilitySettingArray = reinterpret_cast<CEntity **>(GLOBAL_ADDRESS_BY_VERSION(0xA449E0, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE tBuildingSwap *CTheScripts::BuildingSwapArray = reinterpret_cast<tBuildingSwap *>(GLOBAL_ADDRESS_BY_VERSION(0xA44A30, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE unsigned short &CTheScripts::NumberOfIntroRectanglesThisFrame = *reinterpret_cast<unsigned short *>(GLOBAL_ADDRESS_BY_VERSION(0xA44B5C, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE unsigned short &CTheScripts::MessageWidth = *reinterpret_cast<unsigned short *>(GLOBAL_ADDRESS_BY_VERSION(0xA44B60, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE unsigned short &CTheScripts::MessageCentre = *reinterpret_cast<unsigned short *>(GLOBAL_ADDRESS_BY_VERSION(0xA44B64, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE bool &CTheScripts::bUseMessageFormatting = *reinterpret_cast<bool *>(GLOBAL_ADDRESS_BY_VERSION(0xA44B66, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE bool &CTheScripts::UseTextCommands = *reinterpret_cast<bool *>(GLOBAL_ADDRESS_BY_VERSION(0xA44B67, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE unsigned short &CTheScripts::NumberOfIntroTextLinesThisFrame = *reinterpret_cast<unsigned short *>(GLOBAL_ADDRESS_BY_VERSION(0xA44B68, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE unsigned short &CTheScripts::NumberOfUsedObjects = *reinterpret_cast<unsigned short *>(GLOBAL_ADDRESS_BY_VERSION(0xA44B6C, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE tUsedObject *CTheScripts::UsedObjectArray = reinterpret_cast<tUsedObject *>(GLOBAL_ADDRESS_BY_VERSION(0xA44B70, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE int &CTheScripts::LastRandomPedId = *reinterpret_cast<int *>(GLOBAL_ADDRESS_BY_VERSION(0xA476A4, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE unsigned int &CTheScripts::LastMissionPassedTime = *reinterpret_cast<unsigned int *>(GLOBAL_ADDRESS_BY_VERSION(0xA476A8, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE int &CTheScripts::OnAMissionFlag = *reinterpret_cast<int *>(GLOBAL_ADDRESS_BY_VERSION(0xA476AC, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE CEntity *&CTheScripts::EntitiesWaitingForScriptBrain = *reinterpret_cast<CEntity **>(GLOBAL_ADDRESS_BY_VERSION(0xA476B0, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE CStreamedScripts &CTheScripts::StreamedScripts = *reinterpret_cast<CStreamedScripts *>(GLOBAL_ADDRESS_BY_VERSION(0xA47B60, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE CScriptResourceManager &CTheScripts::ScriptResourceManager = *reinterpret_cast<CScriptResourceManager *>(GLOBAL_ADDRESS_BY_VERSION(0xA485A8, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE CUpsideDownCarCheck &CTheScripts::UpsideDownCars = *reinterpret_cast<CUpsideDownCarCheck *>(GLOBAL_ADDRESS_BY_VERSION(0xA4892C, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE tScriptParam *CTheScripts::LocalVariablesForCurrentMission = reinterpret_cast<tScriptParam *>(GLOBAL_ADDRESS_BY_VERSION(0xA48960, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE char *CTheScripts::ScriptSpace = reinterpret_cast<char *>(GLOBAL_ADDRESS_BY_VERSION(0xA49960, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE char *CTheScripts::MissionBlock = reinterpret_cast<char *>(GLOBAL_ADDRESS_BY_VERSION(0xA7A6A0, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE CRunningScript *&CTheScripts::pIdleScripts = *reinterpret_cast<CRunningScript **>(GLOBAL_ADDRESS_BY_VERSION(0xA8B428, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE CRunningScript *&CTheScripts::pActiveScripts = *reinterpret_cast<CRunningScript **>(GLOBAL_ADDRESS_BY_VERSION(0xA8B42C, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE CRunningScript *CTheScripts::ScriptsArray = reinterpret_cast<CRunningScript *>(GLOBAL_ADDRESS_BY_VERSION(0xA8B430, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE unsigned short &CTheScripts::NumberOfScriptSearchLights = *reinterpret_cast<unsigned short *>(GLOBAL_ADDRESS_BY_VERSION(0xA90830, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE CMissionCleanup &CTheScripts::MissionCleanUp = *reinterpret_cast<CMissionCleanup *>(GLOBAL_ADDRESS_BY_VERSION(0xA90850, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE CStuckCarCheck &CTheScripts::StuckCars = *reinterpret_cast<CStuckCarCheck *>(GLOBAL_ADDRESS_BY_VERSION(0xA90AB0, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE CScriptsForBrains &CTheScripts::ScriptsForBrains = *reinterpret_cast<CScriptsForBrains *>(GLOBAL_ADDRESS_BY_VERSION(0xA90CF0, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE tScriptSphere *CTheScripts::ScriptSphereArray = reinterpret_cast<tScriptSphere *>(GLOBAL_ADDRESS_BY_VERSION(0xA91268, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE tScriptText *CTheScripts::IntroTextLines = reinterpret_cast<tScriptText *>(GLOBAL_ADDRESS_BY_VERSION(0xA913E8, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE tScriptRectangle *CTheScripts::IntroRectangles = reinterpret_cast<tScriptRectangle *>(GLOBAL_ADDRESS_BY_VERSION(0xA92D68, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE CSprite2d *CTheScripts::ScriptSprites = reinterpret_cast<CSprite2d *>(GLOBAL_ADDRESS_BY_VERSION(0xA94B68, 0, 0, 0, 0, 0));
PLUGIN_VARIABLE tScriptSearchlight *CTheScripts::ScriptSearchLightArray = reinterpret_cast<tScriptSearchlight *>(GLOBAL_ADDRESS_BY_VERSION(0xA94D68, 0, 0, 0, 0, 0));
int addrof(CTheScripts::AddScriptCheckpoint) = ADDRESS_BY_VERSION(0x4935A0, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::AddScriptCheckpoint) = GLOBAL_ADDRESS_BY_VERSION(0x4935A0, 0, 0, 0, 0, 0);
int CTheScripts::AddScriptCheckpoint(float at_X, float at_Y, float at_Z, float PointTo_X, float PointTo_Y, float PointTo_Z, float radius, int type) {
return plugin::CallAndReturnDynGlobal<int, float, float, float, float, float, float, float, int>(gaddrof(CTheScripts::AddScriptCheckpoint), at_X, at_Y, at_Z, PointTo_X, PointTo_Y, PointTo_Z, radius, type);
}
int addrof(CTheScripts::AddScriptEffectSystem) = ADDRESS_BY_VERSION(0x492F90, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::AddScriptEffectSystem) = GLOBAL_ADDRESS_BY_VERSION(0x492F90, 0, 0, 0, 0, 0);
int CTheScripts::AddScriptEffectSystem(FxSystem_c *a1) {
return plugin::CallAndReturnDynGlobal<int, FxSystem_c *>(gaddrof(CTheScripts::AddScriptEffectSystem), a1);
}
int addrof(CTheScripts::AddScriptSearchLight) = ADDRESS_BY_VERSION(0x493000, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::AddScriptSearchLight) = GLOBAL_ADDRESS_BY_VERSION(0x493000, 0, 0, 0, 0, 0);
int CTheScripts::AddScriptSearchLight(float startX, float startY, float startZ, CEntity *entity, float targetX, float targetY, float targetZ, float targetRadius, float baseRadius) {
return plugin::CallAndReturnDynGlobal<int, float, float, float, CEntity *, float, float, float, float, float>(gaddrof(CTheScripts::AddScriptSearchLight), startX, startY, startZ, entity, targetX, targetY, targetZ, targetRadius, baseRadius);
}
int addrof(CTheScripts::AddScriptSphere) = ADDRESS_BY_VERSION(0x483B30, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::AddScriptSphere) = GLOBAL_ADDRESS_BY_VERSION(0x483B30, 0, 0, 0, 0, 0);
unsigned int CTheScripts::AddScriptSphere(unsigned int id, CVector posn, float radius) {
return plugin::CallAndReturnDynGlobal<unsigned int, unsigned int, CVector, float>(gaddrof(CTheScripts::AddScriptSphere), id, posn, radius);
}
int addrof(CTheScripts::AddToBuildingSwapArray) = ADDRESS_BY_VERSION(0x481140, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::AddToBuildingSwapArray) = GLOBAL_ADDRESS_BY_VERSION(0x481140, 0, 0, 0, 0, 0);
void CTheScripts::AddToBuildingSwapArray(CBuilding *a1, int newModelId, int oldModelId) {
plugin::CallDynGlobal<CBuilding *, int, int>(gaddrof(CTheScripts::AddToBuildingSwapArray), a1, newModelId, oldModelId);
}
int addrof(CTheScripts::AddToInvisibilitySwapArray) = ADDRESS_BY_VERSION(0x481200, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::AddToInvisibilitySwapArray) = GLOBAL_ADDRESS_BY_VERSION(0x481200, 0, 0, 0, 0, 0);
void CTheScripts::AddToInvisibilitySwapArray(CEntity *a2, bool bVisible) {
plugin::CallDynGlobal<CEntity *, bool>(gaddrof(CTheScripts::AddToInvisibilitySwapArray), a2, bVisible);
}
int addrof(CTheScripts::AddToListOfConnectedLodObjects) = ADDRESS_BY_VERSION(0x470980, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::AddToListOfConnectedLodObjects) = GLOBAL_ADDRESS_BY_VERSION(0x470980, 0, 0, 0, 0, 0);
void CTheScripts::AddToListOfConnectedLodObjects(CObject *pObject1, CObject *pObject2) {
plugin::CallDynGlobal<CObject *, CObject *>(gaddrof(CTheScripts::AddToListOfConnectedLodObjects), pObject1, pObject2);
}
int addrof(CTheScripts::AddToListOfSpecialAnimGroupsAttachedToCharModels) = ADDRESS_BY_VERSION(0x474750, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::AddToListOfSpecialAnimGroupsAttachedToCharModels) = GLOBAL_ADDRESS_BY_VERSION(0x474750, 0, 0, 0, 0, 0);
void CTheScripts::AddToListOfSpecialAnimGroupsAttachedToCharModels(int modelid, char *ifpName) {
plugin::CallDynGlobal<int, char *>(gaddrof(CTheScripts::AddToListOfSpecialAnimGroupsAttachedToCharModels), modelid, ifpName);
}
int addrof(CTheScripts::AddToSwitchJumpTable) = ADDRESS_BY_VERSION(0x470390, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::AddToSwitchJumpTable) = GLOBAL_ADDRESS_BY_VERSION(0x470390, 0, 0, 0, 0, 0);
double CTheScripts::AddToSwitchJumpTable(int switchValue, int switchLabelLocalAddress) {
return plugin::CallAndReturnDynGlobal<double, int, int>(gaddrof(CTheScripts::AddToSwitchJumpTable), switchValue, switchLabelLocalAddress);
}
int addrof(CTheScripts::AddToVehicleModelsBlockedByScript) = ADDRESS_BY_VERSION(0x46B200, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::AddToVehicleModelsBlockedByScript) = GLOBAL_ADDRESS_BY_VERSION(0x46B200, 0, 0, 0, 0, 0);
void CTheScripts::AddToVehicleModelsBlockedByScript(int modelindex) {
plugin::CallDynGlobal<int>(gaddrof(CTheScripts::AddToVehicleModelsBlockedByScript), modelindex);
}
int addrof(CTheScripts::AddToWaitingForScriptBrainArray) = ADDRESS_BY_VERSION(0x46AB60, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::AddToWaitingForScriptBrainArray) = GLOBAL_ADDRESS_BY_VERSION(0x46AB60, 0, 0, 0, 0, 0);
void CTheScripts::AddToWaitingForScriptBrainArray(CEntity *pEntity, short arg2) {
plugin::CallDynGlobal<CEntity *, short>(gaddrof(CTheScripts::AddToWaitingForScriptBrainArray), pEntity, arg2);
}
int addrof(CTheScripts::AttachSearchlightToSearchlightObject) = ADDRESS_BY_VERSION(0x4934F0, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::AttachSearchlightToSearchlightObject) = GLOBAL_ADDRESS_BY_VERSION(0x4934F0, 0, 0, 0, 0, 0);
void CTheScripts::AttachSearchlightToSearchlightObject(int searchlightid, CObject *tower, CObject *housing, CObject *bulb, float offsetX, float offsetY, float offsetZ) {
plugin::CallDynGlobal<int, CObject *, CObject *, CObject *, float, float, float>(gaddrof(CTheScripts::AttachSearchlightToSearchlightObject), searchlightid, tower, housing, bulb, offsetX, offsetY, offsetZ);
}
int addrof(CTheScripts::CheckStreamedScriptVersion) = ADDRESS_BY_VERSION(0x464FF0, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::CheckStreamedScriptVersion) = GLOBAL_ADDRESS_BY_VERSION(0x464FF0, 0, 0, 0, 0, 0);
char CTheScripts::CheckStreamedScriptVersion(RwStream *arg1, char *arg2) {
return plugin::CallAndReturnDynGlobal<char, RwStream *, char *>(gaddrof(CTheScripts::CheckStreamedScriptVersion), arg1, arg2);
}
int addrof(CTheScripts::CleanUpThisObject) = ADDRESS_BY_VERSION(0x4866C0, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::CleanUpThisObject) = GLOBAL_ADDRESS_BY_VERSION(0x4866C0, 0, 0, 0, 0, 0);
void CTheScripts::CleanUpThisObject(CObject *pObject) {
plugin::CallDynGlobal<CObject *>(gaddrof(CTheScripts::CleanUpThisObject), pObject);
}
int addrof(CTheScripts::CleanUpThisPed) = ADDRESS_BY_VERSION(0x486300, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::CleanUpThisPed) = GLOBAL_ADDRESS_BY_VERSION(0x486300, 0, 0, 0, 0, 0);
void CTheScripts::CleanUpThisPed(CPed *ped) {
plugin::CallDynGlobal<CPed *>(gaddrof(CTheScripts::CleanUpThisPed), ped);
}
int addrof(CTheScripts::CleanUpThisVehicle) = ADDRESS_BY_VERSION(0x486670, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::CleanUpThisVehicle) = GLOBAL_ADDRESS_BY_VERSION(0x486670, 0, 0, 0, 0, 0);
void CTheScripts::CleanUpThisVehicle(CVehicle *pVehicle) {
plugin::CallDynGlobal<CVehicle *>(gaddrof(CTheScripts::CleanUpThisVehicle), pVehicle);
}
int addrof(CTheScripts::ClearAllSuppressedCarModels) = ADDRESS_BY_VERSION(0x46A7C0, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::ClearAllSuppressedCarModels) = GLOBAL_ADDRESS_BY_VERSION(0x46A7C0, 0, 0, 0, 0, 0);
void CTheScripts::ClearAllSuppressedCarModels() {
plugin::CallDynGlobal(gaddrof(CTheScripts::ClearAllSuppressedCarModels));
}
int addrof(CTheScripts::ClearAllVehicleModelsBlockedByScript) = ADDRESS_BY_VERSION(0x46A840, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::ClearAllVehicleModelsBlockedByScript) = GLOBAL_ADDRESS_BY_VERSION(0x46A840, 0, 0, 0, 0, 0);
void CTheScripts::ClearAllVehicleModelsBlockedByScript() {
plugin::CallDynGlobal(gaddrof(CTheScripts::ClearAllVehicleModelsBlockedByScript));
}
int addrof(CTheScripts::ClearSpaceForMissionEntity) = ADDRESS_BY_VERSION(0x486B00, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::ClearSpaceForMissionEntity) = GLOBAL_ADDRESS_BY_VERSION(0x486B00, 0, 0, 0, 0, 0);
void CTheScripts::ClearSpaceForMissionEntity(CVector const &pos, CEntity *pEntity) {
plugin::CallDynGlobal<CVector const &, CEntity *>(gaddrof(CTheScripts::ClearSpaceForMissionEntity), pos, pEntity);
}
int addrof(CTheScripts::DoScriptSetupAfterPoolsHaveLoaded) = ADDRESS_BY_VERSION(0x5D3390, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::DoScriptSetupAfterPoolsHaveLoaded) = GLOBAL_ADDRESS_BY_VERSION(0x5D3390, 0, 0, 0, 0, 0);
void CTheScripts::DoScriptSetupAfterPoolsHaveLoaded() {
plugin::CallDynGlobal(gaddrof(CTheScripts::DoScriptSetupAfterPoolsHaveLoaded));
}
int addrof(CTheScripts::DrawDebugAngledSquare) = ADDRESS_BY_VERSION(0x486990, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::DrawDebugAngledSquare) = GLOBAL_ADDRESS_BY_VERSION(0x486990, 0, 0, 0, 0, 0);
void CTheScripts::DrawDebugAngledSquare(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4) {
plugin::CallDynGlobal<float, float, float, float, float, float, float, float>(gaddrof(CTheScripts::DrawDebugAngledSquare), x1, y1, x2, y2, x3, y3, x4, y4);
}
int addrof(CTheScripts::DrawDebugCube) = ADDRESS_BY_VERSION(0x486840, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::DrawDebugCube) = GLOBAL_ADDRESS_BY_VERSION(0x486840, 0, 0, 0, 0, 0);
void CTheScripts::DrawDebugCube(float x1, float y1, float x2, float y2) {
plugin::CallDynGlobal<float, float, float, float>(gaddrof(CTheScripts::DrawDebugCube), x1, y1, x2, y2);
}
int addrof(CTheScripts::DrawScriptSpheres) = ADDRESS_BY_VERSION(0x4810E0, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::DrawScriptSpheres) = GLOBAL_ADDRESS_BY_VERSION(0x4810E0, 0, 0, 0, 0, 0);
void CTheScripts::DrawScriptSpheres() {
plugin::CallDynGlobal(gaddrof(CTheScripts::DrawScriptSpheres));
}
int addrof(CTheScripts::DrawScriptSpritesAndRectangles) = ADDRESS_BY_VERSION(0x464980, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::DrawScriptSpritesAndRectangles) = GLOBAL_ADDRESS_BY_VERSION(0x464980, 0, 0, 0, 0, 0);
void CTheScripts::DrawScriptSpritesAndRectangles(char bDrawBeforeFade) {
plugin::CallDynGlobal<char>(gaddrof(CTheScripts::DrawScriptSpritesAndRectangles), bDrawBeforeFade);
}
int addrof(CTheScripts::GetActualScriptThingIndex) = ADDRESS_BY_VERSION(0x4839A0, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::GetActualScriptThingIndex) = GLOBAL_ADDRESS_BY_VERSION(0x4839A0, 0, 0, 0, 0, 0);
signed int CTheScripts::GetActualScriptThingIndex(int index, unsigned char type) {
return plugin::CallAndReturnDynGlobal<signed int, int, unsigned char>(gaddrof(CTheScripts::GetActualScriptThingIndex), index, type);
}
int addrof(CTheScripts::GetNewUniqueScriptThingIndex) = ADDRESS_BY_VERSION(0x483720, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::GetNewUniqueScriptThingIndex) = GLOBAL_ADDRESS_BY_VERSION(0x483720, 0, 0, 0, 0, 0);
unsigned int CTheScripts::GetNewUniqueScriptThingIndex(unsigned int index, char type) {
return plugin::CallAndReturnDynGlobal<unsigned int, unsigned int, char>(gaddrof(CTheScripts::GetNewUniqueScriptThingIndex), index, type);
}
int addrof(CTheScripts::GetScriptIndexFromPointer) = ADDRESS_BY_VERSION(0x464D20, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::GetScriptIndexFromPointer) = GLOBAL_ADDRESS_BY_VERSION(0x464D20, 0, 0, 0, 0, 0);
int CTheScripts::GetScriptIndexFromPointer(CRunningScript *thread) {
return plugin::CallAndReturnDynGlobal<int, CRunningScript *>(gaddrof(CTheScripts::GetScriptIndexFromPointer), thread);
}
int addrof(CTheScripts::GetUniqueScriptThingIndex) = ADDRESS_BY_VERSION(0x4810C0, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::GetUniqueScriptThingIndex) = GLOBAL_ADDRESS_BY_VERSION(0x4810C0, 0, 0, 0, 0, 0);
unsigned int CTheScripts::GetUniqueScriptThingIndex(int playergroup, unsigned char type) {
return plugin::CallAndReturnDynGlobal<unsigned int, int, unsigned char>(gaddrof(CTheScripts::GetUniqueScriptThingIndex), playergroup, type);
}
int addrof(CTheScripts::HasVehicleModelBeenBlockedByScript) = ADDRESS_BY_VERSION(0x46A890, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::HasVehicleModelBeenBlockedByScript) = GLOBAL_ADDRESS_BY_VERSION(0x46A890, 0, 0, 0, 0, 0);
bool CTheScripts::HasVehicleModelBeenBlockedByScript(int modelindex) {
return plugin::CallAndReturnDynGlobal<bool, int>(gaddrof(CTheScripts::HasVehicleModelBeenBlockedByScript), modelindex);
}
int addrof(CTheScripts::HighlightImportantAngledArea) = ADDRESS_BY_VERSION(0x485EF0, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::HighlightImportantAngledArea) = GLOBAL_ADDRESS_BY_VERSION(0x485EF0, 0, 0, 0, 0, 0);
void CTheScripts::HighlightImportantAngledArea(unsigned int markerid, float from_X, float from_Y, float to_X, float to_Y, float angledTo_X, float angledTo_Y, float angledFrom_X, float angledFrom_Y, float height) {
plugin::CallDynGlobal<unsigned int, float, float, float, float, float, float, float, float, float>(gaddrof(CTheScripts::HighlightImportantAngledArea), markerid, from_X, from_Y, to_X, to_Y, angledTo_X, angledTo_Y, angledFrom_X, angledFrom_Y, height);
}
int addrof(CTheScripts::HighlightImportantArea) = ADDRESS_BY_VERSION(0x485E00, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::HighlightImportantArea) = GLOBAL_ADDRESS_BY_VERSION(0x485E00, 0, 0, 0, 0, 0);
void CTheScripts::HighlightImportantArea(int markerid, float from_X, float from_Y, float to_X, float to_Y, float height) {
plugin::CallDynGlobal<int, float, float, float, float, float>(gaddrof(CTheScripts::HighlightImportantArea), markerid, from_X, from_Y, to_X, to_Y, height);
}
int addrof(CTheScripts::Init) = ADDRESS_BY_VERSION(0x468D50, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::Init) = GLOBAL_ADDRESS_BY_VERSION(0x468D50, 0, 0, 0, 0, 0);
void CTheScripts::Init() {
plugin::CallDynGlobal(gaddrof(CTheScripts::Init));
}
int addrof(CTheScripts::InitialiseAllConnectLodObjects) = ADDRESS_BY_VERSION(0x470960, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::InitialiseAllConnectLodObjects) = GLOBAL_ADDRESS_BY_VERSION(0x470960, 0, 0, 0, 0, 0);
void CTheScripts::InitialiseAllConnectLodObjects() {
plugin::CallDynGlobal(gaddrof(CTheScripts::InitialiseAllConnectLodObjects));
}
int addrof(CTheScripts::InitialiseConnectLodObjects) = ADDRESS_BY_VERSION(0x470940, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::InitialiseConnectLodObjects) = GLOBAL_ADDRESS_BY_VERSION(0x470940, 0, 0, 0, 0, 0);
void CTheScripts::InitialiseConnectLodObjects(unsigned short a1) {
plugin::CallDynGlobal<unsigned short>(gaddrof(CTheScripts::InitialiseConnectLodObjects), a1);
}
int addrof(CTheScripts::InitialiseSpecialAnimGroup) = ADDRESS_BY_VERSION(0x474710, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::InitialiseSpecialAnimGroup) = GLOBAL_ADDRESS_BY_VERSION(0x474710, 0, 0, 0, 0, 0);
void CTheScripts::InitialiseSpecialAnimGroup(unsigned short a1) {
plugin::CallDynGlobal<unsigned short>(gaddrof(CTheScripts::InitialiseSpecialAnimGroup), a1);
}
int addrof(CTheScripts::InitialiseSpecialAnimGroupsAttachedToCharModels) = ADDRESS_BY_VERSION(0x474730, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::InitialiseSpecialAnimGroupsAttachedToCharModels) = GLOBAL_ADDRESS_BY_VERSION(0x474730, 0, 0, 0, 0, 0);
void CTheScripts::InitialiseSpecialAnimGroupsAttachedToCharModels() {
plugin::CallDynGlobal(gaddrof(CTheScripts::InitialiseSpecialAnimGroupsAttachedToCharModels));
}
int addrof(CTheScripts::IsEntityWithinAnySearchLight) = ADDRESS_BY_VERSION(0x493960, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::IsEntityWithinAnySearchLight) = GLOBAL_ADDRESS_BY_VERSION(0x493960, 0, 0, 0, 0, 0);
bool CTheScripts::IsEntityWithinAnySearchLight(CEntity *pEntity, int *pIndex) {
return plugin::CallAndReturnDynGlobal<bool, CEntity *, int *>(gaddrof(CTheScripts::IsEntityWithinAnySearchLight), pEntity, pIndex);
}
int addrof(CTheScripts::IsEntityWithinSearchLight) = ADDRESS_BY_VERSION(0x493900, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::IsEntityWithinSearchLight) = GLOBAL_ADDRESS_BY_VERSION(0x493900, 0, 0, 0, 0, 0);
bool CTheScripts::IsEntityWithinSearchLight(unsigned int index, CEntity *pEntity) {
return plugin::CallAndReturnDynGlobal<bool, unsigned int, CEntity *>(gaddrof(CTheScripts::IsEntityWithinSearchLight), index, pEntity);
}
int addrof(CTheScripts::IsPedStopped) = ADDRESS_BY_VERSION(0x486110, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::IsPedStopped) = GLOBAL_ADDRESS_BY_VERSION(0x486110, 0, 0, 0, 0, 0);
bool CTheScripts::IsPedStopped(CPed *ped) {
return plugin::CallAndReturnDynGlobal<bool, CPed *>(gaddrof(CTheScripts::IsPedStopped), ped);
}
int addrof(CTheScripts::IsPlayerOnAMission) = ADDRESS_BY_VERSION(0x464D50, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::IsPlayerOnAMission) = GLOBAL_ADDRESS_BY_VERSION(0x464D50, 0, 0, 0, 0, 0);
bool CTheScripts::IsPlayerOnAMission() {
return plugin::CallAndReturnDynGlobal<bool>(gaddrof(CTheScripts::IsPlayerOnAMission));
}
int addrof(CTheScripts::IsPointWithinSearchLight) = ADDRESS_BY_VERSION(0x493280, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::IsPointWithinSearchLight) = GLOBAL_ADDRESS_BY_VERSION(0x493280, 0, 0, 0, 0, 0);
bool CTheScripts::IsPointWithinSearchLight(CVector *pointPosn, int index) {
return plugin::CallAndReturnDynGlobal<bool, CVector *, int>(gaddrof(CTheScripts::IsPointWithinSearchLight), pointPosn, index);
}
int addrof(CTheScripts::IsVehicleStopped) = ADDRESS_BY_VERSION(0x4861F0, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::IsVehicleStopped) = GLOBAL_ADDRESS_BY_VERSION(0x4861F0, 0, 0, 0, 0, 0);
bool CTheScripts::IsVehicleStopped(CVehicle *pVehicle) {
return plugin::CallAndReturnDynGlobal<bool, CVehicle *>(gaddrof(CTheScripts::IsVehicleStopped), pVehicle);
}
int addrof(CTheScripts::Load) = ADDRESS_BY_VERSION(0x5D4FD0, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::Load) = GLOBAL_ADDRESS_BY_VERSION(0x5D4FD0, 0, 0, 0, 0, 0);
void CTheScripts::Load() {
plugin::CallDynGlobal(gaddrof(CTheScripts::Load));
}
int addrof(CTheScripts::MoveSearchLightBetweenTwoPoints) = ADDRESS_BY_VERSION(0x493360, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::MoveSearchLightBetweenTwoPoints) = GLOBAL_ADDRESS_BY_VERSION(0x493360, 0, 0, 0, 0, 0);
void CTheScripts::MoveSearchLightBetweenTwoPoints(int index, float x1, float y1, float z1, float x2, float y2, float z2, float pathSpeed) {
plugin::CallDynGlobal<int, float, float, float, float, float, float, float>(gaddrof(CTheScripts::MoveSearchLightBetweenTwoPoints), index, x1, y1, z1, x2, y2, z2, pathSpeed);
}
int addrof(CTheScripts::MoveSearchLightToEntity) = ADDRESS_BY_VERSION(0x493420, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::MoveSearchLightToEntity) = GLOBAL_ADDRESS_BY_VERSION(0x493420, 0, 0, 0, 0, 0);
void CTheScripts::MoveSearchLightToEntity(int index, CEntity *pEntity, float pathSpeed) {
plugin::CallDynGlobal<int, CEntity *, float>(gaddrof(CTheScripts::MoveSearchLightToEntity), index, pEntity, pathSpeed);
}
int addrof(CTheScripts::MoveSearchLightToPointAndStop) = ADDRESS_BY_VERSION(0x493480, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::MoveSearchLightToPointAndStop) = GLOBAL_ADDRESS_BY_VERSION(0x493480, 0, 0, 0, 0, 0);
void CTheScripts::MoveSearchLightToPointAndStop(int index, float x, float y, float z, float pathSpeed) {
plugin::CallDynGlobal<int, float, float, float, float>(gaddrof(CTheScripts::MoveSearchLightToPointAndStop), index, x, y, z, pathSpeed);
}
int addrof(CTheScripts::PrintListSizes) = ADDRESS_BY_VERSION(0x4646D0, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::PrintListSizes) = GLOBAL_ADDRESS_BY_VERSION(0x4646D0, 0, 0, 0, 0, 0);
void CTheScripts::PrintListSizes() {
plugin::CallDynGlobal(gaddrof(CTheScripts::PrintListSizes));
}
int addrof(CTheScripts::Process) = ADDRESS_BY_VERSION(0x46A000, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::Process) = GLOBAL_ADDRESS_BY_VERSION(0x46A000, 0, 0, 0, 0, 0);
void CTheScripts::Process() {
plugin::CallDynGlobal(gaddrof(CTheScripts::Process));
}
int addrof(CTheScripts::ProcessAllSearchLights) = ADDRESS_BY_VERSION(0x4939F0, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::ProcessAllSearchLights) = GLOBAL_ADDRESS_BY_VERSION(0x4939F0, 0, 0, 0, 0, 0);
void CTheScripts::ProcessAllSearchLights() {
plugin::CallDynGlobal(gaddrof(CTheScripts::ProcessAllSearchLights));
}
int addrof(CTheScripts::ProcessWaitingForScriptBrainArray) = ADDRESS_BY_VERSION(0x46CF00, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::ProcessWaitingForScriptBrainArray) = GLOBAL_ADDRESS_BY_VERSION(0x46CF00, 0, 0, 0, 0, 0);
void CTheScripts::ProcessWaitingForScriptBrainArray() {
plugin::CallDynGlobal(gaddrof(CTheScripts::ProcessWaitingForScriptBrainArray));
}
int addrof(CTheScripts::ReadMultiScriptFileOffsetsFromScript) = ADDRESS_BY_VERSION(0x4867C0, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::ReadMultiScriptFileOffsetsFromScript) = GLOBAL_ADDRESS_BY_VERSION(0x4867C0, 0, 0, 0, 0, 0);
void CTheScripts::ReadMultiScriptFileOffsetsFromScript() {
plugin::CallDynGlobal(gaddrof(CTheScripts::ReadMultiScriptFileOffsetsFromScript));
}
int addrof(CTheScripts::ReadObjectNamesFromScript) = ADDRESS_BY_VERSION(0x486720, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::ReadObjectNamesFromScript) = GLOBAL_ADDRESS_BY_VERSION(0x486720, 0, 0, 0, 0, 0);
void CTheScripts::ReadObjectNamesFromScript() {
plugin::CallDynGlobal(gaddrof(CTheScripts::ReadObjectNamesFromScript));
}
int addrof(CTheScripts::ReinitialiseSwitchStatementData) = ADDRESS_BY_VERSION(0x470370, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::ReinitialiseSwitchStatementData) = GLOBAL_ADDRESS_BY_VERSION(0x470370, 0, 0, 0, 0, 0);
void CTheScripts::ReinitialiseSwitchStatementData() {
plugin::CallDynGlobal(gaddrof(CTheScripts::ReinitialiseSwitchStatementData));
}
int addrof(CTheScripts::RemoveFromVehicleModelsBlockedByScript) = ADDRESS_BY_VERSION(0x46A860, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::RemoveFromVehicleModelsBlockedByScript) = GLOBAL_ADDRESS_BY_VERSION(0x46A860, 0, 0, 0, 0, 0);
void CTheScripts::RemoveFromVehicleModelsBlockedByScript(int modelindex) {
plugin::CallDynGlobal<int>(gaddrof(CTheScripts::RemoveFromVehicleModelsBlockedByScript), modelindex);
}
int addrof(CTheScripts::RemoveFromWaitingForScriptBrainArray) = ADDRESS_BY_VERSION(0x46ABC0, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::RemoveFromWaitingForScriptBrainArray) = GLOBAL_ADDRESS_BY_VERSION(0x46ABC0, 0, 0, 0, 0, 0);
int CTheScripts::RemoveFromWaitingForScriptBrainArray(CEntity *a1, short modelIndex) {
return plugin::CallAndReturnDynGlobal<int, CEntity *, short>(gaddrof(CTheScripts::RemoveFromWaitingForScriptBrainArray), a1, modelIndex);
}
int addrof(CTheScripts::RemoveScriptCheckpoint) = ADDRESS_BY_VERSION(0x4936C0, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::RemoveScriptCheckpoint) = GLOBAL_ADDRESS_BY_VERSION(0x4936C0, 0, 0, 0, 0, 0);
void CTheScripts::RemoveScriptCheckpoint(int arg1) {
plugin::CallDynGlobal<int>(gaddrof(CTheScripts::RemoveScriptCheckpoint), arg1);
}
int addrof(CTheScripts::RemoveScriptEffectSystem) = ADDRESS_BY_VERSION(0x492FD0, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::RemoveScriptEffectSystem) = GLOBAL_ADDRESS_BY_VERSION(0x492FD0, 0, 0, 0, 0, 0);
void CTheScripts::RemoveScriptEffectSystem(int arg1) {
plugin::CallDynGlobal<int>(gaddrof(CTheScripts::RemoveScriptEffectSystem), arg1);
}
int addrof(CTheScripts::RemoveScriptSearchLight) = ADDRESS_BY_VERSION(0x493160, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::RemoveScriptSearchLight) = GLOBAL_ADDRESS_BY_VERSION(0x493160, 0, 0, 0, 0, 0);
void CTheScripts::RemoveScriptSearchLight(unsigned int index) {
plugin::CallDynGlobal<unsigned int>(gaddrof(CTheScripts::RemoveScriptSearchLight), index);
}
int addrof(CTheScripts::RemoveScriptSphere) = ADDRESS_BY_VERSION(0x483BA0, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::RemoveScriptSphere) = GLOBAL_ADDRESS_BY_VERSION(0x483BA0, 0, 0, 0, 0, 0);
void CTheScripts::RemoveScriptSphere(int index) {
plugin::CallDynGlobal<int>(gaddrof(CTheScripts::RemoveScriptSphere), index);
}
int addrof(CTheScripts::RemoveScriptTextureDictionary) = ADDRESS_BY_VERSION(0x465A40, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::RemoveScriptTextureDictionary) = GLOBAL_ADDRESS_BY_VERSION(0x465A40, 0, 0, 0, 0, 0);
void CTheScripts::RemoveScriptTextureDictionary() {
plugin::CallDynGlobal(gaddrof(CTheScripts::RemoveScriptTextureDictionary));
}
int addrof(CTheScripts::RemoveThisPed) = ADDRESS_BY_VERSION(0x486240, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::RemoveThisPed) = GLOBAL_ADDRESS_BY_VERSION(0x486240, 0, 0, 0, 0, 0);
void CTheScripts::RemoveThisPed(CPed *ped) {
plugin::CallDynGlobal<CPed *>(gaddrof(CTheScripts::RemoveThisPed), ped);
}
int addrof(CTheScripts::RenderAllSearchLights) = ADDRESS_BY_VERSION(0x493E30, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::RenderAllSearchLights) = GLOBAL_ADDRESS_BY_VERSION(0x493E30, 0, 0, 0, 0, 0);
void CTheScripts::RenderAllSearchLights() {
plugin::CallDynGlobal(gaddrof(CTheScripts::RenderAllSearchLights));
}
int addrof(CTheScripts::Save) = ADDRESS_BY_VERSION(0x5D4C40, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::Save) = GLOBAL_ADDRESS_BY_VERSION(0x5D4C40, 0, 0, 0, 0, 0);
void CTheScripts::Save() {
plugin::CallDynGlobal(gaddrof(CTheScripts::Save));
}
int addrof(CTheScripts::ScriptAttachAnimGroupToCharModel) = ADDRESS_BY_VERSION(0x474800, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::ScriptAttachAnimGroupToCharModel) = GLOBAL_ADDRESS_BY_VERSION(0x474800, 0, 0, 0, 0, 0);
bool CTheScripts::ScriptAttachAnimGroupToCharModel(int modelId, char *ifpName) {
return plugin::CallAndReturnDynGlobal<bool, int, char *>(gaddrof(CTheScripts::ScriptAttachAnimGroupToCharModel), modelId, ifpName);
}
int addrof(CTheScripts::ScriptConnectLodsFunction) = ADDRESS_BY_VERSION(0x470A20, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::ScriptConnectLodsFunction) = GLOBAL_ADDRESS_BY_VERSION(0x470A20, 0, 0, 0, 0, 0);
void CTheScripts::ScriptConnectLodsFunction(int objecthandle1, int objecthandle2) {
plugin::CallDynGlobal<int, int>(gaddrof(CTheScripts::ScriptConnectLodsFunction), objecthandle1, objecthandle2);
}
int addrof(CTheScripts::ScriptDebugCircle2D) = ADDRESS_BY_VERSION(0x485C20, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::ScriptDebugCircle2D) = GLOBAL_ADDRESS_BY_VERSION(0x485C20, 0, 0, 0, 0, 0);
void CTheScripts::ScriptDebugCircle2D(float x, float y, float width, float height, CRGBA color) {
plugin::CallDynGlobal<float, float, float, float, CRGBA>(gaddrof(CTheScripts::ScriptDebugCircle2D), x, y, width, height, color);
}
int addrof_o(CTheScripts::StartNewScript, CRunningScript *(*)(unsigned char *)) = ADDRESS_BY_VERSION(0x464C20, 0, 0, 0, 0, 0);
int gaddrof_o(CTheScripts::StartNewScript, CRunningScript *(*)(unsigned char *)) = GLOBAL_ADDRESS_BY_VERSION(0x464C20, 0, 0, 0, 0, 0);
CRunningScript *CTheScripts::StartNewScript(unsigned char *startIP) {
return plugin::CallAndReturnDynGlobal<CRunningScript *, unsigned char *>(gaddrof_o(CTheScripts::StartNewScript, CRunningScript *(*)(unsigned char *)), startIP);
}
int addrof_o(CTheScripts::StartNewScript, int(*)(unsigned char *, unsigned short)) = ADDRESS_BY_VERSION(0x464C90, 0, 0, 0, 0, 0);
int gaddrof_o(CTheScripts::StartNewScript, int(*)(unsigned char *, unsigned short)) = GLOBAL_ADDRESS_BY_VERSION(0x464C90, 0, 0, 0, 0, 0);
int CTheScripts::StartNewScript(unsigned char *startIP, unsigned short index) {
return plugin::CallAndReturnDynGlobal<int, unsigned char *, unsigned short>(gaddrof_o(CTheScripts::StartNewScript, int(*)(unsigned char *, unsigned short)), startIP, index);
}
int addrof(CTheScripts::StartTestScript) = ADDRESS_BY_VERSION(0x464D40, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::StartTestScript) = GLOBAL_ADDRESS_BY_VERSION(0x464D40, 0, 0, 0, 0, 0);
void CTheScripts::StartTestScript() {
plugin::CallDynGlobal(gaddrof(CTheScripts::StartTestScript));
}
int addrof(CTheScripts::UndoBuildingSwaps) = ADDRESS_BY_VERSION(0x481290, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::UndoBuildingSwaps) = GLOBAL_ADDRESS_BY_VERSION(0x481290, 0, 0, 0, 0, 0);
void CTheScripts::UndoBuildingSwaps() {
plugin::CallDynGlobal(gaddrof(CTheScripts::UndoBuildingSwaps));
}
int addrof(CTheScripts::UndoEntityInvisibilitySettings) = ADDRESS_BY_VERSION(0x4812D0, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::UndoEntityInvisibilitySettings) = GLOBAL_ADDRESS_BY_VERSION(0x4812D0, 0, 0, 0, 0, 0);
void CTheScripts::UndoEntityInvisibilitySettings() {
plugin::CallDynGlobal(gaddrof(CTheScripts::UndoEntityInvisibilitySettings));
}
int addrof(CTheScripts::UpdateObjectIndices) = ADDRESS_BY_VERSION(0x486780, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::UpdateObjectIndices) = GLOBAL_ADDRESS_BY_VERSION(0x486780, 0, 0, 0, 0, 0);
void CTheScripts::UpdateObjectIndices() {
plugin::CallDynGlobal(gaddrof(CTheScripts::UpdateObjectIndices));
}
int addrof(CTheScripts::UseSwitchJumpTable) = ADDRESS_BY_VERSION(0x4703C0, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::UseSwitchJumpTable) = GLOBAL_ADDRESS_BY_VERSION(0x4703C0, 0, 0, 0, 0, 0);
void CTheScripts::UseSwitchJumpTable(int *pSwitchLabelAddress) {
plugin::CallDynGlobal<int *>(gaddrof(CTheScripts::UseSwitchJumpTable), pSwitchLabelAddress);
}
int addrof(CTheScripts::WipeLocalVariableMemoryForMissionScript) = ADDRESS_BY_VERSION(0x464BB0, 0, 0, 0, 0, 0);
int gaddrof(CTheScripts::WipeLocalVariableMemoryForMissionScript) = GLOBAL_ADDRESS_BY_VERSION(0x464BB0, 0, 0, 0, 0, 0);
void CTheScripts::WipeLocalVariableMemoryForMissionScript() {
plugin::CallDynGlobal(gaddrof(CTheScripts::WipeLocalVariableMemoryForMissionScript));
}
| 67.983687
| 253
| 0.788957
|
gta-chaos-mod
|
afce2ed6cbffc0e37a0a3db2aa73e00228940513
| 1,807
|
cpp
|
C++
|
HI/HI_L3/WINAPI/main.cpp
|
sandyre/ifmo_course3
|
f697b2308acec149c67b1fbba326e2264da88f29
|
[
"MIT"
] | 3
|
2017-06-19T20:39:26.000Z
|
2020-09-14T04:15:53.000Z
|
HI/HI_L3/WINAPI/main.cpp
|
sandyre/ifmo_course3
|
f697b2308acec149c67b1fbba326e2264da88f29
|
[
"MIT"
] | null | null | null |
HI/HI_L3/WINAPI/main.cpp
|
sandyre/ifmo_course3
|
f697b2308acec149c67b1fbba326e2264da88f29
|
[
"MIT"
] | 2
|
2018-11-12T18:42:09.000Z
|
2019-12-20T03:12:34.000Z
|
#include <Windows.h>
#include "bitmap.hpp"
LRESULT CALLBACK WindowProc(HWND, UINT, WPARAM, LPARAM);
HDC hdc;
Bitmap * pBITMAP;
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nCmdShow)
{
std::wstring filename = L"c:\\Users\\sandyre\\Desktop\\resulted.bmp";
pBITMAP = new Bitmap(hInstance, filename);
filename = L"c:\\Users\\sandyre\\Desktop\\resulted_moded.bmp";
pBITMAP->Save(filename);
WNDCLASS wc = { 0 };
wc.style = CS_OWNDC | CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = WindowProc;
wc.hInstance = hInstance;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.lpszClassName = L"HI_L3";
RegisterClass(&wc);
HWND hWnd = CreateWindow(L"HI_L3", L"HI_L3",
WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, 320, 420,
NULL, NULL, hInstance, NULL);
hdc = GetDC(hWnd);
ShowWindow(hWnd, nCmdShow);
SetTimer(hWnd, 1, USER_TIMER_MINIMUM, NULL);
MSG msg;
while(GetMessage(&msg, NULL, 0, 0) > 0)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
LRESULT CALLBACK WindowProc(HWND hWnd, UINT message,
WPARAM wParam, LPARAM lParam)
{
switch(message)
{
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
HDC memDC = CreateCompatibleDC(hdc);
SelectObject(memDC, pBITMAP->GetHBitmap());
BitBlt(hdc, 0, 0,
pBITMAP->GetBitmapInfo().bmiHeader.biWidth,
pBITMAP->GetBitmapInfo().bmiHeader.biHeight,
memDC, 0, 0,
SRCCOPY);
DeleteDC(memDC);
EndPaint(hWnd, &ps);
break;
}
case WM_DESTROY:
{
PostQuitMessage(0);
}
}
return DefWindowProc(hWnd, message, wParam, lParam);
}
| 24.753425
| 73
| 0.618705
|
sandyre
|
afd249c15ea370269f946c1248413b061e66a6cd
| 4,033
|
cpp
|
C++
|
src/query/data/MinQuery.cpp
|
LouieBHLu/LemonDB-Self-Designed-Multithread-Database
|
ae0ad7f97ef114f7517a368a779e60fb90aa4115
|
[
"MIT"
] | 1
|
2022-01-21T09:49:44.000Z
|
2022-01-21T09:49:44.000Z
|
src/query/data/MinQuery.cpp
|
LouieBHLu/LemonDB-Self-Designed-Multithread-Database
|
ae0ad7f97ef114f7517a368a779e60fb90aa4115
|
[
"MIT"
] | null | null | null |
src/query/data/MinQuery.cpp
|
LouieBHLu/LemonDB-Self-Designed-Multithread-Database
|
ae0ad7f97ef114f7517a368a779e60fb90aa4115
|
[
"MIT"
] | null | null | null |
#include "MinQuery.h"
#include "../../db/Database.h"
#include "../QueryResult.h"
#include "../../threads/thread.h"
#include <algorithm>
using namespace std;
constexpr const char *MinQuery::qname;
static long thread_num;
static long range;
static bool exist;
static Table* table;
static MinQuery* p;
static vector<string> *ops;
static std::vector<std::vector<Table::ValueType>> MinThread;
void* min_per_thread(void* thread_id){
auto begin = table->begin() + int((long) thread_id * range);
auto end = begin + int(range);
if((long) thread_id == thread_num - 1) end = table->end();
for(auto it = begin; it != end; it++){
if(p->evalCondition(*it)){
exist = true;
for (size_t cnt = 0; cnt < ops->size(); ++cnt) {
if (MinThread[(size_t)thread_id][cnt] > (*it)[(*ops)[cnt]]) {
MinThread[(size_t)thread_id][cnt] = (*it)[(*ops)[cnt]];
}
}
}
}
return nullptr;
}
QueryResult::Ptr MinQuery::execute() {
if (this->operands.empty())
return make_unique<ErrorMsgResult>(qname, this->targetTable.c_str(),
"No operand (? operands)."_f %
operands.size());
Database &db = Database::getInstance();
try {
exist = false;
table = &db[this->targetTable];
auto result = initCondition(*table);
if(result.second){
thread_num = getThreadNum();
for(size_t i = 0; i < operands.size(); i++) min.push_back(INT32_MAX);
if (thread_num == 1 || table->size() < 50) {
for (auto it = table->begin(); it != table->end(); ++it) {
if (this->evalCondition(*it)) {
exist = true;
for (size_t cnt = 0; cnt < operands.size(); ++cnt) {
if (min[cnt] > (*it)[operands[cnt]]) {
min[cnt] = (*it)[operands[cnt]];
}
}
}
}
}
else
{
p = this;
range = (long) table->size() / thread_num;
ops = &this->operands;
auto threads = new pthread_t[(size_t)thread_num];
for (size_t i = 0; i < MinThread.size(); ++i) MinThread[i].clear();
MinThread.clear();
MinThread.resize((size_t)thread_num * operands.size());
for (size_t i = 0; i < (size_t)thread_num; ++i) {
for (size_t cnt = 0; cnt < operands.size(); ++cnt) {
MinThread[i].push_back(INT32_MAX);
}
if (pthread_create(&threads[i], NULL, min_per_thread, (void *)i)) {
return make_unique<ErrorMsgResult>(qname, this->targetTable.c_str(), "Fail to create threads");
}
}
for (int i = 0; i < thread_num; ++i) pthread_join(*(threads + i), NULL);
delete[] threads;
for (size_t i = 0; i < (size_t)thread_num; ++i){
for (size_t cnt = 0; cnt < operands.size(); ++cnt) {
if (min[cnt] > MinThread[i][cnt]) {
min[cnt] = MinThread[i][cnt];
}
}
}
}
}
if(exist) return std::make_unique<SuccessMsgResult>(std::move(min));
else return make_unique<NullQueryResult>();
} catch (const TableNameNotFound &e) {
return make_unique<ErrorMsgResult>(qname, this->targetTable,
"No such table."s);
} catch (const IllFormedQueryCondition &e) {
return make_unique<ErrorMsgResult>(qname, this->targetTable, e.what());
} catch (const invalid_argument &e) {
// Cannot convert operand to string
return make_unique<ErrorMsgResult>(qname, this->targetTable,
"Unknown error '?'"_f % e.what());
} catch (const exception &e) {
return make_unique<ErrorMsgResult>(qname, this->targetTable,
"Unkonwn error '?'."_f % e.what());
}
}
std::string MinQuery::toString() {
return "QUERY = MIN " + this->targetTable + "\"";
}
| 35.069565
| 111
| 0.529135
|
LouieBHLu
|
afd8c2bb263a99ae1ed367320478cb3bee31e4b6
| 3,424
|
cpp
|
C++
|
src/main.cpp
|
ZhouYixuanRobtic/NursingRobot
|
1372e4af40a3315b754d1b6273b5a00d09c4def6
|
[
"MIT"
] | 1
|
2020-12-09T01:32:13.000Z
|
2020-12-09T01:32:13.000Z
|
src/main.cpp
|
ZhouYixuanRobtic/NursingRobot
|
1372e4af40a3315b754d1b6273b5a00d09c4def6
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
ZhouYixuanRobtic/NursingRobot
|
1372e4af40a3315b754d1b6273b5a00d09c4def6
|
[
"MIT"
] | 1
|
2021-04-15T15:29:08.000Z
|
2021-04-15T15:29:08.000Z
|
#define EIGEN_USE_MKL_ALL
#include "util/logger.hpp"
#include <ros/ros.h>
#include "collision_detection/MoveItCollisionHelper.h"
#include <moveit_visual_tools/moveit_visual_tools.h>
#include <tf2_eigen/tf2_eigen.h>
#include "Kinematics/custom_kinematics.hpp"
#include "planner/CartesianPlanner.h"
#include "planner/PlannerMethod.hpp"
int main(int argc, char **argv)
{
/*
logger a( argv[0]);
ros::init(argc, argv, "NursingRobot");
ros::AsyncSpinner spinner(2);
spinner.start();
my_collision_detection::MoveItCollisionHelperPtr moveItCollisionHelper(new my_collision_detection::MoveItCollisionHelper("manipulator_i5",
"/home/xcy/WorkSpace/src/NursingRobot/config/aubo_i5.yaml",
my_kinematics::aubo_i5_analytical_IK));
const auto & kinematic_ptr = moveItCollisionHelper->getKinematicsPtr();
auto current_pose = kinematic_ptr->fk(state_space::JointSpace::Zero());
state_space::vector_SE3 cartesian_path;
planner::CartesianPlanner::getCartesianCircle(cartesian_path,state_space::SE3(state_space::SO3::Zero(),Eigen::Vector3d{-0.05,0,0}),
state_space::SE3(state_space::SO3::Zero(),Eigen::Vector3d{-0.25,0,0}),
-2*M_PI);
state_space::vector_JointSpace trajectory;
double percentage = planner::CartesianPlanner::computeCartesianPath(state_space::JointSpace::Zero(),
cartesian_path,
trajectory,
planner::MaxEEFStep(0.0,0.01),
planner::JumpThreshold::MIN(),
kinematic_ptr->getEndEffectorName(),
moveItCollisionHelper);
std::cout<<percentage<<std::endl;
EigenSTL::vector_Affine3d waypoints;
for(const auto & item:trajectory)
{
waypoints.emplace_back(Eigen::Affine3d{kinematic_ptr->fk(item).SE3Matrix()});
}
/*
std::size_t iter= 0;
while(++iter<trajectory.size()){
std::cout<<planner::distance(trajectory[iter-1],trajectory[iter])<<std::endl;
}*
namespace rvt = rviz_visual_tools;
moveit_visual_tools::MoveItVisualTools visual_tools("base_link");
visual_tools.deleteAllMarkers(); // clear all old markers
visual_tools.loadRemoteControl();
visual_tools.publishAxisLabeled(waypoints[0], " start", rvt::LARGE);
visual_tools.publishAxisLabeled(waypoints.back(), " end ", rvt::LARGE);
//visual_tools.publishAxisLabeled(Eigen::Affine3d(center.SE3Matrix())," center ",rvt::LARGE);
visual_tools.trigger();
visual_tools.prompt("Press 'next' in the RvizVisualToolsGui window to start the demo");
visual_tools.publishPath(waypoints, rvt::LIME_GREEN, rvt::SMALL);
for (const auto & waypoint : waypoints)
visual_tools.publishAxis(waypoint, rvt::SMALL);
visual_tools.trigger();
spinner.stop();*/
auto lazy_rrt_ptr = planner::createPlanner<state_space::JointSpace>(planner::LAZY_RRT,6);
return 0;
}
| 51.878788
| 146
| 0.593458
|
ZhouYixuanRobtic
|
afd9e00f9dfef07b0204def29edd1aece79c7cc3
| 909
|
hpp
|
C++
|
common/perf.hpp
|
DimitrisVlachos/sorting_algo_playground
|
98f386b52dc08f61e5f08d150540369c075f3d06
|
[
"MIT"
] | null | null | null |
common/perf.hpp
|
DimitrisVlachos/sorting_algo_playground
|
98f386b52dc08f61e5f08d150540369c075f3d06
|
[
"MIT"
] | null | null | null |
common/perf.hpp
|
DimitrisVlachos/sorting_algo_playground
|
98f386b52dc08f61e5f08d150540369c075f3d06
|
[
"MIT"
] | null | null | null |
#pragma once
#include "license_hdr.hpp"
#include "base_includes.hpp"
class c_perf {
private:
std::chrono::high_resolution_clock::time_point t1;
std::string m_desc;
public:
c_perf(const std::string& desc) : m_desc(desc) {
std::cout << "Starting perf: " << desc << "\n";
t1 = std::chrono::high_resolution_clock::now();
}
~c_perf() {
auto t2 = std::chrono::high_resolution_clock::now();
auto ns = std::chrono::duration_cast<std::chrono::duration<double,std::nano> >(t2 - t1);
auto ms = std::chrono::duration_cast<std::chrono::duration<double,std::milli> >(t2 - t1);
//auto s = std::chrono::duration_cast<std::chrono::seconds>(t2 - t1);
std::cout << "Finished perf: " << m_desc << ". Took [" << std::fixed << std::setprecision(5) << (double)ns.count() << " ns]" << " OR [" << (double)ms.count() << " ms]" <<".\n";
}
};
| 36.36
| 185
| 0.584158
|
DimitrisVlachos
|
afdadc62f2a9ba6726e52a19ab70637d90a813a8
| 2,280
|
cpp
|
C++
|
src/solver/eigen/eigen_solver_factory.cpp
|
dbeurle/neon
|
63cd2929a6eaaa0e1654c729cd35a9a52a706962
|
[
"MIT"
] | 9
|
2018-07-12T17:06:33.000Z
|
2021-11-20T23:13:26.000Z
|
src/solver/eigen/eigen_solver_factory.cpp
|
dbeurle/neon
|
63cd2929a6eaaa0e1654c729cd35a9a52a706962
|
[
"MIT"
] | 119
|
2016-06-22T07:36:04.000Z
|
2019-03-10T19:38:12.000Z
|
src/solver/eigen/eigen_solver_factory.cpp
|
dbeurle/neon
|
63cd2929a6eaaa0e1654c729cd35a9a52a706962
|
[
"MIT"
] | 9
|
2017-10-08T16:51:38.000Z
|
2021-03-15T08:08:04.000Z
|
#include "solver/eigen/eigen_solver_factory.hpp"
#include "io/json.hpp"
#include "solver/eigen/arpack.hpp"
#include "solver/eigen/lanczos_ocl.hpp"
#include "solver/eigen/power_iteration.hpp"
namespace neon
{
std::unique_ptr<eigen_solver> make_eigen_solver(json const& solver_data)
{
if (solver_data.find("type") == end(solver_data))
{
throw std::domain_error("Eigen solver type was not provided. Please use "
"\"power_iteration\", "
"\"arpack\" or \"lanczos\"");
}
std::int64_t number_of_ev = 10;
if (solver_data.find("eigenvalues") != end(solver_data))
{
number_of_ev = solver_data["eigenvalues"];
if (number_of_ev <= 0)
{
throw std::domain_error("The number of requested eigenvalues must be positive");
}
}
eigen_solver::eigen_spectrum spectrum;
if (solver_data.find("spectrum") != end(solver_data))
{
std::string const& input_spectrum = solver_data["spectrum"];
if (input_spectrum == "lower")
{
spectrum = eigen_solver::eigen_spectrum::lower;
}
else if (input_spectrum == "upper")
{
spectrum = eigen_solver::eigen_spectrum::upper;
}
else
{
throw std::domain_error("A spectrum was requested but only \"lower\" and \"upper\" "
"options are supported");
}
}
if (std::string const& type = solver_data["type"]; type == "power_iteration")
{
#ifndef ENABLE_OPENCL
throw std::domain_error("The \"power_iteration\" option requires OpenCL support. "
"Recompile with -DENABLE_OPENCL=1");
#else
return std::make_unique<power_iteration>(number_of_ev, spectrum);
#endif
}
else if (type == "lanczos")
{
#ifndef ENABLE_OPENCL
throw std::domain_error("The \"lanczos\" option requires OpenCL support. "
"Recompile with -DENABLE_OPENCL=1");
#else
return std::make_unique<lanczos_ocl>(number_of_ev, spectrum);
#endif
}
else if (type == "arpack")
{
return std::make_unique<arpack>(number_of_ev, spectrum);
}
return nullptr;
}
}
| 28.860759
| 96
| 0.589474
|
dbeurle
|
afde834ed01f4ebfc956fa6aadbd769d8bba877e
| 806
|
cpp
|
C++
|
notebook/mutsim/src/hist.cpp
|
johnsmith2077/kevlar
|
3ed06dae62479e89ccd200391728c416d4df8052
|
[
"MIT"
] | 24
|
2016-12-07T07:59:09.000Z
|
2019-03-11T02:05:36.000Z
|
notebook/mutsim/src/hist.cpp
|
johnsmith2077/kevlar
|
3ed06dae62479e89ccd200391728c416d4df8052
|
[
"MIT"
] | 325
|
2016-12-07T07:37:17.000Z
|
2019-03-12T19:01:40.000Z
|
notebook/mutsim/src/hist.cpp
|
standage/kevlar
|
622d1869266550422e91a60119ddc7261eea434a
|
[
"MIT"
] | 8
|
2017-08-17T01:37:39.000Z
|
2019-03-01T16:17:44.000Z
|
#include <assert.h>
#include <iostream>
#include "hist.hpp"
Histogram::Histogram(uint max) : maxbin(max)
{
while (hist.size() < maxbin + 1) {
hist.push_back(0);
}
}
void Histogram::increment(uint bin, uint by)
{
if (bin > maxbin) {
bin = maxbin;
}
hist[bin] += by;
}
ulong Histogram::get(uint bin)
{
assert(bin <= maxbin);
return hist[bin];
}
std::ostream& Histogram::print(std::ostream& stream) const
{
bool first = true;
stream << '[';
for (auto value : hist) {
if (first) {
first = false;
}
else {
stream << ", ";
}
stream << value;
}
stream << ']';
return stream;
}
std::ostream& operator<<(std::ostream& stream, const Histogram& h)
{
return h.print(stream);
}
| 17.148936
| 66
| 0.533499
|
johnsmith2077
|
afdee6f8c366470c85766ed237ec7e8e7ca54353
| 5,233
|
cpp
|
C++
|
pal/crypto/hash.test.cpp
|
svens/pal
|
5e73ef39dad32bba2d42c6e1a3af6a3c66725ee7
|
[
"MIT"
] | null | null | null |
pal/crypto/hash.test.cpp
|
svens/pal
|
5e73ef39dad32bba2d42c6e1a3af6a3c66725ee7
|
[
"MIT"
] | null | null | null |
pal/crypto/hash.test.cpp
|
svens/pal
|
5e73ef39dad32bba2d42c6e1a3af6a3c66725ee7
|
[
"MIT"
] | null | null | null |
#include <pal/crypto/hash>
#include <pal/crypto/test>
#include <catch2/catch_template_test_macros.hpp>
#include <unordered_map>
namespace {
static const std::string
empty = "",
lazy_dog = "The quick brown fox jumps over the lazy dog",
lazy_cog = "The quick brown fox jumps over the lazy cog";
struct md5: pal::crypto::md5_hash
{
static inline std::unordered_map<std::string, std::string> hash =
{
{ empty, "d41d8cd98f00b204e9800998ecf8427e" },
{ lazy_dog, "9e107d9d372bb6826bd81d3542a419d6" },
{ lazy_cog, "1055d3e698d289f2af8663725127bd4b" },
{ lazy_dog + lazy_cog, "29b4e7d924350ff800471c80c9ca2a3f" },
};
};
struct sha1: pal::crypto::sha1_hash
{
static inline std::unordered_map<std::string, std::string> hash =
{
{ empty, "da39a3ee5e6b4b0d3255bfef95601890afd80709" },
{ lazy_dog, "2fd4e1c67a2d28fced849ee1bb76e7391b93eb12" },
{ lazy_cog, "de9f2c7fd25e1b3afad3e85a0bd17d9b100db4b3" },
{ lazy_dog + lazy_cog, "38590c861cc71a4186b2909285a04609fb23bb42" },
};
};
struct sha256: pal::crypto::sha256_hash
{
static inline std::unordered_map<std::string, std::string> hash =
{
{ empty, "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" },
{ lazy_dog, "d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592" },
{ lazy_cog, "e4c4d8f3bf76b692de791a173e05321150f7a345b46484fe427f6acc7ecc81be" },
{ lazy_dog + lazy_cog, "0a9a361e469fd8fb48e915a06431f3fabbfb0960226421a25ab939fde121b7c8" },
};
};
struct sha384: pal::crypto::sha384_hash
{
static inline std::unordered_map<std::string, std::string> hash =
{
{ empty, "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b" },
{ lazy_dog, "ca737f1014a48f4c0b6dd43cb177b0afd9e5169367544c494011e3317dbf9a509cb1e5dc1e85a941bbee3d7f2afbc9b1" },
{ lazy_cog, "098cea620b0978caa5f0befba6ddcf22764bea977e1c70b3483edfdf1de25f4b40d6cea3cadf00f809d422feb1f0161b" },
{ lazy_dog + lazy_cog, "03b251e870443c1dc8052967970cc91bdd3bd5c3784ea0b2df52f0f4a6c56f947fcc1369b593730479dc07d73a043297" },
};
};
struct sha512: pal::crypto::sha512_hash
{
static inline std::unordered_map<std::string, std::string> hash =
{
{ empty, "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e" },
{ lazy_dog, "07e547d9586f6a73f73fbac0435ed76951218fb7d0c8d788a309d785436bbb642e93a252a954f23912547d1e8a3b5ed6e1bfd7097821233fa0538f3db854fee6" },
{ lazy_cog, "3eeee1d0e11733ef152a6c29503b3ae20c4f1f3cda4cb26f1bc1a41f91c7fe4ab3bd86494049e201c4bd5155f31ecb7a3c8606843c4cc8dfcab7da11c8ae5045" },
{ lazy_dog + lazy_cog, "9a1eacc4b2de80d412e8e28aa918c22450246c9d249559e6cba45145feebd05298c8d91cde493acd7c2bf9ed5c86612a7f8c8323c10913d8b4703c8d6bcd99f8" },
};
};
TEMPLATE_TEST_CASE("crypto/hash", "",
md5,
sha1,
sha256,
sha384,
sha512)
{
using pal_test::to_hex;
SECTION("copy ctor")
{
TestType h1;
h1.update(std::span{lazy_dog});
auto h2 = h1;
auto r1 = to_hex(h1.update(std::span{lazy_cog}).finish());
auto r2 = to_hex(h2.update(std::span{lazy_cog}).finish());
CHECK(r1 == r2);
CHECK(r1 == TestType::hash[lazy_dog + lazy_cog]);
}
SECTION("copy assign")
{
TestType h1, h2;
h1.update(std::span{lazy_dog});
h2 = h1;
auto r1 = to_hex(h1.update(std::span{lazy_cog}).finish());
auto r2 = to_hex(h2.update(std::span{lazy_cog}).finish());
CHECK(r1 == r2);
CHECK(r1 == TestType::hash[lazy_dog + lazy_cog]);
}
SECTION("move ctor")
{
TestType h1;
h1.update(std::span{lazy_dog});
auto h2{std::move(h1)};
auto r = to_hex(h2.update(std::span{lazy_cog}).finish());
CHECK(r == TestType::hash[lazy_dog + lazy_cog]);
}
SECTION("move assign")
{
TestType h1, h2;
h1.update(std::span{lazy_dog});
h2 = std::move(h1);
auto r = to_hex(h2.update(std::span{lazy_cog}).finish());
CHECK(r == TestType::hash[lazy_dog + lazy_cog]);
}
SECTION("no update")
{
TestType h;
auto r = to_hex(h.finish());
CHECK(r == TestType::hash[empty]);
}
SECTION("finish")
{
TestType h;
uint8_t data[TestType::digest_size];
*reinterpret_cast<typename TestType::result_type *>(data) = h.finish();
CHECK(to_hex(data) == TestType::hash[empty]);
}
SECTION("reuse object")
{
TestType h;
auto r = to_hex(h.update(std::span{lazy_dog}).finish());
CHECK(r == TestType::hash[lazy_dog]);
r = to_hex(h.update(std::span{lazy_cog}).finish());
CHECK(r == TestType::hash[lazy_cog]);
}
SECTION("multiple updates")
{
TestType h;
auto r = to_hex(h
.update(std::span{lazy_dog})
.update(std::span{lazy_cog})
.finish()
);
CHECK(r == TestType::hash[lazy_dog + lazy_cog]);
}
SECTION("multiple spans")
{
TestType h;
std::array spans =
{
std::span{lazy_dog},
std::span{lazy_cog},
};
auto r = to_hex(h.update(spans).finish());
CHECK(r == TestType::hash[lazy_dog + lazy_cog]);
}
SECTION("one_shot")
{
auto r = to_hex(TestType::one_shot(std::span{lazy_dog}));
CHECK(r == TestType::hash[lazy_dog]);
}
SECTION("one_shot: multiple spans")
{
std::array spans =
{
std::span{lazy_dog},
std::span{lazy_cog},
};
auto r = to_hex(TestType::one_shot(spans));
CHECK(r == TestType::hash[lazy_dog + lazy_cog]);
}
}
} // namespace
| 26.974227
| 158
| 0.726543
|
svens
|
afe1bac24100ab5af8a6e0e8d6f5cf5f6916d0f0
| 383
|
cpp
|
C++
|
Sandbox/src/SandboxApp.cpp
|
Tomzopo/parabol
|
2e11a78ba11726c01af2cd320f0a6769f221758f
|
[
"Apache-2.0"
] | null | null | null |
Sandbox/src/SandboxApp.cpp
|
Tomzopo/parabol
|
2e11a78ba11726c01af2cd320f0a6769f221758f
|
[
"Apache-2.0"
] | null | null | null |
Sandbox/src/SandboxApp.cpp
|
Tomzopo/parabol
|
2e11a78ba11726c01af2cd320f0a6769f221758f
|
[
"Apache-2.0"
] | null | null | null |
#include <Parabol.h>
#include <Parabol/Core/EntryPoint.h>
#include "Sandbox2D.h"
#include "ExampleLayer.h"
class Sandbox : public Parabol::Application {
public:
Sandbox() {
// PushLayer(new ExampleLayer());
PushLayer(new Sandbox2D());
}
~Sandbox() override = default;
};
Parabol::Application* Parabol::CreateApplication() {
return new Sandbox();
}
| 19.15
| 52
| 0.665796
|
Tomzopo
|
afe6178f052d24211dbfb8c4626b2f6a420ad1e5
| 1,608
|
cpp
|
C++
|
test/memorymap.cpp
|
davidwed/sqlrelay_rudiments
|
6ccffdfc5fa29f8c0226f3edc2aa888aa1008347
|
[
"BSD-2-Clause-NetBSD"
] | null | null | null |
test/memorymap.cpp
|
davidwed/sqlrelay_rudiments
|
6ccffdfc5fa29f8c0226f3edc2aa888aa1008347
|
[
"BSD-2-Clause-NetBSD"
] | null | null | null |
test/memorymap.cpp
|
davidwed/sqlrelay_rudiments
|
6ccffdfc5fa29f8c0226f3edc2aa888aa1008347
|
[
"BSD-2-Clause-NetBSD"
] | null | null | null |
// Copyright (c) 2003 David Muse
// See the file COPYING for more information
#include <rudiments/file.h>
#include <rudiments/permissions.h>
#include <rudiments/sys.h>
#include <rudiments/charstring.h>
#include <rudiments/memorymap.h>
#include <rudiments/process.h>
#include <rudiments/error.h>
#include <rudiments/stdio.h>
#include "test.cpp"
int main(int argc, const char **argv) {
header("memorymap");
if (!memorymap::supported()) {
stdoutput.printf(" not supported\n\n");
return 0;
}
size_t allocgran=sys::getAllocationGranularity();
// create a file to test with
file::remove("memorymap.txt");
file fd;
test("create file",fd.create("memorymap.txt",
permissions::evalPermString("rw-r--r--")));
for (uint16_t i=0; i<10; i++) {
for (size_t j=0; j<allocgran; j++) {
fd.write((char)('0'+i));
}
}
// loop, mapping blocks of the file
memorymap mm;
for (uint16_t i=0; i<10; i++) {
// attach to the next block
test("attach",mm.attach(fd.getFileDescriptor(),
i*allocgran,allocgran,
PROT_READ,MAP_PRIVATE));
// get a pointer to the block
const char *ptr=(const char *)mm.getData();
test("valid ptr",(ptr!=NULL));
// see if it contains the correct data
bool success=true;
for (size_t j=0; j<allocgran; j++) {
if (*(ptr+j)!='0'+i) {
success=false;
break;
}
}
stringbuffer blockname;
blockname.append("block ")->append(i);
test(blockname.getString(),success);
// detach from the block
test("detach",mm.detach());
}
stdoutput.printf("\n");
// close the file
fd.close();
// clean up
file::remove("memorymap.txt");
}
| 22.333333
| 50
| 0.655473
|
davidwed
|
aff68a3cef0621faf45ad85bedee92e1e70637d9
| 7,100
|
cc
|
C++
|
tests/phi/tests/util.cc
|
juliusnehring/arcana-samples
|
b5d71c114f353b278323b96450b1bfcd947336b7
|
[
"MIT"
] | null | null | null |
tests/phi/tests/util.cc
|
juliusnehring/arcana-samples
|
b5d71c114f353b278323b96450b1bfcd947336b7
|
[
"MIT"
] | null | null | null |
tests/phi/tests/util.cc
|
juliusnehring/arcana-samples
|
b5d71c114f353b278323b96450b1bfcd947336b7
|
[
"MIT"
] | 1
|
2020-01-22T18:04:53.000Z
|
2020-01-22T18:04:53.000Z
|
#include <nexus/fuzz_test.hh>
#include <rich-log/log.hh>
#include <phantasm-hardware-interface/common/byte_util.hh>
#include <phantasm-hardware-interface/util.hh>
TEST("mipsize utils")
{
// simple pow2 square
auto const pow2_square = tg::isize2{1024, 1024};
CHECK(phi::util::get_num_mips(pow2_square) == 11);
CHECK(phi::util::get_mip_size(pow2_square, 0) == tg::isize2{1024, 1024});
CHECK(phi::util::get_mip_size(pow2_square, 1) == tg::isize2{512, 512});
CHECK(phi::util::get_mip_size(pow2_square, 2) == tg::isize2{256, 256});
CHECK(phi::util::get_mip_size(pow2_square, 9) == tg::isize2{2, 2});
CHECK(phi::util::get_mip_size(pow2_square, 10) == tg::isize2{1, 1});
CHECK(phi::util::get_mip_size(pow2_square, 11) == tg::isize2{1, 1});
// non-pow2, non-square
auto const crooked = tg::isize2{57, 43};
CHECK(phi::util::get_num_mips(crooked) == 6);
CHECK(phi::util::get_mip_size(crooked, 0) == tg::isize2{57, 43});
CHECK(phi::util::get_mip_size(crooked, 1) == tg::isize2{28, 21});
CHECK(phi::util::get_mip_size(crooked, 2) == tg::isize2{14, 10});
CHECK(phi::util::get_mip_size(crooked, 3) == tg::isize2{7, 5});
CHECK(phi::util::get_mip_size(crooked, 4) == tg::isize2{3, 2});
CHECK(phi::util::get_mip_size(crooked, 5) == tg::isize2{1, 1});
CHECK(phi::util::get_mip_size(crooked, 6) == tg::isize2{1, 1});
CHECK(phi::util::get_mip_size(crooked, 7) == tg::isize2{1, 1});
CHECK(phi::util::get_num_mips(1, 1) == 1);
}
FUZZ_TEST("mipsize utils fuzz")(tg::rng& rng)
{
int const random = tg::uniform(rng, 4, 1'000'000);
auto const num_mips = phi::util::get_num_mips(random, random);
CHECK(phi::util::get_mip_size(random, 0) == random);
CHECK(phi::util::get_mip_size(random, 1) < random);
CHECK(phi::util::get_mip_size(random, num_mips - 2) > 1);
CHECK(phi::util::get_mip_size(random, num_mips - 1) == 1);
CHECK(phi::util::get_mip_size(random, num_mips) == 1);
}
TEST("upload sizes")
{
// auto const f_test_upsize = [](tg::isize3 size, phi::format fmt) {
// LOG_INFO("{}, format {}:", size, uint8_t(fmt));
// LOG_INFO("m0 d12: {}, vk: {}", phi::util::get_texture_size_bytes(size, fmt, 0, true), phi::util::get_texture_size_bytes(size, fmt, 0, false));
// LOG_INFO("m1 d12: {}, vk: {}", phi::util::get_texture_size_bytes(size, fmt, 1, true), phi::util::get_texture_size_bytes(size, fmt, 1, false));
// };
// f_test_upsize({90128, 28561, 7}, phi::format::rgb32i);
// LOG_INFO("w^8: {}", 1u << 8);
// 4 byte pixels
// in order: all mips d3d12, all mips vk, no mips d3d12, no mips vk
CHECK(phi::util::get_texture_size_bytes({256, 256, 1}, phi::format::bgra8un, 0, true) == 360192);
CHECK(phi::util::get_texture_size_bytes({256, 256, 1}, phi::format::bgra8un, 0, false) == 349524);
CHECK(phi::util::get_texture_size_bytes({256, 256, 1}, phi::format::bgra8un, 1, true) == 262144);
CHECK(phi::util::get_texture_size_bytes({256, 256, 1}, phi::format::bgra8un, 1, false) == 262144);
CHECK(phi::util::get_texture_size_bytes({1024, 1024, 1}, phi::format::bgra8un, 0, true) == 5603072);
CHECK(phi::util::get_texture_size_bytes({1024, 1024, 1}, phi::format::bgra8un, 0, false) == 5592404);
CHECK(phi::util::get_texture_size_bytes({1024, 1024, 1}, phi::format::bgra8un, 1, true) == 4194304);
CHECK(phi::util::get_texture_size_bytes({1024, 1024, 1}, phi::format::bgra8un, 1, false) == 4194304);
CHECK(phi::util::get_texture_size_bytes({57, 43, 1}, phi::format::bgra8un, 0, true) == 20992);
CHECK(phi::util::get_texture_size_bytes({57, 43, 1}, phi::format::bgra8un, 0, false) == 12884);
CHECK(phi::util::get_texture_size_bytes({57, 43, 1}, phi::format::bgra8un, 1, true) == 11008);
CHECK(phi::util::get_texture_size_bytes({57, 43, 1}, phi::format::bgra8un, 1, false) == 9804);
CHECK(phi::util::get_texture_size_bytes({57, 43, 2}, phi::format::bgra8un, 0, true) == 41984);
CHECK(phi::util::get_texture_size_bytes({57, 43, 2}, phi::format::bgra8un, 0, false) == 25768);
CHECK(phi::util::get_texture_size_bytes({57, 43, 2}, phi::format::bgra8un, 1, true) == 22016);
CHECK(phi::util::get_texture_size_bytes({57, 43, 2}, phi::format::bgra8un, 1, false) == 19608);
CHECK(phi::util::get_texture_size_bytes({256, 256, 4}, phi::format::bgra8un, 0, true) == 1440768);
CHECK(phi::util::get_texture_size_bytes({256, 256, 4}, phi::format::bgra8un, 0, false) == 1398096);
CHECK(phi::util::get_texture_size_bytes({256, 256, 4}, phi::format::bgra8un, 1, true) == 1048576);
CHECK(phi::util::get_texture_size_bytes({256, 256, 4}, phi::format::bgra8un, 1, false) == 1048576);
// 8 byte pixels
CHECK(phi::util::get_texture_size_bytes({256, 256, 1}, phi::format::rgba16f, 0, true) == 704256);
CHECK(phi::util::get_texture_size_bytes({256, 256, 1}, phi::format::rgba16f, 0, false) == 699048);
CHECK(phi::util::get_texture_size_bytes({256, 256, 1}, phi::format::rgba16f, 1, true) == 524288);
CHECK(phi::util::get_texture_size_bytes({256, 256, 1}, phi::format::rgba16f, 1, false) == 524288);
CHECK(phi::util::get_texture_size_bytes({57, 43, 2}, phi::format::rgba16f, 0, true) == 64000);
CHECK(phi::util::get_texture_size_bytes({57, 43, 2}, phi::format::rgba16f, 0, false) == 51536);
CHECK(phi::util::get_texture_size_bytes({57, 43, 2}, phi::format::rgba16f, 1, true) == 44032);
CHECK(phi::util::get_texture_size_bytes({57, 43, 2}, phi::format::rgba16f, 1, false) == 39216);
// 12 byte pixels
CHECK(phi::util::get_texture_size_bytes({90128, 28561, 7}, phi::format::rgb32i, 0, true) == 587038464);
CHECK(phi::util::get_texture_size_bytes({90128, 28561, 7}, phi::format::rgb32i, 0, false) == 538751960);
CHECK(phi::util::get_texture_size_bytes({90128, 28561, 7}, phi::format::rgb32i, 1, true) == 1492678400);
CHECK(phi::util::get_texture_size_bytes({90128, 28561, 7}, phi::format::rgb32i, 1, false) == 1479883072);
// 16 byte pixels
CHECK(phi::util::get_texture_size_bytes({51241, 78823, 2}, phi::format::rgba32f, 0, true) == 572323328);
CHECK(phi::util::get_texture_size_bytes({51241, 78823, 2}, phi::format::rgba32f, 0, false) == 528704480);
CHECK(phi::util::get_texture_size_bytes({51241, 78823, 2}, phi::format::rgba32f, 1, true) == 415656448);
CHECK(phi::util::get_texture_size_bytes({51241, 78823, 2}, phi::format::rgba32f, 1, false) == 398000096);
}
TEST("memory alignment")
{
using namespace phi::util;
CHECK(align_up(1u, 4u) == 4u);
CHECK(align_up(4u, 4u) == 4u);
CHECK(align_up(16u, 4u) == 16u);
CHECK(align_up(16u, 32u) == 32u);
CHECK(align_up(31u, 32u) == 32u);
CHECK(align_up(33u, 32u) == 64u);
CHECK(align_down(31u, 16u) == 16u);
CHECK(align_down(32u, 16u) == 32u);
alignas(16) int foo;
CHECK(is_aligned(&foo, 16));
alignas(32) int bar;
CHECK(is_aligned(&bar, 32));
CHECK(align_up<uint32_t>(0, 4) == 0);
CHECK(align_up<int>(0, 4) == 0);
CHECK(align_up<uint32_t>(1, 4) == 4);
CHECK(align_up<int>(1, 4) == 4);
}
| 50
| 156
| 0.644648
|
juliusnehring
|
aff723ff1f7e7351a95306834fbb423395593760
| 1,770
|
cpp
|
C++
|
chapter04/problem_33/main.cpp
|
AhmedShaban94/the_modern_cpp_challenge_solutions
|
c5ea164ecc224389ee35db12126eeee2bc459564
|
[
"MIT"
] | 1
|
2021-07-08T15:34:14.000Z
|
2021-07-08T15:34:14.000Z
|
chapter04/problem_33/main.cpp
|
AhmedShaban94/the_modern_cpp_challenge_solutions
|
c5ea164ecc224389ee35db12126eeee2bc459564
|
[
"MIT"
] | null | null | null |
chapter04/problem_33/main.cpp
|
AhmedShaban94/the_modern_cpp_challenge_solutions
|
c5ea164ecc224389ee35db12126eeee2bc459564
|
[
"MIT"
] | null | null | null |
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>
enum class STATUS
{
RUNNING,
SUSPENDED
};
enum class PLATFORM
{
x32_BIT,
x64_BIT
};
struct ProcessInfo
{
std::string name;
std::size_t pid;
STATUS status;
std::string accountName;
std::size_t memorySize;
PLATFORM platform;
};
std::ostream &operator<<(std::ostream &os, const ProcessInfo &info)
{
os << std::left << std::setw(25) << std::setfill(' ') << info.name;
os << std::left << std::setw(8) << std::setfill(' ') << (info.status == STATUS::RUNNING ? "Running" : "Suspended") << '\t';
os << std::left << std::setw(12) << std::setfill(' ') << info.accountName << '\t';
os << std::right << std::setw(15) << std::setfill(' ') << info.memorySize << '\t';
os << std::left << std::setw(10) << std::setfill(' ') << (info.platform == PLATFORM::x32_BIT ? "32-bit" : "64-bit");
return os;
}
void printProcesses(std::vector<ProcessInfo> processes)
{
std::sort(processes.begin(), processes.end(), [](const auto &first, const auto &second)
{ return first.name < second.name; });
for (const auto &p : processes)
std::cout << p << '\n';
}
int main()
{
std::vector<ProcessInfo> processes{
{"chrome.exe", 1044, STATUS::RUNNING, "ahmed.shaban", 25180, PLATFORM::x32_BIT},
{"explorer.exe", 7108, STATUS::RUNNING, "ahmed.shaban", 29529, PLATFORM::x64_BIT},
{"chrome.exe", 10100, STATUS::RUNNING, "ahmed.shaban", 227756, PLATFORM::x32_BIT},
{"cmd.exe", 512, STATUS::RUNNING, "SYSTEM", 48, PLATFORM::x64_BIT},
{"skype.exe", 22456, STATUS::SUSPENDED, "ahmed.shaban", 656, PLATFORM::x64_BIT}};
printProcesses(processes);
return EXIT_SUCCESS;
}
| 31.052632
| 127
| 0.607345
|
AhmedShaban94
|
affcec9412fd718924399d20facc0a82fd4d6b2f
| 1,487
|
cpp
|
C++
|
Trees/InternalNode.cpp
|
shujianyang/btrForensics
|
5206e3253778169b954986c38b020f0783bdfc58
|
[
"MIT"
] | 17
|
2016-07-25T13:33:31.000Z
|
2022-02-18T00:52:43.000Z
|
Trees/InternalNode.cpp
|
shujianyang/btrForensics
|
5206e3253778169b954986c38b020f0783bdfc58
|
[
"MIT"
] | 2
|
2019-03-03T02:21:49.000Z
|
2019-07-30T13:39:39.000Z
|
Trees/InternalNode.cpp
|
shujianyang/btrForensics
|
5206e3253778169b954986c38b020f0783bdfc58
|
[
"MIT"
] | null | null | null |
//! \file
//! \author Shujian Yang
//!
//! Implementation of class InternalNode.
#include <sstream>
#include "InternalNode.h"
namespace btrForensics{
//! Constructor of btrfs leaf node.
//!
//! \param img Image file.
//! \param imgOffset Offset to the partition.
//! \param header Pointer to header of a node.
//! \param endian The endianess of the array.
//! \param startOffset Offset of the node, right after header.
//!
InternalNode::InternalNode(TSK_IMG_INFO *img, const BtrfsHeader *header,
TSK_ENDIAN_ENUM endian, uint64_t startOffset)
:BtrfsNode(header)
{
char *diskArr;
uint64_t itemOffset(0);
uint32_t itemNum = header -> getNumOfItems();
for(uint32_t i=0; i<itemNum; ++i){
diskArr = new char[KeyPtr::SIZE_OF_KEY_PTR]();
tsk_img_read(img, startOffset + itemOffset,
diskArr, KeyPtr::SIZE_OF_KEY_PTR);
keyPointers.push_back(new KeyPtr(endian, (uint8_t*)diskArr));
delete [] diskArr;
itemOffset += KeyPtr::SIZE_OF_KEY_PTR;
}
}
//! Destructor
InternalNode::~InternalNode()
{
for(auto ptr : keyPointers)
delete ptr;
}
//! Print info about this node.
const std::string InternalNode::info() const
{
std::ostringstream oss;
oss << *nodeHeader << "\n\n";
oss << "Item list:" << '\n';
oss << std::string(30, '=') << "\n\n";
for(auto ptr : keyPointers){
oss << *ptr;
oss << std::string(30, '=') << "\n\n";
}
return oss.str();
}
}
| 22.530303
| 73
| 0.626093
|
shujianyang
|
9b7f11dd91c1fda4cc8ef591f19593234e6aa989
| 7,549
|
hpp
|
C++
|
include/utils/io.hpp
|
alexd2580/statorange
|
02bdbe96273108964f9ec947c331f7f22a66d5c8
|
[
"MIT"
] | 1
|
2016-02-26T01:14:26.000Z
|
2016-02-26T01:14:26.000Z
|
include/utils/io.hpp
|
alexd2580/statorange
|
02bdbe96273108964f9ec947c331f7f22a66d5c8
|
[
"MIT"
] | 6
|
2015-12-06T22:23:29.000Z
|
2015-12-11T14:56:55.000Z
|
include/utils/io.hpp
|
alexd2580/statorange
|
02bdbe96273108964f9ec947c331f7f22a66d5c8
|
[
"MIT"
] | null | null | null |
#ifndef UTILS_IO_HPP
#define UTILS_IO_HPP
#include <memory>
#include <ostream>
#include <string>
#include <type_traits>
#include <cstddef>
#include <cstdio>
#include <sys/socket.h>
#include "Address.hpp"
#include "utils/exception.hpp"
#include "utils/resource.hpp"
// Returns true if input becomes available on a non-closed socket.
// Returns true if the pipe has been closed remotely.
bool has_input(int fd, int microsec = 0);
DEFINE_EXCEPTION_CLASS(StreamException)
// Reads `count` bytes from `fd` and stores them into `buf`.
// Closes `fd` when EOS is reached.
// Returns the number of read bytes.
ssize_t read_all(int fd, char* buf, size_t count) noexcept(false);
// Writes `count` bytes from `buf` and to `fd`.
// Closes `fd` when EPIPE is received.
// Returns the number of wrote bytes.
ssize_t write_all(int fd, char const* buf, size_t count) noexcept(false);
class UniqueSocket final : public UniqueResource<int> {
public:
explicit UniqueSocket();
explicit UniqueSocket(int new_sockfd);
operator int() const; // NOLINT: Implicit `int()` conversions are expected behavior.
};
// NOLINTNEXTLINE: Desired call signature.
bool load_file(std::string const& name, std::string& content);
using UniqueFile = std::unique_ptr<FILE, int (*)(FILE*)>;
UniqueFile run_command(std::string const& command, std::string const& mode);
UniqueFile open_file(std::string const& path);
template <typename Resource>
class FileStream {};
#define DECLARE_FILE_STREAM(TYPE, RESOURCE_VARIABLE_NAME, RESOURCE_INITIALIZER, FD_INITIALIZER) \
template <> \
class FileStream<TYPE> : public std::streambuf { \
private: \
/* This resource will be freed in the destructor. This resource will be freed in the destructor. */ \
TYPE const resource; \
int const fd; \
int buffered_char = EOF; \
\
public: \
explicit FileStream(TYPE RESOURCE_VARIABLE_NAME) : resource(RESOURCE_INITIALIZER), fd(FD_INITIALIZER) {} \
\
FileStream(const FileStream&) = delete; \
FileStream(FileStream&&) = delete; \
FileStream& operator=(const FileStream&) = delete; \
FileStream& operator=(FileStream&&) = delete; \
\
~FileStream() override = default; \
\
int underflow() override { \
if(buffered_char == EOF) { \
char c; \
buffered_char = read_all(fd, &c, 1) == 1 ? static_cast<int>(c) : EOF; \
} \
return buffered_char; \
} \
\
int uflow() override { \
if(buffered_char == EOF) { \
char c; \
return read_all(fd, &c, 1) == 1 ? static_cast<int>(c) : EOF; \
} \
auto c = static_cast<char>(buffered_char); \
buffered_char = EOF; \
return c; \
} \
\
int overflow(int i) override { \
auto c = static_cast<char>(i); \
return write_all(fd, &c, 1) == 1 ? i : EOF; \
} \
};
// We ignore the `unused-private-field` warning, because we use this field to
// hold ownership of the resource and free it on destruction.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-private-field"
// Non-owning file streams.
DECLARE_FILE_STREAM(int, new_fd, new_fd, new_fd)
DECLARE_FILE_STREAM(FILE*, new_file, new_file, fileno(new_file))
// Owning file streams.
DECLARE_FILE_STREAM(UniqueSocket, us, std::move(us), static_cast<int>(resource))
DECLARE_FILE_STREAM(UniqueFile, uf, std::move(uf), fileno(resource.get()))
#pragma clang diagnostic pop
// NOLINTNEXTLINE: Desired call signature.
std::ostream& print_time(std::ostream& out, struct tm& ptm, char const* const format);
std::ostream& print_used_memory(std::ostream& out, uint64_t used, uint64_t total);
UniqueSocket connect_to(std::string const& path, unsigned int port = 0, int domain = AF_LOCAL,
std::string const& interface = "", bool verbose = true);
UniqueSocket connect_to(Address const& path, int domain = AF_LOCAL, std::string const& interface = "",
bool verbose = true);
#endif
| 62.908333
| 120
| 0.358988
|
alexd2580
|
9b80cf95eb234e124ac98f1a981affc93348c214
| 3,723
|
hpp
|
C++
|
radial_menu_rviz/include/radial_menu_rviz/display_base.hpp
|
yoshito-n-students/mvc_menu_ros
|
03871da1a964f2253f0a35df8cb077ffbb4a64b9
|
[
"MIT"
] | 14
|
2020-07-19T18:30:28.000Z
|
2021-07-26T10:24:24.000Z
|
radial_menu_rviz/include/radial_menu_rviz/display_base.hpp
|
yoshito-n-students/mvc_menu_ros
|
03871da1a964f2253f0a35df8cb077ffbb4a64b9
|
[
"MIT"
] | null | null | null |
radial_menu_rviz/include/radial_menu_rviz/display_base.hpp
|
yoshito-n-students/mvc_menu_ros
|
03871da1a964f2253f0a35df8cb077ffbb4a64b9
|
[
"MIT"
] | 2
|
2020-09-05T02:18:01.000Z
|
2020-11-01T05:24:10.000Z
|
#ifndef RADIAL_MENU_RVIZ_DISPLAY_BASE_HPP
#define RADIAL_MENU_RVIZ_DISPLAY_BASE_HPP
#include <memory>
#include <radial_menu_model/model.hpp>
#include <radial_menu_msgs/State.h>
#include <radial_menu_rviz/image_overlay.hpp>
#include <radial_menu_rviz/properties.hpp>
#include <ros/console.h>
#include <ros/exception.h>
#include <ros/subscriber.h>
#include <rviz/display.h>
namespace radial_menu_rviz {
// base implementation of display classes except Qt's signals and slots
// because template classes cannot have any slots and signals by Qt's limitation
template < typename DrawingProperty, class PropertyControl, class ImageDrawer >
class DisplayBase : public rviz::Display {
public:
DisplayBase() {}
virtual ~DisplayBase() {}
protected:
// called once on initialization
virtual void onInitialize() {
// allocate objects
prop_ctl_.reset(new PropertyControl(this));
model_.reset(new radial_menu_model::Model());
drawer_.reset(new ImageDrawer(model_, prop_ctl_->drawingProperty()));
overlay_.reset(new ImageOverlay());
// apply the initial properties
// (except subscription. it will be executed in onEnable().)
updateDescription(prop_ctl_->descriptionProperty());
updateImage(prop_ctl_->drawingProperty());
updatePosition(prop_ctl_->positionProperty());
}
// called when enabled
virtual void onEnable() {
updateSubscription(prop_ctl_->subscriptionProperty());
overlay_->show();
}
// called when disabled
virtual void onDisable() {
overlay_->hide();
state_sub_.shutdown();
}
void updateDescription(const DescriptionProperty &prop) {
const std::string param_name(prop.param_name.toStdString());
if (!param_name.empty() && model_->setDescriptionFromParam(param_name)) {
state_ = model_->exportState();
updateImage();
}
}
void updateSubscription(const SubscriptionProperty &prop) {
// unsubscribe
state_sub_.shutdown();
// destroy the last state from the previous session
model_->resetState();
state_ = model_->exportState();
updateImage();
// subscribe the new topic
const std::string topic(prop.topic.toStdString());
try {
if (!topic.empty()) {
state_sub_ = ros::NodeHandle().subscribe(topic, 1, &DisplayBase::updateImage, this);
}
} catch (const ros::Exception &error) {
ROS_ERROR_STREAM(getName().toStdString()
<< ": error on subscribing '" << topic << "': " << error.what());
}
}
// update menu image based on the current configs
void updateImage() {
overlay_->setImage(drawer_->draw());
overlay_->update();
}
// update menu image with the given menu state
void updateImage(const radial_menu_msgs::StateConstPtr &new_state) {
if (state_->is_enabled != new_state->is_enabled ||
state_->pointed_id != new_state->pointed_id ||
state_->selected_ids != new_state->selected_ids) {
model_->setState(*new_state);
state_ = new_state;
updateImage();
}
}
// update menu image with the given drawing property
void updateImage(const DrawingProperty &prop) {
drawer_->setProperty(prop);
updateImage();
}
void updatePosition(const PositionProperty &prop) {
overlay_->setOrigin(prop.origin);
overlay_->update();
}
protected:
// property control via Rviz
std::unique_ptr< PropertyControl > prop_ctl_;
// menu tree model
radial_menu_model::ModelPtr model_;
// menu state subscriber
ros::Subscriber state_sub_;
radial_menu_msgs::StateConstPtr state_;
// state drawer
std::unique_ptr< ImageDrawer > drawer_;
// overlay on Rviz
std::unique_ptr< ImageOverlay > overlay_;
};
} // namespace radial_menu_rviz
#endif
| 29.547619
| 92
| 0.701585
|
yoshito-n-students
|
9b827f393bca7a9f7e5e33585c856549637422e2
| 412
|
hpp
|
C++
|
include/awl/backends/windows/cursor/convert_predefined.hpp
|
freundlich/libawl
|
0d51f388a6b662373058cb51a24ef25ed826fa0f
|
[
"BSL-1.0"
] | null | null | null |
include/awl/backends/windows/cursor/convert_predefined.hpp
|
freundlich/libawl
|
0d51f388a6b662373058cb51a24ef25ed826fa0f
|
[
"BSL-1.0"
] | null | null | null |
include/awl/backends/windows/cursor/convert_predefined.hpp
|
freundlich/libawl
|
0d51f388a6b662373058cb51a24ef25ed826fa0f
|
[
"BSL-1.0"
] | null | null | null |
#ifndef AWL_BACKENDS_WINDOWS_CURSOR_CONVERT_PREDEFINED_HPP_INCLUDED
#define AWL_BACKENDS_WINDOWS_CURSOR_CONVERT_PREDEFINED_HPP_INCLUDED
#include <awl/cursor/type_fwd.hpp>
#include <awl/detail/symbol.hpp>
#include <fcppt/char_type.hpp>
namespace awl
{
namespace backends
{
namespace windows
{
namespace cursor
{
AWL_DETAIL_SYMBOL
fcppt::char_type const *convert_predefined(awl::cursor::type);
}
}
}
}
#endif
| 15.846154
| 67
| 0.820388
|
freundlich
|
9b86206ad70bb122a452b61b6e40c23067127a31
| 231
|
cpp
|
C++
|
30_days_of_code/scope.cpp
|
williamfdevine/hackerrank
|
80045f708d84feafd9af9094c02ce5b08ba43797
|
[
"MIT"
] | null | null | null |
30_days_of_code/scope.cpp
|
williamfdevine/hackerrank
|
80045f708d84feafd9af9094c02ce5b08ba43797
|
[
"MIT"
] | null | null | null |
30_days_of_code/scope.cpp
|
williamfdevine/hackerrank
|
80045f708d84feafd9af9094c02ce5b08ba43797
|
[
"MIT"
] | null | null | null |
/**
@file scope.cpp
*/
Difference(std::vector<int> element_list): elements(element_list) {;}
void computeDifference(void)
{
std::sort(elements.begin(), elements.end());
maximumDifference = elements.back() - elements.front();
}
| 21
| 69
| 0.709957
|
williamfdevine
|
9b88ff40df4e0712115961d7447c79717dce908e
| 944
|
cpp
|
C++
|
cmygraphicsview.cpp
|
njfever/njCsSprite
|
c1aa6c148f837c8e46fe9bc69977fe9b220ede54
|
[
"Zlib"
] | null | null | null |
cmygraphicsview.cpp
|
njfever/njCsSprite
|
c1aa6c148f837c8e46fe9bc69977fe9b220ede54
|
[
"Zlib"
] | null | null | null |
cmygraphicsview.cpp
|
njfever/njCsSprite
|
c1aa6c148f837c8e46fe9bc69977fe9b220ede54
|
[
"Zlib"
] | null | null | null |
/*
Copyright (C) 2013-2014 njfever@163.com
For conditions of distribution and use, see copyright notice in dataDefine.h
*/
#include "cmygraphicsview.h"
#include "csprite.h"
#include <QScrollBar>
CMyGraphicsView::CMyGraphicsView(QWidget * parent) :
QGraphicsView(parent)
{
setViewportUpdateMode(FullViewportUpdate);
connect(horizontalScrollBar(), SIGNAL(actionTriggered(int)), this, SLOT(scrollActionTriggered(int)));
connect(verticalScrollBar(), SIGNAL(actionTriggered(int)), this, SLOT(scrollActionTriggered(int)));
}
void CMyGraphicsView::drawBackground(QPainter *painter, const QRectF &rect)
{
QBrush brush;
brush.setStyle(Qt::CrossPattern);
painter->setOpacity(0.2);
painter->fillRect(rect, brush);
QGraphicsView::drawBackground(painter, rect);
}
void CMyGraphicsView::scrollActionTriggered(int nAction)
{
Q_UNUSED(nAction);
resetCachedContent();
}
| 26.222222
| 106
| 0.71822
|
njfever
|
9b8ade16965c1ec11c912e5e1f84680598130462
| 736
|
cc
|
C++
|
L9/1 - P28318 - Files i columnes/ex1.cc
|
angelgomezsa/Cplusplus
|
9fd1ed5b1beffcf253019e8376b2bd41dac6e449
|
[
"MIT"
] | null | null | null |
L9/1 - P28318 - Files i columnes/ex1.cc
|
angelgomezsa/Cplusplus
|
9fd1ed5b1beffcf253019e8376b2bd41dac6e449
|
[
"MIT"
] | null | null | null |
L9/1 - P28318 - Files i columnes/ex1.cc
|
angelgomezsa/Cplusplus
|
9fd1ed5b1beffcf253019e8376b2bd41dac6e449
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <vector>
using namespace std;
typedef vector<int> row;
typedef vector<row> matrix;
int main() {
int n,m;
cin >> n >> m;
matrix matrix(n,row(m));
for (int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
cin >> matrix[i][j];
}
}
string p;
int x,y;
while (cin >> p) {
if (p == "fila") {
cin >> x;
cout << p << ' ' << x <<':';
for (int j=0;j<m;j++)
cout << ' ' << matrix[x-1][j];
cout << endl;
}
else if (p == "columna") {
cin >> y;
cout << p << ' ' << y <<':';
for (int i=0;i<n;i++)
cout << ' ' << matrix[i][y-1];
cout << endl;
}
else {
cin >> x >> y;
cout << p << ' ' << x << ' ' << y << ':';
cout << ' ' << matrix[x-1][y-1] << endl;
}
}
}
| 16.727273
| 44
| 0.425272
|
angelgomezsa
|
9b8bbe3a0bed388e00a6f26b7f5f54c9d6327c6c
| 1,836
|
cpp
|
C++
|
src/Tests/OutlineTest.cpp
|
Neko-Box-Coder/ssGUI
|
25e218fd79fea105a30737a63381cf8d0be943f6
|
[
"Apache-2.0"
] | 15
|
2022-01-21T10:48:04.000Z
|
2022-03-27T17:55:11.000Z
|
src/Tests/OutlineTest.cpp
|
Neko-Box-Coder/ssGUI
|
25e218fd79fea105a30737a63381cf8d0be943f6
|
[
"Apache-2.0"
] | null | null | null |
src/Tests/OutlineTest.cpp
|
Neko-Box-Coder/ssGUI
|
25e218fd79fea105a30737a63381cf8d0be943f6
|
[
"Apache-2.0"
] | 4
|
2022-01-21T10:48:05.000Z
|
2022-01-22T15:42:34.000Z
|
#include "ssGUI/HeaderGroups/StandardGroup.hpp"
#include "ssGUI/Extensions/Outline.hpp"
#include "ssGUI/Extensions/RoundedCorners.hpp"
#include "ssGUI/Extensions/Shape.hpp"
//Outline test
int main()
{
//Create the main window
ssGUI::MainWindow mainWindow;
mainWindow.SetSize(glm::ivec2(800, 800));
mainWindow.GetBackendWindowInterface()->SetMSAA(4);
DEBUG_LINE(mainWindow.GetBackendWindowInterface()->GetMSAA());
ssGUI::Widget widget;
widget.SetPosition(glm::ivec2(100, 100));
widget.SetSize(glm::ivec2(300, 300));
widget.SetBackgroundColor(glm::u8vec4(127, 127, 127, 255));
// widget.AddExtension(new ssGUI::Extensions::RoundedCorners());
// auto widgetClone = widget.Clone(false);
// widgetClone->SetBackgroundColor(glm::u8vec4(127, 100, 100, 255));
auto outline = ssGUI::Factory::Create<ssGUI::Extensions::Outline>();
outline->SetOutlineThickness(20);
// outline->ClearTargetShapes();
// outline->AddTargetVertex(0);
// outline->AddTargetVertex(1);
// outline->SetSimpleOutline(false);
// auto illegalShape = ssGUI::Factory::Create<ssGUI::Extensions::Shape>();
// illegalShape->RemoveGUIObjectShape(0);
// std::vector<glm::vec2> illegalVertices = {glm::vec2(0, 0), glm::vec2(1, 0)};
// std::vector<glm::u8vec4> illegalColors = {glm::u8vec4(0, 0, 0, 255), glm::u8vec4(0, 0, 0, 255)};
// illegalShape->AddAdditionalPolygon(illegalVertices, illegalColors, false);
// widget.AddExtension(illegalShape);
widget.AddExtension(outline);
widget.SetParent(&mainWindow);
// widgetClone->SetParent(&mainWindow);
//Create the GUIManager, add the main window and start running
ssGUI::ssGUIManager guiManager;
guiManager.AddGUIObject((ssGUI::GUIObject*)&mainWindow);
guiManager.StartRunning();
return 0;
}
| 36
| 103
| 0.697712
|
Neko-Box-Coder
|
9b8ced1c8026ce715aa55a8fe95196ff9ecbb9a4
| 1,487
|
cpp
|
C++
|
client/src/ui/explosion.cpp
|
gabyrobles93/worms-game-remake
|
b97781f39369f807ae8c8316f7f313353d7a2df7
|
[
"MIT"
] | 2
|
2019-04-24T18:27:29.000Z
|
2020-04-06T17:15:34.000Z
|
client/src/ui/explosion.cpp
|
gabyrobles93/tp-final-taller
|
b97781f39369f807ae8c8316f7f313353d7a2df7
|
[
"MIT"
] | null | null | null |
client/src/ui/explosion.cpp
|
gabyrobles93/tp-final-taller
|
b97781f39369f807ae8c8316f7f313353d7a2df7
|
[
"MIT"
] | null | null | null |
#include "explosion.h"
View::Explosion::Explosion(SDL_Renderer * r, int ratio, std::string weapon) :
sprite(EXPLOSION_FPC, ONLY_GOING) {
this->texture.loadFromFile(gPath.PATH_EXPLOSION_EFFECT, r);
this->width = ratio * 2;
this->height = ratio * 2;
this->x = 0;
this->y = 0;
this->sprite.setSpriteSheet(&this->texture);
if (weapon == "Bazooka") {
this->sound.setSound(gPath.PATH_SOUND_EXPLOSION_3);
} else if (weapon == "Grenade") {
this->sound.setSound(gPath.PATH_SOUND_EXPLOSION_2);
} else {
this->sound.setSound(gPath.PATH_SOUND_EXPLOSION_1);
}
this->soundPlayed = false;
}
View::Explosion::~Explosion() {
}
int View::Explosion::getX(void) const {
return this->x;
}
int View::Explosion::getY(void) const {
return this->y;
}
int View::Explosion::getWidth(void) const {
return this->width;
}
int View::Explosion::getHeight(void) const {
return this->height;
}
void View::Explosion::setX(int x) {
this->x = x - this->width / 2;
}
void View::Explosion::setY(int y) {
this->y = y - this->height / 2;
}
void View::Explosion::render(SDL_Renderer * r, int camX, int camY) {
if (!this->sprite.finished()) {
if (!this->soundPlayed) {
this->sound.playSound(0);
this->soundPlayed = true;
}
SDL_Rect clip = this->sprite.getNextClip();
this->texture.render(r, this->x - camX, this->y - camY, this->width, this->height, &clip);
}
}
bool View::Explosion::finishedExplosion(void) {
return this->sprite.finished();
}
| 23.603175
| 92
| 0.661735
|
gabyrobles93
|
9b8e56ad441dd00df92e688a1d36bd8665da47d0
| 2,213
|
cc
|
C++
|
33-print-table-of-processes/print-table-of-processes.cc
|
yans0ng/coding-is-life
|
1a6842e60adee914e49c3d8dc88d1000566d9561
|
[
"MIT"
] | null | null | null |
33-print-table-of-processes/print-table-of-processes.cc
|
yans0ng/coding-is-life
|
1a6842e60adee914e49c3d8dc88d1000566d9561
|
[
"MIT"
] | null | null | null |
33-print-table-of-processes/print-table-of-processes.cc
|
yans0ng/coding-is-life
|
1a6842e60adee914e49c3d8dc88d1000566d9561
|
[
"MIT"
] | null | null | null |
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>
enum class ProcessStatus { SUSPENDED, RUNNING };
std::ostream &operator<<(std::ostream &os, const ProcessStatus &status) {
if (status == ProcessStatus::SUSPENDED) {
os << "suspended";
} else if (status == ProcessStatus::RUNNING) {
os << "running";
}
return os;
}
enum class Platform { P_32_BIT, P_64_BIT };
std::ostream &operator<<(std::ostream &os, const Platform &status) {
if (status == Platform::P_32_BIT) {
os << "32-bit";
} else if (status == Platform::P_64_BIT) {
os << "64-bit";
}
return os;
}
struct ProcessInfo {
int id;
std::string name;
ProcessStatus status;
std::string account;
size_t memory;
Platform platform;
};
void PrintProcesses(std::vector<ProcessInfo> processes) {
std::sort(processes.begin(), processes.end(),
[](const ProcessInfo &p1, const ProcessInfo &p2) {
return p1.name < p2.name;
});
for (const auto process : processes) {
std::cout << std::left << std::setw(20) << std::setfill(' ')
<< process.name;
std::cout << std::left << std::setw(8) << std::setfill(' ') << process.id;
std::cout << std::left << std::setw(12) << std::setfill(' ')
<< process.status;
std::cout << std::left << std::setw(15) << std::setfill(' ')
<< process.account;
std::cout << std::left << std::setw(10) << std::setfill(' ')
<< (int)process.memory / 1024;
std::cout << std::left << ' ' << process.platform;
std::cout << std::endl;
}
}
int main() {
std::vector<ProcessInfo> processes {
{512, "cmd.exe", ProcessStatus::RUNNING, "SYSTEM", 148293, Platform::P_64_BIT},
{1044, "chrome.exe", ProcessStatus::RUNNING, "marius.bancila", 25180454, Platform::P_32_BIT},
{7108, "explorer.exe", ProcessStatus::RUNNING, "SYSTEM", 2952943, Platform::P_64_BIT},
{10100, "chrome.exe", ProcessStatus::RUNNING, "marius.bancila", 227756123, Platform::P_32_BIT},
{22456, "skype.exe", ProcessStatus::SUSPENDED, "marius.bancila", 16870123, Platform::P_64_BIT},
};
PrintProcesses(processes);
return 0;
}
| 33.530303
| 103
| 0.60732
|
yans0ng
|
9b91ffcdc766074ad64803a2c277634348734c52
| 8,454
|
cpp
|
C++
|
raven/graphics/VulkanSwapChain.cpp
|
nielsuiterwijk/vulkan
|
b2d5c7d23f7a16d9fdb9ba2796051da4d9e66e05
|
[
"MIT"
] | 2
|
2019-11-28T12:42:44.000Z
|
2021-07-02T12:50:20.000Z
|
raven/graphics/VulkanSwapChain.cpp
|
nielsuiterwijk/vulkan
|
b2d5c7d23f7a16d9fdb9ba2796051da4d9e66e05
|
[
"MIT"
] | null | null | null |
raven/graphics/VulkanSwapChain.cpp
|
nielsuiterwijk/vulkan
|
b2d5c7d23f7a16d9fdb9ba2796051da4d9e66e05
|
[
"MIT"
] | null | null | null |
#include "VulkanSwapChain.h"
#include "GraphicsDevice.h"
#include "VulkanInstance.h"
#include "graphics\GraphicsContext.h"
#include "helpers\VulkanHelpers.h"
#include "vec2.hpp"
#include <algorithm>
VulkanSwapChain::VulkanSwapChain() :
surface( GraphicsContext::VulkanInstance->GetNative(), vkDestroySurfaceKHR, GraphicsContext::LocalAllocator ),
swapChain(),
nextBackBufferIndex( 0 ),
depthBuffer()
{
}
VulkanSwapChain::~VulkanSwapChain()
{
DestroyFrameBuffers();
DestroySwapchain();
}
void VulkanSwapChain::Connect( const glm::u32vec2& windowSize, const QueueFamilyIndices& indices )
{
details.Initialize( GraphicsContext::PhysicalDevice, surface );
nextBackBufferIndex = 0;
surfaceFormat = PickSwapSurfaceFormat( details.formats );
presentMode = PickSwapPresentMode( details.presentModes, false );
extent = GetSwapExtents( details.capabilities, windowSize );
//Triple buffering!
uint32_t imageCount = 3;
if ( details.capabilities.maxImageCount > 0 && imageCount > details.capabilities.maxImageCount )
{
imageCount = details.capabilities.maxImageCount;
}
uint32_t queueFamilyIndices[] = { (uint32_t)indices.graphicsFamily, (uint32_t)indices.presentFamily };
VkSwapchainCreateInfoKHR createInfo = {};
createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
createInfo.surface = surface;
createInfo.minImageCount = imageCount;
createInfo.imageFormat = surfaceFormat.format;
createInfo.imageColorSpace = surfaceFormat.colorSpace;
createInfo.imageExtent = extent;
createInfo.imageArrayLayers = 1;
createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
if ( indices.graphicsFamily == indices.presentFamily )
{
createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
createInfo.queueFamilyIndexCount = 0;
createInfo.pQueueFamilyIndices = nullptr;
}
else
{
createInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
createInfo.queueFamilyIndexCount = 2;
createInfo.pQueueFamilyIndices = queueFamilyIndices;
}
createInfo.preTransform = details.capabilities.currentTransform;
createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; //always ignore alpha channel blending with other surfaces
createInfo.presentMode = presentMode;
createInfo.clipped = VK_TRUE;
if ( swapChain == nullptr )
createInfo.oldSwapchain = VK_NULL_HANDLE;
else
createInfo.oldSwapchain = *swapChain.Replace();
swapChain.Initialize( GraphicsContext::LogicalDevice, vkDestroySwapchainKHR, GraphicsContext::LocalAllocator );
if ( vkCreateSwapchainKHR( GraphicsContext::LogicalDevice, &createInfo, swapChain.AllocationCallbacks(), swapChain.Replace() ) != VK_SUCCESS )
{
ASSERT_FAIL( "failed to create swap chain!" );
}
//The implementation is allowed to create more images, which is why we need to explicitly query the amount again.
vkGetSwapchainImagesKHR( GraphicsContext::LogicalDevice, swapChain, &imageCount, nullptr );
std::vector<VkImage> images( imageCount );
vkGetSwapchainImagesKHR( GraphicsContext::LogicalDevice, swapChain, &imageCount, images.data() );
imageFormat = surfaceFormat.format;
std::cout << "Created " << imageCount << " images of " << extent.width << "x" << extent.height << " format: " << Vulkan::GetFormatName( imageFormat ) << std::endl;
backBuffers.resize( imageCount );
for ( int i = 0; i < images.size(); i++ )
{
backBuffers[ i ].InitializeImageView( imageFormat, images[ i ] );
}
depthBuffer.Initialize( windowSize.x, windowSize.y );
}
void VulkanSwapChain::SetupFrameBuffers()
{
for ( size_t i = 0; i < backBuffers.size(); i++ )
{
backBuffers[ i ].InitializeFrameBuffer( extent.width, extent.height, depthBuffer );
}
std::cout << "[Vulkan] created: " << backBuffers.size() << " back buffers." << std::endl;
}
void VulkanSwapChain::DestroyFrameBuffers()
{
depthBuffer.Destroy();
for ( size_t i = 0; i < backBuffers.size(); i++ )
{
backBuffers[ i ].Destroy();
}
}
void VulkanSwapChain::DestroySwapchain()
{
swapChain = nullptr;
}
int32_t VulkanSwapChain::PrepareBackBuffer()
{
uint32_t imageIndex = -1;
VkResult result = vkAcquireNextImageKHR( GraphicsContext::LogicalDevice, swapChain, std::numeric_limits<uint64_t>::max(), backBuffers[ nextBackBufferIndex ].GetLock(), VK_NULL_HANDLE, &imageIndex );
if ( result == VK_ERROR_OUT_OF_DATE_KHR )
{
return -1;
}
ASSERT( result == VK_SUCCESS || result == VK_SUBOPTIMAL_KHR );
ASSERT( imageIndex == nextBackBufferIndex ); //imageIndex should be the same as backBufferIndex
nextBackBufferIndex = ( nextBackBufferIndex + 1 ) % backBuffers.size();
return imageIndex;
}
VkSurfaceFormatKHR VulkanSwapChain::PickSwapSurfaceFormat( const std::vector<VkSurfaceFormatKHR>& availableFormats )
{
//Best case scenario, our surface accepts any format, lets pick the best combination
if ( availableFormats.size() == 1 && availableFormats[ 0 ].format == VK_FORMAT_UNDEFINED )
{
return { VK_FORMAT_B8G8R8A8_UNORM, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR };
}
//If we cannot choose any, lets see if there is a 'best' format available.
for ( const auto& availableFormat : availableFormats )
{
if ( availableFormat.format == VK_FORMAT_B8G8R8A8_UNORM && availableFormat.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR )
{
return availableFormat;
}
}
//If thats not possible, don't bother and use whatever.
return availableFormats[ 0 ];
}
VkPresentModeKHR VulkanSwapChain::PickSwapPresentMode( const std::vector<VkPresentModeKHR>& availablePresentModes, bool waitForVSync )
{
//These are explained here: https://harrylovescode.gitbooks.io/vulkan-api/content/chap06/chap06.html
if ( waitForVSync )
{
for ( const auto& availablePresentMode : availablePresentModes )
{
if ( availablePresentMode == VK_PRESENT_MODE_MAILBOX_KHR )
{
return availablePresentMode;
}
}
}
else
{
for ( const auto& availablePresentMode : availablePresentModes )
{
if ( availablePresentMode == VK_PRESENT_MODE_IMMEDIATE_KHR )
{
return availablePresentMode;
}
}
}
return VK_PRESENT_MODE_FIFO_KHR;
}
VkExtent2D VulkanSwapChain::GetSwapExtents( const VkSurfaceCapabilitiesKHR& capabilities, const glm::u32vec2& windowSize )
{
//The idea is to always pick the size of the window we render to, if that is not possible (told by have the current extent set to int32.max)
//we'll try the largest size available.
if ( capabilities.currentExtent.width != std::numeric_limits<uint32_t>::max() )
{
return capabilities.currentExtent;
}
VkExtent2D actualExtent = { windowSize.x, windowSize.y };
actualExtent.width = std::max( capabilities.minImageExtent.width, std::min( capabilities.maxImageExtent.width, actualExtent.width ) );
actualExtent.height = std::max( capabilities.minImageExtent.height, std::min( capabilities.maxImageExtent.height, actualExtent.height ) );
return actualExtent;
}
InstanceWrapper<VkSurfaceKHR>& VulkanSwapChain::GetSurface()
{
return surface;
}
const FrameBuffer& VulkanSwapChain::GetFrameBuffer( int32_t frameIndex )
{
return backBuffers[ frameIndex ];
}
const VkSurfaceFormatKHR& VulkanSwapChain::GetSurfaceFormat() const
{
return surfaceFormat;
}
const VkPresentModeKHR& VulkanSwapChain::GetPresentMode() const
{
return presentMode;
}
VkExtent2D VulkanSwapChain::GetExtent() const
{
return extent;
}
const DepthBuffer& VulkanSwapChain::GetDepthBuffer() const
{
return depthBuffer;
}
const InstanceWrapper<VkSwapchainKHR>& VulkanSwapChain::GetNative() const
{
return swapChain;
}
void VulkanSwapChainDetails::Initialize( const VkPhysicalDevice& physicalDevice, const InstanceWrapper<VkSurfaceKHR>& surface )
{
vkGetPhysicalDeviceSurfaceCapabilitiesKHR( physicalDevice, surface, &capabilities );
//TODO: See if there is a way to make these sort of calls a helper method?
{
uint32_t formatCount = 0;
vkGetPhysicalDeviceSurfaceFormatsKHR( physicalDevice, surface, &formatCount, nullptr );
if ( formatCount != 0 )
{
formats.resize( formatCount );
vkGetPhysicalDeviceSurfaceFormatsKHR( physicalDevice, surface, &formatCount, formats.data() );
}
}
{
uint32_t presentModeCount;
vkGetPhysicalDeviceSurfacePresentModesKHR( physicalDevice, surface, &presentModeCount, nullptr );
if ( presentModeCount != 0 )
{
presentModes.resize( presentModeCount );
vkGetPhysicalDeviceSurfacePresentModesKHR( physicalDevice, surface, &presentModeCount, presentModes.data() );
}
}
}
bool VulkanSwapChainDetails::IsValid() const
{
return !formats.empty() && !presentModes.empty();
}
| 30.085409
| 199
| 0.763071
|
nielsuiterwijk
|
9b9fa50de1c25a3022e43e54baadf28e6d5128bd
| 595
|
hpp
|
C++
|
FaceLandmarking/math/point.hpp
|
TomaszRewak/FaceLandmarking
|
74bc5cbcdb61cd9835e5bfc61e978fad256940f4
|
[
"MIT"
] | 78
|
2018-02-09T14:30:06.000Z
|
2020-10-01T08:43:32.000Z
|
FaceLandmarking/math/point.hpp
|
YoungerGao/Face-Landmarking
|
74bc5cbcdb61cd9835e5bfc61e978fad256940f4
|
[
"MIT"
] | 1
|
2019-03-20T00:16:47.000Z
|
2019-03-24T09:12:25.000Z
|
FaceLandmarking/math/point.hpp
|
YoungerGao/Face-Landmarking
|
74bc5cbcdb61cd9835e5bfc61e978fad256940f4
|
[
"MIT"
] | 8
|
2019-03-03T11:57:43.000Z
|
2021-07-01T09:27:20.000Z
|
#pragma once
#include "vector.hpp"
namespace FaceLandmarking::Math {
template<typename T>
struct Point {
T x;
T y;
Point()
{ }
Point(T x, T y):
x(x),
y(y)
{ }
Point<T> operator+(const Vector<T>& vector) const
{
return Point<T>(x + vector.x, y + vector.y);
}
void operator+=(const Vector<T>& vector)
{
x += vector.x;
y += vector.y;
}
Point<T> operator-(const Vector<T>& vector) const
{
return Point<T>(x - vector.x, y - vector.y);
}
Vector<T> to(const Point<T>& point) const
{
return Vector<T>(point.x - x, point.y - y);
}
};
}
| 14.875
| 51
| 0.566387
|
TomaszRewak
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.