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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
787f2835bbc3f6b69581d16d01f1f5606afe8664
| 2,141
|
hpp
|
C++
|
src/Service.hpp
|
dancol90/wifi-led-clock
|
d4d391226ddc26ff92fd894e184c5348953b3bfa
|
[
"MIT"
] | 2
|
2018-10-10T12:37:05.000Z
|
2018-12-07T22:36:42.000Z
|
src/Service.hpp
|
dancol90/wifi-led-clock
|
d4d391226ddc26ff92fd894e184c5348953b3bfa
|
[
"MIT"
] | null | null | null |
src/Service.hpp
|
dancol90/wifi-led-clock
|
d4d391226ddc26ff92fd894e184c5348953b3bfa
|
[
"MIT"
] | null | null | null |
#include <Arduino.h>
#include "Task.hpp"
#include <map>
#include <vector>
#include <functional>
#ifndef SERVICE_HPP
#define SERVICE_HPP
#ifdef _DEBUG
// This macros works only with string literals, and cannot be used in headers files.
#define SERVICES_PRINTF(format, ...) Serial.printf_P(PSTR(format), ##__VA_ARGS__)
#define SERVICES_PRINT(text) SERVICES_PRINTF(text)
#define SERVICE_PRINTF(format, ...) Serial.printf_P(PSTR("[%s] " format), _ServiceName.c_str(), ##__VA_ARGS__)
#define SERVICE_PRINT(text) SERVICE_PRINTF(text)
#else
#define SERVICES_PRINT(text)
#define SERVICES_PRINTF(...)
#define SERVICE_PRINTF(...)
#define SERVICE_PRINT(text)
#endif
#define S(name, type) ((type*)Service::Get(name))
struct char_compare
{
bool operator () (const char *a, const char *b) const { return strcmp(a, b) < 0; }
};
enum UpdateType
{
UPDATE_SYNC,
UPDATE_ASYNC
};
enum UpdateRequest
{
NO_UPDATE,
DO_UPDATE,
ALWAYS_UPDATE
};
class Service
{
public:
typedef std::function<void(Service* svc)> EventCallback;
typedef std::map<const char*, Service*, char_compare> ServiceMap;
typedef std::map<const char*, std::vector<EventCallback>, char_compare> EventMap;
Service() {};
virtual void Init() = 0;
virtual void Update() = 0;
static Service* Get(const char* name);
static void BindEvent(const char* event, EventCallback callback);
static void InitAll();
static void SyncUpdate();
static void SuspendAsyncUpdates();
protected:
static void RegisterService(Service* service, const char* name, std::vector<const char*> events);
static void FireEvent(Service* service, const char* event);
void SetPeriodicUpdate(unsigned int period, UpdateType ut = UPDATE_ASYNC);
void EnablePeriodicUpdate();
void DisablePeriodicUpdate();
UpdateRequest _UpdateRequest;
String _ServiceName;
private:
Task _UpdateTask;
// List of service (name,instance) pairs.
static ServiceMap _Services;
// Map every event name (declared by services in register_service) with one or more callbacks.
static EventMap _Events;
};
#endif
| 24.609195
| 111
| 0.711817
|
dancol90
|
7885036a6de923a917c87290c429c078b761c428
| 5,675
|
hpp
|
C++
|
include/UnityEngine/UI/ToggleGroup_--c.hpp
|
RedBrumbler/virtuoso-codegen
|
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
|
[
"Unlicense"
] | null | null | null |
include/UnityEngine/UI/ToggleGroup_--c.hpp
|
RedBrumbler/virtuoso-codegen
|
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
|
[
"Unlicense"
] | null | null | null |
include/UnityEngine/UI/ToggleGroup_--c.hpp
|
RedBrumbler/virtuoso-codegen
|
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
|
[
"Unlicense"
] | null | null | null |
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: UnityEngine.UI.ToggleGroup
#include "UnityEngine/UI/ToggleGroup.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Predicate`1<T>
template<typename T>
class Predicate_1;
// Forward declaring type: Func`2<T, TResult>
template<typename T, typename TResult>
class Func_2;
}
// Forward declaring namespace: UnityEngine::UI
namespace UnityEngine::UI {
// Forward declaring type: Toggle
class Toggle;
}
// Completed forward declares
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::UnityEngine::UI::ToggleGroup::$$c);
DEFINE_IL2CPP_ARG_TYPE(::UnityEngine::UI::ToggleGroup::$$c*, "UnityEngine.UI", "ToggleGroup/<>c");
// Type namespace: UnityEngine.UI
namespace UnityEngine::UI {
// Size: 0x10
#pragma pack(push, 1)
// Autogenerated type: UnityEngine.UI.ToggleGroup/UnityEngine.UI.<>c
// [TokenAttribute] Offset: FFFFFFFF
// [CompilerGeneratedAttribute] Offset: FFFFFFFF
class ToggleGroup::$$c : public ::Il2CppObject {
public:
// Get static field: static public readonly UnityEngine.UI.ToggleGroup/UnityEngine.UI.<>c <>9
static ::UnityEngine::UI::ToggleGroup::$$c* _get_$$9();
// Set static field: static public readonly UnityEngine.UI.ToggleGroup/UnityEngine.UI.<>c <>9
static void _set_$$9(::UnityEngine::UI::ToggleGroup::$$c* value);
// Get static field: static public System.Predicate`1<UnityEngine.UI.Toggle> <>9__13_0
static ::System::Predicate_1<::UnityEngine::UI::Toggle*>* _get_$$9__13_0();
// Set static field: static public System.Predicate`1<UnityEngine.UI.Toggle> <>9__13_0
static void _set_$$9__13_0(::System::Predicate_1<::UnityEngine::UI::Toggle*>* value);
// Get static field: static public System.Func`2<UnityEngine.UI.Toggle,System.Boolean> <>9__14_0
static ::System::Func_2<::UnityEngine::UI::Toggle*, bool>* _get_$$9__14_0();
// Set static field: static public System.Func`2<UnityEngine.UI.Toggle,System.Boolean> <>9__14_0
static void _set_$$9__14_0(::System::Func_2<::UnityEngine::UI::Toggle*, bool>* value);
// static private System.Void .cctor()
// Offset: 0x1145354
static void _cctor();
// System.Boolean <AnyTogglesOn>b__13_0(UnityEngine.UI.Toggle x)
// Offset: 0x11453BC
bool $AnyTogglesOn$b__13_0(::UnityEngine::UI::Toggle* x);
// System.Boolean <ActiveToggles>b__14_0(UnityEngine.UI.Toggle x)
// Offset: 0x11453D4
bool $ActiveToggles$b__14_0(::UnityEngine::UI::Toggle* x);
// public System.Void .ctor()
// Offset: 0x11453B4
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static ToggleGroup::$$c* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::UnityEngine::UI::ToggleGroup::$$c::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<ToggleGroup::$$c*, creationType>()));
}
}; // UnityEngine.UI.ToggleGroup/UnityEngine.UI.<>c
#pragma pack(pop)
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: UnityEngine::UI::ToggleGroup::$$c::_cctor
// Il2CppName: .cctor
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)()>(&UnityEngine::UI::ToggleGroup::$$c::_cctor)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::ToggleGroup::$$c*), ".cctor", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: UnityEngine::UI::ToggleGroup::$$c::$AnyTogglesOn$b__13_0
// Il2CppName: <AnyTogglesOn>b__13_0
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (UnityEngine::UI::ToggleGroup::$$c::*)(::UnityEngine::UI::Toggle*)>(&UnityEngine::UI::ToggleGroup::$$c::$AnyTogglesOn$b__13_0)> {
static const MethodInfo* get() {
static auto* x = &::il2cpp_utils::GetClassFromName("UnityEngine.UI", "Toggle")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::ToggleGroup::$$c*), "<AnyTogglesOn>b__13_0", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{x});
}
};
// Writing MetadataGetter for method: UnityEngine::UI::ToggleGroup::$$c::$ActiveToggles$b__14_0
// Il2CppName: <ActiveToggles>b__14_0
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (UnityEngine::UI::ToggleGroup::$$c::*)(::UnityEngine::UI::Toggle*)>(&UnityEngine::UI::ToggleGroup::$$c::$ActiveToggles$b__14_0)> {
static const MethodInfo* get() {
static auto* x = &::il2cpp_utils::GetClassFromName("UnityEngine.UI", "Toggle")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::ToggleGroup::$$c*), "<ActiveToggles>b__14_0", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{x});
}
};
// Writing MetadataGetter for method: UnityEngine::UI::ToggleGroup::$$c::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
| 53.037383
| 204
| 0.715771
|
RedBrumbler
|
7885bbd7dca3a8088cabc113fe6db4c1f1ad4870
| 33,720
|
cpp
|
C++
|
Wrappers/java/jni/org_openni_NativeMethods.cpp
|
BEIWG/OpenNI2
|
3d144e98884dd78703a3e145856dded166f87e60
|
[
"Apache-2.0"
] | null | null | null |
Wrappers/java/jni/org_openni_NativeMethods.cpp
|
BEIWG/OpenNI2
|
3d144e98884dd78703a3e145856dded166f87e60
|
[
"Apache-2.0"
] | 2
|
2018-04-16T10:51:56.000Z
|
2018-04-24T06:35:09.000Z
|
Wrappers/java/jni/org_openni_NativeMethods.cpp
|
BEIWG/OpenNI2
|
3d144e98884dd78703a3e145856dded166f87e60
|
[
"Apache-2.0"
] | null | null | null |
/*****************************************************************************
* *
* OpenNI 2.x Alpha *
* Copyright (C) 2012 PrimeSense Ltd. *
* *
* This file is part of OpenNI. *
* *
* 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 <jni.h>
#include "OniProperties.h"
#include "OniEnums.h"
#include "OniCAPI.h"
#include "org_openni_NativeMethods.h"
#include <XnPlatform.h>
#ifdef ANDROID
#include <android/log.h>
#endif
#define DEBUG 1
#if DEBUG && defined(ANDROID)
#include <android/log.h>
# define LOGD(x...) __android_log_print(ANDROID_LOG_INFO,"OpenNIJNI",x)
# define LOGE(x...) __android_log_print(ANDROID_LOG_ERROR,"OpenNIJNI",x)
#else
# define LOGD(...)
# define LOGE(...)
#endif
using namespace openni;
JavaVM* g_pVM = NULL;
jclass g_videoStreamClass;
jclass g_openNIClass;
jclass g_deviceInfoClass;
class JNIEnvSupplier
{
public:
JNIEnvSupplier() : m_pEnv(NULL), m_bShouldDetach(FALSE)
{
if (JNI_EDETACHED == g_pVM->GetEnv((void**)&m_pEnv, JNI_VERSION_1_2))
{
g_pVM->AttachCurrentThread((void**)&m_pEnv, NULL);
m_bShouldDetach = TRUE;
}
}
~JNIEnvSupplier()
{
if (m_bShouldDetach)
{
g_pVM->DetachCurrentThread();
}
}
JNIEnv* GetEnv() { return m_pEnv; }
private:
JNIEnv* m_pEnv;
XnBool m_bShouldDetach;
};
void SetOutArgObjectValue(JNIEnv*env, jobject p, jobject value)
{
jclass cls = env->GetObjectClass(p);
jfieldID fieldID = env->GetFieldID(cls, "mValue", "Ljava/lang/Object;");
env->SetObjectField(p, fieldID, value);
}
void SetOutArgVideoModeValue(JNIEnv*env, jobject p, jobject value)
{
SetOutArgObjectValue(env, p, value);
}
void SetOutArgDoubleValue(JNIEnv*env, jobject p, double value)
{
jclass cls = env->FindClass("java/lang/Double");
jmethodID ctor = env->GetMethodID(cls, "<init>", "(D)V");
SetOutArgObjectValue(env, p, env->NewObject(cls, ctor, value));
}
void SetOutArgLongValue(JNIEnv*env, jobject p, XnUInt64 value)
{
jclass cls = env->FindClass("java/lang/Long");
jmethodID ctor = env->GetMethodID(cls, "<init>", "(J)V");
SetOutArgObjectValue(env, p, env->NewObject(cls, ctor, value));
}
void SetOutArgIntValue(JNIEnv*env, jobject p, int value)
{
jclass cls = env->FindClass("java/lang/Integer");
jmethodID ctor = env->GetMethodID(cls, "<init>", "(I)V");
SetOutArgObjectValue(env, p, env->NewObject(cls, ctor, value));
}
void SetOutArgShortValue(JNIEnv*env, jobject p, short value)
{
jclass cls = env->FindClass("java/lang/Short");
jmethodID ctor = env->GetMethodID(cls, "<init>", "(S)V");
SetOutArgObjectValue(env, p, env->NewObject(cls, ctor, value));
}
void SetOutArgByteValue(JNIEnv*env, jobject p, XnUInt8 value)
{
jclass cls = env->FindClass("java/lang/Byte");
jmethodID ctor = env->GetMethodID(cls, "<init>", "(B)V");
SetOutArgObjectValue(env, p, env->NewObject(cls, ctor, value));
}
void SetOutArgBoolValue(JNIEnv*env, jobject p, jboolean value)
{
jclass cls = env->FindClass("java/lang/Boolean");
jmethodID ctor = env->GetMethodID(cls, "<init>", "(Z)V");
SetOutArgObjectValue(env, p, env->NewObject(cls, ctor, value));
}
void SetOutArgFloatValue(JNIEnv*env, jobject p, jfloat value)
{
jclass cls = env->FindClass("java/lang/Float");
jmethodID ctor = env->GetMethodID(cls, "<init>", "(F)V");
SetOutArgObjectValue(env, p, env->NewObject(cls, ctor, value));
}
void SetOutArgStringValue(JNIEnv*env, jobject p, const XnChar* value)
{
SetOutArgObjectValue(env, p, env->NewStringUTF(value));
}
JNIEnv *g_env;
JNIEXPORT void JNICALL Java_org_openni_NativeMethods_oniFrameRelease
(JNIEnv *, jclass, jlong frame)
{
// oniFrameRelease((OniFrame*)frame);
}
JNIEXPORT void JNICALL Java_org_openni_NativeMethods_oniFrameAddRef
(JNIEnv *, jclass, jlong frame)
{
//oniFrameAddRef((OniFrame*)frame);
}
static void ONI_CALLBACK_TYPE callback(OniStreamHandle streamHandle, void*)
{
JNIEnvSupplier suplier;
jmethodID methodID = suplier.GetEnv()->GetStaticMethodID(g_videoStreamClass, "onFrameReady", "(J)V");
jlong handle = (jlong)streamHandle;
suplier.GetEnv()->CallStaticVoidMethod(g_videoStreamClass, methodID, handle);
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniDeviceCreateStream
(JNIEnv *env, jclass, jlong device, jint sensorType, jobject videoStreamObj)
{
OniStreamHandle* streamHandle;
jint status = oniDeviceCreateStream((OniDeviceHandle)device, (OniSensorType)sensorType, (OniStreamHandle*)&streamHandle);
if (status == ONI_STATUS_OK)
{
jclass videoStreamCls = env->FindClass("org/openni/VideoStream");
jfieldID fieldID = env->GetFieldID(videoStreamCls, "mStreamHandle", "J");
env->SetLongField(videoStreamObj, fieldID, (jlong)streamHandle);
OniCallbackHandle handle = 0;
status = oniStreamRegisterNewFrameCallback((OniStreamHandle)streamHandle, callback, videoStreamCls, &handle);
fieldID = env->GetFieldID(videoStreamCls, "mCallbackHandle", "J");
env->SetLongField(videoStreamObj, fieldID, (jlong)handle);
}
return status;
}
JNIEXPORT void JNICALL Java_org_openni_NativeMethods_oniStreamDestroy
(JNIEnv *, jclass, jlong streamHandle, jlong callbackHandle)
{
oniStreamUnregisterNewFrameCallback((OniStreamHandle)streamHandle,(OniCallbackHandle)callbackHandle);
oniStreamDestroy((OniStreamHandle)streamHandle);
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniStreamStart
(JNIEnv *, jclass, jlong streamHandle)
{
return oniStreamStart((OniStreamHandle)streamHandle);
}
JNIEXPORT void JNICALL Java_org_openni_NativeMethods_oniStreamStop
(JNIEnv *, jclass, jlong streamHandle)
{
oniStreamStop((OniStreamHandle)streamHandle);
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniStreamReadFrame
(JNIEnv *env, jclass, jlong streamHandle, jobject outArgObj)
{
OniFrame* pOniFrame;
int status = oniStreamReadFrame((OniStreamHandle)streamHandle, &pOniFrame);
if (status == STATUS_OK)
{
jclass videoFrameRefCls = env->FindClass("org/openni/VideoFrameRef");
jmethodID videoFrameCtor = env->GetMethodID(videoFrameRefCls, "<init>", "(J)V");
jobject videoFrameRefObj = env->NewObject(videoFrameRefCls, videoFrameCtor, (jlong)pOniFrame);
jfieldID fieldID = env->GetFieldID(videoFrameRefCls, "mTimestamp", "J");
env->SetLongField(videoFrameRefObj,fieldID, (jlong)pOniFrame->timestamp);
fieldID = env->GetFieldID(videoFrameRefCls, "mIndex", "I");
env->SetIntField(videoFrameRefObj,fieldID, pOniFrame->frameIndex);
fieldID = env->GetFieldID(videoFrameRefCls, "mWidth", "I");
env->SetIntField(videoFrameRefObj,fieldID, pOniFrame->width);
fieldID = env->GetFieldID(videoFrameRefCls, "mHeight", "I");
env->SetIntField(videoFrameRefObj,fieldID, pOniFrame->height);
fieldID = env->GetFieldID(videoFrameRefCls, "mIsCropping", "Z");
env->SetBooleanField(videoFrameRefObj,fieldID, (pOniFrame->croppingEnabled == TRUE));
fieldID = env->GetFieldID(videoFrameRefCls, "mCropOrigX", "I");
env->SetIntField(videoFrameRefObj,fieldID, pOniFrame->cropOriginX);
fieldID = env->GetFieldID(videoFrameRefCls, "mCropOrigY", "I");
env->SetIntField(videoFrameRefObj,fieldID, pOniFrame->cropOriginY);
fieldID = env->GetFieldID(videoFrameRefCls, "mStride", "I");
env->SetIntField(videoFrameRefObj,fieldID, pOniFrame->stride);
jclass byteOrderCls = env->FindClass("java/nio/ByteOrder");
jfieldID littleEndianField = env->GetStaticFieldID(byteOrderCls, "LITTLE_ENDIAN", "Ljava/nio/ByteOrder;");
jobject littleEndian = env->GetStaticObjectField(byteOrderCls, littleEndianField);
jclass byteBufferCls = env->FindClass("java/nio/ByteBuffer");
jmethodID orderMethodId = env->GetMethodID(byteBufferCls, "order", "(Ljava/nio/ByteOrder;)Ljava/nio/ByteBuffer;");
jobject buffer = env->NewDirectByteBuffer(pOniFrame->data, pOniFrame->dataSize);
env->CallObjectMethod(buffer, orderMethodId, littleEndian);
fieldID = env->GetFieldID(videoFrameRefCls, "mData", "Ljava/nio/ByteBuffer;");
env->SetObjectField(videoFrameRefObj,fieldID, buffer);
jclass sensorTypeCls = env->FindClass("org/openni/SensorType");
jmethodID sensorFromNative = env->GetStaticMethodID(sensorTypeCls, "fromNative", "(I)Lorg/openni/SensorType;");
jobject sensorTypeObj = env->CallStaticObjectMethod(sensorTypeCls, sensorFromNative, pOniFrame->sensorType);
fieldID = env->GetFieldID(videoFrameRefCls, "mSensorType", "Lorg/openni/SensorType;");
env->SetObjectField(videoFrameRefObj,fieldID, sensorTypeObj);
jclass videoModeCls = env->FindClass("org/openni/VideoMode");
jmethodID videoModeCtor = env->GetMethodID(videoModeCls, "<init>", "(IIII)V");
jobject videoModeObj = env->NewObject(videoModeCls, videoModeCtor, (jint)pOniFrame->videoMode.resolutionX,
(jint)pOniFrame->videoMode.resolutionY, (jint)pOniFrame->videoMode.fps, (jint)pOniFrame->videoMode.pixelFormat);
fieldID = env->GetFieldID(videoFrameRefCls, "mVideoMode", "Lorg/openni/VideoMode;");
env->SetObjectField(videoFrameRefObj,fieldID, videoModeObj);
SetOutArgObjectValue(env, outArgObj, videoFrameRefObj);
// release this frame. The java object is its owner now.
oniFrameRelease(pOniFrame);
}
return status;
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_getCropping
(JNIEnv *env, jclass, jlong streamHandle, jobject origXOutArg, jobject origYOutArg, jobject widthOurArg, jobject heightOurArg)
{
OniCropping cropping;
int size = sizeof(cropping);
int status = oniStreamGetProperty((OniStreamHandle)streamHandle, STREAM_PROPERTY_CROPPING, &cropping, &size);
SetOutArgIntValue(env, origXOutArg, cropping.originX);
SetOutArgIntValue(env, origYOutArg, cropping.originY);
SetOutArgIntValue(env, widthOurArg, cropping.width);
SetOutArgIntValue(env, heightOurArg, cropping.height);
return status;
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_setCropping
(JNIEnv *, jclass, jlong streamHandle, jint originX, jint originY, jint width, jint height)
{
OniCropping cropping;
cropping.enabled = true;
cropping.originX = originX;
cropping.originY = originY;
cropping.width = width;
cropping.height = height;
return oniStreamSetProperty((OniStreamHandle)streamHandle, STREAM_PROPERTY_CROPPING, &cropping, sizeof(cropping));
}
JNIEXPORT jboolean JNICALL Java_org_openni_NativeMethods_isCroppingSupported
(JNIEnv *, jclass, jlong streamHandle)
{
return (oniStreamIsPropertySupported((OniStreamHandle)streamHandle, STREAM_PROPERTY_CROPPING) == TRUE);
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_resetCropping
(JNIEnv *, jclass, jlong streamHandle)
{
OniCropping cropping;
cropping.enabled = FALSE;
return oniStreamSetProperty((OniStreamHandle)streamHandle, STREAM_PROPERTY_CROPPING, &cropping, sizeof(cropping));
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_getVideoMode
(JNIEnv *env, jclass, jlong streamHandle, jobject videoModeArgOutObj)
{
jclass videoModeCls = env->FindClass("org/openni/VideoMode");
jmethodID videoModeCtor = env->GetMethodID(videoModeCls, "<init>", "(IIII)V");
OniVideoMode videoMode;
int size = sizeof(OniVideoMode);
jint status = oniStreamGetProperty((OniStreamHandle)streamHandle, STREAM_PROPERTY_VIDEO_MODE, &videoMode, &size);
jobject videoModeObj = env->NewObject(videoModeCls, videoModeCtor, videoMode.resolutionX,
videoMode.resolutionY, videoMode.fps, videoMode.pixelFormat);
SetOutArgVideoModeValue(env, videoModeArgOutObj, videoModeObj);
return status;
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_setVideoMode
(JNIEnv *, jclass, jlong streamHandle, jint resX, jint resY, jint fps, jint pixelFormat)
{
OniVideoMode videoMode;
int size = sizeof(OniVideoMode);
videoMode.resolutionX = resX;
videoMode.resolutionY = resY;
videoMode.fps = fps;
videoMode.pixelFormat = (OniPixelFormat)pixelFormat;
return oniStreamSetProperty((OniStreamHandle)streamHandle, STREAM_PROPERTY_VIDEO_MODE, &videoMode, size);
}
JNIEXPORT jobject JNICALL Java_org_openni_NativeMethods_oniStreamGetSensorInfo
(JNIEnv *env, jclass, jlong streamHandle)
{
jclass arrayListCls = (*env).FindClass("java/util/ArrayList");
jobject vectorObj = (*env).NewObject(arrayListCls, (*env).GetMethodID(arrayListCls, "<init>", "()V"));
jclass videoModeCls = (*env).FindClass("org/openni/VideoMode");
jmethodID videoModeCtor = env->GetMethodID(videoModeCls, "<init>", "(IIII)V");
const OniSensorInfo* sensorInfo = oniStreamGetSensorInfo((OniStreamHandle)streamHandle);
int i = 0;
while (i < sensorInfo->numSupportedVideoModes)
{
OniVideoMode& videoMode = sensorInfo->pSupportedVideoModes[i];
jobject videoModeObj = env->NewObject(videoModeCls, videoModeCtor, videoMode.resolutionX,
videoMode.resolutionY, videoMode.fps, (int)videoMode.pixelFormat);
(*env).CallBooleanMethod(vectorObj, (*env).GetMethodID(arrayListCls, "add", "(Ljava/lang/Object;)Z"), videoModeObj);
i++;
}
jclass sensorInfoCls = (*env).FindClass("org/openni/SensorInfo");
jobject obj = (*env).NewObject(sensorInfoCls, (*env).GetMethodID(sensorInfoCls, "<init>", "(ILjava/util/List;)V"), sensorInfo->sensorType, vectorObj);
return obj;
}
JNIEXPORT jboolean JNICALL Java_org_openni_NativeMethods_hasSensor
(JNIEnv *, jclass, jlong deviceHandle, jint sensorType)
{
const OniSensorInfo* pInfo = oniDeviceGetSensorInfo((OniDeviceHandle)deviceHandle, (OniSensorType)sensorType);
if (pInfo == NULL)
{
return false;
}
return true;
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniStreamGetIntProperty
(JNIEnv *env, jclass, jlong streamHandle, jint property, jobject argOutObj)
{
int value = 0;
int size = sizeof(value);
int rc = oniStreamGetProperty((OniStreamHandle)streamHandle, property, &value, &size);
SetOutArgIntValue(env, argOutObj, value);
return rc;
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniStreamGetBoolProperty
(JNIEnv *env, jclass, jlong streamHandle, jint property, jobject argOutObj)
{
OniBool value = false;
int size = sizeof(value);
int rc = oniStreamGetProperty((OniStreamHandle)streamHandle, property, &value, &size);
SetOutArgBoolValue(env, argOutObj, value == TRUE);
return rc;
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniStreamGetFloatProperty
(JNIEnv *env, jclass, jlong streamHandle, jint property, jobject argOutObj)
{
float value = 0;
int size = sizeof(value);
int rc = oniStreamGetProperty((OniStreamHandle)streamHandle, property, &value, &size);
SetOutArgFloatValue(env, argOutObj, value);
return rc;
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniStreamSetProperty__JII
(JNIEnv *, jclass, jlong streamHandle, jint property, jint value)
{
int size = sizeof(value);
return oniStreamSetProperty((OniStreamHandle)streamHandle, property, &value, size);
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniStreamSetProperty__JIZ
(JNIEnv *, jclass, jlong streamHandle, jint property, jboolean value)
{
OniBool val = value?TRUE:FALSE;
int size = sizeof(val);
return oniStreamSetProperty((OniStreamHandle)streamHandle, property, &val, size);
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniStreamSetProperty__JIF
(JNIEnv *, jclass, jlong streamHandle, jint property, jfloat value)
{
int size = sizeof(value);
return oniStreamSetProperty((OniStreamHandle)streamHandle, property, &value, size);
}
JNIEXPORT jboolean JNICALL Java_org_openni_NativeMethods_oniStreamIsPropertySupported
(JNIEnv *, jclass, jlong streamHandle, jint property)
{
return (oniStreamIsPropertySupported((OniStreamHandle)streamHandle, property) == TRUE);
}
JNIEXPORT jobject JNICALL Java_org_openni_NativeMethods_oniDeviceGetSensorInfo
(JNIEnv *env, jclass, jlong deviceHandle, jint sensorType)
{
jclass arrayListCls = (*env).FindClass("java/util/ArrayList");
jobject vectorObj = (*env).NewObject(arrayListCls, (*env).GetMethodID(arrayListCls, "<init>", "()V"));
jclass videoModeCls = (*env).FindClass("org/openni/VideoMode");
jmethodID videoModeCtor = env->GetMethodID(videoModeCls, "<init>", "(IIII)V");
const OniSensorInfo* sensorInfo = oniDeviceGetSensorInfo((OniDeviceHandle)deviceHandle, (OniSensorType)sensorType);
if (sensorInfo == NULL)
return NULL;
int i = 0;
while (i < sensorInfo->numSupportedVideoModes)
{
OniVideoMode& videoMode = sensorInfo->pSupportedVideoModes[i];
jobject videoModeObj = env->NewObject(videoModeCls, videoModeCtor, videoMode.resolutionX,
videoMode.resolutionY, videoMode.fps, (int)videoMode.pixelFormat);
(*env).CallBooleanMethod(vectorObj, (*env).GetMethodID(arrayListCls, "add", "(Ljava/lang/Object;)Z"), videoModeObj);
i++;
}
jclass sensorInfoCls = (*env).FindClass("org/openni/SensorInfo");
jobject obj = (*env).NewObject(sensorInfoCls, (*env).GetMethodID(sensorInfoCls, "<init>", "(ILjava/util/List;)V"), sensorInfo->sensorType, vectorObj);
return obj;
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniDeviceEnableDepthColorSync
(JNIEnv *, jclass, jlong deviceHandle)
{
return oniDeviceEnableDepthColorSync((OniDeviceHandle)deviceHandle);
}
JNIEXPORT void JNICALL Java_org_openni_NativeMethods_oniDeviceDisableDepthColorSync
(JNIEnv *, jclass, jlong deviceHandle)
{
return oniDeviceDisableDepthColorSync((OniDeviceHandle)deviceHandle);
}
JNIEXPORT jboolean JNICALL Java_org_openni_NativeMethods_oniDeviceGetDepthColorSyncEnabled
(JNIEnv *, jclass, jlong deviceHandle)
{
return (jboolean)oniDeviceGetDepthColorSyncEnabled((OniDeviceHandle)deviceHandle);
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_seek
(JNIEnv *, jclass, jlong deviceHandle, jlong streamHandle, jint frameIndex)
{
OniSeek seek;
seek.frameIndex = frameIndex;
seek.stream = (OniStreamHandle)streamHandle;
return oniDeviceInvoke((OniDeviceHandle)deviceHandle, DEVICE_COMMAND_SEEK, &seek, sizeof(seek));
}
JNIEXPORT jboolean JNICALL Java_org_openni_NativeMethods_isImageRegistrationModeSupported
(JNIEnv *, jclass, jlong deviceHandle, jint mode)
{
return (oniDeviceIsImageRegistrationModeSupported((OniDeviceHandle)deviceHandle, (OniImageRegistrationMode)mode) == TRUE);
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_getImageRegistrationMode
(JNIEnv *env, jclass, jlong deviceHandle, jobject argOutObj)
{
ImageRegistrationMode mode;
int size = sizeof(mode);
int rc = oniDeviceGetProperty((OniDeviceHandle)deviceHandle, DEVICE_PROPERTY_IMAGE_REGISTRATION, &mode, &size);
SetOutArgIntValue(env, argOutObj, mode);
return rc;
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_setImageRegistrationMode
(JNIEnv *, jclass, jlong deviceHandle, jint mode)
{
return oniDeviceSetProperty((OniDeviceHandle)deviceHandle, DEVICE_PROPERTY_IMAGE_REGISTRATION, &mode, sizeof(mode));
}
JNIEXPORT jobject JNICALL Java_org_openni_NativeMethods_oniDeviceGetInfo
(JNIEnv *env, jclass, jlong deviceHandle)
{
OniDeviceInfo deviceInfo;
oniDeviceGetInfo((OniDeviceHandle)deviceHandle, &deviceInfo);
jobject nameObj = env->NewStringUTF(deviceInfo.name);
jobject uriObj = env->NewStringUTF(deviceInfo.uri);
jobject vendorObj = env->NewStringUTF(deviceInfo.vendor);
jclass deviceInfoCls = env->FindClass("org/openni/DeviceInfo");
return (*env).NewObject(deviceInfoCls, (*env).GetMethodID(deviceInfoCls, "<init>", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;II)V"),
uriObj, vendorObj, nameObj, deviceInfo.usbVendorId, deviceInfo.usbProductId);
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniRecorderStart
(JNIEnv *, jclass, jlong recorderHandle)
{
return oniRecorderStart((OniRecorderHandle)recorderHandle);
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniRecorderDestroy
(JNIEnv *, jclass, jlong recorderHandle)
{
return oniRecorderDestroy((OniRecorderHandle*)&recorderHandle);
}
JNIEXPORT void JNICALL Java_org_openni_NativeMethods_oniRecorderStop
(JNIEnv *, jclass, jlong recorderHandle)
{
oniRecorderStop((OniRecorderHandle)recorderHandle);
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniRecorderAttachStream
(JNIEnv *, jclass, jlong recorderHandle, jlong streamHadle, jboolean allowLossy)
{
return oniRecorderAttachStream((OniRecorderHandle)recorderHandle, (OniStreamHandle)streamHadle, allowLossy);
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniDeviceGetIntProperty
(JNIEnv *env , jclass, jlong deviceHandle, jint propery, jobject argOutObj)
{
int value;
int size = sizeof(value);
int rc = oniDeviceGetProperty((OniDeviceHandle)deviceHandle, propery, &value, &size);
SetOutArgIntValue(env, argOutObj, value);
return rc;
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniDeviceGetBoolProperty
(JNIEnv *env , jclass, jlong deviceHandle, jint propery, jobject argOutObj)
{
OniBool value;
int size = sizeof(value);
int rc = oniDeviceGetProperty((OniDeviceHandle)deviceHandle, propery, &value, &size);
SetOutArgBoolValue(env, argOutObj, (value==TRUE)?JNI_TRUE:JNI_FALSE);
return rc;
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniDeviceGetFloatProperty
(JNIEnv *env , jclass, jlong deviceHandle, jint propery, jobject argOutObj)
{
float value;
int size = sizeof(float);
int rc = oniDeviceGetProperty((OniDeviceHandle)deviceHandle, propery, &value, &size);
SetOutArgFloatValue(env, argOutObj, value);
return rc;
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniDeviceSetProperty__JII
(JNIEnv *, jclass, jlong deviceHandle, jint property, jint value)
{
return oniDeviceSetProperty((OniDeviceHandle)deviceHandle, property, &value, sizeof(value));
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniDeviceSetProperty__JIZ
(JNIEnv *, jclass, jlong deviceHandle, jint property, jboolean value)
{
OniBool oniValue = (value == JNI_TRUE)?TRUE:FALSE;
return oniDeviceSetProperty((OniDeviceHandle)deviceHandle, property, &oniValue, sizeof(oniValue));
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniDeviceSetProperty__JIF
(JNIEnv *, jclass, jlong deviceHandle, jint property, float value)
{
return oniDeviceSetProperty((OniDeviceHandle)deviceHandle, property, &value, sizeof(value));
}
JNIEXPORT jboolean JNICALL Java_org_openni_NativeMethods_oniDeviceIsPropertySupported
(JNIEnv *, jclass, jlong deviceHandle, jint property)
{
return (oniDeviceIsPropertySupported((OniDeviceHandle)deviceHandle, property) == TRUE);
}
JNIEXPORT jboolean JNICALL Java_org_openni_NativeMethods_oniDeviceIsCommandSupported
(JNIEnv *, jclass, jlong deviceHandle, jint command)
{
return (oniDeviceIsCommandSupported((OniDeviceHandle)deviceHandle, command) == TRUE);
}
static void ONI_CALLBACK_TYPE deviceConnectedCallback(const OniDeviceInfo* pInfo, void*)
{
JNIEnvSupplier suplier;
JNIEnv *env = suplier.GetEnv();
jmethodID methodID = env->GetStaticMethodID(g_openNIClass, "deviceConnected", "(Lorg/openni/DeviceInfo;)V");
jobject nameObj = env->NewStringUTF(pInfo->name);
jobject uriObj = env->NewStringUTF(pInfo->uri);
jobject vendorObj = env->NewStringUTF(pInfo->vendor);
jobject deviceObj = (*env).NewObject(g_deviceInfoClass, (*env).GetMethodID(g_deviceInfoClass, "<init>", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;II)V"),
uriObj, vendorObj, nameObj, pInfo->usbVendorId, pInfo->usbProductId);
env->CallStaticVoidMethod(g_openNIClass, methodID, deviceObj);
}
static void ONI_CALLBACK_TYPE deviceDisconnectedCallback(const OniDeviceInfo* pInfo, void*)
{
JNIEnvSupplier suplier;
JNIEnv *env = suplier.GetEnv();
jmethodID methodID = env->GetStaticMethodID(g_openNIClass, "deviceDisconnected", "(Lorg/openni/DeviceInfo;)V");
jobject nameObj = env->NewStringUTF(pInfo->name);
jobject uriObj = env->NewStringUTF(pInfo->uri);
jobject vendorObj = env->NewStringUTF(pInfo->vendor);
jobject deviceObj = (*env).NewObject(g_deviceInfoClass, (*env).GetMethodID(g_deviceInfoClass, "<init>", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;II)V"),
uriObj, vendorObj, nameObj, pInfo->usbVendorId, pInfo->usbProductId);
env->CallStaticVoidMethod(g_openNIClass, methodID, deviceObj);
}
static void ONI_CALLBACK_TYPE deviceStateChangedCallback(const OniDeviceInfo* pInfo, OniDeviceState state, void*)
{
JNIEnvSupplier suplier;
JNIEnv *env = suplier.GetEnv();
jmethodID methodID = env->GetStaticMethodID(g_openNIClass, "deviceStateChanged", "(Lorg/openni/DeviceInfo;I)V");
jobject nameObj = env->NewStringUTF(pInfo->name);
jobject uriObj = env->NewStringUTF(pInfo->uri);
jobject vendorObj = env->NewStringUTF(pInfo->vendor);
jobject deviceObj = (*env).NewObject(g_deviceInfoClass, (*env).GetMethodID(g_deviceInfoClass, "<init>", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;II)V"),
uriObj, vendorObj, nameObj, pInfo->usbVendorId, pInfo->usbProductId);
env->CallStaticVoidMethod(g_openNIClass, methodID, deviceObj, state);
}
static OniCallbackHandle callbackHandle = 0;
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniInitialize
(JNIEnv *env, jclass)
{
int status = oniInitialize(ONI_API_VERSION);
if (status == ONI_STATUS_OK)
{
OniDeviceCallbacks callbacks;
callbacks.deviceConnected = deviceConnectedCallback;
callbacks.deviceDisconnected = deviceDisconnectedCallback;
callbacks.deviceStateChanged = deviceStateChangedCallback;
status = oniRegisterDeviceCallbacks(&callbacks, env, &callbackHandle);
}
return status;
}
JNIEXPORT void JNICALL Java_org_openni_NativeMethods_oniShutdown
(JNIEnv *, jclass)
{
if (callbackHandle != 0)
oniUnregisterDeviceCallbacks(callbackHandle);
return oniShutdown();
}
JNIEXPORT jobject JNICALL Java_org_openni_NativeMethods_oniGetVersion
(JNIEnv *env , jclass)
{
OniVersion version = oniGetVersion();
jclass versionCls = env->FindClass("org/openni/Version");
return (*env).NewObject(versionCls, (*env).GetMethodID(versionCls, "<init>", "(IIII)V"),
version.major, version.minor, version.maintenance, version.build);
}
JNIEXPORT jstring JNICALL Java_org_openni_NativeMethods_oniGetExtendedError
(JNIEnv *env , jclass)
{
return env->NewStringUTF(oniGetExtendedError());
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniGetDeviceList
(JNIEnv *env, jclass, jobject deviceListObj)
{
OniDeviceInfo* m_pDeviceInfos;
int m_deviceInfoCount;
jint status = oniGetDeviceList(&m_pDeviceInfos, &m_deviceInfoCount);
if (status == 0)
{
for (int i = 0; i < m_deviceInfoCount; i++)
{
jobject nameObj = env->NewStringUTF(m_pDeviceInfos[i].name);
jobject uriObj = env->NewStringUTF(m_pDeviceInfos[i].uri);
jobject vendorObj = env->NewStringUTF(m_pDeviceInfos[i].vendor);
jclass deviceInfoCls = env->FindClass("org/openni/DeviceInfo");
jobject deviceInfObj = (*env).NewObject(deviceInfoCls, (*env).GetMethodID(deviceInfoCls, "<init>", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;II)V"),
uriObj, vendorObj, nameObj, m_pDeviceInfos[i].usbVendorId, m_pDeviceInfos[i].usbProductId);
jclass vectorCls = (*env).FindClass("java/util/List");
jmethodID methodId = (*env).GetMethodID(vectorCls, "add", "(Ljava/lang/Object;)Z");
(*env).CallBooleanMethod(deviceListObj, methodId, deviceInfObj);
}
}
return status;
}
JNIEXPORT jboolean JNICALL Java_org_openni_NativeMethods_oniWaitForAnyStream
(JNIEnv *env, jclass, jlongArray streamsArray, jobject outArgObj, jint timeout)
{
jlong *streams = env->GetLongArrayElements(streamsArray, JNI_FALSE);
int size = env->GetArrayLength(streamsArray);
int id = 0;
int rc = oniWaitForAnyStream((OniStreamHandle*)streams, size, &id, timeout);
env->ReleaseLongArrayElements(streamsArray, streams, JNI_ABORT);
SetOutArgIntValue(env, outArgObj, id);
return rc == ONI_STATUS_OK;
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniCoordinateConverterWorldToDepth
(JNIEnv *env, jclass, jlong streamHandle, jfloat worldX, jfloat worldY, jfloat worldZ, jobject depthXOutArg, jobject depthYOutArg, jobject depthZOutArg)
{
float x,y,z;
int status = oniCoordinateConverterWorldToDepth((OniStreamHandle)streamHandle, worldX, worldY, worldZ, &x, &y, &z);
SetOutArgFloatValue(env, depthXOutArg, x);
SetOutArgFloatValue(env, depthYOutArg, y);
SetOutArgFloatValue(env, depthZOutArg, z);
return status;
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniCoordinateConverterDepthToWorld
(JNIEnv *env, jclass, jlong streamHandle, jfloat depthX, jfloat depthY, jfloat depthZ, jobject colorXOutArg, jobject colorYOutArg, jobject colorZOutArg)
{
float x,y,z;
int status = oniCoordinateConverterDepthToWorld((OniStreamHandle)streamHandle, depthX, depthY, depthZ, &x, &y, &z);
SetOutArgFloatValue(env, colorXOutArg, x);
SetOutArgFloatValue(env, colorYOutArg, y);
SetOutArgFloatValue(env, colorZOutArg, z);
return status;
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniCoordinateConverterDepthToColor
(JNIEnv *env, jclass, jlong depthHandle, jlong colorHandle, jint depthX, jint depthY, jshort depthZ, jobject colorXOutArg, jobject colorYOutArg)
{
int x,y;
int status = oniCoordinateConverterDepthToColor((OniStreamHandle)depthHandle, (OniStreamHandle)colorHandle, depthX, depthY, depthZ, &x, &y);
SetOutArgIntValue(env, colorXOutArg, x);
SetOutArgIntValue(env, colorYOutArg, y);
return status;
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniCreateRecorder
(JNIEnv *env, jclass, jstring filename, jobject recorder)
{
OniRecorderHandle handle;
jclass recorderCls = env->FindClass("org/openni/Recorder");
const char * str = env->GetStringUTFChars(filename, JNI_FALSE);
int status = oniCreateRecorder(str, &handle);
jfieldID fieldID = env->GetFieldID(recorderCls, "mRecorderHandle", "J");
env->SetLongField(recorder, fieldID, (long)handle);
return status;
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniDeviceOpen__Ljava_lang_String_2Lorg_openni_Device_2
(JNIEnv *env, jclass, jstring uriStrObj, jobject device)
{
OniDeviceHandle handle;
const char * str = env->GetStringUTFChars(uriStrObj, JNI_FALSE);
int status = oniDeviceOpen(str, &handle);
jclass deviceCls = env->FindClass("org/openni/Device");
jfieldID fieldID = env->GetFieldID(deviceCls, "mDeviceHandle", "J");
env->SetLongField(device, fieldID, (long)handle);
return status;
}
static const char* ANY_DEVICE = NULL;
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniDeviceOpen__Lorg_openni_Device_2
(JNIEnv *env, jclass, jobject device)
{
OniDeviceHandle handle;
int status = oniDeviceOpen(ANY_DEVICE, &handle);
jclass deviceCls = env->FindClass("org/openni/Device");
jfieldID fieldID = env->GetFieldID(deviceCls, "mDeviceHandle", "J");
env->SetLongField(device, fieldID, (long)handle);
return status;
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniDeviceClose
(JNIEnv *, jclass, jlong deviceHandle)
{
return oniDeviceClose((OniDeviceHandle)deviceHandle);
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniSetLogOutputFolder
(JNIEnv * env, jclass, jstring path)
{
const char * str = env->GetStringUTFChars(path, JNI_FALSE);
return oniSetLogOutputFolder(str);
}
JNIEXPORT jstring JNICALL Java_org_openni_NativeMethods_oniGetLogFileName
(JNIEnv *env, jclass)
{
XnChar fileName[XN_FILE_MAX_PATH];
oniGetLogFileName(fileName, sizeof(fileName));
return env->NewStringUTF(fileName);
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniSetLogMinSeverity
(JNIEnv *, jclass, jint minSeverity)
{
return oniSetLogMinSeverity(minSeverity);
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniSetLogConsoleOutput
(JNIEnv *, jclass, jboolean enabled)
{
return oniSetLogConsoleOutput(enabled);
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniSetLogFileOutput
(JNIEnv *, jclass, jboolean enabled)
{
return oniSetLogFileOutput(enabled);
}
JNIEXPORT jint JNICALL Java_org_openni_NativeMethods_oniSetLogAndroidOutput
(JNIEnv *, jclass, jboolean enabled)
{
(void)(enabled);
#ifdef ANDROID
return oniSetLogAndroidOutput(enabled);
#else
return ONI_STATUS_NOT_SUPPORTED;
#endif
}
| 40.095125
| 169
| 0.742408
|
BEIWG
|
788827b84d5761fad86b03e6121a2df93ead4f74
| 1,557
|
hh
|
C++
|
src/event_manager.hh
|
nojhan/kakoune
|
c8156429c4685189e0a6b7bd0f273dc64432db2c
|
[
"Unlicense"
] | null | null | null |
src/event_manager.hh
|
nojhan/kakoune
|
c8156429c4685189e0a6b7bd0f273dc64432db2c
|
[
"Unlicense"
] | null | null | null |
src/event_manager.hh
|
nojhan/kakoune
|
c8156429c4685189e0a6b7bd0f273dc64432db2c
|
[
"Unlicense"
] | null | null | null |
#ifndef event_manager_hh_INCLUDED
#define event_manager_hh_INCLUDED
#include "utils.hh"
#include <chrono>
#include <unordered_set>
namespace Kakoune
{
class FDWatcher
{
public:
using Callback = std::function<void (FDWatcher& watcher)>;
FDWatcher(int fd, Callback callback);
~FDWatcher();
int fd() const { return m_fd; }
void run() { m_callback(*this); }
private:
int m_fd;
Callback m_callback;
};
using Clock = std::chrono::steady_clock;
using TimePoint = Clock::time_point;
class Timer
{
public:
using Callback = std::function<void (Timer& timer)>;
Timer(TimePoint date, Callback callback);
~Timer();
TimePoint next_date() const { return m_date; }
void set_next_date(TimePoint date) { m_date = date; }
void run();
private:
TimePoint m_date;
Callback m_callback;
};
// The EventManager provides an interface to file descriptor
// based event handling.
//
// The program main loop should call handle_next_events()
// until it's time to quit.
class EventManager : public Singleton<EventManager>
{
public:
EventManager();
~EventManager();
void handle_next_events();
// force the watchers associated with fd to be executed
// on next handle_next_events call.
void force_signal(int fd);
private:
friend class FDWatcher;
friend class Timer;
std::unordered_set<FDWatcher*> m_fd_watchers;
std::unordered_set<Timer*> m_timers;
std::vector<int> m_forced_fd;
TimePoint m_last;
};
}
#endif // event_manager_hh_INCLUDED
| 20.220779
| 62
| 0.69043
|
nojhan
|
78895d9f05d60511d555be5cfd10e4501ee3d249
| 1,460
|
cpp
|
C++
|
src/logic/axi4/stream/reset_sequence.cpp
|
trosenkranz/logic
|
8bcb5ecbc2df08f32215053b34ddb2bf220f41aa
|
[
"Apache-2.0"
] | 209
|
2017-11-22T14:52:15.000Z
|
2022-03-23T21:44:58.000Z
|
src/logic/axi4/stream/reset_sequence.cpp
|
trosenkranz/logic
|
8bcb5ecbc2df08f32215053b34ddb2bf220f41aa
|
[
"Apache-2.0"
] | 2
|
2018-02-26T09:02:15.000Z
|
2020-01-14T10:19:59.000Z
|
src/logic/axi4/stream/reset_sequence.cpp
|
trosenkranz/logic
|
8bcb5ecbc2df08f32215053b34ddb2bf220f41aa
|
[
"Apache-2.0"
] | 53
|
2018-01-24T07:11:26.000Z
|
2022-03-02T02:14:30.000Z
|
/* Copyright 2018 Tymoteusz Blazejczyk
*
* 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 "logic/axi4/stream/reset_sequence.hpp"
using logic::axi4::stream::reset_sequence;
reset_sequence::reset_sequence() :
reset_sequence{"reset_sequence"}
{ }
reset_sequence::reset_sequence(const std::string& name) :
uvm::uvm_sequence<reset_sequence_item>{name},
items{}
{ }
reset_sequence::~reset_sequence() = default;
void reset_sequence::pre_body() {
if (starting_phase != nullptr) {
starting_phase->raise_objection(this);
}
}
void reset_sequence::body() {
UVM_INFO(get_name(), "Starting reset sequence", uvm::UVM_FULL);
for (auto& item : items) {
start_item(&item);
finish_item(&item);
}
UVM_INFO(get_name(), "Finishing reset sequence", uvm::UVM_FULL);
}
void reset_sequence::post_body() {
if (starting_phase != nullptr) {
starting_phase->drop_objection(this);
}
}
| 27.54717
| 75
| 0.704795
|
trosenkranz
|
78926939b2197b4e9886bdd949e2f89077f2d58e
| 3,023
|
hpp
|
C++
|
libs/mockturtle/io/write_dimacs.hpp
|
wjyoumans/staq
|
d5227bd4651ce64ba277aab5061e3a132be853bb
|
[
"MIT"
] | 96
|
2019-12-11T10:18:10.000Z
|
2022-03-27T20:16:33.000Z
|
libs/mockturtle/io/write_dimacs.hpp
|
wjyoumans/staq
|
d5227bd4651ce64ba277aab5061e3a132be853bb
|
[
"MIT"
] | 43
|
2020-01-08T00:59:07.000Z
|
2022-03-28T21:35:59.000Z
|
libs/mockturtle/io/write_dimacs.hpp
|
wjyoumans/staq
|
d5227bd4651ce64ba277aab5061e3a132be853bb
|
[
"MIT"
] | 21
|
2019-12-15T01:40:48.000Z
|
2021-12-31T05:27:34.000Z
|
/* mockturtle: C++ logic network library
* Copyright (C) 2018-2019 EPFL EPFL
*
* 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.
*/
/*!
\file write_dimacs.hpp
\brief Write networks CNF encoding to DIMACS format
\author Mathias Soeken
*/
#pragma once
#include <cstdint>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <fmt/format.h>
#include "../traits.hpp"
#include "../algorithms/cnf.hpp"
namespace mockturtle {
/*! \brief Writes network into CNF DIMACS format
*
* It also adds unit clauses for the outputs. Therefore a satisfying solution
* is one that makes all outputs 1.
*
* \param ntk Logic network
* \param out Output stream
*/
template <class Ntk>
void write_dimacs(Ntk const& ntk, std::ostream& out = std::cout) {
std::stringstream clauses;
uint32_t num_clauses = 0u;
const auto lits =
generate_cnf(ntk, [&](std::vector<uint32_t> const& clause) {
for (auto lit : clause) {
const auto var = (lit / 2) + 1;
const auto pol = lit % 2;
clauses << fmt::format("{}{} ", pol ? "-" : "", var);
}
clauses << fmt::format("0\n");
++num_clauses;
});
for (auto lit : lits) {
const auto var = (lit / 2) + 1;
const auto pol = lit % 2;
clauses << fmt::format("{}{} 0\n", pol ? "-" : "", var);
++num_clauses;
}
out << fmt::format("p cnf {} {}\n{}", ntk.size(), num_clauses,
clauses.str());
}
/*! \brief Writes network into CNF DIMACS format
*
* It also adds unit clauses for the outputs. Therefore a satisfying solution
* is one that makes all outputs 1.
*
* \param ntk Logic network
* \param filename Filename
*/
template <class Ntk>
void write_dimacs(Ntk const& ntk, std::string const& filename) {
std::ofstream os(filename.c_str(), std::ofstream::out);
write_dimacs(ntk, os);
os.close();
}
} /* namespace mockturtle */
| 30.535354
| 78
| 0.656302
|
wjyoumans
|
78939ce1945f307b29f0c9dd3dbcc2e0c3649e78
| 1,347
|
cpp
|
C++
|
src/context.cpp
|
programmerjake/my-compiler
|
fa70f13e059b44674042cedf1bbf2d9b01132793
|
[
"Zlib"
] | 7
|
2017-11-19T02:42:30.000Z
|
2022-02-13T08:48:31.000Z
|
src/context.cpp
|
programmerjake/my-compiler
|
fa70f13e059b44674042cedf1bbf2d9b01132793
|
[
"Zlib"
] | null | null | null |
src/context.cpp
|
programmerjake/my-compiler
|
fa70f13e059b44674042cedf1bbf2d9b01132793
|
[
"Zlib"
] | null | null | null |
/* Copyright (c) 2015 Jacob R. Lifshay
*
* 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 acknowledgement 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 "context.h"
#include "types/type.h"
std::shared_ptr<TypeNode> CompilerContext::constructTypeNodeHelper(std::shared_ptr<TypeNode> retval)
{
std::size_t theHash = retval->getHash();
auto range = types.equal_range(theHash);
for(auto i = range.first; i != range.second; ++i)
{
if(*retval == *std::get<1>(*i))
return std::get<1>(*i);
}
types.emplace(theHash, retval);
return retval;
}
| 38.485714
| 100
| 0.710468
|
programmerjake
|
7895788e070824a3bf9fe1b3145af9859d2209a9
| 2,351
|
hpp
|
C++
|
include/cobalt/platform.hpp
|
mzhirnov/cool
|
9c360ca8bfc127dffae6264675d9973fd2c6fd6d
|
[
"MIT"
] | 2
|
2020-03-23T19:12:14.000Z
|
2020-08-03T13:29:38.000Z
|
include/cobalt/platform.hpp
|
mzhirnov/cool
|
9c360ca8bfc127dffae6264675d9973fd2c6fd6d
|
[
"MIT"
] | null | null | null |
include/cobalt/platform.hpp
|
mzhirnov/cool
|
9c360ca8bfc127dffae6264675d9973fd2c6fd6d
|
[
"MIT"
] | null | null | null |
#ifndef COBALT_PLATFORM_HPP_INCLUDED
#define COBALT_PLATFORM_HPP_INCLUDED
#pragma once
#include <boost/predef.h>
#define $on(...) __VA_ARGS__
#define $off(...)
////////////////////////////////////////////////////////////////////////////////
// Windows
#if BOOST_OS_WINDOWS
#include <winapifamily.h>
#define $windows $on
#if defined(WINAPI_FAMILY) && WINAPI_FAMILY == WINAPI_PARTITION_APP
#define $windows_app $on
#endif
#endif // BOOST_OS_WINDOWS
#ifdef $windows
#define $not_windows $off
#else
#define $windows $off
#define $not_windows $on
#endif // $windows
#ifdef $windows_app
#define $not_windows_app $off
#else
#define $windows_app $off
#define $not_windows_app $on
#endif // $windows_app
////////////////////////////////////////////////////////////////////////////////
// iOS
#if BOOST_OS_IOS
#include <TargetConditionals.h>
#define $ios $on
#if defined(TARGET_IPHONE_SIMULATOR) && TARGET_IPHONE_SIMULATOR
#define $ios_simulator $on
#endif
#endif // BOOST_OS_IOS
#ifdef $ios
#define $not_ios $off
#else
#define $ios $off
#define $not_ios $on
#endif // $ios
#ifdef $ios_simulator
#define $not_ios_simulator $off
#else
#define $ios_simulator $off
#define $not_ios_simulator $on
#endif // $ios_simulator
////////////////////////////////////////////////////////////////////////////////
// macOS
#if BOOST_OS_MACOS
#define $macos $on
#endif // BOOST_OS_MACOS
#ifdef $macos
#define $not_macos $off
#else
#define $macos $off
#define $not_macos $on
#endif // $macos
////////////////////////////////////////////////////////////////////////////////
// Android
#if BOOST_OS_ANDROID
#define $android $on
#endif // BOOST_OS_ANDROID
#ifdef $android
#define $not_android $off
#else
#define $android $off
#define $not_android $on
#endif // $android
////////////////////////////////////////////////////////////////////////////////
// Linux
#if BOOST_OS_LINUX
#define $linux $on
#endif // BOOST_OS_LINUX
#ifdef $linux
#define $not_linux $off
#else
#define $linux $off
#define $not_linux $on
#endif // $linux
////////////////////////////////////////////////////////////////////////////////
// Desktop | Mobile
#if BOOST_OS_WINDOWS || BOOST_OS_MACOS || BOOST_OS_LINUX
#define $desktop $on
#endif //
#ifdef $desktop
#define $mobile $off
#else
#define $desktop $off
#define $mobile $on
#endif // $linux
#endif // COBALT_PLATFORM_HPP_INCLUDED
| 19.923729
| 80
| 0.586134
|
mzhirnov
|
78973096181449d12b341ef6923aba48905b0248
| 42,528
|
cxx
|
C++
|
Utilities/Cosmo/CosmoHaloFinderP.cxx
|
SCS-B3C/VTK5.6
|
d4afb224f638c1f7e847b0cd3195ea8a977bb602
|
[
"BSD-3-Clause"
] | 2
|
2015-07-11T13:30:23.000Z
|
2017-12-19T05:23:38.000Z
|
Utilities/Cosmo/CosmoHaloFinderP.cxx
|
SCS-B3C/VTK5.6
|
d4afb224f638c1f7e847b0cd3195ea8a977bb602
|
[
"BSD-3-Clause"
] | null | null | null |
Utilities/Cosmo/CosmoHaloFinderP.cxx
|
SCS-B3C/VTK5.6
|
d4afb224f638c1f7e847b0cd3195ea8a977bb602
|
[
"BSD-3-Clause"
] | null | null | null |
/*=========================================================================
Copyright (c) 2007, Los Alamos National Security, LLC
All rights reserved.
Copyright 2007. Los Alamos National Security, LLC.
This software was produced under U.S. Government contract DE-AC52-06NA25396
for Los Alamos National Laboratory (LANL), which is operated by
Los Alamos National Security, LLC for the U.S. Department of Energy.
The U.S. Government has rights to use, reproduce, and distribute this software.
NEITHER THE GOVERNMENT NOR LOS ALAMOS NATIONAL SECURITY, LLC MAKES ANY WARRANTY,
EXPRESS OR IMPLIED, OR ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE.
If software is modified to produce derivative works, such modified software
should be clearly marked, so as not to confuse it with the version available
from LANL.
Additionally, 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 Los Alamos National Security, LLC, Los Alamos National
Laboratory, LANL, the U.S. Government, nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY LOS ALAMOS NATIONAL SECURITY, LLC 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 LOS ALAMOS NATIONAL SECURITY, LLC OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
=========================================================================*/
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <set>
#include <math.h>
#include "Partition.h"
#include "CosmoHaloFinderP.h"
using namespace std;
/////////////////////////////////////////////////////////////////////////
//
// Parallel manager for serial CosmoHaloFinder
// Particle data space is partitioned for the number of processors
// which currently is a factor of two but is easily extended. Particles
// are read in from files where each processor reads one file into a buffer,
// extracts the particles which really belong on the processor (ALIVE) and
// those in a buffer region around the edge (DEAD). The buffer is then
// passed round robin to every other processor so that all particles are
// examined by all processors. All dead particles are tagged with the
// neighbor zone (26 neighbors in 3D) so that later halos can be associated
// with zones.
//
// The serial halo finder is called on each processor and returns enough
// information so that it can be determined if a halo is completely ALIVE,
// completely DEAD, or mixed. A mixed halo that is shared between on two
// processors is kept by the processor that contains it in one of its
// high plane neighbors, and is given up if contained in a low plane neighbor.
//
// Mixed halos that cross more than two processors are bundled up and sent
// to the MASTER processor which decides the processor that should own it.
//
/////////////////////////////////////////////////////////////////////////
CosmoHaloFinderP::CosmoHaloFinderP() : haloData(NULL), haloList(NULL), haloStart(NULL), haloSize(NULL)
{
// Get the number of processors and rank of this processor
this->numProc = Partition::getNumProc();
this->myProc = Partition::getMyProc();
// Get the number of processors in each dimension
Partition::getDecompSize(this->layoutSize);
// Get my position within the Cartesian topology
Partition::getMyPosition(this->layoutPos);
// Get the neighbors of this processor
Partition::getNeighbors(this->neighbor);
// For each neighbor zone, how many dead particles does it contain to start
// and how many dead halos does it contain after the serial halo finder
// For analysis but not necessary to run the code
//
for (int n = 0; n < NUM_OF_NEIGHBORS; n++) {
this->deadParticle[n] = 0;
this->deadHalo[n] = 0;
}
}
CosmoHaloFinderP::~CosmoHaloFinderP()
{
for (unsigned int i = 0; i < this->myMixedHalos.size(); i++)
delete this->myMixedHalos[i];
if(this->haloList)
{
delete [] this->haloList;
}
if(this->haloStart)
{
delete [] this->haloStart;
}
if(this->haloSize)
{
delete [] this->haloSize;
}
if(this->haloData)
{
for (int dim = 0; dim < DIMENSION; dim++)
delete this->haloData[dim];
delete [] this->haloData;
}
}
/////////////////////////////////////////////////////////////////////////
//
// Set parameters for the serial halo finder
//
/////////////////////////////////////////////////////////////////////////
void CosmoHaloFinderP::setParameters(
const string& outName,
POSVEL_T _rL,
POSVEL_T _deadSz,
long _np,
int _pmin,
POSVEL_T _bb)
{
// Particles for this processor output to file
ostringstream oname, hname;
if (this->numProc == 1) {
oname << outName;
hname << outName;
} else {
oname << outName << "." << myProc;
hname << outName << ".halo." << myProc;
}
this->outFile = oname.str();
this->outHaloFile = hname.str();
// Halo finder parameters
this->np = _np;
this->pmin = _pmin;
this->bb = _bb;
this->boxSize = _rL;
this->deadSize = _deadSz;
// First version of this code distributed the dead particles on a processor
// by taking the x,y,z position and adding or subtracting boxSize in all
// combinations. This revised x,y,z was then normalized and added to the
// haloData array which was passed to each serial halo finder.
// This did not get the same answer as the standalone serial version which
// read the x,y,z and normalized without adding or subtracting boxSize first.
// Then when comparing distance the normalized "np" was used for subtraction.
// By doing things in this order some particles were placed slightly off,
// which was enough for particles to be included in halos where they should
// not have been. In this first version, since I had placed particles by
// subtracting first, I made "periodic" false figuring all particles were
// placed where they should go.
//
// In the second version I normalize the dead particles, even from wraparound,
// using the actual x,y,z. So when looking at a processor the alive particles
// will appear all together and the wraparound will properly be on the other
// side of the box. Combined with doing this is setting "periodic" to true
// so that the serial halo finder works as it does in the standalone case
// and the normalization and subtraction from np happens in the same order.
//
// Third version went back to the first version because we need
// contiguous locations coming out of the halo finder for the center finder
this->haloFinder.np = _np;
this->haloFinder.pmin = _pmin;
this->haloFinder.bb = _bb;
this->haloFinder.rL = _rL;
this->haloFinder.periodic = false;
this->haloFinder.textmode = "ascii";
// Serial halo finder wants normalized locations on a grid superimposed
// on the physical rL grid. Grid size is np and number of particles in
// the problem is np^3
this->normalizeFactor = (POSVEL_T)((1.0 * _np) / _rL);
#ifndef USE_VTK_COSMO
if (this->myProc == MASTER) {
cout << endl << "------------------------------------" << endl;
cout << "np: " << this->np << endl;
cout << "bb: " << this->bb << endl;
cout << "pmin: " << this->pmin << endl << endl;
}
#endif
}
/////////////////////////////////////////////////////////////////////////
//
// Set the particle vectors that have already been read and which
// contain only the alive particles for this processor
//
/////////////////////////////////////////////////////////////////////////
void CosmoHaloFinderP::setParticles(
vector<POSVEL_T>* xLoc,
vector<POSVEL_T>* yLoc,
vector<POSVEL_T>* zLoc,
vector<POSVEL_T>* xVel,
vector<POSVEL_T>* yVel,
vector<POSVEL_T>* zVel,
vector<POTENTIAL_T>* potential,
vector<ID_T>* id,
vector<MASK_T>* maskData,
vector<STATUS_T>* state)
{
this->particleCount = (long)xLoc->size();
// Extract the contiguous data block from a vector pointer
this->xx = &(*xLoc)[0];
this->yy = &(*yLoc)[0];
this->zz = &(*zLoc)[0];
this->vx = &(*xVel)[0];
this->vy = &(*yVel)[0];
this->vz = &(*zVel)[0];
this->pot = &(*potential)[0];
this->tag = &(*id)[0];
this->mask = &(*maskData)[0];
this->status = &(*state)[0];
}
/////////////////////////////////////////////////////////////////////////
//
// Execute the serial halo finder on the particles for this processor
// Both ALIVE and DEAD particles we collected and normalized into
// haloData which is in the form that the serial halo finder wants
//
/////////////////////////////////////////////////////////////////////////
void CosmoHaloFinderP::executeHaloFinder()
{
// Allocate data pointer which is sent to the serial halo finder
this->haloData = new POSVEL_T*[DIMENSION];
for (int dim = 0; dim < DIMENSION; dim++)
this->haloData[dim] = new POSVEL_T[this->particleCount];
// Fill it with normalized x,y,z of all particles on this processor
for (int p = 0; p < this->particleCount; p++) {
this->haloData[0][p] = this->xx[p] * this->normalizeFactor;
this->haloData[1][p] = this->yy[p] * this->normalizeFactor;
this->haloData[2][p] = this->zz[p] * this->normalizeFactor;
}
this->haloFinder.setParticleLocations(haloData);
this->haloFinder.setNumberOfParticles(this->particleCount);
this->haloFinder.setMyProc(this->myProc);
this->haloFinder.setOutFile(this->outFile);
#ifndef USE_VTK_COSMO
cout << "Rank " << setw(3) << this->myProc
<< " RUNNING SERIAL HALO FINDER on "
<< particleCount << " particles" << endl;
#endif
#ifndef USE_SERIAL_COSMO
MPI_Barrier(Partition::getComm());
#endif
if (this->particleCount > 0)
this->haloFinder.Finding();
#ifndef USE_SERIAL_COSMO
MPI_Barrier(Partition::getComm());
#endif
}
/////////////////////////////////////////////////////////////////////////
//
// At this point each serial halo finder ran and
// the particles handed to it included alive and dead. Get back the
// halo tag array and figure out the indices of the particles in each halo
// and translate that into absolute particle tags and note alive or dead
//
// After the serial halo finder has run the halo tag is the INDEX of the
// lowest particle in the halo on this processor. It is not the absolute
// particle tag id over the entire problem.
//
// Serial partindex i = 0 haloTag = 0 haloSize = 1
// Serial partindex i = 1 haloTag = 1 haloSize = 1
// Serial partindex i = 2 haloTag = 2 haloSize = 1
// Serial partindex i = 3 haloTag = 3 haloSize = 1
// Serial partindex i = 4 haloTag = 4 haloSize = 2
// Serial partindex i = 5 haloTag = 5 haloSize = 1
// Serial partindex i = 6 haloTag = 6 haloSize = 1616
// Serial partindex i = 7 haloTag = 7 haloSize = 1
// Serial partindex i = 8 haloTag = 8 haloSize = 2
// Serial partindex i = 9 haloTag = 9 haloSize = 1738
// Serial partindex i = 10 haloTag = 10 haloSize = 4
// Serial partindex i = 11 haloTag = 11 haloSize = 1
// Serial partindex i = 12 haloTag = 12 haloSize = 78
// Serial partindex i = 13 haloTag = 12 haloSize = 0
// Serial partindex i = 14 haloTag = 12 haloSize = 0
// Serial partindex i = 15 haloTag = 12 haloSize = 0
// Serial partindex i = 16 haloTag = 16 haloSize = 2
// Serial partindex i = 17 haloTag = 17 haloSize = 1
// Serial partindex i = 18 haloTag = 6 haloSize = 0
// Serial partindex i = 19 haloTag = 6 haloSize = 0
// Serial partindex i = 20 haloTag = 6 haloSize = 0
// Serial partindex i = 21 haloTag = 6 haloSize = 0
//
// Halo of size 1616 has the low particle tag of 6 and other members are
// 18,19,20,21 indicated by a tag of 6 and haloSize of 0
//
/////////////////////////////////////////////////////////////////////////
void CosmoHaloFinderP::collectHalos()
{
// Halo tag returned from the serial halo finder is actually the index
// of the particle on this processor. Must map to get to actual tag
// which is common information between all processors.
this->haloTag = haloFinder.getHaloTag();
// Record the halo size of each particle on this processor
this->haloSize = new int[this->particleCount];
this->haloAliveSize = new int[this->particleCount];
this->haloDeadSize = new int[this->particleCount];
// Create a list of particles in any halo by recording the index of the
// first particle and having that index give the index of the next particle
// Last particle index reports a -1
// List is built by iterating on the tags and storing in opposite order so
this->haloList = new int[this->particleCount];
this->haloStart = new int[this->particleCount];
for (int p = 0; p < this->particleCount; p++) {
this->haloList[p] = -1;
this->haloStart[p] = p;
this->haloSize[p] = 0;
this->haloAliveSize[p] = 0;
this->haloDeadSize[p] = 0;
}
// Build the chaining mesh of particles in all the halos and count particles
buildHaloStructure();
// Mixed halos are saved separately so that they can be merged
processMixedHalos();
delete [] this->haloAliveSize;
delete [] this->haloDeadSize;
}
/////////////////////////////////////////////////////////////////////////
//
// Examine every particle on this processor, both ALIVE and DEAD
// For that particle increment the count for the corresponding halo
// which is indicated by the lowest particle index in that halo
// Also build the haloList so that we can find all particles in any halo
//
/////////////////////////////////////////////////////////////////////////
void CosmoHaloFinderP::buildHaloStructure()
{
// Build the chaining mesh so that all particles in a halo can be found
// This will include even small halos which will be excluded later
for (int p = 0; p < this->particleCount; p++) {
// Chain backwards the halo particles
// haloStart is the index of the last particle in a single halo in haloList
// The value found in haloList is the index of the next particle
if (this->haloTag[p] != p) {
this->haloList[p] = haloStart[this->haloTag[p]];
this->haloStart[this->haloTag[p]] = p;
}
// Count particles in the halos
if (this->status[p] == ALIVE)
this->haloAliveSize[this->haloTag[p]]++;
else
this->haloDeadSize[this->haloTag[p]]++;
this->haloSize[this->haloTag[p]]++;
}
// Iterate over particles and create a CosmoHalo for halos with size > pmin
// only for the mixed halos, not for those completely alive or dead
this->numberOfAliveHalos = 0;
this->numberOfDeadHalos = 0;
this->numberOfMixedHalos = 0;
// Only the first particle id for a halo records the size
// Succeeding particles which are members of a halo have a size of 0
// Record the start index of any legal halo which will allow the
// following of the chaining mesh to identify all particles in a halo
this->numberOfHaloParticles = 0;
for (ID_T p = 0; p < this->particleCount; p++) {
if (this->haloSize[p] >= this->pmin) {
if (this->haloAliveSize[p] > 0 && this->haloDeadSize[p] == 0) {
this->numberOfAliveHalos++;
this->numberOfHaloParticles += this->haloAliveSize[p];
// Save start of legal alive halo for halo properties
this->halos.push_back(this->haloStart[p]);
this->haloCount.push_back(this->haloAliveSize[p]);
}
else if (this->haloDeadSize[p] > 0 && this->haloAliveSize[p] == 0) {
this->numberOfDeadHalos++;
}
else {
this->numberOfMixedHalos++;
CosmoHalo* halo = new CosmoHalo(p,
this->haloAliveSize[p], this->haloDeadSize[p]);
this->myMixedHalos.push_back(halo);
}
}
}
#ifndef USE_VTK_COSMO
#ifdef DEBUG
cout << "Rank " << this->myProc
<< " #alive halos = " << this->numberOfAliveHalos
<< " #dead halos = " << this->numberOfDeadHalos
<< " #mixed halos = " << this->numberOfMixedHalos << endl;
#endif
#endif
}
/////////////////////////////////////////////////////////////////////////
//
// Mixed halos (which cross several processors) have been collected
// By applying a high/low rule most mixed halos are assigned immediately
// to one processor or another. This requires extra processing so that
// it is known which neighbor processors share the halo.
//
/////////////////////////////////////////////////////////////////////////
void CosmoHaloFinderP::processMixedHalos()
{
// Iterate over all particles and add tags to large mixed halos
for (ID_T p = 0; p < this->particleCount; p++) {
// All particles in the same halo have the same haloTag
if (this->haloSize[this->haloTag[p]] >= pmin &&
this->haloAliveSize[this->haloTag[p]] > 0 &&
this->haloDeadSize[this->haloTag[p]] > 0) {
// Check all each mixed halo to see which this particle belongs to
for (unsigned int h = 0; h < this->myMixedHalos.size(); h++) {
// If the tag of the particle matches the halo ID it belongs
if (this->haloTag[p] == this->myMixedHalos[h]->getHaloID()) {
// Add the index to that mixed halo. Also record which neighbor
// the dead particle is associated with for merging
this->myMixedHalos[h]->addParticle(
p, this->tag[p], this->status[p]);
// For debugging only
if (this->status[p] > 0)
this->deadHalo[this->status[p]]++;
// Do some bookkeeping for the final output
// This processor should output all ALIVE particles, unless they
// are in a mixed halo that ends up being INVALID
// This processor should output none of the DEAD particles,
// unless they are in a mixed halo that ends up being VALID
// So since this particle is in a mixed halo set it to MIXED
// which is going to be one less than ALIVE. Later when we
// determine we have a VALID mixed, we'll add one to the status
// for every particle turning all into ALIVE
// Now when we output we only do the ALIVE particles
this->status[p] = MIXED;
}
}
}
}
// Iterate over the mixed halos that were just created checking to see if
// the halo is on the "high" side of the 3D data space or not
// If it is on the high side and is shared with one other processor, keep it
// If it is on the low side and is shared with one other processor, delete it
// Any remaining halos are shared with more than two processors and must
// be merged by having the MASTER node decide
//
for (unsigned int h = 0; h < this->myMixedHalos.size(); h++) {
int lowCount = 0;
int highCount = 0;
set<int>* neighbors = this->myMixedHalos[h]->getNeighbors();
set<int>::iterator iter;
set<int> haloNeighbor;
for (iter = neighbors->begin(); iter != neighbors->end(); ++iter) {
if ((*iter) == X1 || (*iter) == Y1 || (*iter) == Z1 ||
(*iter) == X1_Y1 || (*iter) == Y1_Z1 || (*iter) == Z1_X1 ||
(*iter) == X1_Y1_Z1) {
highCount++;
} else {
lowCount++;
}
// Neighbor zones are on what actual processors
haloNeighbor.insert(this->neighbor[(*iter)]);
}
// Halo is kept by this processor and is marked as VALID
// May be in multiple neighbor zones, but all the same processor neighbor
if (highCount > 0 && lowCount == 0 && haloNeighbor.size() == 1) {
this->numberOfAliveHalos++;
this->numberOfMixedHalos--;
this->myMixedHalos[h]->setValid(VALID);
int id = this->myMixedHalos[h]->getHaloID();
int newAliveParticles = this->myMixedHalos[h]->getAliveCount() +
this->myMixedHalos[h]->getDeadCount();
this->numberOfHaloParticles += newAliveParticles;
// Add this halo to valid halos on this processor for
// subsequent halo properties analysis
this->halos.push_back(this->haloStart[id]);
this->haloCount.push_back(newAliveParticles);
// Output trick - since the status of this particle was marked MIXED
// when it was added to the mixed CosmoHalo vector, and now it has
// been declared VALID, change it to ALIVE even if it was dead before
vector<ID_T>* particles = this->myMixedHalos[h]->getParticles();
vector<ID_T>::iterator iter2;
for (iter2 = particles->begin(); iter2 != particles->end(); ++iter2)
this->status[(*iter2)] = ALIVE;
}
// Halo will be kept by some other processor and is marked INVALID
// May be in multiple neighbor zones, but all the same processor neighbor
else if (highCount == 0 && lowCount > 0 && haloNeighbor.size() == 1) {
this->numberOfDeadHalos++;
this->numberOfMixedHalos--;
this->myMixedHalos[h]->setValid(INVALID);
}
// Remaining mixed halos must be examined by MASTER and stay UNMARKED
// Sort them on the tag field for easy comparison
else {
this->myMixedHalos[h]->setValid(UNMARKED);
this->myMixedHalos[h]->sortParticleTags();
}
}
// If only one processor is running there are no halos to merge
if (this->numProc == 1)
for (unsigned int h = 0; h < this->myMixedHalos.size(); h++)
this->myMixedHalos[h]->setValid(INVALID);
}
/////////////////////////////////////////////////////////////////////////
//
// Using the MASTER node merge all mixed halos so that only one processor
// takes credit for them.
//
// Each processor containing mixed halos that are UNMARKED sends:
// Rank
// Number of mixed halos to merge
// for each halo
// id
// number of alive (for debugging)
// number of dead (for debugging)
// first MERGE_COUNT particle ids (for merging)
//
/////////////////////////////////////////////////////////////////////////
void CosmoHaloFinderP::mergeHalos()
{
// What size integer buffer is needed to hold the largest halo data
int maxNumberOfMixed;
int numberOfMixed = (int)this->myMixedHalos.size();
#ifdef USE_SERIAL_COSMO
maxNumberOfMixed = numberOfMixed;
#else
MPI_Allreduce((void*) &numberOfMixed, (void*) &maxNumberOfMixed,
1, MPI_INT, MPI_MAX, Partition::getComm());
#endif
// If there are no halos to merge, return
if (maxNumberOfMixed == 0)
return;
// Everyone creates the buffer for maximum halos
// MASTER will receive into it, others will send from it
int haloBufSize = maxNumberOfMixed * MERGE_COUNT * 2;
ID_T* haloBuffer = new ID_T[haloBufSize];
// MASTER moves its own mixed halos to mixed halo vector (change index to tag)
// then gets messages from others and creates those mixed halos
collectMixedHalos(haloBuffer, haloBufSize);
#ifndef USE_SERIAL_COSMO
MPI_Barrier(Partition::getComm());
#endif
// MASTER has all data and runs algorithm to make decisions
assignMixedHalos();
#ifndef USE_SERIAL_COSMO
MPI_Barrier(Partition::getComm());
#endif
// MASTER sends merge results to all processors
sendMixedHaloResults(haloBuffer, haloBufSize);
#ifndef USE_SERIAL_COSMO
MPI_Barrier(Partition::getComm());
#endif
// Collect totals for result checking
int totalAliveHalos;
#ifdef USE_SERIAL_COSMO
totalAliveHalos = this->numberOfAliveHalos;
#else
MPI_Allreduce((void*) &this->numberOfAliveHalos, (void*) &totalAliveHalos,
1, MPI_INT, MPI_SUM, Partition::getComm());
#endif
int totalAliveHaloParticles;
#ifdef USE_SERIAL_COSMO
totalAliveHaloParticles = this->numberOfHaloParticles;
#else
MPI_Allreduce((void*) &this->numberOfHaloParticles,
(void*) &totalAliveHaloParticles,
1, MPI_INT, MPI_SUM, Partition::getComm());
#endif
#ifndef USE_VTK_COSMO
if (this->myProc == MASTER) {
cout << endl;
cout << "Total halos found: " << totalAliveHalos << endl;
cout << "Total halo particles: " << totalAliveHaloParticles << endl;
}
#endif
for (unsigned int i = 0; i < this->allMixedHalos.size(); i++)
delete this->allMixedHalos[i];
delete [] haloBuffer;
}
/////////////////////////////////////////////////////////////////////////
//
// MASTER collects all mixed halos which are UNMARKED from all processors
// including its own mixed halos
//
/////////////////////////////////////////////////////////////////////////
void CosmoHaloFinderP::collectMixedHalos
#ifdef USE_SERIAL_COSMO
(ID_T* , int )
#else
(ID_T* haloBuffer, int haloBufSize)
#endif
{
// How many processors have mixed halos
int haveMixedHalo = (this->numberOfMixedHalos > 0 ? 1 : 0);
int processorsWithMixedHalos;
#ifdef USE_SERIAL_COSMO
processorsWithMixedHalos = haveMixedHalo;
#else
MPI_Allreduce((void*) &haveMixedHalo, (void*) &processorsWithMixedHalos,
1, MPI_INT, MPI_SUM, Partition::getComm());
#endif
// MASTER moves its own mixed halos to mixed halo vector (change index to tag)
// then gets messages from others and creates those mixed halos
#ifndef USE_SERIAL_COSMO
if (this->myProc == MASTER) {
#endif
// If MASTER has any mixed halos add them to the mixed halo vector
if (this->numberOfMixedHalos > 0) {
processorsWithMixedHalos--;
for (unsigned int h = 0; h < this->myMixedHalos.size(); h++) {
if (this->myMixedHalos[h]->getValid() == UNMARKED) {
CosmoHalo* halo = new CosmoHalo(
this->myMixedHalos[h]->getHaloID(),
this->myMixedHalos[h]->getAliveCount(),
this->myMixedHalos[h]->getDeadCount());
halo->setRankID(this->myProc);
this->allMixedHalos.push_back(halo);
// Translate index of particle to tag of particle
vector<ID_T>* tags = this->myMixedHalos[h]->getTags();
for (int i = 0; i < MERGE_COUNT; i++)
halo->addParticle((*tags)[i]);
}
}
}
#ifndef USE_SERIAL_COSMO
// Wait on messages from other processors and process
int notReceived = processorsWithMixedHalos;
MPI_Status mpistatus;
while (notReceived > 0) {
// Get message containing mixed halo information
#ifdef ID_64
MPI_Recv(haloBuffer, haloBufSize, MPI_LONG, MPI_ANY_SOURCE,
0, Partition::getComm(), &mpistatus);
#else
MPI_Recv(haloBuffer, haloBufSize, MPI_INT, MPI_ANY_SOURCE,
0, Partition::getComm(), &mpistatus);
#endif
// Gather halo information from the message
int index = 0;
int rank = haloBuffer[index++];
int numMixed = haloBuffer[index++];
for (int m = 0; m < numMixed; m++) {
ID_T id = haloBuffer[index++];
int aliveCount = haloBuffer[index++];
int deadCount = haloBuffer[index++];
// Create the CosmoHalo to hold the data and add to vector
CosmoHalo* halo = new CosmoHalo(id, aliveCount, deadCount);
halo->setRankID(rank);
this->allMixedHalos.push_back(halo);
for (int t = 0; t < MERGE_COUNT; t++)
halo->addParticle(haloBuffer[index++]);
}
notReceived--;
}
#ifndef USE_VTK_COSMO
cout << "Number of halos to merge: " << this->allMixedHalos.size() << endl;
#endif
}
// Other processors bundle up mixed and send to MASTER
else {
int index = 0;
if (this->numberOfMixedHalos > 0) {
haloBuffer[index++] = this->myProc;
haloBuffer[index++] = this->numberOfMixedHalos;
for (unsigned int h = 0; h < this->myMixedHalos.size(); h++) {
if (this->myMixedHalos[h]->getValid() == UNMARKED) {
haloBuffer[index++] = this->myMixedHalos[h]->getHaloID();
haloBuffer[index++] = this->myMixedHalos[h]->getAliveCount();
haloBuffer[index++] = this->myMixedHalos[h]->getDeadCount();
vector<ID_T>* tags = this->myMixedHalos[h]->getTags();
for (int i = 0; i < MERGE_COUNT; i++) {
haloBuffer[index++] = (*tags)[i];
}
}
}
MPI_Request request;
#ifdef ID_64
MPI_Isend(haloBuffer, haloBufSize, MPI_LONG, MASTER,
0, Partition::getComm(), &request);
#else
MPI_Isend(haloBuffer, haloBufSize, MPI_INT, MASTER,
0, Partition::getComm(), &request);
#endif
}
}
#endif // USE_SERIAL_COSMO
}
/////////////////////////////////////////////////////////////////////////
//
// MASTER has collected all the mixed halos and decides which processors
// will get which by matching them up
//
/////////////////////////////////////////////////////////////////////////
void CosmoHaloFinderP::assignMixedHalos()
{
// MASTER has all data and runs algorithm to make decisions
if (this->myProc == MASTER) {
#ifndef USE_VTK_COSMO
#ifdef DEBUG
for (int m = 0; m < this->allMixedHalos.size(); m++) {
vector<ID_T>* tags = this->allMixedHalos[m]->getTags();
cout << "Mixed Halo " << m << ": "
<< " rank=" << this->allMixedHalos[m]->getRankID()
<< " index=" << this->allMixedHalos[m]->getHaloID()
<< " tag=" << (*tags)[0]
<< " alive=" << this->allMixedHalos[m]->getAliveCount()
<< " dead=" << this->allMixedHalos[m]->getDeadCount() << endl;
}
#endif
#endif
// Iterate over mixed halo vector and match and mark
// Remember that I can have 3 or 4 that match
for (unsigned int m = 0; m < this->allMixedHalos.size(); m++) {
// If this halo has not already been paired with another
if (this->allMixedHalos[m]->getPartners()->empty() == true) {
// Current mixed halo has the most alive particles so far
int numberAlive = this->allMixedHalos[m]->getAliveCount();
int haloWithLeastAlive = m;
// Iterate on the rest of the mixed halos
unsigned int n = m + 1;
while (n < this->allMixedHalos.size()) {
// Compare to see if there are a number of tags in common
int match = compareHalos(this->allMixedHalos[m],
this->allMixedHalos[n]);
// Keep track of the mixed halo with the most alive particles
if (match > 0) {
if (numberAlive > this->allMixedHalos[n]->getAliveCount()) {
numberAlive = this->allMixedHalos[n]->getAliveCount();
haloWithLeastAlive = n;
}
this->allMixedHalos[m]->addPartner(n);
this->allMixedHalos[n]->addPartner(m);
this->allMixedHalos[m]->setValid(INVALID);
this->allMixedHalos[n]->setValid(INVALID);
}
n++;
}
// Mixed halo with the least alive particles gets it as VALID
this->allMixedHalos[haloWithLeastAlive]->setValid(VALID);
}
}
#ifndef USE_VTK_COSMO
#ifdef DEBUG
for (unsigned int m = 0; m < this->allMixedHalos.size(); m++) {
cout << "Mixed Halo " << m;
if (this->allMixedHalos[m]->getValid() == VALID)
cout << " is VALID on "
<< " Rank " << this->allMixedHalos[m]->getRankID();
cout << " partners with ";
set<int>::iterator iter;
set<int>* partner = this->allMixedHalos[m]->getPartners();
for (iter = partner->begin(); iter != partner->end(); ++iter)
cout << (*iter) << " ";
cout << endl;
}
#endif
#endif
}
}
/////////////////////////////////////////////////////////////////////////
//
// Compare the tags of two halos to see if they are somewhat the same
// This needs to be made better
//
/////////////////////////////////////////////////////////////////////////
int CosmoHaloFinderP::compareHalos(CosmoHalo* halo1, CosmoHalo* halo2)
{
vector<ID_T>* member1 = halo1->getTags();
vector<ID_T>* member2 = halo2->getTags();
int numFound = 0;
for (unsigned int i = 0; i < member1->size(); i++) {
bool done = false;
unsigned int j = 0;
while (!done &&
(*member1)[i] >= (*member2)[j] &&
j < member2->size()) {
if ((*member1)[i] == (*member2)[j]) {
done = true;
numFound++;
}
j++;
}
}
if (numFound == 0)
return numFound;
else
return numFound;
}
/////////////////////////////////////////////////////////////////////////
//
// MASTER sends the result of the merge back to the processors which
// label their previously UNMARKED mixed halos as VALID or INVALID
// VALID halos have all their particles made ALIVE for output
// INVALID halos have all their particles made DEAD because other
// processors will report them
//
/////////////////////////////////////////////////////////////////////////
void CosmoHaloFinderP::sendMixedHaloResults
#ifdef USE_SERIAL_COSMO
(ID_T* haloBuffer, int)
#else
(ID_T* haloBuffer, int haloBufSize)
#endif
{
#ifndef USE_SERIAL_COSMO
// MASTER sends merge results to all processors
if (this->myProc == MASTER) {
#endif
// Share the information
// Send to each processor the rank, id, and valid status
// Use the same haloBuffer
int index = 0;
haloBuffer[index++] = (ID_T)this->allMixedHalos.size();
for (unsigned int m = 0; m < this->allMixedHalos.size(); m++) {
haloBuffer[index++] = this->allMixedHalos[m]->getRankID();
haloBuffer[index++] = this->allMixedHalos[m]->getHaloID();
haloBuffer[index++] = this->allMixedHalos[m]->getValid();
}
#ifndef USE_SERIAL_COSMO
MPI_Request request;
for (int proc = 1; proc < this->numProc; proc++) {
#ifdef ID_64
MPI_Isend(haloBuffer, haloBufSize, MPI_LONG, proc,
0, Partition::getComm(), &request);
#else
MPI_Isend(haloBuffer, haloBufSize, MPI_INT, proc,
0, Partition::getComm(), &request);
#endif
}
#endif
// MASTER must claim the mixed halos assigned to him
for (unsigned int m = 0; m < this->allMixedHalos.size(); m++) {
if (this->allMixedHalos[m]->getRankID() == MASTER &&
this->allMixedHalos[m]->getValid() == VALID) {
// Locate the mixed halo in question
for (unsigned int h = 0; h < this->myMixedHalos.size(); h++) {
int id = this->myMixedHalos[h]->getHaloID();
if (id == this->allMixedHalos[m]->getHaloID()) {
this->myMixedHalos[h]->setValid(VALID);
int newAliveParticles = this->myMixedHalos[h]->getAliveCount() +
this->myMixedHalos[h]->getDeadCount();
this->numberOfHaloParticles += newAliveParticles;
this->numberOfAliveHalos++;
// Add this halo to valid halos on this processor for
// subsequent halo properties analysis
this->halos.push_back(this->haloStart[id]);
this->haloCount.push_back(newAliveParticles);
// Output trick - since the status of this particle was marked MIXED
// when it was added to the mixed CosmoHalo vector, and now it has
// been declared VALID, change it to ALIVE even if it was dead
vector<ID_T>* particles = this->myMixedHalos[h]->getParticles();
vector<ID_T>::iterator iter;
for (iter = particles->begin(); iter != particles->end(); ++iter)
this->status[(*iter)] = ALIVE;
}
}
}
}
#ifndef USE_SERIAL_COSMO
}
// Other processors wait for result and adjust their halo vector
else {
MPI_Status mpistatus;
#ifdef ID_64
MPI_Recv(haloBuffer, haloBufSize, MPI_LONG, MASTER,
0, Partition::getComm(), &mpistatus);
#else
MPI_Recv(haloBuffer, haloBufSize, MPI_INT, MASTER,
0, Partition::getComm(), &mpistatus);
#endif
// Unpack information to see which of mixed halos are still valid
int index = 0;
int numMixed = haloBuffer[index++];
for (int m = 0; m < numMixed; m++) {
int rank = haloBuffer[index++];
int id = haloBuffer[index++];
int valid = haloBuffer[index++];
// If this mixed halo is on my processor
if (rank == this->myProc && valid == VALID) {
// Locate the mixed halo in question
for (unsigned int h = 0; h < this->myMixedHalos.size(); h++) {
if (this->myMixedHalos[h]->getHaloID() == id) {
this->myMixedHalos[h]->setValid(VALID);
int newAliveParticles = this->myMixedHalos[h]->getAliveCount() +
this->myMixedHalos[h]->getDeadCount();
this->numberOfHaloParticles += newAliveParticles;
this->numberOfAliveHalos++;
// Add this halo to valid halos on this processor for
// subsequent halo properties analysis
this->halos.push_back(this->haloStart[id]);
this->haloCount.push_back(newAliveParticles);
// Output trick - since the status of this particle was marked MIXED
// when it was added to the mixed CosmoHalo vector, and now it has
// been declared VALID, change it to ALIVE even if it was dead
vector<ID_T>* particles = this->myMixedHalos[h]->getParticles();
vector<ID_T>::iterator iter;
for (iter = particles->begin(); iter != particles->end(); ++iter)
this->status[(*iter)] = ALIVE;
}
}
}
}
}
#endif // USE_SERIAL_COSMO
}
#ifndef USE_VTK_COSMO
/////////////////////////////////////////////////////////////////////////
//
// Write the output of the halo finder in the form of the input .cosmo file
//
// Encoded mixed halo VALID or INVALID into the status array such that
// ALIVE particles that are part of an INVALID mixed array will not write
// but DEAD particles that are part of a VALID mixed array will be written
//
// In order to make the output consistent with the serial output where the
// lowest tagged particle in a halo owns the halo, work must be done to
// identify the lowest tag. This is because as particles are read onto
// this processor using the round robin read of every particle, those
// particles are no longer in tag order. When the serial halo finder is
// called it has to use the index of the particle on this processor which
// is no longer the tag.
//
// p haloTag tag haloSize
// 0 0 523 3
// 1 0 522 0
// 2 0 266 0
//
// In the above example the halo will be credited to 523 instead of 266
// because the index of 523 is 0 and the index of 266 is 2. So we must
// make a pass to map the indexes.
//
/////////////////////////////////////////////////////////////////////////
void CosmoHaloFinderP::writeTaggedParticles()
{
// Map the index of the particle on this process to the index of the
// particle with the lowest tag value so that the written output refers
// to the lowest tag as being the owner of the halo
int* mapIndex = new int[this->particleCount];
for (int p = 0; p < this->particleCount; p++)
mapIndex[p] = p;
// If the tag for the first particle of this halo is bigger than the tag
// for this particle, change the map to identify this particle as the lowest
for (int p = 0; p < this->particleCount; p++) {
if (this->tag[mapIndex[this->haloTag[p]]] > this->tag[p])
mapIndex[this->haloTag[p]] = p;
}
// Write the tagged particle file
ofstream* outStream = new ofstream(this->outFile.c_str(), ios::out);
string textMode = "ascii";
char str[1024];
string ascii = "ascii";
if (textMode == "ascii") {
// Output all ALIVE particles that were not part of a mixed halo
// unless that halo is VALID. Output only the DEAD particles that are
// part of a VALID halo. This was encoded when mixed halos were found
// so any ALIVE particle is VALID
for (int p = 0; p < this->particleCount; p++) {
if (this->status[p] == ALIVE) {
// Every alive particle appears in the particle output
sprintf(str, "%12.4E %12.4E ", this->xx[p], this->vx[p]);
*outStream << str;
sprintf(str, "%12.4E %12.4E ", this->yy[p], this->vy[p]);
*outStream << str;
sprintf(str, "%12.4E %12.4E ", this->zz[p], this->vz[p]);
*outStream << str;
int result = (this->haloSize[this->haloTag[p]] < this->pmin)
? -1: this->tag[mapIndex[this->haloTag[p]]];
sprintf(str, "%12d %12d\n", result, this->tag[p]);
*outStream << str;
}
}
}
else {
// output in COSMO form
for (int p = 0; p < this->particleCount; p++) {
float fBlock[COSMO_FLOAT];
fBlock[0] = this->xx[p];
fBlock[1] = this->vx[p];
fBlock[2] = this->yy[p];
fBlock[3] = this->vy[p];
fBlock[4] = this->zz[p];
fBlock[5] = this->vz[p];
fBlock[6] = (this->haloSize[this->haloTag[p]] < this->pmin)
? -1.0: 1.0 * this->tag[this->haloTag[p]];
outStream->write((char *)fBlock, COSMO_FLOAT * sizeof(float));
int iBlock[COSMO_INT];
iBlock[0] = this->tag[p];
outStream->write((char *)iBlock, COSMO_INT * sizeof(int));
}
}
outStream->close();
delete outStream;
delete [] mapIndex;
}
#endif // USE_VTK_COSMO
| 37.602122
| 102
| 0.608752
|
SCS-B3C
|
7898e349b2fa142d82fb16ea237b63fba1765daf
| 653
|
cpp
|
C++
|
src/gen/detail/ExecHandler.cpp
|
bgn9000/rapidcheck
|
593ada72f6938221973bf30bf7a7f7e6a24160de
|
[
"BSD-2-Clause"
] | null | null | null |
src/gen/detail/ExecHandler.cpp
|
bgn9000/rapidcheck
|
593ada72f6938221973bf30bf7a7f7e6a24160de
|
[
"BSD-2-Clause"
] | null | null | null |
src/gen/detail/ExecHandler.cpp
|
bgn9000/rapidcheck
|
593ada72f6938221973bf30bf7a7f7e6a24160de
|
[
"BSD-2-Clause"
] | 1
|
2019-03-05T13:52:28.000Z
|
2019-03-05T13:52:28.000Z
|
#include "rapidcheck/gen/detail/ExecHandler.h"
#include "rapidcheck/Gen.h"
namespace rc {
namespace gen {
namespace detail {
ExecHandler::ExecHandler(Recipe &recipe)
: m_recipe(recipe)
, m_random(m_recipe.random)
, m_it(begin(m_recipe.ingredients)) {}
rc::detail::Any ExecHandler::onGenerate(const Gen<rc::detail::Any> &gen) {
rc::detail::ImplicitScope newScope;
Random random = m_random.split();
if (m_it == end(m_recipe.ingredients)) {
m_it = m_recipe.ingredients.insert(m_it, gen(random, m_recipe.size));
}
auto current = m_it++;
return current->value();
}
} // namespace detail
} // namespace gen
} // namespace rc
| 23.321429
| 74
| 0.698315
|
bgn9000
|
789ae1fadb38be5a53cf6de771eef086900f3266
| 774
|
cpp
|
C++
|
2018/day13/tests/TestClass.cpp
|
alexandru-andronache/adventofcode
|
ee41d82bae8b705818fda5bd43e9962bb0686fec
|
[
"Apache-2.0"
] | 3
|
2021-07-01T14:31:06.000Z
|
2022-03-29T20:41:21.000Z
|
2018/day13/tests/TestClass.cpp
|
alexandru-andronache/adventofcode
|
ee41d82bae8b705818fda5bd43e9962bb0686fec
|
[
"Apache-2.0"
] | null | null | null |
2018/day13/tests/TestClass.cpp
|
alexandru-andronache/adventofcode
|
ee41d82bae8b705818fda5bd43e9962bb0686fec
|
[
"Apache-2.0"
] | null | null | null |
#include "TestClass.h"
#include "../test.h"
namespace aoc2018_day13 {
TEST_F(Tests2018Day13, part_1_test) {
auto sol = part_1("../2018/day13/input_test.in");
ASSERT_EQ(sol.first, 7);
ASSERT_EQ(sol.second, 3);
}
TEST_F(Tests2018Day13, part_1_real_test) {
auto sol = part_1("../2018/day13/input.in");
ASSERT_EQ(sol.first, 103);
ASSERT_EQ(sol.second, 85);
}
TEST_F(Tests2018Day13, part_2_test) {
auto sol = part_2("../2018/day13/input_test2.in");
ASSERT_EQ(sol.first, 6);
ASSERT_EQ(sol.second, 4);
}
TEST_F(Tests2018Day13, part_2_real_test) {
auto sol = part_2("../2018/day13/input.in");
ASSERT_EQ(sol.first, 88);
ASSERT_EQ(sol.second, 64);
}
}
| 26.689655
| 58
| 0.600775
|
alexandru-andronache
|
789b5cceacf0f4601a7c391bc7590c069b3cce16
| 4,287
|
cc
|
C++
|
ThirdParty/webrtc/src/webrtc/video/video_loopback.cc
|
JokeJoe8806/licode-windows
|
2bfdaf6e87669df2b9960da50c6800bc3621b80b
|
[
"MIT"
] | 8
|
2018-12-27T14:57:13.000Z
|
2021-04-07T07:03:15.000Z
|
ThirdParty/webrtc/src/webrtc/video/video_loopback.cc
|
JokeJoe8806/licode-windows
|
2bfdaf6e87669df2b9960da50c6800bc3621b80b
|
[
"MIT"
] | 1
|
2019-03-13T01:35:03.000Z
|
2020-10-08T04:13:04.000Z
|
ThirdParty/webrtc/src/webrtc/video/video_loopback.cc
|
JokeJoe8806/licode-windows
|
2bfdaf6e87669df2b9960da50c6800bc3621b80b
|
[
"MIT"
] | 9
|
2018-12-28T11:45:12.000Z
|
2021-05-11T02:15:31.000Z
|
/*
* Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <stdio.h>
#include <map>
#include "gflags/gflags.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "webrtc/test/field_trial.h"
#include "webrtc/test/run_test.h"
#include "webrtc/typedefs.h"
#include "webrtc/video/loopback.h"
namespace webrtc {
namespace flags {
DEFINE_int32(width, 640, "Video width.");
size_t Width() {
return static_cast<size_t>(FLAGS_width);
}
DEFINE_int32(height, 480, "Video height.");
size_t Height() {
return static_cast<size_t>(FLAGS_height);
}
DEFINE_int32(fps, 30, "Frames per second.");
int Fps() {
return static_cast<int>(FLAGS_fps);
}
DEFINE_int32(min_bitrate, 50, "Minimum video bitrate.");
size_t MinBitrate() {
return static_cast<size_t>(FLAGS_min_bitrate);
}
DEFINE_int32(start_bitrate, 300, "Video starting bitrate.");
size_t StartBitrate() {
return static_cast<size_t>(FLAGS_start_bitrate);
}
DEFINE_int32(max_bitrate, 800, "Maximum video bitrate.");
size_t MaxBitrate() {
return static_cast<size_t>(FLAGS_max_bitrate);
}
int MinTransmitBitrate() {
return 0;
} // No min padding for regular video.
DEFINE_string(codec, "VP8", "Video codec to use.");
std::string Codec() {
return static_cast<std::string>(FLAGS_codec);
}
DEFINE_int32(loss_percent, 0, "Percentage of packets randomly lost.");
int LossPercent() {
return static_cast<int>(FLAGS_loss_percent);
}
DEFINE_int32(link_capacity,
0,
"Capacity (kbps) of the fake link. 0 means infinite.");
int LinkCapacity() {
return static_cast<int>(FLAGS_link_capacity);
}
DEFINE_int32(queue_size, 0, "Size of the bottleneck link queue in packets.");
int QueueSize() {
return static_cast<int>(FLAGS_queue_size);
}
DEFINE_int32(avg_propagation_delay_ms,
0,
"Average link propagation delay in ms.");
int AvgPropagationDelayMs() {
return static_cast<int>(FLAGS_avg_propagation_delay_ms);
}
DEFINE_int32(std_propagation_delay_ms,
0,
"Link propagation delay standard deviation in ms.");
int StdPropagationDelayMs() {
return static_cast<int>(FLAGS_std_propagation_delay_ms);
}
DEFINE_bool(logs, false, "print logs to stderr");
DEFINE_string(
force_fieldtrials,
"",
"Field trials control experimental feature code which can be forced. "
"E.g. running with --force_fieldtrials=WebRTC-FooFeature/Enable/"
" will assign the group Enable to field trial WebRTC-FooFeature. Multiple "
"trials are separated by \"/\"");
DEFINE_int32(num_temporal_layers,
0,
"Number of temporal layers. Set to 1-4 to override.");
size_t NumTemporalLayers() {
return static_cast<size_t>(FLAGS_num_temporal_layers);
}
} // namespace flags
void Loopback() {
test::Loopback::Config config{flags::Width(),
flags::Height(),
flags::Fps(),
flags::MinBitrate(),
flags::StartBitrate(),
flags::MaxBitrate(),
0, // No min transmit bitrate.
flags::Codec(),
flags::NumTemporalLayers(),
flags::LossPercent(),
flags::LinkCapacity(),
flags::QueueSize(),
flags::AvgPropagationDelayMs(),
flags::StdPropagationDelayMs(),
flags::FLAGS_logs};
test::Loopback loopback(config);
loopback.Run();
}
} // namespace webrtc
int main(int argc, char* argv[]) {
::testing::InitGoogleTest(&argc, argv);
google::ParseCommandLineFlags(&argc, &argv, true);
webrtc::test::InitFieldTrialsFromString(
webrtc::flags::FLAGS_force_fieldtrials);
webrtc::test::RunTest(webrtc::Loopback);
return 0;
}
| 29.363014
| 79
| 0.643107
|
JokeJoe8806
|
a192aad2c3bbb4071b8e8490ed2c5a78fda1df77
| 8,941
|
cpp
|
C++
|
opt/nomad/src/Algos/MeshBase.cpp
|
scikit-quant/scikit-quant
|
397ab0b6287f3815e9bcadbfadbe200edbee5a23
|
[
"BSD-3-Clause-LBNL"
] | 31
|
2019-02-05T16:39:18.000Z
|
2022-03-11T23:14:11.000Z
|
opt/nomad/src/Algos/MeshBase.cpp
|
scikit-quant/scikit-quant
|
397ab0b6287f3815e9bcadbfadbe200edbee5a23
|
[
"BSD-3-Clause-LBNL"
] | 20
|
2020-04-13T09:22:53.000Z
|
2021-08-16T16:14:13.000Z
|
opt/nomad/src/Algos/MeshBase.cpp
|
scikit-quant/scikit-quant
|
397ab0b6287f3815e9bcadbfadbe200edbee5a23
|
[
"BSD-3-Clause-LBNL"
] | 6
|
2020-04-21T17:43:47.000Z
|
2021-03-10T04:12:34.000Z
|
/*---------------------------------------------------------------------------------*/
/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct Search - */
/* */
/* NOMAD - Version 4 has been created by */
/* Viviane Rochon Montplaisir - Polytechnique Montreal */
/* Christophe Tribes - Polytechnique Montreal */
/* */
/* The copyright of NOMAD - version 4 is owned by */
/* Charles Audet - Polytechnique Montreal */
/* Sebastien Le Digabel - Polytechnique Montreal */
/* Viviane Rochon Montplaisir - Polytechnique Montreal */
/* Christophe Tribes - Polytechnique Montreal */
/* */
/* NOMAD 4 has been funded by Rio Tinto, Hydro-Québec, Huawei-Canada, */
/* NSERC (Natural Sciences and Engineering Research Council of Canada), */
/* InnovÉÉ (Innovation en Énergie Électrique) and IVADO (The Institute */
/* for Data Valorization) */
/* */
/* NOMAD v3 was created and developed by Charles Audet, Sebastien Le Digabel, */
/* Christophe Tribes and Viviane Rochon Montplaisir and was funded by AFOSR */
/* and Exxon Mobil. */
/* */
/* NOMAD v1 and v2 were created and developed by Mark Abramson, Charles Audet, */
/* Gilles Couture, and John E. Dennis Jr., and were funded by AFOSR and */
/* Exxon Mobil. */
/* */
/* Contact information: */
/* Polytechnique Montreal - GERAD */
/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */
/* e-mail: nomad@gerad.ca */
/* */
/* This program is free software: you can redistribute it and/or modify it */
/* under the terms of the GNU Lesser General Public License as published by */
/* the Free Software Foundation, either version 3 of the License, or (at your */
/* option) any later version. */
/* */
/* This program is distributed in the hope that it will be useful, but WITHOUT */
/* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or */
/* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License */
/* for more details. */
/* */
/* You should have received a copy of the GNU Lesser General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/* You can find information on the NOMAD software at www.gerad.ca/nomad */
/*---------------------------------------------------------------------------------*/
#include "../Algos/MeshBase.hpp"
NOMAD::MeshBase::MeshBase(const std::shared_ptr<NOMAD::PbParameters> pbParams)
: _n(pbParams->getAttributeValue<size_t>("DIMENSION")),
_pbParams(pbParams),
_initialMeshSize(pbParams->getAttributeValue<NOMAD::ArrayOfDouble>("INITIAL_MESH_SIZE")),
_minMeshSize(pbParams->getAttributeValue<NOMAD::ArrayOfDouble>("MIN_MESH_SIZE")),
_initialFrameSize(pbParams->getAttributeValue<NOMAD::ArrayOfDouble>("INITIAL_FRAME_SIZE")),
_minFrameSize(pbParams->getAttributeValue<NOMAD::ArrayOfDouble>("MIN_FRAME_SIZE")),
_lowerBound(pbParams->getAttributeValue<NOMAD::ArrayOfDouble>("LOWER_BOUND")),
_upperBound(pbParams->getAttributeValue<NOMAD::ArrayOfDouble>("UPPER_BOUND"))
{
init();
}
void NOMAD::MeshBase::init()
{
if ( _pbParams->toBeChecked() )
{
throw NOMAD::Exception(__FILE__, __LINE__, "Parameters::checkAndComply() needs to be called before constructing a mesh.");
}
}
NOMAD::ArrayOfDouble NOMAD::MeshBase::getRho(void) const
{
NOMAD::ArrayOfDouble rho(_n);
for (size_t i = 0; i < _n; i++)
{
rho[i] = getRho(i);
}
return rho;
}
NOMAD::ArrayOfDouble NOMAD::MeshBase::getdeltaMeshSize(void) const
{
NOMAD::ArrayOfDouble delta(_n);
for (size_t i = 0; i < _n; i++)
{
delta[i] = getdeltaMeshSize(i);
}
return delta;
}
NOMAD::ArrayOfDouble NOMAD::MeshBase::getDeltaFrameSize() const
{
NOMAD::ArrayOfDouble Delta(_n);
for (size_t i = 0; i < _n; i++)
{
Delta[i] = getDeltaFrameSize(i);
}
return Delta;
}
NOMAD::ArrayOfDouble NOMAD::MeshBase::getDeltaFrameSizeCoarser() const
{
NOMAD::ArrayOfDouble Delta(_n);
for (size_t i = 0; i < _n; i++)
{
Delta[i] = getDeltaFrameSizeCoarser(i);
}
return Delta;
}
void NOMAD::MeshBase::setDeltas(const NOMAD::ArrayOfDouble &deltaMeshSize,
const NOMAD::ArrayOfDouble &deltaFrameSize)
{
for (size_t i = 0; i < _n; i++)
{
setDeltas(i, deltaMeshSize[i], deltaFrameSize[i]);
}
}
/*-----------------------------------------------------------*/
/* scale and project on the mesh */
/*-----------------------------------------------------------*/
NOMAD::Double NOMAD::MeshBase::scaleAndProjectOnMesh(size_t i, const NOMAD::Double &l) const
{
// Not defined for MeshBase.
throw NOMAD::Exception(__FILE__, __LINE__, "scaleAndProjectOnMesh() not defined for MeshBase.");
}
NOMAD::ArrayOfDouble NOMAD::MeshBase::scaleAndProjectOnMesh(
const NOMAD::Direction &dir) const
{
// Not defined for MeshBase.
throw NOMAD::Exception(__FILE__, __LINE__, "scaleAndProjectOnMesh() not defined for MeshBase.");
}
NOMAD::Point NOMAD::MeshBase::projectOnMesh(const NOMAD::Point& point,
const NOMAD::Point& frameCenter) const
{
// Not defined for MeshBase.
throw NOMAD::Exception(__FILE__, __LINE__, "projectOnMesh() not defined for MeshBase.");
}
bool NOMAD::MeshBase::verifyPointIsOnMesh(const NOMAD::Point& point, const NOMAD::Point& center) const
{
bool isOnMesh = true;
for (size_t i = 0; i < point.size(); i++)
{
NOMAD::Double pointRebaseI = point[i];
NOMAD::Double centerI = center[i];
NOMAD::Double deltaI = getdeltaMeshSize(i);
if ( (_lowerBound[i].isDefined() && _lowerBound[i] == pointRebaseI)
|| (_upperBound[i].isDefined() && _upperBound[i] == pointRebaseI))
{
isOnMesh = true;
}
else
{
if (!centerI.isMultipleOf(deltaI))
{
// Rebase point on the mesh centered on center Point
pointRebaseI -= centerI;
}
if (!pointRebaseI.isMultipleOf(deltaI))
{
isOnMesh = false;
break;
}
}
}
return isOnMesh;
}
std::ostream& NOMAD::operator<<(std::ostream& os, const NOMAD::MeshBase& mesh)
{
os << "DELTA_MESH_SIZE " << mesh.getdeltaMeshSize() << std::endl;
os << "DELTA_FRAME_SIZE " << mesh.getDeltaFrameSize() << std::endl;
return os;
}
std::istream& NOMAD::operator>>(std::istream& is, NOMAD::MeshBase& mesh)
{
size_t n = mesh.getSize();
// Read line by line
std::string name;
NOMAD::ArrayOfDouble deltaMeshSize(n), deltaFrameSize(n);
while (is >> name && is.good() && !is.eof())
{
if ("DELTA_MESH_SIZE" == name)
{
is >> deltaMeshSize;
}
else if ("DELTA_FRAME_SIZE" == name)
{
is >> deltaFrameSize;
}
else
{
// Put back name to istream. Maybe there is a simpler way.
for (unsigned i = 0; i < name.size(); i++)
{
is.unget();
}
break;
}
}
mesh.setDeltas(deltaMeshSize, deltaFrameSize);
return is;
}
| 39.043668
| 130
| 0.489766
|
scikit-quant
|
a193a90473aed44aade937251dfbd67d33fb5d3b
| 1,820
|
cpp
|
C++
|
ZROI/20zr提高组十连测附加赛4/B/B.cpp
|
jinzhengyu1212/Clovers
|
0efbb0d87b5c035e548103409c67914a1f776752
|
[
"MIT"
] | null | null | null |
ZROI/20zr提高组十连测附加赛4/B/B.cpp
|
jinzhengyu1212/Clovers
|
0efbb0d87b5c035e548103409c67914a1f776752
|
[
"MIT"
] | null | null | null |
ZROI/20zr提高组十连测附加赛4/B/B.cpp
|
jinzhengyu1212/Clovers
|
0efbb0d87b5c035e548103409c67914a1f776752
|
[
"MIT"
] | null | null | null |
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
#define mk make_pair
void checkmin(int &x,int y){if(x>y) x=y;}
void checkmax(int &x,int y){if(x<y) x=y;}
void checkmin(ll &x,ll y){if(x>y) x=y;}
void checkmax(ll &x,ll y){if(x<y) x=y;}
#define out(x) cerr<<#x<<'='<<x<<' '
#define outln(x) cerr<<#x<<'='<<x<<endl
#define sz(x) (int)(x).size()
inline int read(){
int x=0,f=1; char c=getchar();
while(c>'9'||c<'0'){if(c=='-') f=-1; c=getchar();}
while(c>='0'&&c<='9') x=(x<<1)+(x<<3)+(c^48),c=getchar();
return x*f;
}
const int N=100005;
int n;
vector<int> v[N];
ll up[N],down[N],deg[N],ans=0;
void dfs1(int u,int f){
up[u]=deg[u];
for(auto &to : v[u]){
if(to==f) continue;
dfs1(to,u); up[u]+=up[to];
}
down[u]=2*n-2-up[u];
}
ll mx1[N],mx2[N];
ll dp[N],dp2[N],sum[N],sz[N];
void dfs2(int u,int f){
dp[u]=down[u]; ll mx=0;
sum[u]=down[u]; sz[u]=1;
for(auto &to : v[u]){
if(to==f) continue;
dfs2(to,u);
if(mx1[u]<dp[to]) mx2[u]=mx1[u],mx1[u]=dp[to];
else if(mx2[u]<dp[to]) mx2[u]=dp[to];
sz[u]+=sz[to];
}
dp[u]+=mx1[u];
}
void dfs3(int u,int f,ll S){
if(f!=-1){
dp2[u]=dp2[f]+(2*n-2-(up[f]-up[u])-S);
if(dp[u]==mx1[f]) checkmax(dp2[u],mx2[f]+(2*n-2-(up[f]-up[u])-S));
else checkmax(dp2[u],mx1[f]+(2*n-2-(up[f]-up[u])-S));
}
checkmax(ans,dp2[u]);
for(auto &to : v[u]){
if(to==f) continue;
dfs3(to,u,u==1 ? 0 : S+up[f]-up[u]);
}
}
int main()
{
n=read();
for(int i=1;i<n;i++){
int x=read(),y=read();
v[x].push_back(y); v[y].push_back(x);
deg[x]++; deg[y]++;
}
dfs1(1,-1);
dfs2(1,-1);
ans=dp[1];
dfs3(1,-1,0);
printf("%.5lf\n",(double)ans);
return 0;
}
| 24.266667
| 74
| 0.48956
|
jinzhengyu1212
|
a194e0d2bd4ac009e3e06485ecf0b217ffede005
| 5,987
|
cpp
|
C++
|
rndlevelsource/Polygon.cpp
|
Telefragged/rndlevelsource
|
17dfcf3a12d10d1884860c39e2169a6cb9dc0ba1
|
[
"MIT"
] | null | null | null |
rndlevelsource/Polygon.cpp
|
Telefragged/rndlevelsource
|
17dfcf3a12d10d1884860c39e2169a6cb9dc0ba1
|
[
"MIT"
] | null | null | null |
rndlevelsource/Polygon.cpp
|
Telefragged/rndlevelsource
|
17dfcf3a12d10d1884860c39e2169a6cb9dc0ba1
|
[
"MIT"
] | null | null | null |
#include "Polygon.h"
#include <algorithm>
#include <numeric>
#include <boost/range/adaptors.hpp>
#include <boost/range/algorithm.hpp>
#include "Vector.h"
#include "Vertex.h"
Polygon::classification Polygon::classify(const Plane& plane) const
{
size_t count = points.size();
size_t front = 0, back = 0, onplane = 0;
for (const auto& p : points)
{
auto test = plane.evaluate(p);
if (test <= 0) back++;
if (test >= 0) front++;
if (test == 0) onplane++;
}
if (onplane == count) return Polygon::classification::onPlane;
if (front == count) return Polygon::classification::front;
if (back == count) return Polygon::classification::back;
return Polygon::classification::spanning;
}
Vertex Polygon::origin() const
{
return std::accumulate(points.cbegin(), points.cend(), Vertex{ 0, 0, 0 }) / double(points.size());
}
Plane Polygon::plane() const
{
if(points.size() < 3)
return Plane();
return { points[0], points[1], points[2] };
}
void Polygon::rotate(const Vertex & point, const Matrix3d & rotmat)
{
for (auto &p : points)
p = p.rotate(point, rotmat);
}
void Polygon::move(const Vertex & v)
{
for (auto &p : points)
p += v;
}
void Polygon::moveTo(const Vertex & p)
{
Vertex dist = p - origin();
for (auto &p : points)
p += dist;
}
void Polygon::scale(const Vertex &scale)
{
this->scale(origin(), scale);
}
void Polygon::scale(const Vertex& origin, const Vertex& scale)
{
for (auto &point : points)
{
Vertex vec = Vector::diff(origin, point).vec();
vec.x(vec.x() * scale.x());
vec.y(vec.y() * scale.y());
vec.z(vec.z() * scale.z());
point = origin + vec;
}
}
void Polygon::sliceThis(const Plane &plane)
{
auto[back, front] = slice(plane);
if (!back.points.empty() && !front.points.empty())
points = back.points;
}
std::pair<Polygon, Polygon> Polygon::slice(const Plane& plane) const
{
auto classification = classify(plane);
std::pair<Polygon, Polygon> ret;
if (classification != classification::spanning)
{
if (classification == classification::back) ret.first = *this;
else if (classification == classification::front) ret.second = *this;
return ret;
}
size_t prev = 0;
for (size_t i = 0; i <= points.size(); i++)
{
size_t index = i % points.size();
Vertex end = points[index];
auto c = plane.evaluate(end);
if (i > 0 && c != 0 && prev != 0 && c != prev)
{
Vertex start = points[i - 1];
Vector line = Vector::diff(start, end);
Vertex intersect = Plane::intersectPoint(plane, line);
if (!Vertex::isVertex(intersect))
throw new std::exception("Expected intersection");
ret.first.points.push_back(intersect);
ret.second.points.push_back(intersect);
}
if (i < points.size())
{
if (c <= 0) ret.first.points.push_back(end);
if (c >= 0) ret.second.points.push_back(end);
}
prev = c;
}
return ret;
}
void Polygon::flip()
{
std::reverse(points.begin(), points.end());
}
void Polygon::roundPoints(size_t precision)
{
double exp = std::pow(10, precision);
std::transform(points.begin(), points.end(), points.begin(), [exp](Vertex v) {
v.x(std::round(v.x() * exp) / exp);
v.y(std::round(v.y() * exp) / exp);
v.z(std::round(v.z() * exp) / exp);
return v;
});
}
Vertex Polygon::intersectPoint(const Vector& line, int flags) const
{
Plane plane = this->plane();
auto point = Plane::intersectPoint(plane, line);
Vertex defaultRet = (flags & lineBoundsFlag::RETURN_END_ON_FAIL) > 0 ? line.end() : Vertex();
flags = flags & lineBoundsFlag::ALLOW_BOTH;
if (!Vertex::isVertex(point))
return defaultRet;
bool test = testCollision(point);
if (!test)
return defaultRet;
if (flags != lineBoundsFlag::ALLOW_BOTH)
{
double position = line.calculatePosition(point);
if ((lineBoundsFlag::ALLOW_BACK & flags) == 0 && (position < 0 || doubleeq(position, 0)))
return defaultRet;
if ((lineBoundsFlag::ALLOW_FRONT & flags) == 0 && (position > 1 || doubleeq(position, 1)))
return defaultRet;
}
return point;
}
bool Polygon::testCollision(const Vertex& point) const
{
double sum = 0;
for (size_t n = 0; n < points.size(); n++)
{
Vertex p1 = points[n] - point;
Vertex p2 = points[(n + 1) % points.size()] - point;
double nom = p1.length() * p2.length();
if (doubleeq(nom, 0))
return false;
sum += acos(p1.dotProduct(p2) / nom);
}
return doubleeq(sum, M_PI * 2);
}
bool Polygon::testCollision(const Vector& line, int flags) const
{
// Ensure method returns NaN vector if it fails so we can test it.
Vertex intersect = intersectPoint(line, flags);
if (!Vertex::isVertex(intersect))
return false;
return true;
}
bool Polygon::testCollision(const Polygon& polygon) const
{
if (&polygon == this)
return true;
if (points.size() < 3 || polygon.points.size() < 3)
return false;
Vertex thisNorm = this->plane().normal();
Vertex polyNorm = polygon.plane().normal();
if (thisNorm == polyNorm || thisNorm == -polyNorm)
return false;
for (size_t n = 0; n < points.size(); n++)
{
Vector line = Vector::diff(points[n], points[(n + 1) % points.size()]);
if (polygon.testCollision(line, ALLOW_NONE))
return true;
}
for (size_t n = 0; n < polygon.points.size(); n++)
{
Vector line = Vector::diff(polygon.points[n], polygon.points[(n + 1) % polygon.points.size()]);
if (this->testCollision(line, ALLOW_NONE))
return true;
}
return false;
}
Polygon::Polygon(const Plane & p)
{
auto dir = p.closestAxisToNormal();
auto tempV = dir == Vertex::unitZ ? -Vertex::unitY : -Vertex::unitZ;
auto normal = p.normal();
auto up = tempV.crossProduct(normal).normalize();
auto right = normal.crossProduct(up).normalize();
points = {
p.p1() + right + up,
p.p1() - right + up,
p.p1() - right - up,
p.p1() + right + up
};
auto orig = origin();
std::transform(points.begin(), points.end(), points.begin(), [&orig](Vertex v) {
return (v - orig).normalize() * 10'000'000.0 + orig;
});
}
Polygon::Polygon(const std::initializer_list<Vertex>& points)
: points(points)
{
}
| 21.692029
| 99
| 0.645899
|
Telefragged
|
a196bb870df02b117de37985f649874b412388f8
| 822
|
cpp
|
C++
|
algorithms/fillingJars.cpp
|
kosmaz/HackerRank
|
1107804c8213d169070a5529de26b97eb190e06c
|
[
"MIT"
] | 1
|
2015-03-21T20:08:28.000Z
|
2015-03-21T20:08:28.000Z
|
algorithms/fillingJars.cpp
|
kosmaz/HackerRank
|
1107804c8213d169070a5529de26b97eb190e06c
|
[
"MIT"
] | null | null | null |
algorithms/fillingJars.cpp
|
kosmaz/HackerRank
|
1107804c8213d169070a5529de26b97eb190e06c
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <vector>
using namespace std;
struct three{unsigned long a,b,k;};
unsigned long long averageOperations(vector<three> data,
unsigned long long N,
unsigned long long M)
{
long double average=0;
for(unsigned long long i=0; i<M; ++i)
{
unsigned long diff=data[i].b-data[i].a;
++diff;
average+=(long double)(data[i].k*diff);
}
return ((unsigned long long)(average/=N));
}
void Run()
{
//enter values of N && M
unsigned long long N,M;
cin>>N>>M;
//enter value of a,b && k for M operations
vector<three> data;
for(unsigned long long i=0; i<M; ++i)
{
three temp;
cin>>temp.a>>temp.b>>temp.k;
data.push_back(temp);
}
cout<<averageOperations(data,N,M)<<endl;
}
int main()
{
Run();
return 0;
}
| 20.04878
| 57
| 0.594891
|
kosmaz
|
a199cf405dac1df8ee49d0b116a55105db367ed5
| 8,393
|
hpp
|
C++
|
include/UnityEngine/Internal_DrawTextureArguments.hpp
|
Fernthedev/BeatSaber-Quest-Codegen
|
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
|
[
"Unlicense"
] | null | null | null |
include/UnityEngine/Internal_DrawTextureArguments.hpp
|
Fernthedev/BeatSaber-Quest-Codegen
|
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
|
[
"Unlicense"
] | null | null | null |
include/UnityEngine/Internal_DrawTextureArguments.hpp
|
Fernthedev/BeatSaber-Quest-Codegen
|
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
|
[
"Unlicense"
] | null | null | null |
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
#include "extern/beatsaber-hook/shared/utils/byref.hpp"
// Including type: System.ValueType
#include "System/ValueType.hpp"
// Including type: UnityEngine.Rect
#include "UnityEngine/Rect.hpp"
// Including type: UnityEngine.Color
#include "UnityEngine/Color.hpp"
// Including type: UnityEngine.Vector4
#include "UnityEngine/Vector4.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: UnityEngine
namespace UnityEngine {
// Forward declaring type: Texture
class Texture;
// Forward declaring type: Material
class Material;
}
// Completed forward declares
// Type namespace: UnityEngine
namespace UnityEngine {
// Size: 0xB8
#pragma pack(push, 1)
// WARNING Layout: Sequential may not be correctly taken into account!
// Autogenerated type: UnityEngine.Internal_DrawTextureArguments
// [TokenAttribute] Offset: FFFFFFFF
// [VisibleToOtherModulesAttribute] Offset: FFFFFFFF
struct Internal_DrawTextureArguments/*, public System::ValueType*/ {
public:
// public UnityEngine.Rect screenRect
// Size: 0x10
// Offset: 0x0
UnityEngine::Rect screenRect;
// Field size check
static_assert(sizeof(UnityEngine::Rect) == 0x10);
// public UnityEngine.Rect sourceRect
// Size: 0x10
// Offset: 0x10
UnityEngine::Rect sourceRect;
// Field size check
static_assert(sizeof(UnityEngine::Rect) == 0x10);
// public System.Int32 leftBorder
// Size: 0x4
// Offset: 0x20
int leftBorder;
// Field size check
static_assert(sizeof(int) == 0x4);
// public System.Int32 rightBorder
// Size: 0x4
// Offset: 0x24
int rightBorder;
// Field size check
static_assert(sizeof(int) == 0x4);
// public System.Int32 topBorder
// Size: 0x4
// Offset: 0x28
int topBorder;
// Field size check
static_assert(sizeof(int) == 0x4);
// public System.Int32 bottomBorder
// Size: 0x4
// Offset: 0x2C
int bottomBorder;
// Field size check
static_assert(sizeof(int) == 0x4);
// public UnityEngine.Color leftBorderColor
// Size: 0x10
// Offset: 0x30
UnityEngine::Color leftBorderColor;
// Field size check
static_assert(sizeof(UnityEngine::Color) == 0x10);
// public UnityEngine.Color rightBorderColor
// Size: 0x10
// Offset: 0x40
UnityEngine::Color rightBorderColor;
// Field size check
static_assert(sizeof(UnityEngine::Color) == 0x10);
// public UnityEngine.Color topBorderColor
// Size: 0x10
// Offset: 0x50
UnityEngine::Color topBorderColor;
// Field size check
static_assert(sizeof(UnityEngine::Color) == 0x10);
// public UnityEngine.Color bottomBorderColor
// Size: 0x10
// Offset: 0x60
UnityEngine::Color bottomBorderColor;
// Field size check
static_assert(sizeof(UnityEngine::Color) == 0x10);
// public UnityEngine.Color color
// Size: 0x10
// Offset: 0x70
UnityEngine::Color color;
// Field size check
static_assert(sizeof(UnityEngine::Color) == 0x10);
// public UnityEngine.Vector4 borderWidths
// Size: 0x10
// Offset: 0x80
UnityEngine::Vector4 borderWidths;
// Field size check
static_assert(sizeof(UnityEngine::Vector4) == 0x10);
// public UnityEngine.Vector4 cornerRadiuses
// Size: 0x10
// Offset: 0x90
UnityEngine::Vector4 cornerRadiuses;
// Field size check
static_assert(sizeof(UnityEngine::Vector4) == 0x10);
// public System.Boolean smoothCorners
// Size: 0x1
// Offset: 0xA0
bool smoothCorners;
// Field size check
static_assert(sizeof(bool) == 0x1);
// Padding between fields: smoothCorners and: pass
char __padding13[0x3] = {};
// public System.Int32 pass
// Size: 0x4
// Offset: 0xA4
int pass;
// Field size check
static_assert(sizeof(int) == 0x4);
// public UnityEngine.Texture texture
// Size: 0x8
// Offset: 0xA8
UnityEngine::Texture* texture;
// Field size check
static_assert(sizeof(UnityEngine::Texture*) == 0x8);
// public UnityEngine.Material mat
// Size: 0x8
// Offset: 0xB0
UnityEngine::Material* mat;
// Field size check
static_assert(sizeof(UnityEngine::Material*) == 0x8);
// Creating value type constructor for type: Internal_DrawTextureArguments
constexpr Internal_DrawTextureArguments(UnityEngine::Rect screenRect_ = {}, UnityEngine::Rect sourceRect_ = {}, int leftBorder_ = {}, int rightBorder_ = {}, int topBorder_ = {}, int bottomBorder_ = {}, UnityEngine::Color leftBorderColor_ = {}, UnityEngine::Color rightBorderColor_ = {}, UnityEngine::Color topBorderColor_ = {}, UnityEngine::Color bottomBorderColor_ = {}, UnityEngine::Color color_ = {}, UnityEngine::Vector4 borderWidths_ = {}, UnityEngine::Vector4 cornerRadiuses_ = {}, bool smoothCorners_ = {}, int pass_ = {}, UnityEngine::Texture* texture_ = {}, UnityEngine::Material* mat_ = {}) noexcept : screenRect{screenRect_}, sourceRect{sourceRect_}, leftBorder{leftBorder_}, rightBorder{rightBorder_}, topBorder{topBorder_}, bottomBorder{bottomBorder_}, leftBorderColor{leftBorderColor_}, rightBorderColor{rightBorderColor_}, topBorderColor{topBorderColor_}, bottomBorderColor{bottomBorderColor_}, color{color_}, borderWidths{borderWidths_}, cornerRadiuses{cornerRadiuses_}, smoothCorners{smoothCorners_}, pass{pass_}, texture{texture_}, mat{mat_} {}
// Creating interface conversion operator: operator System::ValueType
operator System::ValueType() noexcept {
return *reinterpret_cast<System::ValueType*>(this);
}
// Get instance field reference: public UnityEngine.Rect screenRect
UnityEngine::Rect& dyn_screenRect();
// Get instance field reference: public UnityEngine.Rect sourceRect
UnityEngine::Rect& dyn_sourceRect();
// Get instance field reference: public System.Int32 leftBorder
int& dyn_leftBorder();
// Get instance field reference: public System.Int32 rightBorder
int& dyn_rightBorder();
// Get instance field reference: public System.Int32 topBorder
int& dyn_topBorder();
// Get instance field reference: public System.Int32 bottomBorder
int& dyn_bottomBorder();
// Get instance field reference: public UnityEngine.Color leftBorderColor
UnityEngine::Color& dyn_leftBorderColor();
// Get instance field reference: public UnityEngine.Color rightBorderColor
UnityEngine::Color& dyn_rightBorderColor();
// Get instance field reference: public UnityEngine.Color topBorderColor
UnityEngine::Color& dyn_topBorderColor();
// Get instance field reference: public UnityEngine.Color bottomBorderColor
UnityEngine::Color& dyn_bottomBorderColor();
// Get instance field reference: public UnityEngine.Color color
UnityEngine::Color& dyn_color();
// Get instance field reference: public UnityEngine.Vector4 borderWidths
UnityEngine::Vector4& dyn_borderWidths();
// Get instance field reference: public UnityEngine.Vector4 cornerRadiuses
UnityEngine::Vector4& dyn_cornerRadiuses();
// Get instance field reference: public System.Boolean smoothCorners
bool& dyn_smoothCorners();
// Get instance field reference: public System.Int32 pass
int& dyn_pass();
// Get instance field reference: public UnityEngine.Texture texture
UnityEngine::Texture*& dyn_texture();
// Get instance field reference: public UnityEngine.Material mat
UnityEngine::Material*& dyn_mat();
}; // UnityEngine.Internal_DrawTextureArguments
#pragma pack(pop)
static check_size<sizeof(Internal_DrawTextureArguments), 176 + sizeof(UnityEngine::Material*)> __UnityEngine_Internal_DrawTextureArgumentsSizeCheck;
static_assert(sizeof(Internal_DrawTextureArguments) == 0xB8);
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(UnityEngine::Internal_DrawTextureArguments, "UnityEngine", "Internal_DrawTextureArguments");
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
| 44.643617
| 1,067
| 0.699869
|
Fernthedev
|
a19ab8c171610582786195a3635f1f91abab6bbd
| 646
|
hpp
|
C++
|
common/SoapyIfAddrs.hpp
|
kerel-fs/SoapyRemote
|
29a08cc7b50ab9bb1f9d1509dff2feaaff3ef95f
|
[
"BSL-1.0"
] | 89
|
2015-09-13T14:48:08.000Z
|
2022-03-26T17:32:18.000Z
|
common/SoapyIfAddrs.hpp
|
kerel-fs/SoapyRemote
|
29a08cc7b50ab9bb1f9d1509dff2feaaff3ef95f
|
[
"BSL-1.0"
] | 77
|
2015-09-17T05:50:45.000Z
|
2022-03-09T14:53:58.000Z
|
common/SoapyIfAddrs.hpp
|
kerel-fs/SoapyRemote
|
29a08cc7b50ab9bb1f9d1509dff2feaaff3ef95f
|
[
"BSL-1.0"
] | 24
|
2015-09-26T04:54:36.000Z
|
2022-02-05T15:10:08.000Z
|
// Copyright (c) 2018-2018 Josh Blum
// SPDX-License-Identifier: BSL-1.0
#pragma once
#include "SoapyRemoteConfig.hpp"
#include <string>
#include <vector>
struct SoapyIfAddr
{
SoapyIfAddr(void);
int ethno; //! The ethernet index
int ipVer; //! The ip protocol: 4 or 6
bool isUp; //! Is this link active?
bool isLoopback; //! Is this a loopback interface?
bool isMulticast; //! Does this interface support multicast?
std::string name; //! The interface name: ex eth0
std::string addr; //! The ip address as a string
};
//! Get a list of IF addrs
SOAPY_REMOTE_API std::vector<SoapyIfAddr> listSoapyIfAddrs(void);
| 28.086957
| 65
| 0.693498
|
kerel-fs
|
a19ccb7eb6ad863b1002be875fb337a6d398ffdd
| 587
|
cpp
|
C++
|
Il2Native.Logic/NativeImplementations/System.Private.CoreLib/System/Diagnostics/StackTrace.cpp
|
Vinay1705/cs2cpp
|
d07d3206fb57edb959df8536562909a4d516e359
|
[
"MIT"
] | 192
|
2016-03-23T04:33:24.000Z
|
2022-03-28T14:41:06.000Z
|
Il2Native.Logic/NativeImplementations/System.Private.CoreLib/System/Diagnostics/StackTrace.cpp
|
Vinay1705/cs2cpp
|
d07d3206fb57edb959df8536562909a4d516e359
|
[
"MIT"
] | 9
|
2017-03-08T14:45:16.000Z
|
2021-09-06T09:28:47.000Z
|
Il2Native.Logic/NativeImplementations/System.Private.CoreLib/System/Diagnostics/StackTrace.cpp
|
Vinay1705/cs2cpp
|
d07d3206fb57edb959df8536562909a4d516e359
|
[
"MIT"
] | 56
|
2016-03-22T20:37:08.000Z
|
2022-03-28T12:20:47.000Z
|
#include "System.Private.CoreLib.h"
namespace CoreLib { namespace System { namespace Diagnostics {
namespace _ = ::CoreLib::System::Diagnostics;
// Method : System.Diagnostics.StackTrace.GetStackFramesInternal(System.Diagnostics.StackFrameHelper, int, bool, System.Exception)
void StackTrace::GetStackFramesInternal(_::StackFrameHelper* sfh, int32_t iSkip, bool fNeedFileInfo, ::CoreLib::System::Exception* e)
{
throw 3221274624U;
}
}}}
namespace CoreLib { namespace System { namespace Diagnostics {
namespace _ = ::CoreLib::System::Diagnostics;
}}}
| 36.6875
| 137
| 0.735945
|
Vinay1705
|
a19fec56457ddb7d51ea5e3314f73962b0615502
| 423
|
cpp
|
C++
|
UWPSamples/System/GamepadCppWinRT_UWP/pch.cpp
|
ComputeWorks/Xbox-ATG-Samples
|
6b88d6a03cf1efae7007a928713896863ec04ca5
|
[
"MIT"
] | 298
|
2019-05-09T20:54:35.000Z
|
2022-03-31T20:10:51.000Z
|
UWPSamples/System/GamepadCppWinRT_UWP/pch.cpp
|
ComputeWorks/Xbox-ATG-Samples
|
6b88d6a03cf1efae7007a928713896863ec04ca5
|
[
"MIT"
] | 14
|
2019-07-07T15:25:15.000Z
|
2022-02-05T02:44:29.000Z
|
UWPSamples/System/GamepadCppWinRT_UWP/pch.cpp
|
ComputeWorks/Xbox-ATG-Samples
|
6b88d6a03cf1efae7007a928713896863ec04ca5
|
[
"MIT"
] | 137
|
2019-05-07T20:58:34.000Z
|
2022-03-30T08:01:34.000Z
|
//--------------------------------------------------------------------------------------
// pch.cpp
//
// Include the standard header and generate the precompiled header.
//
// Advanced Technology Group (ATG)
// Copyright (C) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------
#pragma warning(disable : 4996)
#include "pch.h"
| 32.538462
| 90
| 0.399527
|
ComputeWorks
|
a1a1e3d9cb16da0a66c586b22636a9fea28c5acf
| 841
|
cc
|
C++
|
src/quipper/quipper_lib_test.cc
|
cervantesyu/perf_data_converter
|
5fe21942c1db6625963e657f458fea5c30af40e2
|
[
"BSD-3-Clause"
] | null | null | null |
src/quipper/quipper_lib_test.cc
|
cervantesyu/perf_data_converter
|
5fe21942c1db6625963e657f458fea5c30af40e2
|
[
"BSD-3-Clause"
] | 1
|
2019-10-18T07:50:07.000Z
|
2019-10-19T02:14:40.000Z
|
src/quipper/quipper_lib_test.cc
|
cervantesyu/perf_data_converter
|
5fe21942c1db6625963e657f458fea5c30af40e2
|
[
"BSD-3-Clause"
] | null | null | null |
#include "quipper_lib.h"
#include "compat/test.h"
namespace {
TEST(QuipperLibTest, ValidOldPerfCommandLine) {
int argc = 6;
const char* argv[] = {"quipper", "10", "perf", "record", "-e", "cycles"};
std::vector<string> perf_args;
int perf_duration = 0;
EXPECT_TRUE(ParseOldPerfArguments(argc, argv, &perf_duration, &perf_args));
EXPECT_EQ(10, perf_duration);
for (int i = 0; i < perf_args.size(); ++i) {
EXPECT_EQ(argv[i + 2], perf_args[i]);
}
}
TEST(QuipperLibTest, InValidOldPerfCommandLine) {
int argc = 6;
const char* argv[] = {
"quipper", "--duration", "10", "--perf_path",
"perf", "--output_file", "file", "-- record -e cycles"};
std::vector<string> perf_args;
int perf_duration = 0;
EXPECT_FALSE(ParseOldPerfArguments(argc, argv, &perf_duration, &perf_args));
}
} // namespace
| 26.28125
| 78
| 0.646849
|
cervantesyu
|
a1a6c6f24b6a5c64c43f463d70b3c15476546b26
| 8,561
|
cpp
|
C++
|
src/CryptoNoteCore/Transactions/TransactionUtils.cpp
|
ElSamaritan/blockchain-OLD
|
ca3422c8873613226db99b7e6735c5ea1fac9f1a
|
[
"Apache-2.0"
] | null | null | null |
src/CryptoNoteCore/Transactions/TransactionUtils.cpp
|
ElSamaritan/blockchain-OLD
|
ca3422c8873613226db99b7e6735c5ea1fac9f1a
|
[
"Apache-2.0"
] | null | null | null |
src/CryptoNoteCore/Transactions/TransactionUtils.cpp
|
ElSamaritan/blockchain-OLD
|
ca3422c8873613226db99b7e6735c5ea1fac9f1a
|
[
"Apache-2.0"
] | null | null | null |
// Copyright (c) 2012-2017, The CryptoNote developers, The Bytecoin developers
//
// This file is part of Bytecoin.
//
// Bytecoin is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Bytecoin is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with Bytecoin. If not, see <http://www.gnu.org/licenses/>.
#include "CryptoNoteCore/Transactions/TransactionUtils.h"
#include <unordered_set>
#include <numeric>
#include <iterator>
#include <exception>
#include <algorithm>
#include <Xi/Exceptions.hpp>
#include <crypto/crypto.h>
#include "CryptoNoteCore/Account.h"
#include "CryptoNoteCore/CryptoNoteFormatUtils.h"
#include "CryptoNoteCore/Transactions/TransactionExtra.h"
using namespace Crypto;
namespace CryptoNote {
bool checkInputsKeyimagesDiff(const CryptoNote::TransactionPrefix& tx) {
std::unordered_set<Crypto::KeyImage> ki;
for (const auto& in : tx.inputs) {
if (auto keyInput = std::get_if<KeyInput>(&in)) {
if (!ki.insert(keyInput->keyImage).second)
return false;
}
}
return true;
}
// TransactionInput helper functions
size_t getRequiredSignaturesCount(const TransactionInput& in) {
if (auto keyInput = std::get_if<KeyInput>(&in)) {
return keyInput->outputIndices.size();
}
return 0;
}
uint64_t getTransactionInputAmount(const TransactionInput& in) {
if (auto keyInput = std::get_if<KeyInput>(&in)) {
return keyInput->amount;
} else {
return 0;
}
}
uint64_t getTransactionInputAmount(const Transaction& transaction) {
return std::accumulate(transaction.inputs.begin(), transaction.inputs.end(), 0ULL,
[](uint64_t acc, const auto& input) { return acc + getTransactionInputAmount(input); });
}
uint64_t getTransactionOutputAmount(const TransactionOutput& out) {
if (const auto amountOutput = std::get_if<TransactionAmountOutput>(std::addressof(out))) {
return amountOutput->amount;
} else {
return 0ULL;
}
}
uint64_t getTransactionOutputAmount(const Transaction& transaction) {
return std::accumulate(transaction.outputs.begin(), transaction.outputs.end(), 0ULL,
[](uint64_t acc, const auto& out) { return acc + getTransactionOutputAmount(out); });
}
boost::optional<KeyImage> getTransactionInputKeyImage(const TransactionInput& input) {
if (auto keyInput = std::get_if<KeyInput>(&input)) {
return boost::optional<KeyImage>{keyInput->keyImage};
} else {
return boost::optional<KeyImage>{};
}
}
std::vector<KeyImage> getTransactionKeyImages(const Transaction& transaction) {
std::vector<KeyImage> reval{};
reval.reserve(transaction.inputs.size());
for (const auto& input : transaction.inputs) {
auto keyImage = getTransactionInputKeyImage(input);
if (keyImage) {
reval.push_back(*keyImage);
}
}
return reval;
}
std::vector<PublicKey> getTransactionOutputKeys(const Transaction& transaction) {
std::vector<PublicKey> keys;
keys.reserve(transaction.outputs.size());
for (const auto& output : transaction.outputs) {
const auto amountOutput = std::get_if<TransactionAmountOutput>(std::addressof(output));
if (amountOutput == nullptr) {
continue;
}
const auto keyTarget = std::get_if<KeyOutput>(std::addressof(amountOutput->target));
if (keyTarget == nullptr) {
continue;
}
keys.emplace_back(keyTarget->key);
}
return keys;
}
TransactionTypes::InputType getTransactionInputType(const TransactionInput& in) {
if (std::holds_alternative<KeyInput>(in)) {
return TransactionTypes::InputType::Key;
}
if (std::holds_alternative<BaseInput>(in)) {
return TransactionTypes::InputType::Generating;
}
return TransactionTypes::InputType::Invalid;
}
const TransactionInput& getInputChecked(const CryptoNote::TransactionPrefix& transaction, size_t index) {
if (transaction.inputs.size() <= index) {
throw std::runtime_error("Transaction input index out of range");
}
return transaction.inputs[index];
}
const TransactionInput& getInputChecked(const CryptoNote::TransactionPrefix& transaction, size_t index,
TransactionTypes::InputType type) {
const auto& input = getInputChecked(transaction, index);
if (getTransactionInputType(input) != type) {
throw std::runtime_error("Unexpected transaction input type");
}
return input;
}
// TransactionOutput helper functions
TransactionTypes::OutputType getTransactionOutputType(const TransactionOutput& out) {
if (std::holds_alternative<TransactionAmountOutput>(out)) {
return TransactionTypes::OutputType::Amount;
}
return TransactionTypes::OutputType::Invalid;
}
TransactionTypes::OutputTargetType getTransactionOutputTargetType(const TransactionOutputTarget& out) {
if (std::holds_alternative<KeyOutput>(out)) {
return TransactionTypes::OutputTargetType::Key;
}
return TransactionTypes::OutputTargetType::Invalid;
}
const TransactionOutput& getOutputChecked(const CryptoNote::TransactionPrefix& transaction, size_t index) {
if (transaction.outputs.size() <= index) {
throw std::runtime_error("Transaction output index out of range");
}
return transaction.outputs[index];
}
const TransactionOutputTarget& getOutputTargetChecked(const TransactionOutput& out) {
if (!std::holds_alternative<TransactionAmountOutput>(out)) {
throw std::runtime_error{"Unexpected transaction output type"};
}
return std::get<TransactionAmountOutput>(out).target;
}
const TransactionOutput& getOutputChecked(const CryptoNote::TransactionPrefix& transaction, size_t index,
TransactionTypes::OutputType outType,
TransactionTypes::OutputTargetType type) {
const auto& output = getOutputChecked(transaction, index);
const auto outputType = getTransactionOutputType(output);
if (outputType != outType) {
throw std::runtime_error{"Unexpected transaction output type"};
}
const auto& target = getOutputTargetChecked(output);
if (getTransactionOutputTargetType(target) != type) {
throw std::runtime_error("Unexpected transaction output target type");
}
return output;
}
bool isOutToKey(const Crypto::PublicKey& spendPublicKey, const Crypto::PublicKey& outKey,
const Crypto::KeyDerivation& derivation, size_t keyIndex) {
Crypto::PublicKey pk;
derive_public_key(derivation, keyIndex, spendPublicKey, pk);
return pk == outKey;
}
bool findOutputsToAccount(const CryptoNote::TransactionPrefix& transaction, const AccountPublicAddress& addr,
const SecretKey& viewSecretKey, std::vector<uint32_t>& out, uint64_t& amount) {
using namespace Xi;
AccountKeys keys;
keys.address = addr;
// only view secret key is used, spend key is not needed
keys.viewSecretKey = viewSecretKey;
::Crypto::PublicKey txPubKey = getTransactionPublicKeyFromExtra(transaction.extra);
amount = 0;
size_t keyIndex = 0;
uint32_t outputIndex = 0;
::Crypto::KeyDerivation derivation;
generate_key_derivation(txPubKey, keys.viewSecretKey, derivation);
for (const TransactionOutput& o : transaction.outputs) {
exceptional_if_not<InvalidVariantTypeError>(std::holds_alternative<TransactionAmountOutput>(o));
const auto& amountOutput = std::get<TransactionAmountOutput>(o);
exceptional_if_not<InvalidVariantTypeError>(std::holds_alternative<KeyOutput>(amountOutput.target));
const auto& keyOutput = std::get<KeyOutput>(amountOutput.target);
if (is_out_to_acc(keys, keyOutput, derivation, keyIndex)) {
out.push_back(outputIndex);
amount += amountOutput.amount;
}
++keyIndex;
++outputIndex;
}
return true;
}
std::vector<uint32_t> getTransactionInputIndices(const KeyInput& input) {
std::vector<uint32_t> indices{};
if (input.outputIndices.empty())
return indices;
indices.resize(input.outputIndices.size());
indices[0] = input.outputIndices[0];
for (size_t i = 1; i < input.outputIndices.size(); ++i) {
indices[i] = indices[i - 1] + input.outputIndices[i];
}
return indices;
}
} // namespace CryptoNote
| 33.311284
| 113
| 0.726667
|
ElSamaritan
|
a1adbc63c0c8c3af12f36f286e651b630b745e9b
| 26,287
|
cpp
|
C++
|
unit-tests/co/test-tpdo-sdo.cpp
|
DroidDrive/lely-core
|
2ec4560f513264a53d2afaedecdae4a49a39023c
|
[
"Apache-2.0"
] | 1
|
2021-10-02T21:08:05.000Z
|
2021-10-02T21:08:05.000Z
|
unit-tests/co/test-tpdo-sdo.cpp
|
DroidDrive/lely-core
|
2ec4560f513264a53d2afaedecdae4a49a39023c
|
[
"Apache-2.0"
] | null | null | null |
unit-tests/co/test-tpdo-sdo.cpp
|
DroidDrive/lely-core
|
2ec4560f513264a53d2afaedecdae4a49a39023c
|
[
"Apache-2.0"
] | null | null | null |
/**@file
* This file is part of the CANopen Library Unit Test Suite.
*
* @copyright 2020 N7 Space Sp. z o.o.
*
* Unit Test Suite was developed under a programme of,
* and funded by, the European Space Agency.
*
*
* 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.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <memory>
#include <CppUTest/TestHarness.h>
#include <lely/co/csdo.h>
#include <lely/co/tpdo.h>
#include <lely/co/sdo.h>
#include <libtest/allocators/default.hpp>
#include <libtest/tools/lely-cpputest-ext.hpp>
#include <libtest/tools/lely-unit-test.hpp>
#include "holder/dev.hpp"
#include "holder/obj.hpp"
TEST_BASE(CO_SdoTpdoBase) {
TEST_BASE_SUPER(CO_SdoTpdoBase);
Allocators::Default allocator;
const co_unsigned8_t DEV_ID = 0x01u;
const co_unsigned16_t TPDO_NUM = 0x0001u;
co_dev_t* dev = nullptr;
can_net_t* net = nullptr;
co_tpdo_t* tpdo = nullptr;
std::unique_ptr<CoDevTHolder> dev_holder;
std::unique_ptr<CoObjTHolder> obj1800;
std::unique_ptr<CoObjTHolder> obj1a00;
void CreateObjInDev(std::unique_ptr<CoObjTHolder> & obj_holder,
co_unsigned16_t idx) {
obj_holder.reset(new CoObjTHolder(idx));
CHECK(obj_holder->Get() != nullptr);
CHECK_EQUAL(0, co_dev_insert_obj(dev, obj_holder->Take()));
}
void SetPdoCommCobid(const co_unsigned32_t cobid) {
co_sub_t* const sub_comm_cobid = co_dev_find_sub(dev, 0x1800u, 0x01u);
CHECK(sub_comm_cobid != nullptr);
co_sub_set_val_u32(sub_comm_cobid, cobid);
}
void RestartTPDO() {
co_tpdo_stop(tpdo);
co_tpdo_start(tpdo);
}
TEST_SETUP() {
LelyUnitTest::DisableDiagnosticMessages();
net = can_net_create(allocator.ToAllocT());
CHECK(net != nullptr);
dev_holder.reset(new CoDevTHolder(DEV_ID));
dev = dev_holder->Get();
CHECK(dev != nullptr);
CreateObjInDev(obj1800, 0x1800u);
CreateObjInDev(obj1a00, 0x1a00u);
// 0x00 - highest sub-index supported
obj1800->InsertAndSetSub(0x00u, CO_DEFTYPE_UNSIGNED8,
co_unsigned8_t(0x02u));
// 0x01 - COB-ID used by TPDO
obj1800->InsertAndSetSub(0x01u, CO_DEFTYPE_UNSIGNED32,
co_unsigned32_t(DEV_ID));
// 0x02 - transmission type
obj1800->InsertAndSetSub(0x02u, CO_DEFTYPE_UNSIGNED8,
co_unsigned8_t(0xfeu)); // event-driven
tpdo = co_tpdo_create(net, dev, TPDO_NUM);
CHECK(tpdo != nullptr);
CoCsdoDnCon::Clear();
}
TEST_TEARDOWN() {
co_tpdo_destroy(tpdo);
dev_holder.reset();
can_net_destroy(net);
}
};
TEST_GROUP_BASE(CO_SdoTpdo1800, CO_SdoTpdoBase) {
int clang_format_fix = 0; // unused
void Insert1800Values() {
// adjust highest subindex supported
co_sub_t* const sub = co_dev_find_sub(dev, 0x1800u, 0x00u);
CHECK(sub != nullptr);
co_sub_set_val_u8(sub, 0x06u);
// 0x03 - inhibit time
obj1800->InsertAndSetSub(0x03u, CO_DEFTYPE_UNSIGNED16,
co_unsigned16_t(0x0000u)); // n*100 us
// 0x04 - reserved (compatibility entry)
obj1800->InsertAndSetSub(0x04u, CO_DEFTYPE_UNSIGNED8,
co_unsigned8_t(0x00u));
// 0x05 - event-timer
obj1800->InsertAndSetSub(0x05u, CO_DEFTYPE_UNSIGNED16,
co_unsigned16_t(0x0000u)); // ms
// 0x06 - sync value
obj1800->InsertAndSetSub(0x06u, CO_DEFTYPE_UNSIGNED8,
co_unsigned8_t(0x00u));
}
TEST_SETUP() {
TEST_BASE_SETUP();
Insert1800Values();
co_tpdo_start(tpdo);
}
TEST_TEARDOWN() {
co_tpdo_stop(tpdo);
TEST_BASE_TEARDOWN();
}
};
// given: valid TPDO
// when: co_1800_dn_ind()
// then: CO_SDO_AC_TYPE_LEN_HI abort code is returned
TEST(CO_SdoTpdo1800, Co1800DnInd_TooLongData) {
const co_unsigned16_t data = 0;
const auto ret =
co_dev_dn_val_req(dev, 0x1800u, 0x00u, CO_DEFTYPE_UNSIGNED16, &data,
nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(CO_SDO_AC_TYPE_LEN_HI, CoCsdoDnCon::ac);
}
// given: valid TPDO
// when: co_1800_dn_ind()
// then: CO_SDO_AC_NO_WRITE abort code is returned
TEST(CO_SdoTpdo1800, Co1800DnInd_HighestSubIdxSupported) {
const co_unsigned8_t num_of_elems = 0x7fu;
const auto ret =
co_dev_dn_val_req(dev, 0x1800u, 0x00u, CO_DEFTYPE_UNSIGNED8,
&num_of_elems, nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(CO_SDO_AC_NO_WRITE, CoCsdoDnCon::ac);
}
// given: valid TPDO
// when: co_1800_dn_ind()
// then: 0 abort code is returned
TEST(CO_SdoTpdo1800, Co1800DnInd_CobidSameAsPrevious) {
const co_unsigned32_t cobid = DEV_ID;
const auto ret =
co_dev_dn_val_req(dev, 0x1800u, 0x01u, CO_DEFTYPE_UNSIGNED32, &cobid,
nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(0, CoCsdoDnCon::ac);
}
// given: valid TPDO
// when: co_1800_dn_ind()
// then: CO_SDO_AC_PARAM_VAL abort code is returned
TEST(CO_SdoTpdo1800, Co1800DnInd_CobidValidToValid_NewCanId) {
SetPdoCommCobid(DEV_ID);
RestartTPDO();
const co_unsigned32_t cobid = DEV_ID + 1u;
const auto ret =
co_dev_dn_val_req(dev, 0x1800u, 0x01u, CO_DEFTYPE_UNSIGNED32, &cobid,
nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(CO_SDO_AC_PARAM_VAL, CoCsdoDnCon::ac);
}
// given: invalid TPDO
// when: co_1800_dn_ind()
// then: 0 abort code is returned
TEST(CO_SdoTpdo1800, Co1800DnInd_CobidInvalidToValid_NewCanId) {
SetPdoCommCobid(DEV_ID | CO_PDO_COBID_VALID);
RestartTPDO();
const co_unsigned32_t cobid = DEV_ID + 1u;
const auto ret =
co_dev_dn_val_req(dev, 0x1800u, 0x01u, CO_DEFTYPE_UNSIGNED32, &cobid,
nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(0, CoCsdoDnCon::ac);
}
// given: valid TPDO
// when: co_1800_dn_ind()
// then: 0 abort code is returned
TEST(CO_SdoTpdo1800, Co1800DnInd_CobidValidToValid_FrameBit) {
const co_unsigned32_t cobid = DEV_ID | CO_PDO_COBID_FRAME;
const auto ret =
co_dev_dn_val_req(dev, 0x1800u, 0x01u, CO_DEFTYPE_UNSIGNED32, &cobid,
nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(0, CoCsdoDnCon::ac);
}
// given: valid TPDO
// when: COB-ID with frame bit and CO_PDO_COBID_VALID set is downloaded
// then: CO_SDO_AC_PARAM_VAL abort code is returned
TEST(CO_SdoTpdo1800, Co1800DnInd_CobidValidToInvalid_ExtendedId_NoFrameBit) {
co_unsigned32_t cobid = DEV_ID | (1u << 28u) | CO_PDO_COBID_VALID;
const auto ret =
co_dev_dn_val_req(dev, 0x1800u, 0x01u, CO_DEFTYPE_UNSIGNED32, &cobid,
nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(CO_SDO_AC_PARAM_VAL, CoCsdoDnCon::ac);
}
// given: valid TPDO
// when: COB-ID with CO_PDO_COBID_VALID set is downloaded
// then: 0 abort code is returned
TEST(CO_SdoTpdo1800, Co1800DnInd_CobidValidToInvalid) {
const co_unsigned32_t cobid = DEV_ID | CO_PDO_COBID_VALID;
const auto ret =
co_dev_dn_val_req(dev, 0x1800u, 0x01u, CO_DEFTYPE_UNSIGNED32, &cobid,
nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(0, CoCsdoDnCon::ac);
}
// given: valid TPDO
// when: co_1800_dn_ind()
// then: 0 abort code is returned
TEST(CO_SdoTpdo1800, Co1800DnInd_TransmissionTypeSameAsPrevious) {
const co_unsigned8_t transmission_type = 0xfeu;
const auto ret = co_dev_dn_val_req(dev, 0x1800u, 0x02u, CO_DEFTYPE_UNSIGNED8,
&transmission_type, nullptr,
CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(0, CoCsdoDnCon::ac);
}
// given: valid TPDO
// when: co_1800_dn_ind()
// then: CO_SDO_AC_PARAM_VAL abort code is returned
TEST(CO_SdoTpdo1800, Co1800DnInd_TransmissionTypeReserved) {
SetPdoCommCobid(DEV_ID | CO_PDO_COBID_RTR);
RestartTPDO();
const co_unsigned8_t transmission_type = 0xf1u;
const auto ret = co_dev_dn_val_req(dev, 0x1800u, 0x02u, CO_DEFTYPE_UNSIGNED8,
&transmission_type, nullptr,
CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(CO_SDO_AC_PARAM_VAL, CoCsdoDnCon::ac);
}
// given: valid TPDO
// when: co_1800_dn_ind()
// then: CO_SDO_AC_PARAM_VAL abort code is returned
TEST(CO_SdoTpdo1800, Co1800DnInd_TransmissionType_SynchronousRTR_RTRBitSet) {
SetPdoCommCobid(DEV_ID | CO_PDO_COBID_RTR);
RestartTPDO();
const co_unsigned8_t transmission_type = 0xfcu;
const auto ret = co_dev_dn_val_req(dev, 0x1800u, 0x02u, CO_DEFTYPE_UNSIGNED8,
&transmission_type, nullptr,
CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(CO_SDO_AC_PARAM_VAL, CoCsdoDnCon::ac);
}
// given: valid TPDO
// when: co_1800_dn_ind()
// then: CO_SDO_AC_PARAM_VAL abort code is returned
TEST(CO_SdoTpdo1800, Co1800DnInd_TransmissionType_EventDrivenRTR_RTRBitSet) {
SetPdoCommCobid(DEV_ID | CO_PDO_COBID_RTR);
RestartTPDO();
const co_unsigned8_t transmission_type = 0xfdu;
const auto ret = co_dev_dn_val_req(dev, 0x1800u, 0x02u, CO_DEFTYPE_UNSIGNED8,
&transmission_type, nullptr,
CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(CO_SDO_AC_PARAM_VAL, CoCsdoDnCon::ac);
}
// given: valid TPDO
// when: co_1800_dn_ind()
// then: CO_SDO_AC_PARAM_VAL abort code is returned
TEST(CO_SdoTpdo1800, Co1800DnInd_TransmissionType_RTROnly_RTRBitNotSet) {
const co_unsigned8_t transmission_type = 0xfdu;
const auto ret = co_dev_dn_val_req(dev, 0x1800u, 0x02u, CO_DEFTYPE_UNSIGNED8,
&transmission_type, nullptr,
CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(0, CoCsdoDnCon::ac);
}
// given: valid TPDO
// when: co_1800_dn_ind()
// then: 0 abort code is returned
TEST(CO_SdoTpdo1800, Co1800DnInd_TransmissionTypeMax) {
const co_unsigned8_t transmission_type = 0xffu;
const auto ret = co_dev_dn_val_req(dev, 0x1800u, 0x02u, CO_DEFTYPE_UNSIGNED8,
&transmission_type, nullptr,
CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(0, CoCsdoDnCon::ac);
}
// given: valid TPDO
// when: co_1800_dn_ind()
// then: 0 abort code is returned
TEST(CO_SdoTpdo1800, Co1800DnInd_TransmissionType) {
const co_unsigned8_t transmission_type = 0x35u;
const auto ret = co_dev_dn_val_req(dev, 0x1800u, 0x02u, CO_DEFTYPE_UNSIGNED8,
&transmission_type, nullptr,
CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(0, CoCsdoDnCon::ac);
}
// given: invalid TPDO
// when: co_1800_dn_ind()
// then: 0 abort code is returned
TEST(CO_SdoTpdo1800, Co1800DnInd_InhibitTimeSameAsPrevious) {
SetPdoCommCobid(DEV_ID | CO_PDO_COBID_VALID);
RestartTPDO();
const co_unsigned16_t inhibit_time = 0x0000u;
const auto ret =
co_dev_dn_val_req(dev, 0x1800u, 0x03u, CO_DEFTYPE_UNSIGNED16,
&inhibit_time, nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(0, CoCsdoDnCon::ac);
}
// given: valid TPDO
// when: co_1800_dn_ind()
// then: CO_SDO_AC_PARAM_VAL abort code is returned
TEST(CO_SdoTpdo1800, Co1800DnInd_InhibitTimeValidTPDO) {
const co_unsigned16_t inhibit_time = 0x0001u;
const auto ret =
co_dev_dn_val_req(dev, 0x1800u, 0x03u, CO_DEFTYPE_UNSIGNED16,
&inhibit_time, nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(CO_SDO_AC_PARAM_VAL, CoCsdoDnCon::ac);
}
// given: invalid TPDO
// when: co_1800_dn_ind()
// then: 0 abort code is returned
TEST(CO_SdoTpdo1800, Co1800DnInd_InhibitTime) {
SetPdoCommCobid(DEV_ID | CO_PDO_COBID_VALID);
RestartTPDO();
const co_unsigned16_t inhibit_time = 0x0003u;
const auto ret =
co_dev_dn_val_req(dev, 0x1800u, 0x03u, CO_DEFTYPE_UNSIGNED16,
&inhibit_time, nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(0, CoCsdoDnCon::ac);
}
// given: valid TPDO
// when: co_1800_dn_ind()
// then: CO_SDO_AC_NO_SUB abort code is returned
TEST(CO_SdoTpdo1800, Co1800DnInd_CompatibilityEntry) {
const co_unsigned8_t compat = 0x44u;
const auto ret =
co_dev_dn_val_req(dev, 0x1800u, 0x04u, CO_DEFTYPE_UNSIGNED8, &compat,
nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(CO_SDO_AC_NO_SUB, CoCsdoDnCon::ac);
}
// given: valid TPDO
// when: co_1800_dn_ind()
// then: 0 abort code is returned
TEST(CO_SdoTpdo1800, Co1800DnInd_EventTimerSameAsPrevious) {
const co_unsigned16_t event_timer = 0x0000u;
const auto ret =
co_dev_dn_val_req(dev, 0x1800u, 0x05u, CO_DEFTYPE_UNSIGNED16,
&event_timer, nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(0, CoCsdoDnCon::ac);
}
// given: valid TPDO
// when: co_1800_dn_ind()
// then: 0 abort code is returned
TEST(CO_SdoTpdo1800, Co1800DnInd_EventTimer) {
const co_unsigned16_t event_timer = 0x3456u;
const auto ret =
co_dev_dn_val_req(dev, 0x1800u, 0x05u, CO_DEFTYPE_UNSIGNED16,
&event_timer, nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(0, CoCsdoDnCon::ac);
}
// given: valid TPDO
// when: co_1800_dn_ind()
// then: 0 abort code is returned
TEST(CO_SdoTpdo1800, Co1800DnInd_SyncSameAsPrevious) {
const co_unsigned8_t sync = 0x00u;
const auto ret =
co_dev_dn_val_req(dev, 0x1800u, 0x06u, CO_DEFTYPE_UNSIGNED8, &sync,
nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(0, CoCsdoDnCon::ac);
}
// given: valid TPDO
// when: co_1800_dn_ind()
// then: CO_SDO_AC_PARAM_VAL abort code is returned
TEST(CO_SdoTpdo1800, Co1800DnInd_SyncNewValue_TPDOValid) {
const co_unsigned8_t sync = 0x01u;
const auto ret =
co_dev_dn_val_req(dev, 0x1800u, 0x06u, CO_DEFTYPE_UNSIGNED8, &sync,
nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(CO_SDO_AC_PARAM_VAL, CoCsdoDnCon::ac);
}
// given: invalid TPDO
// when: co_1800_dn_ind()
// then: 0 abort code is returned
TEST(CO_SdoTpdo1800, Co1800DnInd_SyncNewValue_TPDOInvalid) {
SetPdoCommCobid(DEV_ID | CO_PDO_COBID_VALID);
RestartTPDO();
const co_unsigned8_t sync = 0x01u;
const auto ret =
co_dev_dn_val_req(dev, 0x1800u, 0x06u, CO_DEFTYPE_UNSIGNED8, &sync,
nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(0, CoCsdoDnCon::ac);
}
TEST_GROUP_BASE(CO_SdoTpdo1a00, CO_SdoTpdoBase) {
std::unique_ptr<CoObjTHolder> obj2021;
void Insert1a00Values() {
// 0x00 - number of mapped application objects in PDO
obj1a00->InsertAndSetSub(0x00, CO_DEFTYPE_UNSIGNED8,
co_unsigned8_t(CO_PDO_NUM_MAPS));
// 0x01-0x40 - application objects
for (co_unsigned8_t i = 0x01u; i <= CO_PDO_NUM_MAPS; ++i) {
obj1a00->InsertAndSetSub(i, CO_DEFTYPE_UNSIGNED32, co_unsigned32_t(0));
}
}
void Set1a00Sub1Mapping(co_unsigned32_t mapping) {
co_sub_t* const sub = co_dev_find_sub(dev, 0x1a00u, 0x01u);
co_sub_set_val_u32(sub, mapping);
}
void Insert2021Values() {
assert(obj2021->Get());
obj2021->InsertAndSetSub(0x00u, CO_DEFTYPE_UNSIGNED32,
co_unsigned32_t(0xdeadbeefu));
co_sub_t* sub2021 = obj2021->GetLastSub();
co_sub_set_access(sub2021, CO_ACCESS_RW);
co_sub_set_pdo_mapping(sub2021, 1);
}
void SetNumOfMappings(co_unsigned8_t mappings_num) {
co_sub_t* const sub_map_n = co_dev_find_sub(dev, 0x1a00u, 0x00u);
co_sub_set_val_u8(sub_map_n, mappings_num);
}
TEST_SETUP() {
TEST_BASE_SETUP();
Insert1a00Values();
co_tpdo_start(tpdo);
CoCsdoDnCon::Clear();
}
TEST_TEARDOWN() {
co_tpdo_stop(tpdo);
TEST_BASE_TEARDOWN();
}
};
// given: invalid TPDO
// when: co_1a00_dn_ind()
// then: CO_SDO_AC_PDO_LEN abort code is returned
TEST(CO_SdoTpdo1a00, Co1a00DnInd_NumOfMappingsLenGreaterThanMax) {
SetPdoCommCobid(DEV_ID | CO_PDO_COBID_VALID);
Set1a00Sub1Mapping(0x202100ffu);
RestartTPDO();
// object which could be mapped
CreateObjInDev(obj2021, 0x2021u);
Insert2021Values();
const co_unsigned8_t num_of_mappings = 1u;
const auto ret =
co_dev_dn_val_req(dev, 0x1a00u, 0x00u, CO_DEFTYPE_UNSIGNED8,
&num_of_mappings, nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(CO_SDO_AC_PDO_LEN, CoCsdoDnCon::ac);
}
// given: invalid TPDO
// when: co_1a00_dn_ind()
// then: CO_SDO_AC_PARAM_VAL abort code is returned
TEST(CO_SdoTpdo1a00, Co1a00DnInd_EmptyMapping) {
SetPdoCommCobid(DEV_ID | CO_PDO_COBID_VALID);
Set1a00Sub1Mapping(0x00000000u);
RestartTPDO();
// object which could be mapped
CreateObjInDev(obj2021, 0x2021u);
Insert2021Values();
const co_unsigned8_t num_of_mappings = 1u;
const auto ret =
co_dev_dn_val_req(dev, 0x1a00u, 0x00u, CO_DEFTYPE_UNSIGNED8,
&num_of_mappings, nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(0, CoCsdoDnCon::ac);
}
// given: valid TPDO
// when: too long value is downloaded
// then: CO_SDO_AC_TYPE_LEN_HI abort code is returned
TEST(CO_SdoTpdo1a00, Co1a00DnInd_NumOfMappingsRequestFailed) {
const co_unsigned32_t data = 0;
const auto ret =
co_dev_dn_val_req(dev, 0x1a00u, 0x00u, CO_DEFTYPE_UNSIGNED32, &data,
nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(CO_SDO_AC_TYPE_LEN_HI, CoCsdoDnCon::ac);
}
// given: invalid TPDO
// when: co_1a00_dn_ind()
// then: CO_SDO_AC_NO_OBJ abort code is returned
TEST(CO_SdoTpdo1a00, Co1a00DnInd_NumOfMappingsNonExistingObjMapping) {
Set1a00Sub1Mapping(0xffff0000u);
SetPdoCommCobid(DEV_ID | CO_PDO_COBID_VALID);
RestartTPDO();
const co_unsigned8_t num_of_mappings = 1u;
const auto ret =
co_dev_dn_val_req(dev, 0x1a00u, 0x00u, CO_DEFTYPE_UNSIGNED8,
&num_of_mappings, nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(CO_SDO_AC_NO_OBJ, CoCsdoDnCon::ac);
}
// given: invalid TPDO
// when: co_1a00_dn_ind()
// then: 0 abort code is returned
TEST(CO_SdoTpdo1a00, Co1a00DnInd_NumOfMappingsSameAsPrevious) {
SetPdoCommCobid(DEV_ID | CO_PDO_COBID_VALID);
RestartTPDO();
const co_unsigned8_t num_of_mappings = CO_PDO_NUM_MAPS;
const auto ret =
co_dev_dn_val_req(dev, 0x1a00u, 0x00u, CO_DEFTYPE_UNSIGNED8,
&num_of_mappings, nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(0, CoCsdoDnCon::ac);
}
// given: valid TPDO
// when: co_1a00_dn_ind()
// then: CO_SDO_AC_PARAM_VAL abort code is returned
TEST(CO_SdoTpdo1a00, Co1a00DnInd_NumOfMappingsValidTPDO) {
const co_unsigned8_t num_of_mappings = 2u;
const auto ret =
co_dev_dn_val_req(dev, 0x1a00u, 0x00u, CO_DEFTYPE_UNSIGNED8,
&num_of_mappings, nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(CO_SDO_AC_PARAM_VAL, CoCsdoDnCon::ac);
}
// given: invalid TPDO
// when: co_1a00_dn_ind()
// then: CO_SDO_AC_PARAM_VAL abort code is returned
TEST(CO_SdoTpdo1a00, Co1a00DnInd_NumOfMappingsTooManyObjsToMap) {
SetPdoCommCobid(DEV_ID | CO_PDO_COBID_VALID);
RestartTPDO();
const co_unsigned8_t num_of_mappings = CO_PDO_NUM_MAPS + 1u;
const auto ret =
co_dev_dn_val_req(dev, 0x1a00u, 0x00u, CO_DEFTYPE_UNSIGNED8,
&num_of_mappings, nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(CO_SDO_AC_PARAM_VAL, CoCsdoDnCon::ac);
}
// given: valid TPDO
// when: co_1a00_dn_ind()
// then: 0 abort code is returned
TEST(CO_SdoTpdo1a00, Co1a00DnInd_NumOfMappingsNoMappings) {
const co_unsigned8_t num_of_mappings = 0;
const auto ret =
co_dev_dn_val_req(dev, 0x1a00u, 0x00u, CO_DEFTYPE_UNSIGNED8,
&num_of_mappings, nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(CO_SDO_AC_PARAM_VAL, CoCsdoDnCon::ac);
}
// given: invalid TPDO
// when: co_1a00_dn_ind()
// then: 0 abort code is returned
TEST(CO_SdoTpdo1a00, Co1a00DnInd_NumOfMappings) {
SetPdoCommCobid(DEV_ID | CO_PDO_COBID_VALID);
Set1a00Sub1Mapping(0x20210020u);
RestartTPDO();
// object which could be mapped
CreateObjInDev(obj2021, 0x2021u);
Insert2021Values();
const co_unsigned8_t num_of_mappings = 1u;
const auto ret =
co_dev_dn_val_req(dev, 0x1a00u, 0x00u, CO_DEFTYPE_UNSIGNED8,
&num_of_mappings, nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(0, CoCsdoDnCon::ac);
}
// given: invalid TPDO
// when: co_1a00_dn_ind()
// then: CO_SDO_AC_NO_OBJ abort code is returned
TEST(CO_SdoTpdo1a00, Co1a00DnInd_MappingNonexisting) {
SetPdoCommCobid(DEV_ID | CO_PDO_COBID_VALID);
SetNumOfMappings(0x00);
RestartTPDO();
const co_unsigned32_t mapping = 0xffff0000u;
const auto ret =
co_dev_dn_val_req(dev, 0x1a00u, 0x01u, CO_DEFTYPE_UNSIGNED32, &mapping,
nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(CO_SDO_AC_NO_OBJ, CoCsdoDnCon::ac);
}
// given: invalid TPDO
// when: co_1a00_dn_ind()
// then: 0 abort code is returned
TEST(CO_SdoTpdo1a00, Co1a00DnInd_MappingSameAsPrevious) {
SetPdoCommCobid(DEV_ID | CO_PDO_COBID_VALID);
Set1a00Sub1Mapping(0x20210020u);
RestartTPDO();
// object which could be mapped
CreateObjInDev(obj2021, 0x2021u);
Insert2021Values();
const co_unsigned32_t mapping = 0x20210020u;
const auto ret =
co_dev_dn_val_req(dev, 0x1a00u, 0x01u, CO_DEFTYPE_UNSIGNED32, &mapping,
nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(0, CoCsdoDnCon::ac);
}
// given: invalid TPDO
// when: co_1a00_dn_ind()
// then: CO_SDO_AC_PARAM_VAL abort code is returned
TEST(CO_SdoTpdo1a00, Co1a00DnInd_MappingNumOfMappingsNonzero) {
SetPdoCommCobid(DEV_ID | CO_PDO_COBID_VALID);
SetNumOfMappings(0x01u);
RestartTPDO();
// object which could be mapped
CreateObjInDev(obj2021, 0x2021u);
Insert2021Values();
const co_unsigned32_t mapping = 0x20210020u;
const auto ret =
co_dev_dn_val_req(dev, 0x1a00u, 0x01u, CO_DEFTYPE_UNSIGNED32, &mapping,
nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(CO_SDO_AC_PARAM_VAL, CoCsdoDnCon::ac);
}
// given: valid TPDO
// when: co_1a00_dn_ind()
// then: CO_SDO_AC_PARAM_VAL abort code is returned
TEST(CO_SdoTpdo1a00, Co1a00DnInd_MappingValidTPDO) {
SetPdoCommCobid(DEV_ID);
SetNumOfMappings(0x01u);
RestartTPDO();
// object which could be mapped
CreateObjInDev(obj2021, 0x2021u);
Insert2021Values();
const co_unsigned32_t mapping = 0x20210020u;
const auto ret =
co_dev_dn_val_req(dev, 0x1a00u, 0x01u, CO_DEFTYPE_UNSIGNED32, &mapping,
nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(CO_SDO_AC_PARAM_VAL, CoCsdoDnCon::ac);
}
// given: invalid TPDO
// when: co_1a00_dn_ind()
// then: 0 abort code is returned
TEST(CO_SdoTpdo1a00, Co1a00DnInd_Mapping) {
SetPdoCommCobid(DEV_ID | CO_PDO_COBID_VALID);
SetNumOfMappings(0x00);
RestartTPDO();
// object which could be mapped
CreateObjInDev(obj2021, 0x2021u);
Insert2021Values();
const co_unsigned32_t mapping = 0x20210020u;
const auto ret =
co_dev_dn_val_req(dev, 0x1a00u, 0x01u, CO_DEFTYPE_UNSIGNED32, &mapping,
nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(0, CoCsdoDnCon::ac);
}
// given: invalid TPDO
// when: co_1a00_dn_ind()
// then: 0 abort code is returned
TEST(CO_SdoTpdo1a00, Co1a00DnInd_MappingZeros) {
SetPdoCommCobid(DEV_ID | CO_PDO_COBID_VALID);
SetNumOfMappings(0x00);
Set1a00Sub1Mapping(0x20210020u);
RestartTPDO();
// object which could be mapped
CreateObjInDev(obj2021, 0x2021u);
Insert2021Values();
const co_unsigned32_t mapping = 0x00000000u;
const auto ret =
co_dev_dn_val_req(dev, 0x1a00u, 0x01, CO_DEFTYPE_UNSIGNED32, &mapping,
nullptr, CoCsdoDnCon::func, nullptr);
CHECK_EQUAL(0, ret);
CHECK(CoCsdoDnCon::called());
CHECK_EQUAL(0, CoCsdoDnCon::ac);
}
| 31.44378
| 79
| 0.703199
|
DroidDrive
|
a1b16e81141b90aae983455f91c51150b957988b
| 290
|
cpp
|
C++
|
cppsrc/main.cpp
|
ferserc1/node-api-test
|
43a732b4d0539af812d8a8b86de756cbe915b1ab
|
[
"MIT"
] | null | null | null |
cppsrc/main.cpp
|
ferserc1/node-api-test
|
43a732b4d0539af812d8a8b86de756cbe915b1ab
|
[
"MIT"
] | null | null | null |
cppsrc/main.cpp
|
ferserc1/node-api-test
|
43a732b4d0539af812d8a8b86de756cbe915b1ab
|
[
"MIT"
] | null | null | null |
#include <napi.h>
#include "Samples/functionalexample.h"
#include "Samples/classexample.h"
Napi::Object InitAll(Napi::Env env, Napi::Object exports) {
functionalexample::Init(env, exports);
return ClassExample::Init(env, exports);
}
NODE_API_MODULE(NODE_GYP_MODULE_NAME, InitAll)
| 26.363636
| 59
| 0.758621
|
ferserc1
|
a1b3d03313775732713a2392675ae0ee6497415f
| 455
|
cpp
|
C++
|
200111Zad06/zad6.cpp
|
elenazaharieva/fifthgrade
|
60d1301c118b9f0cb4089d672fdf9e1780aedf80
|
[
"Apache-2.0"
] | null | null | null |
200111Zad06/zad6.cpp
|
elenazaharieva/fifthgrade
|
60d1301c118b9f0cb4089d672fdf9e1780aedf80
|
[
"Apache-2.0"
] | null | null | null |
200111Zad06/zad6.cpp
|
elenazaharieva/fifthgrade
|
60d1301c118b9f0cb4089d672fdf9e1780aedf80
|
[
"Apache-2.0"
] | null | null | null |
/*
*
* zad6.cpp
*
* Created on: Jan 15, 2020
* Author: eli
*/
#include <iostream>
using namespace std;
int main() {
int posl = 1;
int maxPosl = 1;
int digitOld;
int digitNew;
cin >> digitNew;
digitOld = -1;
while (digitNew != 0) {
if (digitOld == digitNew) {
posl++;
if (maxPosl < posl) {
maxPosl = posl;
}
} else {
posl = 1;
}
digitOld = digitNew;
cin >> digitNew;
}
cout << maxPosl << endl;
return 0;
}
| 13.382353
| 29
| 0.553846
|
elenazaharieva
|
a1b5d43994e173fad63c344fa45c8e49b3b8a20f
| 101
|
cpp
|
C++
|
Source/SaveExtension/Private/Multithreading/ScopedTaskManager.cpp
|
foobit/SaveExtension
|
390033bc757f2b694c497e22c324dcac539bcd15
|
[
"Apache-2.0"
] | 110
|
2018-10-20T21:47:54.000Z
|
2022-03-14T03:47:58.000Z
|
Source/SaveExtension/Private/Multithreading/ScopedTaskManager.cpp
|
foobit/SaveExtension
|
390033bc757f2b694c497e22c324dcac539bcd15
|
[
"Apache-2.0"
] | 68
|
2018-12-19T09:08:56.000Z
|
2022-03-09T06:43:38.000Z
|
Source/SaveExtension/Private/Multithreading/ScopedTaskManager.cpp
|
foobit/SaveExtension
|
390033bc757f2b694c497e22c324dcac539bcd15
|
[
"Apache-2.0"
] | 45
|
2018-12-03T14:35:47.000Z
|
2022-03-05T01:35:24.000Z
|
// Copyright 2015-2020 Piperift. All Rights Reserved.
#include "Multithreading/ScopedTaskManager.h"
| 25.25
| 53
| 0.80198
|
foobit
|
a1b6bf09314cd5b26683a17a0e4e2e8c01b21d5f
| 1,823
|
hpp
|
C++
|
Krakoa/Source/Graphics/2D/Textures/SubTexture2d.hpp
|
KingKiller100/Krakatoa-Engine
|
ff07f7328d428c04e06b561b6afd315eea39865c
|
[
"Apache-2.0"
] | 1
|
2020-04-05T13:37:48.000Z
|
2020-04-05T13:37:48.000Z
|
Krakoa/Source/Graphics/2D/Textures/SubTexture2d.hpp
|
KingKiller100/Krakoa-Engine
|
0f2a5a5109e256a384abe8dc21eacaa45c1de610
|
[
"Apache-2.0"
] | null | null | null |
Krakoa/Source/Graphics/2D/Textures/SubTexture2d.hpp
|
KingKiller100/Krakoa-Engine
|
0f2a5a5109e256a384abe8dc21eacaa45c1de610
|
[
"Apache-2.0"
] | null | null | null |
#pragma once
#include "../Primitives2D/BatchRendererData.hpp"
#include "../../../Core/PointerTypes.hpp"
#include <Maths/Vectors/Vector2.hpp>
#include <Utility/Enum/kEnum.hpp>
#include <vector>
#include <cstdint>
namespace krakoa::gfx
{
class iTexture2D;
using TexCoordsList = std::vector<kmaths::Vector2f>;
ENUM_CLASS(GeometryType, std::uint16_t,
QUAD = batch::limits::quad::vertices,
CIRCLE = batch::limits::circle::vertices,
TRIANGLE = batch::limits::triangle::vertices,
UNKNOWN = 65535
);
class SubTexture2D
{
public:
struct TexCoordData
{
kmaths::Vector2f coordIndex;
kmaths::Vector2f spriteDimensions;
TexCoordsList baseCoords;
};
public:
SubTexture2D(GeometryType geo);
SubTexture2D(iTexture2D* texture, const TexCoordData& data);
SubTexture2D(const std::shared_ptr<iTexture2D>& texture, const TexCoordData& data);
~SubTexture2D() noexcept;
USE_RESULT const Multi_Ptr<iTexture2D>& GetTexture() const noexcept;
USE_RESULT Multi_Ptr<iTexture2D>& GetTexture() noexcept;
USE_RESULT const kmaths::Vector2f* GetTexCoord() const noexcept;
void SetTexture(iTexture2D* tex) noexcept;
void SetTexture(const std::shared_ptr<iTexture2D>& value) noexcept { (texture) = value; }
USE_RESULT const TexCoordData& GetTexCoordData() const noexcept { return texCoordData; }
USE_RESULT GeometryType GetGeometryType() const noexcept;
// Only for quads
static SubTexture2D* Create(iTexture2D* texture, const TexCoordData& texCoordData);
static SubTexture2D* Create(const std::shared_ptr<iTexture2D > & texture, const TexCoordData& data);
private:
void CreateTexCoords();
GeometryType DeduceGeometryType() const;
private:
Multi_Ptr<iTexture2D> texture;
std::vector<kmaths::Vector2f> texCoords;
TexCoordData texCoordData;
GeometryType geometry;
};
}
| 28.046154
| 102
| 0.752606
|
KingKiller100
|
a1b84677e65a81ac1f44d4a6c110c910466bb307
| 3,377
|
hpp
|
C++
|
includes/reflex/function/function.hpp
|
Cylix/Reflex
|
b51433f6f07e88d5b167ea71f481aa685bedcb86
|
[
"MIT"
] | 112
|
2015-08-12T01:12:46.000Z
|
2022-03-27T13:11:22.000Z
|
includes/reflex/function/function.hpp
|
Cylix/Reflex
|
b51433f6f07e88d5b167ea71f481aa685bedcb86
|
[
"MIT"
] | 2
|
2015-11-22T15:04:14.000Z
|
2018-01-05T05:38:44.000Z
|
includes/reflex/function/function.hpp
|
Cylix/Reflex
|
b51433f6f07e88d5b167ea71f481aa685bedcb86
|
[
"MIT"
] | 17
|
2015-10-16T02:50:58.000Z
|
2021-09-10T09:41:58.000Z
|
#pragma once
#include <memory>
#include <string>
#include <reflex/function/callable_base.hpp>
#include <reflex/function/callable_with_instance.hpp>
#include <reflex/function/callable_without_instance.hpp>
#include <reflex/reflection_exception.hpp>
namespace reflex {
class function {
public:
struct functions_container {
std::shared_ptr<callable_base> callable_without_obj;
std::shared_ptr<callable_base> callable_with_obj;
};
public:
//! ctor & dtor
function(void) : m_name(""), m_functions{ nullptr, nullptr } {}
function(const std::string& name, const functions_container& functions) : m_name(name), m_functions(functions) {}
~function(void) = default;
//! copy ctor & assignment operator
function(const function&) = default;
function& operator=(const function&) = default;
//! member function call on new instance
//! c-style functions
//! static member functions
template <typename ReturnType, typename... Params>
ReturnType invoke(Params... params) {
if (not m_functions.callable_without_obj)
throw reflection_exception("Invalid callable_base pointer (nullptr) for function " + m_name);
return invoke<callable_without_instance<ReturnType(Params...)>, ReturnType, Params...>(m_functions.callable_without_obj, params...);
}
//! member function call on given instance
template <typename Type, typename ReturnType, typename... Params>
ReturnType invoke(Type* obj, Params... params) {
if (not m_functions.callable_with_obj)
throw reflection_exception("Function " + m_name + " can't be called with object");
return invoke<callable_with_instance<Type, ReturnType(Params...)>, ReturnType, Type*, Params...>(m_functions.callable_with_obj, obj, params...);
}
//! member function call on given instance
template <typename Type, typename ReturnType, typename... Params>
ReturnType invoke(const std::shared_ptr<Type>& obj, Params... params) {
if (not m_functions.callable_with_obj)
throw reflection_exception("Function " + m_name + " can't be called with object");
return invoke<callable_with_instance<Type, ReturnType(Params...)>, ReturnType, Type*, Params...>(m_functions.callable_with_obj, obj.get(), params...);
}
//! member function call on given instance
template <typename Type, typename ReturnType, typename... Params>
ReturnType invoke(const std::unique_ptr<Type>& obj, Params... params) {
if (not m_functions.callable_with_obj)
throw reflection_exception("Function " + m_name + " can't be called with object");
return invoke<callable_with_instance<Type, ReturnType(Params...)>, ReturnType, Type*, Params...>(m_functions.callable_with_obj, obj.get(), params...);
}
private:
template <typename RealFunctionType, typename ReturnType, typename... Params>
ReturnType invoke(const std::shared_ptr<callable_base>& function, Params... params) {
auto function_with_real_type = std::dynamic_pointer_cast<RealFunctionType>(function);
if (not function_with_real_type)
throw reflection_exception("Invalid function signature for function " + m_name);
return (*function_with_real_type)(params...);
}
private:
std::string m_name;
functions_container m_functions;
};
} //! reflex
| 39.729412
| 158
| 0.703583
|
Cylix
|
a1b88a2355cb3220ecebadbf4540b83294441f79
| 2,145
|
cpp
|
C++
|
tests/test_query.cpp
|
kamchatka-volcano/hot_teacup
|
ef894b6f333364f9768f1d2477580604affada87
|
[
"MS-PL"
] | null | null | null |
tests/test_query.cpp
|
kamchatka-volcano/hot_teacup
|
ef894b6f333364f9768f1d2477580604affada87
|
[
"MS-PL"
] | null | null | null |
tests/test_query.cpp
|
kamchatka-volcano/hot_teacup
|
ef894b6f333364f9768f1d2477580604affada87
|
[
"MS-PL"
] | null | null | null |
#include <hot_teacup/query.h>
#include <gtest/gtest.h>
TEST(Query, ToStringSingle)
{
auto query = http::Query{"foo", "bar"};
EXPECT_EQ(query.toString(), "foo=bar");
}
TEST(Query, ToString)
{
{
auto queries = http::Queries{{"name", "test"}, {"foo", "bar"}};
EXPECT_EQ(http::queriesToString(queries), "name=test&foo=bar");
}
{
auto queries = http::Queries{{"name", "test"}, {"foo", "bar"}};
EXPECT_EQ(http::queriesToString(queries, {"foo"}), "name=test");
}
}
TEST(Query, PathWithQueries)
{
{
auto query = http::Query{"name", "test"};
auto path = "/test/";
EXPECT_EQ(http::pathWithQuery(path, query), "/test/?name=test");
}
{
auto queries = http::Queries{{"name", "test"}, {"foo", "bar"}};
auto path = "/test/";
EXPECT_EQ(http::pathWithQueries(path, queries), "/test/?name=test&foo=bar");
}
{
auto queries = http::Queries{{"name", "test"}, {"foo", "bar"}};
auto path = "/test/";
EXPECT_EQ(http::pathWithQueries(path, queries, {"name"}), "/test/?foo=bar");
}
}
TEST(Query, FromString)
{
{
auto queries = http::queriesFromString("name=test&foo=bar");
auto expectedQueries = http::Queries{{"name", "test"}, {"foo", "bar"}};
EXPECT_EQ(queries, expectedQueries);
}
{
auto queries = http::queriesFromString("");
auto expectedQueries = http::Queries{};
EXPECT_EQ(queries, expectedQueries);
}
{
auto queries = http::queriesFromString("=");
auto expectedQueries = http::Queries{};
EXPECT_EQ(queries, expectedQueries);
}
{
auto queries = http::queriesFromString("&");
auto expectedQueries = http::Queries{};
EXPECT_EQ(queries, expectedQueries);
}
{
auto queries = http::queriesFromString("&&");
auto expectedQueries = http::Queries{};
EXPECT_EQ(queries, expectedQueries);
}
{
auto queries = http::queriesFromString("=&=&=");
auto expectedQueries = http::Queries{};
EXPECT_EQ(queries, expectedQueries);
}
}
| 27.857143
| 84
| 0.568765
|
kamchatka-volcano
|
a1b922b304bdcae834e5f2ca99f020f565a70783
| 5,942
|
cpp
|
C++
|
windows/runner/main.cpp
|
alexmercerind/flutter-win32-acrylic
|
734094d5f3c445934d1860aef849ddd6b8188d2e
|
[
"MIT"
] | 2
|
2021-08-03T16:51:20.000Z
|
2021-08-04T10:39:53.000Z
|
windows/runner/main.cpp
|
alexmercerind/flutter-win32-acrylic
|
734094d5f3c445934d1860aef849ddd6b8188d2e
|
[
"MIT"
] | null | null | null |
windows/runner/main.cpp
|
alexmercerind/flutter-win32-acrylic
|
734094d5f3c445934d1860aef849ddd6b8188d2e
|
[
"MIT"
] | null | null | null |
#include <Unknwn.h>
#include <Windows.h>
#include <winrt/Windows.Foundation.Collections.h>
#include <winrt/Windows.UI.Xaml.Hosting.h>
#include <winrt/Windows.UI.Xaml.Controls.h>
#include <winrt/Windows.UI.Xaml.Media.h>
#include <windows.ui.xaml.hosting.desktopwindowxamlsource.h>
#include "utils.h"
#include "flutter/generated_plugin_registrant.h"
#include <flutter/dart_project.h>
#include <flutter/flutter_view_controller.h>
static CONST WCHAR szWindowClassName[] = L"FLUTTER_WIN32_XAML_WINDOW";
static CONST WCHAR szWindowTitle[] = L"flutter_win32_xaml";
HWND g_window_handle = nullptr;
HWND g_flutter_view_handle = nullptr;
HWND g_xaml_handle = nullptr;
flutter::FlutterViewController* g_flutter_view_controller = nullptr;
static HINSTANCE g_instance = nullptr;
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
int APIENTRY wWinMain(_In_ HINSTANCE h_instance, _In_opt_ HINSTANCE prev, _In_ wchar_t *command_line, _In_ int show_command) {
UNREFERENCED_PARAMETER(prev);
UNREFERENCED_PARAMETER(command_line);
WNDCLASSEXW window_class;
SecureZeroMemory(&window_class, sizeof(window_class));
window_class.cbSize = sizeof(window_class);
window_class.style = CS_HREDRAW | CS_VREDRAW;
window_class.lpfnWndProc = WndProc;
window_class.hInstance = h_instance;
window_class.lpszClassName = szWindowClassName;
window_class.hCursor = LoadCursorW(nullptr, IDC_ARROW);
window_class.hbrBackground = reinterpret_cast<HBRUSH>(COLOR_WINDOW + 1);
RegisterClassExW(&window_class);
if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) {
CreateAndAttachConsole();
}
CONST HWND window_handle = CreateWindowExW(
0L,
szWindowClassName,
szWindowTitle,
WS_OVERLAPPEDWINDOW | WS_VISIBLE,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
nullptr,
nullptr,
h_instance,
nullptr
);
if (!window_handle) {
return EXIT_FAILURE;
}
g_instance = h_instance;
g_window_handle = window_handle;
RECT rect;
::GetClientRect(g_window_handle, &rect);
winrt::init_apartment(winrt::apartment_type::single_threaded);
const auto windows_xaml_manager = winrt::Windows::UI::Xaml::Hosting::WindowsXamlManager::InitializeForCurrentThread();
winrt::Windows::UI::Xaml::Hosting::DesktopWindowXamlSource desktop_window_xaml_source = {};
const auto interop = desktop_window_xaml_source.as<IDesktopWindowXamlSourceNative>();
winrt::check_hresult(interop->AttachToWindow(g_window_handle));
HWND xaml_handle = nullptr;
interop->get_WindowHandle(&xaml_handle);
g_xaml_handle = xaml_handle;
if (!xaml_handle) {
return false;
}
winrt::Windows::UI::Xaml::Controls::Grid grid = {};
winrt::Windows::UI::Xaml::Media::AcrylicBrush acrylic_brush = {};
acrylic_brush.TintColor(winrt::Windows::UI::ColorHelper::FromArgb(0, 0, 0, 0));
acrylic_brush.BackgroundSource(winrt::Windows::UI::Xaml::Media::AcrylicBackgroundSource::HostBackdrop);
grid.Background(acrylic_brush);
grid.UpdateLayout();
desktop_window_xaml_source.Content(grid);
::SetWindowPos(xaml_handle, 0, rect.left, rect.top, 400, rect.bottom - rect.top, SWP_SHOWWINDOW);
::ShowWindow(g_xaml_handle, show_command);
::UpdateWindow(g_xaml_handle);
::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
flutter::DartProject project(L"data");
std::vector<std::string> command_line_arguments = GetCommandLineArguments();
project.set_dart_entrypoint_arguments(std::move(command_line_arguments));
flutter::FlutterViewController* flutter_view_controller = new flutter::FlutterViewController(
rect.right - rect.left, rect.bottom - rect.top, project
);
g_flutter_view_controller = flutter_view_controller;
if (!flutter_view_controller->engine() || !flutter_view_controller->view()) {
return false;
}
RegisterPlugins(flutter_view_controller->engine());
g_flutter_view_handle = flutter_view_controller->view()->GetNativeWindow();
SetParent(g_flutter_view_handle, g_window_handle);
::SetWindowPos(
g_flutter_view_handle, 0,
rect.left, rect.top,
rect.right - rect.left, rect.bottom - rect.top, true
);
::SetFocus(g_flutter_view_handle);
::MSG msg;
while (::GetMessageW(&msg, nullptr, 0, 0)) {
::TranslateMessage(&msg);
::DispatchMessageW(&msg);
}
::CoUninitialize();
return (int)msg.wParam;
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT const message, WPARAM const wparam, LPARAM const lparam) {
if (g_flutter_view_controller != nullptr) {
std::optional<LRESULT> result = g_flutter_view_controller->HandleTopLevelWindowProc(
hwnd, message, wparam, lparam
);
if (result) {
return *result;
}
}
switch (message) {
case WM_DESTROY: {
g_window_handle = nullptr;
DestroyWindow(g_window_handle);
PostQuitMessage(0);
return 0;
}
case WM_SIZE: {
RECT rect;
::GetClientRect(g_window_handle, &rect);
if (g_xaml_handle != nullptr) {
::MoveWindow(
g_xaml_handle,
rect.left, rect.top,
rect.right - rect.left, rect.bottom - rect.top, TRUE
);
}
if (g_flutter_view_handle != nullptr) {
::MoveWindow(
g_flutter_view_handle,
rect.left, rect.top,
rect.right - rect.left, rect.bottom - rect.top, TRUE
);
}
break;
}
case WM_FONTCHANGE: {
g_flutter_view_controller->engine()->ReloadSystemFonts();
break;
}
case WM_DPICHANGED: {
auto newRectSize = reinterpret_cast<RECT*>(lparam);
LONG newWidth = newRectSize->right - newRectSize->left;
LONG newHeight = newRectSize->bottom - newRectSize->top;
::SetWindowPos(
hwnd,
nullptr,
newRectSize->left,
newRectSize->top,
newWidth,
newHeight,
SWP_NOZORDER | SWP_NOACTIVATE
);
return 0;
}
default: {
break;
}
}
return DefWindowProcW(hwnd, message, wparam, lparam);
}
| 34.346821
| 126
| 0.71794
|
alexmercerind
|
a1c4531959f309f8a8710bb2ed045af97cc5bf32
| 2,541
|
hpp
|
C++
|
obcsim/obcsim_configuration.hpp
|
Zethian/proto-cubes-obc
|
a37aed0e9e3b3fd917baeb29b6279d91845818dd
|
[
"MIT"
] | null | null | null |
obcsim/obcsim_configuration.hpp
|
Zethian/proto-cubes-obc
|
a37aed0e9e3b3fd917baeb29b6279d91845818dd
|
[
"MIT"
] | 4
|
2020-04-16T13:41:11.000Z
|
2020-06-03T11:30:54.000Z
|
obcsim/obcsim_configuration.hpp
|
tstana/proto-cubes-obc
|
671b0d1c44ee81973275d386ed70912fd06e275c
|
[
"MIT"
] | 2
|
2021-11-19T09:32:01.000Z
|
2021-12-28T09:11:00.000Z
|
/* A generated header file from setup.py */
#ifndef OBCSIM_CONFIGURATION_H
#define OBCSIM_CONFIGURATION_H
#include "msp_obc.h"
#define EXP_ADDR 0x35
#define EXP_MTU 507
#define REQUEST_BUFFER_SIZE 25000
#define MSP_ERROR_THRESHOLD 5
#ifndef MSP_OP_REQ_PAYLOAD
#define MSP_OP_REQ_PAYLOAD 0x20
#endif
#ifndef MSP_OP_ACTIVE
#define MSP_OP_ACTIVE 0x10
#endif
#ifndef MSP_OP_REQ_PARAMS
#define MSP_OP_REQ_PARAMS 0x60
#endif
#ifndef MSP_OP_POWER_OFF
#define MSP_OP_POWER_OFF 0x12
#endif
#ifndef MSP_OP_SEND_PARAMS
#define MSP_OP_SEND_PARAMS 0x70
#endif
#ifndef MSP_OP_REQ_HK
#define MSP_OP_REQ_HK 0x21
#endif
#ifndef MSP_OP_SEND_CUBES_HVPS_CONF
#define MSP_OP_SEND_CUBES_HVPS_CONF 0x71
#endif
#ifndef MSP_OP_SEND_CUBES_CITI_CONF
#define MSP_OP_SEND_CUBES_CITI_CONF 0x72
#endif
#ifndef MSP_OP_SEND_CUBES_PROBE_CONF
#define MSP_OP_SEND_CUBES_PROBE_CONF 0x73
#endif
#ifndef MSP_OP_SEND_CUBES_DAQ_DUR
#define MSP_OP_SEND_CUBES_DAQ_DUR 0x74
#endif
#ifndef MSP_OP_SEND_CUBES_HVPS_TMP_VOLT
#define MSP_OP_SEND_CUBES_HVPS_TMP_VOLT 0x75
#endif
#ifndef MSP_OP_SEND_READ_REG_DEBUG
#define MSP_OP_SEND_READ_REG_DEBUG 0x76
#endif
#ifndef MSP_OP_SEND_CUBES_GATEWARE_CONF
#define MSP_OP_SEND_CUBES_GATEWARE_CONF 0x77
#endif
#ifndef MSP_OP_REQ_PUS
#define MSP_OP_REQ_PUS 0x22
#endif
#ifndef MSP_OP_SEND_TIME
#define MSP_OP_SEND_TIME 0x30
#endif
#ifndef MSP_OP_SEND_PUS
#define MSP_OP_SEND_PUS 0x31
#endif
#ifndef MSP_OP_SLEEP
#define MSP_OP_SLEEP 0x11
#endif
#ifndef MSP_OP_CUBES_DAQ_START
#define MSP_OP_CUBES_DAQ_START 0x53
#endif
#ifndef MSP_OP_CUBES_DAQ_STOP
#define MSP_OP_CUBES_DAQ_STOP 0x54
#endif
#ifndef MSP_OP_REQ_CUBES_ID
#define MSP_OP_REQ_CUBES_ID 0x61
#endif
/*
* Proto-CUBES Serial Port Commands
* - write commands (ground to Proto-CUBES) are in capital letters
* - read commands (ground from Proto-CUBES) are in non-capital letters
*/
#define CMD_SEND_CITIROC_CONF 'C'
#define CMD_SEND_PROBE_CONF 'P'
#define CMD_SEND_READ_REG_DEBUG 'R'
#define CMD_SEND_HVPS_CONF 'H'
#define CMD_SEND_HVPS_TMP_VOLT 'V'
#define CMD_SEND_DAQ_DUR 'D'
#define CMD_SEND_GATEWARE_CONF 'G'
#define CMD_DAQ_START 'S'
#define CMD_DAQ_STOP 'T'
#define CMD_DEL_FILES 'Q'
#define CMD_SEND_TIME 'Z'
#define CMD_REQ_HK 'h'
#define CMD_REQ_PAYLOAD 'p'
#define CMD_REQ_ID 'i'
/* Function prototypes */
void sequence_init(msp_link_t *lnk);
void sequence_loop(msp_link_t *lnk);
#endif /* OBCSIM_CONFIGURATION_H */
| 25.666667
| 72
| 0.783943
|
Zethian
|
a1c782b01ed8e6d08690a394a39c4e193bff2f61
| 25,016
|
cpp
|
C++
|
cpp/sdk/src/json_rpc.cpp
|
violas-core/violas-client-sdk
|
fc72fc0ea6e8e0e395759020038129736d93b64c
|
[
"MIT"
] | null | null | null |
cpp/sdk/src/json_rpc.cpp
|
violas-core/violas-client-sdk
|
fc72fc0ea6e8e0e395759020038129736d93b64c
|
[
"MIT"
] | null | null | null |
cpp/sdk/src/json_rpc.cpp
|
violas-core/violas-client-sdk
|
fc72fc0ea6e8e0e395759020038129736d93b64c
|
[
"MIT"
] | 2
|
2021-12-28T06:50:27.000Z
|
2022-02-15T09:28:36.000Z
|
#include <cpprest/filestream.h>
#include <cpprest/http_client.h>
#include <cpprest/json.h>
#include "../include/utils.hpp"
#include "../include/json_rpc.hpp"
using namespace std;
using namespace utility;
using namespace web;
using namespace web::http;
using namespace web::http::client;
namespace json_rpc
{
class ClientImp : public Client
{
http_client m_http_cli;
public:
ClientImp(string_view url) : m_http_cli(U(string(url)), client_config_for_proxy())
{
}
virtual ~ClientImp()
{
}
web::http::client::http_client_config client_config_for_proxy()
{
web::http::client::http_client_config client_config;
#ifdef _WIN32
wchar_t *pValue = nullptr;
std::unique_ptr<wchar_t, void (*)(wchar_t *)> holder(nullptr, [](wchar_t *p)
{ free(p); });
size_t len = 0;
auto err = _wdupenv_s(&pValue, &len, L"http_proxy");
if (pValue)
holder.reset(pValue);
if (!err && pValue && len)
{
std::wstring env_http_proxy_string(pValue, len - 1);
#else
if (const char *env_http_proxy = std::getenv("http_proxy"))
{
std::string env_http_proxy_string(env_http_proxy);
#endif
if (env_http_proxy_string == U("auto"))
client_config.set_proxy(web::web_proxy::use_auto_discovery);
else
client_config.set_proxy(web::web_proxy(env_http_proxy_string));
}
return client_config;
}
virtual void submit(const diem_types::SignedTransaction &signed_txn) override
{
auto data = bytes_to_hex(signed_txn.bcsSerialize());
string method = format(R"({"jsonrpc":"2.0","method":"submit","params":["%s"],"id":1})", data.c_str());
string content_type = "application/json";
auto rpc_response = m_http_cli.request(methods::POST, "/", method, content_type)
.then([=](http_response response) -> pplx::task<json::value>
{
if (response.status_code() != 200)
__throw_runtime_error(response.extract_string().get().c_str());
return response.extract_json(); })
.get();
auto error = rpc_response["error"];
if (!error.is_null())
__throw_runtime_error(("fun : get_account_state_blob, error : " + error.serialize()).c_str());
auto version = rpc_response["diem_ledger_version"].as_integer();
}
//
// Async submit
//
virtual void async_submit(const diem_types::SignedTransaction &signed_txn,
std::function<void()> callback) override
{
auto data = bytes_to_hex(signed_txn.bcsSerialize());
string method = format(R"({"jsonrpc":"2.0","method":"submit","params":["%s"],"id":1})", data.c_str());
string content_type = "application/json";
m_http_cli.request(methods::POST, "/", method, content_type)
.then([=](http_response response) -> pplx::task<json::value>
{
if (response.status_code() != 200)
__throw_runtime_error(response.extract_string().get().c_str());
return response.extract_json();
; })
.then(
[=](json::value json_value)
{
auto error = json_value["error"];
if (!error.is_null())
__throw_runtime_error(("fun : get_account_state_blob, error : " + error.serialize()).c_str());
auto version = json_value["diem_ledger_version"].as_integer();
if(callback)
callback();
; });
}
virtual Task<void>
await_submit2(dt::SignedTransaction &&signed_txn) override
{
auto data = bytes_to_hex(signed_txn.bcsSerialize());
string method = format(R"({"jsonrpc":"2.0","method":"submit","params":["%s"],"id":1})", data.c_str());
struct awaitable
{
http_client &http_cli;
dt::SignedTransaction &&signed_txn;
string &&method;
bool await_ready() { return false; }
void await_resume() {}
void await_suspend(std::coroutine_handle<> h)
{
http_cli.request(methods::POST, "/", method, "application/json")
.then([=](http_response response) -> pplx::task<json::value>
{ //
if (response.status_code() != 200)
__throw_runtime_error(response.extract_string().get().c_str());
return response.extract_json();
})
.then([=](json::value json_value) { //
auto error = json_value["error"];
if (!error.is_null())
__throw_runtime_error(("fun : get_account_state_blob, error : " + error.serialize()).c_str());
auto version = json_value["diem_ledger_version"].as_integer();
h.resume();
});
}
};
co_await awaitable{m_http_cli, move(signed_txn), move(method)};
}
virtual std::optional<TransactionView>
get_account_transaction(const diem_types::AccountAddress &address,
uint64_t sequence_number,
bool include_events) override
{
string method = format(R"({"jsonrpc":"2.0","method":"get_account_transaction","params":["%s", %d, %s],"id":1})",
bytes_to_hex(address.value).c_str(),
sequence_number,
include_events ? "true" : "false");
string content_type = "application/json";
auto rpc_response = m_http_cli.request(methods::POST, "/", method, content_type)
.then([=](http_response response) -> pplx::task<json::value>
{
if (response.status_code() != 200)
__throw_runtime_error(response.extract_string().get().c_str());
return response.extract_json(); })
.get();
auto error = rpc_response["error"];
if (!error.is_null())
__throw_runtime_error(("get_account_transaction error, " + error.serialize()).c_str());
auto result = rpc_response["result"];
TransactionView txn;
if (!result.is_null())
{
auto vm_status = result["vm_status"];
auto type = vm_status["type"].as_string();
if (type == "executed")
txn.vm_status.value = VMStatus::Executed{type};
else if (type == "execution_failure")
{
txn.vm_status.value = VMStatus::ExecutionFailure{
type,
vm_status["location"].as_string(),
(uint64_t)vm_status["function_index"].as_integer(),
(uint64_t)vm_status["code_offset"].as_integer()};
}
else if (type == "out_of_gas")
txn.vm_status.value = VMStatus::OutOfGas{type};
else if (type == "miscellaneous_error")
txn.vm_status.value = VMStatus::MiscellaneousError{type};
else if (type == "move_abort")
txn.vm_status.value = VMStatus::MoveAbort{
type,
vm_status["location"].as_string(),
(uint64_t)vm_status["abort_code"].as_integer(),
{
vm_status["explanation"].is_null() ? "" : vm_status["explanation"]["category"].as_string(),
vm_status["explanation"].is_null() ? "" : vm_status["explanation"]["category_description"].as_string(),
vm_status["explanation"].is_null() ? "" : vm_status["explanation"]["reason"].as_string(),
vm_status["explanation"].is_null() ? "" : vm_status["explanation"]["reason_description"].as_string(),
}};
else
throw runtime_error("unknow vm status");
// cout << result.serialize() << endl;
return txn;
}
else
return std::nullopt;
}
virtual Task<std::optional<TransactionView>>
await_get_account_transaction(const diem_types::AccountAddress &address,
uint64_t sequence_number,
bool include_events) override
{
struct Awaitable
{
http_client &_http_cli;
const diem_types::AccountAddress &address;
uint64_t sequence_number;
bool include_events;
json::value result;
TransactionView _txn_view;
bool await_ready() { return false; }
auto await_resume() { return result; }
void await_suspend(std::coroutine_handle<> h)
{
string method = format(R"({"jsonrpc":"2.0","method":"get_account_transaction","params":["%s", %d, %s],"id":1})",
bytes_to_hex(address.value).c_str(),
sequence_number,
include_events ? "true" : "false");
string content_type = "application/json";
_http_cli.request(methods::POST, "/", method, content_type)
.then([=](http_response response) -> pplx::task<json::value>
{
if (response.status_code() != 200)
__throw_runtime_error(response.extract_string().get().c_str());
return response.extract_json(); })
.then([this, h](json::value value)
{
try
{
result = value;
h.resume();
}
catch (const std::exception &e)
{
std::cerr << e.what() << '\n';
} });
}
};
auto rpc_response = co_await Awaitable{m_http_cli, address, sequence_number, include_events};
auto error = rpc_response["error"];
if (!error.is_null())
__throw_runtime_error(("get_account_transaction error, " + error.serialize()).c_str());
auto result = rpc_response["result"];
TransactionView txn;
if (!result.is_null())
{
auto vm_status = result["vm_status"];
auto type = vm_status["type"].as_string();
if (type == "executed")
txn.vm_status.value = VMStatus::Executed{type};
else if (type == "execution_failure")
{
txn.vm_status.value = VMStatus::ExecutionFailure{
type,
vm_status["location"].as_string(),
(uint64_t)vm_status["function_index"].as_integer(),
(uint64_t)vm_status["code_offset"].as_integer()};
}
else if (type == "out_of_gas")
txn.vm_status.value = VMStatus::OutOfGas{type};
else if (type == "miscellaneous_error")
txn.vm_status.value = VMStatus::MiscellaneousError{type};
else if (type == "move_abort")
txn.vm_status.value = VMStatus::MoveAbort{
type,
vm_status["location"].as_string(),
(uint64_t)vm_status["abort_code"].as_integer(),
{
vm_status["explanation"].is_null() ? "" : vm_status["explanation"]["category"].as_string(),
vm_status["explanation"].is_null() ? "" : vm_status["explanation"]["category_description"].as_string(),
vm_status["explanation"].is_null() ? "" : vm_status["explanation"]["reason"].as_string(),
vm_status["explanation"].is_null() ? "" : vm_status["explanation"]["reason_description"].as_string(),
}};
else
throw runtime_error("unknow vm status");
// cout << result.serialize() << endl;
co_return txn;
}
else
co_return std::nullopt;
}
virtual std::optional<AccountView>
get_account(const diem_types::AccountAddress &address, std::optional<uint64_t> version) override
{
string method = format(R"({"jsonrpc":"2.0","method":"get_account","params":["%s"],"id":1})", bytes_to_hex(address.value).c_str());
string content_type = "application/json";
auto rpc_response = m_http_cli.request(methods::POST, "/", method, content_type)
.then([=](http_response response) -> pplx::task<json::value>
{
if (response.status_code() != 200)
__throw_runtime_error(response.extract_string().get().c_str());
return response.extract_json(); })
.get();
auto error = rpc_response["error"];
if (!error.is_null())
__throw_runtime_error(("fun : get_account_state_blob, error : " + error.serialize()).c_str());
auto result = rpc_response["result"];
if (!result.is_null())
{
AccountView view;
if (!result["sequence_number"].is_null())
{
view.sequence_number = result["sequence_number"].as_number().to_int64();
view.address = diem_types::AccountAddress{hex_to_array_u8<16>(result["address"].as_string())};
}
return view;
}
else
return std::nullopt;
}
virtual std::vector<Currency> get_currencies() override
{
vector<Currency> crc;
return crc;
}
virtual AccountStateWithProof
get_account_state_blob(string account_address) override
{
AccountStateWithProof asp;
string method = format(R"({"jsonrpc":"2.0","method":"get_account_state_with_proof","params":["%s", null, null],"id":1})", account_address.c_str());
string content_type = "application/json";
auto rpc_response = m_http_cli.request(methods::POST, "/", method, content_type)
.then([=](http_response response) -> pplx::task<json::value>
{
// printf("Response status code %u returned.\n", response.status_code());
if (response.status_code() != 200)
__throw_runtime_error(response.extract_string().get().c_str());
return response.extract_json(); })
.get();
auto error = rpc_response["error"];
if (!error.is_null())
__throw_runtime_error(("fun : get_account_state_blob, error : " + error.serialize()).c_str());
auto result = rpc_response["result"];
// cout << result.serialize() << endl;
asp.version = result["version"].as_integer();
auto blob = result["blob"];
// if (blob.is_null())
// __throw_runtime_error(("fun : get_account_state_blob, error : " + rpc_response.serialize()).c_str());
if (!blob.is_null())
asp.blob = blob.as_string();
asp.proof.ledger_info_to_transaction_info_proof = result["proof"]["ledger_info_to_transaction_info_proof"].as_string();
asp.proof.transaction_info = result["proof"]["transaction_info"].as_string();
asp.proof.transaction_info_to_account_proof = result["proof"]["transaction_info_to_account_proof"].as_string();
return asp;
}
virtual Task<AccountStateWithProof>
await_get_account_state_blob(string account_address) override
{
struct Awaitable
{
http_client &_http_cli;
const string &address;
json::value result;
bool await_ready() { return false; }
auto await_resume() { return result; }
void await_suspend(std::coroutine_handle<> h)
{
AccountStateWithProof asp;
string method = format(R"({"jsonrpc":"2.0","method":"get_account_state_with_proof","params":["%s", null, null],"id":1})", address.c_str());
string content_type = "application/json";
_http_cli.request(methods::POST, "/", method, content_type)
.then([=](http_response response) -> pplx::task<json::value>
{
if (response.status_code() != 200)
__throw_runtime_error(response.extract_string().get().c_str());
return response.extract_json(); })
.then([=](json::value rpc_response)
{
result = rpc_response;
h.resume(); });
}
};
auto rpc_response = co_await Awaitable{m_http_cli, account_address, {}};
AccountStateWithProof asp;
auto error = rpc_response["error"];
if (!error.is_null())
__throw_runtime_error(("fun : get_account_state_blob, error : " + error.serialize()).c_str());
auto result = rpc_response["result"];
// cout << result.serialize() << endl;
asp.version = result["version"].as_integer();
auto blob = result["blob"];
if (blob.is_null())
__throw_runtime_error(("json_rpc::await_get_account_state_blob, error : " + rpc_response.serialize()).c_str());
if (!blob.is_null())
asp.blob = blob.as_string();
asp.proof.ledger_info_to_transaction_info_proof = result["proof"]["ledger_info_to_transaction_info_proof"].as_string();
asp.proof.transaction_info = result["proof"]["transaction_info"].as_string();
asp.proof.transaction_info_to_account_proof = result["proof"]["transaction_info_to_account_proof"].as_string();
co_return asp;
}
virtual std::vector<EventView>
get_events(std::string event_key, uint64_t start, uint64_t limit, uint64_t rpc_id) override
{
vector<EventView> events;
string method = format(R"({"jsonrpc":"2.0","method":"get_events","params":["%s", %d, %d],"id":1})",
event_key.c_str(),
start,
limit,
rpc_id);
string content_type = "application/json";
auto rpc_response = m_http_cli.request(methods::POST, "/", method, content_type)
.then([=](http_response response) -> pplx::task<json::value>
{
if (response.status_code() != 200)
__throw_runtime_error(response.extract_string().get().c_str());
return response.extract_json(); })
.get();
auto error = rpc_response["error"];
if (!error.is_null())
__throw_runtime_error(("fun : get_events, error : " + error.serialize()).c_str());
auto result = rpc_response["result"];
for (auto &e : result.as_array())
{
// cout << e.serialize() << endl;
EventView ev;
ev.key = e["key"].as_string();
ev.sequence_number = e["sequence_number"].as_integer();
ev.transaction_version = e["transaction_version"].as_integer();
if (e["data"]["type"].as_string() == "unknown")
{
UnknownEvent ue;
ue.bytes = hex_to_bytes(e["data"]["bytes"].as_string());
ev.event = ue;
}
events.emplace_back(ev);
}
return events;
}
virtual Task<std::vector<EventView>>
await_get_events(std::string event_key, uint64_t start, uint64_t limit, uint64_t rpc_id = 1) override
{
string method = format(R"({"jsonrpc":"2.0","method":"get_events","params":["%s", %d, %d],"id":1})",
event_key.c_str(),
start,
limit,
rpc_id);
string content_type = "application/json";
struct Awaitable
{
http_client _http_client;
string _method;
string _content_type;
string _event_key;
json::value result;
bool await_ready() { return false; }
auto await_resume() { return result; }
void await_suspend(std::coroutine_handle<> h)
{
_http_client.request(methods::POST, "/", _method, _content_type)
.then([=](http_response response) -> pplx::task<json::value>
{
if (response.status_code() != 200)
__throw_runtime_error(response.extract_string().get().c_str());
return response.extract_json(); })
.then([=](json::value value)
{
result = value;
h.resume(); });
}
};
auto rpc_response = co_await Awaitable{m_http_cli, method, content_type};
auto error = rpc_response["error"];
if (!error.is_null())
__throw_runtime_error(("fun : get_events, error : " + error.serialize()).c_str());
vector<EventView> events;
auto result = rpc_response["result"];
for (auto &e : result.as_array())
{
// cout << e.serialize() << endl;
EventView ev;
ev.key = e["key"].as_string();
ev.sequence_number = e["sequence_number"].as_integer();
ev.transaction_version = e["transaction_version"].as_integer();
if (e["data"]["type"].as_string() == "unknown")
{
UnknownEvent ue;
ue.bytes = hex_to_bytes(e["data"]["bytes"].as_string());
ev.event = ue;
}
events.emplace_back(ev);
}
co_return events;
}
};
std::shared_ptr<Client>
Client::create(std::string_view url)
{
return make_shared<ClientImp>(url);
}
}
| 42.909091
| 159
| 0.473417
|
violas-core
|
a1c796e1d20d0cd9b45e813cf3b3102e62059d36
| 3,315
|
cpp
|
C++
|
src/sounds/Buzzer.cpp
|
iw4rr10r/gb-donkey-kong-jr
|
fe8e755b6c0c9c483ad543b6f2dce3168cdf989c
|
[
"MIT"
] | 5
|
2019-10-06T15:49:10.000Z
|
2020-01-18T19:37:33.000Z
|
src/sounds/Buzzer.cpp
|
iw4rr10r/gb-donkey-kong-jr
|
fe8e755b6c0c9c483ad543b6f2dce3168cdf989c
|
[
"MIT"
] | null | null | null |
src/sounds/Buzzer.cpp
|
iw4rr10r/gb-donkey-kong-jr
|
fe8e755b6c0c9c483ad543b6f2dce3168cdf989c
|
[
"MIT"
] | 1
|
2020-07-04T17:45:18.000Z
|
2020-07-04T17:45:18.000Z
|
// -------------------------------------------------------------------------
// Donkey Kong Jr
// a Nintendo's Game & Watch adaptation on Gamebuino META
// -------------------------------------------------------------------------
// © 2019 Steph
// https://gamebuino.com/@steph
// -------------------------------------------------------------------------
// Sound Effects Controller
// -------------------------------------------------------------------------
// loads the header file of the class
#include "Buzzer.h"
// initializes the properties of the controller
Sound Buzzer::toRepeat = Sound::None;
uint8_t Buzzer::counter = 0;
uint32_t Buzzer::timer = 0;
uint8_t Buzzer::delay = 0;
bool Buzzer::mute = false;
bool Buzzer::hasRepeated = false;
// control loop
void Buzzer::update() {
// if there are any sounds left to play...
if (counter > 0) {
// and once the break is over...
if (gb.frameCount - timer > delay) {
// we continue the replay
repeat(toRepeat, counter, delay);
}
// otherwise, the repetitive loop is interrupted
} else if (!hasRepeated && toRepeat != Sound::None && gb.frameCount - timer > delay) {
hasRepeated = true;
toRepeat = Sound::None;
}
}
// plays a specific sound without delay
void Buzzer::play(Sound sound) {
// only if the sound has not been muted
if (mute) return;
switch (sound) {
case Sound::Tick:
gb.sound.fx(FxTick);
break;
case Sound::Move:
gb.sound.fx(FxMove);
break;
case Sound::Score:
gb.sound.fx(FxScore);
break;
case Sound::Lost:
gb.sound.fx(FxLost);
break;
}
}
// initiates the repetition of a sound effect with a regular interval
void Buzzer::repeat(Sound sound, uint8_t count, uint8_t delay) {
play(sound);
toRepeat = sound;
counter = count - 1;
timer = gb.frameCount;
Buzzer::delay = delay;
hasRepeated = false;
}
// switch the mute indicator
void Buzzer::toggleMute() {
mute = !mute;
}
// -------------------------------------------------------------------------
// WAV sounds consume toooooo much CPU... 🙁 set up FX are much better!
// -------------------------------------------------------------------------
// I left the WAV sounds on the repository so you could eventually test the
// difference. But you'll see that you'll give up the idea like me...
//
// When installing the game, you will need to copy the `sounds` folder to
// the root of the game folder.
// -------------------------------------------------------------------------
// void Buzzer::play(Sound sound) {
// switch (sound) {
// case Sound::Tick:
// gb.sound.play("sounds/tick.wav");
// break;
// case Sound::Move:
// gb.sound.play("sounds/move.wav");
// break;
// case Sound::Score:
// gb.sound.play("sounds/score.wav");
// break;
// case Sound::Lost:
// gb.sound.play("sounds/lost.wav");
// break;
// }
// }
| 33.826531
| 90
| 0.460633
|
iw4rr10r
|
a1c893b151b1541f61768c2725659cf1b48d9591
| 1,957
|
cpp
|
C++
|
src/box_type.cpp
|
tnoho/cpp-mp4
|
3686ee530a459a554dee1a5d21a93a537c04e4e0
|
[
"Apache-2.0"
] | null | null | null |
src/box_type.cpp
|
tnoho/cpp-mp4
|
3686ee530a459a554dee1a5d21a93a537c04e4e0
|
[
"Apache-2.0"
] | null | null | null |
src/box_type.cpp
|
tnoho/cpp-mp4
|
3686ee530a459a554dee1a5d21a93a537c04e4e0
|
[
"Apache-2.0"
] | null | null | null |
#include "shiguredo/mp4/box_type.hpp"
#include <fmt/core.h>
#include <algorithm>
#include <array>
#include <cctype>
#include <cstdint>
#include <iterator>
#include <regex>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
namespace shiguredo::mp4 {
BoxType::BoxType(const std::string& str) {
if (std::size(str) != 4) {
throw std::invalid_argument(fmt::format("BoxType::BoxType(): invalid box type id length: [{}]", str));
}
m_data[0] = static_cast<std::uint8_t>(str[0]);
m_data[1] = static_cast<std::uint8_t>(str[1]);
m_data[2] = static_cast<std::uint8_t>(str[2]);
m_data[3] = static_cast<std::uint8_t>(str[3]);
}
BoxType::BoxType(const std::array<std::uint8_t, 4>& t_data) : m_data(t_data) {}
void BoxType::setData(const std::uint8_t d0, const std::uint8_t d1, const std::uint8_t d2, const std::uint8_t d3) {
m_data[0] = d0;
m_data[1] = d1;
m_data[2] = d2;
m_data[3] = d3;
}
std::array<std::uint8_t, 4> BoxType::getData() const {
return m_data;
}
bool BoxType::operator<(const BoxType& r) const {
return m_data < r.getData();
}
bool BoxType::operator==(const BoxType& r) const {
return m_data == r.getData();
}
std::string BoxType::toString() const {
if (std::all_of(std::begin(m_data), std::end(m_data),
[](const std::uint8_t ch) { return std::isprint(ch) != 0 || ch == 0xa9; })) {
auto s = std::string(std::begin(m_data), std::end(m_data));
return std::regex_replace(s, std::regex("\x00a9"), "©");
}
return fmt::format("0x{:02x}{:02x}{:02x}{:02x}", m_data[0], m_data[1], m_data[2], m_data[3]);
}
bool BoxType::matchWith(const BoxType& other) const {
const auto boxTypeAny = box_type_any();
if (*this == boxTypeAny || other == boxTypeAny) {
return true;
}
return *this == other;
}
BoxType box_type_any() {
static BoxType boxTypeAny(std::array<std::uint8_t, 4>{0x00, 0x00, 0x00, 0x00});
return boxTypeAny;
}
} // namespace shiguredo::mp4
| 27.180556
| 115
| 0.650996
|
tnoho
|
a1cba7d5801215052aff070ab51177e29b5a4f9c
| 920
|
cpp
|
C++
|
src/core/simulate/src/dunesim_impl.cpp
|
henryiii/spatial-model-editor
|
2138d03ae4c7cc353b40324dfd1a3e763d7085d9
|
[
"MIT"
] | 1
|
2021-04-19T10:23:58.000Z
|
2021-04-19T10:23:58.000Z
|
src/core/simulate/src/dunesim_impl.cpp
|
henryiii/spatial-model-editor
|
2138d03ae4c7cc353b40324dfd1a3e763d7085d9
|
[
"MIT"
] | 418
|
2020-10-08T07:42:27.000Z
|
2022-03-08T12:10:52.000Z
|
src/core/simulate/src/dunesim_impl.cpp
|
henryiii/spatial-model-editor
|
2138d03ae4c7cc353b40324dfd1a3e763d7085d9
|
[
"MIT"
] | 2
|
2021-09-02T11:20:38.000Z
|
2021-10-13T14:05:32.000Z
|
#include "dunesim_impl.hpp"
#include "duneconverter.hpp"
#include "dunegrid.hpp"
#include "logger.hpp"
namespace sme::simulate {
DuneImpl::DuneImpl(const simulate::DuneConverter &dc) {
for (const auto &ini : dc.getIniFiles()) {
std::stringstream ssIni(ini.toStdString());
auto &config = configs.emplace_back();
Dune::ParameterTreeParser::readINITree(ssIni, config);
}
// init Dune logging if not already done
if (!Dune::Logging::Logging::initialized()) {
Dune::Logging::Logging::init(
Dune::FakeMPIHelper::getCollectiveCommunication(),
configs[0].sub("logging"));
if (SPDLOG_ACTIVE_LEVEL > SPDLOG_LEVEL_DEBUG) {
// for release builds disable DUNE logging
Dune::Logging::Logging::mute();
}
}
// construct grid
std::tie(grid, hostGrid) = makeDuneGrid<HostGrid, MDGTraits>(*dc.getMesh());
}
DuneImpl::~DuneImpl() = default;
} // namespace sme::simulate
| 29.677419
| 78
| 0.68587
|
henryiii
|
a1cdea98253f76592ae406b07acc3f0ead46e044
| 1,676
|
cpp
|
C++
|
test/unit/jt_test/box2d_joint_test.cpp
|
Thunraz/JamTemplateCpp
|
ee516d8a57dcfa6e7997585ab9bd7ff7df3640ea
|
[
"CC0-1.0"
] | null | null | null |
test/unit/jt_test/box2d_joint_test.cpp
|
Thunraz/JamTemplateCpp
|
ee516d8a57dcfa6e7997585ab9bd7ff7df3640ea
|
[
"CC0-1.0"
] | null | null | null |
test/unit/jt_test/box2d_joint_test.cpp
|
Thunraz/JamTemplateCpp
|
ee516d8a57dcfa6e7997585ab9bd7ff7df3640ea
|
[
"CC0-1.0"
] | null | null | null |
#include "box2d_joint.hpp"
#include "mocks/box2d_world_mock.hpp"
#include "mocks/mock_game.hpp"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
using namespace ::testing;
class Box2dJointTest : public ::testing::Test {
public:
std::shared_ptr<Box2DWorldMock> m_mockWorld;
void SetUp() override { m_mockWorld = std::make_shared<NiceMock<Box2DWorldMock>>(); }
};
TEST_F(Box2dJointTest, ConstructorCallsCreateJoint)
{
EXPECT_CALL(*m_mockWorld, createJoint(nullptr));
jt::Box2DJoint joint { m_mockWorld, nullptr };
}
TEST_F(Box2dJointTest, GetBodyReturnsNullptrWhenCreatedWithNullptrJointDef)
{
jt::Box2DJoint joint { m_mockWorld, nullptr };
EXPECT_EQ(joint.getB2Joint(), nullptr);
}
TEST_F(Box2dJointTest, Create)
{
jt::Box2DJoint joint { m_mockWorld, nullptr };
auto g = std::make_shared<MockGame>();
joint.setGameInstance(g);
joint.create();
SUCCEED();
}
TEST_F(Box2dJointTest, Update)
{
jt::Box2DJoint joint { m_mockWorld, nullptr };
joint.update(1.0f);
SUCCEED();
}
TEST_F(Box2dJointTest, Draw)
{
jt::Box2DJoint joint { m_mockWorld, nullptr };
joint.draw();
SUCCEED();
}
TEST_F(Box2dJointTest, DestroyCallsDestroyJointOnWorld)
{
jt::Box2DJoint joint { m_mockWorld, nullptr };
EXPECT_CALL(*m_mockWorld, destroyJoint(_));
joint.destroy();
}
TEST_F(Box2dJointTest, DestroyJointWithoutWorld)
{
jt::Box2DJoint joint { m_mockWorld, nullptr };
m_mockWorld.reset();
joint.destroy();
}
TEST_F(Box2dJointTest, CreateJointWithNullptrWorldRaisesException)
{
auto func = []() { jt::Box2DJoint joint { nullptr, nullptr }; };
ASSERT_THROW(func(), std::invalid_argument);
}
| 22.958904
| 89
| 0.713604
|
Thunraz
|
a1d04f04c3dab7531aaa6a32c18821df6a9a8a5d
| 316
|
cpp
|
C++
|
src/pot.cpp
|
JulianNeeleman/kattis
|
035c1113ffb397c2d8538af8ba16b7ee4160393d
|
[
"MIT"
] | null | null | null |
src/pot.cpp
|
JulianNeeleman/kattis
|
035c1113ffb397c2d8538af8ba16b7ee4160393d
|
[
"MIT"
] | 1
|
2017-05-16T15:57:29.000Z
|
2017-05-17T19:43:56.000Z
|
src/pot.cpp
|
JulianNeeleman/kattis
|
035c1113ffb397c2d8538af8ba16b7ee4160393d
|
[
"MIT"
] | null | null | null |
#include <algorithm>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <vector>
using namespace std;
int main() {
int N, ans = 0;
cin >> N;
for(int i = 0; i < N; i++) {
int P;
cin >> P;
int b = P / 10,
e = P % 10;
ans += pow(b, e);
}
cout << ans << endl;
return 0;
}
| 11.703704
| 29
| 0.531646
|
JulianNeeleman
|
a1d9290a99edc51de314d70e72f64b04709f91a8
| 3,211
|
cpp
|
C++
|
aws-cpp-sdk-lexv2-models/source/model/ExportSummary.cpp
|
perfectrecall/aws-sdk-cpp
|
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
|
[
"Apache-2.0"
] | 1
|
2022-02-12T08:09:30.000Z
|
2022-02-12T08:09:30.000Z
|
aws-cpp-sdk-lexv2-models/source/model/ExportSummary.cpp
|
perfectrecall/aws-sdk-cpp
|
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
|
[
"Apache-2.0"
] | 1
|
2022-01-03T23:59:37.000Z
|
2022-01-03T23:59:37.000Z
|
aws-cpp-sdk-lexv2-models/source/model/ExportSummary.cpp
|
ravindra-wagh/aws-sdk-cpp
|
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
|
[
"Apache-2.0"
] | 1
|
2021-11-09T11:58:03.000Z
|
2021-11-09T11:58:03.000Z
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/lexv2-models/model/ExportSummary.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace LexModelsV2
{
namespace Model
{
ExportSummary::ExportSummary() :
m_exportIdHasBeenSet(false),
m_resourceSpecificationHasBeenSet(false),
m_fileFormat(ImportExportFileFormat::NOT_SET),
m_fileFormatHasBeenSet(false),
m_exportStatus(ExportStatus::NOT_SET),
m_exportStatusHasBeenSet(false),
m_creationDateTimeHasBeenSet(false),
m_lastUpdatedDateTimeHasBeenSet(false)
{
}
ExportSummary::ExportSummary(JsonView jsonValue) :
m_exportIdHasBeenSet(false),
m_resourceSpecificationHasBeenSet(false),
m_fileFormat(ImportExportFileFormat::NOT_SET),
m_fileFormatHasBeenSet(false),
m_exportStatus(ExportStatus::NOT_SET),
m_exportStatusHasBeenSet(false),
m_creationDateTimeHasBeenSet(false),
m_lastUpdatedDateTimeHasBeenSet(false)
{
*this = jsonValue;
}
ExportSummary& ExportSummary::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("exportId"))
{
m_exportId = jsonValue.GetString("exportId");
m_exportIdHasBeenSet = true;
}
if(jsonValue.ValueExists("resourceSpecification"))
{
m_resourceSpecification = jsonValue.GetObject("resourceSpecification");
m_resourceSpecificationHasBeenSet = true;
}
if(jsonValue.ValueExists("fileFormat"))
{
m_fileFormat = ImportExportFileFormatMapper::GetImportExportFileFormatForName(jsonValue.GetString("fileFormat"));
m_fileFormatHasBeenSet = true;
}
if(jsonValue.ValueExists("exportStatus"))
{
m_exportStatus = ExportStatusMapper::GetExportStatusForName(jsonValue.GetString("exportStatus"));
m_exportStatusHasBeenSet = true;
}
if(jsonValue.ValueExists("creationDateTime"))
{
m_creationDateTime = jsonValue.GetDouble("creationDateTime");
m_creationDateTimeHasBeenSet = true;
}
if(jsonValue.ValueExists("lastUpdatedDateTime"))
{
m_lastUpdatedDateTime = jsonValue.GetDouble("lastUpdatedDateTime");
m_lastUpdatedDateTimeHasBeenSet = true;
}
return *this;
}
JsonValue ExportSummary::Jsonize() const
{
JsonValue payload;
if(m_exportIdHasBeenSet)
{
payload.WithString("exportId", m_exportId);
}
if(m_resourceSpecificationHasBeenSet)
{
payload.WithObject("resourceSpecification", m_resourceSpecification.Jsonize());
}
if(m_fileFormatHasBeenSet)
{
payload.WithString("fileFormat", ImportExportFileFormatMapper::GetNameForImportExportFileFormat(m_fileFormat));
}
if(m_exportStatusHasBeenSet)
{
payload.WithString("exportStatus", ExportStatusMapper::GetNameForExportStatus(m_exportStatus));
}
if(m_creationDateTimeHasBeenSet)
{
payload.WithDouble("creationDateTime", m_creationDateTime.SecondsWithMSPrecision());
}
if(m_lastUpdatedDateTimeHasBeenSet)
{
payload.WithDouble("lastUpdatedDateTime", m_lastUpdatedDateTime.SecondsWithMSPrecision());
}
return payload;
}
} // namespace Model
} // namespace LexModelsV2
} // namespace Aws
| 23.785185
| 117
| 0.760822
|
perfectrecall
|
a1db887ad3e0071857721412f59e517d367fff9b
| 2,017
|
cpp
|
C++
|
Contests/Atcoder_ABC_222/probF.cpp
|
francoisvogel/cp
|
ae59cf635ab19382d924344fbb137ab9ae631103
|
[
"MIT"
] | 1
|
2021-10-02T15:40:33.000Z
|
2021-10-02T15:40:33.000Z
|
Contests/Atcoder_ABC_222/probF.cpp
|
francoisvogel/cp
|
ae59cf635ab19382d924344fbb137ab9ae631103
|
[
"MIT"
] | null | null | null |
Contests/Atcoder_ABC_222/probF.cpp
|
francoisvogel/cp
|
ae59cf635ab19382d924344fbb137ab9ae631103
|
[
"MIT"
] | null | null | null |
/*
* File created on 10/09/2021 at 14:56:58.
* Link to problem:
* Description:
* Time complexity: O()
* Space complexity: O()
* Status: DEV (most of the time I don't update status, so it stays DEV which is the default value)
* Copyright: Ⓒ 2021 Francois Vogel
*/
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <functional>
using namespace std;
using namespace __gnu_pbds;
#define pii pair<int, int>
#define f first
#define s second
#define vi vector<int>
#define all(x) x.begin(), x.end()
#define size(x) (int)(x.size())
#define pb push_back
#define ins insert
#define cls clear
#define int ll
#define ll long long
#define ld long double
typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;
const int siz = 2e5+40;
vector<pii> graph [siz];
int cost [siz];
int mx [siz];
int furthest [siz];
void dfs(int x, int p) {
mx[x] = cost[x];
for (pii y : graph[x]) if (y.f != p) {
dfs(y.f, x);
mx[x] = max(mx[x], mx[y.f]+y.s);
}
}
void calc(int x, int p, int till) {
furthest[x] = till;
vi ms;
ms.pb(cost[x]);
ms.pb(till);
for (pii y : graph[x]) if (y.f != p) {
int loc = mx[y.f]+y.s;
ms.pb(loc);
furthest[x] = max(furthest[x], loc);
}
sort(all(ms));
for (pii y : graph[x]) if (y.f != p) {
int loc = ms.back();
if (ms.back() == mx[y.f]+y.s) loc = ms[size(ms)-2];
loc += y.s;
calc(y.f, x, loc);
}
}
signed main() {
cin.tie(0);
ios_base::sync_with_stdio(0);
int n;
cin >> n;
for (int i = 0; i < n-1; i++) {
int na, nb, lw;
cin >> na >> nb >> lw;
na--;
nb--;
graph[na].pb(pii(nb, lw));
graph[nb].pb(pii(na, lw));
}
for (int i = 0; i < n; i++) cin >> cost[i];
dfs(0, -1);
calc(0, -1, 0);
for (int i = 0; i < n; i++) cout << furthest[i] << '\n';
cout.flush();
int d = 0;
d++;
}
| 21.923913
| 100
| 0.548339
|
francoisvogel
|
a1df9c9046e271bdf30acb12203b7fba722c1f0a
| 3,044
|
hpp
|
C++
|
src/opencv_bridge/shape_finder_impl.hpp
|
cognitive-machines/garooda-core
|
509f54ad0db7916f963418e5c5af302dbacf1147
|
[
"MIT"
] | null | null | null |
src/opencv_bridge/shape_finder_impl.hpp
|
cognitive-machines/garooda-core
|
509f54ad0db7916f963418e5c5af302dbacf1147
|
[
"MIT"
] | null | null | null |
src/opencv_bridge/shape_finder_impl.hpp
|
cognitive-machines/garooda-core
|
509f54ad0db7916f963418e5c5af302dbacf1147
|
[
"MIT"
] | 1
|
2018-04-11T15:20:14.000Z
|
2018-04-11T15:20:14.000Z
|
/*
MIT License
Copyright (c) 2018 Cognitive Machines
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#ifndef __opencv__bridge__shape__finder__impl__hpp__
#define __opencv__bridge__shape__finder__impl__hpp__
#include "../common_includes.hpp"
#include "../computed_result.hpp"
#include "../json_reader.hpp"
using namespace cv;
using namespace std;
namespace cm {
namespace lib_bridge {
const int k_threshold_min = 0 ;
const int k_threshold_max = 255 ;
bool circle_finder_impl(Mat& in,
double dp,
double min_dist,
double canny_param_1,
double canny_param_2,
int min_radius,
int max_radius,
bool clear_and_add,
computed_objects & circles_found);
bool rectangle_finder_impl(Mat &in,
int threshold_step,
double shape_appoximator_ratio,
double min_contour_area,
double max_contour_area,
double cosine_angle,
bool clear_and_add,
computed_objects & rectangles_found);
bool line_finder_impl(Mat &in,
double rho,
double theta,
double threshold,
double length_factor,
double max_seperation,
bool clear_and_add,
computed_objects & lines_found);
//Utility functions
double angle_between_points(cv::Point pt1, cv::Point pt2, cv::Point pt0);
bool get_tracker(Mat & image1, Mat & image2, cm::rectangle_i &tracker, int min_good_features, int nfeatures);
void drawBoundingBox(Mat image, vector<Point2f> bb);
struct time_counter
{
TickMeter tm;
explicit time_counter() {
tm.start();
}
~time_counter() {
tm.stop();
CM_LOG << "FPS = " << 1.0 / tm.getTimeSec() << std::endl;
}
};
}
}
#endif
| 32.042105
| 109
| 0.639947
|
cognitive-machines
|
a1e4e796164e3a04eb35f74968455d8692f77745
| 1,274
|
cpp
|
C++
|
src/constexpr/static_assert2.cpp
|
victorcruceru/my_tour_of_cplusplus
|
c9627e9355a8cf6eaa8f5d51a0001947cfe86e48
|
[
"Beerware"
] | null | null | null |
src/constexpr/static_assert2.cpp
|
victorcruceru/my_tour_of_cplusplus
|
c9627e9355a8cf6eaa8f5d51a0001947cfe86e48
|
[
"Beerware"
] | null | null | null |
src/constexpr/static_assert2.cpp
|
victorcruceru/my_tour_of_cplusplus
|
c9627e9355a8cf6eaa8f5d51a0001947cfe86e48
|
[
"Beerware"
] | 1
|
2021-06-21T07:22:10.000Z
|
2021-06-21T07:22:10.000Z
|
/*
* ----------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* Victor Cruceru wrote this file. As long as you retain this notice you
* can do whatever you want with this stuff. If we meet some day, and you think
* this stuff is worth it, you can buy me a beer in return.
* ----------------------------------------------------------------------------
*/
/*
* Description: Trying static_assert (compile time check) in various
* scenarios like template parameters and basic types.
*/
#include <cstdlib>
#include <iostream>
#include <string>
#include <type_traits>
/* check a template parameter value */
template <typename T, size_t L>
struct Record { // struct is just a class with all members public
static_assert(L >= 1, "Length must be a scalar >= 1");
T vector[L];
};
int main() {
// Record<std::string, 0> failed_rec; // This fails at compile time
Record<int, 10> ok_rec; // This is OK.
ok_rec = {{1, 2, 3}};
// Next two might fail or not at compile time depending on your machine
static_assert(sizeof(int) == 4, "int type must be of size 4");
static_assert(sizeof(int *) == 8, "int* pointer type must be of size 8");
return (EXIT_SUCCESS);
}
| 35.388889
| 80
| 0.584772
|
victorcruceru
|
a1e7fe36b81ac869fa99a279404946eada191401
| 4,095
|
cpp
|
C++
|
Brain/sustain.cpp
|
vikbez/PlayerPianoController
|
098e0a9df2be3d029490986eedd1bf2eac0a44ca
|
[
"MIT"
] | null | null | null |
Brain/sustain.cpp
|
vikbez/PlayerPianoController
|
098e0a9df2be3d029490986eedd1bf2eac0a44ca
|
[
"MIT"
] | null | null | null |
Brain/sustain.cpp
|
vikbez/PlayerPianoController
|
098e0a9df2be3d029490986eedd1bf2eac0a44ca
|
[
"MIT"
] | null | null | null |
#include "sustain.h"
#include "sustain.h"
#include "serial.h"
#include "settings.h"
#include "note.h"
SustainPedal sustain;
SustainPedal::SustainPedal()
{
//initialize one row of vectors so program won't crash while comparing
//initialize sustain as off by default
for(int index = 0; index < 4; index++)
{
schedule[index].reserve(6);
schedule[index].resize(1);
}
schedule[OFF].push_back(millis());
}
void SustainPedal::prepareToSchedule(uint8_t velocity)
{
const uint8_t SUSTAIN_MIN_VELOCITY = 64;
if(Setting::handleNotes && Setting::scheduleNotes)
{
if(velocity < SUSTAIN_MIN_VELOCITY)
{
scheduleSustain(false);
} else if(instances == 0) //only schedule if sustain is off
scheduleSustain(true);
} else
{
if(velocity < SUSTAIN_MIN_VELOCITY)
sendMidiToProMicro(SUSTAIN_NOTE, 0); // ledcWrite(0, 0);
else
sendMidiToProMicro(SUSTAIN_NOTE, 127); // ledcWrite(0, 255);
}
}
void SustainPedal::checkSchedule()
{
unsigned long ms = millis();
//less checks for sustain because it's slower and less important
if(schedule[OFF].size() > 1 && schedule[DEACTIVATION].size() > 1 &&
ms >= schedule[OFF].at(1) && schedule[OFF].at(1) >= schedule[DEACTIVATION].at(1))
{
schedule[DEACTIVATION].erase(schedule[DEACTIVATION].begin()++);
sendMidiToProMicro(SUSTAIN_NOTE, 0); // ledcWrite(0, 0);
}
if(schedule[ACTIVATION].size() > 1 && schedule[OFF].size() > 1 &&
ms >= schedule[ACTIVATION].at(1) && schedule[ACTIVATION].at(1) >= schedule[OFF].at(1))
{
schedule[OFF].erase(schedule[OFF].begin()++);
sendMidiToProMicro(SUSTAIN_NOTE, 127); // ledcWrite(0, 255);
}
if(schedule[ON].size() > 1 && schedule[ACTIVATION].size() > 1 &&
ms >= schedule[ON].at(1) && schedule[ON].at(1) >= schedule[ACTIVATION].at(1))
{
schedule[ACTIVATION].erase(schedule[ACTIVATION].begin()++);
}
if(schedule[DEACTIVATION].size() > 1 && schedule[ON].size() > 1 &&
ms >= schedule[DEACTIVATION].at(1) && schedule[DEACTIVATION].at(1) >= schedule[ON].at(1))
{
schedule[ON].erase(schedule[ON].begin()++);
sendMidiToProMicro(SUSTAIN_NOTE, 15); // ledcWrite(0, 30);
}
}
void SustainPedal::checkForErrors()
{
unsigned long ms = millis();
if(ms >= timeSinceActivation + Setting::sustainTimeoutMs && timeSinceActivation > 0) resetSchedule();
if(schedule[ON].size() > 1) if(ms >= schedule[ON].at(1) + Setting::sustainTimeoutMs) resetSchedule();
}
void SustainPedal::resetSchedule()
{
for(int index = 0; index < 4; index++)
schedule[index].resize(1);
schedule[OFF].push_back(millis());
timeSinceActivation = 0;
instances = 0;
sendMidiToProMicro(SUSTAIN_NOTE, 0); // ledcWrite(0, 0);
}
void SustainPedal::scheduleSustain(bool state)
{
unsigned long ms = millis();
unsigned long msAndDelay = ms + fullDelay;
using namespace Setting;
if(state)
{
if(msAndDelay - sustainOnMs >= schedule[OFF].back()) //if sustain can be scheduled with current scheduling
{
schedule[ACTIVATION].push_back(msAndDelay - sustainOnMs);
schedule[ON]. push_back(msAndDelay);
timeSinceActivation = ms;
instances++;
} else if(msAndDelay - sustainOffMs - sustainOnMs >= schedule[ON].back()) //if current scheduling can be modified to still schedule the sustain
{
schedule[ON]. push_back(msAndDelay - sustainOnMs - sustainOffMs);
schedule[ON]. erase(----schedule[ON].end());
schedule[OFF]. push_back(msAndDelay - sustainOnMs);
schedule[OFF]. erase(----schedule[OFF].end());
schedule[ACTIVATION].push_back(msAndDelay - sustainOnMs);
schedule[ON]. push_back(msAndDelay);
timeSinceActivation = ms;
instances++;
}
} else if(instances > 0) //if sustain off command and sustain is not already off
{
instances = 0;
if(msAndDelay - sustainOffMs >= schedule[ON].back()) //if sustain can be ideally deactivated
{
schedule[DEACTIVATION].push_back(msAndDelay - sustainOffMs);
schedule[OFF]. push_back(msAndDelay);
} else //deactivate sustain anyways so it's not stuck on
{
schedule[DEACTIVATION].push_back(msAndDelay);
schedule[OFF]. push_back(msAndDelay + sustainOffMs);
}
}
}
| 33.024194
| 145
| 0.689133
|
vikbez
|
a1ec0ab68080b9c9b82ce1e5dabc4fbc18dde4ab
| 721
|
hpp
|
C++
|
src/org/apache/poi/ss/formula/functions/Sumx2py2_1.hpp
|
pebble2015/cpoi
|
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
|
[
"Apache-2.0"
] | null | null | null |
src/org/apache/poi/ss/formula/functions/Sumx2py2_1.hpp
|
pebble2015/cpoi
|
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
|
[
"Apache-2.0"
] | null | null | null |
src/org/apache/poi/ss/formula/functions/Sumx2py2_1.hpp
|
pebble2015/cpoi
|
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
|
[
"Apache-2.0"
] | null | null | null |
// Generated from /POI/java/org/apache/poi/ss/formula/functions/Sumx2py2.java
#pragma once
#include <fwd-POI.hpp>
#include <org/apache/poi/ss/formula/functions/fwd-POI.hpp>
#include <java/lang/Object.hpp>
#include <org/apache/poi/ss/formula/functions/XYNumericFunction_Accumulator.hpp>
struct default_init_tag;
class poi::ss::formula::functions::Sumx2py2_1
: public virtual ::java::lang::Object
, public virtual XYNumericFunction_Accumulator
{
public:
typedef ::java::lang::Object super;
double accumulate(double x, double y) override;
// Generated
Sumx2py2_1();
static ::java::lang::Class *class_();
private:
virtual ::java::lang::Class* getClass0();
friend class Sumx2py2;
};
| 24.862069
| 80
| 0.725381
|
pebble2015
|
a1ec56221d0b2b9656ed3614ab88d3b3b68e6598
| 3,724
|
cpp
|
C++
|
tests/tests/referral_mandatory_transfer_test.cpp
|
edinar-dev/edinarcoin
|
d3f11ab57acd745fd407f87999f2ab72378f5194
|
[
"MIT"
] | 1
|
2019-08-05T08:09:37.000Z
|
2019-08-05T08:09:37.000Z
|
tests/tests/referral_mandatory_transfer_test.cpp
|
reactivespace/Dex
|
d5716eab035f993dad3e5b4df664f9ebd32ab3a0
|
[
"MIT"
] | null | null | null |
tests/tests/referral_mandatory_transfer_test.cpp
|
reactivespace/Dex
|
d5716eab035f993dad3e5b4df664f9ebd32ab3a0
|
[
"MIT"
] | null | null | null |
#include <boost/test/unit_test.hpp>
#include <graphene/chain/database.hpp>
#include <graphene/chain/exceptions.hpp>
#include <graphene/chain/hardfork.hpp>
#include <graphene/chain/account_object.hpp>
#include <graphene/chain/asset_object.hpp>
#include <graphene/chain/committee_member_object.hpp>
#include <graphene/chain/proposal_object.hpp>
#include <fc/crypto/digest.hpp>
#include "../common/database_fixture.hpp"
#include "../common/test_utils.hpp"
using namespace graphene::chain;
using namespace graphene::chain::test;
#define MEASURE_TIME(operation, description) \
auto start = fc::time_point::now(); \
operation; \
std::cout << " "<< description <<" completed in " \
<< (fc::time_point::now() - start).count() / 1000000.0 \
<< " seconds " << std::endl;
BOOST_FIXTURE_TEST_SUITE( referral_mandatory_transfer_test, database_fixture )
BOOST_AUTO_TEST_CASE( no_out_transaction_issue_test )
{
try {
ACTOR(alice);
transfer(committee_account, alice_id, asset(300000, asset_id_type()));
generate_block();
transaction_evaluation_state evalState(&db);
referral_issue_operation ref_op;
ref_op.issue_to_account = alice_id;
ref_op.asset_to_issue = asset(1, asset_id_type());
ref_op.issuer = account_id_type(3);
BOOST_REQUIRE_THROW(db.apply_operation(evalState, ref_op), fc::exception);
} catch (fc::exception& e) {
edump((e.to_detail_string()));
throw;
}
}
BOOST_AUTO_TEST_CASE( recent_out_transaction_issue_test )
{
try {
ACTOR(alice);
transfer(committee_account, alice_id, asset(300000, asset_id_type()));
transfer(alice_id, committee_account, asset(1000, asset_id_type()));
generate_block();
transaction_evaluation_state evalState(&db);
referral_issue_operation ref_op;
ref_op.issue_to_account = alice_id;
ref_op.asset_to_issue = asset(1, asset_id_type());
ref_op.issuer = account_id_type(3);
BOOST_REQUIRE_NO_THROW(db.apply_operation(evalState, ref_op));
} catch (fc::exception& e) {
edump((e.to_detail_string()));
throw;
}
}
BOOST_AUTO_TEST_CASE( old_out_transaction_issue_test )
{
try {
ACTOR(alice);
transfer(committee_account, alice_id, asset(300000, asset_id_type()));
transfer(alice_id, committee_account, asset(1000, asset_id_type()));
generate_block();
fc::time_point_sec target = db.head_block_time() + fc::hours(24);
while(db.head_block_time() < target)
{
generate_block();
}
transaction_evaluation_state evalState(&db);
referral_issue_operation ref_op;
ref_op.issue_to_account = alice_id;
ref_op.asset_to_issue = asset(1, asset_id_type());
ref_op.issuer = account_id_type(3);
MEASURE_TIME(
BOOST_REQUIRE_THROW(db.apply_operation(evalState, ref_op), fc::exception),
"apply operation"
);
} catch (fc::exception& e) {
edump((e.to_detail_string()));
throw;
}
}
BOOST_AUTO_TEST_CASE( appply_time_test_tx_each_block )
{
ACTOR(alice);
fc::time_point_sec target = db.head_block_time() + fc::hours(24);
while(db.head_block_time() < target)
{
transfer(committee_account, alice_id, asset(1, asset_id_type()));
generate_block();
}
transaction_evaluation_state evalState(&db);
referral_issue_operation ref_op;
ref_op.issue_to_account = alice_id;
ref_op.asset_to_issue = asset(1, asset_id_type());
ref_op.issuer = account_id_type(3);
MEASURE_TIME(
BOOST_REQUIRE_THROW(db.apply_operation(evalState, ref_op), fc::exception),
"apply operation"
);
}
BOOST_AUTO_TEST_SUITE_END()
| 25.861111
| 86
| 0.686627
|
edinar-dev
|
a1ec7be46d1d5dec918d69c61a92522de5ab7d54
| 8,633
|
cpp
|
C++
|
src/backend/graph_compiler/core/src/compiler/ir/ir_module.cpp
|
wuxun-zhang/mkl-dnn
|
00a239ad2c932b967234ffb528069800ffcc0334
|
[
"Apache-2.0"
] | null | null | null |
src/backend/graph_compiler/core/src/compiler/ir/ir_module.cpp
|
wuxun-zhang/mkl-dnn
|
00a239ad2c932b967234ffb528069800ffcc0334
|
[
"Apache-2.0"
] | null | null | null |
src/backend/graph_compiler/core/src/compiler/ir/ir_module.cpp
|
wuxun-zhang/mkl-dnn
|
00a239ad2c932b967234ffb528069800ffcc0334
|
[
"Apache-2.0"
] | null | null | null |
/*******************************************************************************
* Copyright 2020-2022 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
#include "ir_module.hpp"
#include <atomic>
#include <utility>
#include "builder.hpp"
#include "pass/func_dependency.hpp"
#include "visitor.hpp"
#include <unordered_set>
#include <util/any_map.hpp>
namespace sc {
static std::atomic<int> rename_cnt = {0};
// this pass will
// break the link from call_nodes to function nodes with bodies
class func_unlinker_t : public ir_inplace_visitor_t {
public:
using ir_inplace_visitor_t::dispatch_impl;
expr visit_impl(call c) override {
auto ret = ir_inplace_visitor_t::visit_impl(std::move(c)).as<call>();
func_t callee = ret->func_;
// if the callee has a function body, unlink the call_node with the
// function with body. Use the decl_ instead
if (callee->body_.defined()) {
assert(callee->decl_);
callee = callee->decl_;
return builder::remake_call(callee, ret->args_, ret);
} else {
assert(!callee->decl_);
}
// if the call is to a decl_, no changes
return ret;
}
func_t dispatch_impl(func_t f) override {
if (f->decl_) {
if (f->decl_->name_ != f->name_) { f->decl_->name_ = f->name_; }
}
return ir_inplace_visitor_t::dispatch_impl(std::move(f));
}
};
std::shared_ptr<ir_module_t> ir_module_t::from_entry_func(
context_ptr ctx, func_t funct) {
auto ret = from_entry_func(
std::move(ctx), std::vector<func_t> {std::move(funct)});
ret->entry_func_idx_ = 0;
return ret;
}
// resolve function dependency, returns funcs with their dependency
static std::vector<func_t> resolve_func(const std::vector<func_t> &funcs) {
std::vector<func_t> dep;
std::unordered_set<func_t> set;
func_dependency_finder_t finder(dep);
for (auto &f : funcs) {
if (set.find(f) != set.end()) { continue; }
dep.emplace_back(f);
set.insert(f);
size_t old_size = 0;
do {
size_t last_size = old_size;
old_size = set.size();
// run dependency_finder on newly added functions
for (size_t i = last_size; i < dep.size(); i++) {
finder(dep[i], set);
}
assert(set.size() == dep.size());
// if old_size == set.size(), no dependency added, can exit
} while (old_size != set.size());
}
return dep;
}
std::shared_ptr<ir_module_t> ir_module_t::from_entry_func(
context_ptr ctx, const std::vector<func_t> &funcs) {
auto ret = std::make_shared<ir_module_t>(std::move(ctx));
ret->add_resolved_func(resolve_func(funcs));
return ret;
}
ir_module_t *ir_module_t::merge(const ir_module_t &m) {
assert(m.ctx_ == ctx_);
add_resolved_func(m.get_contents());
for (auto &v : m.module_vars_) {
add_global_var(v);
}
return this;
}
ir_module_t *ir_module_t::merge(const std::vector<ir_module_ptr> &list) {
for (auto &m : list) {
merge(*m);
}
return this;
}
func_t ir_module_t::get_func(const std::string &name) const {
auto itr = symbols_.find(name);
if (itr != symbols_.end()) { return contents_.at(itr->second); }
return func_t();
}
ir_module_ptr ir_module_t::copy() const {
return std::make_shared<ir_module_t>(*this);
}
void ir_module_t::add_func(const std::vector<func_t> &funcs) {
add_resolved_func(resolve_func(funcs));
}
var ir_module_t::make_global_var(sc_data_type_t dtype, const std::string &name,
linkage linkage, expr init) {
var ret = builder::make_var(dtype, name).static_as<var>();
auto def = builder::make_var_tensor_def_unattached(
ret, linkage, std::move(init))
.static_as<define>();
add_global_var(std::move(def));
return ret;
}
tensor ir_module_t::make_global_tensor(sc_data_type_t dtype,
const std::string &name, const std::vector<expr> &dims,
linkage linkage) {
tensor ret = builder::make_tensor(name, dims, dtype).static_as<tensor>();
auto def = builder::make_var_tensor_def_unattached(ret, linkage)
.static_as<define>();
add_global_var(std::move(def));
return ret;
}
tensor ir_module_t::make_global_stensor(sc_data_type_t dtype,
const std::string &name, const std::vector<expr> &dims,
const std::vector<expr> &strides, linkage linkage) {
tensor ret = builder::make_stensor(name, dims, strides, dtype)
.static_as<tensor>();
auto def = builder::make_var_tensor_def_unattached(ret, linkage)
.static_as<define>();
add_global_var(std::move(def));
return ret;
}
void ir_module_t::add_global_var(define def) {
auto &name = def->var_.isa<var>() ? def->var_.static_as<var>()->name_
: def->var_.checked_as<tensor>()->name_;
auto itr = var_symbols_.find(name);
if (itr != var_symbols_.end()) {
COMPILE_ASSERT(def->linkage_ != linkage::public_global,
"Global var redefinition: " << name);
std::string new_name;
do {
new_name = name + '_' + std::to_string(++rename_cnt);
itr = var_symbols_.find(new_name);
} while (itr != var_symbols_.end());
name = new_name;
}
var_symbols_.insert(std::make_pair(name, def));
module_vars_.emplace_back(std::move(def));
}
void ir_module_t::add_resolved_func(const std::vector<func_t> &funcs) {
func_unlinker_t replacer;
// all dependencies found, now check if any function name duplications
for (auto &f : funcs) {
// skip function decl_
if (!f->body_.defined()) { continue; }
auto itr = symbols_.find(f->name_);
if (itr != symbols_.end()) {
// if the function is already added to the module, skip
if (contents_.at(itr->second) == f) { continue; }
// try to rename the function if we are allowed to
COMPILE_ASSERT(!f->attr_ || !f->attr_->has_key("entry_func"),
"The function "
<< f->name_
<< " is duplicated and is marked \'entry_func\'.")
std::string name;
do {
name = f->name_ + '_' + std::to_string(++rename_cnt);
itr = symbols_.find(name);
} while (itr != symbols_.end());
f->name_ = name;
assert(f->decl_);
}
symbols_.insert(std::make_pair(f->name_, contents_.size()));
replacer.dispatch_impl(f);
contents_.emplace_back(f);
}
}
void ir_module_t::run_pass(function_pass_t &pass) {
for (auto &f : contents_) {
f = std::const_pointer_cast<func_base>(pass(f));
}
}
func_t ir_module_t::make_init_func() const {
if (!module_vars_.empty()) {
stmts seq = make_stmt<stmts_node_t>(std::vector<stmt>());
for (auto &v : module_vars_) {
assert(v->linkage_ == linkage::private_global
|| v->linkage_ == linkage::public_global);
if (v->init_.defined()) {
seq->seq_.emplace_back(
builder::make_assign_unattached(v->var_, v->init_));
}
}
if (seq->seq_.empty()) return func_t();
auto ret = builder::make_func("__sc_init__", std::vector<expr_c>(),
std::move(seq), datatypes::void_t);
return ret;
}
return func_t();
}
ostream &operator<<(ostream &os, const ir_module_t &m) {
for (auto &f : m.get_module_vars()) {
os << f << '\n';
}
for (auto &f : m.get_contents()) {
os << f << '\n';
}
return os;
}
ostream &operator<<(ostream &os, const const_ir_module_ptr &m) {
return (os << *m);
}
ostream &operator<<(ostream &os, const ir_module_ptr &m) {
return (os << const_ir_module_ptr(m));
}
} // namespace sc
| 34.810484
| 81
| 0.595042
|
wuxun-zhang
|
a1f032b3dc62745f9cdad320aca73b9796f99240
| 1,618
|
hh
|
C++
|
functions/concepts.hh
|
GuylainGreer/manifolds
|
96f996f67fc523c726f2edbc9705125c212bedae
|
[
"MIT"
] | null | null | null |
functions/concepts.hh
|
GuylainGreer/manifolds
|
96f996f67fc523c726f2edbc9705125c212bedae
|
[
"MIT"
] | null | null | null |
functions/concepts.hh
|
GuylainGreer/manifolds
|
96f996f67fc523c726f2edbc9705125c212bedae
|
[
"MIT"
] | null | null | null |
#ifndef MANIFOLDS_FUNCTIONS_CONCEPTS_HH
#define MANIFOLDS_FUNCTIONS_CONCEPTS_HH
#include "variables.hh"
#include "composition.hh"
#include "addition.hh"
#include "multiplication.hh"
namespace manifolds {
template <class T> struct is_variable : std::false_type {};
template <int N, bool a, bool c>
struct is_variable<Variable<N, a, c> > : std::true_type {};
template <class, class> struct is_same_v : std::false_type {};
template <template <class...> class T, class... T1s, class... T2s>
struct is_same_v<T<T1s...>, T<T2s...> > : std::true_type {};
template <class F, class = void> struct is_reorderable : std::false_type {};
template <class F>
struct is_reorderable<
F, typename std::enable_if<is_same_v<F, Multiplication<> >::value>::
type> : bool_<F::abelian_arithmetic> {};
template <class F>
struct is_reorderable<F, typename std::enable_if<is_same_v<
F, Addition<> >::value>::type> : std::true_type {};
template <class F> struct is_composition : std::false_type {};
template <class... Fs>
struct is_composition<Composition<Fs...> > : std::true_type {};
template <class...> using void_t = void;
template <class F>
using Variable_c = typename std::enable_if<is_variable<F>::value>::type;
template <class F>
using Composition_c = typename std::enable_if<is_composition<F>::value>::type;
template <class F>
using IsFunctionContainer = void_t<decltype(std::declval<F>().GetFunctions())>;
template <class F>
using IsReorderableFunctionContainer =
void_t<IsFunctionContainer<F>,
typename std::enable_if<is_reorderable<F>::value>::type>;
}
#endif
| 30.528302
| 80
| 0.70581
|
GuylainGreer
|
a1f1506404fa5a3207e701f62d2d0d4b679d5156
| 1,523
|
cpp
|
C++
|
SQLiteFS/SQLiteArchive.cpp
|
sedawk/SqliteFS
|
d308c7d8bc178afffec86290b29c3754188aa4a2
|
[
"MIT"
] | 1
|
2022-02-10T02:55:16.000Z
|
2022-02-10T02:55:16.000Z
|
SQLiteFS/SQLiteArchive.cpp
|
sedawk/SqliteFS
|
d308c7d8bc178afffec86290b29c3754188aa4a2
|
[
"MIT"
] | null | null | null |
SQLiteFS/SQLiteArchive.cpp
|
sedawk/SqliteFS
|
d308c7d8bc178afffec86290b29c3754188aa4a2
|
[
"MIT"
] | 1
|
2022-02-10T07:08:58.000Z
|
2022-02-10T07:08:58.000Z
|
#include <stdexcept>
#include "SQLiteArchive.hpp"
#include "Util.hpp"
#include "SQLitePreparedStatementFactory.hpp"
#include "SQLiteRootDirectory.hpp"
#include "SQLiteDirectory.hpp"
#include "SQLiteFile.hpp"
#include "SQLitePath.hpp"
namespace SQLite {
void Archive::open(std::shared_ptr<SQLite::Database> db) {
mDB = db;
}
void Archive::open(const std::string& path) {
try {
mDB = std::make_shared<SQLite::Database>(path);
SQLite::PreparedStatementFactory(mDB).createTable().execute();
}
catch (const std::runtime_error& e) {
throw std::invalid_argument(e.what());
}
}
void Archive::open(const std::wstring& path) {
open(util::string::to_string(path, CP_UTF8));
}
static std::string normalize(const std::string& path) {
return util::string::trim(util::string::replace(path, '\\', '/'), '/');
}
std::shared_ptr<SQLite::Entry> Archive::get(const std::string& path) {
auto pathToFile = normalize(path);
if (pathToFile == "") {
return std::make_shared<SQLite::RootDirectory>(mDB);
}
auto stmt = SQLite::PreparedStatementFactory(mDB).findByName(pathToFile);
if (!stmt.fetch()) {
return std::make_shared<SQLite::Path>(mDB, pathToFile);
}
if (stmt.getColumn("type").getInt() == SQLite::Directory::TYPE) {
return std::make_shared<SQLite::Directory>(mDB, pathToFile);
}
return std::make_shared <SQLite::File>(mDB, pathToFile);
}
std::shared_ptr<SQLite::Entry> Archive::get(const std::wstring& path) {
return get(util::string::to_string(path, CP_UTF8));
}
}
| 27.196429
| 75
| 0.692712
|
sedawk
|
a1fa1d0301f911238570cbf318c39dc22b42ded2
| 5,604
|
cpp
|
C++
|
SideProject/Intermediate/Build/Win64/UE4Editor/Inc/SideProject/MyCharacter.gen.cpp
|
Therobodavo/Purification-Camp
|
fe511459c4d938157f3ebb7f9256a02c12be675b
|
[
"MIT"
] | null | null | null |
SideProject/Intermediate/Build/Win64/UE4Editor/Inc/SideProject/MyCharacter.gen.cpp
|
Therobodavo/Purification-Camp
|
fe511459c4d938157f3ebb7f9256a02c12be675b
|
[
"MIT"
] | null | null | null |
SideProject/Intermediate/Build/Win64/UE4Editor/Inc/SideProject/MyCharacter.gen.cpp
|
Therobodavo/Purification-Camp
|
fe511459c4d938157f3ebb7f9256a02c12be675b
|
[
"MIT"
] | null | null | null |
// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved.
/*===========================================================================
Generated code exported from UnrealHeaderTool.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
#include "UObject/GeneratedCppIncludes.h"
#include "SideProject/MyCharacter.h"
#ifdef _MSC_VER
#pragma warning (push)
#pragma warning (disable : 4883)
#endif
PRAGMA_DISABLE_DEPRECATION_WARNINGS
void EmptyLinkFunctionForGeneratedCodeMyCharacter() {}
// Cross Module References
SIDEPROJECT_API UClass* Z_Construct_UClass_AMyCharacter_NoRegister();
SIDEPROJECT_API UClass* Z_Construct_UClass_AMyCharacter();
ENGINE_API UClass* Z_Construct_UClass_ACharacter();
UPackage* Z_Construct_UPackage__Script_SideProject();
SIDEPROJECT_API UClass* Z_Construct_UClass_AProjectileSphere_NoRegister();
COREUOBJECT_API UClass* Z_Construct_UClass_UClass();
// End Cross Module References
void AMyCharacter::StaticRegisterNativesAMyCharacter()
{
}
UClass* Z_Construct_UClass_AMyCharacter_NoRegister()
{
return AMyCharacter::StaticClass();
}
struct Z_Construct_UClass_AMyCharacter_Statics
{
static UObject* (*const DependentSingletons[])();
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[];
#endif
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_proj_MetaData[];
#endif
static const UE4CodeGen_Private::FObjectPropertyParams NewProp_proj;
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_ProjSphereClass_MetaData[];
#endif
static const UE4CodeGen_Private::FClassPropertyParams NewProp_ProjSphereClass;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
static const FCppClassTypeInfoStatic StaticCppClassTypeInfo;
static const UE4CodeGen_Private::FClassParams ClassParams;
};
UObject* (*const Z_Construct_UClass_AMyCharacter_Statics::DependentSingletons[])() = {
(UObject* (*)())Z_Construct_UClass_ACharacter,
(UObject* (*)())Z_Construct_UPackage__Script_SideProject,
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AMyCharacter_Statics::Class_MetaDataParams[] = {
{ "HideCategories", "Navigation" },
{ "IncludePath", "MyCharacter.h" },
{ "ModuleRelativePath", "MyCharacter.h" },
};
#endif
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AMyCharacter_Statics::NewProp_proj_MetaData[] = {
{ "Category", "MyCharacter" },
{ "ModuleRelativePath", "MyCharacter.h" },
};
#endif
const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UClass_AMyCharacter_Statics::NewProp_proj = { UE4CodeGen_Private::EPropertyClass::Object, "proj", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0020080000010005, 1, nullptr, STRUCT_OFFSET(AMyCharacter, proj), Z_Construct_UClass_AProjectileSphere_NoRegister, METADATA_PARAMS(Z_Construct_UClass_AMyCharacter_Statics::NewProp_proj_MetaData, ARRAY_COUNT(Z_Construct_UClass_AMyCharacter_Statics::NewProp_proj_MetaData)) };
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AMyCharacter_Statics::NewProp_ProjSphereClass_MetaData[] = {
{ "Category", "MyCharacter" },
{ "ModuleRelativePath", "MyCharacter.h" },
};
#endif
const UE4CodeGen_Private::FClassPropertyParams Z_Construct_UClass_AMyCharacter_Statics::NewProp_ProjSphereClass = { UE4CodeGen_Private::EPropertyClass::Class, "ProjSphereClass", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0014000000000004, 1, nullptr, STRUCT_OFFSET(AMyCharacter, ProjSphereClass), Z_Construct_UClass_AProjectileSphere_NoRegister, Z_Construct_UClass_UClass, METADATA_PARAMS(Z_Construct_UClass_AMyCharacter_Statics::NewProp_ProjSphereClass_MetaData, ARRAY_COUNT(Z_Construct_UClass_AMyCharacter_Statics::NewProp_ProjSphereClass_MetaData)) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UClass_AMyCharacter_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_AMyCharacter_Statics::NewProp_proj,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_AMyCharacter_Statics::NewProp_ProjSphereClass,
};
const FCppClassTypeInfoStatic Z_Construct_UClass_AMyCharacter_Statics::StaticCppClassTypeInfo = {
TCppClassTypeTraits<AMyCharacter>::IsAbstract,
};
const UE4CodeGen_Private::FClassParams Z_Construct_UClass_AMyCharacter_Statics::ClassParams = {
&AMyCharacter::StaticClass,
DependentSingletons, ARRAY_COUNT(DependentSingletons),
0x009000A0u,
nullptr, 0,
Z_Construct_UClass_AMyCharacter_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UClass_AMyCharacter_Statics::PropPointers),
nullptr,
&StaticCppClassTypeInfo,
nullptr, 0,
METADATA_PARAMS(Z_Construct_UClass_AMyCharacter_Statics::Class_MetaDataParams, ARRAY_COUNT(Z_Construct_UClass_AMyCharacter_Statics::Class_MetaDataParams))
};
UClass* Z_Construct_UClass_AMyCharacter()
{
static UClass* OuterClass = nullptr;
if (!OuterClass)
{
UE4CodeGen_Private::ConstructUClass(OuterClass, Z_Construct_UClass_AMyCharacter_Statics::ClassParams);
}
return OuterClass;
}
IMPLEMENT_CLASS(AMyCharacter, 2803804649);
static FCompiledInDefer Z_CompiledInDefer_UClass_AMyCharacter(Z_Construct_UClass_AMyCharacter, &AMyCharacter::StaticClass, TEXT("/Script/SideProject"), TEXT("AMyCharacter"), false, nullptr, nullptr, nullptr);
DEFINE_VTABLE_PTR_HELPER_CTOR(AMyCharacter);
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#ifdef _MSC_VER
#pragma warning (pop)
#endif
| 52.373832
| 570
| 0.813526
|
Therobodavo
|
a1faf478182abac5bc9d6ef285c68d1f15532d59
| 17,327
|
cpp
|
C++
|
GraphicsSamples/RawGraphicsOnWindows/RawDX11/RawDX11_Triangle_With_ComPtr/DX11_Triangle.cpp
|
dmhud/AllSamples
|
9bfa3d26a51d7722927f05a48e1dbf5fc399d150
|
[
"Unlicense"
] | null | null | null |
GraphicsSamples/RawGraphicsOnWindows/RawDX11/RawDX11_Triangle_With_ComPtr/DX11_Triangle.cpp
|
dmhud/AllSamples
|
9bfa3d26a51d7722927f05a48e1dbf5fc399d150
|
[
"Unlicense"
] | null | null | null |
GraphicsSamples/RawGraphicsOnWindows/RawDX11/RawDX11_Triangle_With_ComPtr/DX11_Triangle.cpp
|
dmhud/AllSamples
|
9bfa3d26a51d7722927f05a48e1dbf5fc399d150
|
[
"Unlicense"
] | null | null | null |
#include "DX11_Triangle.h"
#include <vector>
#include <d3d11.h>
#include <dxgi1_2.h>
#include <d3dcompiler.h>
#include "Common/DX.Utils/DxException.h"
#include "Common/Math.Utils/Math.h"
#include "Common/Win.Utils/ExePath.h"
void DX11_Triangle::DrawTriangle(HWND hWnd, uint32_t windowWidth, uint32_t windowHeight)
{
using namespace dx;
using namespace math;
auto exePath = win::exe_path();
///////////////////////////////
/// Initialize API ///
///////////////////////////////
/**
* Factory
*/
ComPtr<IDXGIFactory> factory;
ThrowIfFailed(CreateDXGIFactory(IID_PPV_ARGS(factory.GetAddressOf())));
/**
* Adapter
*/
ComPtr<IDXGIAdapter> adapter;
ThrowIfFailed(factory->EnumAdapters(0, adapter.GetAddressOf()));
/**
* Adapter Output
*/
ComPtr<IDXGIOutput> adapterOutput;
ThrowIfFailed(adapter->EnumOutputs(0, adapterOutput.GetAddressOf()));
// Get the number of modes that fit the DXGI_FORMAT_R8G8B8A8_UNORM display
// format for the adapter output (monitor).
unsigned int numModes;
ThrowIfFailed(adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM,
DXGI_ENUM_MODES_INTERLACED,
&numModes, nullptr));
// Create a list to hold all the possible display modes for this monitor/video
// card combination.
std::vector<DXGI_MODE_DESC> displayModeList;
displayModeList.resize(numModes);
ThrowIfFailed(adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM,
DXGI_ENUM_MODES_INTERLACED,
&numModes, displayModeList.data()));
// Now go through all the display modes and find the one that matches the screen
// width and height. When a match is found store the numerator and denominator
// of the refresh rate for that monitor.
unsigned numerator = 0;
unsigned denominator = 1;
for (size_t i = 0; i < numModes; i++)
{
if (displayModeList[i].Width = windowWidth && displayModeList[i].Height == windowHeight)
{
numerator = displayModeList[i].RefreshRate.Numerator;
denominator = displayModeList[i].RefreshRate.Denominator;
break;
}
}
/**
* Device
*/
ComPtr<ID3D11Device> device;
ComPtr<ID3D11DeviceContext> deviceContext;
D3D_FEATURE_LEVEL featureLevelInputs[7] = {
D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1,
D3D_FEATURE_LEVEL_10_0, D3D_FEATURE_LEVEL_9_3, D3D_FEATURE_LEVEL_9_2,
D3D_FEATURE_LEVEL_9_1 };
D3D_FEATURE_LEVEL featureLevelOutputs = D3D_FEATURE_LEVEL_11_1;
ThrowIfFailed(D3D11CreateDevice(adapter.Get(), D3D_DRIVER_TYPE_UNKNOWN, nullptr,
D3D11_CREATE_DEVICE_SINGLETHREADED |
D3D11_CREATE_DEVICE_DEBUG,
featureLevelInputs, 7u, D3D11_SDK_VERSION,
device.GetAddressOf(), &featureLevelOutputs, deviceContext.GetAddressOf()));
// Optionally enable the Debug Controller to validate your commands on runtime.
#if defined(_DEBUG)
ComPtr<ID3D11Debug> debugController;
ThrowIfFailed(device.As(&debugController));
#endif
///////////////////////////////
/// Frame Backing ///
///////////////////////////////
/**
* Swapchain
*/
bool isEnabledVSync = false;
bool isFullScreenWindow = false;
DXGI_SWAP_CHAIN_DESC swapchainDesc;
ZeroMemory(&swapchainDesc, sizeof(DXGI_SWAP_CHAIN_DESC));
swapchainDesc.BufferCount = 1;
swapchainDesc.BufferDesc.Width = windowWidth;
swapchainDesc.BufferDesc.Height = windowHeight;
swapchainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
// Set the refresh rate of the back buffer.
if (isEnabledVSync)
{
swapchainDesc.BufferDesc.RefreshRate.Numerator = numerator;
swapchainDesc.BufferDesc.RefreshRate.Denominator = denominator;
}
else
{
swapchainDesc.BufferDesc.RefreshRate.Numerator = 0;
swapchainDesc.BufferDesc.RefreshRate.Denominator = 1;
}
// Set the usage of the back buffer.
swapchainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
// Turn multi-sampling off.
swapchainDesc.SampleDesc.Count = 1;
swapchainDesc.SampleDesc.Quality = 0;
// Set the scan line ordering and scaling to unspecified.
swapchainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
swapchainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
// Discard the back buffer contents after presenting.
swapchainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
// Don't set the advanced flags.
swapchainDesc.Flags = 0;
swapchainDesc.OutputWindow = hWnd;
swapchainDesc.Windowed = !isFullScreenWindow;
ComPtr<IDXGISwapChain> swapchain;
ThrowIfFailed(factory->CreateSwapChain(device.Get(), &swapchainDesc, swapchain.GetAddressOf()));
/**
* Render Targets
*/
// Get the back buffer texture.
ComPtr<ID3D11Texture2D> texBackBuffer;
ThrowIfFailed(swapchain->GetBuffer(0, IID_PPV_ARGS(texBackBuffer.GetAddressOf())));
// Create the render target view with the back buffer pointer.
ComPtr<ID3D11RenderTargetView> rtv;
ThrowIfFailed(device->CreateRenderTargetView(texBackBuffer.Get(), nullptr, rtv.GetAddressOf()));
// Create the texture for the depth buffer.
D3D11_TEXTURE2D_DESC depthBufferDesc;
ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc));
depthBufferDesc.Width = windowWidth;
depthBufferDesc.Height = windowHeight;
depthBufferDesc.MipLevels = 1;
depthBufferDesc.ArraySize = 1;
depthBufferDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
depthBufferDesc.SampleDesc.Count = 1;
depthBufferDesc.SampleDesc.Quality = 0;
depthBufferDesc.Usage = D3D11_USAGE_DEFAULT;
depthBufferDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
depthBufferDesc.CPUAccessFlags = 0;
depthBufferDesc.MiscFlags = 0;
ComPtr<ID3D11Texture2D> texDepthStencilBuffer;
ThrowIfFailed(device->CreateTexture2D(&depthBufferDesc, nullptr, texDepthStencilBuffer.GetAddressOf()));
// Create the depth stencil view.
D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc;
ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc));
depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
depthStencilViewDesc.Texture2D.MipSlice = 0;
ComPtr<ID3D11DepthStencilView> dsv;
ThrowIfFailed(device->CreateDepthStencilView(texDepthStencilBuffer.Get(), &depthStencilViewDesc, dsv.GetAddressOf()));
///////////////////////////////
/// Resources ///
///////////////////////////////
/**
* Vertex Buffer
*/
// Declare Data
struct Vertex
{
float position[3];
float color[3];
};
Vertex vertexBufferData[3] = { {{ 1.0f, -1.0f, 0.0f}, {1.0f, 0.0f, 0.0f}},
{{-1.0f, -1.0f, 0.0f}, {0.0f, 1.0f, 0.0f}},
{{ 0.0f, 1.0f, 0.0f}, {0.0f, 0.0f, 1.0f}} };
// Set up the description of the static vertex buffer.
D3D11_BUFFER_DESC vertexBufferDesc;
vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
vertexBufferDesc.ByteWidth = sizeof(Vertex) * 3;
vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vertexBufferDesc.CPUAccessFlags = 0;
vertexBufferDesc.MiscFlags = 0;
vertexBufferDesc.StructureByteStride = 0;
// Give the subresource structure a pointer to the vertex data.
D3D11_SUBRESOURCE_DATA vertexData;
vertexData.pSysMem = vertexBufferData;
vertexData.SysMemPitch = 0;
vertexData.SysMemSlicePitch = 0;
// Now create the vertex buffer.
ComPtr<ID3D11Buffer> vertexBuffer;
ThrowIfFailed(device->CreateBuffer(&vertexBufferDesc, &vertexData, vertexBuffer.GetAddressOf()));
/**
* Index Buffer
*/
// Declare Data
uint32_t indexBufferData[3] = { 0, 1, 2 };
// Set up the description of the static index buffer.
D3D11_BUFFER_DESC indexBufferDesc;
indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
indexBufferDesc.ByteWidth = sizeof(unsigned) * 3;
indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
indexBufferDesc.CPUAccessFlags = 0;
indexBufferDesc.MiscFlags = 0;
indexBufferDesc.StructureByteStride = 0;
// Give the subresource structure a pointer to the index data.
D3D11_SUBRESOURCE_DATA indexData;
indexData.pSysMem = indexBufferData;
indexData.SysMemPitch = 0;
indexData.SysMemSlicePitch = 0;
// Create the index buffer.
ComPtr<ID3D11Buffer> indexBuffer;
ThrowIfFailed(device->CreateBuffer(&indexBufferDesc, &indexData, indexBuffer.GetAddressOf()));
/**
* Constant Buffer
*/
struct
{
float4x4 projectionMatrix = float4x4::Identity();
float4x4 modelMatrix = float4x4::Identity();
float4x4 viewMatrix = float4x4::Identity();
} cbVS;
// Setup the description of the dynamic matrix constant buffer that is in the
// vertex shader.
D3D11_BUFFER_DESC constantBufferDesc;
constantBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
constantBufferDesc.ByteWidth = sizeof(cbVS);
constantBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
constantBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
constantBufferDesc.MiscFlags = 0;
constantBufferDesc.StructureByteStride = 0;
// Create the constant buffer pointer so we can access the vertex shader
// constant buffer from within this class.
ComPtr<ID3D11Buffer> constantBuffer;
ThrowIfFailed(device->CreateBuffer(&constantBufferDesc, nullptr, constantBuffer.GetAddressOf()));
/**
* Shaders options
*/
#if defined(_DEBUG)
// Enable better shader debugging with the graphics debugging tools.
UINT compileFlags = D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION;
#else
UINT compileFlags = 0;
#endif
ComPtr<ID3DBlob> errors;
/**
* Vertex Shader
*/
ComPtr<ID3DBlob> vertexShaderBlob = nullptr;
std::wstring pathVS = exePath / "shaders" / "triangle.vs.hlsl";
ThrowIfFailed(D3DCompileFromFile(pathVS.c_str(), nullptr, nullptr, "main",
"vs_5_0", compileFlags, 0, vertexShaderBlob.GetAddressOf(),
errors.ReleaseAndGetAddressOf()), errors);
// Create the vertex shader from the buffer.
ComPtr<ID3D11VertexShader> vertexShader;
ThrowIfFailed(device->CreateVertexShader(
vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(),
nullptr, vertexShader.GetAddressOf()));
/**
* Pixel Shader
*/
ComPtr<ID3DBlob> pixelShaderBlob;
std::wstring pathPS = exePath / "shaders" / "triangle.ps.hlsl";
ThrowIfFailed(D3DCompileFromFile(pathPS.c_str(), nullptr, nullptr, "main",
"ps_5_0", compileFlags, 0, pixelShaderBlob.GetAddressOf(),
errors.ReleaseAndGetAddressOf()), errors);
// Create the pixel shader from the buffer.
ComPtr<ID3D11PixelShader> pixelShader;
ThrowIfFailed(device->CreatePixelShader(
pixelShaderBlob->GetBufferPointer(), pixelShaderBlob->GetBufferSize(),
nullptr, pixelShader.GetAddressOf()));
///////////////////////////////
/// Rendering ///
///////////////////////////////
/**
* Pipeline State
*/
// Input Assembly
D3D11_INPUT_ELEMENT_DESC polygonLayout[2];
polygonLayout[0].SemanticName = "POSITION";
polygonLayout[0].SemanticIndex = 0;
polygonLayout[0].Format = DXGI_FORMAT_R32G32B32_FLOAT;
polygonLayout[0].InputSlot = 0;
polygonLayout[0].AlignedByteOffset = 0;
polygonLayout[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
polygonLayout[0].InstanceDataStepRate = 0;
polygonLayout[1].SemanticName = "COLOR";
polygonLayout[1].SemanticIndex = 0;
polygonLayout[1].Format = DXGI_FORMAT_R32G32B32_FLOAT;
polygonLayout[1].InputSlot = 0;
polygonLayout[1].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
polygonLayout[1].InstanceDataStepRate = 0;
// Get a count of the elements in the layout.
unsigned numElements = sizeof(polygonLayout) / sizeof(polygonLayout[0]);
// Create the vertex input layout.
ComPtr<ID3D11InputLayout> inputLayout;
ThrowIfFailed(device->CreateInputLayout(polygonLayout, numElements,
vertexShaderBlob->GetBufferPointer(),
vertexShaderBlob->GetBufferSize(),
inputLayout.GetAddressOf()));
// Depth/Stencil
D3D11_DEPTH_STENCIL_DESC depthStencilDesc;
ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc));
depthStencilDesc.DepthEnable = true;
depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;
depthStencilDesc.StencilEnable = true;
depthStencilDesc.StencilReadMask = 0xFF;
depthStencilDesc.StencilWriteMask = 0xFF;
// Stencil operations if pixel is front-facing.
depthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
// Stencil operations if pixel is back-facing.
depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
// Create the depth stencil state.
ComPtr<ID3D11DepthStencilState> depthStencilState;
ThrowIfFailed(device->CreateDepthStencilState(&depthStencilDesc, depthStencilState.GetAddressOf()));
// Set the depth stencil state.
deviceContext->OMSetDepthStencilState(depthStencilState.Get(), 1);
// Rasterization
D3D11_RASTERIZER_DESC rasterDesc;
rasterDesc.AntialiasedLineEnable = false;
rasterDesc.CullMode = D3D11_CULL_NONE;
rasterDesc.DepthBias = 0;
rasterDesc.DepthBiasClamp = 0.0f;
rasterDesc.DepthClipEnable = true;
rasterDesc.FillMode = D3D11_FILL_SOLID;
rasterDesc.FrontCounterClockwise = false;
rasterDesc.MultisampleEnable = false;
rasterDesc.ScissorEnable = false;
rasterDesc.SlopeScaledDepthBias = 0.0f;
// Create the rasterizer state from the description we just filled out.
ComPtr<ID3D11RasterizerState> rasterState;
ThrowIfFailed(device->CreateRasterizerState(&rasterDesc, rasterState.GetAddressOf()));
// Now set the rasterizer state.
deviceContext->RSSetState(rasterState.Get());
/**
* Viewport
*/
D3D11_VIEWPORT viewport;
viewport.TopLeftX = 0;
viewport.TopLeftY = 0;
viewport.Width = windowWidth;
viewport.Height = windowHeight;
viewport.MinDepth = 0;
viewport.MaxDepth = 1;
/**
* Draw Calls
*/
// Set the position of the constant buffer in the vertex shader.
unsigned int bufferNumber = 0;
// Lock the constant buffer so it can be written to.
D3D11_MAPPED_SUBRESOURCE mappedResource;
ThrowIfFailed(deviceContext->Map(constantBuffer.Get(), 0, D3D11_MAP_WRITE_DISCARD,
0, &mappedResource));
// Get a pointer to the data in the constant buffer.
memcpy(mappedResource.pData, &cbVS, sizeof(cbVS));
// Unlock the constant buffer.
deviceContext->Unmap(constantBuffer.Get(), 0);
// Finally set the constant buffer in the vertex shader with the updated
// values.
deviceContext->VSSetConstantBuffers(bufferNumber, 1, constantBuffer.GetAddressOf());
// Bind the render target view and depth stencil buffer to the output render
// pipeline.
deviceContext->OMSetRenderTargets(1, rtv.GetAddressOf(), dsv.Get());
deviceContext->RSSetViewports(1, &viewport);
// Clear textures
float color[4] = { 0.2f, 0.2f, 0.2f, 1.0f };
deviceContext->ClearRenderTargetView(rtv.Get(), color);
// Clear the depth buffer.
deviceContext->ClearDepthStencilView(dsv.Get(), D3D11_CLEAR_DEPTH, 1.0f, 0);
// Set the vertex input layout.
deviceContext->IASetInputLayout(inputLayout.Get());
// Set the vertex and pixel shaders that will be used to render this
// triangle.
deviceContext->VSSetShader(vertexShader.Get(), nullptr, 0);
deviceContext->PSSetShader(pixelShader.Get(), nullptr, 0);
// Set the vertex buffer to active in the input assembler so it can be
// rendered.
unsigned stride = sizeof(Vertex);
unsigned offset = 0;
deviceContext->IASetVertexBuffers(0, 1, vertexBuffer.GetAddressOf(), &stride, &offset);
// Set the index buffer to active in the input assembler so it can be
// rendered.
deviceContext->IASetIndexBuffer(indexBuffer.Get(), DXGI_FORMAT_R32_UINT, 0);
// Set the type of primitive that should be rendered from this vertex
// buffer, in this case triangles.
deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
// Render the triangle.
deviceContext->DrawIndexed(3, 0, 0);
if (isEnabledVSync)
{
swapchain->Present(1, 0);
}
else
{
swapchain->Present(0, 0);
}
return;
}
| 36.097917
| 122
| 0.702141
|
dmhud
|
a1fc0d174cf444e0ab58d32893339a3af96e1a68
| 1,620
|
cpp
|
C++
|
Suffix-Array(Doubling).cpp
|
cirno99/Algorithms
|
6425b143f406693caf8f882bdfe5497c81df255a
|
[
"Unlicense"
] | 1,210
|
2016-08-07T13:32:12.000Z
|
2022-03-21T01:01:57.000Z
|
Suffix-Array(Doubling).cpp
|
NeilQingqing/Algorithms-2
|
c10d4c212fa1fbf8b9fb3c781d61f41e75e96aaa
|
[
"Unlicense"
] | 7
|
2016-09-11T11:41:03.000Z
|
2017-10-29T02:12:57.000Z
|
Suffix-Array(Doubling).cpp
|
NeilQingqing/Algorithms-2
|
c10d4c212fa1fbf8b9fb3c781d61f41e75e96aaa
|
[
"Unlicense"
] | 514
|
2016-10-17T03:52:16.000Z
|
2022-03-19T16:23:33.000Z
|
#include <cstdio>
#include <cstring>
#define STRING_LENGTH 100000
using namespace std;
struct sortinfo
{
int x, y, ord;
};
int l;
char s[STRING_LENGTH];
int rank[STRING_LENGTH * 2], sa[STRING_LENGTH];
void radix_sort(sortinfo *d)
{
static sortinfo _d[STRING_LENGTH], res[STRING_LENGTH];
static int c[STRING_LENGTH];
memset(c, 0, sizeof(c));
for (int i = 0; i < l; i++)
{
c[d[i].y]++;
}
for (int i = 1; i <= l; i++)
{
c[i] += c[i - 1];
}
for (int i = l - 1; i >= 0; i--)
{
_d[--c[d[i].y]] = d[i];
}
memset(c, 0, sizeof(c));
for (int i = 0; i < l; i++)
{
c[_d[i].x]++;
}
for (int i = 1; i <= l; i++)
{
c[i] += c[i - 1];
}
for (int i = l - 1; i >= 0; i--)
{
res[--c[_d[i].x]] = _d[i];
}
for (int i = 0; i < l; i++)
{
d[i] = res[i];
}
}
void init_rank()
{
static int c[256];
static sortinfo d[STRING_LENGTH];
int x = 1;
for (int i = 0; i < l; i++)
{
c[(int)s[i]] = 1;
}
for (int i = 0; i < 256; i++)
{
if (c[i] == 1)
{
c[i] = x++;
}
}
for (int i = 0; i < l; i++)
{
rank[i] = c[(int)s[i]];
}
for (int k = 1; k < l; k <<= 1)
{
for (int i = 0; i < l; i++)
{
d[i].x = rank[i];
d[i].y = rank[i + k];
d[i].ord = i;
}
radix_sort(d);
x = 1;
rank[d[0].ord] = 1;
for (int i = 1; i < l; i++)
{
rank[d[i].ord] = (d[i].x == d[i - 1].x && d[i].y == d[i - 1].y ? x : ++x);
}
if (x == l)
{
break;
}
}
}
void rank_to_sa()
{
for (int i = 0; i < l; i++)
{
sa[rank[i] - 1] = i + 1;
}
}
int main()
{
scanf("%d%s", &l, s);
init_rank();
rank_to_sa();
for (int i = 0; i < l; i++)
{
printf("%d\n", sa[i]);
}
return 0;
}
| 14.210526
| 77
| 0.448148
|
cirno99
|
a1fe0d7c1cf06943b39286420805b97bd9fdb09b
| 4,912
|
cpp
|
C++
|
src/adtfUser/common/katanaWorld/src/RoadJunction.cpp
|
KAtana-Karlsruhe/AADC_2015_KAtana
|
c6e55be189b8b2d46c905926b6533df2aba5979e
|
[
"BSD-4-Clause"
] | null | null | null |
src/adtfUser/common/katanaWorld/src/RoadJunction.cpp
|
KAtana-Karlsruhe/AADC_2015_KAtana
|
c6e55be189b8b2d46c905926b6533df2aba5979e
|
[
"BSD-4-Clause"
] | null | null | null |
src/adtfUser/common/katanaWorld/src/RoadJunction.cpp
|
KAtana-Karlsruhe/AADC_2015_KAtana
|
c6e55be189b8b2d46c905926b6533df2aba5979e
|
[
"BSD-4-Clause"
] | null | null | null |
// this is for emacs file handling -*- mode: c++; indent-tabs-mode: nil -*-
// -- BEGIN LICENSE BLOCK ----------------------------------------------
// -- END LICENSE BLOCK ------------------------------------------------
//----------------------------------------------------------------------
/*!\file
*
* \author Christoph Rist <rist@fzi.de>
* \date 2014-12-07
*
*/
//----------------------------------------------------------------------
#include "RoadJunction.h"
namespace katana
{
RoadPatch::TrajectoryPtr RoadJunction::getDrivingStrip(RoadBase::DrivingStripId drivingStrip) const
{
DiversionId diversion = 0;
if(m_direction == Action::LEFT) {
diversion = 0;
} else if(m_direction == Action::RIGHT) {
diversion = 2;
} else if(m_direction == Action::STRAIGHT) {
diversion = 1;
} else {
assert(false && "Unkown direction passed.");
}
#ifdef KATANA_MC_MANEUVER_DEBUG
std::cout << "MC Maneuver; Diversion of junction with id " << this->getId() << " " << this->getAnchorPose() << " is " << (int32_t) diversion << std::endl;
#endif
return katana::RoadBase::getDrivingStrip(drivingStrip, diversion);
}
void RoadJunction::setRightOfWay(const RightOfWayDirection& right_of_way)
{
if (right_of_way.first == right_of_way.second && right_of_way.first != RIGHT_OF_WAY::PRIORITY_FROM_RIGHT) //< error
m_right_of_way = RightOfWayDirection(RIGHT_OF_WAY::UNDEFINED, RIGHT_OF_WAY::UNDEFINED);
else
m_right_of_way = right_of_way;
if (m_right_of_way.first == RIGHT_OF_WAY::PRIORITY_FROM_RIGHT || m_right_of_way.first == RIGHT_OF_WAY::OWN)
return;
if (m_right_of_way.second == RIGHT_OF_WAY::PRIORITY_FROM_RIGHT)
std::swap(m_right_of_way.first, m_right_of_way.second);
else if (m_right_of_way.second == RIGHT_OF_WAY::OWN)
std::swap(m_right_of_way.first, m_right_of_way.second);
else if (m_right_of_way.second == RIGHT_OF_WAY::RIGHT)
std::swap(m_right_of_way.first, m_right_of_way.second);
else if (m_right_of_way.first == RIGHT_OF_WAY::LEFT)
std::swap(m_right_of_way.first, m_right_of_way.second);
}
void RoadJunction::setRightOfWay(TrafficSign ts)
{
m_is_stop = false;
switch(ts)
{
case TrafficSign::JUNCTION_STOP_GIVE_WAY:
m_is_stop = true;
case TrafficSign::JUNCTION_GIVE_WAY:
m_right_of_way = RightOfWayDirection(RIGHT_OF_WAY::RIGHT, RIGHT_OF_WAY::LEFT);
break;
case TrafficSign::JUNCTION_PRIORITY:
m_right_of_way = RightOfWayDirection(RIGHT_OF_WAY::OWN, RIGHT_OF_WAY::STRAIGHT);
break;
case TrafficSign::JUNCTION_PRIORITY_FROM_RIGHT:
m_right_of_way = RightOfWayDirection(RIGHT_OF_WAY::PRIORITY_FROM_RIGHT, RIGHT_OF_WAY::UNDEFINED);
break;
default:
m_right_of_way = RightOfWayDirection(RIGHT_OF_WAY::UNDEFINED, RIGHT_OF_WAY::UNDEFINED);
m_is_stop = true;
break;
}
}
std::vector<DIVERSION> RoadJunction::yieldRightOfWayTo(DIVERSION where_to_go) const
{
std::vector<DIVERSION> yield_to;
if (where_to_go == DIVERSION::UNDEFINED) //< error
{
yield_to.push_back(DIVERSION::RIGHT);
yield_to.push_back(DIVERSION::STRAIGHT);
yield_to.push_back(DIVERSION::LEFT);
return yield_to;
}
if (m_right_of_way.first == RIGHT_OF_WAY::OWN)
{
if (m_right_of_way.second == RIGHT_OF_WAY::STRAIGHT && where_to_go == DIVERSION::LEFT)
{
yield_to.push_back(DIVERSION::STRAIGHT);
}
else if (m_right_of_way.second == RIGHT_OF_WAY::RIGHT && where_to_go == DIVERSION::STRAIGHT)
{
yield_to.push_back(DIVERSION::RIGHT);
}
}
else if (m_right_of_way.first == RIGHT_OF_WAY::PRIORITY_FROM_RIGHT)
{
if (where_to_go != DIVERSION::RIGHT)
{
yield_to.push_back(DIVERSION::RIGHT);
if (where_to_go == DIVERSION::LEFT)
{
yield_to.push_back(DIVERSION::STRAIGHT);
}
}
}
else if (m_right_of_way.first == RIGHT_OF_WAY::UNDEFINED || m_right_of_way.second == RIGHT_OF_WAY::UNDEFINED)
{
yield_to.push_back(DIVERSION::RIGHT);
yield_to.push_back(DIVERSION::STRAIGHT);
yield_to.push_back(DIVERSION::LEFT);
}
else
{
if (m_right_of_way.first == RIGHT_OF_WAY::RIGHT)
{
// right - left
if (m_right_of_way.second == RIGHT_OF_WAY::LEFT)
{
yield_to.push_back(DIVERSION::LEFT);
if (where_to_go != DIVERSION::RIGHT)
yield_to.push_back(DIVERSION::RIGHT);
if (where_to_go == DIVERSION::LEFT)
yield_to.push_back(DIVERSION::STRAIGHT);
}
// right - straight
else
{
yield_to.push_back(DIVERSION::STRAIGHT);
if (where_to_go != DIVERSION::RIGHT)
yield_to.push_back(DIVERSION::RIGHT);
}
}
// straight - left
else
{
yield_to.push_back(DIVERSION::STRAIGHT);
yield_to.push_back(DIVERSION::LEFT);
if (where_to_go != DIVERSION::RIGHT)
{
yield_to.push_back(DIVERSION::RIGHT);
}
}
}
return yield_to;
}
} //ns
| 30.893082
| 158
| 0.652484
|
KAtana-Karlsruhe
|
a1ff1251e626289c4dc32899b0f29f8c4cfacc9d
| 3,105
|
cpp
|
C++
|
jit/bf.cpp
|
Mark1626/performance-case-studies
|
06890e80a945f66bade639a9dedd6bf6eeb4e2f1
|
[
"CC0-1.0"
] | null | null | null |
jit/bf.cpp
|
Mark1626/performance-case-studies
|
06890e80a945f66bade639a9dedd6bf6eeb4e2f1
|
[
"CC0-1.0"
] | null | null | null |
jit/bf.cpp
|
Mark1626/performance-case-studies
|
06890e80a945f66bade639a9dedd6bf6eeb4e2f1
|
[
"CC0-1.0"
] | null | null | null |
#include "parser.h"
#include "util.h"
#include <cstdint>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <vector>
constexpr int MEMORY_SIZE = 30000;
void interpretor(const Program &p, bool verbose) {
std::vector<uint8_t> memory(MEMORY_SIZE, 0);
size_t pc = 0;
size_t dataptr = 0;
while (pc < p.instructions.size()) {
char instruction = p.instructions[pc];
switch (instruction) {
case '>':
dataptr++;
break;
case '<':
dataptr--;
break;
case '+':
memory[dataptr]++;
break;
case '-':
memory[dataptr]--;
break;
case '.':
std::cout.put(memory[dataptr]);
break;
case ',':
memory[dataptr] = std::cin.get();
break;
case '[':
if (memory[dataptr] == 0) {
int bracket_nesting = 1;
size_t saved_pc = pc;
while (bracket_nesting && ++pc < p.instructions.size()) {
if (p.instructions[pc] == ']') {
bracket_nesting--;
} else if (p.instructions[pc] == ']') {
bracket_nesting++;
}
}
if (!bracket_nesting) {
break;
} else {
DIE << "unmatched [ " << saved_pc;
}
}
break;
case ']':
if (memory[dataptr] != 0) {
int bracket_nesting = 1;
size_t saved_pc = pc;
while (bracket_nesting && pc > 0) {
pc--;
if (p.instructions[pc] == '[') {
bracket_nesting--;
} else if (p.instructions[pc] == ']') {
bracket_nesting++;
}
}
if (!bracket_nesting) {
break;
} else {
DIE << "unmatched ] " << saved_pc;
}
}
break;
default:
DIE << "unknown character at " << pc;
break;
}
pc++;
}
if (verbose) {
std::cout << "\n";
std::cout << " * pc = " << pc << "\n";
std::cout << " * dataptr = " << dataptr << "\n";
std::cout << " * Memory Nonzero locations "
<< "\n";
for (size_t i = 0, pcount = 0; i < memory.size(); ++i) {
if (memory[i]) {
std::cout << std::right << "[" << std::setw(3) << i
<< " ] = " << std::setw(3) << std::left
<< static_cast<int32_t>(memory[i]) << " ";
pcount++;
if (pcount > 0 && pcount % 4 == 0) {
std::cout << "\n";
}
std::cout << "\n";
}
}
}
}
int main(int argc, char **argv) {
bool verbose = false;
std::string bf_line_path;
parse_command_line(argc, argv, &bf_line_path, &verbose);
Timer t1;
std::ifstream file(bf_line_path);
if (!file) {
DIE << "unable to open file " << bf_line_path;
}
Program program = parse_from_stream(file);
std::cout << "Parsing took " << t1.elapsed() << "\n";
if (verbose) {
std::cout << "Program size " << program.instructions.size() << "\n";
std::cout << "Instructions " << program.instructions << "\n";
}
Timer t2;
interpretor(program, verbose);
std::cout << "Done (elapsed) " << t2.elapsed() << "\n";
return EXIT_SUCCESS;
}
| 23.171642
| 72
| 0.485668
|
Mark1626
|
b80026d2b70cfdb47bd1cb5e7d134da481591096
| 2,257
|
cpp
|
C++
|
src/tmsocket/cpp/server_communicator.cpp
|
Timothy-LiuXuefeng/TMChat
|
cd69441524f1b86914477f3061e36ffbb8d17478
|
[
"MIT"
] | 1
|
2022-01-30T01:09:15.000Z
|
2022-01-30T01:09:15.000Z
|
src/tmsocket/cpp/server_communicator.cpp
|
Timothy-LiuXuefeng/TMChat
|
cd69441524f1b86914477f3061e36ffbb8d17478
|
[
"MIT"
] | null | null | null |
src/tmsocket/cpp/server_communicator.cpp
|
Timothy-LiuXuefeng/TMChat
|
cd69441524f1b86914477f3061e36ffbb8d17478
|
[
"MIT"
] | null | null | null |
#include "../include/server_communicator.hpp"
#include <prep/include/prep.h>
#include <cstddef>
#include <string>
#include <utility>
#include <algorithm>
TMSOCKET_NAMESPACE_BEGIN
#include "details/protocol.ipp"
server_communicator::
server_communicator()
{
this->m_stm.on_reveive
(
[this] (tmsocket_t fd, const ::std::string& str)
{
this->m_buffers[fd].append(str);
::std::string msg;
while (protocol_ns::protocol::try_decode_message(this->m_buffers[fd], msg))
{
this->m_on_receive.invoke(fd, msg);
}
}
);
}
PREP_NODISCARD bool
server_communicator::
is_connected() const
{
return this->m_stm.is_connected();
}
PREP_NODISCARD bool
server_communicator::
is_finished() const
{
return this->m_stm.is_finished();
}
void
server_communicator::
add_log(::std::function<void(const ::std::string&)> log_func)
{
this->m_stm.add_log(::std::move(log_func));
}
void
server_communicator::
on_reveive(::std::function<void(tmsocket_t, const ::std::string&)> func)
{
m_on_receive.subscript(::std::move(func));
}
void
server_communicator::
listen(const ::std::string& host, const ::std::string& port)
{
this->m_stm.listen(host, port);
}
void
server_communicator::
listen(const ::std::string& port)
{
this->m_stm.listen(port);
}
void
server_communicator::
on_listen(::std::function<void(void)> listen_func)
{
this->m_stm.on_listen(::std::move(listen_func));
}
void
server_communicator::
on_connect(::std::function<void(tmsocket_t)> connect_func)
{
this->m_stm.on_connect(::std::move(connect_func));
}
void
server_communicator::
on_disconnect(::std::function<void(tmsocket_t)> disconnect_func)
{
this->m_stm.on_disconnect(::std::move(disconnect_func));
}
void
server_communicator::
send_to_one_client(tmsocket_t client_fd, const ::std::string& msg)
{
this->m_stm.send_to_one_client(client_fd, protocol_ns::protocol::encode_message(msg));
}
void
server_communicator::
send_to_all_clients(const ::std::string& msg)
{
this->m_stm.send_to_all_clients(protocol_ns::protocol::encode_message(msg));
}
void
server_communicator::
end_communication()
{
this->m_stm.end_communication();
}
TMSOCKET_NAMESPACE_END
| 19.626087
| 90
| 0.701817
|
Timothy-LiuXuefeng
|
b8017d93c4850e975c5fc579e0dd964bfd1b45ab
| 1,150
|
cpp
|
C++
|
Source/Engine/Core/Resources/ResourceFactory.cpp
|
everard/SELENE-Device
|
775bb5cf66ba9fdbc55eac7b216e035c36d82954
|
[
"MIT"
] | null | null | null |
Source/Engine/Core/Resources/ResourceFactory.cpp
|
everard/SELENE-Device
|
775bb5cf66ba9fdbc55eac7b216e035c36d82954
|
[
"MIT"
] | null | null | null |
Source/Engine/Core/Resources/ResourceFactory.cpp
|
everard/SELENE-Device
|
775bb5cf66ba9fdbc55eac7b216e035c36d82954
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2012 Nezametdinov E. Ildus
// Licensed under the MIT License (see LICENSE.txt for details)
#include "ResourceFactory.h"
#include "ResourceManager.h"
namespace selene
{
ResourceFactory::ResourceFactory(FileManager* fileManager):
fileManager_(fileManager), resourceManager_(nullptr), resourceFactory_(nullptr) {}
ResourceFactory::~ResourceFactory() {}
//----------------------------------------------------------------------------------------
void ResourceFactory::setFileManager(FileManager* fileManager)
{
fileManager_ = fileManager;
}
//----------------------------------------------------------------------------------------
void ResourceFactory::setResourceManager(ResourceManager* resourceManager)
{
resourceManager_ = resourceManager;
}
//----------------------------------------------------------------------------------------
void ResourceFactory::setResourceFactory(ResourceFactory* resourceFactory)
{
resourceFactory_ = resourceFactory;
}
}
| 34.848485
| 98
| 0.493043
|
everard
|
b802a0b7659d1f22dd4ea2aee5aaafc8177026fb
| 4,853
|
cpp
|
C++
|
unit_tests/os_interface/windows/driver_info_tests.cpp
|
abhi5658054/compute-runtime
|
894060de5010874381fc981cf96a722769e65a76
|
[
"MIT"
] | 1
|
2022-03-04T22:47:19.000Z
|
2022-03-04T22:47:19.000Z
|
unit_tests/os_interface/windows/driver_info_tests.cpp
|
abhi5658054/compute-runtime
|
894060de5010874381fc981cf96a722769e65a76
|
[
"MIT"
] | null | null | null |
unit_tests/os_interface/windows/driver_info_tests.cpp
|
abhi5658054/compute-runtime
|
894060de5010874381fc981cf96a722769e65a76
|
[
"MIT"
] | null | null | null |
/*
* Copyright (c) 2017 - 2018, Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#include "unit_tests/os_interface/windows/wddm_fixture.h"
#include "runtime/os_interface/windows/driver_info.h"
#include "runtime/os_interface/windows/registry_reader.h"
#include "runtime/os_interface/windows/os_interface.h"
#include "runtime/memory_manager/os_agnostic_memory_manager.h"
#include "runtime/helpers/options.h"
#include "unit_tests/mocks/mock_device.h"
#include "unit_tests/mocks/mock_csr.h"
#include "unit_tests/libult/create_command_stream.h"
#include "gtest/gtest.h"
namespace OCLRT {
extern CommandStreamReceiverCreateFunc commandStreamReceiverFactory[2 * IGFX_MAX_CORE];
CommandStreamReceiver *createMockCommandStreamReceiver(const HardwareInfo &hwInfoIn, bool withAubDump);
class DriverInfoDeviceTest : public ::testing::Test {
public:
static Wddm *wddmMock;
void SetUp() {
wddmMock = nullptr;
hwInfo = platformDevices[0];
commandStreamReceiverCreateFunc = commandStreamReceiverFactory[hwInfo->pPlatform->eRenderCoreFamily];
commandStreamReceiverFactory[hwInfo->pPlatform->eRenderCoreFamily] = createMockCommandStreamReceiver;
}
void TearDown() {
commandStreamReceiverFactory[hwInfo->pPlatform->eRenderCoreFamily] = commandStreamReceiverCreateFunc;
delete wddmMock;
}
CommandStreamReceiverCreateFunc commandStreamReceiverCreateFunc;
const HardwareInfo *hwInfo;
};
CommandStreamReceiver *createMockCommandStreamReceiver(const HardwareInfo &hwInfoIn, bool withAubDump) {
auto csr = new MockCommandStreamReceiver();
OSInterface *osInterface = new OSInterface();
DriverInfoDeviceTest::wddmMock = new WddmMock();
osInterface->get()->setWddm(DriverInfoDeviceTest::wddmMock);
csr->setOSInterface(osInterface);
return csr;
}
Wddm *DriverInfoDeviceTest::wddmMock = nullptr;
TEST_F(DriverInfoDeviceTest, GivenDeviceCreatedWhenCorrectOSInterfaceThenCreateDriverInfo) {
overrideCommandStreamReceiverCreation = true;
auto device = Device::create<OCLRT::MockDevice>(hwInfo);
EXPECT_TRUE(device->hasDriverInfo());
delete device;
}
TEST_F(DriverInfoDeviceTest, GivenDeviceCreatedWithoutCorrectOSInterfaceThenDontCreateDriverInfo) {
overrideCommandStreamReceiverCreation = false;
auto device = Device::create<OCLRT::MockDevice>(hwInfo);
EXPECT_FALSE(device->hasDriverInfo());
delete device;
}
class RegistryReaderMock : public SettingsReader {
public:
std::string nameString;
std::string versionString;
std::string getSetting(const char *settingName, const std::string &value) {
std::string key(settingName);
if (key == "HardwareInformation.AdapterString") {
properNameKey = true;
} else if (key == "DriverVersion") {
properVersionKey = true;
}
return value;
}
bool getSetting(const char *settingName, bool defaultValue) { return defaultValue; };
int32_t getSetting(const char *settingName, int32_t defaultValue) { return defaultValue; };
bool properNameKey = false;
bool properVersionKey = false;
};
TEST(DriverInfo, GivenDriverInfoWhenThenReturnNonNullptr) {
DriverInfoWindows driverInfo;
RegistryReaderMock *registryReaderMock = new RegistryReaderMock();
driverInfo.setRegistryReader(registryReaderMock);
std::string defaultName = "defaultName";
auto name = driverInfo.getDeviceName(defaultName);
EXPECT_STREQ(defaultName.c_str(), name.c_str());
EXPECT_TRUE(registryReaderMock->properNameKey);
std::string defaultVersion = "defaultVersion";
auto driverVersion = driverInfo.getVersion(defaultVersion);
EXPECT_STREQ(defaultVersion.c_str(), driverVersion.c_str());
EXPECT_TRUE(registryReaderMock->properVersionKey);
}
} // namespace OCLRT
| 37.620155
| 109
| 0.762209
|
abhi5658054
|
b8033f5c4f1d9d07692592354e4e646209e29962
| 2,563
|
cpp
|
C++
|
usaco/january-2022/bronze/problem-2/problem-2.cpp
|
Yash-Singh1/competitive-programming
|
3b9d278ed8138ab614e2a3d748627db8f4a2cdbd
|
[
"MIT"
] | null | null | null |
usaco/january-2022/bronze/problem-2/problem-2.cpp
|
Yash-Singh1/competitive-programming
|
3b9d278ed8138ab614e2a3d748627db8f4a2cdbd
|
[
"MIT"
] | null | null | null |
usaco/january-2022/bronze/problem-2/problem-2.cpp
|
Yash-Singh1/competitive-programming
|
3b9d278ed8138ab614e2a3d748627db8f4a2cdbd
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <ios>
using std::cin;
int main()
{
std::ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int t{0};
cin >> t;
for (int i{0}; i < t; ++i)
{
int die1[4], die2[4];
for (int j{0}; j < 4; ++j)
{
cin >> die1[j];
}
double prob2{0};
double prob1{0};
for (int j{0}; j < 4; ++j)
{
cin >> die2[j];
for (int k{0}; k < 4; ++k)
{
if (die2[j] > die1[k])
{
prob2 += 0.25;
}
}
}
for (int j{0}; j < 4; ++j)
{
for (int k{0}; k < 4; ++k)
{
if (die1[j] > die2[k])
{
prob1 += 0.25;
}
}
}
bool done{false};
for (int j{1}; j <= 10; ++j)
{
for (int k{j}; k <= 10; ++k)
{
for (int l{k}; l <= 10; ++l)
{
for (int m{l}; m <= 10; ++m)
{
double prob3{0};
double prob4{0};
int die3[4]{j, k, l, m};
for (int j{0}; j < 4; ++j)
{
for (int k{0}; k < 4; ++k)
{
if (die2[j] > die3[k])
{
prob3 += 0.25;
}
}
}
for (int j{0}; j < 4; ++j)
{
for (int k{0}; k < 4; ++k)
{
if (die3[j] > die2[k])
{
prob4 += 0.25;
}
}
}
if (prob3 > prob4)
{
continue;
}
double prob5{0};
double prob6{0};
for (int j{0}; j < 4; ++j)
{
for (int k{0}; k < 4; ++k)
{
if (die1[j] > die3[k])
{
prob5 += 0.25;
}
}
}
for (int j{0}; j < 4; ++j)
{
for (int k{0}; k < 4; ++k)
{
if (die3[j] > die1[k])
{
prob6 += 0.25;
}
}
}
if (prob6 < prob5)
{
continue;
}
std::cout << "yes\n";
done = true;
break;
}
if (done)
{
break;
}
}
if (done)
{
break;
}
}
if (done)
{
break;
}
}
if (done)
{
continue;
}
else
{
std::cout << "no\n";
}
}
}
| 19.270677
| 40
| 0.261022
|
Yash-Singh1
|
b80544cba266f8ae7a54e8f4be80e41852b1af37
| 7,254
|
cpp
|
C++
|
src/turtlebot_controller.cpp
|
DevasenaInupakutika/assn2
|
e533e0560241c81fa92a25b7058187562aa9fbfc
|
[
"Apache-2.0"
] | 1
|
2015-03-06T05:33:39.000Z
|
2015-03-06T05:33:39.000Z
|
src/turtlebot_controller.cpp
|
DevasenaInupakutika/assn2
|
e533e0560241c81fa92a25b7058187562aa9fbfc
|
[
"Apache-2.0"
] | null | null | null |
src/turtlebot_controller.cpp
|
DevasenaInupakutika/assn2
|
e533e0560241c81fa92a25b7058187562aa9fbfc
|
[
"Apache-2.0"
] | null | null | null |
#include <ros/ros.h>
#include <math.h>
#include <iostream>
#include "boost/thread/mutex.hpp"
#include <LinearMath/btMatrix3x3.h>
#include <sensor_msgs/LaserScan.h>
#include <geometry_msgs/Twist.h>
#include <geometry_msgs/PoseStamped.h>
#include <visualization_msgs/Marker.h>
#include <tf/transform_listener.h>
#include <tf/transform_datatypes.h>
#include <geometry_msgs/PointStamped.h>
using namespace std;
// current robot pose, relative to /odom
tf::StampedTransform robotPose;
// current goal pose
// TODO: clean up these types. why are they different??
// RESPONSE: one of them is a pose and one of them is a transform
// you could replace tf::Stamped<tf::Pose> with StampedPose, which
// I think is just a typedef
tf::Stamped<tf::Pose> goalPose;
// current linear/angular velocity of the robot
// these values are used to send out the cmd_vel
// messages to the robot each iteration
double linear = -0.3;
double angular = 0;
// true if the robot's forward path is blocked
bool pathBlocked = false;
// used to get the robot unstuck
int itcount = 0;
/* Called when receiving a new laser scan message */
void scanCallback(const sensor_msgs::LaserScan::ConstPtr& msg) {
// convenience vars
int numPts = msg->ranges.size();
//int centerIdx = numPts / 2;
// check to see if any point blocks the robot
// i.e. is the point within a rectangular window
double robotRadius = 0.16; // meters
double cutoffDist = 1.0; // meters (subtract about 0.08 to get true distance)
double cutoffAngle = atan2(robotRadius, cutoffDist);
bool foundAny = false;
bool blocked = false;
double blockAngle = 0;
// loop through scan range
for (int i = 0; i < numPts; i++) {
double distance = msg->ranges[i]-0.08;
double angle = msg->angle_min + i * msg->angle_increment;
// bounds check
if (distance < msg->range_min || distance > msg->range_max) {
continue;
}
foundAny = true;
// x-coordinate of point
double forward = distance * cos(angle);
if (abs(angle) > cutoffAngle) {
double lCutoff = abs(robotRadius / sin(angle));
if (distance < lCutoff) {
cout << "blocked at angle: " << angle << endl;
blocked = true;
blockAngle = angle;
}
} else if (forward < cutoffDist) {
cout << "forward too small: " << angle << endl;
blocked = true;
blockAngle = angle;
}
}
// TODO: move this to the controller code
// update control appropriately
if (foundAny && blocked) {
linear = 0;
itcount = 0;
pathBlocked = true;
// rotate away from obstacle
if (blockAngle >= 0) angular = -0.5;
else angular = 0.5;
} else if (pathBlocked) {
// once unblocked, try moving forward 8 times
if (itcount < 8) {
// move forward a little bit
itcount++;
linear = -0.3;
angular = 0.0;
} else {
// resume normal control
pathBlocked = false;
}
}
}
/* Called when receiving a new laser scan message */
void goalCallback(const geometry_msgs::PoseStamped::ConstPtr &msg) {
cout << "got a new goal" << endl;
// update goalPose
tf::poseStampedMsgToTF(*msg, goalPose);
}
int main(int argc, char** argv) {
// initialize ros
ros::init(argc, argv, "turtlebot_controller");
ros::NodeHandle n;
/* subscribe to laser scans */
ros::Subscriber scanSub = n.subscribe("scan", 1, scanCallback);
/* subscribe to rviz goals */
ros::Subscriber goalSub = n.subscribe("goal", 1, goalCallback);
/* publish cmd velocities */
ros::Publisher pub = n.advertise<geometry_msgs::Twist>("cmd_vel", 1);
/* transform listener */
tf::TransformListener listener;
// collect transforms for a while
listener.waitForTransform("/odom", "/base_link", ros::Time(), ros::Duration(1.5));
// set initial goal to be the robot's pose
try {
// lookup current robot pose wrt odom
listener.lookupTransform("/odom", "/base_link", ros::Time(), robotPose);
goalPose.setRotation(robotPose.getRotation());
goalPose.setOrigin(robotPose.getOrigin());
} catch (tf::TransformException ex) {
ROS_ERROR("%s",ex.what());
}
// publish frequency
ros::Rate loop_rate(30);
while (ros::ok()) {
try {
// update robotPose
listener.lookupTransform("/odom", "/base_footprint", ros::Time(0), robotPose);
} catch (tf::TransformException ex) {
ROS_ERROR("%s",ex.what());
}
// check for laser scans
ros::spinOnce();
// Controller, version 0
// Navigates in a series of phases:
// (0) If blocked, get unblocked
// (1) If misaligned, rotate towards goal
// (2) If facing goal, move towards goal
// (3) If at goal position, rotate into final orientation
/* --------------------------------------------------------- */
// convert goal pose to a message type
geometry_msgs::PoseStamped goalPoseMsg;
tf::poseStampedTFToMsg(goalPose, goalPoseMsg);
goalPoseMsg.header.frame_id = "/odom";
goalPoseMsg.header.stamp = ros::Time();
// get goal in base_link frame
geometry_msgs::PoseStamped relativePoseMsg;
listener.transformPose("/base_footprint", goalPoseMsg, relativePoseMsg);
// extract goal pose from the message
tf::Stamped<tf::Pose> relativePose;
tf::poseStampedMsgToTF(relativePoseMsg, relativePose);
// get the RPY and offset of the current goal
// (relative to robot's current position)
double roll, pitch, yaw;
tf::Matrix3x3(relativePose.getRotation()).getRPY(roll, pitch, yaw);
tf::Vector3 offset = relativePose.getOrigin();
// compute the 2-D angle from robot position to goal position
double angle = atan2(relativePose.getOrigin().getY(), relativePose.getOrigin().getX());
// if blocked, appropriate velocities are already set
if (!pathBlocked) {
// far away from goal?
if (sqrt(offset.getX()*offset.getX() + offset.getY()*offset.getY()) > 0.05) {
// not lined up?
if (abs(angle) > 0.3) {
cout << "rotating towards target\n";
if (abs(angle) > 0.05) {
if (angle > 0) {
angular = 1;
} else {
angular = -1;
}
}
linear = 0;
} else {
cout << "moving toward target" << endl;
if (offset.getX() > 0.05) {
linear = -0.3;
} else {
linear = 0.3;
}
// adjust course?
if (abs(angle) > 0.05) {
cout << "adjusting course\n" << endl;
if (angle > 0) {
angular = 0.2;
} else {
angular = -0.2;
}
}
}
} else {
// rotate into place?
if (abs(yaw) > 0.1) {
cout << "yaw into place\n" << endl;
if (yaw > 0) {
angular = 0.8;
} else {
angular = -0.8;
}
} else {
cout << "done!" << endl;
angular = 0;
}
linear = 0;
}
}
/* ---------------------------------------------------- */
// send out a new control message
double x = robotPose.getOrigin().x();
double y = robotPose.getOrigin().y();
double gx = goalPose.getOrigin().x();
double gy = goalPose.getOrigin().y();
cout<< "Robot is at position: "<< "( "<< x << "," << y <<") "<< endl;
cout<< "Goal coordinates are: "<<"( "<< gx << "," << gy <<") "<< endl;
geometry_msgs::Twist vel;
vel.linear.x = linear;
vel.angular.z = angular;
pub.publish(vel);
loop_rate.sleep();
}
return 0;
};
| 28.447059
| 89
| 0.621588
|
DevasenaInupakutika
|
b80859b2aecabe1fa51dabf8c71180d89f1db61b
| 48,944
|
cpp
|
C++
|
src/coreclr/dlls/mscorpe/ceefilegenwriter.cpp
|
berkansasmaz/runtime
|
7626c5d8be527d6735eddcdc7c97423211d8f9e9
|
[
"MIT"
] | 1
|
2021-11-21T18:25:08.000Z
|
2021-11-21T18:25:08.000Z
|
src/coreclr/dlls/mscorpe/ceefilegenwriter.cpp
|
berkansasmaz/runtime
|
7626c5d8be527d6735eddcdc7c97423211d8f9e9
|
[
"MIT"
] | 1
|
2021-11-19T10:42:54.000Z
|
2021-11-19T10:42:54.000Z
|
src/coreclr/dlls/mscorpe/ceefilegenwriter.cpp
|
berkansasmaz/runtime
|
7626c5d8be527d6735eddcdc7c97423211d8f9e9
|
[
"MIT"
] | 1
|
2020-01-31T06:16:53.000Z
|
2020-01-31T06:16:53.000Z
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// Derived class from CCeeGen which handles writing out
// the exe. All references to PEWriter pulled out of CCeeGen,
// and moved here
//
//
#include "stdafx.h"
#include <string.h>
#include <limits.h>
#include "corerror.h"
#include <posterror.h>
#include <shlwapi.h>
// The following block contains a template for the default entry point stubs of a COM+
// IL only program. One can emit these stubs (with some fix-ups) and make
// the code supplied the entry point value for the image. The fix-ups will
// in turn cause mscoree.dll to be loaded and the correct entry point to be
// called.
//
// Note: Although these stubs contain x86 specific code, they are used
// for all platforms
//*****************************************************************************
// This stub is designed for a x86 Windows application. It will call the
// _CorExeMain function in mscoree.dll. This entry point will in turn load
// and run the IL program.
//
// jump _CorExeMain();
//
// The code jumps to the imported function _CorExeMain using the iat.
// The address in the template is address of the iat entry which is
// fixed up by the loader when the image is paged in.
//*****************************************************************************
const BYTE ExeMainX86Template[] =
{
// Jump through IAT to _CorExeMain
0xFF, 0x25, // jmp [iat:_CorDllMain entry]
0x00, 0x00, 0x00, 0x00, // address to replace
};
#define ExeMainX86TemplateSize sizeof(ExeMainX86Template)
#define CorExeMainX86IATOffset 2
//*****************************************************************************
// This stub is designed for a x86 Windows application. It will call the
// _CorDllMain function in mscoree.dll with with the base entry point for
// the loaded DLL. This entry point will in turn load and run the IL program.
//
// jump _CorDllMain
//
// The code jumps to the imported function _CorExeMain using the iat.
// The address in the template is address of the iat entry which is
// fixed up by the loader when the image is paged in.
//*****************************************************************************
const BYTE DllMainX86Template[] =
{
// Jump through IAT to CorDllMain
0xFF, 0x25, // jmp [iat:_CorDllMain entry]
0x00, 0x00, 0x00, 0x00, // address to replace
};
#define DllMainX86TemplateSize sizeof(DllMainX86Template)
#define CorDllMainX86IATOffset 2
//*****************************************************************************
// This stub is designed for a AMD64 Windows application. It will call the
// _CorExeMain function in mscoree.dll. This entry point will in turn load
// and run the IL program.
//
// mov rax, _CorExeMain();
// jmp [rax]
//
// The code jumps to the imported function _CorExeMain using the iat.
// The address in the template is address of the iat entry which is
// fixed up by the loader when the image is paged in.
//*****************************************************************************
const BYTE ExeMainAMD64Template[] =
{
// Jump through IAT to _CorExeMain
0x48, 0xA1, // rex.w rex.b mov rax,[following address]
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,//address of iat:_CorExeMain entry
0xFF, 0xE0 // jmp [rax]
};
#define ExeMainAMD64TemplateSize sizeof(ExeMainAMD64Template)
#define CorExeMainAMD64IATOffset 2
//*****************************************************************************
// This stub is designed for a AMD64 Windows application. It will call the
// _CorDllMain function in mscoree.dll with with the base entry point for
// the loaded DLL. This entry point will in turn load and run the IL program.
//
// mov rax, _CorDllMain();
// jmp [rax]
//
// The code jumps to the imported function _CorDllMain using the iat.
// The address in the template is address of the iat entry which is
// fixed up by the loader when the image is paged in.
//*****************************************************************************
const BYTE DllMainAMD64Template[] =
{
// Jump through IAT to CorDllMain
0x48, 0xA1, // rex.w rex.b mov rax,[following address]
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,//address of iat:_CorDllMain entry
0xFF, 0xE0 // jmp [rax]
};
#define DllMainAMD64TemplateSize sizeof(DllMainAMD64Template)
#define CorDllMainAMD64IATOffset 2
//*****************************************************************************
// This stub is designed for an ia64 Windows application. It will call the
// _CorExeMain function in mscoree.dll. This entry point will in turn load
// and run the IL program.
//
// jump _CorExeMain();
//
// The code jumps to the imported function _CorExeMain using the iat.
// We set the value of gp to point at the iat table entry for _CorExeMain
//*****************************************************************************
const BYTE ExeMainIA64Template[] =
{
// ld8 r9 = [gp] ;;
// ld8 r10 = [r9],8
// nop.i ;;
// ld8 gp = [r9]
// mov b6 = r10
// br.cond.sptk.few b6
//
0x0B, 0x48, 0x00, 0x02, 0x18, 0x10, 0xA0, 0x40,
0x24, 0x30, 0x28, 0x00, 0x00, 0x00, 0x04, 0x00,
0x10, 0x08, 0x00, 0x12, 0x18, 0x10, 0x60, 0x50,
0x04, 0x80, 0x03, 0x00, 0x60, 0x00, 0x80, 0x00
};
#define ExeMainIA64TemplateSize sizeof(ExeMainIA64Template)
//*****************************************************************************
// This stub is designed for an ia64 Windows application. It will call the
// _CorDllMain function in mscoree.dll with with the base entry point for
// the loaded DLL. This entry point will in turn load and run the IL program.
//
// jump _CorDllMain
//
// The code jumps to the imported function _CorExeMain using the iat.
// We set the value of gp to point at the iat table entry for _CorExeMain
//*****************************************************************************
const BYTE DllMainIA64Template[] =
{
// ld8 r9 = [gp] ;;
// ld8 r10 = [r9],8
// nop.i ;;
// ld8 gp = [r9]
// mov b6 = r10
// br.cond.sptk.few b6
//
0x0B, 0x48, 0x00, 0x02, 0x18, 0x10, 0xA0, 0x40,
0x24, 0x30, 0x28, 0x00, 0x00, 0x00, 0x04, 0x00,
0x10, 0x08, 0x00, 0x12, 0x18, 0x10, 0x60, 0x50,
0x04, 0x80, 0x03, 0x00, 0x60, 0x00, 0x80, 0x00
};
#define DllMainIA64TemplateSize sizeof(DllMainIA64Template)
// Get the Symbol entry given the head and a 0-based index
inline IMAGE_SYMBOL* GetSymbolEntry(IMAGE_SYMBOL* pHead, SIZE_T idx)
{
return (IMAGE_SYMBOL*) (((BYTE*) pHead) + IMAGE_SIZEOF_SYMBOL * idx);
}
//*****************************************************************************
// To get a new instance, call CreateNewInstance() or CreateNewInstanceEx() instead of new
//*****************************************************************************
HRESULT CeeFileGenWriter::CreateNewInstance(CCeeGen *pCeeFileGenFrom,
CeeFileGenWriter* & pGenWriter,
DWORD createFlags)
{
return CreateNewInstanceEx(pCeeFileGenFrom, pGenWriter, createFlags);
}
//
// Seed file is used as the base file. The new file data will be "appended" to the seed file
//
HRESULT CeeFileGenWriter::CreateNewInstanceEx(CCeeGen *pCeeFileGenFrom,
CeeFileGenWriter* & pGenWriter,
DWORD createFlags,
LPCWSTR seedFileName)
{
HRESULT hr = S_OK;
ULONG preallocatedOffset = 0;
NewHolder<PEWriter> pPEWriter(NULL);
NewHolder<CeeFileGenWriter> pPrivateGenWriter;
CeeSection *corHeaderSection = NULL;
pPrivateGenWriter = new (nothrow) CeeFileGenWriter;
if (pPrivateGenWriter == NULL)
IfFailGo(E_OUTOFMEMORY);
pPEWriter = new (nothrow) PEWriter;
if (pPEWriter == NULL)
IfFailGo(E_OUTOFMEMORY);
//workaround
//What's really the correct thing to be doing here?
//HRESULT hr = pPEWriter->Init(pCeeFileGenFrom ? pCeeFileGenFrom->getPESectionMan() : NULL);
hr = pPEWriter->Init(NULL, createFlags, seedFileName);
IfFailGo(hr);
//Create the general PEWriter.
pPrivateGenWriter->m_peSectionMan = pPEWriter;
hr = pPrivateGenWriter->Init(); // base class member to finish init
IfFailGo(hr);
if (!seedFileName) // Use base file's preferred base (if present)
{
if (pPEWriter->isPE32())
{
pPrivateGenWriter->setImageBase((DWORD) CEE_IMAGE_BASE_32); // use same default as linker
}
else
{
pPrivateGenWriter->setImageBase64((ULONGLONG) CEE_IMAGE_BASE_64); // use same default as linker
}
}
pPrivateGenWriter->setSubsystem(IMAGE_SUBSYSTEM_WINDOWS_CUI, CEE_IMAGE_SUBSYSTEM_MAJOR_VERSION, CEE_IMAGE_SUBSYSTEM_MINOR_VERSION);
if (pPEWriter->createCorMainStub())
{
hr = pPrivateGenWriter->allocateIAT(); // so the IAT goes out first
IfFailGo(hr);
}
hr = pPrivateGenWriter->allocateCorHeader(); // get COR header near front
IfFailGo(hr);
//If we were passed a CCeeGen at the beginning, copy it's data now.
if (pCeeFileGenFrom) {
pCeeFileGenFrom->cloneInstance((CCeeGen*)pPrivateGenWriter);
}
hr = pPrivateGenWriter->getSectionCreate(".text0", sdExecute, &corHeaderSection);
IfFailGo(hr);
preallocatedOffset = corHeaderSection->dataLen();
// set il RVA to be after the preallocated sections
pPEWriter->setIlRva(preallocatedOffset);
pPEWriter.SuppressRelease();
pPrivateGenWriter.SuppressRelease();
pGenWriter = pPrivateGenWriter;
ErrExit:
return hr;
} // HRESULT CeeFileGenWriter::CreateNewInstance()
CeeFileGenWriter::CeeFileGenWriter() // ctor is protected
{
m_outputFileName = NULL;
m_resourceFileName = NULL;
m_dllSwitch = false;
m_entryPoint = 0;
m_comImageFlags = COMIMAGE_FLAGS_ILONLY; // ceegen PEs don't have native code
m_iatOffset = 0;
m_dllCount = 0;
m_dwManifestSize = 0;
m_dwManifestRVA = NULL;
m_dwStrongNameSize = 0;
m_dwStrongNameRVA = NULL;
m_dwVTableSize = 0;
m_dwVTableRVA = NULL;
m_iDataDlls = NULL;
m_linked = false;
m_fixed = false;
} // CeeFileGenWriter::CeeFileGenWriter()
//*****************************************************************************
// Cleanup
//*****************************************************************************
HRESULT CeeFileGenWriter::Cleanup() // virtual
{
((PEWriter *)m_peSectionMan)->Cleanup(); // call derived cleanup
delete m_peSectionMan;
m_peSectionMan = NULL; // so base class won't delete
delete[] m_outputFileName;
delete[] m_resourceFileName;
if (m_iDataDlls) {
for (int i=0; i < m_dllCount; i++) {
if (m_iDataDlls[i].m_methodName)
delete[] m_iDataDlls[i].m_methodName;
}
delete[] m_iDataDlls;
}
return CCeeGen::Cleanup();
} // HRESULT CeeFileGenWriter::Cleanup()
HRESULT CeeFileGenWriter::link()
{
HRESULT hr = checkForErrors();
if (! SUCCEEDED(hr))
return hr;
// Don't set this if SetManifestEntry was not called - zapper sets the
// resource directory explicitly
if (m_dwManifestSize != 0)
{
m_corHeader->Resources.VirtualAddress = VAL32(m_dwManifestRVA);
m_corHeader->Resources.Size = VAL32(m_dwManifestSize);
}
if (m_dwStrongNameSize != 0)
{
m_corHeader->StrongNameSignature.VirtualAddress = VAL32(m_dwStrongNameRVA);
m_corHeader->StrongNameSignature.Size = VAL32(m_dwStrongNameSize);
}
if (m_dwVTableSize != 0)
{
m_corHeader->VTableFixups.VirtualAddress = VAL32(m_dwVTableRVA);
m_corHeader->VTableFixups.Size = VAL32(m_dwVTableSize);
}
unsigned characteristicsMask = IMAGE_FILE_EXECUTABLE_IMAGE;
if (getPEWriter().isPE32())
characteristicsMask |= IMAGE_FILE_32BIT_MACHINE;
if (!getPEWriter().isPE32())
characteristicsMask |= IMAGE_FILE_LARGE_ADDRESS_AWARE;
getPEWriter().setCharacteristics(characteristicsMask);
m_corHeader->cb = VAL32(sizeof(IMAGE_COR20_HEADER));
m_corHeader->MajorRuntimeVersion = VAL16(COR_VERSION_MAJOR);
m_corHeader->MinorRuntimeVersion = VAL16(COR_VERSION_MINOR);
if (m_dllSwitch)
getPEWriter().setCharacteristics(IMAGE_FILE_DLL);
m_corHeader->Flags = VAL32(m_comImageFlags);
IMAGE_COR20_HEADER_FIELD(*m_corHeader, EntryPointToken) = VAL32(m_entryPoint);
_ASSERTE(TypeFromToken(m_entryPoint) == mdtMethodDef || m_entryPoint == mdTokenNil ||
TypeFromToken(m_entryPoint) == mdtFile);
setDirectoryEntry(getCorHeaderSection(), IMAGE_DIRECTORY_ENTRY_COMHEADER, sizeof(IMAGE_COR20_HEADER), m_corHeaderOffset);
if ((m_comImageFlags & COMIMAGE_FLAGS_IL_LIBRARY) == 0
&& !m_linked)
{
hr = emitExeMain();
if (FAILED(hr))
return hr;
#ifndef TARGET_UNIX
hr = emitResourceSection();
if (FAILED(hr))
return hr;
#endif
}
m_linked = true;
IfFailRet(getPEWriter().link());
return S_OK;
} // HRESULT CeeFileGenWriter::link()
HRESULT CeeFileGenWriter::fixup()
{
HRESULT hr;
m_fixed = true;
if (!m_linked)
IfFailRet(link());
CeeGenTokenMapper *pMapper = getTokenMapper();
// Apply token remaps if there are any.
if (! m_fTokenMapSupported && pMapper != NULL) {
IMetaDataImport *pImport;
hr = pMapper->GetMetaData(&pImport);
_ASSERTE(SUCCEEDED(hr));
hr = MapTokens(pMapper, pImport);
pImport->Release();
}
// remap the entry point if entry point token has been moved
if (pMapper != NULL)
{
mdToken tk = m_entryPoint;
pMapper->HasTokenMoved(tk, tk);
IMAGE_COR20_HEADER_FIELD(*m_corHeader, EntryPointToken) = VAL32(tk);
}
IfFailRet(getPEWriter().fixup(pMapper));
return S_OK;
} // HRESULT CeeFileGenWriter::fixup()
HRESULT CeeFileGenWriter::generateImage(void **ppImage)
{
HRESULT hr = S_OK;
LPCWSTR outputFileName = NULL;
#ifndef TARGET_UNIX
HANDLE hThreadToken = NULL;
// Impersonation is only supported on Win2k and above.
if (!OpenThreadToken(GetCurrentThread(), TOKEN_READ | TOKEN_IMPERSONATE, TRUE, &hThreadToken))
{
if (GetLastError() != ERROR_NO_TOKEN)
{
_ASSERTE(!"Failed to get thread token!");
return HRESULT_FROM_GetLastError();
}
}
if (hThreadToken != NULL)
{
if (!RevertToSelf())
{
_ASSERTE(!"Failed to revert impersonation!");
CloseHandle(hThreadToken);
return HRESULT_FROM_GetLastError();
}
}
#endif // !TARGET_UNIX
if (!m_fixed)
IfFailGo(fixup());
outputFileName = m_outputFileName;
if (! outputFileName && ppImage == NULL) {
if (m_comImageFlags & COMIMAGE_FLAGS_IL_LIBRARY)
outputFileName = W("output.ill");
else if (m_dllSwitch)
outputFileName = W("output.dll");
else
outputFileName = W("output.exe");
}
// output file name and ppImage are mutually exclusive
_ASSERTE((NULL == outputFileName && ppImage != NULL) || (outputFileName != NULL && NULL == ppImage));
if (outputFileName != NULL)
IfFailGo(getPEWriter().write(outputFileName));
else
IfFailGo(getPEWriter().write(ppImage));
ErrExit:
#ifndef TARGET_UNIX
if (hThreadToken != NULL)
{
BOOL success = SetThreadToken(NULL, hThreadToken);
CloseHandle(hThreadToken);
if (!success)
{
_ASSERTE(!"Failed to reimpersonate!");
hr = HRESULT_FROM_GetLastError();
}
}
#endif // !TARGET_UNIX
return hr;
} // HRESULT CeeFileGenWriter::generateImage()
HRESULT CeeFileGenWriter::setOutputFileName(_In_ LPWSTR fileName)
{
if (m_outputFileName)
delete[] m_outputFileName;
size_t len = wcslen(fileName) + 1;
m_outputFileName = (LPWSTR)new (nothrow) WCHAR[len];
TESTANDRETURN(m_outputFileName!=NULL, E_OUTOFMEMORY);
wcscpy_s(m_outputFileName, len, fileName);
return S_OK;
} // HRESULT CeeFileGenWriter::setOutputFileName()
HRESULT CeeFileGenWriter::setResourceFileName(_In_ LPWSTR fileName)
{
if (m_resourceFileName)
delete[] m_resourceFileName;
size_t len = wcslen(fileName) + 1;
m_resourceFileName = (LPWSTR)new (nothrow) WCHAR[len];
TESTANDRETURN(m_resourceFileName!=NULL, E_OUTOFMEMORY);
wcscpy_s(m_resourceFileName, len, fileName);
return S_OK;
} // HRESULT CeeFileGenWriter::setResourceFileName()
HRESULT CeeFileGenWriter::setImageBase(size_t imageBase)
{
_ASSERTE(getPEWriter().isPE32());
getPEWriter().setImageBase32((DWORD)imageBase);
return S_OK;
} // HRESULT CeeFileGenWriter::setImageBase()
HRESULT CeeFileGenWriter::setImageBase64(ULONGLONG imageBase)
{
_ASSERTE(!getPEWriter().isPE32());
getPEWriter().setImageBase64(imageBase);
return S_OK;
} // HRESULT CeeFileGenWriter::setImageBase64()
HRESULT CeeFileGenWriter::setFileAlignment(ULONG fileAlignment)
{
getPEWriter().setFileAlignment(fileAlignment);
return S_OK;
} // HRESULT CeeFileGenWriter::setFileAlignment()
HRESULT CeeFileGenWriter::setSubsystem(DWORD subsystem, DWORD major, DWORD minor)
{
getPEWriter().setSubsystem(subsystem, major, minor);
return S_OK;
} // HRESULT CeeFileGenWriter::setSubsystem()
HRESULT CeeFileGenWriter::checkForErrors()
{
if (TypeFromToken(m_entryPoint) == mdtMethodDef) {
if (m_dllSwitch) {
//current spec would need to check the binary sig of the entry point method
}
return S_OK;
}
return S_OK;
} // HRESULT CeeFileGenWriter::checkForErrors()
HRESULT CeeFileGenWriter::getMethodRVA(ULONG codeOffset, ULONG *codeRVA)
{
_ASSERTE(codeRVA);
*codeRVA = getPEWriter().getIlRva() + codeOffset;
return S_OK;
} // HRESULT CeeFileGenWriter::getMethodRVA()
HRESULT CeeFileGenWriter::setDirectoryEntry(CeeSection §ion, ULONG entry, ULONG size, ULONG offset)
{
return getPEWriter().setDirectoryEntry((PEWriterSection*)(§ion.getImpl()), entry, size, offset);
} // HRESULT CeeFileGenWriter::setDirectoryEntry()
HRESULT CeeFileGenWriter::getFileTimeStamp(DWORD *pTimeStamp)
{
return getPEWriter().getFileTimeStamp(pTimeStamp);
} // HRESULT CeeFileGenWriter::getFileTimeStamp()
HRESULT CeeFileGenWriter::setAddrReloc(UCHAR *instrAddr, DWORD value)
{
*(DWORD *)instrAddr = VAL32(value);
return S_OK;
} // HRESULT CeeFileGenWriter::setAddrReloc()
HRESULT CeeFileGenWriter::addAddrReloc(CeeSection &thisSection, UCHAR *instrAddr, DWORD offset, CeeSection *targetSection)
{
if (!targetSection) {
thisSection.addBaseReloc(offset, srRelocHighLow);
} else {
thisSection.addSectReloc(offset, *targetSection, srRelocHighLow);
}
return S_OK;
} // HRESULT CeeFileGenWriter::addAddrReloc()
// create CorExeMain and import directory into .text and the .iat into .data
//
// The structure of the import directory information is as follows, but it is not contiguous in
// section. All the r/o data goes into the .text section and the iat array (which the loader
// updates with the imported addresses) goes into the .data section because WINCE needs it to be writable.
//
// struct IData {
// // one for each DLL, terminating in NULL
// IMAGE_IMPORT_DESCRIPTOR iid[];
// // import lookup table: a set of entries for the methods of each DLL,
// // terminating each set with NULL
// IMAGE_THUNK_DATA32/64 ilt[];
// // hint/name table: an set of entries for each method of each DLL wiht
// // no terminating entry
// struct {
// WORD Hint;
// // null terminated string
// BYTE Name[];
// } ibn; // Hint/name table
// // import address table: a set of entries for the methods of each DLL,
// // terminating each set with NULL
// IMAGE_THUNK_DATA32/64 iat[];
// // one for each DLL, null terminated strings
// BYTE DllName[];
// };
//
// IAT must be first in its section, so have code here to allocate it up front
// prior to knowing other info such as if dll or not. This won't work if have > 1
// function imported, but we'll burn that bridge when we get to it.
HRESULT CeeFileGenWriter::allocateIAT()
{
m_dllCount = 1;
m_iDataDlls = new (nothrow) IDataDllInfo[m_dllCount];
if (m_iDataDlls == NULL) {
return E_OUTOFMEMORY;
}
memset(m_iDataDlls, '\0', m_dllCount * sizeof(IDataDllInfo));
m_iDataDlls[0].m_name = "mscoree.dll";
m_iDataDlls[0].m_numMethods = 1;
m_iDataDlls[0].m_methodName = new (nothrow) const char*[m_iDataDlls[0].m_numMethods];
if (! m_iDataDlls[0].m_methodName) {
return E_OUTOFMEMORY;
}
m_iDataDlls[0].m_methodName[0] = NULL;
int iDataSizeIAT = 0;
for (int i=0; i < m_dllCount; i++) {
m_iDataDlls[i].m_iatOffset = iDataSizeIAT;
iDataSizeIAT += (m_iDataDlls[i].m_numMethods + 1)
* (getPEWriter().isPE32() ? sizeof(IMAGE_THUNK_DATA32)
: sizeof(IMAGE_THUNK_DATA64));
}
HRESULT hr = getSectionCreate(".text0", sdExecute, &m_iDataSectionIAT);
TESTANDRETURNHR(hr);
m_iDataOffsetIAT = m_iDataSectionIAT->dataLen();
_ASSERTE(m_iDataOffsetIAT == 0);
m_iDataIAT = m_iDataSectionIAT->getBlock(iDataSizeIAT);
if (! m_iDataIAT) {
return E_OUTOFMEMORY;
}
memset(m_iDataIAT, '\0', iDataSizeIAT);
// Don't set the IAT directory entry yet, since we may not actually end up doing
// an emitExeMain.
return S_OK;
} // HRESULT CeeFileGenWriter::allocateIAT()
HRESULT CeeFileGenWriter::emitExeMain()
{
if (m_dllCount == 0)
return S_OK;
// Note: code later on in this method assumes that mscoree.dll is at
// index m_iDataDlls[0], with CorDllMain or CorExeMain at method[0]
_ASSERTE(getPEWriter().createCorMainStub());
if (m_dllSwitch) {
m_iDataDlls[0].m_methodName[0] = "_CorDllMain";
} else {
m_iDataDlls[0].m_methodName[0] = "_CorExeMain";
}
// IMAGE_IMPORT_DESCRIPTOR on PE/PE+ must be 4-byte or 8-byte aligned
int align = (getPEWriter().isPE32()) ? 4 : 8;
int curOffset = getTextSection().dataLen();
int diff = ((curOffset + align -1) & ~(align-1)) - curOffset;
if (diff)
{
char* pDiff = getTextSection().getBlock(diff);
if (NULL==pDiff) return E_OUTOFMEMORY;
memset(pDiff,0,diff);
}
int iDataSizeRO = (m_dllCount + 1) * sizeof(IMAGE_IMPORT_DESCRIPTOR);
CeeSection &iDataSectionRO = getTextSection();
int iDataOffsetRO = iDataSectionRO.dataLen();
int iDataSizeIAT = 0;
int i;
for (i=0; i < m_dllCount; i++) {
m_iDataDlls[i].m_iltOffset = iDataSizeRO + iDataSizeIAT;
iDataSizeIAT += (m_iDataDlls[i].m_numMethods + 1)
* (getPEWriter().isPE32() ? sizeof(IMAGE_THUNK_DATA32)
: sizeof(IMAGE_THUNK_DATA64));
}
iDataSizeRO += iDataSizeIAT;
for (i=0; i < m_dllCount; i++) {
int delta = (iDataSizeRO + iDataOffsetRO) % 16;
// make sure is on a 16-byte offset
if (delta != 0)
iDataSizeRO += (16 - delta);
_ASSERTE((iDataSizeRO + iDataOffsetRO) % 16 == 0);
m_iDataDlls[i].m_ibnOffset = iDataSizeRO;
for (int j=0; j < m_iDataDlls[i].m_numMethods; j++) {
int nameLen = (int)(strlen(m_iDataDlls[i].m_methodName[j]) + 1);
iDataSizeRO += sizeof(WORD) + nameLen + nameLen%2;
}
}
for (i=0; i < m_dllCount; i++) {
m_iDataDlls[i].m_nameOffset = iDataSizeRO;
iDataSizeRO += (int)(strlen(m_iDataDlls[i].m_name) + 2);
}
char *iDataRO = iDataSectionRO.getBlock(iDataSizeRO);
if (!iDataRO) return E_OUTOFMEMORY;
memset(iDataRO, '\0', iDataSizeRO);
setDirectoryEntry(iDataSectionRO, IMAGE_DIRECTORY_ENTRY_IMPORT, iDataSizeRO, iDataOffsetRO);
IMAGE_IMPORT_DESCRIPTOR *iid = (IMAGE_IMPORT_DESCRIPTOR *)iDataRO;
for (i=0; i < m_dllCount; i++) {
// fill in the import descriptors for each DLL
IMAGE_IMPORT_DESC_FIELD(iid[i], OriginalFirstThunk) = VAL32((ULONG)(m_iDataDlls[i].m_iltOffset + iDataOffsetRO));
iid[i].Name = VAL32(m_iDataDlls[i].m_nameOffset + iDataOffsetRO);
iid[i].FirstThunk = VAL32((ULONG)(m_iDataDlls[i].m_iatOffset + m_iDataOffsetIAT));
iDataSectionRO.addSectReloc(
(unsigned)(iDataOffsetRO + (char *)(&IMAGE_IMPORT_DESC_FIELD(iid[i], OriginalFirstThunk)) - iDataRO), iDataSectionRO, srRelocAbsolute);
iDataSectionRO.addSectReloc(
(unsigned)(iDataOffsetRO + (char *)(&iid[i].Name) - iDataRO), iDataSectionRO, srRelocAbsolute);
iDataSectionRO.addSectReloc(
(unsigned)(iDataOffsetRO + (char *)(&iid[i].FirstThunk) - iDataRO), *m_iDataSectionIAT, srRelocAbsolute);
if (getPEWriter().isPE32())
{
// now fill in the import lookup table for each DLL
IMAGE_THUNK_DATA32 *ilt = (IMAGE_THUNK_DATA32*) (iDataRO + m_iDataDlls[i].m_iltOffset);
IMAGE_THUNK_DATA32 *iat = (IMAGE_THUNK_DATA32*) (m_iDataIAT + m_iDataDlls[i].m_iatOffset);
int ibnOffset = m_iDataDlls[i].m_ibnOffset;
for (int j=0; j < m_iDataDlls[i].m_numMethods; j++)
{
ilt[j].u1.AddressOfData = VAL32((ULONG)(ibnOffset + iDataOffsetRO));
iat[j].u1.AddressOfData = VAL32((ULONG)(ibnOffset + iDataOffsetRO));
iDataSectionRO.addSectReloc( (unsigned)(iDataOffsetRO + (char *)(&ilt[j].u1.AddressOfData) - iDataRO),
iDataSectionRO, srRelocAbsolute);
m_iDataSectionIAT->addSectReloc( (unsigned)(m_iDataOffsetIAT + (char *)(&iat[j].u1.AddressOfData) - m_iDataIAT),
iDataSectionRO, srRelocAbsolute);
int nameLen = (int)(strlen(m_iDataDlls[i].m_methodName[j]) + 1);
memcpy(iDataRO + ibnOffset + offsetof(IMAGE_IMPORT_BY_NAME, Name),
m_iDataDlls[i].m_methodName[j], nameLen);
ibnOffset += sizeof(WORD) + nameLen + nameLen%2;
}
}
else
{
// now fill in the import lookup table for each DLL
IMAGE_THUNK_DATA64 *ilt = (IMAGE_THUNK_DATA64*) (iDataRO + m_iDataDlls[i].m_iltOffset);
IMAGE_THUNK_DATA64 *iat = (IMAGE_THUNK_DATA64*) (m_iDataIAT + m_iDataDlls[i].m_iatOffset);
int ibnOffset = m_iDataDlls[i].m_ibnOffset;
for (int j=0; j < m_iDataDlls[i].m_numMethods; j++)
{
ilt[j].u1.AddressOfData = VAL64((ULONG)(ibnOffset + iDataOffsetRO));
iat[j].u1.AddressOfData = VAL64((ULONG)(ibnOffset + iDataOffsetRO));
iDataSectionRO.addSectReloc( (unsigned)(iDataOffsetRO + (char *)(&ilt[j].u1.AddressOfData) - iDataRO),
iDataSectionRO, srRelocAbsolute);
m_iDataSectionIAT->addSectReloc( (unsigned)(m_iDataOffsetIAT + (char *)(&iat[j].u1.AddressOfData) - m_iDataIAT),
iDataSectionRO, srRelocAbsolute);
int nameLen = (int)(strlen(m_iDataDlls[i].m_methodName[j]) + 1);
memcpy(iDataRO + ibnOffset + offsetof(IMAGE_IMPORT_BY_NAME, Name),
m_iDataDlls[i].m_methodName[j], nameLen);
ibnOffset += sizeof(WORD) + nameLen + nameLen%2;
}
}
// now fill in the import lookup table for each DLL
strcpy_s(iDataRO + m_iDataDlls[i].m_nameOffset,
iDataSizeRO - m_iDataDlls[i].m_nameOffset,
m_iDataDlls[i].m_name);
} // end of for loop i < m_dllCount
if (getPEWriter().isI386())
{
// Put the entry point code into the PE file
unsigned entryPointOffset = getTextSection().dataLen();
int iatOffset = (int) (entryPointOffset + (m_dllSwitch ? CorDllMainX86IATOffset : CorExeMainX86IATOffset));
align = 4; // x86 fixups must be 4-byte aligned
// The IAT offset must be aligned because fixup is applied to it.
diff = ((iatOffset + align -1) & ~(align-1)) - iatOffset;
if (diff)
{
char* pDiff = getTextSection().getBlock(diff);
if(NULL==pDiff) return E_OUTOFMEMORY;
memset(pDiff,0,diff);
entryPointOffset += diff;
}
_ASSERTE((getTextSection().dataLen() + (m_dllSwitch ? CorDllMainX86IATOffset : CorExeMainX86IATOffset)) % align == 0);
getPEWriter().setEntryPointTextOffset(entryPointOffset);
if (m_dllSwitch)
{
UCHAR *dllMainBuf = (UCHAR*)getTextSection().getBlock(sizeof(DllMainX86Template));
if(dllMainBuf==NULL) return E_OUTOFMEMORY;
memcpy(dllMainBuf, DllMainX86Template, sizeof(DllMainX86Template));
//mscoree.dll
setAddrReloc(dllMainBuf+CorDllMainX86IATOffset, m_iDataDlls[0].m_iatOffset + m_iDataOffsetIAT);
addAddrReloc(getTextSection(), dllMainBuf, entryPointOffset+CorDllMainX86IATOffset, m_iDataSectionIAT);
}
else
{
UCHAR *exeMainBuf = (UCHAR*)getTextSection().getBlock(sizeof(ExeMainX86Template));
if(exeMainBuf==NULL) return E_OUTOFMEMORY;
memcpy(exeMainBuf, ExeMainX86Template, sizeof(ExeMainX86Template));
//mscoree.dll
setAddrReloc(exeMainBuf+CorExeMainX86IATOffset, m_iDataDlls[0].m_iatOffset + m_iDataOffsetIAT);
addAddrReloc(getTextSection(), exeMainBuf, entryPointOffset+CorExeMainX86IATOffset, m_iDataSectionIAT);
}
}
else if (getPEWriter().isAMD64())
{
// Put the entry point code into the PE file
unsigned entryPointOffset = getTextSection().dataLen();
int iatOffset = (int) (entryPointOffset + (m_dllSwitch ? CorDllMainAMD64IATOffset : CorExeMainAMD64IATOffset));
align = 16; // AMD64 fixups must be 8-byte aligned
// The IAT offset must be aligned because fixup is applied to it.
diff = ((iatOffset + align -1) & ~(align-1)) - iatOffset;
if (diff)
{
char* pDiff = getTextSection().getBlock(diff);
if(NULL==pDiff) return E_OUTOFMEMORY;
memset(pDiff,0,diff);
entryPointOffset += diff;
}
_ASSERTE((getTextSection().dataLen() + (m_dllSwitch ? CorDllMainAMD64IATOffset : CorExeMainAMD64IATOffset)) % align == 0);
getPEWriter().setEntryPointTextOffset(entryPointOffset);
if (m_dllSwitch)
{
UCHAR *dllMainBuf = (UCHAR*)getTextSection().getBlock(sizeof(DllMainAMD64Template));
if(dllMainBuf==NULL) return E_OUTOFMEMORY;
memcpy(dllMainBuf, DllMainAMD64Template, sizeof(DllMainAMD64Template));
//mscoree.dll
setAddrReloc(dllMainBuf+CorDllMainAMD64IATOffset, m_iDataDlls[0].m_iatOffset + m_iDataOffsetIAT);
addAddrReloc(getTextSection(), dllMainBuf, entryPointOffset+CorDllMainAMD64IATOffset, m_iDataSectionIAT);
}
else
{
UCHAR *exeMainBuf = (UCHAR*)getTextSection().getBlock(sizeof(ExeMainAMD64Template));
if(exeMainBuf==NULL) return E_OUTOFMEMORY;
memcpy(exeMainBuf, ExeMainAMD64Template, sizeof(ExeMainAMD64Template));
//mscoree.dll
setAddrReloc(exeMainBuf+CorExeMainAMD64IATOffset, m_iDataDlls[0].m_iatOffset + m_iDataOffsetIAT);
addAddrReloc(getTextSection(), exeMainBuf, entryPointOffset+CorExeMainAMD64IATOffset, m_iDataSectionIAT);
}
}
else if (getPEWriter().isIA64())
{
// Must have a PE+ PE64 file
//_ASSERTE(!getPEWriter().isPE32());
// Put the entry point code into the PE+ file
curOffset = getTextSection().dataLen();
align = 16; // instructions on ia64 must be 16-byte aligned
// The entry point address be aligned
diff = ((curOffset + align -1) & ~(align-1)) - curOffset;
if (diff)
{
char* pDiff = getTextSection().getBlock(diff);
if(NULL==pDiff) return E_OUTOFMEMORY;
memset(pDiff,0,diff);
}
unsigned entryPointOffset = getTextSection().dataLen();
if (m_dllSwitch)
{
UCHAR *dllMainBuf = (UCHAR*)getTextSection().getBlock(sizeof(DllMainIA64Template));
if (dllMainBuf==NULL) return E_OUTOFMEMORY;
memcpy(dllMainBuf, DllMainIA64Template, sizeof(DllMainIA64Template));
}
else
{
UCHAR *exeMainBuf = (UCHAR*)getTextSection().getBlock(sizeof(ExeMainIA64Template));
if (exeMainBuf==NULL) return E_OUTOFMEMORY;
memcpy(exeMainBuf, ExeMainIA64Template, sizeof(ExeMainIA64Template));
}
// Put the entry point function pointer into the PE file
unsigned entryPlabelOffset = getTextSection().dataLen();
getPEWriter().setEntryPointTextOffset(entryPlabelOffset);
UCHAR * entryPtr = (UCHAR*)getTextSection().getBlock(sizeof(ULONGLONG));
UCHAR * gpPtr = (UCHAR*)getTextSection().getBlock(sizeof(ULONGLONG));
memset(entryPtr,0,sizeof(ULONGLONG));
memset(gpPtr,0,sizeof(ULONGLONG));
setAddrReloc(entryPtr, entryPointOffset);
addAddrReloc(getTextSection(), entryPtr, entryPlabelOffset, &getTextSection());
setAddrReloc(gpPtr, m_iDataDlls[0].m_iatOffset + m_iDataOffsetIAT);
addAddrReloc(getTextSection(), gpPtr, entryPlabelOffset+8, m_iDataSectionIAT);
}
else
{
_ASSERTE(!"Unknown target machine");
}
// Now set our IAT entry since we're using the IAT
setDirectoryEntry(*m_iDataSectionIAT, IMAGE_DIRECTORY_ENTRY_IAT, iDataSizeIAT, m_iDataOffsetIAT);
return S_OK;
} // HRESULT CeeFileGenWriter::emitExeMain()
#ifndef TARGET_UNIX
// This function reads a resource file and emits it into the generated PE file.
// 1. We can only link resources in obj format. Must convert from .res to .obj
// with CvtRes.exe. See https://github.com/dotnet/runtime/issues/11412.
// 2. Must touch up all COFF relocs from .rsrc$01 (resource header) to .rsrc$02
// (resource raw data)
HRESULT CeeFileGenWriter::emitResourceSection()
{
if (m_resourceFileName == NULL)
return S_OK;
const WCHAR* szResFileName = m_resourceFileName;
// read the resource file and spit it out in the .rsrc section
HANDLE hFile = INVALID_HANDLE_VALUE;
HANDLE hMap = NULL;
IMAGE_FILE_HEADER *hMod = NULL;
HRESULT hr = S_OK;
struct Param
{
HANDLE hFile;
HANDLE hMap;
IMAGE_FILE_HEADER *hMod;
const WCHAR* szResFileName;
CeeFileGenWriter *genWriter;
HRESULT hr;
} param;
param.hFile = hFile;
param.hMap = hMap;
param.hMod = hMod;
param.szResFileName = szResFileName;
param.genWriter = this;
param.hr = S_OK;
PAL_TRY(Param *, pParam, ¶m)
{
SIZE_T cbFileSize;
const BYTE *pbStartOfMappedMem;
IMAGE_SECTION_HEADER *rsrc[2] = { NULL, NULL };
S_SIZE_T cbTotalSizeOfRawData;
char *data = NULL;
SIZE_T cReloc = 0;
IMAGE_RELOCATION *pReloc = NULL;
SIZE_T cSymbol = 0;
IMAGE_SYMBOL *pSymbolTable = NULL;
// create a mapped view of the .res file
pParam->hFile = WszCreateFile(pParam->szResFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (pParam->hFile == INVALID_HANDLE_VALUE)
{
//dbprintf("Resource file %S not found\n", szResFileName);
pParam->hr = HRESULT_FROM_WIN32(ERROR_RESOURCE_DATA_NOT_FOUND);
goto lDone;
}
// Grab the file size for verification checks.
{
DWORD dwFileSizeHigh;
DWORD dwFileSize = SafeGetFileSize(pParam->hFile, &dwFileSizeHigh);
if (dwFileSize == (DWORD)(-1))
{
pParam->hr = HRESULT_FROM_GetLastError();
goto lDone;
}
// Since we intend to memory map this file, the size of the file can not need 64 bits to represent!
if (dwFileSizeHigh != 0)
{
pParam->hr = HRESULT_FROM_WIN32(ERROR_RESOURCE_DATA_NOT_FOUND);
goto lDone;
}
cbFileSize = static_cast<SIZE_T>(dwFileSize);
}
pParam->hMap = WszCreateFileMapping(pParam->hFile, 0, PAGE_READONLY, 0, 0, NULL);
if (pParam->hMap == NULL)
{
//dbprintf("Invalid .res file: %S\n", szResFileName);
pParam->hr = HRESULT_FROM_GetLastError();
goto lDone;
}
pbStartOfMappedMem = reinterpret_cast<const BYTE *>(MapViewOfFile(pParam->hMap, FILE_MAP_READ, 0, 0, 0));
// test failure conditions
if (pbStartOfMappedMem == NULL)
{
//dbprintf("Invalid .res file: %S:Can't get header\n", szResFileName);
pParam->hr = HRESULT_FROM_GetLastError();
goto lDone;
}
// Check that the file contains an IMAGE_FILE_HEADER structure.
if (IMAGE_SIZEOF_FILE_HEADER > cbFileSize)
{
pParam->hr = HRESULT_FROM_WIN32(ERROR_RESOURCE_DATA_NOT_FOUND);
goto lDone;
}
pParam->hMod = (IMAGE_FILE_HEADER*)pbStartOfMappedMem;
if (VAL16(pParam->hMod->SizeOfOptionalHeader) != 0)
{
//dbprintf("Invalid .res file: %S:Illegal optional header\n", szResFileName);
pParam->hr = HRESULT_FROM_WIN32(ERROR_RESOURCE_DATA_NOT_FOUND); // GetLastError() = 0 since API worked.
goto lDone;
}
// Scan all section headers and grab .rsrc$01 and .rsrc$02
{
// First section is directly after header
SIZE_T cSections = static_cast<SIZE_T>(VAL16(pParam->hMod->NumberOfSections));
SIZE_T cbStartOfSections = IMAGE_SIZEOF_FILE_HEADER;
S_SIZE_T cbEndOfSections(S_SIZE_T(cbStartOfSections) +
(S_SIZE_T(cSections) * S_SIZE_T(IMAGE_SIZEOF_SECTION_HEADER)));
// Check that all sections are within the bounds of the mapped file.
if (cbEndOfSections.IsOverflow() ||
cbEndOfSections.Value() > cbFileSize)
{
pParam->hr = HRESULT_FROM_WIN32(ERROR_RESOURCE_DATA_NOT_FOUND);
goto lDone;
}
{
IMAGE_SECTION_HEADER *pSection =
(IMAGE_SECTION_HEADER *)(pbStartOfMappedMem + cbStartOfSections);
IMAGE_SECTION_HEADER *pSectionEnd = pSection + cSections;
for (; pSection < pSectionEnd; pSection++)
{
if (strcmp(".rsrc$01", (char *)pSection->Name) == 0)
{
rsrc[0] = pSection;
}
else if (strcmp(".rsrc$02", (char *)pSection->Name) == 0)
{
rsrc[1] = pSection;
}
}
}
}
// If we don't have both resources, fail.
if (!rsrc[0] || !rsrc[1])
{
//dbprintf("Invalid .res file: %S: Missing sections .rsrc$01 or .rsrc$02\n", szResFileName);
pParam->hr = HRESULT_FROM_WIN32(ERROR_RESOURCE_DATA_NOT_FOUND);
goto lDone;
}
// Verify the resource data starts and sizes
{
cbTotalSizeOfRawData = S_SIZE_T(0);
for (int i = 0; i < 2; i++)
{
S_SIZE_T cbStartOfResourceData(static_cast<SIZE_T>(VAL32(rsrc[i]->PointerToRawData)));
S_SIZE_T cbSizeOfResourceData(static_cast<SIZE_T>(VAL32(rsrc[i]->SizeOfRawData)));
S_SIZE_T cbEndOfResourceData(cbStartOfResourceData + cbSizeOfResourceData);
if (cbEndOfResourceData.IsOverflow() ||
cbEndOfResourceData.Value() > cbFileSize)
{
pParam->hr = HRESULT_FROM_WIN32(ERROR_RESOURCE_DATA_NOT_FOUND);
goto lDone;
}
cbTotalSizeOfRawData += cbSizeOfResourceData;
}
// Check that the total raw data doesn't overflow.
if (cbTotalSizeOfRawData.IsOverflow() ||
cbTotalSizeOfRawData.Value() > cbFileSize)
{
pParam->hr = HRESULT_FROM_WIN32(ERROR_RESOURCE_DATA_NOT_FOUND);
goto lDone;
}
}
PESection *rsrcSection;
pParam->hr = pParam->genWriter->getPEWriter().getSectionCreate(".rsrc", sdReadOnly, &rsrcSection);
if (FAILED(pParam->hr)) goto lDone;
rsrcSection->directoryEntry(IMAGE_DIRECTORY_ENTRY_RESOURCE);
data = rsrcSection->getBlock(static_cast<unsigned>(cbTotalSizeOfRawData.Value()), 8);
if(data == NULL)
{
pParam->hr = E_OUTOFMEMORY;
goto lDone;
}
// Copy resource header
memcpy(data, (char *)pParam->hMod + VAL32(rsrc[0]->PointerToRawData), VAL32(rsrc[0]->SizeOfRawData));
// Map all the relocs in .rsrc$01 using the reloc and symbol tables in the COFF object.,
cReloc = 0; // Total number of relocs
pReloc = NULL; // Reloc table start
cSymbol = 0; // Total number of symbols
pSymbolTable = NULL; // Symbol table start
{
// Check that the relocations and symbols lie within the resource
cReloc = VAL16(rsrc[0]->NumberOfRelocations);
SIZE_T cbStartOfRelocations = static_cast<SIZE_T>(VAL32(rsrc[0]->PointerToRelocations));
S_SIZE_T cbEndOfRelocations(S_SIZE_T(cbStartOfRelocations) +
(S_SIZE_T(cReloc) * S_SIZE_T(sizeof(IMAGE_RELOCATION))));
// Verify the number of symbols fit into the resource.
cSymbol = static_cast<SIZE_T>(VAL32(pParam->hMod->NumberOfSymbols));
SIZE_T cbStartOfSymbolTable = static_cast<SIZE_T>(VAL32(pParam->hMod->PointerToSymbolTable));
S_SIZE_T cbEndOfSymbolTable(S_SIZE_T(cbStartOfSymbolTable) +
(S_SIZE_T(cSymbol) * S_SIZE_T(IMAGE_SIZEOF_SYMBOL)));
if (cbEndOfRelocations.IsOverflow() ||
cbEndOfRelocations.Value() > cbFileSize ||
cbEndOfSymbolTable.IsOverflow() ||
cbEndOfSymbolTable.Value() > cbFileSize)
{
pParam->hr = HRESULT_FROM_WIN32(ERROR_RESOURCE_DATA_NOT_FOUND);
goto lDone;
}
pReloc = (IMAGE_RELOCATION *)(pbStartOfMappedMem + cbStartOfRelocations);
pSymbolTable = (IMAGE_SYMBOL *)(pbStartOfMappedMem + cbStartOfSymbolTable);
}
_ASSERTE(pReloc != NULL && pSymbolTable != NULL);
for(SIZE_T iReloc = 0; iReloc < cReloc; iReloc++, pReloc++)
{
// Ensure this is a valid reloc
{
S_SIZE_T cbRelocEnd = S_SIZE_T(VAL32(pReloc->VirtualAddress)) + S_SIZE_T(sizeof(DWORD));
if (cbRelocEnd.IsOverflow() ||
cbRelocEnd.Value() > static_cast<SIZE_T>(VAL32(rsrc[0]->SizeOfRawData)))
{
pParam->hr = HRESULT_FROM_WIN32(ERROR_RESOURCE_DATA_NOT_FOUND);
goto lDone;
}
}
// index into symbol table, provides address into $02
DWORD iSymbol = VAL32(pReloc->SymbolTableIndex);
// Make sure the index is in range
if (iSymbol >= cSymbol)
{
pParam->hr = HRESULT_FROM_WIN32(ERROR_RESOURCE_DATA_NOT_FOUND);
goto lDone;
}
IMAGE_SYMBOL* pSymbolEntry = GetSymbolEntry(pSymbolTable, iSymbol);
// Ensure the symbol entry is valid for a resource.
if ((pSymbolEntry->StorageClass != IMAGE_SYM_CLASS_STATIC) ||
(VAL16(pSymbolEntry->Type) != IMAGE_SYM_TYPE_NULL) ||
(VAL16(pSymbolEntry->SectionNumber) != 3)) // 3rd section is .rsrc$02
{
//dbprintf("Invalid .res file: %S:Illegal symbol entry\n", szResFileName);
pParam->hr = HRESULT_FROM_WIN32(ERROR_RESOURCE_DATA_NOT_FOUND);
goto lDone;
}
// Ensure that RVA is valid address (inside rsrc[1])
if (VAL32(pSymbolEntry->Value) >= VAL32(rsrc[1]->SizeOfRawData))
{
//dbprintf("Invalid .res file: %S:Illegal rva into .rsrc$02\n", szResFileName);
pParam->hr = HRESULT_FROM_WIN32(ERROR_RESOURCE_DATA_NOT_FOUND);
goto lDone;
}
DWORD dwOffsetInRsrc2 = VAL32(pSymbolEntry->Value) + VAL32(rsrc[0]->SizeOfRawData);
// Create reloc
*(DWORD*)(data + VAL32(pReloc->VirtualAddress)) = VAL32(dwOffsetInRsrc2);
rsrcSection->addSectReloc(pReloc->VirtualAddress, rsrcSection, srRelocAbsolute);
}
// Copy $02 (resource raw) data
memcpy(data+VAL32(rsrc[0]->SizeOfRawData),
(char *)pParam->hMod + VAL32(rsrc[1]->PointerToRawData),
VAL32(rsrc[1]->SizeOfRawData));
lDone: ;
}
PAL_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
{
//dbprintf("Exception occurred manipulating .res file %S\n", szResFileName);
param.hr = HRESULT_FROM_WIN32(ERROR_RESOURCE_DATA_NOT_FOUND);
}
PAL_ENDTRY
hMod = param.hMod;
hFile = param.hFile;
szResFileName = param.szResFileName;
hr = param.hr;
if (hMod != NULL)
UnmapViewOfFile(hMod);
if (hMap != NULL)
CloseHandle(hMap);
if (hFile != INVALID_HANDLE_VALUE)
CloseHandle(hFile);
return hr;
} // HRESULT CeeFileGenWriter::emitResourceSection()
#endif // !TARGET_UNIX
HRESULT CeeFileGenWriter::setManifestEntry(ULONG size, ULONG offset)
{
if (offset)
m_dwManifestRVA = offset;
else {
CeeSection TextSection = getTextSection();
getMethodRVA(TextSection.dataLen() - size, &m_dwManifestRVA);
}
m_dwManifestSize = size;
return S_OK;
} // HRESULT CeeFileGenWriter::setManifestEntry()
HRESULT CeeFileGenWriter::setStrongNameEntry(ULONG size, ULONG offset)
{
m_dwStrongNameRVA = offset;
m_dwStrongNameSize = size;
return S_OK;
} // HRESULT CeeFileGenWriter::setStrongNameEntry()
HRESULT CeeFileGenWriter::setVTableEntry64(ULONG size, void* ptr)
{
if (ptr && size)
{
void * pv;
CeeSection TextSection = getTextSection();
// make it DWORD-aligned
ULONG L = TextSection.dataLen();
if((L &= ((ULONG)sizeof(DWORD)-1)))
{
L = (ULONG)sizeof(DWORD) - L;
if((pv = TextSection.getBlock(L)))
memset(pv,0,L);
else
return E_OUTOFMEMORY;
}
getMethodRVA(TextSection.dataLen(), &m_dwVTableRVA);
if((pv = TextSection.getBlock(size)))
{
memcpy(pv,ptr,size);
}
else
return E_OUTOFMEMORY;
m_dwVTableSize = size;
}
return S_OK;
} // HRESULT CeeFileGenWriter::setVTableEntry()
HRESULT CeeFileGenWriter::setVTableEntry(ULONG size, ULONG offset)
{
return setVTableEntry64(size,(void*)(ULONG_PTR)offset);
} // HRESULT CeeFileGenWriter::setVTableEntry()
HRESULT CeeFileGenWriter::computeSectionOffset(CeeSection §ion, _In_ char *ptr,
unsigned *offset)
{
*offset = section.computeOffset(ptr);
return S_OK;
} // HRESULT CeeFileGenWriter::computeSectionOffset()
HRESULT CeeFileGenWriter::computeOffset(_In_ char *ptr,
CeeSection **pSection, unsigned *offset)
{
TESTANDRETURNPOINTER(pSection);
CeeSection **s = m_sections;
CeeSection **sEnd = s + m_numSections;
while (s < sEnd)
{
if ((*s)->containsPointer(ptr))
{
*pSection = *s;
*offset = (*s)->computeOffset(ptr);
return S_OK;
}
s++;
}
return E_FAIL;
} // HRESULT CeeFileGenWriter::computeOffset()
HRESULT CeeFileGenWriter::getCorHeader(IMAGE_COR20_HEADER **ppHeader)
{
*ppHeader = m_corHeader;
return S_OK;
} // HRESULT CeeFileGenWriter::getCorHeader()
| 36.744745
| 147
| 0.616541
|
berkansasmaz
|
b80c8bd5dca485d9744f1e7de8264d7e87f3987a
| 13,797
|
cpp
|
C++
|
test/core/crypto/crypto_store/crypto_store_test.cpp
|
Harrm/kagome
|
22932bbbbf2f09712ca81b9e6256492f84cf2a46
|
[
"Apache-2.0"
] | null | null | null |
test/core/crypto/crypto_store/crypto_store_test.cpp
|
Harrm/kagome
|
22932bbbbf2f09712ca81b9e6256492f84cf2a46
|
[
"Apache-2.0"
] | null | null | null |
test/core/crypto/crypto_store/crypto_store_test.cpp
|
Harrm/kagome
|
22932bbbbf2f09712ca81b9e6256492f84cf2a46
|
[
"Apache-2.0"
] | null | null | null |
/**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#include "crypto/crypto_store/crypto_store_impl.hpp"
#include <gmock/gmock.h>
#include "crypto/bip39/impl/bip39_provider_impl.hpp"
#include "crypto/ed25519/ed25519_provider_impl.hpp"
#include "crypto/pbkdf2/impl/pbkdf2_provider_impl.hpp"
#include "crypto/random_generator/boost_generator.hpp"
#include "crypto/sr25519/sr25519_provider_impl.hpp"
#include "testutil/outcome.hpp"
#include "testutil/storage/base_fs_test.hpp"
using kagome::common::Blob;
using kagome::common::Buffer;
using kagome::crypto::Bip39Provider;
using kagome::crypto::Bip39ProviderImpl;
using kagome::crypto::BoostRandomGenerator;
using kagome::crypto::CryptoStore;
using kagome::crypto::CryptoStoreError;
using kagome::crypto::CryptoStoreImpl;
using kagome::crypto::Ed25519Keypair;
using kagome::crypto::Ed25519PrivateKey;
using kagome::crypto::Ed25519Provider;
using kagome::crypto::Ed25519ProviderImpl;
using kagome::crypto::Ed25519PublicKey;
using kagome::crypto::Ed25519Suite;
using kagome::crypto::KeyTypeId;
using kagome::crypto::KnownKeyTypeId;
using kagome::crypto::Pbkdf2Provider;
using kagome::crypto::Pbkdf2ProviderImpl;
using kagome::crypto::Sr25519Keypair;
using kagome::crypto::Sr25519Provider;
using kagome::crypto::Sr25519ProviderImpl;
using kagome::crypto::Sr25519PublicKey;
using kagome::crypto::Sr25519SecretKey;
using kagome::crypto::Sr25519Suite;
static CryptoStoreImpl::Path crypto_store_test_directory =
boost::filesystem::temp_directory_path() / "crypto_store_test";
struct CryptoStoreTest : public test::BaseFS_Test {
CryptoStoreTest() : BaseFS_Test(crypto_store_test_directory) {}
void SetUp() override {
auto csprng = std::make_shared<BoostRandomGenerator>();
auto ed25519_provider = std::make_shared<Ed25519ProviderImpl>(csprng);
auto sr25519_provider = std::make_shared<Sr25519ProviderImpl>(csprng);
auto pbkdf2_provider = std::make_shared<Pbkdf2ProviderImpl>();
bip39_provider =
std::make_shared<Bip39ProviderImpl>(std::move(pbkdf2_provider));
crypto_store = std::make_shared<CryptoStoreImpl>(
std::make_shared<Ed25519Suite>(std::move(ed25519_provider)),
std::make_shared<Sr25519Suite>(std::move(sr25519_provider)),
bip39_provider,
kagome::crypto::KeyFileStorage::createAt(crypto_store_test_directory)
.value());
mnemonic =
"ozone drill grab fiber curtain grace pudding thank cruise elder eight "
"picnic";
EXPECT_OUTCOME_TRUE(e, Buffer::fromHex("9e885d952ad362caeb4efe34a8e91bd2"));
entropy = std::move(e);
EXPECT_OUTCOME_TRUE(s,
Blob<32>::fromHex("a4681403ba5b6a3f3bd0b0604ce439a78244"
"c7d43b127ec35cd8325602dd47fd"));
seed = s;
key_type = KnownKeyTypeId::KEY_TYPE_BABE;
EXPECT_OUTCOME_TRUE(
ed_publ,
Ed25519PublicKey::fromHex("3e765f2bde3daadd443097b3145abf1f71f99f0aa946"
"960990fe02aa26b7fc72"));
EXPECT_OUTCOME_TRUE(
ed_priv,
Ed25519PrivateKey::fromHex("a4681403ba5b6a3f3bd0b0604ce439a78244c7d43b1"
"27ec35cd8325602dd47fd"));
ed_pair = {ed_priv, ed_publ};
EXPECT_OUTCOME_TRUE(
sr_publ,
Sr25519PublicKey::fromHex("56a03c8afc0e7a3a8b1d53bcc875ba5b6364754f9045"
"16009b57ef3adf96f61f"));
EXPECT_OUTCOME_TRUE(
sr_secr,
Sr25519SecretKey::fromHex(
"ec96cb0816b67b045baae21841952a61ecb0612a109293e10c5453b950659c0a8b"
"35b6d6196f33169334e36a05d624d9996d07243f9f71e638e3bc29a5330ec9"));
sr_pair = {sr_secr, sr_publ};
}
bool isStoredOnDisk(KeyTypeId kt, const Blob<32> &public_key) {
auto file_name = kagome::crypto::decodeKeyTypeId(kt) + public_key.toHex();
auto file_path = crypto_store_test_directory / file_name;
return boost::filesystem::exists(file_path);
}
std::shared_ptr<Bip39Provider> bip39_provider;
std::shared_ptr<CryptoStoreImpl> crypto_store;
std::string mnemonic;
Buffer entropy;
Blob<32> seed;
KeyTypeId key_type;
Ed25519Keypair ed_pair;
Sr25519Keypair sr_pair;
};
/**
* @given cryptostore instance, type, mnemonic and predefined key pair
* @when generateEd25519Keypair is called
* @then method call succeeds and result matches predefined key pair
* @and generated key pair is stored in memory
*/
TEST_F(CryptoStoreTest, generateEd25519KeypairMnemonicSuccess) {
EXPECT_OUTCOME_FALSE(
err, crypto_store->findEd25519Keypair(key_type, ed_pair.public_key));
ASSERT_EQ(err, CryptoStoreError::KEY_NOT_FOUND);
EXPECT_OUTCOME_TRUE(pair,
crypto_store->generateEd25519Keypair(key_type, mnemonic));
ASSERT_EQ(pair, ed_pair);
// check that created pair is now contained in memory
EXPECT_OUTCOME_TRUE(
found, crypto_store->findEd25519Keypair(key_type, pair.public_key));
ASSERT_EQ(found, pair);
// not stored on disk
ASSERT_FALSE(isStoredOnDisk(key_type, pair.public_key));
}
/**
* @given cryptostore instance, type, mnemonic and predefined key pair
* @when generateSr25519Keypair is called
* @then method call succeeds and result matches predefined key pair
* @and generated key pair is stored in memory
*/
TEST_F(CryptoStoreTest, generateSr25519KeypairMnemonicSuccess) {
EXPECT_OUTCOME_TRUE(pair,
crypto_store->generateSr25519Keypair(key_type, mnemonic));
ASSERT_EQ(pair, sr_pair);
// check that created pair is now contained in memory
EXPECT_OUTCOME_TRUE(
found, crypto_store->findSr25519Keypair(key_type, pair.public_key));
ASSERT_EQ(found, pair);
// not stored on disk
ASSERT_FALSE(isStoredOnDisk(key_type, pair.public_key));
}
/**
* @given cryptostore instance, type, seed and predefined key pair
* @when generateEd25519Keypair is called
* @then method call succeeds and result matches predefined key pair
* @and generated key pair is stored in memory
*/
TEST_F(CryptoStoreTest, generateEd25519KeypairSeedSuccess) {
EXPECT_OUTCOME_FALSE(
err, crypto_store->findEd25519Keypair(key_type, ed_pair.public_key));
ASSERT_EQ(err, CryptoStoreError::KEY_NOT_FOUND);
auto pair = crypto_store->generateEd25519Keypair(key_type, seed);
ASSERT_EQ(pair, ed_pair);
// check that created pair is now contained in memory
EXPECT_OUTCOME_TRUE(
found, crypto_store->findEd25519Keypair(key_type, pair.public_key));
ASSERT_EQ(found, pair);
// not stored on disk
ASSERT_FALSE(isStoredOnDisk(key_type, pair.public_key));
}
/**
* @given cryptostore instance, type, seed and predefined key pair
* @when generateSr25519Keypair is called
* @then method call succeeds and result matches predefined key pair
* @and key generated pair is stored in memory
*/
TEST_F(CryptoStoreTest, generateSr25519KeypairSeedSuccess) {
EXPECT_OUTCOME_FALSE(
err, crypto_store->findSr25519Keypair(key_type, sr_pair.public_key));
ASSERT_EQ(err, CryptoStoreError::KEY_NOT_FOUND);
auto &&pair = crypto_store->generateSr25519Keypair(key_type, seed);
ASSERT_EQ(pair, sr_pair);
// check that created pair is now contained in memory
EXPECT_OUTCOME_TRUE(
found, crypto_store->findSr25519Keypair(key_type, pair.public_key));
ASSERT_EQ(found, pair);
// not stored on disk
ASSERT_FALSE(isStoredOnDisk(key_type, pair.public_key));
}
/**
* @given cryptostore instance, and key type
* @when call generateEd25519KeypairOnDisk(key_type)
* @then a new ed25519 key pair is generated and stored on disk
*/
TEST_F(CryptoStoreTest, generateEd25519KeypairStoreSuccess) {
EXPECT_OUTCOME_TRUE(pair,
crypto_store->generateEd25519KeypairOnDisk(key_type));
// check that created pair is contained in the storage on disk
EXPECT_OUTCOME_TRUE(
found, crypto_store->findEd25519Keypair(key_type, pair.public_key));
ASSERT_EQ(found, pair);
// stored on disk
ASSERT_TRUE(isStoredOnDisk(key_type, pair.public_key));
}
/**
* @given cryptostore instance, and key type
* @when call generateSr25519KeypairOnDisk(key_type)
* @then a new ed25519 key pair is generated and stored on disk
*/
TEST_F(CryptoStoreTest, generateSr25519KeypairStoreSuccess) {
EXPECT_OUTCOME_TRUE(pair,
crypto_store->generateSr25519KeypairOnDisk(key_type));
// check that created pair is contained in the storage on disk
EXPECT_OUTCOME_TRUE(
found, crypto_store->findSr25519Keypair(key_type, pair.public_key));
ASSERT_EQ(found, pair);
// stored on disk
ASSERT_TRUE(isStoredOnDisk(key_type, pair.public_key));
}
/**
* @given cryptostore instance, and key type
* @when call getEd25519PublicKeys
* @then collection of all ed25519 public keys of provided type is returned
*/
TEST_F(CryptoStoreTest, getEd25519PublicKeysSuccess) {
EXPECT_OUTCOME_TRUE(pair1,
crypto_store->generateEd25519KeypairOnDisk(
KnownKeyTypeId::KEY_TYPE_BABE));
EXPECT_OUTCOME_TRUE(pair2,
crypto_store->generateEd25519KeypairOnDisk(
KnownKeyTypeId::KEY_TYPE_BABE));
EXPECT_OUTCOME_SUCCESS(pair3,
crypto_store->generateEd25519KeypairOnDisk(
KnownKeyTypeId::KEY_TYPE_LP2P));
EXPECT_OUTCOME_SUCCESS(pair4,
crypto_store->generateSr25519KeypairOnDisk(
KnownKeyTypeId::KEY_TYPE_BABE));
EXPECT_OUTCOME_SUCCESS(pair5,
crypto_store->generateSr25519KeypairOnDisk(
KnownKeyTypeId::KEY_TYPE_ACCO));
std::set<Ed25519PublicKey> ed_babe_keys_set = {pair1.public_key,
pair2.public_key};
std::vector<Ed25519PublicKey> ed_babe_keys(ed_babe_keys_set.begin(),
ed_babe_keys_set.end());
auto keys =
crypto_store->getEd25519PublicKeys(KnownKeyTypeId::KEY_TYPE_BABE).value();
ASSERT_THAT(keys, testing::UnorderedElementsAreArray(ed_babe_keys));
}
/**
* @given cryptostore instance, and key type
* @when call getSr25519PublicKeys
* @then collection of all sr25519 public keys of provided type is returned
*/
TEST_F(CryptoStoreTest, getSr25519PublicKeysSuccess) {
EXPECT_OUTCOME_TRUE(pair1,
crypto_store->generateSr25519KeypairOnDisk(
KnownKeyTypeId::KEY_TYPE_BABE));
EXPECT_OUTCOME_TRUE(pair2,
crypto_store->generateSr25519KeypairOnDisk(
KnownKeyTypeId::KEY_TYPE_BABE));
EXPECT_OUTCOME_SUCCESS(pair3,
crypto_store->generateSr25519KeypairOnDisk(
KnownKeyTypeId::KEY_TYPE_LP2P));
EXPECT_OUTCOME_SUCCESS(pair4,
crypto_store->generateEd25519KeypairOnDisk(
KnownKeyTypeId::KEY_TYPE_BABE));
EXPECT_OUTCOME_SUCCESS(pair5,
crypto_store->generateEd25519KeypairOnDisk(
KnownKeyTypeId::KEY_TYPE_ACCO));
std::set<Sr25519PublicKey> sr_babe_keys_set = {pair1.public_key,
pair2.public_key};
std::vector<Sr25519PublicKey> sr_babe_keys(sr_babe_keys_set.begin(),
sr_babe_keys_set.end());
auto keys =
crypto_store->getSr25519PublicKeys(KnownKeyTypeId::KEY_TYPE_BABE).value();
ASSERT_THAT(keys, testing::UnorderedElementsAreArray(sr_babe_keys));
}
/**
* @given an empty crypto storage
* @when having inserted keys into it
* @then session keys are initialized with inserted keys of the corresponding
* types
*/
TEST_F(CryptoStoreTest, SessionKeys) {
// GIVEN
ASSERT_FALSE(crypto_store->getGrandpaKeypair());
ASSERT_FALSE(crypto_store->getBabeKeypair());
ASSERT_FALSE(crypto_store->getLibp2pKeypair());
// WHEN
EXPECT_OUTCOME_TRUE(
pair1,
crypto_store->generateSr25519KeypairOnDisk(KnownKeyTypeId::KEY_TYPE_BABE))
EXPECT_OUTCOME_TRUE(
pair2,
crypto_store->generateEd25519KeypairOnDisk(KnownKeyTypeId::KEY_TYPE_GRAN))
EXPECT_OUTCOME_TRUE(
pair3,
crypto_store->generateEd25519KeypairOnDisk(KnownKeyTypeId::KEY_TYPE_LP2P))
// THEN
ASSERT_TRUE(crypto_store->getGrandpaKeypair());
ASSERT_EQ(crypto_store->getGrandpaKeypair().value(), pair2);
ASSERT_TRUE(crypto_store->getBabeKeypair());
ASSERT_EQ(crypto_store->getBabeKeypair().value(), pair1);
ASSERT_TRUE(crypto_store->getLibp2pKeypair());
ASSERT_THAT(pair3.secret_key,
testing::ElementsAreArray(
crypto_store->getLibp2pKeypair().value().privateKey.data));
}
/**
* Currently incompatible with subkey because subkey doesn't append key type to
* filename
*/
TEST(CryptoStoreCompatibilityTest, DISABLED_SubkeyCompat) {
auto csprng = std::make_shared<BoostRandomGenerator>();
auto ed25519_provider = std::make_shared<Ed25519ProviderImpl>(csprng);
auto sr25519_provider = std::make_shared<Sr25519ProviderImpl>(csprng);
auto pbkdf2_provider = std::make_shared<Pbkdf2ProviderImpl>();
auto bip39_provider =
std::make_shared<Bip39ProviderImpl>(std::move(pbkdf2_provider));
auto keystore_path = boost::filesystem::path(__FILE__).parent_path()
/ "subkey_keys" / "keystore";
auto crypto_store = std::make_shared<CryptoStoreImpl>(
std::make_shared<Ed25519Suite>(std::move(ed25519_provider)),
std::make_shared<Sr25519Suite>(std::move(sr25519_provider)),
bip39_provider,
kagome::crypto::KeyFileStorage::createAt(keystore_path).value());
EXPECT_OUTCOME_TRUE(
keys, crypto_store->getEd25519PublicKeys(KnownKeyTypeId::KEY_TYPE_BABE));
ASSERT_EQ(keys.size(), 1);
}
| 38.431755
| 80
| 0.718272
|
Harrm
|
b80d3c82f849ab216721d0f6d7f6841f90a1f9a2
| 1,162
|
hpp
|
C++
|
dylibwrap/DylibWrap.hpp
|
churuxu/codesnippets
|
9d01c53a5bd7be29168e3c8bfb27ebacc5164f03
|
[
"MIT"
] | 4
|
2018-11-05T03:21:02.000Z
|
2021-09-25T15:33:52.000Z
|
dylibwrap/DylibWrap.hpp
|
churuxu/codesnippets
|
9d01c53a5bd7be29168e3c8bfb27ebacc5164f03
|
[
"MIT"
] | null | null | null |
dylibwrap/DylibWrap.hpp
|
churuxu/codesnippets
|
9d01c53a5bd7be29168e3c8bfb27ebacc5164f03
|
[
"MIT"
] | 2
|
2021-01-28T08:14:07.000Z
|
2021-09-25T15:33:54.000Z
|
#pragma once
/**
用于动态加载dll/so的包装类
用法示例:
class User32DLL {
public:
DYLIB_LOAD(User32DLL, "user32");
DYLIB_IMPORT(MessageBoxA);
DYLIB_IMPORT(MessageBoxW);
};
User32DLL user32;
user32.MessageBoxA(NULL, "Hello World", "test", MB_OK);
*/
#include <stdexcept>
#include <string>
#ifdef _WIN32
#include <windows.h>
static void _DylibLoad(const char* name, void** lib, int size) {
HMODULE mod = LoadLibraryA(name);
if (!mod) {
std::string msg = "can not load library ";
msg + name;
throw std::runtime_error(msg);
}
for (int i = 0; i < size; i += 2) {
const char* name = (const char*)(lib[i]);
void* func = GetProcAddress(mod, name);
if (!func) {
std::string msg = "no function names ";
msg + name;
throw std::runtime_error(msg);
}
else {
lib[i + 1] = func;
}
}
}
#else
#error "current not support"
#endif
#define _DYLIB_NAME_CAT(a,b) a##b
/** 声明一个导入类的构造函数 */
#define DYLIB_LOAD(cls, name) \
cls() {\
_DylibLoad(name, (void**)this, sizeof(cls) / sizeof(void*));\
}
/** 声明一个导入函数 */
#define DYLIB_IMPORT(func) \
const char* _DYLIB_NAME_CAT(name_of_,func) = #func;\
decltype(::func)* func = NULL;
| 15.090909
| 65
| 0.636833
|
churuxu
|
b81874f403f5aa58b31dd0a8fe27df2f303f13ff
| 1,770
|
hpp
|
C++
|
SDK/ARKSurvivalEvolved_ProjMekSiegeCannon_classes.hpp
|
2bite/ARK-SDK
|
c38ca9925309516b2093ad8c3a70ed9489e1d573
|
[
"MIT"
] | 10
|
2020-02-17T19:08:46.000Z
|
2021-07-31T11:07:19.000Z
|
SDK/ARKSurvivalEvolved_ProjMekSiegeCannon_classes.hpp
|
2bite/ARK-SDK
|
c38ca9925309516b2093ad8c3a70ed9489e1d573
|
[
"MIT"
] | 9
|
2020-02-17T18:15:41.000Z
|
2021-06-06T19:17:34.000Z
|
SDK/ARKSurvivalEvolved_ProjMekSiegeCannon_classes.hpp
|
2bite/ARK-SDK
|
c38ca9925309516b2093ad8c3a70ed9489e1d573
|
[
"MIT"
] | 3
|
2020-07-22T17:42:07.000Z
|
2021-06-19T17:16:13.000Z
|
#pragma once
// ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_ProjMekSiegeCannon_structs.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass ProjMekSiegeCannon.ProjMekSiegeCannon_C
// 0x0090 (0x06F0 - 0x0660)
class AProjMekSiegeCannon_C : public AShooterProjectile
{
public:
float MaxStructureImpactDistance; // 0x0660(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
TEnumAsByte<ENetworkModeResult> CallFunc_CanRunCosmeticEvents_OutNetworkMode; // 0x0664(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool K2Node_SwitchEnum_CmpSuccess; // 0x0665(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData00[0x2]; // 0x0666(0x0002) MISSED OFFSET
struct FHitResult K2Node_Event_Result; // 0x0668(0x0088) (OutParm, Transient, DuplicateTransient, ReferenceParm)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass ProjMekSiegeCannon.ProjMekSiegeCannon_C");
return ptr;
}
void UserConstructionScript();
void OnExplode(struct FHitResult* Result);
void ExecuteUbergraph_ProjMekSiegeCannon(int EntryPoint);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 38.478261
| 208
| 0.590395
|
2bite
|
b81adeaf4697f45632c66e56d383c6949584a165
| 4,737
|
hh
|
C++
|
dam/source/cc/dam/DataFragmentUnpack.hh
|
DUNE/dunepdsprce
|
2a4ca9b5ed08e1ba6ff7972681d8c0076d314d30
|
[
"BSD-3-Clause-LBNL"
] | null | null | null |
dam/source/cc/dam/DataFragmentUnpack.hh
|
DUNE/dunepdsprce
|
2a4ca9b5ed08e1ba6ff7972681d8c0076d314d30
|
[
"BSD-3-Clause-LBNL"
] | null | null | null |
dam/source/cc/dam/DataFragmentUnpack.hh
|
DUNE/dunepdsprce
|
2a4ca9b5ed08e1ba6ff7972681d8c0076d314d30
|
[
"BSD-3-Clause-LBNL"
] | null | null | null |
// -*-Mode: C++;-*-
#ifndef DATAFRAGMENTUNPACK_HH
#define DATAFRAGMENTUNPACK_HH
/* ---------------------------------------------------------------------- *//*!
*
* @file DataFragment.hh
* @brief Access methods for the RCE data fragments
* decoding a binary test file.
* @verbatim
* Copyright 2017
* by
*
* The Board of Trustees of the
* Leland Stanford Junior University.
* All rights reserved.
*
* @endverbatim
*
\* ---------------------------------------------------------------------- */
/* ---------------------------------------------------------------------- *\
HISTORY
-------
DATE WHO WHAT
---------- --- ---------------------------------------------------------
2018.08.30 jjr Added isTpcEmpty method
2018.03.23 jjr Added isTpcDamaged method
2017.08.29 jjr Created
\* ---------------------------------------------------------------------- */
#include "dam/access/DataFragment.hh"
#include <cinttypes>
/* ====================================================================== */
/* FORWARD REFERENCES */
/* ---------------------------------------------------------------------- */
namespace pdd {
namespace fragment {
class DataFragmentHeader;
class Identifier;
class Originator;
class Data;
}
class Trailer;
}
/* ====================================================================== */
/* ====================================================================== */
/* CLASS DEFINITION */
/* ---------------------------------------------------------------------- *//*!
\class DataFragmentUnpack
\brief Provides access to a Data Fragment and its records
\par
This is more of a convenience class than anything else. Its main value
is in cacheing pointer to the records contained within a Data Fragment.
Finding thes records can also be done by the caller using the static
routines contained in this class, with no need to instantiate the
class.
*/
/* ---------------------------------------------------------------------- */
class DataFragmentUnpack
{
public:
DataFragmentUnpack (uint64_t const *buf);
// ------------------------------------------------------------
// Get the length of the Data Fragment and check its subtype
// Currently only TpcNormal streams exist, but this may change
// in the future.
// ------------------------------------------------------------
uint32_t getN64 () const;
bool isTpcNormal () const;
bool isTpcDamaged () const;
bool isTpcEmpty () const;
// ------------------------------------------------------------
// Access the records within the Data Fragment
// ------------------------------------------------------------
pdd::record::DataFragmentHeader const *getHeader () const;
pdd::record::Identifier const *getIdentifier () const;
pdd::record::Originator const *getOriginator () const;
pdd::record::Data const *getData () const;
pdd::Trailer const *getTrailer () const;
static pdd::record::DataFragmentHeader
const *getHeader (uint64_t const *buf);
static pdd::record::Identifier const *getIdentifier (uint64_t const *buf);
static pdd::record::Originator const *getOriginator (uint64_t const *buf);
static pdd::record::Data const *getData (uint64_t const *buf);
static pdd::Trailer const *getTrailer (uint64_t const *buf);
// ---------------------------------------------------------
// Crude print methods, meant only to get one off the ground
// Given the size and complexity of a Data Fragment, writing
// one-size-fits-all print routines is not feasible.
// ---------------------------------------------------------
void print () const;
void printHeader () const;
void printIdentifier () const;
void printOriginator () const;
void printData () const;
void printTrailer () const;
static void print (pdd::Header0 const *header);
static void print (pdd::Trailer const *trailer);
public:
pdd::access::DataFragment m_df;
};
/* ====================================================================== */
#endif
| 35.886364
| 80
| 0.410809
|
DUNE
|
b81b14fbdab9a89d7245ebe0466bb3ca7fce1725
| 8,764
|
cpp
|
C++
|
main.cpp
|
Bango1999/cpp-tictactoe-cli
|
6add1cc62b242212b7106cf79426f674e9b654c8
|
[
"MIT"
] | null | null | null |
main.cpp
|
Bango1999/cpp-tictactoe-cli
|
6add1cc62b242212b7106cf79426f674e9b654c8
|
[
"MIT"
] | null | null | null |
main.cpp
|
Bango1999/cpp-tictactoe-cli
|
6add1cc62b242212b7106cf79426f674e9b654c8
|
[
"MIT"
] | null | null | null |
//---------------------------------------------------------------------------
// Program: tic tac toe cli
// Name: Bango
// Purpose: This will be an implementation of a tic-tac-toe game.
// This is a 2 player version of tic-tac-toe where 'X' goes first
// followed by 'O'. When it is player 1's turn, (s)he places an 'X'
// on a 3x3 grid; player 2 places an 'O' on the grid. The first
// player to get 3 characters ('X' or 'O') in a row wins. If
// the board fills up with no winner, the game ends in a tie.
//---------------------------------------------------------------------------
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
using namespace std;
// Global variables
const char BLANK = '-';
const char X = 'X';
const char O = 'O';
const char TIE = 'T';
//---------------------------------------------------------------------------
// Name: PlayX
// Parameters: game board 2d array
// Returns: void
// Purpose: Asks for a position and places an X on the grid at a position and returns true.
// Also performs error checking
//---------------------------------------------------------------------------
void PlayX(char board[3][3], string player1)
{
int row, col;
// Ask for the position to place an X.
cout << player1 << ": Enter the row followed by the column for your X (1-3), 0 to exit." << endl;
cin >> row >> col;
if (row == 0 || col == 0) {
board[0][0] = '1';
} else {
while (row < 0 || row > 3 || col < 0 || col > 3 || (row >=1 && row <=3 && col >=1 && col <=3 && board[row-1][col-1] != BLANK))
{
cout << "\nNot a valid play. \n" << player1 << ": Enter the row followed by the column for your X (1-3), 0 to exit." << endl;
cin >> row;
cin >> col;
}
// set the position on the board to X
board[row-1][col-1] = X;
}
}
//---------------------------------------------------------------------------
// Name: PlayO
// Parameters:
// Returns:
// Purpose: Similar to the PlayX function
//---------------------------------------------------------------------------
void PlayO(char board[3][3], string player2)
{
int row = 0;
int col = 0;
// Ask for the position to place an O.
cout << player2 << ": Enter the row followed by the column for your O (1-3), 0 to exit." << endl;
cin >> row >> col;
if (row == 0 || col == 0) {
board[0][0] = '2';
} else {
while (row < 0 || row > 3 || col < 0 || col > 3 || (row >=1 && row <=3 && col >=1 && col <=3 && board[row-1][col-1] != BLANK))
{
cout << "\nNot a valid play. \n" << player2 << ": Enter the row followed by the column for your O (1-3), 0 to exit." << endl;
cin >> row >> col;
}
// set the position on the board to X
board[row-1][col-1] = O;
}
}
//---------------------------------------------------------------------------
// Name: CheckWinner
// Parameters: 2d array for game board
// Returns: char
// Purpose: return 'X' if x wins, 'O' if o wins, 'T' if
// the game has ended in a tie.
//---------------------------------------------------------------------------
int CheckWinner(char board[3][3]) {
int done = 0;
int counter = 0;
//check for a full board
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
if (board[i][j] != BLANK) {
counter++;
}
}
}
//check for a winner over all possible winning combinations, check for the exit code, 0, and define the variable 'done' which will tell main what it needs to know to output the right thing.
if ((board[0][0] == X && board[0][1] == X && board[0][2] == X) || (board[1][0] == X && board[1][1] == X && board[1][2] == X) || (board[2][0] == X && board[2][1] == X && board[2][2] == X) || (board[0][0] == X && board[1][0] == X && board[2][0] == X) || (board[0][1] == X && board[1][1] == X && board[2][1] == X) || (board[0][2] == X && board[1][2] == X && board[2][2] == X) || (board[0][0] == X && board[1][1] == X && board[2][2] == X) || (board[0][2] == X && board[1][1] == X && board[2][0] == X)) {
done = 1;
} else if ((board[0][0] == O && board[0][1] == O && board[0][2] == O) || (board[1][0] == O && board[1][1] == O && board[1][2] == O) || (board[2][0] == O && board[2][1] == O && board[2][2] == O) || (board[0][0] == O && board[1][0] == O && board[2][0] == O) || (board[0][1] == O && board[1][1] == O && board[2][1] == O) || (board[0][2] == O && board[1][2] == O && board[2][2] == O) || (board[0][0] == O && board[1][1] == O && board[2][2] == O) || (board[0][2] == O && board[1][1] == O && board[2][0] == O)) {
done = 2;
} else if (board[0][0] == '1') {
done = 4;
} else if (board[0][0] == '2') {
done = 5;
} else if (counter == 9) {
done = 3;
}
return done;
}
//---------------------------------------------------------------------------
// Name: ConfirmPlayAgain
// Parameters: none
// Returns: bool
// Purpose: Once the game has ended, this function asks if the player wants to
// play again.
//---------------------------------------------------------------------------
bool ConfirmPlayAgain() {
char x;
bool again;
cout << "Would you like to play again? (y/n) ";
cin >> x;
if (x == 'y' || x == 'Y') {
again = true;
cout << "\n=======================\n\n";
} else {
again = false;
}
return again;
}
//---------------------------------------------------------------------------
// Name: PrintBoard
// Parameters: 2d array game board
// Returns: void
// Purpose: Output current tic-tac-toe game board
//---------------------------------------------------------------------------
void PrintBoard(char board[3][3]) {
for (int i = 0; i < 3; i++)
{
cout << "\n";
for (int j = 0; j < 3; j++)
{
cout << board[i][j];
}
}
}
//---------------------------------------------------------------------------
// Name: InitializeBoard
// Parameters: 2d array game board
// Returns: void
// Purpose: Sets tic-tac-toe game board to blank
//---------------------------------------------------------------------------
void InitializeBoard(char board[3][3])
{
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
board[i][j] = BLANK;
}
}
}
// Main should be used to call the functions above to complete the tic-tac-toe game.
int main ()
{
char board[3][3];
bool again = true;
char done = 0;
int counter = 0;
string player1;
string player2;
cout << " ________________________________" << endl;
cout << "| |" << endl;
cout << "| Logan B.A. Swango -- 010636621 |" << endl;
cout << "| Project 4: Tic Tac Toe |" << endl;
cout << "| 3/7/2013 |" << endl;
cout << "|________________________________|" << endl;
while (again) {
InitializeBoard(board);
cout << "Player 1, please enter your name: ";
getline(cin, player1);
while (!cin) {
cin.clear();
cout << "Invalid input Player 1, please enter your name: ";
getline(cin, player1);
}
cout << "Player 2, please enter your name: ";
getline(cin, player2);
while (!cin) {
cin.clear();
cout << "Invalid input Player 2, please enter your name: ";
getline(cin, player2);
}
while (done == 0) {
PrintBoard(board);
if (counter % 2 == 0) {
cout << "\n";
PlayX(board, player1);
} else {
cout << "\n";
PlayO(board, player2);
}
counter++;
done = CheckWinner(board);
if (done == 1) {
PrintBoard(board);
cout << "\n" << player1 << " wins!" << endl;
} else if (done == 2) {
PrintBoard(board);
cout << "\n" << player2 << " wins!" << endl;
} else if (done == 3) {
PrintBoard(board);
cout << "\nThe match has ended in a tie!" << endl;
} else if (done == 4) {
cout << "\n" << player1 << " has forefeited the match!" << endl;
} else if (done == 5) {
cout << "\n" << player2 << " has forefeited the match!" << endl;
}
}
if (done == 1 || done == 2 || done == 3 || done == 4 || done == 5) {
again = ConfirmPlayAgain();
}
if (again) {
done = 0;
counter = 0;
}
}
return 0;
}
| 30.430556
| 507
| 0.420812
|
Bango1999
|
b81e68a74e764c0c9d2c8ccab0ffa0d53c328407
| 1,967
|
cpp
|
C++
|
main.cpp
|
svenpilz/gpgpu
|
0c74790f3753ecafa10256745531de4e6240787d
|
[
"MIT"
] | 1
|
2016-04-09T00:39:04.000Z
|
2016-04-09T00:39:04.000Z
|
main.cpp
|
svenpilz/gpgpu
|
0c74790f3753ecafa10256745531de4e6240787d
|
[
"MIT"
] | null | null | null |
main.cpp
|
svenpilz/gpgpu
|
0c74790f3753ecafa10256745531de4e6240787d
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <gpgpu/Context.hpp>
#include <gpgpu/Framebuffer.hpp>
#include <gpgpu/Program.hpp>
#include <OpenImageIO/imagebufalgo.h>
using namespace std;
int main() {
/*
* Context
*/
gpgpu::Context context;
cout << context << endl;
/*
* Shader
*/
gpgpu::Program fixed_color_shader;
auto vs = gpgpu::create_shader(gpgpu::Shader::Vertex, R"(
#version 130
uniform mat4 camera;
in vec4 vertex;
void main() {
gl_Position = camera * vertex;
})"
);
auto fs = gpgpu::create_shader(gpgpu::Shader::Fragment, R"(
#version 130
out vec4 color;
void main() {
color = vec4(1.0, 0.0, 0.0, 1.0);
})"
);
fixed_color_shader.append({vs, fs});
fixed_color_shader.link();
/*
* Framebuffer
*/
gpgpu::Framebuffer fb(800, 600, true);
auto canvas = make_shared<gpgpu::Texture2D>(800, 600);
fb.set_color_attachment(canvas, 0);
/*
* Geometry
*/
float vertices[] = {
-0.5, -0.5, 0.0,
0.0, 0.5, 0.0,
0.5, -0.5, 0.0
};
auto geometry = make_shared<gpgpu::ArrayBuffer>();
geometry->data(3, 3, vertices);
unsigned int face_vertices[] = {
0, 1, 2
};
gpgpu::ElementArrayBuffer faces;
faces.data(3, 3, face_vertices);
/*
* Camera
*/
Eigen::Matrix4f camera = Eigen::Matrix4f::Identity();
/*
* Render
*/
fb.bind();
fixed_color_shader.use();
fixed_color_shader.uniform("camera", camera);
fixed_color_shader.attribute("vertex", geometry);
fixed_color_shader.render(faces);
// Or without indirection.
//fixed_color_shader.render(geometry, "vertex", GL_TRIANGLES);
auto image = canvas->image();
OpenImageIO::ImageBuf output;
OpenImageIO::ImageBufAlgo::flip(output, *image);
output.write("canvas.png");
return 0;
}
| 20.705263
| 66
| 0.571429
|
svenpilz
|
b821505ac59988b02264175486a38ad044fd3c68
| 1,192
|
cpp
|
C++
|
Extern/il2cpp/24.2/il2cpp/libil2cpp/os/c-api/Path.cpp
|
TDToolbox/btdapi
|
b8349ef33d5bc2dacc85e96ced86dc37e972e8ee
|
[
"MIT"
] | null | null | null |
Extern/il2cpp/24.2/il2cpp/libil2cpp/os/c-api/Path.cpp
|
TDToolbox/btdapi
|
b8349ef33d5bc2dacc85e96ced86dc37e972e8ee
|
[
"MIT"
] | 8
|
2020-03-10T23:11:09.000Z
|
2020-03-14T01:19:32.000Z
|
Extern/il2cpp/24.2/il2cpp/libil2cpp/os/c-api/Path.cpp
|
TDToolbox/btdapi
|
b8349ef33d5bc2dacc85e96ced86dc37e972e8ee
|
[
"MIT"
] | null | null | null |
#include "os/c-api/il2cpp-config-platforms.h"
#if !IL2CPP_DOTS_WITHOUT_DEBUGGER
#include "os/Path.h"
#include "utils/PathUtils.h"
#include "Allocator.h"
extern "C"
{
const char* UnityPalGetTempPath()
{
return Allocator::CopyToAllocatedStringBuffer(il2cpp::os::Path::GetTempPath());
}
const char* UnityPalGetExecutablePath()
{
return Allocator::CopyToAllocatedStringBuffer(il2cpp::os::Path::GetExecutablePath());
}
int32_t UnityPalIsAbsolutePath(const char* path)
{
if (path == NULL)
return 0;
std::string path_string = path;
return il2cpp::os::Path::IsAbsolute(path_string);
}
char* UnityPalBasename(const char* path)
{
if (path == NULL)
return NULL;
std::string pathString = path;
return Allocator::CopyToAllocatedStringBuffer(il2cpp::utils::PathUtils::Basename(pathString));
}
char* UnityPalDirectoryName(const char* path)
{
if (path == NULL)
return NULL;
std::string pathString = path;
return Allocator::CopyToAllocatedStringBuffer(il2cpp::utils::PathUtils::DirectoryName(pathString));
}
}
#endif
| 25.361702
| 107
| 0.647651
|
TDToolbox
|
b822c39b7bcda06ac3fd9e243df856767593e48b
| 2,715
|
cpp
|
C++
|
buffer.cpp
|
alexander-sholohov/rtlmuxer
|
cae7fb29f4daa7df0cd74279bf8168e9645a5306
|
[
"MIT"
] | 13
|
2016-05-15T08:20:43.000Z
|
2021-05-19T12:53:46.000Z
|
buffer.cpp
|
US1GHQ/rtlmuxer
|
9f317f9730169b074dcd96bfe4eecaeae22aa4de
|
[
"MIT"
] | 1
|
2018-11-21T18:19:14.000Z
|
2018-11-27T12:02:03.000Z
|
buffer.cpp
|
US1GHQ/rtlmuxer
|
9f317f9730169b074dcd96bfe4eecaeae22aa4de
|
[
"MIT"
] | 5
|
2016-10-14T19:45:56.000Z
|
2020-10-04T19:31:31.000Z
|
//
// Author: Alexander Sholohov <ra9yer@yahoo.com>
//
// License: MIT
//
#include <memory.h>
#include "buffer.h"
//---------------------------------------------------------------------------------------------------
CBuffer::CBuffer(size_t bufferSize)
{
m_buffer.resize(bufferSize + 16);
m_head = 0;
m_tail = 0;
}
//---------------------------------------------------------------------------------------------------
void CBuffer::consume(size_t len)
{
if( bytesAvailable() < len )
{
// never happen but for some reason
m_head = 0;
m_tail = 0;
return;
}
m_tail += len;
if( m_tail >= m_buffer.size() )
{
m_tail -= m_buffer.size();
}
}
//---------------------------------------------------------------------------------------------------
void CBuffer::peek(char* buf, size_t len) const
{
if( m_tail + len < m_buffer.size() )
{
memcpy(buf, &m_buffer[m_tail], len);
}
else
{
size_t len1 = m_buffer.size() - m_tail;
size_t len2 = len - len1;
memcpy(buf, &m_buffer[m_tail], len1);
memcpy(buf+len1, &m_buffer[0], len2);
}
}
//---------------------------------------------------------------------------------------------------
void CBuffer::peek(std::vector<char> & buffer, size_t len) const
{
size_t len2 = (len > buffer.size())? buffer.size() : len; // limit length for some reason
peek(&buffer[0], len2);
}
//---------------------------------------------------------------------------------------------------
void CBuffer::put(const char* buf, size_t len)
{
// ignore huge data (should never happen)
if( len >= m_buffer.size())
return;
size_t bytesAvailableBefore = bytesAvailable();
if( m_head + len < m_buffer.size() )
{
memcpy(&m_buffer[m_head], buf, len);
m_head += len;
}
else
{
size_t len1 = m_buffer.size() - m_head;
size_t len2 = len - len1;
memcpy(&m_buffer[m_head], buf, len1);
memcpy(&m_buffer[0], buf+len1, len2);
m_head = len2;
}
// check buffer overflow
if( bytesAvailableBefore + len >= m_buffer.size() - 1 )
{
m_tail = m_head + 1;
if( m_tail == m_buffer.size() )
m_tail = 0;
}
}
//---------------------------------------------------------------------------------------------------
size_t CBuffer::bytesAvailable() const
{
int s = m_head - m_tail;
if( s < 0 )
{
s += m_buffer.size();
}
return s;
}
//---------------------------------------------------------------------------------------------------
void CBuffer::reset()
{
m_head = 0;
m_tail = 0;
}
| 23.815789
| 101
| 0.402578
|
alexander-sholohov
|
b82664066fbd78861a15ddb3e3cc9346ed2cc044
| 1,203
|
cpp
|
C++
|
vpi/src/copyMemory.cpp
|
anycore/anycore-pisa-funcsim
|
122e08c7b94448ace742bc298740ec4ed1e7ec81
|
[
"BSD-3-Clause"
] | null | null | null |
vpi/src/copyMemory.cpp
|
anycore/anycore-pisa-funcsim
|
122e08c7b94448ace742bc298740ec4ed1e7ec81
|
[
"BSD-3-Clause"
] | null | null | null |
vpi/src/copyMemory.cpp
|
anycore/anycore-pisa-funcsim
|
122e08c7b94448ace742bc298740ec4ed1e7ec81
|
[
"BSD-3-Clause"
] | 3
|
2017-10-14T00:51:39.000Z
|
2021-03-25T16:37:11.000Z
|
#include <stdio.h>
#include <stdlib.h>
#include "vpi_user.h"
#include "Thread.h"
#include "veri_memory_macros.h"
#include "veri_memory.h"
#include "global_vars.h"
#include "VPI_global_vars.h"
int copyMemory_calltf(char *user_data)
{
vpiHandle systf_handle, arg_iterator, arg_handle, reg_handle;
s_vpi_value current_value;
s_vpi_value value_s;
/* obtain a handle to the system task instance. */
systf_handle = vpi_handle(vpiSysTfCall, 0);
/* obtain handle to system task argument. */
//arg_iterator = vpi_iterate(vpiArgument, systf_handle);
//reg_handle = vpi_scan(arg_iterator);
/* free iterator memory */
//vpi_free_object(arg_iterator);
VMEM[0]->copy_mem(THREAD[0]->get_mem_table());
vpi_printf("Memory table copied from functional simulator\n");
return(0);
}
// Associate C Function with a New System Function
void copyMemory_register() {
s_vpi_systf_data task_data_s;
task_data_s.type = vpiSysTask;
//task_data_s.sysfunctype = vpiSysFuncSized;
task_data_s.tfname = "$copyMemory";
task_data_s.calltf = copyMemory_calltf;
task_data_s.compiletf = 0;
//task_data_s.sizetf = readInst_sizetf;
vpi_register_systf(&task_data_s);
}
| 23.588235
| 64
| 0.733167
|
anycore
|
b83058b31b94eb3c8d13f0dbab2514f00cf7ab38
| 251
|
hpp
|
C++
|
book/cpp_templates/tmplbook/basics/boolstring.hpp
|
houruixiang/day_day_learning
|
208f70a4f0a85dd99191087835903d279452fd54
|
[
"MIT"
] | null | null | null |
book/cpp_templates/tmplbook/basics/boolstring.hpp
|
houruixiang/day_day_learning
|
208f70a4f0a85dd99191087835903d279452fd54
|
[
"MIT"
] | null | null | null |
book/cpp_templates/tmplbook/basics/boolstring.hpp
|
houruixiang/day_day_learning
|
208f70a4f0a85dd99191087835903d279452fd54
|
[
"MIT"
] | null | null | null |
class BoolString {
private:
std::string value;
public:
BoolString (std::string const& s)
: value(s) {
}
template<typename T = std::string>
T get() const { // get value (converted to T)
return value;
}
};
| 19.307692
| 57
| 0.553785
|
houruixiang
|
b8308bc07a36798b295c2d51b1bd93ffa8067edb
| 213
|
hpp
|
C++
|
game.hpp
|
comprogger/Space-Opera
|
2ff1d62689c31fcf4878d4255125e82136b94d5e
|
[
"Artistic-2.0"
] | null | null | null |
game.hpp
|
comprogger/Space-Opera
|
2ff1d62689c31fcf4878d4255125e82136b94d5e
|
[
"Artistic-2.0"
] | 1
|
2016-06-01T22:47:33.000Z
|
2016-06-01T22:47:33.000Z
|
game.hpp
|
comprogger/Space-Opera
|
2ff1d62689c31fcf4878d4255125e82136b94d5e
|
[
"Artistic-2.0"
] | null | null | null |
#ifndef GAME_HPP_INCLUDED
#define GAME_HPP_INCLUDED
#include <SFML/Graphics.hpp>
class Game{
public:
static void Start();
private:
static sf::RenderWindow app;
sf::View view1;
};
#endif // GAME_HPP_INCLUDED
| 16.384615
| 28
| 0.755869
|
comprogger
|
b831ea1e4e61bbd2a76fa445087f7ab49cd35239
| 3,495
|
cc
|
C++
|
src/proof_stat_collector.cc
|
rcurtin/drat2er
|
77fd5f6abd1ddc5b7ebfdc62d9bf1e3fdd0bfe76
|
[
"MIT"
] | 1
|
2019-12-24T18:37:34.000Z
|
2019-12-24T18:37:34.000Z
|
src/proof_stat_collector.cc
|
rcurtin/drat2er
|
77fd5f6abd1ddc5b7ebfdc62d9bf1e3fdd0bfe76
|
[
"MIT"
] | 4
|
2018-09-23T23:44:59.000Z
|
2019-01-22T17:32:10.000Z
|
src/proof_stat_collector.cc
|
rcurtin/drat2er
|
77fd5f6abd1ddc5b7ebfdc62d9bf1e3fdd0bfe76
|
[
"MIT"
] | 2
|
2018-12-13T22:39:55.000Z
|
2021-08-09T21:06:48.000Z
|
// MIT License
//
// Copyright (c) 2018 Benjamin Kiesl
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
#include "proof_stat_collector.h"
#include <string>
#include <algorithm>
#include <memory>
#include "formula.h"
#include "clause.h"
#include "rat_clause.h"
#include "rup_clause.h"
#include "deletion.h"
#include "lrat_parser.h"
using std::string;
using std::shared_ptr;
using std::max;
namespace drat2er
{
ProofStatCollector::ProofStatCollector(shared_ptr<Formula> formula) :
formula_ {formula},
max_variable_ {0},
max_instruction_ {0},
number_of_instructions_ {0},
number_of_proper_rat_additions_ {0},
number_of_rup_additions_ {0},
number_of_deletions_ {0}
{ }
int ProofStatCollector::GetMaxVariable() const
{
return max_variable_;
}
int ProofStatCollector::GetMaxInstruction() const
{
return max_instruction_;
}
int ProofStatCollector::GetNumberOfInstructions() const
{
return number_of_instructions_;
}
int ProofStatCollector::GetNumberOfProperRatAdditions() const
{
return number_of_proper_rat_additions_;
}
int ProofStatCollector::GetNumberOfRupAdditions() const
{
return number_of_rup_additions_;
}
int ProofStatCollector::GetNumberOfDeletions() const
{
return number_of_deletions_;
}
int ProofStatCollector::GetNumberOfExtensionClauses() const
{
return number_of_extension_clauses_;
}
void ProofStatCollector::ObserveDeletion(const Deletion& deletion)
{
max_instruction_ = max(max_instruction_, deletion.GetIndex());
number_of_instructions_++;
number_of_deletions_++;
}
void ProofStatCollector::ObserveProperRatAddition(const RatClause& rat)
{
UpdateInstructionAndMaxVariableStats(rat);
number_of_proper_rat_additions_++;
}
void ProofStatCollector::ObserveRupAddition(const RupClause& rup)
{
UpdateInstructionAndMaxVariableStats(rup);
number_of_rup_additions_++;
}
void ProofStatCollector::ObserveComment(const string& comment_line)
{
// do nothing
}
void ProofStatCollector::ObserveExtension(const Clause& definition_clause)
{
UpdateInstructionAndMaxVariableStats(definition_clause);
number_of_extension_clauses_++;
}
void ProofStatCollector::UpdateInstructionAndMaxVariableStats(
const Clause& clause)
{
max_instruction_ = max(max_instruction_, clause.GetIndex());
max_variable_ = max(max_variable_, clause.GetMaxVariable());
number_of_instructions_++;
}
} // namespace drat2er
| 27.96
| 79
| 0.762232
|
rcurtin
|
b836de530818bb730f484311be23e725c3afda4c
| 1,368
|
cxx
|
C++
|
src/internal/1m/dot.cxx
|
devinamatthews/tensor
|
7d979b6624071879383377611cb2fa483b6a3104
|
[
"BSD-3-Clause"
] | 86
|
2016-05-30T16:08:24.000Z
|
2022-03-30T22:57:35.000Z
|
src/internal/1m/dot.cxx
|
devinamatthews/tensor
|
7d979b6624071879383377611cb2fa483b6a3104
|
[
"BSD-3-Clause"
] | 41
|
2017-02-02T22:28:17.000Z
|
2022-02-22T16:51:14.000Z
|
src/internal/1m/dot.cxx
|
devinamatthews/tensor
|
7d979b6624071879383377611cb2fa483b6a3104
|
[
"BSD-3-Clause"
] | 26
|
2016-05-30T16:08:33.000Z
|
2021-12-29T03:02:30.000Z
|
#include "dot.hpp"
namespace tblis
{
namespace internal
{
template <typename T>
void dot(const communicator& comm, const config& cfg, len_type m, len_type n,
bool conj_A, const T* A, stride_type rs_A, stride_type cs_A,
bool conj_B, const T* B, stride_type rs_B, stride_type cs_B, T& result)
{
if (rs_B > cs_B)
{
std::swap(m, n);
std::swap(rs_A, cs_A);
std::swap(rs_B, cs_B);
}
atomic_accumulator<T> local_result;
comm.distribute_over_threads(m, n,
[&](len_type m_min, len_type m_max, len_type n_min, len_type n_max)
{
T micro_result = T();
for (len_type j = n_min;j < n_max;j++)
{
cfg.dot_ukr.call<T>(m_max-m_min,
conj_A, A + m_min*rs_A + j*cs_A, rs_A,
conj_B, B + m_min*rs_B + j*cs_B, rs_B, micro_result);
}
local_result += micro_result;
});
reduce(comm, local_result);
if (comm.master()) result = local_result;
comm.barrier();
}
#define FOREACH_TYPE(T) \
template void dot(const communicator& comm, const config& cfg, len_type m, len_type n, \
bool conj_A, const T* A, stride_type rs_A, stride_type cs_A, \
bool conj_B, const T* B, stride_type rs_B, stride_type cs_B, T& result);
#include "configs/foreach_type.h"
}
}
| 26.823529
| 90
| 0.592105
|
devinamatthews
|
b83b9d79495d47c49ed32a1dbc8c36093d718ad6
| 1,567
|
cpp
|
C++
|
BurningGround/src/hooks/consume.cpp
|
idmontie/gptp
|
14d68e5eac84c2f3085ac25a7fff31a07ea387f6
|
[
"0BSD"
] | 8
|
2015-04-03T16:50:59.000Z
|
2021-01-06T17:12:29.000Z
|
BurningGround/src/hooks/consume.cpp
|
idmontie/gptp
|
14d68e5eac84c2f3085ac25a7fff31a07ea387f6
|
[
"0BSD"
] | 6
|
2015-04-03T18:10:56.000Z
|
2016-02-18T05:04:21.000Z
|
BurningGround/src/hooks/consume.cpp
|
idmontie/gptp
|
14d68e5eac84c2f3085ac25a7fff31a07ea387f6
|
[
"0BSD"
] | 6
|
2015-04-04T04:37:33.000Z
|
2018-04-09T09:03:50.000Z
|
#include "consume.h"
#include "max_unit_energy.h"
#include "../SCBW/api.h"
#include "../SCBW/scbwdata.h"
#include "../SCBW/enumerations.h"
/// Helper function: Sets death scores for [unit] owned by [player].
void incrementDeathScores(const CUnit *unit, u8 player);
/// Decides whether the given unit can be Consumed.
bool unitIsConsumable(const CUnit* unit, u8 consumingPlayer) {
using Unit::BaseProperty;
using Unit::GroupFlags;
using UnitProperty::Building;
//Default StarCraft behavior
return !(BaseProperty[unit->id] & Building) //Cannot consume buildings
&& unit->playerId == consumingPlayer //Must be owned by the current player
&& GroupFlags[unit->id].isZerg //Must be a Zerg unit
&& unit->id != UnitId::larva; //Cannot consume larvae
}
/// Is called when a unit is consumed.
void onConsumeUnit(CUnit* caster, CUnit *target) {
//Default StarCraft behavior
incrementDeathScores(target, caster->playerId);
target->remove();
if (!(target->status & UnitStatus::IsHallucination)) { //If not a hallucination
u16 energy = caster->energy + 12800; //50 energy
u16 maxEnergy = getUnitMaxEnergy(caster);
if (energy > maxEnergy)
energy = maxEnergy;
caster->energy = energy;
}
}
/**** Definitions of helper functions. Do not edit anything below this! ****/
void incrementDeathScores(const CUnit *unit, u8 player) {
__asm {
PUSHAD
MOV EDI, unit
MOVZX EDX, player
CALL offsets::Util_IncrementDeathScores
POPAD
}
}
| 31.34
| 86
| 0.668794
|
idmontie
|
b83cafb7bb44272086953fc5bb485628de372e86
| 3,872
|
cc
|
C++
|
backend/schema/verifiers/foreign_key_verifiers_test.cc
|
sgorse12/cloud-spanner-emulator
|
13ebb6d42867bfbc80224b4a74a896b683ae4555
|
[
"Apache-2.0"
] | 179
|
2020-03-30T20:30:49.000Z
|
2022-03-31T04:47:55.000Z
|
backend/schema/verifiers/foreign_key_verifiers_test.cc
|
sgorse12/cloud-spanner-emulator
|
13ebb6d42867bfbc80224b4a74a896b683ae4555
|
[
"Apache-2.0"
] | 53
|
2020-08-31T15:14:30.000Z
|
2022-03-30T21:28:36.000Z
|
backend/schema/verifiers/foreign_key_verifiers_test.cc
|
sgorse12/cloud-spanner-emulator
|
13ebb6d42867bfbc80224b4a74a896b683ae4555
|
[
"Apache-2.0"
] | 26
|
2020-04-02T04:05:58.000Z
|
2022-02-22T12:05:55.000Z
|
//
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include "backend/schema/verifiers/foreign_key_verifiers.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "zetasql/base/testing/status_matchers.h"
#include "tests/common/proto_matchers.h"
#include "backend/database/database.h"
#include "backend/transaction/options.h"
#include "backend/transaction/read_write_transaction.h"
#include "common/clock.h"
namespace google {
namespace spanner {
namespace emulator {
namespace backend {
namespace {
using zetasql::values::Int64;
using zetasql::values::NullInt64;
using zetasql_base::testing::StatusIs;
// Unit tests for the foreign key verifier. These include branch coverage of the
// verifier code. Separate conformance tests cover more detailed end-to-end
// tests for different foreign key shapes and initial data states.
class ForeignKeyVerifiersTest : public ::testing::Test {
protected:
void SetUp() override {
ZETASQL_ASSERT_OK(CreateDatabase({R"(
CREATE TABLE T (
A INT64,
B INT64,
C INT64,
) PRIMARY KEY(A))",
R"(
CREATE TABLE U (
X INT64,
Y INT64,
Z INT64,
) PRIMARY KEY(X))"}));
}
absl::Status AddForeignKey() {
return UpdateSchema({R"(
ALTER TABLE U
ADD CONSTRAINT C
FOREIGN KEY(Z, Y)
REFERENCES T(B, C))"});
}
absl::Status CreateDatabase(const std::vector<std::string>& statements) {
ZETASQL_ASSIGN_OR_RETURN(database_, Database::Create(&clock_, statements));
return absl::OkStatus();
}
absl::Status UpdateSchema(absl::Span<const std::string> statements) {
int succesful;
absl::Status status;
absl::Time timestamp;
ZETASQL_RETURN_IF_ERROR(
database_->UpdateSchema(statements, &succesful, ×tamp, &status));
return status;
}
void Insert(const std::string& table, const std::vector<std::string>& columns,
const std::vector<int>& values) {
Mutation m;
m.AddWriteOp(MutationOpType::kInsert, table, columns, {AsList(values)});
ZETASQL_ASSERT_OK_AND_ASSIGN(std::unique_ptr<ReadWriteTransaction> txn,
database_->CreateReadWriteTransaction(
ReadWriteOptions(), RetryState()));
ZETASQL_ASSERT_OK(txn->Write(m));
ZETASQL_ASSERT_OK(txn->Commit());
}
ValueList AsList(const std::vector<int>& values) {
ValueList value_list;
std::transform(
values.begin(), values.end(), std::back_inserter(value_list),
[](int value) { return value == 0 ? NullInt64() : Int64(value); });
return value_list;
}
Clock clock_;
std::unique_ptr<Database> database_;
};
TEST_F(ForeignKeyVerifiersTest, NoExistingData) { ZETASQL_EXPECT_OK(AddForeignKey()); }
TEST_F(ForeignKeyVerifiersTest, ValidExistingData) {
Insert("T", {"A", "B", "C"}, {1, 2, 3});
Insert("U", {"X", "Y", "Z"}, {4, 3, 2});
ZETASQL_EXPECT_OK(AddForeignKey());
}
TEST_F(ForeignKeyVerifiersTest, InvalidExistingData) {
Insert("T", {"A", "B", "C"}, {1, 2, 3});
Insert("U", {"X", "Y", "Z"}, {4, 2, 3});
EXPECT_THAT(AddForeignKey(), StatusIs(absl::StatusCode::kFailedPrecondition));
}
} // namespace
} // namespace backend
} // namespace emulator
} // namespace spanner
} // namespace google
| 31.737705
| 87
| 0.668905
|
sgorse12
|
b83ee13397a05776a3c1e47ad5d079b0391122d9
| 2,606
|
cpp
|
C++
|
src/xr_3da/xrGame/GameTask_script.cpp
|
ixray-team/ixray-b2939
|
d9dc2359c0177cd3b58c310e015a1f390af2d8a1
|
[
"Linux-OpenIB"
] | 1
|
2022-03-26T17:00:19.000Z
|
2022-03-26T17:00:19.000Z
|
src/xr_3da/xrGame/GameTask_script.cpp
|
ixray-team/ixray-b2939
|
d9dc2359c0177cd3b58c310e015a1f390af2d8a1
|
[
"Linux-OpenIB"
] | null | null | null |
src/xr_3da/xrGame/GameTask_script.cpp
|
ixray-team/ixray-b2939
|
d9dc2359c0177cd3b58c310e015a1f390af2d8a1
|
[
"Linux-OpenIB"
] | 1
|
2022-03-26T17:00:21.000Z
|
2022-03-26T17:00:21.000Z
|
#include "stdafx.h"
#include "GameTask.h"
#include "script_space.h"
#include <luabind/adopt_policy.hpp>
using namespace luabind;
#pragma optimize("s",on)
void CGameTask::script_register(lua_State *L)
{
module(L)
[
class_<enum_exporter<ETaskState> >("task")
.enum_("task_state")
[
value("fail", int(eTaskStateFail)),
value("in_progress", int(eTaskStateInProgress)),
value("completed", int(eTaskStateCompleted)),
value("task_dummy", int(eTaskStateDummy))
],
class_<SGameTaskObjective>("SGameTaskObjective")
.def( constructor<CGameTask*, int>() )
.def("set_description", &SGameTaskObjective::SetDescription_script )
.def("get_description", &SGameTaskObjective::GetDescription_script )
.def("set_article_id", &SGameTaskObjective::SetArticleID_script )
.def("set_map_hint", &SGameTaskObjective::SetMapHint_script )
.def("set_map_location", &SGameTaskObjective::SetMapLocation_script )
.def("set_object_id", &SGameTaskObjective::SetObjectID_script )
.def("set_article_key", &SGameTaskObjective::SetArticleKey_script )
.def("add_complete_info", &SGameTaskObjective::AddCompleteInfo_script )
.def("add_fail_info", &SGameTaskObjective::AddFailInfo_script )
.def("add_on_complete_info", &SGameTaskObjective::AddOnCompleteInfo_script )
.def("add_on_fail_info", &SGameTaskObjective::AddOnFailInfo_script )
.def("add_complete_func", &SGameTaskObjective::AddCompleteFunc_script )
.def("add_fail_func", &SGameTaskObjective::AddFailFunc_script )
.def("add_on_complete_func", &SGameTaskObjective::AddOnCompleteFunc_script )
.def("add_on_fail_func", &SGameTaskObjective::AddOnFailFunc_script )
.def("get_state", &SGameTaskObjective::TaskState )
.def("get_idx", &SGameTaskObjective::GetIDX_script )
.def("get_state", &SGameTaskObjective::TaskState ),
class_<CGameTask>("CGameTask")
.def( constructor<>() )
.def("load", &CGameTask::Load_script )
.def("set_title", &CGameTask::SetTitle_script )
.def("get_title", &CGameTask::GetTitle_script )
.def("add_objective", &CGameTask::AddObjective_script, adopt(_2))
.def("get_objective", &CGameTask::GetObjective_script )
.def("get_id", &CGameTask::GetID_script )
.def("get_objectives_cnt", &CGameTask::GetObjectiveSize_script )
];
}
| 46.535714
| 84
| 0.651573
|
ixray-team
|
b83f048dc7c3b3547b53cb378630a073b7d4552e
| 1,277
|
cpp
|
C++
|
Plugins/VictoryPlugin-master/Source/VictoryBPLibrary/Private/VictoryBPHTML.cpp
|
crimsonstrife/velorum-defunct
|
1a6e1eab9057293da2aa045eff021d069df54c5e
|
[
"CC0-1.0"
] | null | null | null |
Plugins/VictoryPlugin-master/Source/VictoryBPLibrary/Private/VictoryBPHTML.cpp
|
crimsonstrife/velorum-defunct
|
1a6e1eab9057293da2aa045eff021d069df54c5e
|
[
"CC0-1.0"
] | null | null | null |
Plugins/VictoryPlugin-master/Source/VictoryBPLibrary/Private/VictoryBPHTML.cpp
|
crimsonstrife/velorum-defunct
|
1a6e1eab9057293da2aa045eff021d069df54c5e
|
[
"CC0-1.0"
] | null | null | null |
/*
By Rama
*/
#include "VictoryBPLibraryPrivatePCH.h"
#include "VictoryBPHTML.h"
#if PLATFORM_HTML5_BROWSER
#include "SDL_opengl.h"
DEFINE_LOG_CATEGORY_STATIC(VictoryPluginHTML, Log, All);
#include "emscripten.h"
#include "html5.h"
#endif
bool UVictoryBPHTML::IsHTML()
{
#if PLATFORM_HTML5_BROWSER
return true;
#else
return false;
#endif //HTML
}
void UVictoryBPHTML::VictoryHTML5_SetCursorVisible(bool MakeVisible)
{
if(MakeVisible)
{
#if PLATFORM_HTML5_WIN32
{
SDL_SetRelativeMouseMode(SDL_FALSE);
SDL_ShowCursor(SDL_ENABLE);
SDL_SetWindowGrab(WindowHandle, SDL_FALSE);
UE_LOG(VictoryPluginHTML, Warning, TEXT("SDL Showing Mouse Cursor"));
}
#endif
#if PLATFORM_HTML5_BROWSER
{
emscripten_exit_pointerlock();
UE_LOG(VictoryPluginHTML, Warning, TEXT("Exiting Pointer Lock"));
}
#endif
}
else
{
#if PLATFORM_HTML5_WIN32
{
SDL_SetWindowGrab(WindowHandle, SDL_TRUE);
SDL_ShowCursor(SDL_DISABLE);
SDL_SetRelativeMouseMode(SDL_TRUE);
UE_LOG(VictoryPluginHTML, Warning, TEXT("SDL Hiding Mouse Cursor"));
}
#endif
#if PLATFORM_HTML5_BROWSER
{
emscripten_request_pointerlock ( "#canvas" , true);
UE_LOG(VictoryPluginHTML, Warning, TEXT("Entering Pointer Lock"));
}
#endif
}
}
| 20.269841
| 72
| 0.729052
|
crimsonstrife
|
b84141fe534387171bef980fd9676c08b623280b
| 1,349
|
cpp
|
C++
|
Day 25/Flood Fill - DFS Version (Better).cpp
|
shtanriverdi/CS487-Introduction-to-Competitive-Programming-Progress
|
0d7a4fa4346ee08d9b2b2f628c3ffab7f3f81166
|
[
"MIT"
] | 4
|
2019-12-12T19:59:50.000Z
|
2020-01-20T15:44:44.000Z
|
Day 25/Flood Fill - DFS Version (Better).cpp
|
shtanriverdi/CS487-Introduction-to-Competitive-Programming-Progress
|
0d7a4fa4346ee08d9b2b2f628c3ffab7f3f81166
|
[
"MIT"
] | null | null | null |
Day 25/Flood Fill - DFS Version (Better).cpp
|
shtanriverdi/CS487-Introduction-to-Competitive-Programming-Progress
|
0d7a4fa4346ee08d9b2b2f628c3ffab7f3f81166
|
[
"MIT"
] | null | null | null |
// Question Link ---> https://leetcode.com/problems/flood-fill/
// Day #25
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
class Solution {
public:
vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
// We need to consider starting pixel, if it is alrealy filled with newColor then return
if (image[sr][sc] != newColor) {
int oldColor = image[sr][sc];
dfs(image, sr, sc, newColor, oldColor);
}
return image;
}
void dfs(vector<vector<int>> &image, int x, int y, int &newColor, int &oldColor) {
if (x >= 0 && x < image.size() && y >= 0 && y < image[0].size() && image[x][y] == oldColor) {
image[x][y] = newColor;
dfs(image, x, y + 1, newColor, oldColor);
dfs(image, x, y - 1, newColor, oldColor);
dfs(image, x - 1, y, newColor, oldColor);
dfs(image, x + 1, y, newColor, oldColor);
}
}
};
int main(void) {
vector<vector<int>> res, image = { {0, 0, 0}, {0, 1, 1} };
int sr = 1, sc = 1, newColor = 1;
//vector<vector<int>> res, image = { {1, 1, 1}, {1, 1, 0}, {1, 0, 1} };
//int sr = 1, sc = 1, newColor = 2;
Solution obj;
res = obj.floodFill(image, sr, sc, newColor);
cout << "Result: \n";
for (auto row : image) {
for (auto pixel : row) {
cout << pixel << " ";
}
cout << endl;
}
}
| 30.659091
| 96
| 0.570793
|
shtanriverdi
|
cdc7bd71d9ec72ddccba414e42a22e60c693de99
| 9,632
|
cxx
|
C++
|
modules/scene_manager/include/geometry_msgs/msg/dds_connext/PoseStamped_.cxx
|
Omnirobotic/godot
|
d50b5d047bbf6c68fc458c1ad097321ca627185d
|
[
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | null | null | null |
modules/scene_manager/include/geometry_msgs/msg/dds_connext/PoseStamped_.cxx
|
Omnirobotic/godot
|
d50b5d047bbf6c68fc458c1ad097321ca627185d
|
[
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | 3
|
2019-11-14T12:20:06.000Z
|
2020-08-07T13:51:10.000Z
|
modules/scene_manager/include/geometry_msgs/msg/dds_connext/PoseStamped_.cxx
|
Omnirobotic/godot
|
d50b5d047bbf6c68fc458c1ad097321ca627185d
|
[
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | null | null | null |
/*
WARNING: THIS FILE IS AUTO-GENERATED. DO NOT MODIFY.
This file was generated from PoseStamped_.idl using "rtiddsgen".
The rtiddsgen tool is part of the RTI Connext distribution.
For more information, type 'rtiddsgen -help' at a command shell
or consult the RTI Connext manual.
*/
#ifndef NDDS_STANDALONE_TYPE
#ifndef ndds_cpp_h
#include "ndds/ndds_cpp.h"
#endif
#ifndef dds_c_log_impl_h
#include "dds_c/dds_c_log_impl.h"
#endif
#ifndef cdr_type_h
#include "cdr/cdr_type.h"
#endif
#ifndef osapi_heap_h
#include "osapi/osapi_heap.h"
#endif
#else
#include "ndds_standalone_type.h"
#endif
#include "PoseStamped_.h"
#include <new>
namespace geometry_msgs {
namespace msg {
namespace dds_ {
/* ========================================================================= */
const char *PoseStamped_TYPENAME = "geometry_msgs::msg::dds_::PoseStamped_";
DDS_TypeCode* PoseStamped__get_typecode()
{
static RTIBool is_initialized = RTI_FALSE;
static DDS_TypeCode_Member PoseStamped__g_tc_members[2]=
{
{
(char *)"header_",/* Member name */
{
0,/* Representation ID */
DDS_BOOLEAN_FALSE,/* Is a pointer? */
-1, /* Bitfield bits */
NULL/* Member type code is assigned later */
},
0, /* Ignored */
0, /* Ignored */
0, /* Ignored */
NULL, /* Ignored */
RTI_CDR_REQUIRED_MEMBER, /* Is a key? */
DDS_PUBLIC_MEMBER,/* Member visibility */
1,
NULL/* Ignored */
},
{
(char *)"pose_",/* Member name */
{
1,/* Representation ID */
DDS_BOOLEAN_FALSE,/* Is a pointer? */
-1, /* Bitfield bits */
NULL/* Member type code is assigned later */
},
0, /* Ignored */
0, /* Ignored */
0, /* Ignored */
NULL, /* Ignored */
RTI_CDR_REQUIRED_MEMBER, /* Is a key? */
DDS_PUBLIC_MEMBER,/* Member visibility */
1,
NULL/* Ignored */
}
};
static DDS_TypeCode PoseStamped__g_tc =
{{
DDS_TK_STRUCT,/* Kind */
DDS_BOOLEAN_FALSE, /* Ignored */
-1, /*Ignored*/
(char *)"geometry_msgs::msg::dds_::PoseStamped_", /* Name */
NULL, /* Ignored */
0, /* Ignored */
0, /* Ignored */
NULL, /* Ignored */
2, /* Number of members */
PoseStamped__g_tc_members, /* Members */
DDS_VM_NONE /* Ignored */
}}; /* Type code for PoseStamped_*/
if (is_initialized) {
return &PoseStamped__g_tc;
}
PoseStamped__g_tc_members[0]._representation._typeCode = (RTICdrTypeCode *)std_msgs::msg::dds_::Header__get_typecode();
PoseStamped__g_tc_members[1]._representation._typeCode = (RTICdrTypeCode *)geometry_msgs::msg::dds_::Pose__get_typecode();
is_initialized = RTI_TRUE;
return &PoseStamped__g_tc;
}
RTIBool PoseStamped__initialize(
PoseStamped_* sample) {
return geometry_msgs::msg::dds_::PoseStamped__initialize_ex(sample,RTI_TRUE,RTI_TRUE);
}
RTIBool PoseStamped__initialize_ex(
PoseStamped_* sample,RTIBool allocatePointers, RTIBool allocateMemory)
{
struct DDS_TypeAllocationParams_t allocParams =
DDS_TYPE_ALLOCATION_PARAMS_DEFAULT;
allocParams.allocate_pointers = (DDS_Boolean)allocatePointers;
allocParams.allocate_memory = (DDS_Boolean)allocateMemory;
return geometry_msgs::msg::dds_::PoseStamped__initialize_w_params(
sample,&allocParams);
}
RTIBool PoseStamped__initialize_w_params(
PoseStamped_* sample, const struct DDS_TypeAllocationParams_t * allocParams)
{
if (sample == NULL) {
return RTI_FALSE;
}
if (allocParams == NULL) {
return RTI_FALSE;
}
if (!std_msgs::msg::dds_::Header__initialize_w_params(&sample->header_,
allocParams)) {
return RTI_FALSE;
}
if (!geometry_msgs::msg::dds_::Pose__initialize_w_params(&sample->pose_,
allocParams)) {
return RTI_FALSE;
}
return RTI_TRUE;
}
void PoseStamped__finalize(
PoseStamped_* sample)
{
geometry_msgs::msg::dds_::PoseStamped__finalize_ex(sample,RTI_TRUE);
}
void PoseStamped__finalize_ex(
PoseStamped_* sample,RTIBool deletePointers)
{
struct DDS_TypeDeallocationParams_t deallocParams =
DDS_TYPE_DEALLOCATION_PARAMS_DEFAULT;
if (sample==NULL) {
return;
}
deallocParams.delete_pointers = (DDS_Boolean)deletePointers;
geometry_msgs::msg::dds_::PoseStamped__finalize_w_params(
sample,&deallocParams);
}
void PoseStamped__finalize_w_params(
PoseStamped_* sample,const struct DDS_TypeDeallocationParams_t * deallocParams)
{
if (sample==NULL) {
return;
}
if (deallocParams == NULL) {
return;
}
std_msgs::msg::dds_::Header__finalize_w_params(&sample->header_,deallocParams);
geometry_msgs::msg::dds_::Pose__finalize_w_params(&sample->pose_,deallocParams);
}
void PoseStamped__finalize_optional_members(
PoseStamped_* sample, RTIBool deletePointers)
{
struct DDS_TypeDeallocationParams_t deallocParamsTmp =
DDS_TYPE_DEALLOCATION_PARAMS_DEFAULT;
struct DDS_TypeDeallocationParams_t * deallocParams =
&deallocParamsTmp;
if (sample==NULL) {
return;
}
if (deallocParams) {} /* To avoid warnings */
deallocParamsTmp.delete_pointers = (DDS_Boolean)deletePointers;
deallocParamsTmp.delete_optional_members = DDS_BOOLEAN_TRUE;
std_msgs::msg::dds_::Header__finalize_optional_members(&sample->header_, deallocParams->delete_pointers);
geometry_msgs::msg::dds_::Pose__finalize_optional_members(&sample->pose_, deallocParams->delete_pointers);
}
RTIBool PoseStamped__copy(
PoseStamped_* dst,
const PoseStamped_* src)
{
try {
if (dst == NULL || src == NULL) {
return RTI_FALSE;
}
if (!std_msgs::msg::dds_::Header__copy(
&dst->header_,(const std_msgs::msg::dds_::Header_*)&src->header_)) {
return RTI_FALSE;
}
if (!geometry_msgs::msg::dds_::Pose__copy(
&dst->pose_,(const geometry_msgs::msg::dds_::Pose_*)&src->pose_)) {
return RTI_FALSE;
}
return RTI_TRUE;
} catch (std::bad_alloc&) {
return RTI_FALSE;
}
}
/**
* <<IMPLEMENTATION>>
*
* Defines: TSeq, T
*
* Configure and implement 'PoseStamped_' sequence class.
*/
#define T PoseStamped_
#define TSeq PoseStamped_Seq
#define T_initialize_w_params geometry_msgs::msg::dds_::PoseStamped__initialize_w_params
#define T_finalize_w_params geometry_msgs::msg::dds_::PoseStamped__finalize_w_params
#define T_copy geometry_msgs::msg::dds_::PoseStamped__copy
#ifndef NDDS_STANDALONE_TYPE
#include "dds_c/generic/dds_c_sequence_TSeq.gen"
#include "dds_cpp/generic/dds_cpp_sequence_TSeq.gen"
#else
#include "dds_c_sequence_TSeq.gen"
#include "dds_cpp_sequence_TSeq.gen"
#endif
#undef T_copy
#undef T_finalize_w_params
#undef T_initialize_w_params
#undef TSeq
#undef T
} /* namespace dds_ */
} /* namespace msg */
} /* namespace geometry_msgs */
| 34.898551
| 138
| 0.48858
|
Omnirobotic
|
cdc85a8aaa84d76d1b59685fdf79359face70a9d
| 3,191
|
hpp
|
C++
|
stan/math/rev/core/operator_multiplication.hpp
|
peterwicksstringfield/math
|
5ce0718ea64f2cca8b2f1e4eeac27a2dc2bd246e
|
[
"BSD-3-Clause"
] | null | null | null |
stan/math/rev/core/operator_multiplication.hpp
|
peterwicksstringfield/math
|
5ce0718ea64f2cca8b2f1e4eeac27a2dc2bd246e
|
[
"BSD-3-Clause"
] | null | null | null |
stan/math/rev/core/operator_multiplication.hpp
|
peterwicksstringfield/math
|
5ce0718ea64f2cca8b2f1e4eeac27a2dc2bd246e
|
[
"BSD-3-Clause"
] | null | null | null |
#ifndef STAN_MATH_REV_CORE_OPERATOR_MULTIPLICATION_HPP
#define STAN_MATH_REV_CORE_OPERATOR_MULTIPLICATION_HPP
#include <stan/math/rev/core/var.hpp>
#include <stan/math/rev/core/vv_vari.hpp>
#include <stan/math/rev/core/vd_vari.hpp>
#include <stan/math/prim/scal/fun/is_any_nan.hpp>
#include <limits>
namespace stan {
namespace math {
namespace internal {
class multiply_vv_vari : public op_vv_vari {
public:
multiply_vv_vari(vari* avi, vari* bvi)
: op_vv_vari(avi->val_ * bvi->val_, avi, bvi) {}
void chain() {
if (unlikely(is_any_nan(avi_->val_, bvi_->val_))) {
avi_->adj_ = std::numeric_limits<double>::quiet_NaN();
bvi_->adj_ = std::numeric_limits<double>::quiet_NaN();
} else {
avi_->adj_ += bvi_->val_ * adj_;
bvi_->adj_ += avi_->val_ * adj_;
}
}
};
class multiply_vd_vari : public op_vd_vari {
public:
multiply_vd_vari(vari* avi, double b) : op_vd_vari(avi->val_ * b, avi, b) {}
void chain() {
if (unlikely(is_any_nan(avi_->val_, bd_))) {
avi_->adj_ = std::numeric_limits<double>::quiet_NaN();
} else {
avi_->adj_ += adj_ * bd_;
}
}
};
} // namespace internal
/**
* Multiplication operator for two variables (C++).
*
* The partial derivatives are
*
* \f$\frac{\partial}{\partial x} (x * y) = y\f$, and
*
* \f$\frac{\partial}{\partial y} (x * y) = x\f$.
*
\f[
\mbox{operator*}(x, y) =
\begin{cases}
xy & \mbox{if } -\infty\leq x, y \leq \infty \\[6pt]
\textrm{NaN} & \mbox{if } x = \textrm{NaN or } y = \textrm{NaN}
\end{cases}
\f]
\f[
\frac{\partial\, \mbox{operator*}(x, y)}{\partial x} =
\begin{cases}
y & \mbox{if } -\infty\leq x, y \leq \infty \\[6pt]
\textrm{NaN} & \mbox{if } x = \textrm{NaN or } y = \textrm{NaN}
\end{cases}
\f]
\f[
\frac{\partial\, \mbox{operator*}(x, y)}{\partial y} =
\begin{cases}
x & \mbox{if } -\infty\leq x, y \leq \infty \\[6pt]
\textrm{NaN} & \mbox{if } x = \textrm{NaN or } y = \textrm{NaN}
\end{cases}
\f]
*
* @param a First variable operand.
* @param b Second variable operand.
* @return Variable result of multiplying operands.
*/
inline var operator*(const var& a, const var& b) {
return var(new internal::multiply_vv_vari(a.vi_, b.vi_));
}
/**
* Multiplication operator for a variable and a scalar (C++).
*
* The partial derivative for the variable is
*
* \f$\frac{\partial}{\partial x} (x * c) = c\f$, and
*
* @param a Variable operand.
* @param b Scalar operand.
* @return Variable result of multiplying operands.
*/
inline var operator*(const var& a, double b) {
if (b == 1.0) {
return a;
}
return var(new internal::multiply_vd_vari(a.vi_, b));
}
/**
* Multiplication operator for a scalar and a variable (C++).
*
* The partial derivative for the variable is
*
* \f$\frac{\partial}{\partial y} (c * y) = c\f$.
*
* @param a Scalar operand.
* @param b Variable operand.
* @return Variable result of multiplying the operands.
*/
inline var operator*(double a, const var& b) {
if (a == 1.0) {
return b;
}
return var(new internal::multiply_vd_vari(b.vi_, a)); // by symmetry
}
} // namespace math
} // namespace stan
#endif
| 26.155738
| 78
| 0.622689
|
peterwicksstringfield
|
cdcb3c9d7b0ab48f58035e94362a02c755229f35
| 203
|
cpp
|
C++
|
judges/uri/iniciante/1174.cpp
|
eduardonunes2525/competitive-programming
|
0f6bdc573b4d03d1ed20a2b77ec5388dca1ee47b
|
[
"MIT"
] | null | null | null |
judges/uri/iniciante/1174.cpp
|
eduardonunes2525/competitive-programming
|
0f6bdc573b4d03d1ed20a2b77ec5388dca1ee47b
|
[
"MIT"
] | 1
|
2018-10-17T11:53:02.000Z
|
2018-10-17T11:54:42.000Z
|
judges/uri/iniciante/1174.cpp
|
eduardonunes2525/competitive-programming
|
0f6bdc573b4d03d1ed20a2b77ec5388dca1ee47b
|
[
"MIT"
] | 1
|
2018-10-17T12:14:04.000Z
|
2018-10-17T12:14:04.000Z
|
#include <bits/stdc++.h>
using namespace std;
int main (){
double n[100];
for(int i = 0; i < 100; i++){
cin >> n[i];
if(n[i] <= 10){
printf("A[%d] = %.1lf\n", i, n[i]);
}
}
return 0;
}
| 11.277778
| 38
| 0.472906
|
eduardonunes2525
|
cdcdda1727cad51d2b9f1d5364b44d01972f86f3
| 1,317
|
cc
|
C++
|
洛谷/提高/P2014.cc
|
OFShare/Algorithm-challenger
|
43336871a5e48f8804d6e737c813d9d4c0dc2731
|
[
"MIT"
] | 67
|
2019-07-14T05:38:41.000Z
|
2021-12-23T11:52:51.000Z
|
洛谷/提高/P2014.cc
|
OFShare/Algorithm-challenger
|
43336871a5e48f8804d6e737c813d9d4c0dc2731
|
[
"MIT"
] | null | null | null |
洛谷/提高/P2014.cc
|
OFShare/Algorithm-challenger
|
43336871a5e48f8804d6e737c813d9d4c0dc2731
|
[
"MIT"
] | 12
|
2020-01-16T10:48:01.000Z
|
2021-06-11T16:49:04.000Z
|
/*
* Author : OFShare
* E-mail : OFShare@outlook.com
* Created Time : 2020-07-01 13:40:58 PM
* File Name : P2014.cc
*/
#include <bits/stdc++.h>
#define ll long long
void debug() {
#ifdef Acui
freopen("data.in", "r", stdin);
freopen("data.out", "w", stdout);
#endif
}
const int N = 3e2 + 5;
int n, m, score[N], size[N], dp[N][N];
std::vector<int> sons[N];
// dp[u][j]表示以结点u为根, 选j门课(看成背包容量且恰好装满), 能获得的最大学分
void dfs(int u) {
dp[u][0] = 0;
size[u] = 1;
// 每个儿子看成一组背包
for (int i = 0; i < sons[u].size(); ++i) {
int v = sons[u][i];
dfs(v);
size[u] += size[v];
// 类似分组背包, k枚举第i组背包(即第i个儿子)选几门课
for (int j = m; j >= 0; --j) {
for (int k = 0; k <= size[v]; ++k) {
if (j - k >= 0)
dp[u][j] = std::max(dp[u][j], dp[u][j - k] + dp[v][k]);
}
}
}
// 根结点u本身看成一组背包, 且必须取它
for (int j = m; j >= 0; --j) {
if (j - 1 >= 0) {
// dp[u][j] = std::max(dp[u][j], dp[u][j - 1] + score[u]);
dp[u][j] = dp[u][j - 1] + score[u];
}
}
}
int main() {
scanf("%d %d", &n, &m);
for (int i = 1; i <= n; ++i) {
int k, s;
scanf("%d %d", &k, &s);
sons[k].push_back(i);
score[i] = s;
}
m += 1;
score[0] = 0;
std::memset(dp, -0x3f3f3f, sizeof dp);
dfs(0);
printf("%d\n", dp[0][m]);
return 0;
}
| 21.241935
| 65
| 0.459377
|
OFShare
|
cdcdfa70ac642fa745ec04bc6dcd146877c746ac
| 3,001
|
cpp
|
C++
|
src/ldb_reader.cpp
|
Prime9999/liblcf
|
3ea048387c36b14af48a4061a7a23d2276f35ac4
|
[
"MIT"
] | null | null | null |
src/ldb_reader.cpp
|
Prime9999/liblcf
|
3ea048387c36b14af48a4061a7a23d2276f35ac4
|
[
"MIT"
] | null | null | null |
src/ldb_reader.cpp
|
Prime9999/liblcf
|
3ea048387c36b14af48a4061a7a23d2276f35ac4
|
[
"MIT"
] | null | null | null |
/*
* This file is part of liblcf. Copyright (c) 2018 liblcf authors.
* https://github.com/EasyRPG/liblcf - https://easyrpg.org
*
* liblcf is Free/Libre Open Source Software, released under the MIT License.
* For the full copyright and license information, please view the COPYING
* file that was distributed with this source code.
*/
#include <fstream>
#include "ldb_reader.h"
#include "ldb_chunks.h"
#include "data.h"
#include "reader_util.h"
#include "reader_struct.h"
bool LDB_Reader::Load(const std::string& filename, const std::string& encoding) {
std::ifstream stream(filename.c_str(), std::ios::binary);
return LDB_Reader::Load(stream, encoding);
}
bool LDB_Reader::Save(const std::string& filename, const std::string& encoding) {
std::ofstream stream(filename.c_str(), std::ios::binary);
return LDB_Reader::Save(stream, encoding);
}
bool LDB_Reader::SaveXml(const std::string& filename) {
std::ofstream stream(filename.c_str(), std::ios::binary);
return LDB_Reader::SaveXml(stream);
}
bool LDB_Reader::LoadXml(const std::string& filename) {
std::ifstream stream(filename.c_str(), std::ios::binary);
return LDB_Reader::LoadXml(stream);
}
bool LDB_Reader::Load(std::istream& filestream, const std::string& encoding) {
LcfReader reader(filestream, encoding);
if (!reader.IsOk()) {
LcfReader::SetError("Couldn't parse database file.\n");
return false;
}
std::string header;
reader.ReadString(header, reader.ReadInt());
if (header.length() != 11) {
LcfReader::SetError("This is not a valid RPG2000 database.\n");
return false;
}
if (header != "LcfDataBase") {
fprintf(stderr, "Warning: This header is not LcfDataBase and might not be a valid RPG2000 database.\n");
}
TypeReader<RPG::Database>::ReadLcf(Data::data, reader, 0);
// Delayed initialization of some actor fields because they are engine
// dependent
std::vector<RPG::Actor>::iterator it;
for (it = Data::actors.begin(); it != Data::actors.end(); ++it) {
(*it).Setup();
}
return true;
}
bool LDB_Reader::Save(std::ostream& filestream, const std::string& encoding) {
LcfWriter writer(filestream, encoding);
if (!writer.IsOk()) {
LcfReader::SetError("Couldn't parse database file.\n");
return false;
}
const std::string header("LcfDataBase");
writer.WriteInt(header.size());
writer.Write(header);
TypeReader<RPG::Database>::WriteLcf(Data::data, writer);
return true;
}
bool LDB_Reader::SaveXml(std::ostream& filestream) {
XmlWriter writer(filestream);
if (!writer.IsOk()) {
LcfReader::SetError("Couldn't parse database file.\n");
return false;
}
writer.BeginElement("LDB");
TypeReader<RPG::Database>::WriteXml(Data::data, writer);
writer.EndElement("LDB");
return true;
}
bool LDB_Reader::LoadXml(std::istream& filestream) {
XmlReader reader(filestream);
if (!reader.IsOk()) {
LcfReader::SetError("Couldn't parse database file.\n");
return false;
}
reader.SetHandler(new RootXmlHandler<RPG::Database>(Data::data, "LDB"));
reader.Parse();
return true;
}
| 30.01
| 106
| 0.715095
|
Prime9999
|
cdce7c6e95a62bd75ef115cdc5cbb46bff04970e
| 1,439
|
cpp
|
C++
|
Source/RuntimeImageLoader/Private/ImageReaders/ImageReaderLocal.cpp
|
RaiaN/ue4_runtimeimageimporter
|
02fec76b591fb9b5988e3355bf73f16248c244a4
|
[
"MIT"
] | 1
|
2022-02-02T09:06:41.000Z
|
2022-02-02T09:06:41.000Z
|
Source/RuntimeImageLoader/Private/ImageReaders/ImageReaderLocal.cpp
|
RaiaN/ue4_runtimeimageimporter
|
02fec76b591fb9b5988e3355bf73f16248c244a4
|
[
"MIT"
] | null | null | null |
Source/RuntimeImageLoader/Private/ImageReaders/ImageReaderLocal.cpp
|
RaiaN/ue4_runtimeimageimporter
|
02fec76b591fb9b5988e3355bf73f16248c244a4
|
[
"MIT"
] | null | null | null |
// Copyright 2022 Peter Leontev. All Rights Reserved.
#include "ImageReaderLocal.h"
#include "HAL/FileManager.h"
#include "Misc/FileHelper.h"
#include "Stats/Stats.h"
bool FImageReaderLocal::ReadImage(const FString& ImageURI, TArray<uint8>& OutImageData)
{
QUICK_SCOPE_CYCLE_COUNTER(STAT_RuntimeImageUtils_ImportFileAsTexture);
// TODO:
const int64 MAX_FILESIZE_BYTES = 999999999;
IFileManager& FileManager = IFileManager::Get();
if (!FileManager.FileExists(*ImageURI))
{
OutError = FString::Printf(TEXT("Image does not exist: %s"), *ImageURI);
return false;
}
const int64 ImageFileSizeBytes = FileManager.FileSize(*ImageURI);
check(ImageFileSizeBytes != INDEX_NONE);
// check filesize
if (ImageFileSizeBytes > MAX_FILESIZE_BYTES)
{
OutError = FString::Printf(TEXT("Image filesize > %d MBs): %s"), MAX_FILESIZE_BYTES, *ImageURI);
return false;
}
QUICK_SCOPE_CYCLE_COUNTER(STAT_FImageReaderLocal_LoadFileToArray);
if (!FFileHelper::LoadFileToArray(OutImageData, *ImageURI))
{
OutError = FString::Printf(TEXT("Image loading I/O error: %s"), *ImageURI);
return false;
}
OutImageData.Add(0);
return true;
}
FString FImageReaderLocal::GetLastError() const
{
return OutError;
}
void FImageReaderLocal::Flush()
{
// do nothing as we image reader local is synchronous and does not depend on game thread
}
| 27.673077
| 104
| 0.702571
|
RaiaN
|
cdd31d556fdcad78e0b66559b3a5d11b71f88d97
| 261
|
hpp
|
C++
|
lib/tests/ruby/ruby_helper.hpp
|
mihaibuzgau/facter
|
451ee4288c61c6185295b454339801b84b8242ef
|
[
"Apache-2.0"
] | null | null | null |
lib/tests/ruby/ruby_helper.hpp
|
mihaibuzgau/facter
|
451ee4288c61c6185295b454339801b84b8242ef
|
[
"Apache-2.0"
] | null | null | null |
lib/tests/ruby/ruby_helper.hpp
|
mihaibuzgau/facter
|
451ee4288c61c6185295b454339801b84b8242ef
|
[
"Apache-2.0"
] | null | null | null |
#pragma once
#include <facter/facts/collection.hpp>
#include <facter/facts/value.hpp>
#include <string>
bool load_custom_fact(std::string const& filename, facter::facts::collection& facts);
std::string ruby_value_to_string(facter::facts::value const* value);
| 29
| 85
| 0.777778
|
mihaibuzgau
|
cdd3415aacc6450af278647dd8d7980e2c101d2e
| 1,460
|
hpp
|
C++
|
gearoenix/render/camera/gx-rnd-cmr-manager.hpp
|
Hossein-Noroozpour/gearoenix
|
c8fa8b8946c03c013dad568d6d7a97d81097c051
|
[
"BSD-Source-Code"
] | 35
|
2018-01-07T02:34:38.000Z
|
2022-02-09T05:19:03.000Z
|
gearoenix/render/camera/gx-rnd-cmr-manager.hpp
|
Hossein-Noroozpour/gearoenix
|
c8fa8b8946c03c013dad568d6d7a97d81097c051
|
[
"BSD-Source-Code"
] | 111
|
2017-09-20T09:12:36.000Z
|
2020-12-27T12:52:03.000Z
|
gearoenix/render/camera/gx-rnd-cmr-manager.hpp
|
Hossein-Noroozpour/gearoenix
|
c8fa8b8946c03c013dad568d6d7a97d81097c051
|
[
"BSD-Source-Code"
] | 5
|
2020-02-11T11:17:37.000Z
|
2021-01-08T17:55:43.000Z
|
#ifndef GEAROENIX_RENDER_CAMERA_MANAGER_HPP
#define GEAROENIX_RENDER_CAMERA_MANAGER_HPP
#include "../../core/asset/gx-cr-asset-manager.hpp"
#include "../../core/cache/gx-cr-cache-file.hpp"
#include "../../core/sync/gx-cr-sync-end-caller.hpp"
#include "gx-rnd-cmr-camera.hpp"
namespace gearoenix {
namespace system::stream {
class Stream;
}
namespace render {
namespace engine {
class Engine;
}
namespace camera {
class Manager {
protected:
engine::Engine* const e;
core::cache::File<Camera> cache;
public:
Manager(std::unique_ptr<system::stream::Stream> s, engine::Engine* e) noexcept;
~Manager() noexcept = default;
std::shared_ptr<Camera> get_gx3d(core::Id cid, core::sync::EndCaller<Camera>& call) noexcept;
template <typename T>
typename std::enable_if<std::is_base_of<Camera, T>::value, std::shared_ptr<T>>::type create(std::string name) noexcept;
};
}
}
}
template <typename T>
typename std::enable_if<std::is_base_of<gearoenix::render::camera::Camera, T>::value, std::shared_ptr<T>>::type
gearoenix::render::camera::Manager::create(std::string name) noexcept
{
const core::Id id = core::asset::Manager::create_id();
const std::shared_ptr<T> result(new T(id, std::move(name), e));
const std::weak_ptr<Camera> w = result;
cache.get_cacher().get_cacheds()[id] = w;
return result;
}
#endif
| 33.181818
| 131
| 0.65411
|
Hossein-Noroozpour
|
cdd66f3fdd4f4cbd8a5d1bedc91b172b0727f686
| 1,824
|
hpp
|
C++
|
layout/include/nesci/layout/spike_detector.hpp
|
halfflat/nesci
|
60f90b41d4d4c50a306fe2af28b322c1cbef943c
|
[
"Apache-2.0"
] | null | null | null |
layout/include/nesci/layout/spike_detector.hpp
|
halfflat/nesci
|
60f90b41d4d4c50a306fe2af28b322c1cbef943c
|
[
"Apache-2.0"
] | null | null | null |
layout/include/nesci/layout/spike_detector.hpp
|
halfflat/nesci
|
60f90b41d4d4c50a306fe2af28b322c1cbef943c
|
[
"Apache-2.0"
] | 1
|
2018-10-11T15:14:36.000Z
|
2018-10-11T15:14:36.000Z
|
//------------------------------------------------------------------------------
// nesci -- neuronal simulator conan interface
//
// Copyright (c) 2018 RWTH Aachen University, Germany,
// Virtual Reality & Immersive Visualization Group.
//------------------------------------------------------------------------------
// License
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//------------------------------------------------------------------------------
#ifndef LAYOUT_INCLUDE_NESCI_LAYOUT_SPIKE_DETECTOR_HPP_
#define LAYOUT_INCLUDE_NESCI_LAYOUT_SPIKE_DETECTOR_HPP_
#include <string>
#include "nesci/layout/device.hpp"
namespace nesci {
namespace layout {
class SpikeDetector : public Device {
public:
SpikeDetector() = delete;
explicit SpikeDetector(const std::string& name);
SpikeDetector(const SpikeDetector&) = default;
explicit SpikeDetector(const Device& device);
SpikeDetector(SpikeDetector&&) = default;
explicit SpikeDetector(Device&& device);
~SpikeDetector() override = default;
SpikeDetector& operator=(const SpikeDetector&) = default;
SpikeDetector& operator=(SpikeDetector&&) = default;
std::string GetPath() const override;
};
} // namespace layout
} // namespace nesci
#endif // LAYOUT_INCLUDE_NESCI_LAYOUT_SPIKE_DETECTOR_HPP_
| 35.076923
| 80
| 0.645285
|
halfflat
|
cdd6d6354490997081eaa944e7bd55f72e3091fb
| 6,367
|
cpp
|
C++
|
src/qt/qtbase/tests/auto/corelib/tools/qsize/tst_qsize.cpp
|
power-electro/phantomjs-Gohstdriver-DIY-openshift
|
a571d301a9658a4c1b524d07e15658b45f8a0579
|
[
"BSD-3-Clause"
] | 1
|
2020-04-30T15:47:35.000Z
|
2020-04-30T15:47:35.000Z
|
src/qt/qtbase/tests/auto/corelib/tools/qsize/tst_qsize.cpp
|
power-electro/phantomjs-Gohstdriver-DIY-openshift
|
a571d301a9658a4c1b524d07e15658b45f8a0579
|
[
"BSD-3-Clause"
] | null | null | null |
src/qt/qtbase/tests/auto/corelib/tools/qsize/tst_qsize.cpp
|
power-electro/phantomjs-Gohstdriver-DIY-openshift
|
a571d301a9658a4c1b524d07e15658b45f8a0579
|
[
"BSD-3-Clause"
] | null | null | null |
/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#include <qsize.h>
class tst_QSize : public QObject
{
Q_OBJECT
private slots:
void getSetCheck();
void scale();
void expandedTo();
void expandedTo_data();
void boundedTo_data();
void boundedTo();
void transpose_data();
void transpose();
};
// Testing get/set functions
void tst_QSize::getSetCheck()
{
QSize obj1;
// int QSize::width()
// void QSize::setWidth(int)
obj1.setWidth(0);
QCOMPARE(0, obj1.width());
obj1.setWidth(INT_MIN);
QCOMPARE(INT_MIN, obj1.width());
obj1.setWidth(INT_MAX);
QCOMPARE(INT_MAX, obj1.width());
// int QSize::height()
// void QSize::setHeight(int)
obj1.setHeight(0);
QCOMPARE(0, obj1.height());
obj1.setHeight(INT_MIN);
QCOMPARE(INT_MIN, obj1.height());
obj1.setHeight(INT_MAX);
QCOMPARE(INT_MAX, obj1.height());
QSizeF obj2;
// qreal QSizeF::width()
// void QSizeF::setWidth(qreal)
obj2.setWidth(0.0);
QCOMPARE(0.0, obj2.width());
obj2.setWidth(1.1);
QCOMPARE(1.1, obj2.width());
// qreal QSizeF::height()
// void QSizeF::setHeight(qreal)
obj2.setHeight(0.0);
QCOMPARE(0.0, obj2.height());
obj2.setHeight(1.1);
QCOMPARE(1.1, obj2.height());
}
void tst_QSize::scale()
{
QSize t1( 10, 12 );
t1.scale( 60, 60, Qt::IgnoreAspectRatio );
QCOMPARE( t1, QSize(60, 60) );
QSize t2( 10, 12 );
t2.scale( 60, 60, Qt::KeepAspectRatio );
QCOMPARE( t2, QSize(50, 60) );
QSize t3( 10, 12 );
t3.scale( 60, 60, Qt::KeepAspectRatioByExpanding );
QCOMPARE( t3, QSize(60, 72) );
QSize t4( 12, 10 );
t4.scale( 60, 60, Qt::KeepAspectRatio );
QCOMPARE( t4, QSize(60, 50) );
QSize t5( 12, 10 );
t5.scale( 60, 60, Qt::KeepAspectRatioByExpanding );
QCOMPARE( t5, QSize(72, 60) );
// test potential int overflow
QSize t6(88473, 88473);
t6.scale(141817, 141817, Qt::KeepAspectRatio);
QCOMPARE(t6, QSize(141817, 141817));
QSize t7(800, 600);
t7.scale(400, INT_MAX, Qt::KeepAspectRatio);
QCOMPARE(t7, QSize(400, 300));
QSize t8(800, 600);
t8.scale(INT_MAX, 150, Qt::KeepAspectRatio);
QCOMPARE(t8, QSize(200, 150));
QSize t9(600, 800);
t9.scale(300, INT_MAX, Qt::KeepAspectRatio);
QCOMPARE(t9, QSize(300, 400));
QSize t10(600, 800);
t10.scale(INT_MAX, 200, Qt::KeepAspectRatio);
QCOMPARE(t10, QSize(150, 200));
QSize t11(0, 0);
t11.scale(240, 200, Qt::IgnoreAspectRatio);
QCOMPARE(t11, QSize(240, 200));
QSize t12(0, 0);
t12.scale(240, 200, Qt::KeepAspectRatio);
QCOMPARE(t12, QSize(240, 200));
QSize t13(0, 0);
t13.scale(240, 200, Qt::KeepAspectRatioByExpanding);
QCOMPARE(t13, QSize(240, 200));
}
void tst_QSize::expandedTo_data()
{
QTest::addColumn<QSize>("input1");
QTest::addColumn<QSize>("input2");
QTest::addColumn<QSize>("expected");
QTest::newRow("data0") << QSize(10,12) << QSize(6,4) << QSize(10,12);
QTest::newRow("data1") << QSize(0,0) << QSize(6,4) << QSize(6,4);
// This should pick the highest of w,h components independently of each other,
// thus the results don't have to be equal to neither input1 nor input2.
QTest::newRow("data3") << QSize(6,4) << QSize(4,6) << QSize(6,6);
}
void tst_QSize::expandedTo()
{
QFETCH( QSize, input1);
QFETCH( QSize, input2);
QFETCH( QSize, expected);
QCOMPARE( input1.expandedTo(input2), expected);
}
void tst_QSize::boundedTo_data()
{
QTest::addColumn<QSize>("input1");
QTest::addColumn<QSize>("input2");
QTest::addColumn<QSize>("expected");
QTest::newRow("data0") << QSize(10,12) << QSize(6,4) << QSize(6,4);
QTest::newRow("data1") << QSize(0,0) << QSize(6,4) << QSize(0,0);
// This should pick the lowest of w,h components independently of each other,
// thus the results don't have to be equal to neither input1 nor input2.
QTest::newRow("data3") << QSize(6,4) << QSize(4,6) << QSize(4,4);
}
void tst_QSize::boundedTo()
{
QFETCH( QSize, input1);
QFETCH( QSize, input2);
QFETCH( QSize, expected);
QCOMPARE( input1.boundedTo(input2), expected);
}
void tst_QSize::transpose_data()
{
QTest::addColumn<QSize>("input1");
QTest::addColumn<QSize>("expected");
QTest::newRow("data0") << QSize(10,12) << QSize(12,10);
QTest::newRow("data1") << QSize(0,0) << QSize(0,0);
QTest::newRow("data3") << QSize(6,4) << QSize(4,6);
}
void tst_QSize::transpose()
{
QFETCH( QSize, input1);
QFETCH( QSize, expected);
// transpose() works only inplace and does not return anything, so we must do the operation itself before the compare.
input1.transpose();
QCOMPARE(input1 , expected);
}
QTEST_APPLESS_MAIN(tst_QSize)
#include "tst_qsize.moc"
| 29.476852
| 122
| 0.641275
|
power-electro
|
cdd86cd37fbbfb7ed78c314cfa0208fc260b1c1f
| 2,860
|
hpp
|
C++
|
lib/dmitigr/fcgi/listener_options.hpp
|
dmitigr/fcgi
|
0d3755e87c8fe168a7325c5fb93f450375601bfc
|
[
"Zlib"
] | 40
|
2019-05-16T14:37:10.000Z
|
2022-03-25T11:35:13.000Z
|
lib/dmitigr/fcgi/listener_options.hpp
|
dmitigr/fcgi
|
0d3755e87c8fe168a7325c5fb93f450375601bfc
|
[
"Zlib"
] | 2
|
2019-05-30T09:41:03.000Z
|
2020-05-27T18:29:38.000Z
|
lib/dmitigr/fcgi/listener_options.hpp
|
dmitigr/fcgi
|
0d3755e87c8fe168a7325c5fb93f450375601bfc
|
[
"Zlib"
] | 6
|
2019-05-17T13:13:41.000Z
|
2022-01-18T01:26:50.000Z
|
// -*- C++ -*-
// Copyright (C) Dmitry Igrishin
// For conditions of distribution and use, see files LICENSE.txt or fcgi.hpp
#ifndef DMITIGR_FCGI_LISTENER_OPTIONS_HPP
#define DMITIGR_FCGI_LISTENER_OPTIONS_HPP
#include "dmitigr/fcgi/dll.hpp"
#include "dmitigr/fcgi/types_fwd.hpp"
#include <dmitigr/misc/filesystem.hpp>
#include <dmitigr/net/types_fwd.hpp>
#include <memory>
#include <optional>
#include <string>
namespace dmitigr::fcgi {
/**
* @brief FastCGI Listener options.
*/
class Listener_options {
public:
/**
* @brief The destructor.
*/
virtual ~Listener_options() = default;
/// @name Constructors
/// @{
#ifdef _WIN32
/**
* @returns A new instance of the options for listeners of
* Windows Named Pipes (WNP).
*
* @param pipe_name - the pipe name.
*
* @par Effects
* `(endpoint()->communication_mode() == Communication_mode::wnp)`.
*/
static DMITIGR_FCGI_API std::unique_ptr<Listener_options> make(std::string pipe_name);
#else
/**
* @returns A new instance of the options for listeners of
* Unix Domain Sockets (UDS).
*
* @param path - the path to the socket.
* @param backlog - the maximum size of the queue of pending connections.
*
* @par Effects
* `(endpoint()->communication_mode() == Communication_mode::uds)`.
*/
static DMITIGR_FCGI_API std::unique_ptr<Listener_options> make(std::filesystem::path path, int backlog);
#endif
/**
* @overload
*
* @returns A new instance of the options for listeners of network.
*
* @param address - IPv4 or IPv6 address to use for binding on.
* @param port - the port number to use for binding on.
* @param backlog - the maximum size of the queue of pending connections.
*
* @par Requires
* `(port > 0)`.
*
* @par Effects
* `(endpoint()->communication_mode() == Communication_mode::net)`.
*/
static DMITIGR_FCGI_API std::unique_ptr<Listener_options> make(std::string address, int port, int backlog);
/**
* @returns A new instance of the Listener initialized with this instance.
*
* @see Listener::make().
*/
virtual std::unique_ptr<Listener> make_listener() const = 0;
/**
* @returns The copy of this instance.
*/
virtual std::unique_ptr<Listener_options> to_listener_options() const = 0;
/// @}
/**
* @returns The endpoint identifier.
*/
virtual const net::Endpoint& endpoint() const = 0;
/**
* @returns The value of backlog if the communication mode of the endpoint is
* not `Communication_mode::wnp`, or `std::nullopt` otherwise.
*/
virtual std::optional<int> backlog() const = 0;
private:
friend detail::iListener_options;
Listener_options() = default;
};
} // namespace dmitigr::fcgi
#ifdef DMITIGR_FCGI_HEADER_ONLY
#include "dmitigr/fcgi/listener_options.cpp"
#endif
#endif // DMITIGR_FCGI_LISTENER_OPTIONS_HPP
| 25.535714
| 109
| 0.682517
|
dmitigr
|
cde33b2e843334d259f12f8a2263cd8d663b6996
| 701
|
cpp
|
C++
|
LeetCode/Tree/same-tree.cpp
|
vasanth9/coding-universe
|
69ffcb58af0c163689ab9893e6d1e0581e0247e0
|
[
"MIT"
] | null | null | null |
LeetCode/Tree/same-tree.cpp
|
vasanth9/coding-universe
|
69ffcb58af0c163689ab9893e6d1e0581e0247e0
|
[
"MIT"
] | null | null | null |
LeetCode/Tree/same-tree.cpp
|
vasanth9/coding-universe
|
69ffcb58af0c163689ab9893e6d1e0581e0247e0
|
[
"MIT"
] | null | null | null |
/**
Definition for a binary tree node. */
//https://leetcode.com/problems/same-tree/
#include<bits/stdc++.h>
using namespace std;
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:
bool isSameTree(TreeNode* p, TreeNode* q) {
if(p==NULL && q==NULL) return true;
if(p==NULL || q==NULL) return false;
return (p->val==q->val&&isSameTree(p->left,q->left)&&isSameTree(p->right,q->right));
}
};
| 31.863636
| 92
| 0.603424
|
vasanth9
|
cde815305470ccc734b19a7718cdd93b74788053
| 607
|
cpp
|
C++
|
src/main.cpp
|
danbz/signsSlippyMap
|
7b5b1f512479fc27a2ddbdd6b34b074a3c0cae2c
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
danbz/signsSlippyMap
|
7b5b1f512479fc27a2ddbdd6b34b074a3c0cae2c
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
danbz/signsSlippyMap
|
7b5b1f512479fc27a2ddbdd6b34b074a3c0cae2c
|
[
"MIT"
] | null | null | null |
//
// slippy map elements based on example code Copyright (c) 2014 Christopher Baker <https://christopherbaker.net>
// SPDX-License-Identifier: MIT
//
/*
Project Title: Signs of Surveillance
Description:
©Daniel Buzzo 2019
dan@buzzo.com
http://buzzo.com
https://github.com/danbz
*/
#include "ofAppRunner.h"
#include "ofApp.h"
int main()
{
ofGLWindowSettings settings;
settings.setSize(1280, 768);
settings.setGLVersion(3, 2);
settings.windowMode = OF_FULLSCREEN;
auto window = ofCreateWindow(settings);
auto app = std::make_shared<ofApp>();
return ofRunApp(app);
}
| 20.931034
| 112
| 0.70346
|
danbz
|
cdebb80f0ab70fcd88c13f4c41657343898bfbc6
| 5,744
|
cpp
|
C++
|
src/optimizer/rule/PushFilterDownGetNbrsRule.cpp
|
yixinglu/nebula-graph
|
faf9cd44d818b953da98b5c922999560c89867bd
|
[
"Apache-2.0"
] | 1
|
2021-08-23T05:55:55.000Z
|
2021-08-23T05:55:55.000Z
|
src/optimizer/rule/PushFilterDownGetNbrsRule.cpp
|
yixinglu/nebula-graph
|
faf9cd44d818b953da98b5c922999560c89867bd
|
[
"Apache-2.0"
] | null | null | null |
src/optimizer/rule/PushFilterDownGetNbrsRule.cpp
|
yixinglu/nebula-graph
|
faf9cd44d818b953da98b5c922999560c89867bd
|
[
"Apache-2.0"
] | null | null | null |
/* Copyright (c) 2020 vesoft inc. All rights reserved.
*
* This source code is licensed under Apache 2.0 License,
* attached with Common Clause Condition 1.0, found in the LICENSES directory.
*/
#include "optimizer/rule/PushFilterDownGetNbrsRule.h"
#include "common/expression/BinaryExpression.h"
#include "common/expression/ConstantExpression.h"
#include "common/expression/Expression.h"
#include "common/expression/FunctionCallExpression.h"
#include "common/expression/LogicalExpression.h"
#include "common/expression/UnaryExpression.h"
#include "optimizer/OptGroup.h"
#include "planner/PlanNode.h"
#include "planner/Query.h"
#include "visitor/ExtractFilterExprVisitor.h"
using nebula::graph::Filter;
using nebula::graph::GetNeighbors;
using nebula::graph::PlanNode;
using nebula::graph::QueryContext;
namespace nebula {
namespace opt {
std::unique_ptr<OptRule> PushFilterDownGetNbrsRule::kInstance =
std::unique_ptr<PushFilterDownGetNbrsRule>(new PushFilterDownGetNbrsRule());
PushFilterDownGetNbrsRule::PushFilterDownGetNbrsRule() {
RuleSet::queryRules().addRule(this);
}
bool PushFilterDownGetNbrsRule::match(const OptGroupExpr *groupExpr) const {
auto pair = findMatchedGroupExpr(groupExpr);
if (!pair.first) {
return false;
}
return true;
}
Status PushFilterDownGetNbrsRule::transform(QueryContext *qctx,
const OptGroupExpr *groupExpr,
TransformResult *result) const {
auto pair = findMatchedGroupExpr(groupExpr);
auto filter = static_cast<const Filter *>(groupExpr->node());
auto gn = static_cast<const GetNeighbors *>(pair.second->node());
auto condition = filter->condition()->clone();
graph::ExtractFilterExprVisitor visitor;
condition->accept(&visitor);
if (!visitor.ok()) {
result->eraseCurr = false;
result->eraseAll = false;
return Status::OK();
}
auto pool = qctx->objPool();
auto remainedExpr = std::move(visitor).remainedExpr();
OptGroupExpr *newFilterGroupExpr = nullptr;
if (remainedExpr != nullptr) {
auto newFilter = Filter::make(qctx, nullptr, pool->add(remainedExpr.release()));
newFilter->setOutputVar(filter->outputVar());
newFilter->setInputVar(filter->inputVar());
newFilterGroupExpr = OptGroupExpr::create(qctx, newFilter, groupExpr->group());
}
auto newGNFilter = condition->encode();
if (!gn->filter().empty()) {
auto filterExpr = Expression::decode(gn->filter());
LogicalExpression logicExpr(
Expression::Kind::kLogicalAnd, condition.release(), filterExpr.release());
newGNFilter = logicExpr.encode();
}
auto newGN = cloneGetNbrs(qctx, gn);
newGN->setFilter(newGNFilter);
OptGroupExpr *newGroupExpr = nullptr;
if (newFilterGroupExpr != nullptr) {
// Filter(A&&B)->GetNeighbors(C) => Filter(A)->GetNeighbors(B&&C)
auto newGroup = OptGroup::create(qctx);
newGroupExpr = OptGroupExpr::create(qctx, newGN, newGroup);
newFilterGroupExpr->dependsOn(newGroup);
} else {
// Filter(A)->GetNeighbors(C) => GetNeighbors(A&&C)
newGroupExpr = OptGroupExpr::create(qctx, newGN, groupExpr->group());
newGN->setOutputVar(filter->outputVar());
}
for (auto dep : pair.second->dependencies()) {
newGroupExpr->dependsOn(dep);
}
result->newGroupExprs.emplace_back(newFilterGroupExpr ? newFilterGroupExpr : newGroupExpr);
result->eraseAll = true;
result->eraseCurr = true;
return Status::OK();
}
std::string PushFilterDownGetNbrsRule::toString() const {
return "PushFilterDownGetNbrsRule";
}
std::pair<bool, const OptGroupExpr *> PushFilterDownGetNbrsRule::findMatchedGroupExpr(
const OptGroupExpr *groupExpr) const {
auto node = groupExpr->node();
if (node->kind() != PlanNode::Kind::kFilter) {
return std::make_pair(false, nullptr);
}
for (auto dep : groupExpr->dependencies()) {
for (auto expr : dep->groupExprs()) {
if (expr->node()->kind() == PlanNode::Kind::kGetNeighbors) {
return std::make_pair(true, expr);
}
}
}
return std::make_pair(false, nullptr);
}
GetNeighbors *PushFilterDownGetNbrsRule::cloneGetNbrs(QueryContext *qctx,
const GetNeighbors *gn) const {
auto newGN = GetNeighbors::make(qctx, nullptr, gn->space());
newGN->setSrc(gn->src());
newGN->setEdgeTypes(gn->edgeTypes());
newGN->setEdgeDirection(gn->edgeDirection());
newGN->setDedup(gn->dedup());
newGN->setRandom(gn->random());
newGN->setLimit(gn->limit());
newGN->setInputVar(gn->inputVar());
newGN->setOutputVar(gn->outputVar());
if (gn->vertexProps()) {
auto vertexProps = *gn->vertexProps();
auto vertexPropsPtr = std::make_unique<decltype(vertexProps)>(std::move(vertexProps));
newGN->setVertexProps(std::move(vertexPropsPtr));
}
if (gn->edgeProps()) {
auto edgeProps = *gn->edgeProps();
auto edgePropsPtr = std::make_unique<decltype(edgeProps)>(std::move(edgeProps));
newGN->setEdgeProps(std::move(edgePropsPtr));
}
if (gn->statProps()) {
auto statProps = *gn->statProps();
auto statPropsPtr = std::make_unique<decltype(statProps)>(std::move(statProps));
newGN->setStatProps(std::move(statPropsPtr));
}
if (gn->exprs()) {
auto exprs = *gn->exprs();
auto exprsPtr = std::make_unique<decltype(exprs)>(std::move(exprs));
newGN->setExprs(std::move(exprsPtr));
}
return newGN;
}
} // namespace opt
} // namespace nebula
| 35.02439
| 95
| 0.657904
|
yixinglu
|
cdf05999595b8296f34e1e2e39939a2ca3dbb56e
| 3,733
|
cc
|
C++
|
tensorflow/core/kernels/matrix_inverse_op.cc
|
sylviawhoa/tensorflow
|
30f3cdfc420d831e2591cce62fa51164cf8a700a
|
[
"Apache-2.0"
] | 21
|
2016-03-10T11:55:45.000Z
|
2021-02-03T02:49:11.000Z
|
tensorflow/core/kernels/matrix_inverse_op.cc
|
sylviawhoa/tensorflow
|
30f3cdfc420d831e2591cce62fa51164cf8a700a
|
[
"Apache-2.0"
] | null | null | null |
tensorflow/core/kernels/matrix_inverse_op.cc
|
sylviawhoa/tensorflow
|
30f3cdfc420d831e2591cce62fa51164cf8a700a
|
[
"Apache-2.0"
] | 39
|
2016-03-25T05:13:09.000Z
|
2020-06-16T01:30:53.000Z
|
/* Copyright 2015 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// See docs in ../ops/linalg_ops.cc.
#include <cmath>
#include "third_party/eigen3/Eigen/Cholesky"
#include "third_party/eigen3/Eigen/LU"
#include "tensorflow/core/framework/kernel_def_builder.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/kernels/linalg_ops_common.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
template <class Scalar, bool SupportsBatchOperationT>
class MatrixInverseOp
: public UnaryLinearAlgebraOp<Scalar, SupportsBatchOperationT> {
public:
explicit MatrixInverseOp(OpKernelConstruction* context)
: UnaryLinearAlgebraOp<Scalar, SupportsBatchOperationT>(context) {}
~MatrixInverseOp() override {}
TensorShape GetOutputMatrixShape(
const TensorShape& input_matrix_shape) override {
return input_matrix_shape;
}
int64 GetCostPerUnit(const TensorShape& input_matrix_shape) override {
const int64 rows = input_matrix_shape.dim_size(0);
if (rows > (1LL << 20)) {
// A big number to cap the cost in case overflow.
return kint64max;
} else {
return rows * rows * rows;
}
}
typedef UnaryLinearAlgebraOp<Scalar, SupportsBatchOperationT> Base;
using Matrix = typename Base::Matrix;
using MatrixMap = typename Base::MatrixMap;
using ConstMatrixMap = typename Base::ConstMatrixMap;
void ComputeMatrix(OpKernelContext* context, const ConstMatrixMap& input,
MatrixMap* output) override {
OP_REQUIRES(context, input.rows() == input.cols(),
errors::InvalidArgument("Input matrix must be square."));
if (input.rows() == 0) {
// By definition, an empty matrix's inverse is an empty matrix.
return;
}
Eigen::PartialPivLU<Matrix> lu_decomposition(input);
// TODO(rmlarsen): Add check based on condition number estimation.
// PartialPivLU cannot give strong guarantees on invertibility, but
// we can at least guard against exact zero pivots. This can occur as
// a result of basic user mistakes, such as providing integer valued
// matrices that are exactly singular, or due to underflow if this
// code is run with denormals being flushed to zero.
const Scalar min_abs_pivot =
lu_decomposition.matrixLU().diagonal().cwiseAbs().minCoeff();
OP_REQUIRES(context, min_abs_pivot > Scalar(0),
errors::InvalidArgument("Input is not invertible."));
output->noalias() = lu_decomposition.inverse();
}
private:
TF_DISALLOW_COPY_AND_ASSIGN(MatrixInverseOp);
};
REGISTER_LINALG_OP("MatrixInverse", (MatrixInverseOp<float, false>), float);
REGISTER_LINALG_OP("MatrixInverse", (MatrixInverseOp<double, false>), double);
REGISTER_LINALG_OP("BatchMatrixInverse", (MatrixInverseOp<float, true>), float);
REGISTER_LINALG_OP("BatchMatrixInverse", (MatrixInverseOp<double, true>),
double);
} // namespace tensorflow
| 40.139785
| 80
| 0.723547
|
sylviawhoa
|
cdfe2209868063639d2d513a2b54807c5630e9bc
| 1,572
|
cpp
|
C++
|
src/cppcalllua_lib/jass_luastate.cpp
|
uniqss/uconfig
|
85bd9e429d0d6df4b6a4d6100a0a7c968160c565
|
[
"MIT"
] | 1
|
2020-12-30T08:06:51.000Z
|
2020-12-30T08:06:51.000Z
|
projects/uconfiglua/src/jass_luastate.cpp
|
uniqss/uniqsconfiggenerator
|
00fcf2b89d43d86c5eb210e8e517cff9a6303b91
|
[
"MIT"
] | 3
|
2021-04-12T03:32:39.000Z
|
2021-04-12T03:38:36.000Z
|
projects/uconfiglua/src/jass_luastate.cpp
|
uniqss/uniqsconfiggenerator
|
00fcf2b89d43d86c5eb210e8e517cff9a6303b91
|
[
"MIT"
] | null | null | null |
#include "jass_luastate.h"
// Use raw function of form "int(lua_State*)"
// -- this is called a "raw C function",
// and matches the type for lua_CFunction
int LoadFileRequire(lua_State* L) {
// use sol2 stack API to pull
// "first argument"
std::string path = sol::stack::get<std::string>(L, 1);
if (path == "a") {
std::string script = R"(
print("Hello from module land!")
test = 123
return "bananas"
)";
// load "module", but don't run it
luaL_loadbuffer(
L, script.data(), script.size(), path.c_str());
// returning 1 object left on Lua stack:
// a function that, when called, executes the script
// (this is what lua_loadX/luaL_loadX functions return
return 1;
}
sol::stack::push(
L, "This is not the module you're looking for!");
return 1;
}
void jass_luastate::init(const std::string& scriptsPath)
{
luastate.open_libraries(
sol::lib::base
, sol::lib::package
, sol::lib::os
, sol::lib::string
, sol::lib::math
, sol::lib::io
);
// https://github.com/ThePhD/sol2/issues/90
/*
sol::state lua;
lua.open_libraries(sol::lib::base, sol::lib::package);
const std::string package_path = lua["package"]["path"];
lua["package"]["path"]
= package_path + (!package_path.empty() ? ";" : "") + test::scripts_path("proc/valid/") + "?.lua";
*/
//luastate.clear_package_loaders();
//luastate.add_package_loader(LoadFileRequire);
const std::string package_path = luastate["package"]["path"];
luastate["package"]["path"] = package_path + (!package_path.empty() ? ";" : "") + "./?.lua;" + scriptsPath +"?.lua";
}
| 27.578947
| 117
| 0.648219
|
uniqss
|
cdff7ff2070b66edde68e62e8ece8465b1e07a29
| 3,476
|
cpp
|
C++
|
src/Processors/Formats/Impl/JSONCompactEachRowRowOutputFormat.cpp
|
540522905/ClickHouse
|
299445ec7da10bd2ef62d8e333a95b7ab12bf5f2
|
[
"Apache-2.0"
] | 2
|
2022-03-15T16:35:11.000Z
|
2022-03-18T12:39:52.000Z
|
src/Processors/Formats/Impl/JSONCompactEachRowRowOutputFormat.cpp
|
540522905/ClickHouse
|
299445ec7da10bd2ef62d8e333a95b7ab12bf5f2
|
[
"Apache-2.0"
] | null | null | null |
src/Processors/Formats/Impl/JSONCompactEachRowRowOutputFormat.cpp
|
540522905/ClickHouse
|
299445ec7da10bd2ef62d8e333a95b7ab12bf5f2
|
[
"Apache-2.0"
] | null | null | null |
#include <IO/WriteHelpers.h>
#include <IO/WriteBufferValidUTF8.h>
#include <Processors/Formats/Impl/JSONCompactEachRowRowOutputFormat.h>
#include <Formats/FormatFactory.h>
#include <Formats/registerWithNamesAndTypes.h>
namespace DB
{
JSONCompactEachRowRowOutputFormat::JSONCompactEachRowRowOutputFormat(WriteBuffer & out_,
const Block & header_,
const RowOutputFormatParams & params_,
const FormatSettings & settings_,
bool with_names_,
bool with_types_,
bool yield_strings_)
: IRowOutputFormat(header_, out_, params_), settings(settings_), with_names(with_names_), with_types(with_types_), yield_strings(yield_strings_)
{
}
void JSONCompactEachRowRowOutputFormat::writeField(const IColumn & column, const ISerialization & serialization, size_t row_num)
{
if (yield_strings)
{
WriteBufferFromOwnString buf;
serialization.serializeText(column, row_num, buf, settings);
writeJSONString(buf.str(), out, settings);
}
else
serialization.serializeTextJSON(column, row_num, out, settings);
}
void JSONCompactEachRowRowOutputFormat::writeFieldDelimiter()
{
writeCString(", ", out);
}
void JSONCompactEachRowRowOutputFormat::writeRowStartDelimiter()
{
writeChar('[', out);
}
void JSONCompactEachRowRowOutputFormat::writeRowEndDelimiter()
{
writeCString("]\n", out);
}
void JSONCompactEachRowRowOutputFormat::writeTotals(const Columns & columns, size_t row_num)
{
writeChar('\n', out);
size_t num_columns = columns.size();
writeRowStartDelimiter();
for (size_t i = 0; i < num_columns; ++i)
{
if (i != 0)
writeFieldDelimiter();
writeField(*columns[i], *serializations[i], row_num);
}
writeRowEndDelimiter();
}
void JSONCompactEachRowRowOutputFormat::writeLine(const std::vector<String> & values)
{
writeRowStartDelimiter();
for (size_t i = 0; i < values.size(); ++i)
{
writeChar('\"', out);
writeString(values[i], out);
writeChar('\"', out);
if (i != values.size() - 1)
writeFieldDelimiter();
}
writeRowEndDelimiter();
}
void JSONCompactEachRowRowOutputFormat::doWritePrefix()
{
const auto & header = getPort(PortKind::Main).getHeader();
if (with_names)
writeLine(header.getNames());
if (with_types)
writeLine(header.getDataTypeNames());
}
void JSONCompactEachRowRowOutputFormat::consumeTotals(DB::Chunk chunk)
{
if (with_names)
IRowOutputFormat::consumeTotals(std::move(chunk));
}
void registerOutputFormatJSONCompactEachRow(FormatFactory & factory)
{
for (bool yield_strings : {false, true})
{
auto register_func = [&](const String & format_name, bool with_names, bool with_types)
{
factory.registerOutputFormat(format_name, [yield_strings, with_names, with_types](
WriteBuffer & buf,
const Block & sample,
const RowOutputFormatParams & params,
const FormatSettings & format_settings)
{
return std::make_shared<JSONCompactEachRowRowOutputFormat>(buf, sample, params, format_settings, with_names, with_types, yield_strings);
});
factory.markOutputFormatSupportsParallelFormatting(format_name);
};
registerWithNamesAndTypes(yield_strings ? "JSONCompactStringsEachRow" : "JSONCompactEachRow", register_func);
}
}
}
| 27.808
| 152
| 0.682681
|
540522905
|
a8057a68a9b2951cfab34cb04e3a82cd1f6e045c
| 26,344
|
cpp
|
C++
|
src/lp_data/HighsModelUtils.cpp
|
ERGO-Code/HiGHS
|
5196737298b23cbf1b8d300ca3e1bf3898041801
|
[
"MIT"
] | 241
|
2018-03-27T15:04:14.000Z
|
2022-03-31T14:44:18.000Z
|
src/lp_data/HighsModelUtils.cpp
|
ERGO-Code/HiGHS
|
5196737298b23cbf1b8d300ca3e1bf3898041801
|
[
"MIT"
] | 384
|
2018-03-28T10:34:36.000Z
|
2022-03-31T20:19:37.000Z
|
src/lp_data/HighsModelUtils.cpp
|
ERGO-Code/HiGHS
|
5196737298b23cbf1b8d300ca3e1bf3898041801
|
[
"MIT"
] | 54
|
2018-04-28T22:43:19.000Z
|
2022-03-31T14:44:22.000Z
|
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* */
/* This file is part of the HiGHS linear optimization suite */
/* */
/* Written and engineered 2008-2021 at the University of Edinburgh */
/* */
/* Available as open-source under the MIT License */
/* */
/* Authors: Julian Hall, Ivet Galabova, Qi Huangfu, Leona Gottwald */
/* and Michael Feldmeier */
/* */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**@file lp_data/HighsUtils.cpp
* @brief Class-independent utilities for HiGHS
*/
#include "lp_data/HighsModelUtils.h"
#include <algorithm>
#include <vector>
#include "HConfig.h"
#include "io/HighsIO.h"
#include "lp_data/HConst.h"
#include "util/HighsUtils.h"
HighsStatus assessMatrixDimensions(const HighsLogOptions& log_options,
const std::string matrix_name,
const HighsInt num_vec,
const vector<HighsInt>& matrix_start,
const vector<HighsInt>& matrix_index,
const vector<double>& matrix_value) {
HighsStatus return_status = HighsStatus::kOk;
// Use error_found to track whether an error has been found in multiple tests
bool error_found = false;
// Assess main dimensions
bool legal_num_vec = num_vec >= 0;
if (!legal_num_vec) {
highsLogUser(log_options, HighsLogType::kError,
"%s matrix has illegal number of vectors = %" HIGHSINT_FORMAT
"\n",
matrix_name.c_str(), num_vec);
error_found = true;
}
HighsInt matrix_start_size = matrix_start.size();
bool legal_matrix_start_size = false;
// Don't expect the matrix_start_size to be legal if there are no vectors
if (num_vec > 0) {
legal_matrix_start_size = matrix_start_size >= num_vec + 1;
if (!legal_matrix_start_size) {
highsLogUser(log_options, HighsLogType::kError,
"%s matrix has illegal start vector size = %" HIGHSINT_FORMAT
" < %" HIGHSINT_FORMAT "\n",
matrix_name.c_str(), matrix_start_size, num_vec + 1);
error_found = true;
}
}
if (matrix_start_size > 0) {
// Check whether the first start is zero
if (matrix_start[0]) {
highsLogUser(log_options, HighsLogType::kWarning,
"%s matrix start vector begins with %" HIGHSINT_FORMAT
" rather than 0\n",
matrix_name.c_str(), matrix_start[0]);
error_found = true;
}
}
// Possibly check the sizes of the index and value vectors. Can only
// do this with the number of nonzeros, and this is only known if
// the start vector has a legal size. Setting num_nz = 0 otherwise
// means that all tests pass, as they just check that the sizes of
// the index and value vectors are non-negative.
HighsInt num_nz = 0;
if (legal_matrix_start_size) num_nz = matrix_start[num_vec];
bool legal_num_nz = num_nz >= 0;
if (!legal_num_nz) {
highsLogUser(log_options, HighsLogType::kError,
"%s matrix has illegal number of nonzeros = %" HIGHSINT_FORMAT
"\n",
matrix_name.c_str(), num_nz);
error_found = true;
} else {
HighsInt matrix_index_size = matrix_index.size();
HighsInt matrix_value_size = matrix_value.size();
bool legal_matrix_index_size = matrix_index_size >= num_nz;
bool legal_matrix_value_size = matrix_value_size >= num_nz;
if (!legal_matrix_index_size) {
highsLogUser(log_options, HighsLogType::kError,
"%s matrix has illegal index vector size = %" HIGHSINT_FORMAT
" < %" HIGHSINT_FORMAT "\n",
matrix_name.c_str(), matrix_index_size, num_nz);
error_found = true;
}
if (!legal_matrix_value_size) {
highsLogUser(log_options, HighsLogType::kError,
"%s matrix has illegal value vector size = %" HIGHSINT_FORMAT
" < %" HIGHSINT_FORMAT "\n",
matrix_name.c_str(), matrix_value_size, num_nz);
error_found = true;
}
}
if (error_found)
return_status = HighsStatus::kError;
else
return_status = HighsStatus::kOk;
return return_status;
}
HighsStatus assessMatrix(const HighsLogOptions& log_options,
const std::string matrix_name, const HighsInt vec_dim,
const HighsInt num_vec, vector<HighsInt>& matrix_start,
vector<HighsInt>& matrix_index,
vector<double>& matrix_value,
const double small_matrix_value,
const double large_matrix_value) {
if (assessMatrixDimensions(log_options, matrix_name, num_vec, matrix_start,
matrix_index, matrix_value) == HighsStatus::kError)
return HighsStatus::kError;
const HighsInt num_nz = matrix_start[num_vec];
if (num_vec <= 0) return HighsStatus::kOk;
if (num_nz <= 0) return HighsStatus::kOk;
HighsStatus return_status = HighsStatus::kOk;
bool error_found = false;
bool warning_found = false;
// Assess the starts
// Set up previous_start for a fictitious previous empty packed vector
HighsInt previous_start = matrix_start[0];
for (HighsInt ix = 0; ix < num_vec; ix++) {
HighsInt this_start = matrix_start[ix];
bool this_start_too_small = this_start < previous_start;
if (this_start_too_small) {
highsLogUser(log_options, HighsLogType::kError,
"%s matrix packed vector %" HIGHSINT_FORMAT
" has illegal start of %" HIGHSINT_FORMAT
" < %" HIGHSINT_FORMAT
" = "
"previous start\n",
matrix_name.c_str(), ix, this_start, previous_start);
return HighsStatus::kError;
}
bool this_start_too_big = this_start > num_nz;
if (this_start_too_big) {
highsLogUser(log_options, HighsLogType::kError,
"%s matrix packed vector %" HIGHSINT_FORMAT
" has illegal start of %" HIGHSINT_FORMAT
" > %" HIGHSINT_FORMAT
" = "
"number of nonzeros\n",
matrix_name.c_str(), ix, this_start, num_nz);
return HighsStatus::kError;
}
}
// Assess the indices and values
// Count the number of acceptable indices/values
HighsInt num_new_nz = 0;
HighsInt num_small_values = 0;
double max_small_value = 0;
double min_small_value = kHighsInf;
// Set up a zeroed vector to detect duplicate indices
vector<HighsInt> check_vector;
if (vec_dim > 0) check_vector.assign(vec_dim, 0);
for (HighsInt ix = 0; ix < num_vec; ix++) {
HighsInt from_el = matrix_start[ix];
HighsInt to_el = matrix_start[ix + 1];
// Account for any index-value pairs removed so far
matrix_start[ix] = num_new_nz;
for (HighsInt el = from_el; el < to_el; el++) {
// Check the index
HighsInt component = matrix_index[el];
// Check that the index is non-negative
bool legal_component = component >= 0;
if (!legal_component) {
highsLogUser(log_options, HighsLogType::kError,
"%s matrix packed vector %" HIGHSINT_FORMAT
", entry %" HIGHSINT_FORMAT
", is illegal index %" HIGHSINT_FORMAT "\n",
matrix_name.c_str(), ix, el, component);
return HighsStatus::kError;
}
// Check that the index does not exceed the vector dimension
legal_component = component < vec_dim;
if (!legal_component) {
highsLogUser(log_options, HighsLogType::kError,
"%s matrix packed vector %" HIGHSINT_FORMAT
", entry %" HIGHSINT_FORMAT
", is illegal index "
"%12" HIGHSINT_FORMAT " >= %" HIGHSINT_FORMAT
" = vector dimension\n",
matrix_name.c_str(), ix, el, component, vec_dim);
return HighsStatus::kError;
}
// Check that the index has not already ocurred
legal_component = check_vector[component] == 0;
if (!legal_component) {
highsLogUser(log_options, HighsLogType::kError,
"%s matrix packed vector %" HIGHSINT_FORMAT
", entry %" HIGHSINT_FORMAT
", is duplicate index %" HIGHSINT_FORMAT "\n",
matrix_name.c_str(), ix, el, component);
return HighsStatus::kError;
}
// Indicate that the index has occurred
check_vector[component] = 1;
// Check the value
double abs_value = fabs(matrix_value[el]);
/*
// Check that the value is not zero
bool zero_value = abs_value == 0;
if (zero_value) {
highsLogUser(log_options, HighsLogType::kError,
"%s matrix packed vector %" HIGHSINT_FORMAT ", entry %"
HIGHSINT_FORMAT ", is zero\n", matrix_name.c_str(), ix, el); return
HighsStatus::kError;
}
*/
// Check that the value is not too large
bool large_value = abs_value > large_matrix_value;
if (large_value) {
highsLogUser(
log_options, HighsLogType::kError,
"%s matrix packed vector %" HIGHSINT_FORMAT
", entry %" HIGHSINT_FORMAT ", is large value |%g| >= %g\n",
matrix_name.c_str(), ix, el, abs_value, large_matrix_value);
return HighsStatus::kError;
}
bool ok_value = abs_value > small_matrix_value;
if (!ok_value) {
if (max_small_value < abs_value) max_small_value = abs_value;
if (min_small_value > abs_value) min_small_value = abs_value;
num_small_values++;
}
if (ok_value) {
// Shift the index and value of the OK entry to the new
// position in the index and value vectors, and increment
// the new number of nonzeros
matrix_index[num_new_nz] = matrix_index[el];
matrix_value[num_new_nz] = matrix_value[el];
num_new_nz++;
} else {
// Zero the check_vector entry since the small value
// _hasn't_ occurred
check_vector[component] = 0;
}
}
// Zero check_vector
for (HighsInt el = matrix_start[ix]; el < num_new_nz; el++)
check_vector[matrix_index[el]] = 0;
#ifdef HiGHSDEV
// NB This is very expensive so shouldn't be true
const bool check_check_vector = false;
if (check_check_vector) {
// Check zeroing of check vector
for (HighsInt component = 0; component < vec_dim; component++) {
if (check_vector[component]) error_found = true;
}
if (error_found)
highsLogUser(log_options, HighsLogType::kError,
"assessMatrix: check_vector not zeroed\n");
}
#endif
}
if (num_small_values) {
highsLogUser(log_options, HighsLogType::kWarning,
"%s matrix packed vector contains %" HIGHSINT_FORMAT
" |values| in [%g, %g] "
"less than %g: ignored\n",
matrix_name.c_str(), num_small_values, min_small_value,
max_small_value, small_matrix_value);
warning_found = true;
}
matrix_start[num_vec] = num_new_nz;
if (error_found)
return_status = HighsStatus::kError;
else if (warning_found)
return_status = HighsStatus::kWarning;
else
return_status = HighsStatus::kOk;
return return_status;
}
void analyseModelBounds(const HighsLogOptions& log_options, const char* message,
HighsInt numBd, const std::vector<double>& lower,
const std::vector<double>& upper) {
if (numBd == 0) return;
HighsInt numFr = 0;
HighsInt numLb = 0;
HighsInt numUb = 0;
HighsInt numBx = 0;
HighsInt numFx = 0;
for (HighsInt ix = 0; ix < numBd; ix++) {
if (highs_isInfinity(-lower[ix])) {
// Infinite lower bound
if (highs_isInfinity(upper[ix])) {
// Infinite lower bound and infinite upper bound: Fr
numFr++;
} else {
// Infinite lower bound and finite upper bound: Ub
numUb++;
}
} else {
// Finite lower bound
if (highs_isInfinity(upper[ix])) {
// Finite lower bound and infinite upper bound: Lb
numLb++;
} else {
// Finite lower bound and finite upper bound:
if (lower[ix] < upper[ix]) {
// Distinct finite bounds: Bx
numBx++;
} else {
// Equal finite bounds: Fx
numFx++;
}
}
}
}
highsLogDev(log_options, HighsLogType::kInfo,
"Analysing %" HIGHSINT_FORMAT " %s bounds\n", numBd, message);
if (numFr > 0)
highsLogDev(log_options, HighsLogType::kInfo,
" Free: %7" HIGHSINT_FORMAT " (%3" HIGHSINT_FORMAT "%%)\n",
numFr, (100 * numFr) / numBd);
if (numLb > 0)
highsLogDev(log_options, HighsLogType::kInfo,
" LB: %7" HIGHSINT_FORMAT " (%3" HIGHSINT_FORMAT "%%)\n",
numLb, (100 * numLb) / numBd);
if (numUb > 0)
highsLogDev(log_options, HighsLogType::kInfo,
" UB: %7" HIGHSINT_FORMAT " (%3" HIGHSINT_FORMAT "%%)\n",
numUb, (100 * numUb) / numBd);
if (numBx > 0)
highsLogDev(log_options, HighsLogType::kInfo,
" Boxed: %7" HIGHSINT_FORMAT " (%3" HIGHSINT_FORMAT "%%)\n",
numBx, (100 * numBx) / numBd);
if (numFx > 0)
highsLogDev(log_options, HighsLogType::kInfo,
" Fixed: %7" HIGHSINT_FORMAT " (%3" HIGHSINT_FORMAT "%%)\n",
numFx, (100 * numFx) / numBd);
highsLogDev(log_options, HighsLogType::kInfo,
"grep_CharMl,%s,Free,LB,UB,Boxed,Fixed\n", message);
highsLogDev(log_options, HighsLogType::kInfo,
"grep_CharMl,%" HIGHSINT_FORMAT ",%" HIGHSINT_FORMAT
",%" HIGHSINT_FORMAT ",%" HIGHSINT_FORMAT ",%" HIGHSINT_FORMAT
",%" HIGHSINT_FORMAT "\n",
numBd, numFr, numLb, numUb, numBx, numFx);
}
std::string statusToString(const HighsBasisStatus status, const double lower,
const double upper) {
switch (status) {
case HighsBasisStatus::kLower:
if (lower == upper) {
return "FX";
} else {
return "LB";
}
break;
case HighsBasisStatus::kBasic:
return "BS";
break;
case HighsBasisStatus::kUpper:
return "UB";
break;
case HighsBasisStatus::kZero:
return "FR";
break;
case HighsBasisStatus::kNonbasic:
return "NB";
break;
}
return "";
}
void writeModelBoundSolution(FILE* file, const bool columns, const HighsInt dim,
const std::vector<double>& lower,
const std::vector<double>& upper,
const std::vector<std::string>& names,
const std::vector<double>& primal,
const std::vector<double>& dual,
const std::vector<HighsBasisStatus>& status) {
const bool have_names = names.size() > 0;
const bool have_primal = primal.size() > 0;
const bool have_dual = dual.size() > 0;
const bool have_basis = status.size() > 0;
if (have_names) assert((int)names.size() >= dim);
if (have_primal) assert((int)primal.size() >= dim);
if (have_dual) assert((int)dual.size() >= dim);
if (have_basis) assert((int)status.size() >= dim);
std::string var_status_string;
if (columns) {
fprintf(file, "Columns\n");
} else {
fprintf(file, "Rows\n");
}
fprintf(
file,
" Index Status Lower Upper Primal Dual");
if (have_names) {
fprintf(file, " Name\n");
} else {
fprintf(file, "\n");
}
for (HighsInt ix = 0; ix < dim; ix++) {
if (have_basis) {
var_status_string = statusToString(status[ix], lower[ix], upper[ix]);
} else {
var_status_string = "";
}
fprintf(file, "%9" HIGHSINT_FORMAT " %4s %12g %12g", ix,
var_status_string.c_str(), lower[ix], upper[ix]);
if (have_primal) {
fprintf(file, " %12g", primal[ix]);
} else {
fprintf(file, " ");
}
if (have_dual) {
fprintf(file, " %12g", dual[ix]);
} else {
fprintf(file, " ");
}
if (have_names) {
fprintf(file, " %-s\n", names[ix].c_str());
} else {
fprintf(file, "\n");
}
}
}
void writeModelSolution(FILE* file, const HighsOptions& options,
double solutionObjective, const HighsInt dim,
const std::vector<std::string>& names,
const std::vector<double>& primal,
const std::vector<HighsVarType>& integrality) {
const bool have_names = names.size() > 0;
const bool have_primal = primal.size() > 0;
const bool have_integrality = integrality.size() > 0;
if (!have_names || !have_primal) return;
if (have_names) assert((int)names.size() >= dim);
if (have_primal) assert((int)primal.size() >= dim);
if (have_integrality) assert((int)integrality.size() >= dim);
std::array<char, 32> objStr = highsDoubleToString(solutionObjective, 1e-13);
fprintf(file, "=obj= %s\n", objStr.data());
for (HighsInt ix = 0; ix < dim; ix++) {
std::array<char, 32> valStr = highsDoubleToString(primal[ix], 1e-13);
fprintf(file, "%-s %s\n", names[ix].c_str(), valStr.data());
}
}
bool namesWithSpaces(const HighsInt num_name,
const std::vector<std::string>& names, const bool report) {
bool names_with_spaces = false;
for (HighsInt ix = 0; ix < num_name; ix++) {
HighsInt space_pos = names[ix].find(" ");
if (space_pos >= 0) {
if (report)
printf(
"Name |%s| contains a space character in position %" HIGHSINT_FORMAT
"\n",
names[ix].c_str(), space_pos);
names_with_spaces = true;
}
}
return names_with_spaces;
}
HighsInt maxNameLength(const HighsInt num_name,
const std::vector<std::string>& names) {
HighsInt max_name_length = 0;
for (HighsInt ix = 0; ix < num_name; ix++)
max_name_length = std::max((HighsInt)names[ix].length(), max_name_length);
return max_name_length;
}
HighsStatus normaliseNames(const HighsLogOptions& log_options,
const std::string name_type, const HighsInt num_name,
std::vector<std::string>& names,
HighsInt& max_name_length) {
// Record the desired maximum name length
HighsInt desired_max_name_length = max_name_length;
// First look for empty names
HighsInt num_empty_name = 0;
std::string name_prefix = name_type.substr(0, 1);
bool names_with_spaces = false;
for (HighsInt ix = 0; ix < num_name; ix++) {
if ((HighsInt)names[ix].length() == 0) num_empty_name++;
}
// If there are no empty names - in which case they will all be
// replaced - find the maximum name length
if (!num_empty_name) max_name_length = maxNameLength(num_name, names);
bool construct_names =
num_empty_name || max_name_length > desired_max_name_length;
if (construct_names) {
// Construct names, either because they are empty names, or
// because the existing names are too long
highsLogUser(log_options, HighsLogType::kWarning,
"There are empty or excessively-long %s names: using "
"constructed names with prefix %s\n",
name_type.c_str(), name_prefix.c_str());
for (HighsInt ix = 0; ix < num_name; ix++)
names[ix] = name_prefix + std::to_string(ix);
} else {
// Using original names, so look to see whether there are names with spaces
names_with_spaces = namesWithSpaces(num_name, names);
}
// Find the final maximum name length
max_name_length = maxNameLength(num_name, names);
// Can't have names with spaces and more than 8 characters
if (max_name_length > 8 && names_with_spaces) return HighsStatus::kError;
if (construct_names) return HighsStatus::kWarning;
return HighsStatus::kOk;
}
HighsBasisStatus checkedVarHighsNonbasicStatus(
const HighsBasisStatus ideal_status, const double lower,
const double upper) {
HighsBasisStatus checked_status;
if (ideal_status == HighsBasisStatus::kLower ||
ideal_status == HighsBasisStatus::kZero) {
// Looking to give status LOWER or ZERO
if (highs_isInfinity(-lower)) {
// Lower bound is infinite
if (highs_isInfinity(upper)) {
// Upper bound is infinite
checked_status = HighsBasisStatus::kZero;
} else {
// Upper bound is finite
checked_status = HighsBasisStatus::kUpper;
}
} else {
checked_status = HighsBasisStatus::kLower;
}
} else {
// Looking to give status UPPER
if (highs_isInfinity(upper)) {
// Upper bound is infinite
if (highs_isInfinity(-lower)) {
// Lower bound is infinite
checked_status = HighsBasisStatus::kZero;
} else {
// Upper bound is finite
checked_status = HighsBasisStatus::kLower;
}
} else {
checked_status = HighsBasisStatus::kUpper;
}
}
return checked_status;
}
// Return a string representation of SolutionStatus
std::string utilSolutionStatusToString(const HighsInt solution_status) {
switch (solution_status) {
case kSolutionStatusNone:
return "None";
break;
case kSolutionStatusInfeasible:
return "Infeasible";
break;
case kSolutionStatusFeasible:
return "Feasible";
break;
default:
assert(1 == 0);
return "Unrecognised solution status";
}
}
// Return a string representation of HighsBasisStatus
std::string utilBasisStatusToString(const HighsBasisStatus basis_status) {
switch (basis_status) {
case HighsBasisStatus::kLower:
return "At lower/fixed bound";
break;
case HighsBasisStatus::kBasic:
return "Basic";
break;
case HighsBasisStatus::kUpper:
return "At upper bound";
break;
case HighsBasisStatus::kZero:
return "Free at zero";
break;
case HighsBasisStatus::kNonbasic:
return "Nonbasic";
break;
default:
assert(1 == 0);
return "Unrecognised solution status";
}
}
// Return a string representation of basis validity
std::string utilBasisValidityToString(const HighsInt basis_validity) {
if (basis_validity) {
return "Valid";
} else {
return "Not valid";
}
}
// Return a string representation of HighsModelStatus.
std::string utilModelStatusToString(const HighsModelStatus model_status) {
switch (model_status) {
case HighsModelStatus::kNotset:
return "Not Set";
break;
case HighsModelStatus::kLoadError:
return "Load error";
break;
case HighsModelStatus::kModelError:
return "Model error";
break;
case HighsModelStatus::kPresolveError:
return "Presolve error";
break;
case HighsModelStatus::kSolveError:
return "Solve error";
break;
case HighsModelStatus::kPostsolveError:
return "Postsolve error";
break;
case HighsModelStatus::kModelEmpty:
return "Model empty";
break;
case HighsModelStatus::kOptimal:
return "Optimal";
break;
case HighsModelStatus::kInfeasible:
return "Infeasible";
break;
case HighsModelStatus::kUnboundedOrInfeasible:
return "Primal infeasible or unbounded";
break;
case HighsModelStatus::kUnbounded:
return "Unbounded";
break;
case HighsModelStatus::kObjectiveBound:
return "Reached objective bound";
break;
case HighsModelStatus::kObjectiveTarget:
return "Reached objective target";
break;
case HighsModelStatus::kTimeLimit:
return "Reached time limit";
break;
case HighsModelStatus::kIterationLimit:
return "Reached iteration limit";
break;
case HighsModelStatus::kUnknown:
return "Unknown";
break;
default:
assert(1 == 0);
return "Unrecognised HiGHS model status";
}
}
void zeroHighsIterationCounts(HighsIterationCounts& iteration_counts) {
iteration_counts.simplex = 0;
iteration_counts.ipm = 0;
iteration_counts.crossover = 0;
iteration_counts.qp = 0;
}
// Deduce the HighsStatus value corresponding to a HighsModelStatus value.
HighsStatus highsStatusFromHighsModelStatus(HighsModelStatus model_status) {
switch (model_status) {
case HighsModelStatus::kNotset:
return HighsStatus::kError;
case HighsModelStatus::kLoadError:
return HighsStatus::kError;
case HighsModelStatus::kModelError:
return HighsStatus::kError;
case HighsModelStatus::kPresolveError:
return HighsStatus::kError;
case HighsModelStatus::kSolveError:
return HighsStatus::kError;
case HighsModelStatus::kPostsolveError:
return HighsStatus::kError;
case HighsModelStatus::kModelEmpty:
return HighsStatus::kOk;
case HighsModelStatus::kOptimal:
return HighsStatus::kOk;
case HighsModelStatus::kInfeasible:
return HighsStatus::kOk;
case HighsModelStatus::kUnboundedOrInfeasible:
return HighsStatus::kOk;
case HighsModelStatus::kUnbounded:
return HighsStatus::kOk;
case HighsModelStatus::kObjectiveBound:
return HighsStatus::kOk;
case HighsModelStatus::kObjectiveTarget:
return HighsStatus::kOk;
case HighsModelStatus::kTimeLimit:
return HighsStatus::kWarning;
case HighsModelStatus::kIterationLimit:
return HighsStatus::kWarning;
case HighsModelStatus::kUnknown:
return HighsStatus::kWarning;
default:
return HighsStatus::kError;
}
}
| 37.052039
| 80
| 0.605641
|
ERGO-Code
|
a805cf5a88e2c33b7877e17769b40ac702621243
| 178
|
hpp
|
C++
|
dev/test/so_5_extra/disp/asio_one_thread/multifile_hello/a.hpp
|
Stiffstream/so5extra
|
20f4c83ecde1509fbaf337dcf40f2f49dcf2690d
|
[
"BSD-3-Clause"
] | 12
|
2020-01-02T01:32:50.000Z
|
2022-02-07T17:55:54.000Z
|
dev/test/so_5_extra/disp/asio_one_thread/multifile_hello/a.hpp
|
Stiffstream/so5extra
|
20f4c83ecde1509fbaf337dcf40f2f49dcf2690d
|
[
"BSD-3-Clause"
] | 1
|
2019-09-04T12:33:35.000Z
|
2020-01-15T15:22:20.000Z
|
dev/test/so_5_extra/disp/asio_one_thread/multifile_hello/a.hpp
|
Stiffstream/so5extra
|
20f4c83ecde1509fbaf337dcf40f2f49dcf2690d
|
[
"BSD-3-Clause"
] | 3
|
2019-08-30T09:55:26.000Z
|
2022-03-19T12:29:04.000Z
|
#pragma once
#include <so_5_extra/disp/asio_one_thread/pub.hpp>
void make_coop_a(
so_5::environment_t & env,
so_5::extra::disp::asio_one_thread::dispatcher_handle_t disp );
| 19.777778
| 64
| 0.775281
|
Stiffstream
|
a808fe8a5a392d42a9a9dd76074627d98b9a06f9
| 2,799
|
cpp
|
C++
|
src/config.cpp
|
manjogsingh/ComputerNetworks2020
|
37e061fcc0f988d9eb720cc8df54b9d1b627ce3f
|
[
"MIT"
] | null | null | null |
src/config.cpp
|
manjogsingh/ComputerNetworks2020
|
37e061fcc0f988d9eb720cc8df54b9d1b627ce3f
|
[
"MIT"
] | null | null | null |
src/config.cpp
|
manjogsingh/ComputerNetworks2020
|
37e061fcc0f988d9eb720cc8df54b9d1b627ce3f
|
[
"MIT"
] | 1
|
2020-11-03T00:11:43.000Z
|
2020-11-03T00:11:43.000Z
|
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <algorithm>
#include <sstream>
using namespace std;
struct configpeer{
int peerId;
string hostname;
int listport;
bool havefile;
} confp;
struct configcommon{
int noprfnbrs;
int unchokint;
int optunchokint;
string filename;
long filesize;
int piecesize;
} conf;
vector<string> split (string s, string delimiter) {
size_t pos_start = 0, pos_end, delim_len = delimiter.length();
string token;
vector<string> res;
while ((pos_end = s.find (delimiter, pos_start)) != string::npos) {
token = s.substr (pos_start, pos_end - pos_start);
pos_start = pos_end + delim_len;
res.push_back (token);
}
res.push_back (s.substr (pos_start));
return res;
}
int main()
{
//Parsing Peer Info Config file
std::ifstream pFile ("samplePeerInfo.cfg");
if(pFile.is_open())
{
string delimiter=" ";
size_t pos = 0;
while(pFile.good()){
string line;
getline(pFile,line);
vector<string> v = split(line, delimiter);
confp.peerId=stoi(v[0]);
confp.hostname=v[1];
confp.listport=stoi(v[2]);
int hfile=stoi(v[3]);
(hfile==1) ? confp.havefile=true : confp.havefile=false;
}
}
else
{
std::cerr << "Couldn't open config file for reading.\n";
}
//Parsing Common Config file
std::ifstream cFile ("sampleCommon.cfg");
if (cFile.is_open())
{
string delimiter=" ";
size_t pos = 0;
string token1,token2;
while(cFile.good()){
string line;
getline(cFile,line);
pos=line.find(delimiter);
token1=line.substr(0,pos);
token2=line.substr(pos+1,line.length());
if(token1.compare("NumberOfPreferredNeighbors")==0){
conf.noprfnbrs=stoi(token2);
}
else if(token1.compare("UnchokingInterval")==0)
{
conf.unchokint=stoi(token2);
}
else if(token1.compare("OptimisticUnchokingInterval")==0)
{
conf.optunchokint=stoi(token2);
}
else if(token1.compare("FileName")==0)
{
conf.filename=token2;
}
else if(token1.compare("FileSize")==0)
{
conf.filesize=stoi(token2);
}
else{
conf.piecesize=stoi(token2);
}
}
}
else
{
std::cerr << "Couldn't open config file for reading.\n";
}
}
| 25.445455
| 73
| 0.518042
|
manjogsingh
|
a80ad36a5094a9d8084e3949d43e7a0c3bdbbb16
| 3,601
|
cpp
|
C++
|
week5_spanning_trees/1_connecting_points/connecting_points.cpp
|
cdlavila/Algorithms-on-Graphs
|
7bbb9937ede317b0080932c73664748bc5a9f0d0
|
[
"MIT"
] | null | null | null |
week5_spanning_trees/1_connecting_points/connecting_points.cpp
|
cdlavila/Algorithms-on-Graphs
|
7bbb9937ede317b0080932c73664748bc5a9f0d0
|
[
"MIT"
] | null | null | null |
week5_spanning_trees/1_connecting_points/connecting_points.cpp
|
cdlavila/Algorithms-on-Graphs
|
7bbb9937ede317b0080932c73664748bc5a9f0d0
|
[
"MIT"
] | null | null | null |
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <vector>
#include <cmath>
using namespace std;
// Disjoint set implementation
class disjoint_set {
private:
int *rank, *parent;
unsigned int n;
public:
// default constructor
disjoint_set() = default;
// Constructor to create and initialize sets of n items
disjoint_set(unsigned int n) {
rank = new int[n];
parent = new int[n];
this->n = n;
makeSet();
}
// Creates n single item sets
void makeSet() {
for (int i = 0; i < n; i++) {
parent[i] = i;
}
}
// Finds set of given item x
int find(int x) {
// Finds the representative of the set that x is an element of
if (parent[x] != x) {
// if x is not the parent of itself Then x is not the representative of his set,
parent[x] = find(parent[x]);
// so we recursively call Find on its parent and move I's node directly under the representative of this set
}
return parent[x];
}
// Do union of two sets represented by x and y.
void Union(int x, int y) {
// Find current sets of x and y
int xSet = find(x);
int ySet = find(y);
// If they are already in same set
if (xSet == ySet)
return;
// Put smaller ranked item under bigger ranked item if ranks are different
if (rank[xSet] < rank[ySet]) {
parent[xSet] = ySet;
} else if (rank[xSet] > rank[ySet]) {
parent[ySet] = xSet;
} else { // If ranks are same, then increment rank.
parent[ySet] = xSet;
rank[xSet]++;
}
}
};
// Undirected weighted edge implementation
class edge{
public:
int u, v;
double weight;
// default constructor
edge() = default;
// Constructor
edge(int u, int v, double weight) {
this->u = u;
this->v = v;
this->weight = weight;
}
};
// Sorting function by weight
bool sorting_by_weight(edge a, edge b) {
return a.weight < b.weight;
}
// Kruskal's algorithm implementation
pair<vector<edge>, double> kruskal(vector<edge> &edges) {
double total_cost = 0;
// for all u ∈ V : MakeSet(v)
disjoint_set ds(edges.size());
// X ← empty set
vector<edge> X(0);
// sort the edges E by weight
sort(edges.begin(), edges.end(), sorting_by_weight);
// for all {u, v} ∈ E in non-decreasing weight order:
for(edge e: edges) {
int u = e.u;
int v = e.v;
// if Find(u) ̸= Find(v):
if (ds.find(u) != ds.find(v)) {
// add {u, v} to X
X.push_back(e);
// Union(u, v)
ds.Union(u, v);
total_cost += e.weight;
}
}
return make_pair(X, total_cost);
}
// Distance between two points function
double distance_between_two_points(int x1, int y1, int x2, int y2) {
return sqrt(pow(x1 - x2, 2) + pow(y1 - y2, 2));
}
// Minimum distance (problem solution)
double minimum_distance(vector<int> x, vector<int> y) {
// Constructing the edges list
unsigned int v = x.size();
vector<edge> edges(v);
for (int i = 0; i < v; i++) {
for (int j = i; j < v; j++) {
if (j != i) {
double weight = distance_between_two_points(x[i], y[i], x[j], y[j]);
edge e(i, j, weight);
edges.push_back(e);
}
}
}
// Running Kruskal's algorithm in our graph
pair<vector<edge>, double> result = kruskal(edges);
return result.second;
}
int main() {
size_t n;
cin >> n;
vector<int> x(n), y(n);
for (size_t i = 0; i < n; i++) {
cin >> x[i] >> y[i];
}
cout << fixed << setprecision(10) << minimum_distance(x, y) << "\n";
}
| 24.834483
| 116
| 0.579006
|
cdlavila
|
a813227e81753b00849810d67580f4564b45f55f
| 968
|
hpp
|
C++
|
include/sharpen/AsyncReadWriteLock.hpp
|
iceBear67/Sharpen
|
4f00fb13a2b3e7dc26cdb34596d58f958eb341f8
|
[
"MIT"
] | 13
|
2020-10-25T04:02:07.000Z
|
2022-03-29T13:21:30.000Z
|
include/sharpen/AsyncReadWriteLock.hpp
|
iceBear67/Sharpen
|
4f00fb13a2b3e7dc26cdb34596d58f958eb341f8
|
[
"MIT"
] | 18
|
2020-10-09T04:51:03.000Z
|
2022-03-01T06:24:23.000Z
|
include/sharpen/AsyncReadWriteLock.hpp
|
iceBear67/Sharpen
|
4f00fb13a2b3e7dc26cdb34596d58f958eb341f8
|
[
"MIT"
] | 7
|
2020-10-23T04:25:28.000Z
|
2022-03-23T06:52:39.000Z
|
#pragma once
#ifndef _SHARPEN_ASYNCREADWRITELOCK_HPP
#define _SHARPEN_ASYNCREADWRITELOCK_HPP
#include <list>
#include "AwaitableFuture.hpp"
namespace sharpen
{
enum class ReadWriteLockState
{
Free,
SharedReading,
UniquedWriting
};
class AsyncReadWriteLock:public sharpen::Noncopyable,public sharpen::Nonmovable
{
private:
using MyFuture = sharpen::AwaitableFuture<void>;
using MyFuturePtr = MyFuture*;
using List = std::list<MyFuturePtr>;
sharpen::ReadWriteLockState state_;
List readWaiters_;
List writeWaiters_;
sharpen::SpinLock lock_;
sharpen::Uint32 readers_;
void WriteUnlock() noexcept;
void ReadUnlock() noexcept;
public:
AsyncReadWriteLock();
void LockReadAsync();
void LockWriteAsync();
void Unlock() noexcept;
~AsyncReadWriteLock() noexcept = default;
};
}
#endif
| 19.755102
| 83
| 0.646694
|
iceBear67
|
a813e0cbb9fa0a0e0053a8a103fd78a6322be976
| 1,396
|
hpp
|
C++
|
ext/src/java/util/Properties_XmlSupport.hpp
|
pebble2015/cpoi
|
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
|
[
"Apache-2.0"
] | null | null | null |
ext/src/java/util/Properties_XmlSupport.hpp
|
pebble2015/cpoi
|
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
|
[
"Apache-2.0"
] | null | null | null |
ext/src/java/util/Properties_XmlSupport.hpp
|
pebble2015/cpoi
|
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
|
[
"Apache-2.0"
] | null | null | null |
// Generated from /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/rt.jar
#pragma once
#include <java/io/fwd-POI.hpp>
#include <java/lang/fwd-POI.hpp>
#include <java/util/fwd-POI.hpp>
#include <sun/util/spi/fwd-POI.hpp>
#include <java/lang/Object.hpp>
struct default_init_tag;
class java::util::Properties_XmlSupport
: public virtual ::java::lang::Object
{
public:
typedef ::java::lang::Object super;
private:
static ::sun::util::spi::XmlPropertiesProvider* PROVIDER_;
/*void ctor(); (private) */
public: /* package */
static void load(Properties* props, ::java::io::InputStream* in);
/*static ::sun::util::spi::XmlPropertiesProvider* loadProvider(); (private) */
/*static ::sun::util::spi::XmlPropertiesProvider* loadProviderAsService(::java::lang::ClassLoader* cl); (private) */
/*static ::sun::util::spi::XmlPropertiesProvider* loadProviderFromProperty(::java::lang::ClassLoader* cl); (private) */
static void save(Properties* props, ::java::io::OutputStream* os, ::java::lang::String* comment, ::java::lang::String* encoding);
// Generated
public:
Properties_XmlSupport();
protected:
Properties_XmlSupport(const ::default_init_tag&);
public:
static ::java::lang::Class *class_();
private:
static ::sun::util::spi::XmlPropertiesProvider*& PROVIDER();
virtual ::java::lang::Class* getClass0();
};
| 29.702128
| 133
| 0.698424
|
pebble2015
|
a813ff369b15329f575fac851fe8a334b23785cd
| 6,424
|
cpp
|
C++
|
examples/06_duino/main/SSD1306UiDemo.cpp
|
graealex/qemu_esp32
|
d4d334d1cc53e6e517ac740c0d51e7e4b7afbd3e
|
[
"Apache-2.0"
] | 335
|
2016-10-12T06:59:33.000Z
|
2022-03-29T14:26:04.000Z
|
examples/06_duino/main/SSD1306UiDemo.cpp
|
graealex/qemu_esp32
|
d4d334d1cc53e6e517ac740c0d51e7e4b7afbd3e
|
[
"Apache-2.0"
] | 30
|
2016-10-30T11:23:59.000Z
|
2021-11-12T10:51:20.000Z
|
examples/06_duino/main/SSD1306UiDemo.cpp
|
graealex/qemu_esp32
|
d4d334d1cc53e6e517ac740c0d51e7e4b7afbd3e
|
[
"Apache-2.0"
] | 48
|
2016-10-30T08:41:13.000Z
|
2022-02-15T22:15:09.000Z
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2016 by Daniel Eichhorn
* Copyright (c) 2016 by Fabrice Weinberg
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
// Include the correct display library
// For a connection via I2C using Wire include
#include <Wire.h> // Only needed for Arduino 1.6.5 and earlier
#include "SSD1306.h" // alias for `#include "SSD1306Wire.h"`
// or #include "SH1106.h" alis for `#include "SH1106Wire.h"`
// For a connection via I2C using brzo_i2c (must be installed) include
// #include <brzo_i2c.h> // Only needed for Arduino 1.6.5 and earlier
// #include "SSD1306Brzo.h"
// #include "SH1106Brzo.h"
// For a connection via SPI include
// #include <SPI.h> // Only needed for Arduino 1.6.5 and earlier
// #include "SSD1306Spi.h"
// #include "SH1106SPi.h"
// Include the UI lib
#include "OLEDDisplayUi.h"
// Include custom images
#include "images.h"
// Use the corresponding display class:
// Initialize the OLED display using SPI
// D5 -> CLK
// D7 -> MOSI (DOUT)
// D0 -> RES
// D2 -> DC
// D8 -> CS
// SSD1306Spi display(D0, D2, D8);
// or
// SH1106Spi display(D0, D2);
// Initialize the OLED display using brzo_i2c
// D3 -> SDA
// D5 -> SCL
// SSD1306Brzo display(0x3c, D3, D5);
// or
// SH1106Brzo display(0x3c, D3, D5);
// Initialize the OLED display using Wire library
///SSD1306 display(0x3c, 5, 4);
// SH1106 display(0x3c, D3, D5);
extern SSD1306 display;
OLEDDisplayUi ui ( &display );
void msOverlay(OLEDDisplay *display, OLEDDisplayUiState* state) {
display->setTextAlignment(TEXT_ALIGN_RIGHT);
display->setFont(ArialMT_Plain_10);
display->drawString(128, 0, String(millis()));
}
void drawFrame1(OLEDDisplay *display, OLEDDisplayUiState* state, int16_t x, int16_t y) {
// draw an xbm image.
// Please note that everything that should be transitioned
// needs to be drawn relative to x and y
display->drawXbm(x + 34, y + 14, WiFi_Logo_width, WiFi_Logo_height, WiFi_Logo_bits);
}
void drawFrame2(OLEDDisplay *display, OLEDDisplayUiState* state, int16_t x, int16_t y) {
// Demonstrates the 3 included default sizes. The fonts come from SSD1306Fonts.h file
// Besides the default fonts there will be a program to convert TrueType fonts into this format
display->setTextAlignment(TEXT_ALIGN_LEFT);
display->setFont(ArialMT_Plain_10);
display->drawString(0 + x, 10 + y, "Arial 10");
display->setFont(ArialMT_Plain_16);
display->drawString(0 + x, 20 + y, "Arial 16");
display->setFont(ArialMT_Plain_24);
display->drawString(0 + x, 34 + y, "Arial 24");
}
void drawFrame3(OLEDDisplay *display, OLEDDisplayUiState* state, int16_t x, int16_t y) {
// Text alignment demo
display->setFont(ArialMT_Plain_10);
// The coordinates define the left starting point of the text
display->setTextAlignment(TEXT_ALIGN_LEFT);
display->drawString(0 + x, 11 + y, "Left aligned (0,10)");
// The coordinates define the center of the text
display->setTextAlignment(TEXT_ALIGN_CENTER);
display->drawString(64 + x, 22 + y, "Center aligned (64,22)");
// The coordinates define the right end of the text
display->setTextAlignment(TEXT_ALIGN_RIGHT);
display->drawString(128 + x, 33 + y, "Right aligned (128,33)");
}
void drawFrame4(OLEDDisplay *display, OLEDDisplayUiState* state, int16_t x, int16_t y) {
// Demo for drawStringMaxWidth:
// with the third parameter you can define the width after which words will be wrapped.
// Currently only spaces and "-" are allowed for wrapping
display->setTextAlignment(TEXT_ALIGN_LEFT);
display->setFont(ArialMT_Plain_10);
display->drawStringMaxWidth(0 + x, 10 + y, 128, "Lorem ipsum\n dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore.");
}
void drawFrame5(OLEDDisplay *display, OLEDDisplayUiState* state, int16_t x, int16_t y) {
}
// This array keeps function pointers to all frames
// frames are the single views that slide in
FrameCallback frames[] = { drawFrame1, drawFrame2, drawFrame3, drawFrame4, drawFrame5 };
// how many frames are there?
int frameCount = 5;
// Overlays are statically drawn on top of a frame eg. a clock
OverlayCallback overlays[] = { msOverlay };
int overlaysCount = 1;
void ui_setup() {
//Serial.begin(115200);
//Serial.println();
//Serial.println();
// The ESP is capable of rendering 60fps in 80Mhz mode
// but that won't give you much time for anything else
// run it in 160Mhz mode or just set it to 30 fps
ui.setTargetFPS(60);
// Customize the active and inactive symbol
ui.setActiveSymbol(activeSymbol);
ui.setInactiveSymbol(inactiveSymbol);
// You can change this to
// TOP, LEFT, BOTTOM, RIGHT
ui.setIndicatorPosition(BOTTOM);
// Defines where the first frame is located in the bar.
ui.setIndicatorDirection(LEFT_RIGHT);
// You can change the transition that is used
// SLIDE_LEFT, SLIDE_RIGHT, SLIDE_UP, SLIDE_DOWN
ui.setFrameAnimation(SLIDE_LEFT);
// Add frames
ui.setFrames(frames, frameCount);
// Add overlays
ui.setOverlays(overlays, overlaysCount);
// Initialising the UI will init the display too.
ui.init();
display.flipScreenVertically();
}
void ui_loop() {
int remainingTimeBudget = ui.update();
if (remainingTimeBudget > 0) {
// You can do some work here
// Don't do stuff if you are below your
// time budget.
delay(remainingTimeBudget);
}
}
| 33.458333
| 162
| 0.721669
|
graealex
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.