blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
b002a1b4ef2fd434925eca100b9e3f9044c4d9fb
84283cea46b67170bb50f22dcafef2ca6ddaedff
/Codeforces/664/C.cpp
611fb3fe008ed52f4224aeafa8b5e7ed2d27a563
[]
no_license
ssyze/Codes
b36fedf103c18118fd7375ce7a40e864dbef7928
1376c40318fb67a7912f12765844f5eefb055c13
refs/heads/master
2023-01-09T18:36:05.417233
2020-11-03T15:45:45
2020-11-03T15:45:45
282,236,294
0
0
null
null
null
null
UTF-8
C++
false
false
733
cpp
/* * @Date : 2020-08-14 18:16:46 * @Author : ssyze * @Description : */ #include <bits/stdc++.h> using namespace std; int n, m; int a[205], b[205], ans; bool check(int x) { for (int i = 1; i <= n; i++) { int tmp = -1; for (int j = 1; j <= m; j++) { tmp = x | a[i] & b[j]; if (tmp == x) break; } if (tmp != x) return 0; } return 1; } int main() { ios::sync_with_stdio(0); cin.tie(0); cin >> n >> m; for (int i = 1; i <= n; i++) cin >> a[i]; for (int i = 1; i <= m; i++) cin >> b[i]; for (int i = 0; i < 1 << 9; i++) { if (check(i)) { ans = i; break; } } cout << ans << endl; }
[ "46869158+shu-ssyze@users.noreply.github.com" ]
46869158+shu-ssyze@users.noreply.github.com
40c5f8a903bf1c85b612f78e4a264722d2be0d26
ece30e7058d8bd42bc13c54560228bd7add50358
/DataCollector/mozilla/xulrunner-sdk/include/inISearchObserver.h
29da8f065f5107903f637af244926e320ce741a3
[ "Apache-2.0" ]
permissive
andrasigneczi/TravelOptimizer
b0fe4d53f6494d40ba4e8b98cc293cb5451542ee
b08805f97f0823fd28975a36db67193386aceb22
refs/heads/master
2022-07-22T02:07:32.619451
2018-12-03T13:58:21
2018-12-03T13:58:21
53,926,539
1
0
Apache-2.0
2022-07-06T20:05:38
2016-03-15T08:16:59
C++
UTF-8
C++
false
false
4,849
h
/* * DO NOT EDIT. THIS FILE IS GENERATED FROM ../../../dist/idl\inISearchObserver.idl */ #ifndef __gen_inISearchObserver_h__ #define __gen_inISearchObserver_h__ #ifndef __gen_nsISupports_h__ #include "nsISupports.h" #endif /* For IDL files that don't want to include root IDL files. */ #ifndef NS_NO_VTABLE #define NS_NO_VTABLE #endif class inISearchProcess; /* forward declaration */ /* starting interface: inISearchObserver */ #define INISEARCHOBSERVER_IID_STR "46226d9b-e398-4106-8d9b-225d4d0589f5" #define INISEARCHOBSERVER_IID \ {0x46226d9b, 0xe398, 0x4106, \ { 0x8d, 0x9b, 0x22, 0x5d, 0x4d, 0x05, 0x89, 0xf5 }} class NS_NO_VTABLE inISearchObserver : public nsISupports { public: NS_DECLARE_STATIC_IID_ACCESSOR(INISEARCHOBSERVER_IID) enum { IN_SUCCESS = 1, IN_INTERRUPTED = 2, IN_ERROR = 3 }; /* void onSearchStart (in inISearchProcess aModule); */ NS_IMETHOD OnSearchStart(inISearchProcess *aModule) = 0; /* void onSearchResult (in inISearchProcess aModule); */ NS_IMETHOD OnSearchResult(inISearchProcess *aModule) = 0; /* void onSearchEnd (in inISearchProcess aModule, in short aResult); */ NS_IMETHOD OnSearchEnd(inISearchProcess *aModule, int16_t aResult) = 0; /* void onSearchError (in inISearchProcess aModule, in AString aMessage); */ NS_IMETHOD OnSearchError(inISearchProcess *aModule, const nsAString & aMessage) = 0; }; NS_DEFINE_STATIC_IID_ACCESSOR(inISearchObserver, INISEARCHOBSERVER_IID) /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_INISEARCHOBSERVER \ NS_IMETHOD OnSearchStart(inISearchProcess *aModule) override; \ NS_IMETHOD OnSearchResult(inISearchProcess *aModule) override; \ NS_IMETHOD OnSearchEnd(inISearchProcess *aModule, int16_t aResult) override; \ NS_IMETHOD OnSearchError(inISearchProcess *aModule, const nsAString & aMessage) override; /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_INISEARCHOBSERVER(_to) \ NS_IMETHOD OnSearchStart(inISearchProcess *aModule) override { return _to OnSearchStart(aModule); } \ NS_IMETHOD OnSearchResult(inISearchProcess *aModule) override { return _to OnSearchResult(aModule); } \ NS_IMETHOD OnSearchEnd(inISearchProcess *aModule, int16_t aResult) override { return _to OnSearchEnd(aModule, aResult); } \ NS_IMETHOD OnSearchError(inISearchProcess *aModule, const nsAString & aMessage) override { return _to OnSearchError(aModule, aMessage); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_INISEARCHOBSERVER(_to) \ NS_IMETHOD OnSearchStart(inISearchProcess *aModule) override { return !_to ? NS_ERROR_NULL_POINTER : _to->OnSearchStart(aModule); } \ NS_IMETHOD OnSearchResult(inISearchProcess *aModule) override { return !_to ? NS_ERROR_NULL_POINTER : _to->OnSearchResult(aModule); } \ NS_IMETHOD OnSearchEnd(inISearchProcess *aModule, int16_t aResult) override { return !_to ? NS_ERROR_NULL_POINTER : _to->OnSearchEnd(aModule, aResult); } \ NS_IMETHOD OnSearchError(inISearchProcess *aModule, const nsAString & aMessage) override { return !_to ? NS_ERROR_NULL_POINTER : _to->OnSearchError(aModule, aMessage); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class inSearchObserver : public inISearchObserver { public: NS_DECL_ISUPPORTS NS_DECL_INISEARCHOBSERVER inSearchObserver(); private: ~inSearchObserver(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS(inSearchObserver, inISearchObserver) inSearchObserver::inSearchObserver() { /* member initializers and constructor code */ } inSearchObserver::~inSearchObserver() { /* destructor code */ } /* void onSearchStart (in inISearchProcess aModule); */ NS_IMETHODIMP inSearchObserver::OnSearchStart(inISearchProcess *aModule) { return NS_ERROR_NOT_IMPLEMENTED; } /* void onSearchResult (in inISearchProcess aModule); */ NS_IMETHODIMP inSearchObserver::OnSearchResult(inISearchProcess *aModule) { return NS_ERROR_NOT_IMPLEMENTED; } /* void onSearchEnd (in inISearchProcess aModule, in short aResult); */ NS_IMETHODIMP inSearchObserver::OnSearchEnd(inISearchProcess *aModule, int16_t aResult) { return NS_ERROR_NOT_IMPLEMENTED; } /* void onSearchError (in inISearchProcess aModule, in AString aMessage); */ NS_IMETHODIMP inSearchObserver::OnSearchError(inISearchProcess *aModule, const nsAString & aMessage) { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif #endif /* __gen_inISearchObserver_h__ */
[ "andras.igneczi@doclerholding.com" ]
andras.igneczi@doclerholding.com
6012ca05c2717b3569125d182643f2d3b80de035
ac363c08f47ae63962abe9dbab909b1cd9547c43
/lib/arda2/math/matIntVector4.cpp
c87f2619553d6b505651a51bde0fbd15ea9baf2f
[]
no_license
naturalleo/game_login
5f474988746bcc3a0f55acd8b5d899dd405c62d2
473f8ab5db8ef4d959cf8a7946118ebf993f8802
refs/heads/master
2022-12-14T15:51:19.903843
2020-09-18T09:41:28
2020-09-18T09:41:28
294,059,361
1
1
null
null
null
null
UTF-8
C++
false
false
491
cpp
#include "arda2/math/matFirst.h" #include "arda2/math/matIntVector4.h" const matIntVector4 matIntVector4::Zero(matZero); const matIntVector4 matIntVector4::Max(matMaximum); const matIntVector4 matIntVector4::Min(matMinimum); void matIntVector4::StoreComponentClamp( const matIntVector4& min, const matIntVector4& max) { // componentwise clamp x = matClamp(x, min.x, max.x); y = matClamp(y, min.y, max.y); z = matClamp(z, min.z, max.z); w = matClamp(w, min.w, max.w); }
[ "136034343@qq.com" ]
136034343@qq.com
7604bd7c0107b08e6686107f36745e3e16ef461a
afc088475e7d972b672772eaf02c2476544fbfc6
/loadouts/RU_EMR.hpp
f41f7aafa59197fbc3a7d286fcf5a741462ce14d
[]
no_license
xrufix/Loadouts
32c42890875f971cbe19fd06db3a47c8d47f530e
58a49af39ab2b4ff072f562e1c30394885f6b880
refs/heads/master
2021-01-01T15:34:14.664103
2019-05-27T21:18:32
2019-05-27T21:18:32
97,648,349
0
0
null
null
null
null
UTF-8
C++
false
false
5,443
hpp
#include "RU_FLORA.hpp" /* ###################### - UNIFORMS - ###################### */ #define UNIFORM_SINGLE "rhs_uniform_vdv_emr" // Für Inventar #define UNIFORM ARR_1(UNIFORM_SINGLE) // Für Zufallsauswahl #define UNIFORM_COMPANY UNIFORM #define UNIFORM_RECON UNIFORM /* ###################### - VESTS - ###################### */ #define VEST_EMPTY "rhs_6b23_digi" #define VEST_OFFICER "rhs_6b23_digi_crewofficer" #define VEST_LIGHT "rhs_6b23_digi_6sh92_spetsnaz2" #define VEST_RM ARR_2("rhs_6b23_6sh116","rhs_6b23_digi_6sh92") #define VEST_GR ARR_2("rhs_6b23_6sh116_vog","rhs_6b23_digi_6sh92_vog") #define VEST_CM "rhs_6b23_digi_medic" #define VEST_TL ARR_2("rhs_6b23_digi_6sh92_headset","rhs_6b23_digi_6sh92_radio") #define VEST_SL ARR_2("rhs_6b23_digi_6sh92_vog_headset","rhs_6b23_digi_6sh92_Vog_Radio_Spetsnaz") #define VEST_MG VEST_RM #define VEST_DM VEST_RM #define VEST_CREW "rhs_6b23_crew" #define VEST_RECON VEST_TL #define VEST_RECON_TL VEST_SL #define VEST_RECON_MG VEST_RECON #define VEST_RECON_GR VEST_SL #define VEST_BREATHER ARR_1("V_RebreatherIR") #define VEST_DIVER VEST_RECON /* ###################### - ATTACHMENTS- ###################### */ #define LASERPOINTER "rhs_acc_perst1ik_ris" #define SNIPER_OPTIC_NV "ace_banana" /* ###################### - PRIMARY WEAPONS - ###################### */ // STANDARD ISSUE ASSAULT RIFLE #define RIFLE_CCO WEAPON_OLD(RIFLE,"rhs_acc_1p63","rhs_acc_2dpZenit","rhs_acc_dtk2") #define RIFLE_RCO WEAPON_OLD(RIFLE,"rhs_acc_pkas","rhs_acc_2dpZenit","rhs_acc_dtk2") #define MAG_RIFLE ARR_1("rhs_30Rnd_545x39_7N22_AK") #define MAG_RIFLE_TRACER ARR_1("rhs_30Rnd_545x39_AK_plum_green") // GRENADIER ASSAULT RIFLE #define RIFLE_UGL_CCO WEAPON_OLD(RIFLE_UGL,"rhs_acc_1p63","","rhs_acc_dtk2") #define RIFLE_UGL_RCO WEAPON_OLD(RIFLE_UGL,"rhs_acc_pkas","","rhs_acc_dtk3") // CARBINE // SF CARBINES #define RIFLE_RECON WEAPON_OLD("hlc_rifle_ak12","rhs_acc_1p87","rhs_acc_perst3","rhs_acc_tgpa") #define RIFLE_UGL_RECON WEAPON_OLD("hlc_rifle_ak12GL","rhs_acc_rakurspm","rhs_acc_perst3","rhs_acc_tgpa") #define RIFLE_RECON_TAN WEAPON_OLD("rhs_weap_ak74m_camo","rhs_acc_pkas","rhs_acc_perst3","rhs_acc_tgpa") #define RIFLE_UGL_RECON_TAN RIFLE_UGL_RECON #define RIFLE_DIVER RIFLE_RECON #define RIFLE_UGL_DIVER RIFLE_UGL_RECON #define MAG_RIFLE_RECON "hlc_30Rnd_545x39_B_AK_Plum" #define MAG_RIFLE_RECON_TRACER "hlc_30Rnd_545x39_t_ak_Black" // DESIGNATED MARKSMAN RIFLES & SNIPER RIFLES #define DMR WEAPON_OLD("rhs_weap_svdp","rhs_acc_pso1m21","","") #define MAG_DMR "rhs_10Rnd_762x54mmR_7N1" #define DMR_RECON WEAPON_OLD("rhs_weap_vss_grip","rhs_acc_pso1m21","rhs_acc_perst1ik_ris","") #define DMR_DIVER DMR_RECON #define MAG_DMR_RECON ARR_1("rhs_20rnd_9x39mm_SP5") #define SR_AP WEAPON_OLD("rhs_weap_t5000","rhs_acc_dh520x56","bipod_02_F_blk","") #define MAGS_SR_AP ARR_2("rhs_5Rnd_338lapua_t5000",20) #define SR_AM WEAPON_OLD("CUP_srifle_ksvk","CUP_optic_PSO_3","","") #define MAGS_SR_AM ARR_2("CUP_5Rnd_127x108_KSVK_M",10) // AUTOMATIC RIFLES & MACHINE GUNS #define MAG_AUTORIFLE "hlc_45Rnd_545x39_m_rpkm" #define AUTORIFLE_RECON WEAPON_OLD("hlc_rifle_RPK12","rhs_acc_1p87","rhs_acc_perst1ik_ris","rhs_acc_dtk4short") #define MAGS_AUTORIFLE_RECON ARR_2("hlc_60Rnd_545x39_t_rpk",8) #define MMG "rhs_weap_pkp" /* ###################### - SIDEARMS - ###################### */ #define PISTOL WEAPON_OLD("hgun_Rook40_F","","","") #define MAG_PISTOL ARR_1("16Rnd_9x21_Mag") #define PISTOL_SF WEAPON_OLD("hgun_Rook40_F","muzzle_snds_l","","") #define MAG_PISTOL_SF ARR_1("16Rnd_9x21_Mag") /* ###################### - LAUNCHERS - ###################### */ #define AT_LIGHT WEAPON_OLD("rhs_weap_rpg7","rhs_acc_pgo7v2","","") #define MAGS_AT_LIGHT ARR_3("rhs_rpg7_PG7VR_mag","rhs_rpg7_PG7VL_mag","rhs_rpg7_OG7V_mag") #define AT_ROCKET WEAPON_OLD("rhs_weap_rpg7","rhs_acc_pgo7v3","","") #define MAGS_AT_ROCKET ARR_3("rhs_rpg7_PG7VR_mag",2,"rhs_rpg7_TBG7V_mag") #define MAGS_AT_ROCKET_ASST ARR_4("rhs_rpg7_PG7VR_mag",3,"rhs_rpg7_OG7V_mag",3) #define AA_MISSILE WEAPON_OLD("rhs_weap_igla","","","") #define MAGS_AA_MISSILE ARR_1("rhs_mag_9k38_rocket") #define MAGS_AA_MISSILE_ASST ARR_2("rhs_mag_9k38_rocket",2) #define AT_MISSILE WEAPON_OLD("CUP_launch_Metis","","","") #define MAGS_AT_MISSILE ARR_1("CUP_AT13_M") #define MAGS_AT_MISSILE_ASST ARR_1("CUP_AT13_M") /* ###################### - HEADGEAR - ###################### */ #define HELMET ARR_1("rhs_6b28") #define HELMET_BARE "rhs_6b28_green" #define HELMET_SF "rhs_6b47" // COMMANDERS #define CAP_OFFICER ARR_2("rhs_fieldcap_digi2","rhs_fieldcap_digi") /* ###################### - RADIOS - ###################### */ #define RADIO_SR "ACRE_SEM52SL" /* ###################### - GOGGLES / FACEWEAR - ###################### */ #define GOGGLES ARR_2("","rhs_scarf") #define GOGGLES_OFFICER ARR_3("","G_Spectacles","G_Aviator") #define GOGGLES_FULL ARR_1("G_Lowprofile") #define GOGGLES_SF ARR_1("G_Balaclava_oli") #define GOGGLES_SF_FULL ARR_1("G_Balaclava_lowprofile") #define GOGGLES_DIVER ARR_1("G_I_Diving") #define GOGGLES_PILOT ARR_1("G_Aviator")
[ "stefan@ruhfass.com" ]
stefan@ruhfass.com
e9a75d12ea519da123403f8ab7c0791c5e59a2c0
dd1a7278930b01d83805111d2a334f5a5f02c76d
/glmock/framework.cpp
2e093f82685a4c3fb0a7f153a867fa86a9e9a77f
[]
no_license
perandersson/glmock
b44177809bc15a1de58894ed0674e9a4ed6ebbb2
cdc62bc7614bdad899ba23f8bd290cc9a767d883
refs/heads/master
2020-04-19T01:18:17.107814
2013-07-02T09:15:58
2013-07-02T09:15:58
10,435,181
5
0
null
null
null
null
UTF-8
C++
false
false
3,190
cpp
#include "framework.h" #include "impl/gl_framework.h" #include <sstream> namespace glmock { // // The default error callback listener. This will cause the exception {@code glmock::IMockException} to be thrown // with the complete information regarding all the errors if any error where raised. class ExceptionErrorCallback : public IErrorCallback { public: ExceptionErrorCallback(); virtual ~ExceptionErrorCallback(); public: virtual void OnFunctionNotCalled(const char* expected); virtual void OnBadParameter(const char* function, const char* name, const char* expected, const char* actual); virtual void OnBadFunctionCalled(const char* expected, const char* actual); virtual void OnUnspecifiedFunctionCalled(const char* expected); private: std::vector<CommandError> mErrors; }; /////////////////////////////////////////////////////////////////// ExceptionErrorCallback::ExceptionErrorCallback() { } ExceptionErrorCallback::~ExceptionErrorCallback() { if(!mErrors.empty()) { CommandError* errors = new CommandError[mErrors.size()]; for(size_t i = 0; i < mErrors.size(); ++i) { memcpy(&errors[i], &mErrors[i], sizeof(CommandError)); } throw ValidationException(errors, mErrors.size()); } } void ExceptionErrorCallback::OnFunctionNotCalled(const char* expected) { // Expected function 'glGetError' to be called, but wasn't char tmp[512] = {0}; sprintf(tmp, "Expected function '%s' to be called, but wasn't", expected); CommandError cmd; strcpy_s(cmd.Command, 50, expected); strcpy_s(cmd.Error, 512, tmp); mErrors.push_back(cmd); } void ExceptionErrorCallback::OnBadParameter(const char* function, const char* name, const char* expected, const char* actual) { // Parameter 'sfactor' on function 'glTexParameteri' expected to be 'GL_NONE', but was 'GL_SRC_ALPHA' char tmp[512] = {0}; sprintf(tmp, "Parameter '%s' on function '%s' expected to be '%s', but was '%s'", name, function, expected, actual); CommandError cmd; strcpy_s(cmd.Command, 50, function); strcpy_s(cmd.Error, 512, tmp); mErrors.push_back(cmd); } void ExceptionErrorCallback::OnBadFunctionCalled(const char* expected, const char* actual) { // Expected function 'glGetError', but was 'glGenTextures' char tmp[512] = {0}; sprintf(tmp, "Expected function '%s', but was '%s'", expected, actual); CommandError cmd; strcpy_s(cmd.Command, 50, expected); strcpy_s(cmd.Error, 512, tmp); mErrors.push_back(cmd); } void ExceptionErrorCallback::OnUnspecifiedFunctionCalled(const char* expected) { // Expected function 'glGetError' but no function call has been registered char tmp[512] = {0}; sprintf(tmp, "Expected function '%s' but no function call has been registered", expected); CommandError cmd; strcpy_s(cmd.Command, 50, expected); strcpy_s(cmd.Error, 512, tmp); mErrors.push_back(cmd); } /////////////////////////////////////////////////////////////////// IFramework* Create() { return new GLFramework(new ExceptionErrorCallback()); } IFramework* Create(IErrorCallback* callback) { return new GLFramework(callback); } void Destroy(IFramework* framework) { delete framework; } }
[ "dim.raven@gmail.com" ]
dim.raven@gmail.com
12ee688df196b2d467a6f97ea88f6191031ff5fd
45ab5256040b5160b97c6786accb8a60dd4fa0bf
/tests/Video/VideoSuite.hpp
c85454079437f26f9a22792e5f1f601d38134283
[ "MIT", "LicenseRef-scancode-public-domain" ]
permissive
Chainsawkitten/HymnToBeauty
9e5cb541661a9bdb8e8ee791df8e1f5bd9a790e4
c3d869482f031a792c1c54c0f78d4cda47c6da09
refs/heads/main
2023-07-27T12:40:27.342516
2023-06-23T13:15:05
2023-06-23T14:08:14
33,508,463
11
4
MIT
2023-06-23T14:08:15
2015-04-06T22:09:26
C++
UTF-8
C++
false
false
4,251
hpp
#pragma once #include <Framework/TestSuite.hpp> #include <Video/Renderer.hpp> namespace Video { class LowLevelRenderer; } namespace Utility { class Window; } /// Suite testing the Video module. class VideoSuite : public TestSuite { public: /// Create a new video suite. /** * @param graphicsAPI Which graphics API to use. */ explicit VideoSuite(Video::Renderer::GraphicsAPI graphicsAPI); /// Destructor. ~VideoSuite() {}; /// Initialize the test suite. void Init(); /// Shut down the test suite. void Shutdown(); /// Width and height of the swapchain. static const unsigned int swapchainSize = 128; private: Video::Renderer::GraphicsAPI graphicsAPI; Video::LowLevelRenderer* lowLevelRenderer; Utility::Window* window; }; /// Draw a colored triangle generated in the shader based on vertex index. /** * @param data The low-level renderer. * * @return Whether the test was successful. */ Result DrawTriangle(void* data); /// Draw a colored triangle from a vertex buffer. /** * @param data The low-level renderer. * * @return Whether the test was successful. */ Result DrawVertexTriangle(void* data); /// Draw a textured triangle. /** * @param data The low-level renderer. * * @return Whether the test was successful. */ Result DrawTexturedTriangle(void* data); /// Draw a quad using a vertex and index buffer. /** * @param data The low-level renderer. * * @return Whether the test was successful. */ Result DrawQuad(void* data); /// Draw two colored triangles, offset by a model matrix in uniform buffer and using a depth buffer. /** * @param data The low-level renderer. * * @return Whether the test was successful. */ Result DrawTriangles(void* data); /// Draw two colored triangles, offset by a model matrix in push constants. /** * @param data The low-level renderer. * * @return Whether the test was successful. */ Result DrawPushTriangles(void* data); /// Draw a triangle using vertex pulling from a storage buffer. /** * @param data The low-level renderer. * * @return Whether the test was successful. */ Result DrawStorageTriangle(void* data); /// Draw two triangles, then invert the colors. /** * @param data The low-level renderer. * * @return Whether the test was successful. */ Result InvertColors(void* data); /// Draw a mipmapped triangle. /** * @param data The low-level renderer. * * @return Whether the test was successful. */ Result DrawMipmappedTriangle(void* data); /// Use a depth pre-pass to occlude some fragments. /** * @param data The low-level renderer. * * @return Whether the test was successful. */ Result DepthPrePass(void* data); /// Draw lines with width. /** * @param data The low-level renderer. * * @return Whether the test was successful. */ Result DrawLines(void* data); /// Test attachmentless rendering. /** * @param data The low-level renderer. * * @return Whether the test was successful. */ Result Attachmentless(void* data); /// Test conservative rasterization. /** * @param data The low-level renderer. * * @return Whether the test was successful. */ Result ConservativeRasterization(void* data); /// Test depth clamping. /** * @param data The low-level renderer. * * @return Whether the test was successful. */ Result DepthClamping(void* data); /// Test rendering multiple frames. /** * @param data The low-level renderer. * * @return Whether the test was successful. */ Result MultipleFrames(void* data); /// Test setting buffer contents in a compute shader. /** * @param data The low-level renderer. * * @return Whether the test was successful. */ Result ComputeSetBuffer(void* data); /// Test writing vertex buffer contents in a compute shader. /** * @param data The low-level renderer. * * @return Whether the test was successful. */ Result ComputeVertexBuffer(void* data); /// Test using multiple storage buffers in a compute shaders. /** * @param data The low-level renderer. * * @return Whether the test was successful. */ Result ComputeMultipleBuffers(void* data); /// Test using ClearBuffer. /** * @param data The low-level renderer. * * @return Whether the test was successful. */ Result ComputeClearBuffer(void* data);
[ "catscratchesp@gmail.com" ]
catscratchesp@gmail.com
1a04690ce703fc27c34595459a6c98b6a5ef4403
d0c44dd3da2ef8c0ff835982a437946cbf4d2940
/cmake-build-debug/programs_tiling/function14163/function14163_schedule_6/function14163_schedule_6_wrapper.cpp
9cf92a978da778a7ab291139fc6bb2402065880a
[]
no_license
IsraMekki/tiramisu_code_generator
8b3f1d63cff62ba9f5242c019058d5a3119184a3
5a259d8e244af452e5301126683fa4320c2047a3
refs/heads/master
2020-04-29T17:27:57.987172
2019-04-23T16:50:32
2019-04-23T16:50:32
176,297,755
1
2
null
null
null
null
UTF-8
C++
false
false
999
cpp
#include "Halide.h" #include "function14163_schedule_6_wrapper.h" #include "tiramisu/utils.h" #include <cstdlib> #include <iostream> #include <time.h> #include <fstream> #include <chrono> #define MAX_RAND 200 int main(int, char **){ Halide::Buffer<int32_t> buf00(1024, 256); Halide::Buffer<int32_t> buf01(1024, 256); Halide::Buffer<int32_t> buf0(256, 1024, 256); init_buffer(buf0, (int32_t)0); auto t1 = std::chrono::high_resolution_clock::now(); function14163_schedule_6(buf00.raw_buffer(), buf01.raw_buffer(), buf0.raw_buffer()); auto t2 = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> diff = t2 - t1; std::ofstream exec_times_file; exec_times_file.open("../data/programs/function14163/function14163_schedule_6/exec_times.txt", std::ios_base::app); if (exec_times_file.is_open()){ exec_times_file << diff.count() * 1000000 << "us" <<std::endl; exec_times_file.close(); } return 0; }
[ "ei_mekki@esi.dz" ]
ei_mekki@esi.dz
7677d38b1b4a0cde5cc1eee7791fdf0b13a0b8ce
0eef685450b756845a67ced37125848c4a028aed
/libs/dmlf/include/dmlf/execution/vm_state.hpp
c5a4ae524e2b7890092624fdbb896c73b707b399
[ "Apache-2.0", "LicenseRef-scancode-unknown", "LicenseRef-scancode-unknown-license-reference" ]
permissive
vhavrylov-ncube/ledger
b144606e2c4c74ee83b431cce34e5b22422f7292
1e216c304aea344e8ef88e1954658ff665f4f4ac
refs/heads/master
2020-09-09T13:56:09.745391
2020-01-16T15:08:29
2020-01-16T15:08:29
221,464,124
0
0
Apache-2.0
2019-11-13T13:20:44
2019-11-13T13:20:44
null
UTF-8
C++
false
false
1,718
hpp
#pragma once //------------------------------------------------------------------------------ // // Copyright 2018-2020 Fetch.AI Limited // // 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 "vm/io_observer_interface.hpp" #include "core/byte_array/const_byte_array.hpp" #include "vm/vm.hpp" #include <memory> #include <unordered_map> namespace fetch { namespace dmlf { class VmState : public vm::IoObserverInterface { public: VmState() = default; VmState(VmState &&other) noexcept = default; VmState &operator=(VmState &&other) noexcept = default; VmState(VmState const &other) = delete; VmState &operator=(VmState const &other) = delete; Status Read(std::string const &key, void *data, uint64_t &size) override; Status Write(std::string const &key, void const *data, uint64_t size) override; Status Exists(std::string const &key) override; VmState DeepCopy() const; private: using Buffer = fetch::byte_array::ConstByteArray; using Store = std::unordered_map<std::string, Buffer>; Store store_; }; } // namespace dmlf } // namespace fetch
[ "42541508+fetch-bot@users.noreply.github.com" ]
42541508+fetch-bot@users.noreply.github.com
02891f7e14192174c18c400e77c414e537ef774e
d7064f934212f95b897afde0dad4dacafe393aaa
/src/qt/transactiontablemodel.cpp
be33872d06b2f1722b1cb5fd0576aaa308f9744c
[ "MIT" ]
permissive
mirzaei-ce/core-javabit
0e382eea4e3e688aac531088818caa41bc84590d
bfc1f145268455ca788c8a0b70fb3f054e4287f9
refs/heads/master
2021-07-23T12:13:04.992774
2017-11-02T12:27:50
2017-11-02T12:27:50
109,261,835
0
0
null
null
null
null
UTF-8
C++
false
false
25,913
cpp
// Copyright (c) 2011-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "transactiontablemodel.h" #include "addresstablemodel.h" #include "guiconstants.h" #include "guiutil.h" #include "optionsmodel.h" #include "platformstyle.h" #include "transactiondesc.h" #include "transactionrecord.h" #include "walletmodel.h" #include "core_io.h" #include "main.h" #include "sync.h" #include "uint256.h" #include "util.h" #include "wallet/wallet.h" #include <QColor> #include <QDateTime> #include <QDebug> #include <QIcon> #include <QList> #include <boost/foreach.hpp> // Amount column is right-aligned it contains numbers static int column_alignments[] = { Qt::AlignLeft|Qt::AlignVCenter, /* status */ Qt::AlignLeft|Qt::AlignVCenter, /* watchonly */ Qt::AlignLeft|Qt::AlignVCenter, /* date */ Qt::AlignLeft|Qt::AlignVCenter, /* type */ Qt::AlignLeft|Qt::AlignVCenter, /* address */ Qt::AlignRight|Qt::AlignVCenter /* amount */ }; // Comparison operator for sort/binary search of model tx list struct TxLessThan { bool operator()(const TransactionRecord &a, const TransactionRecord &b) const { return a.hash < b.hash; } bool operator()(const TransactionRecord &a, const uint256 &b) const { return a.hash < b; } bool operator()(const uint256 &a, const TransactionRecord &b) const { return a < b.hash; } }; // Private implementation class TransactionTablePriv { public: TransactionTablePriv(CWallet *wallet, TransactionTableModel *parent) : wallet(wallet), parent(parent) { } CWallet *wallet; TransactionTableModel *parent; /* Local cache of wallet. * As it is in the same order as the CWallet, by definition * this is sorted by sha256. */ QList<TransactionRecord> cachedWallet; /* Query entire wallet anew from core. */ void refreshWallet() { qDebug() << "TransactionTablePriv::refreshWallet"; cachedWallet.clear(); { LOCK2(cs_main, wallet->cs_wallet); for(std::map<uint256, CWalletTx>::iterator it = wallet->mapWallet.begin(); it != wallet->mapWallet.end(); ++it) { if(TransactionRecord::showTransaction(it->second)) cachedWallet.append(TransactionRecord::decomposeTransaction(wallet, it->second)); } } } /* Update our model of the wallet incrementally, to synchronize our model of the wallet with that of the core. Call with transaction that was added, removed or changed. */ void updateWallet(const uint256 &hash, int status, bool showTransaction) { qDebug() << "TransactionTablePriv::updateWallet: " + QString::fromStdString(hash.ToString()) + " " + QString::number(status); // Find bounds of this transaction in model QList<TransactionRecord>::iterator lower = qLowerBound( cachedWallet.begin(), cachedWallet.end(), hash, TxLessThan()); QList<TransactionRecord>::iterator upper = qUpperBound( cachedWallet.begin(), cachedWallet.end(), hash, TxLessThan()); int lowerIndex = (lower - cachedWallet.begin()); int upperIndex = (upper - cachedWallet.begin()); bool inModel = (lower != upper); if(status == CT_UPDATED) { if(showTransaction && !inModel) status = CT_NEW; /* Not in model, but want to show, treat as new */ if(!showTransaction && inModel) status = CT_DELETED; /* In model, but want to hide, treat as deleted */ } qDebug() << " inModel=" + QString::number(inModel) + " Index=" + QString::number(lowerIndex) + "-" + QString::number(upperIndex) + " showTransaction=" + QString::number(showTransaction) + " derivedStatus=" + QString::number(status); switch(status) { case CT_NEW: if(inModel) { qWarning() << "TransactionTablePriv::updateWallet: Warning: Got CT_NEW, but transaction is already in model"; break; } if(showTransaction) { LOCK2(cs_main, wallet->cs_wallet); // Find transaction in wallet std::map<uint256, CWalletTx>::iterator mi = wallet->mapWallet.find(hash); if(mi == wallet->mapWallet.end()) { qWarning() << "TransactionTablePriv::updateWallet: Warning: Got CT_NEW, but transaction is not in wallet"; break; } // Added -- insert at the right position QList<TransactionRecord> toInsert = TransactionRecord::decomposeTransaction(wallet, mi->second); if(!toInsert.isEmpty()) /* only if something to insert */ { parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex+toInsert.size()-1); int insert_idx = lowerIndex; Q_FOREACH(const TransactionRecord &rec, toInsert) { cachedWallet.insert(insert_idx, rec); insert_idx += 1; } parent->endInsertRows(); } } break; case CT_DELETED: if(!inModel) { qWarning() << "TransactionTablePriv::updateWallet: Warning: Got CT_DELETED, but transaction is not in model"; break; } // Removed -- remove entire transaction from table parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex-1); cachedWallet.erase(lower, upper); parent->endRemoveRows(); break; case CT_UPDATED: // Miscellaneous updates -- nothing to do, status update will take care of this, and is only computed for // visible transactions. break; } } int size() { return cachedWallet.size(); } TransactionRecord *index(int idx) { if(idx >= 0 && idx < cachedWallet.size()) { TransactionRecord *rec = &cachedWallet[idx]; // Get required locks upfront. This avoids the GUI from getting // stuck if the core is holding the locks for a longer time - for // example, during a wallet rescan. // // If a status update is needed (blocks came in since last check), // update the status of this transaction from the wallet. Otherwise, // simply re-use the cached status. TRY_LOCK(cs_main, lockMain); if(lockMain) { TRY_LOCK(wallet->cs_wallet, lockWallet); if(lockWallet && rec->statusUpdateNeeded()) { std::map<uint256, CWalletTx>::iterator mi = wallet->mapWallet.find(rec->hash); if(mi != wallet->mapWallet.end()) { rec->updateStatus(mi->second); } } } return rec; } return 0; } QString describe(TransactionRecord *rec, int unit) { { LOCK2(cs_main, wallet->cs_wallet); std::map<uint256, CWalletTx>::iterator mi = wallet->mapWallet.find(rec->hash); if(mi != wallet->mapWallet.end()) { return TransactionDesc::toHTML(wallet, mi->second, rec, unit); } } return QString(); } QString getTxHex(TransactionRecord *rec) { LOCK2(cs_main, wallet->cs_wallet); std::map<uint256, CWalletTx>::iterator mi = wallet->mapWallet.find(rec->hash); if(mi != wallet->mapWallet.end()) { std::string strHex = EncodeHexTx(static_cast<CTransaction>(mi->second)); return QString::fromStdString(strHex); } return QString(); } }; TransactionTableModel::TransactionTableModel(const PlatformStyle *platformStyle, CWallet* wallet, WalletModel *parent): QAbstractTableModel(parent), wallet(wallet), walletModel(parent), priv(new TransactionTablePriv(wallet, this)), fProcessingQueuedTransactions(false), platformStyle(platformStyle) { columns << QString() << QString() << tr("Date") << tr("Type") << tr("Label") << JavabitUnits::getAmountColumnTitle(walletModel->getOptionsModel()->getDisplayUnit()); priv->refreshWallet(); connect(walletModel->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); subscribeToCoreSignals(); } TransactionTableModel::~TransactionTableModel() { unsubscribeFromCoreSignals(); delete priv; } /** Updates the column title to "Amount (DisplayUnit)" and emits headerDataChanged() signal for table headers to react. */ void TransactionTableModel::updateAmountColumnTitle() { columns[Amount] = JavabitUnits::getAmountColumnTitle(walletModel->getOptionsModel()->getDisplayUnit()); Q_EMIT headerDataChanged(Qt::Horizontal,Amount,Amount); } void TransactionTableModel::updateTransaction(const QString &hash, int status, bool showTransaction) { uint256 updated; updated.SetHex(hash.toStdString()); priv->updateWallet(updated, status, showTransaction); } void TransactionTableModel::updateConfirmations() { // Blocks came in since last poll. // Invalidate status (number of confirmations) and (possibly) description // for all rows. Qt is smart enough to only actually request the data for the // visible rows. Q_EMIT dataChanged(index(0, Status), index(priv->size()-1, Status)); Q_EMIT dataChanged(index(0, ToAddress), index(priv->size()-1, ToAddress)); } int TransactionTableModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return priv->size(); } int TransactionTableModel::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent); return columns.length(); } QString TransactionTableModel::formatTxStatus(const TransactionRecord *wtx) const { QString status; switch(wtx->status.status) { case TransactionStatus::OpenUntilBlock: status = tr("Open for %n more block(s)","",wtx->status.open_for); break; case TransactionStatus::OpenUntilDate: status = tr("Open until %1").arg(GUIUtil::dateTimeStr(wtx->status.open_for)); break; case TransactionStatus::Offline: status = tr("Offline"); break; case TransactionStatus::Unconfirmed: status = tr("Unconfirmed"); break; case TransactionStatus::Confirming: status = tr("Confirming (%1 of %2 recommended confirmations)").arg(wtx->status.depth).arg(TransactionRecord::RecommendedNumConfirmations); break; case TransactionStatus::Confirmed: status = tr("Confirmed (%1 confirmations)").arg(wtx->status.depth); break; case TransactionStatus::Conflicted: status = tr("Conflicted"); break; case TransactionStatus::Immature: status = tr("Immature (%1 confirmations, will be available after %2)").arg(wtx->status.depth).arg(wtx->status.depth + wtx->status.matures_in); break; case TransactionStatus::MaturesWarning: status = tr("This block was not received by any other nodes and will probably not be accepted!"); break; case TransactionStatus::NotAccepted: status = tr("Generated but not accepted"); break; } return status; } QString TransactionTableModel::formatTxDate(const TransactionRecord *wtx) const { if(wtx->time) { return GUIUtil::dateTimeStr(wtx->time); } return QString(); } /* Look up address in address book, if found return label (address) otherwise just return (address) */ QString TransactionTableModel::lookupAddress(const std::string &address, bool tooltip) const { QString label = walletModel->getAddressTableModel()->labelForAddress(QString::fromStdString(address)); QString description; if(!label.isEmpty()) { description += label; } if(label.isEmpty() || tooltip) { description += QString(" (") + QString::fromStdString(address) + QString(")"); } return description; } QString TransactionTableModel::formatTxType(const TransactionRecord *wtx) const { switch(wtx->type) { case TransactionRecord::RecvWithAddress: return tr("Received with"); case TransactionRecord::RecvFromOther: return tr("Received from"); case TransactionRecord::SendToAddress: case TransactionRecord::SendToOther: return tr("Sent to"); case TransactionRecord::SendToSelf: return tr("Payment to yourself"); case TransactionRecord::Generated: return tr("Mined"); default: return QString(); } } QVariant TransactionTableModel::txAddressDecoration(const TransactionRecord *wtx) const { switch(wtx->type) { case TransactionRecord::Generated: return QIcon(":/icons/tx_mined"); case TransactionRecord::RecvWithAddress: case TransactionRecord::RecvFromOther: return QIcon(":/icons/tx_input"); case TransactionRecord::SendToAddress: case TransactionRecord::SendToOther: return QIcon(":/icons/tx_output"); default: return QIcon(":/icons/tx_inout"); } } QString TransactionTableModel::formatTxToAddress(const TransactionRecord *wtx, bool tooltip) const { QString watchAddress; if (tooltip) { // Mark transactions involving watch-only addresses by adding " (watch-only)" watchAddress = wtx->involvesWatchAddress ? QString(" (") + tr("watch-only") + QString(")") : ""; } switch(wtx->type) { case TransactionRecord::RecvFromOther: return QString::fromStdString(wtx->address) + watchAddress; case TransactionRecord::RecvWithAddress: case TransactionRecord::SendToAddress: case TransactionRecord::Generated: return lookupAddress(wtx->address, tooltip) + watchAddress; case TransactionRecord::SendToOther: return QString::fromStdString(wtx->address) + watchAddress; case TransactionRecord::SendToSelf: default: return tr("(n/a)") + watchAddress; } } QVariant TransactionTableModel::addressColor(const TransactionRecord *wtx) const { // Show addresses without label in a less visible color switch(wtx->type) { case TransactionRecord::RecvWithAddress: case TransactionRecord::SendToAddress: case TransactionRecord::Generated: { QString label = walletModel->getAddressTableModel()->labelForAddress(QString::fromStdString(wtx->address)); if(label.isEmpty()) return COLOR_BAREADDRESS; } break; case TransactionRecord::SendToSelf: return COLOR_BAREADDRESS; default: break; } return QVariant(); } QString TransactionTableModel::formatTxAmount(const TransactionRecord *wtx, bool showUnconfirmed, JavabitUnits::SeparatorStyle separators) const { QString str = JavabitUnits::format(walletModel->getOptionsModel()->getDisplayUnit(), wtx->credit + wtx->debit, false, separators); if(showUnconfirmed) { if(!wtx->status.countsForBalance) { str = QString("[") + str + QString("]"); } } return QString(str); } QVariant TransactionTableModel::txStatusDecoration(const TransactionRecord *wtx) const { switch(wtx->status.status) { case TransactionStatus::OpenUntilBlock: case TransactionStatus::OpenUntilDate: return COLOR_TX_STATUS_OPENUNTILDATE; case TransactionStatus::Offline: return COLOR_TX_STATUS_OFFLINE; case TransactionStatus::Unconfirmed: return QIcon(":/icons/transaction_0"); case TransactionStatus::Confirming: switch(wtx->status.depth) { case 1: return QIcon(":/icons/transaction_1"); case 2: return QIcon(":/icons/transaction_2"); case 3: return QIcon(":/icons/transaction_3"); case 4: return QIcon(":/icons/transaction_4"); default: return QIcon(":/icons/transaction_5"); }; case TransactionStatus::Confirmed: return QIcon(":/icons/transaction_confirmed"); case TransactionStatus::Conflicted: return QIcon(":/icons/transaction_conflicted"); case TransactionStatus::Immature: { int total = wtx->status.depth + wtx->status.matures_in; int part = (wtx->status.depth * 4 / total) + 1; return QIcon(QString(":/icons/transaction_%1").arg(part)); } case TransactionStatus::MaturesWarning: case TransactionStatus::NotAccepted: return QIcon(":/icons/transaction_0"); default: return COLOR_BLACK; } } QVariant TransactionTableModel::txWatchonlyDecoration(const TransactionRecord *wtx) const { if (wtx->involvesWatchAddress) return QIcon(":/icons/eye"); else return QVariant(); } QString TransactionTableModel::formatTooltip(const TransactionRecord *rec) const { QString tooltip = formatTxStatus(rec) + QString("\n") + formatTxType(rec); if(rec->type==TransactionRecord::RecvFromOther || rec->type==TransactionRecord::SendToOther || rec->type==TransactionRecord::SendToAddress || rec->type==TransactionRecord::RecvWithAddress) { tooltip += QString(" ") + formatTxToAddress(rec, true); } return tooltip; } QVariant TransactionTableModel::data(const QModelIndex &index, int role) const { if(!index.isValid()) return QVariant(); TransactionRecord *rec = static_cast<TransactionRecord*>(index.internalPointer()); switch(role) { case RawDecorationRole: switch(index.column()) { case Status: return txStatusDecoration(rec); case Watchonly: return txWatchonlyDecoration(rec); case ToAddress: return txAddressDecoration(rec); } break; case Qt::DecorationRole: { QIcon icon = qvariant_cast<QIcon>(index.data(RawDecorationRole)); return platformStyle->TextColorIcon(icon); } case Qt::DisplayRole: switch(index.column()) { case Date: return formatTxDate(rec); case Type: return formatTxType(rec); case ToAddress: return formatTxToAddress(rec, false); case Amount: return formatTxAmount(rec, true, JavabitUnits::separatorAlways); } break; case Qt::EditRole: // Edit role is used for sorting, so return the unformatted values switch(index.column()) { case Status: return QString::fromStdString(rec->status.sortKey); case Date: return rec->time; case Type: return formatTxType(rec); case Watchonly: return (rec->involvesWatchAddress ? 1 : 0); case ToAddress: return formatTxToAddress(rec, true); case Amount: return qint64(rec->credit + rec->debit); } break; case Qt::ToolTipRole: return formatTooltip(rec); case Qt::TextAlignmentRole: return column_alignments[index.column()]; case Qt::ForegroundRole: // Non-confirmed (but not immature) as transactions are grey if(!rec->status.countsForBalance && rec->status.status != TransactionStatus::Immature) { return COLOR_UNCONFIRMED; } if(index.column() == Amount && (rec->credit+rec->debit) < 0) { return COLOR_NEGATIVE; } if(index.column() == ToAddress) { return addressColor(rec); } break; case TypeRole: return rec->type; case DateRole: return QDateTime::fromTime_t(static_cast<uint>(rec->time)); case WatchonlyRole: return rec->involvesWatchAddress; case WatchonlyDecorationRole: return txWatchonlyDecoration(rec); case LongDescriptionRole: return priv->describe(rec, walletModel->getOptionsModel()->getDisplayUnit()); case AddressRole: return QString::fromStdString(rec->address); case LabelRole: return walletModel->getAddressTableModel()->labelForAddress(QString::fromStdString(rec->address)); case AmountRole: return qint64(rec->credit + rec->debit); case TxIDRole: return rec->getTxID(); case TxHashRole: return QString::fromStdString(rec->hash.ToString()); case TxHexRole: return priv->getTxHex(rec); case ConfirmedRole: return rec->status.countsForBalance; case FormattedAmountRole: // Used for copy/export, so don't include separators return formatTxAmount(rec, false, JavabitUnits::separatorNever); case StatusRole: return rec->status.status; } return QVariant(); } QVariant TransactionTableModel::headerData(int section, Qt::Orientation orientation, int role) const { if(orientation == Qt::Horizontal) { if(role == Qt::DisplayRole) { return columns[section]; } else if (role == Qt::TextAlignmentRole) { return column_alignments[section]; } else if (role == Qt::ToolTipRole) { switch(section) { case Status: return tr("Transaction status. Hover over this field to show number of confirmations."); case Date: return tr("Date and time that the transaction was received."); case Type: return tr("Type of transaction."); case Watchonly: return tr("Whether or not a watch-only address is involved in this transaction."); case ToAddress: return tr("User-defined intent/purpose of the transaction."); case Amount: return tr("Amount removed from or added to balance."); } } } return QVariant(); } QModelIndex TransactionTableModel::index(int row, int column, const QModelIndex &parent) const { Q_UNUSED(parent); TransactionRecord *data = priv->index(row); if(data) { return createIndex(row, column, priv->index(row)); } return QModelIndex(); } void TransactionTableModel::updateDisplayUnit() { // emit dataChanged to update Amount column with the current unit updateAmountColumnTitle(); Q_EMIT dataChanged(index(0, Amount), index(priv->size()-1, Amount)); } // queue notifications to show a non freezing progress dialog e.g. for rescan struct TransactionNotification { public: TransactionNotification() {} TransactionNotification(uint256 hash, ChangeType status, bool showTransaction): hash(hash), status(status), showTransaction(showTransaction) {} void invoke(QObject *ttm) { QString strHash = QString::fromStdString(hash.GetHex()); qDebug() << "NotifyTransactionChanged: " + strHash + " status= " + QString::number(status); QMetaObject::invokeMethod(ttm, "updateTransaction", Qt::QueuedConnection, Q_ARG(QString, strHash), Q_ARG(int, status), Q_ARG(bool, showTransaction)); } private: uint256 hash; ChangeType status; bool showTransaction; }; static bool fQueueNotifications = false; static std::vector< TransactionNotification > vQueueNotifications; static void NotifyTransactionChanged(TransactionTableModel *ttm, CWallet *wallet, const uint256 &hash, ChangeType status) { // Find transaction in wallet std::map<uint256, CWalletTx>::iterator mi = wallet->mapWallet.find(hash); // Determine whether to show transaction or not (determine this here so that no relocking is needed in GUI thread) bool inWallet = mi != wallet->mapWallet.end(); bool showTransaction = (inWallet && TransactionRecord::showTransaction(mi->second)); TransactionNotification notification(hash, status, showTransaction); if (fQueueNotifications) { vQueueNotifications.push_back(notification); return; } notification.invoke(ttm); } static void ShowProgress(TransactionTableModel *ttm, const std::string &title, int nProgress) { if (nProgress == 0) fQueueNotifications = true; if (nProgress == 100) { fQueueNotifications = false; if (vQueueNotifications.size() > 10) // prevent balloon spam, show maximum 10 balloons QMetaObject::invokeMethod(ttm, "setProcessingQueuedTransactions", Qt::QueuedConnection, Q_ARG(bool, true)); for (unsigned int i = 0; i < vQueueNotifications.size(); ++i) { if (vQueueNotifications.size() - i <= 10) QMetaObject::invokeMethod(ttm, "setProcessingQueuedTransactions", Qt::QueuedConnection, Q_ARG(bool, false)); vQueueNotifications[i].invoke(ttm); } std::vector<TransactionNotification >().swap(vQueueNotifications); // clear } } void TransactionTableModel::subscribeToCoreSignals() { // Connect signals to wallet wallet->NotifyTransactionChanged.connect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3)); wallet->ShowProgress.connect(boost::bind(ShowProgress, this, _1, _2)); } void TransactionTableModel::unsubscribeFromCoreSignals() { // Disconnect signals from wallet wallet->NotifyTransactionChanged.disconnect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3)); wallet->ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2)); }
[ "mirzaei@ce.sharif.edu" ]
mirzaei@ce.sharif.edu
992391fceede35a0f47ff691c17bec99cec510c3
6d3aa4bd25f8a959a823c58d8e1da2d640ff1cc8
/src/i2c.hpp
6e2a1eb77bf74cf30ad3ad1944e14d744504e49a
[]
no_license
PerOrsoli/gd32v
4ae213adea3d490ffbc66ea889be60f701feb55b
796ccc11115a1cf835b86e14612c1087f5187ff8
refs/heads/master
2021-01-03T02:11:12.184026
2020-02-11T22:52:02
2020-02-11T22:52:02
239,874,588
0
0
null
null
null
null
UTF-8
C++
false
false
2,140
hpp
// Copyright © 2020 by P.Orsolic. All right reserved // created 141205 - STM32F1 C // Created 200104 - GD32V C+ #ifndef I2C_H #define I2C_H #include <stdint.h> #include "debug.h" #include "gpio.hpp" #include "gd32vf103_rcu.h" #define I2C_TIMEOUT_MAX 0xFFFF // for SW delay: how long to wait for I2C bus response namespace i2c { // index for DevMap[] enum class Device: uint8_t { myI2C0 = 0, myI2C1, wrong, }; enum class Speed { // used for CKCFG.FAST Speed100kHz = 0, // Standard Speed400kHz = 1, // Fast }; enum class DutyCycle { // used for CKCFG.DTCY // only used for Fast/400kHz mode Duty2 = 0, // Tlow/Thigh = 2 Duty16_9 = 1, // Tlow/Thigh = 16/9 }; enum class Mode { // bit used in SADDR0.ADDRESS0 Read = 1, // Receiver, last bit of address = 1 Write = 0, // Transmitter, last bit of address = 0 }; enum class NackPosition { Current, Next, }; enum class Flag { // bits in STAT1 IsTransmitter, // IsBusy, // I2CBSY BSY, IsMaster, // bits in STAT0 TxEmpty, RxNotEmpty, // RBNE RBNE, // ByteTxComplete, // BTC BTC, // AddressSent, // ADDSEND ADDSEND, // StartSent, SBSEND, STPDET, // STOP detected in slave mode }; enum class Event { MasterModeSelected = 0x00030001, // MasterTxSelected = 0x00070082, // BSY, MASTER MasterRxSelected = 0x00030002, // MasterByteReceived = 0x00030040, // }; void test(void); void init(Device dev, Speed speed, DutyCycle duty); void start(Device dev); void restart(Device dev); void stop(Device dev); void enable(Device dev); void disable(Device dev); void send_addr(Device dev, uint8_t address, Mode mode); uint8_t read(Device dev); void write(Device dev, uint8_t data); void ack(Device dev); void nack(Device dev); void nack_position(Device dev, NackPosition pos); // 200128 Needed for wii nunchuck: #define wait_until_flag(dev, flag, condition) _wait_until_flag(dev, flag, condition, __func__, __FILE__, __LINE__); void _wait_until_flag(Device dev, Flag flag, uint8_t condition, const char* fn_name, const char* file, uint32_t line); void clear_flag(Device dev, Flag flag); bool check_event(Event event); } // namespace #endif // I2C_H
[ "pero74656@gmail.com" ]
pero74656@gmail.com
3b18bd86a2a4be77cae2cdcd1d1448f0e2a0bf3f
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_2464487_0/C++/Prowindy/A.cpp
2b364383900647ef0c85fc61c97ee710aa533806
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
880
cpp
#include <vector> #include <list> #include <map> #include <set> #include <deque> #include <stack> #include <bitset> #include <algorithm> #include <functional> #include <numeric> #include <utility> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <ctime> #include <string.h> using namespace std; #define maxn 100010 #define LL long long LL r,tot; LL cal(LL n) { return n*(n+1)/2; } int main() { freopen("A-small-attempt0.in","r",stdin); freopen("A-small-attempt0.out","w",stdout); int i,j,k; int t,cas; scanf("%d",&t); for(cas=1;cas<=t;cas++){ cin>>r>>tot; LL L=0,R=tot, res=0; while(L<=R){ LL mid=(L+R)/2; if(2*r*mid+4*cal(mid)-3*mid<=tot){ res=mid; L=mid+1; }else R=mid-1; } printf("Case #%d: ",cas); cout<<res<<endl; } }
[ "eewestman@gmail.com" ]
eewestman@gmail.com
a5061bb9ce5412eb8b7438e67327cd749eb38814
48e9625fcc35e6bf790aa5d881151906280a3554
/Sources/Elastos/Runtime/Core/eladll/dll/dllmain.cpp
d459e19f44c62b7a9dcb077f9b97dc3ffe92540c
[ "Apache-2.0" ]
permissive
suchto/ElastosRT
f3d7e163d61fe25517846add777690891aa5da2f
8a542a1d70aebee3dbc31341b7e36d8526258849
refs/heads/master
2021-01-22T20:07:56.627811
2017-03-17T02:37:51
2017-03-17T02:37:51
85,281,630
4
2
null
2017-03-17T07:08:49
2017-03-17T07:08:49
null
UTF-8
C++
false
false
1,450
cpp
//========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // 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 <elastos.h> #include <stdio.h> _ELASTOS_NAMESPACE_USING Boolean AttachElastosDll(); void DetachElastosDll(); EXTERN_C int DllMain( void* hDllHandle, unsigned int dwReason, void* preserved) { _ELASTOS Boolean ret = TRUE; // TODO: PALDisableThreadLibraryCalls((HMODULE)hModule); switch (dwReason) { case DLL_PROCESS_ATTACH: ret = AttachElastosDll(); break; case DLL_PROCESS_DETACH: #if !defined(_linux) || defined(_android) DetachElastosDll(); #endif // Do something // TODO: here need recycle the memory used by ezCOM break; } return ret ? 1 : 0; }
[ "cao.jing@kortide.com" ]
cao.jing@kortide.com
7c18453be477b1907883e140251644d314558823
4dd78f5b79e7215d9f4394e9f96aae87bee8319f
/dtectV3/TRANSDb_Core/TransDb.cpp
0091bba0ad164d9947a74d55830492df2269a275
[]
no_license
man4ish/Genetic_ABI_Services
8652fa9d974c0dbeba99fbba9b014d627f01dc2e
a83af1d4a07125cfd15edb56155ff067807a718c
refs/heads/master
2020-04-02T10:53:36.351511
2018-10-23T16:22:03
2018-10-23T16:22:03
154,360,488
0
0
null
null
null
null
UTF-8
C++
false
false
12,998
cpp
/* * File: TransDb.cpp * Author: Manish * * Created on December 31, 2012, 4:10 PM */ #include <vector> #include "TransDb.h" TransDb::TransDb(const char* _dbname) : DbBase(_dbname) { } TransDb::~TransDb() { this->disconnect(); } bool TransDb::init( const char* _dbhost, const char* _dbuser, const char* _dbpswd) { bool ret = this->connect(_dbhost, _dbuser, _dbpswd, false); assert(ret == true); mysqlpp::Query qry = this->db_conn.query(); qry << "SET NAMES utf8"; ret = this->query_execute(qry); assert(ret == true); return ret; } bool TransDb::insert_text_version( const char* _doc_id, const char* _lang_code, int _text_ver_no, int lock_text) { mysqlpp::Query qry = this->db_conn.query(); qry << "INSERT IGNORE " "INTO TextVersion " "SET " "TextVersion.DocID=" << mysqlpp::quote << _doc_id << "," "TextVersion.LanguageCode=" << mysqlpp::quote << _lang_code << "," "TextVersion.TextVerNo=" << mysqlpp::quote << _text_ver_no << "," "TextVersion.LockText=" << mysqlpp::quote << lock_text; return this->query_execute(qry); } bool TransDb::insert_document( const char* _doc_id, const char* _doc_desc, int _doc_type_idx) { assert(_doc_id != NULL); assert(_doc_desc != NULL); assert(_doc_type_idx != 0); mysqlpp::Query qry = this->db_conn.query(); qry << "INSERT IGNORE " "INTO Document " "VALUES (" << mysqlpp::quote << _doc_id << "," << mysqlpp::quote << _doc_desc << "," << mysqlpp::quote << _doc_type_idx << ")"; return this->query_execute(qry); } bool TransDb::insert_content( const char* _doc_id, const char* _lang_code, const char* _text_ver_no, const char* _text_type, const char* _text_id, const char* _content) { assert(_doc_id != NULL); assert(_lang_code != NULL); assert(_text_ver_no != NULL); assert(_text_type != NULL); assert(_text_id != NULL); assert(_content != NULL); mysqlpp::Query qry = this->db_conn.query(); qry << "INSERT IGNORE " "INTO TextTranslate " "SET " "TextTranslate.DocID=" << mysqlpp::quote << _doc_id << "," "TextTranslate.LanguageCode=" << mysqlpp::quote << _lang_code << "," "TextTranslate.TextVerNo=" << mysqlpp::quote << _text_ver_no << "," "TextTranslate.TextType=" << mysqlpp::quote << _text_type << "," "TextTranslate.TextID=" << mysqlpp::quote << _text_id << "," "TextTranslate.Content=" << mysqlpp::quote << _content << "," "TextTranslate.Source=" << mysqlpp::quote << "DT" << "," "TextTranslate.TranslateText=" << mysqlpp::quote << "1" << "," "TextTranslate.EditDateTime=NOW()"; return this->query_execute(qry); } bool TransDb::get_content( const char* _doc_id, const char* _lang_code, int _text_ver_no, const char* _text_type, const char* _text_id, string& _content) { assert(_doc_id != NULL); assert(_lang_code != NULL); assert(_text_ver_no != 0); assert(_text_type != NULL); assert(_text_id != NULL); _content.clear(); mysqlpp::Query qry = this->db_conn.query(); qry << "SELECT " "TextTranslate.Content, " "TextTranslate.LanguageCode, " "TextTranslate.TranslateText " "FROM TextTranslate " "WHERE " "TextTranslate.DocID=" << mysqlpp::quote << _doc_id << " AND " "TextTranslate.TextVerNo=" << mysqlpp::quote << _text_ver_no << " AND " "TextTranslate.TextType=" << mysqlpp::quote << _text_type << " AND " "TextTranslate.TextID=" << mysqlpp::quote << _text_id; /* if (strcmp(_text_id,"female")== 0 || strcmp(_text_id,"male")== 0){ cout << "------------------------------------------------------------" << endl; cout << qry << endl; cout << "------------------------------------------------------------" << endl; } */ mysqlpp::StoreQueryResult str_res; bool ret = this->query_store(qry, str_res); if (ret == false) return false; if (str_res.empty()) return false; for (size_t i = 0; i < str_res.size(); ++i) { if (str_res[i]["LanguageCode"] == _lang_code) { _content = str_res[i]["Content"].c_str(); return true; } } for (size_t i = 0; i < str_res.size(); ++i) { if (atoi(str_res[i]["TranslateText"].c_str()) == 0) { _content = str_res[i]["Content"].c_str(); return true; } } //Get the english text contents if all criteria are not met -syhwah 20130312 for (size_t i = 0; i < str_res.size(); ++i) { if (str_res[i]["LanguageCode"] == "en") { _content = str_res[i]["Content"].c_str(); return true; } } return false; } bool TransDb::get_content_multi( //syhwah 2013-03-18 bool _check_empty, const char *_doc_id, const char *_lang_code, int _text_ver_no, const char *_text_type, const char *_text_id, set<string> &_content_set, string &_source) { assert(_doc_id != NULL); assert(_lang_code != NULL); assert(_text_ver_no != 0); assert(_text_type != NULL); assert(_text_id != NULL); char *tmp_text_id = new char[strlen(_text_id)+2]; sprintf(tmp_text_id,"%s%%",_text_id); mysqlpp::Query qry = this->db_conn.query(); qry << "SELECT " "TextTranslate.Content, " "TextTranslate.LanguageCode, " "TextTranslate.TranslateText " "FROM TextTranslate " "WHERE " "TextTranslate.DocID=" << mysqlpp::quote << _doc_id << " AND " "TextTranslate.TextVerNo=" << mysqlpp::quote << _text_ver_no << " AND " "TextTranslate.TextType=" << mysqlpp::quote << _text_type << " AND " "TextTranslate.TextID like " << mysqlpp::quote << tmp_text_id; mysqlpp::StoreQueryResult str_res; bool ret = this->query_store(qry, str_res); if (ret == false) { return false; } if (str_res.empty()){ if (_check_empty) return false; return true; } for (size_t i = 0; i < str_res.size(); ++i){ if (str_res[i]["LanguageCode"] == _lang_code){ _content_set.insert(str_res[i]["Content"].c_str()); } } if (_content_set.size() > 0 ) { return true; } for (size_t i = 0; i < str_res.size(); ++i){ if (atoi(str_res[i]["TranslateText"].c_str()) == 0){ _content_set.insert(str_res[i]["Content"].c_str()); } } if (_content_set.size() > 0 ) { return true; } //Get the english text contents if all criteria are not met -syhwah 20130312 for (size_t i = 0; i < str_res.size(); ++i){ if (str_res[i]["LanguageCode"] == "en"){ _content_set.insert(str_res[i]["Content"].c_str()); } } if (_content_set.size() > 0 ) { return true; } else { return false; } } bool TransDb::get_content( bool _check_empty, const char* _doc_id, const char* _lang_code, int _text_ver_no, const char* _text_type, const char* _text_id, string& _content, string& _source) { assert(_doc_id != NULL); assert(_lang_code != NULL); assert(_text_ver_no != 0); assert(_text_type != NULL); assert(_text_id != 0); _content.clear(); mysqlpp::Query qry = this->db_conn.query(); qry << "SELECT " "TextTranslate.Content, " "TextTranslate.Source, " "TextTranslate.LanguageCode," "TextTranslate.TranslateText " "FROM TextTranslate " "WHERE " "TextTranslate.DocID=" << mysqlpp::quote << _doc_id << " AND " "TextTranslate.TextVerNo=" << mysqlpp::quote << _text_ver_no << " AND " "TextTranslate.TextType=" << mysqlpp::quote << _text_type << " AND " "TextTranslate.TextID=" << mysqlpp::quote << _text_id; mysqlpp::StoreQueryResult str_res; bool ret = this->query_store(qry, str_res); if (ret == false) return false; if (str_res.empty()) { if (_check_empty) return false; return true; } bool match_found = false; for (size_t i = 0; i < str_res.size(); ++i) { if (_source.empty() == false) { if ((str_res[i]["LanguageCode"] == _lang_code) && (str_res[i]["Source"] == _source)) { assert(match_found == false); match_found = true; _content = str_res[i]["Content"].c_str(); } } else { if (str_res[i]["LanguageCode"] == _lang_code) { assert(match_found == false); match_found = true; _content = str_res[i]["Content"].c_str(); _source = str_res[i]["Source"].c_str(); } } } return true; } bool TransDb::get_latest_date( string &_content_date, const char* _lang_code) { mysqlpp::Query qry = this->db_conn.query(); qry << "SELECT " "MAX(DATE(TextTranslate.EditDateTime)) " "FROM TextTranslate "; if (_lang_code != NULL) qry << "WHERE TextTranslate.LanguageCode=" << mysqlpp::quote << _lang_code; mysqlpp::StoreQueryResult str_res; bool ret = this->query_store(qry, str_res); if (ret == false) return false; if (str_res.size() != 1) return false; _content_date.assign(str_res[0][0].c_str()); return ret; } bool TransDb::update_text_id( const char* _current, const char* _new) { assert(_current != NULL); assert(_new != NULL); mysqlpp::Query qry = this->db_conn.query(); qry << "UPDATE TextTranslate " "SET TextTranslate.TextID=" << mysqlpp::quote << _new << " " "WHERE " "TextTranslate.TextID=" << mysqlpp::quote << _current; return this->query_execute(qry); } bool TransDb::has_text_id( const char* _text_id, const char* _lang_code) { assert(_text_id != NULL); mysqlpp::Query qry = this->db_conn.query(); qry << "SELECT * " "FROM TextTranslate " "WHERE TextTranslate.TextID=" << mysqlpp::quote << _text_id; if (_lang_code != NULL) qry << " AND TextTranslate.LanguageCode=" << mysqlpp::quote << _lang_code; mysqlpp::StoreQueryResult str_res; bool ret = this->query_store(qry, str_res); assert(ret == true); if (str_res.empty()) return false; // this->print(stderr, &str_res); return true; } bool TransDb::has_content( const char* _content, set<string>& _text_id_set) { assert(_content != NULL); mysqlpp::Query qry = this->db_conn.query(); qry << "SELECT * " "FROM TextTranslate " "WHERE TextTranslate.Content=" << mysqlpp::quote << _content; mysqlpp::StoreQueryResult str_res; bool ret = this->query_store(qry, str_res); if (ret == false) return false; if (str_res.empty()) return false; // this->print(stderr, &str_res); for (size_t i = 0; i < str_res.size(); ++i) { if (strstr(str_res[i]["DocID"].c_str(), "GS") != NULL) _text_id_set.insert(str_res[i]["TextID"].c_str()); } return true; } bool TransDb::get_text_id( const char* _doc_id, const char* _lang_code, const char* _text_type, const char* _content, set<string> &_text_id) { assert(_doc_id != NULL); assert(_lang_code != NULL); assert(_text_type != NULL); assert(_content != NULL); mysqlpp::Query qry = this->db_conn.query(); qry << "SELECT DISTINCT TextTranslate.TextID " "FROM TextTranslate " "WHERE " "TextTranslate.DocID=" << mysqlpp::quote << _doc_id << " AND " "TextTranslate.LanguageCode=" << mysqlpp::quote << _lang_code << " AND " "TextTranslate.TextType=" << mysqlpp::quote << _text_type << " AND " "TextTranslate.Content=" << mysqlpp::quote << _content; mysqlpp::StoreQueryResult str_res; bool ret = this->query_store(qry, str_res); if (ret == false) return false; if (str_res.empty()) return false; for (size_t i = 0; i < str_res.size(); i++) { if ((strstr(str_res[i][0].c_str(), "Disease") != NULL) || (strstr(str_res[i][0].c_str(), "Drug") != NULL) || (strstr(str_res[i][0].c_str(), "Trait") != NULL) || (strstr(str_res[i][0].c_str(), "EFF") != NULL)) continue; _text_id.insert(str_res[i][0].c_str()); } return ret; }
[ "mandecent.gupta@gmail.com" ]
mandecent.gupta@gmail.com
c08d9a03ddab6702eef571297409070d60acb0cc
9f5d66e81d4709400a9b77fc4495e0d7e4268a15
/coj/1888-EvilNumbers.cpp
46722157abf662b2d1c4fcc7b2fd0009215579fb
[]
no_license
danpe91/acm-codes
405c2938cdff0c9bbebd10f3541a96d10b14c2fe
e0b75f370e3a82b84bcc481535a30adce9b1062e
refs/heads/master
2021-05-01T13:21:15.932017
2018-02-11T02:42:29
2018-02-11T02:42:29
121,075,878
0
0
null
null
null
null
UTF-8
C++
false
false
651
cpp
#include <iostream> typedef unsigned long long ll; using namespace std; bool containssix(ll number) { while ( number > 0) { if ((number % 10) == 6) return true; number /= 10; } return false; } bool ismultipleofsix(ll number) { return (number % 6) == 0; } bool sumismultipleofsix(ll number) { ll sum = 0; while ( number > 0) { sum += number % 10; number /= 10; } return ismultipleofsix(sum); } bool isevil(ll number) { return containssix(number) && ismultipleofsix(number) && sumismultipleofsix(number); } int main() { ll n; while((cin >>n), !cin.eof()) { cout << ((isevil(n))? ("EVIL"): ("GOOD")) << endl; } }
[ "danpe91@gmail.com" ]
danpe91@gmail.com
4eec22e13bdb26d9f0cc4cf1f061b50b0961f799
6e8aea602af790932559e83243b9d9cc42014bf8
/Vulkan.Core/Math/BoundingPlane.h
d6645ff711c1fc9802fe33d567cde01bdc42310b
[]
no_license
TeleMEDGit/Vulkan_learning
fbc6e9b94c828ce49c37e1dc556596822ec26716
7a1a107b5c1838dea58680ed0b6b4d8c9ccc5c07
refs/heads/master
2022-10-26T02:48:36.117380
2020-06-16T01:05:54
2020-06-16T01:05:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,661
h
// // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // // Developed by Minigraph // // Author: James Stanard // #pragma once #include "VectorMath.h" namespace Math { class BoundingPlane { public: BoundingPlane() {} BoundingPlane(Vector3 normalToPlane, float distanceFromOrigin) : m_repr(normalToPlane, distanceFromOrigin) {} BoundingPlane(Vector3 pointOnPlane, Vector3 normalToPlane); BoundingPlane(float A, float B, float C, float D) : m_repr(A, B, C, D) {} BoundingPlane(const BoundingPlane& plane) : m_repr(plane.m_repr) {} explicit BoundingPlane(Vector4 plane) : m_repr(plane) {} INLINE operator Vector4() const { return m_repr; } Vector3 GetNormal(void) const { return Vector3(m_repr); } Scalar DistanceFromPoint(Vector3 point) const { //return Dot(point, GetNormal()) + m_repr.GetW(); return Dot(Vector4(point, 1.0f), m_repr); } friend BoundingPlane operator* (const OrthogonalTransform& xform, BoundingPlane plane) { return BoundingPlane(xform.GetTranslation() - plane.GetNormal() * plane.m_repr.GetW(), xform.GetRotation() * plane.GetNormal()); } friend BoundingPlane operator* (const Matrix4& mat, BoundingPlane plane) { return BoundingPlane(Transpose(Invert(mat)) * plane.m_repr); } private: Vector4 m_repr; }; //======================================================================================================= // Inline implementations // inline BoundingPlane::BoundingPlane(Vector3 pointOnPlane, Vector3 normalToPlane) { // Guarantee a normal. This constructor isn't meant to be called frequently, but if it is, we can change this. normalToPlane = Normalize(normalToPlane); m_repr = Vector4(normalToPlane, -Dot(pointOnPlane, normalToPlane)); } //======================================================================================================= // Functions operating on planes // inline BoundingPlane PlaneFromPointsCCW(Vector3 A, Vector3 B, Vector3 C) { return BoundingPlane(A, Cross(B - A, C - A)); } inline void GetFrustumPlanes(Plane planes[6], const Math::Matrix4 & frustum, bool zeroToOne, bool normalize) { // FIXME: need to know whether or not this is a D3D MVP. // We cannot just assume that it's an D3D MVP matrix when // zeroToOne = false and CLIP_SPACE_ZERO_TO_ONE is defined because // this code may be called for non-MVP matrices. const bool isZeroOneZ = false; if (zeroToOne) { // left: inside(p) = p * frustum[0] > 0 planes[0][0] = frustum.GetX().GetX(); planes[0][1] = frustum.GetX().GetY(); planes[0][2] = frustum.GetX().GetZ(); planes[0][3] = frustum.GetX().GetW(); // bottom: inside(p) = p * frustum[1] > 0 planes[2][0] = frustum.GetY().GetX(); planes[2][1] = frustum.GetY().GetY(); planes[2][2] = frustum.GetY().GetZ(); planes[2][3] = frustum.GetY().GetW(); // near: inside(p) = p * frustum[2] > 0 planes[4][0] = frustum.GetZ().GetX(); planes[4][1] = frustum.GetZ().GetY(); planes[4][2] = frustum.GetZ().GetZ(); planes[4][3] = frustum.GetZ().GetW(); } else { // left: inside(p) = p * frustum[0] > - ( p * frustum[3] ) planes[0][0] = frustum.GetZ().GetX() + frustum.GetX().GetX(); planes[0][1] = frustum.GetZ().GetY() + frustum.GetX().GetY(); planes[0][2] = frustum.GetZ().GetZ() + frustum.GetX().GetZ(); planes[0][3] = frustum.GetZ().GetW() + frustum.GetX().GetW(); // bottom: inside(p) = p * frustum[1] > -( p * frustum[3] ) planes[2][0] = frustum.GetZ().GetX() + frustum.GetY().GetX(); planes[2][1] = frustum.GetZ().GetY() + frustum.GetY().GetY(); planes[2][2] = frustum.GetZ().GetZ() + frustum.GetY().GetZ(); planes[2][3] = frustum.GetZ().GetW() + frustum.GetY().GetW(); // near: inside(p) = p * frustum[2] > -( p * frustum[3] ) planes[4][0] = isZeroOneZ ? (frustum.GetY().GetX()) : (frustum.GetZ().GetX() + frustum.GetY().GetX()); planes[4][1] = isZeroOneZ ? (frustum.GetY().GetY()) : (frustum.GetZ().GetY() + frustum.GetY().GetY()); planes[4][2] = isZeroOneZ ? (frustum.GetY().GetZ()) : (frustum.GetZ().GetZ() + frustum.GetY().GetZ()); planes[4][3] = isZeroOneZ ? (frustum.GetY().GetW()) : (frustum.GetZ().GetW() + frustum.GetY().GetW()); } // right: inside(p) = p * frustum[0] < p * frustum[3] planes[1][0] = frustum.GetZ().GetX() - frustum.GetX().GetX(); planes[1][1] = frustum.GetZ().GetY() - frustum.GetX().GetY(); planes[1][2] = frustum.GetZ().GetZ() - frustum.GetX().GetZ(); planes[1][3] = frustum.GetZ().GetW() - frustum.GetX().GetW(); // top: inside(p) = p * frustum[1] < p * frustum[3] planes[3][0] = frustum.GetZ().GetX() - frustum.GetY().GetX(); planes[3][1] = frustum.GetZ().GetY() - frustum.GetY().GetY(); planes[3][2] = frustum.GetZ().GetZ() - frustum.GetY().GetZ(); planes[3][3] = frustum.GetZ().GetW() - frustum.GetY().GetW(); // far: inside(p) = p * frustum[2] < p * frustum[3] planes[5][0] = frustum.GetZ().GetX() - frustum.GetZ().GetX(); planes[5][1] = frustum.GetZ().GetY() - frustum.GetZ().GetY(); planes[5][2] = frustum.GetZ().GetZ() - frustum.GetZ().GetZ(); planes[5][3] = frustum.GetZ().GetW() - frustum.GetZ().GetW(); if (normalize) { for (int i = 0; i < 6; i++) { float s = Math::InvSqrt(Math::LengthSquare(planes[i].Normal())); planes[i][0] *= s; planes[i][1] *= s; planes[i][2] *= s; planes[i][3] *= s; } } } } // namespace Math
[ "ahmed@telemed.net" ]
ahmed@telemed.net
28b4065adebe24b8a6c465d674e20baf8f8acfdc
600df3590cce1fe49b9a96e9ca5b5242884a2a70
/third_party/skia/include/gpu/GrProgramElement.h
ba9daf71541c353f424debbd98149af7b2c40b2c
[ "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0", "BSD-3-Clause" ]
permissive
metux/chromium-suckless
efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a
72a05af97787001756bae2511b7985e61498c965
refs/heads/orig
2022-12-04T23:53:58.681218
2017-04-30T10:59:06
2017-04-30T23:35:58
89,884,931
5
3
BSD-3-Clause
2022-11-23T20:52:53
2017-05-01T00:09:08
null
UTF-8
C++
false
false
5,376
h
/* * Copyright 2014 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #ifndef GrProgramElement_DEFINED #define GrProgramElement_DEFINED #include "../private/SkTArray.h" #include "SkRefCnt.h" class GrGpuResourceRef; /** * Base class for GrProcessor. This exists to manage transitioning a GrProcessor from being owned by * a client to being scheduled for execution. While a GrProcessor is ref'ed by drawing code its * GrGpu resources must also be ref'ed to prevent incorrectly recycling them through the cache. * However, once the GrProcessor is baked into a GrPipeline and the drawing code has stopped ref'ing * it, it's internal resources can be recycled in some cases. * * We track this using two types of refs on GrProgramElement. A regular ref is owned by any client * that may continue to issue draws that use the GrProgramElement. The GrPipeline owns "pending * executions" instead of refs. A pending execution is cleared by ~GrPipeline(). * * While a GrProgramElement is ref'ed any resources it owns are also ref'ed. However, once it gets * into the state where it has pending executions AND no refs then it converts its ownership of * its GrGpuResources from refs to pending IOs. The pending IOs allow the cache to track when it is * safe to recycle a resource even though we still have buffered GrBatches that read or write to the * the resource. * * To make this work all GrGpuResource objects owned by a GrProgramElement or derived classes * (either directly or indirectly) must be wrapped in a GrGpuResourceRef and registered with the * GrProgramElement using addGpuResource(). This allows the regular refs to be converted to pending * IO events when the program element is scheduled for deferred execution. * * Moreover, a GrProgramElement that in turn owns other GrProgramElements must convert its ownership * of its children to pending executions when its ref count reaches zero so that the GrGpuResources * owned by the children GrProgramElements are correctly converted from ownership by ref to * ownership by pending IO. Any GrProgramElement hierarchy is managed by subclasses which must * implement notifyRefCntIsZero() in order to convert refs of children to pending executions. */ class GrProgramElement : public SkNoncopyable { public: virtual ~GrProgramElement() { // fRefCnt can be one when an effect is created statically using GR_CREATE_STATIC_EFFECT SkASSERT((0 == fRefCnt || 1 == fRefCnt) && 0 == fPendingExecutions); // Set to invalid values. SkDEBUGCODE(fRefCnt = fPendingExecutions = -10;) } void ref() const { this->validate(); // Once the ref cnt reaches zero it should never be ref'ed again. SkASSERT(fRefCnt > 0); ++fRefCnt; this->validate(); } void unref() const { this->validate(); --fRefCnt; if (0 == fRefCnt) { this->notifyRefCntIsZero(); if (0 == fPendingExecutions) { delete this; return; } else { this->removeRefs(); } } this->validate(); } /** * Gets an id that is unique for this GrProgramElement object. This will never return 0. */ uint32_t getUniqueID() const { return fUniqueID; } void validate() const { #ifdef SK_DEBUG SkASSERT(fRefCnt >= 0); SkASSERT(fPendingExecutions >= 0); SkASSERT(fRefCnt + fPendingExecutions > 0); #endif } protected: GrProgramElement() : fRefCnt(1), fPendingExecutions(0), fUniqueID(CreateUniqueID()) {} /** Subclasses registers their resources using this function. It is assumed the GrProgramResouce is and will remain owned by the subclass and this function will retain a raw ptr. Once a GrGpuResourceRef is registered its setResource must not be called. */ void addGpuResource(const GrGpuResourceRef* res) { fGpuResources.push_back(res); } void addPendingExecution() const { this->validate(); SkASSERT(fRefCnt > 0); if (0 == fPendingExecutions) { this->addPendingIOs(); } ++fPendingExecutions; this->validate(); } void completedExecution() const { this->validate(); --fPendingExecutions; if (0 == fPendingExecutions) { if (0 == fRefCnt) { delete this; return; } else { this->pendingIOComplete(); } } this->validate(); } private: /** This will be called when the ref cnt is zero. The object may or may not have pending executions. */ virtual void notifyRefCntIsZero() const = 0; static uint32_t CreateUniqueID(); void removeRefs() const; void addPendingIOs() const; void pendingIOComplete() const; mutable int32_t fRefCnt; // Count of deferred executions not yet issued to the 3D API. mutable int32_t fPendingExecutions; uint32_t fUniqueID; SkSTArray<4, const GrGpuResourceRef*, true> fGpuResources; // Only this class can access addPendingExecution() and completedExecution(). template <typename T> friend class GrPendingProgramElement; typedef SkNoncopyable INHERITED; }; #endif
[ "enrico.weigelt@gr13.net" ]
enrico.weigelt@gr13.net
ca9ca9e7ffbb51134a982265333b88e0188ca773
e217eaf05d0dab8dd339032b6c58636841aa8815
/IfcAlignment/src/OpenInfraPlatform/IfcAlignment/entity/include/IfcSite.h
a329965af1c7b53a4f6ea294436f742a43e455cf
[]
no_license
bigdoods/OpenInfraPlatform
f7785ebe4cb46e24d7f636e1b4110679d78a4303
0266e86a9f25f2ea9ec837d8d340d31a58a83c8e
refs/heads/master
2021-01-21T03:41:20.124443
2016-01-26T23:20:21
2016-01-26T23:20:21
57,377,206
0
1
null
2016-04-29T10:38:19
2016-04-29T10:38:19
null
UTF-8
C++
false
false
4,351
h
/*! \verbatim * \copyright Copyright (c) 2015 Julian Amann. All rights reserved. * \author Julian Amann <julian.amann@tum.de> (https://www.cms.bgu.tum.de/en/team/amann) * \brief This file is part of the BlueFramework. * \endverbatim */ #pragma once #include <vector> #include <map> #include <sstream> #include <string> #include "OpenInfraPlatform/IfcAlignment/model/shared_ptr.h" #include "OpenInfraPlatform/IfcAlignment/model/IfcAlignmentP6Object.h" #include "IfcSpatialStructureElement.h" namespace OpenInfraPlatform { namespace IfcAlignment { class IfcCompoundPlaneAngleMeasure; class IfcLengthMeasure; class IfcLabel; class IfcPostalAddress; //ENTITY class IfcSite : public IfcSpatialStructureElement { public: IfcSite(); IfcSite( int id ); ~IfcSite(); // method setEntity takes over all attributes from another instance of the class virtual void setEntity( shared_ptr<IfcAlignmentP6Entity> other ); virtual void getStepLine( std::stringstream& stream ) const; virtual void getStepParameter( std::stringstream& stream, bool is_select_type = false ) const; virtual void readStepData( std::vector<std::string>& args, const std::map<int,shared_ptr<IfcAlignmentP6Entity> >& map ); virtual void setInverseCounterparts( shared_ptr<IfcAlignmentP6Entity> ptr_self ); virtual void unlinkSelf(); virtual const char* classname() const { return "IfcSite"; } // IfcRoot ----------------------------------------------------------- // attributes: // shared_ptr<IfcGloballyUniqueId> m_GlobalId; // shared_ptr<IfcOwnerHistory> m_OwnerHistory; //optional // shared_ptr<IfcLabel> m_Name; //optional // shared_ptr<IfcText> m_Description; //optional // IfcObjectDefinition ----------------------------------------------------------- // inverse attributes: // std::vector<weak_ptr<IfcRelAssigns> > m_HasAssignments_inverse; // std::vector<weak_ptr<IfcRelNests> > m_Nests_inverse; // std::vector<weak_ptr<IfcRelNests> > m_IsNestedBy_inverse; // std::vector<weak_ptr<IfcRelDeclares> > m_HasContext_inverse; // std::vector<weak_ptr<IfcRelAggregates> > m_IsDecomposedBy_inverse; // std::vector<weak_ptr<IfcRelAggregates> > m_Decomposes_inverse; // std::vector<weak_ptr<IfcRelAssociates> > m_HasAssociations_inverse; // IfcObject ----------------------------------------------------------- // attributes: // shared_ptr<IfcLabel> m_ObjectType; //optional // inverse attributes: // std::vector<weak_ptr<IfcRelDefinesByObject> > m_IsDeclaredBy_inverse; // std::vector<weak_ptr<IfcRelDefinesByObject> > m_Declares_inverse; // std::vector<weak_ptr<IfcRelDefinesByType> > m_IsTypedBy_inverse; // std::vector<weak_ptr<IfcRelDefinesByProperties> > m_IsDefinedBy_inverse; // IfcProduct ----------------------------------------------------------- // attributes: // shared_ptr<IfcObjectPlacement> m_ObjectPlacement; //optional // shared_ptr<IfcProductRepresentation> m_Representation; //optional // inverse attributes: // std::vector<weak_ptr<IfcRelAssignsToProduct> > m_ReferencedBy_inverse; // IfcSpatialElement ----------------------------------------------------------- // attributes: // shared_ptr<IfcLabel> m_LongName; //optional // inverse attributes: // std::vector<weak_ptr<IfcRelReferencedInSpatialStructure> > m_ReferencesElements_inverse; // std::vector<weak_ptr<IfcRelContainedInSpatialStructure> > m_ContainsElements_inverse; // std::vector<weak_ptr<IfcRelServicesBuildings> > m_ServicedBySystems_inverse; // IfcSpatialStructureElement ----------------------------------------------------------- // attributes: // shared_ptr<IfcElementCompositionEnum> m_CompositionType; //optional // IfcSite ----------------------------------------------------------- // attributes: shared_ptr<IfcCompoundPlaneAngleMeasure> m_RefLatitude; //optional shared_ptr<IfcCompoundPlaneAngleMeasure> m_RefLongitude; //optional shared_ptr<IfcLengthMeasure> m_RefElevation; //optional shared_ptr<IfcLabel> m_LandTitleNumber; //optional shared_ptr<IfcPostalAddress> m_SiteAddress; //optional }; } // end namespace IfcAlignment } // end namespace OpenInfraPlatform
[ "planung.cms.bv@tum.de" ]
planung.cms.bv@tum.de
474260b672fb96c927a7ea9f85cdf04ff37d3c24
383288a72568edbca59c1551711659387afcc250
/标准CSting类的使用/main.cpp
b8da216510206e47033edc896d97cb7bcb9b7243
[]
no_license
dongfeng86/CppPrimerPlus-SourceCode
caf7ce8867d759cea37a7021f57580a4c58e3213
79c3505c67d88d38d6af89ffb0b9588a5461b3a7
refs/heads/master
2023-09-04T00:16:33.162076
2023-08-25T09:44:39
2023-08-25T09:44:39
199,538,001
0
1
null
null
null
null
GB18030
C++
false
false
3,772
cpp
//#include<iostream> //#include<atlstr.h> #include <iostream> #include <stdlib.h> #include <string> #include "atlbase.h" #include "atlstr.h" #include "comutil.h" #include <atlconv.h> // //using namespace std; //using namespace System; using std::wcout; using std::wcin; using std::endl; using std::cout; using std::cin; int main() { //以下修改于2019.11.8 记录CString与string的相互转换 CString sTT = _T("hello "); wcout << (const wchar_t *)sTT << endl; wcout << (LPCTSTR)sTT << endl; std::string mmm = CT2A(sTT.GetString()); //从CString转换为string cout << mmm << endl; CString new1 = CA2T(mmm.c_str()); //从string转为CString wcout << (LPCTSTR)new1 << endl; //以上 CString s1 = _T("This "); // Cascading concatenation s1 += _T("is a "); CString s2 = _T("test"); CString message = s1 + _T("big ") + s2; // Message contains "This is a big test". wcout << (const wchar_t*)message<<endl; //注意,这个输出必须要进行显示转换,不然会出错 wcout << (LPCTSTR)message << endl; char *orig = "Hello, World!"; cout << orig << " (char *)" << endl; // newsize describes the length of the // wchar_t string called wcstring in terms of the number // of wide characters, not the number of bytes. size_t newsize = strlen(orig) + 1; // The following creates a buffer large enough to contain // the exact number of characters in the original string // in the new format. If you want to add more characters // to the end of the string, increase the value of newsize // to increase the size of the buffer. wchar_t * wcstring = new wchar_t[newsize]; // Convert char* string to a wchar_t* string. size_t convertedChars = 0; mbstowcs_s(&convertedChars, wcstring, newsize, orig, _TRUNCATE); // Display the result and indicate the type of string that it is. wcout << wcstring << _T(" (wchar_t *)") << ";转化后的字符数是:" <<convertedChars<< endl; //// Convert the C style string to a _bstr_t string. //_bstr_t bstrt(orig); //// Append the type of string to the new string //// and then display the result. //bstrt += " (_bstr_t)"; //cout << bstrt << endl; //// Convert the C style string to a CComBSTR string. //CComBSTR ccombstr(orig); //if (ccombstr.Append(_T(" (CComBSTR)")) == S_OK) //{ // CW2A printstr(ccombstr); // cout << printstr << endl; //} // Convert the C style string to a CstringA and display it. CStringA cstringa(orig); cstringa += " (CStringA)"; cout << cstringa << endl; // Convert the C style string to a CStringW and display it. CStringW cstring(orig); cstring += " (CStringW)"; // To display a CStringW correctly, use wcout and cast cstring // to (LPCTSTR). wcout << (LPCTSTR)cstring << endl; //convert the c style string to a Csting and display it CString strTemp(orig); strTemp += _T(" (CString)"); wcout << (LPCTSTR)strTemp << endl; //输出一句带汉字的CString对象总是出现问题 ////输入一句话到CSting当中 //cout <<"请输入一句话\n"; //std::string sTemp2; //std::getline(cin, sTemp2); //cout << "这是用string对象输出的:" << sTemp2 << endl; ////CString sWtemp(sTemp2.c_str()); //CString sWtemp("hahahah哈哈哈"); //wcout << "这是用CString对象输出的:"; ////wcout << (LPCTSTR)sWtemp << endl; // Convert the C style string to a basic_string and display it. std::string basicstring(orig); basicstring += " (basic_string)"; cout << basicstring << endl; //// Convert the C style string to a System::String and display it. //String ^systemstring = gcnew String(orig); //systemstring += " (System::String)"; //Console::WriteLine("{0}", systemstring); //delete systemstring; }
[ "115949168@qq.com" ]
115949168@qq.com
9547a3bdf5e1a6710998a28c20c88fff11c31fa1
b840dda7b728f0b4e758eb5ad757b13db2407cf7
/2_HEQLayers/HEQLayers.cpp
4a79fc65dc5eb28c201ecb982c4c5f133e9dd9a8
[]
permissive
billkarsh/Alignment_Projects
0bf9f4009fa740f51bdc9d58c826fd00d4dfce9c
45b7a808dfc1aae698f02354d5586c6eafad542b
refs/heads/master
2023-07-24T18:31:16.890373
2023-07-07T21:05:32
2023-07-07T21:05:32
18,221,689
15
20
BSD-3-Clause
2018-01-21T00:40:02
2014-03-28T18:10:18
C++
UTF-8
C++
false
false
5,486
cpp
// // Write script to submit HEQ1Lyr jobs for: // // tag // z range // pct, // lrbt // #include "GenDefs.h" #include "Cmdline.h" #include "File.h" #include "TrakEM2_UTL.h" #include <sys/stat.h> /* --------------------------------------------------------------- */ /* Macros -------------------------------------------------------- */ /* --------------------------------------------------------------- */ /* --------------------------------------------------------------- */ /* Types --------------------------------------------------------- */ /* --------------------------------------------------------------- */ /* --------------------------------------------------------------- */ /* CArgs_gray ---------------------------------------------------- */ /* --------------------------------------------------------------- */ class CArgs_gray { public: IBox roi; double pct; char *infile, *tag; int zmin, zmax; public: CArgs_gray() { roi.L = roi.R = 0; pct = 99.5; infile = NULL; tag = NULL; zmin = 0; zmax = 32768; }; void SetCmdLine( int argc, char* argv[] ); }; /* --------------------------------------------------------------- */ /* Statics ------------------------------------------------------- */ /* --------------------------------------------------------------- */ static CArgs_gray gArgs; static FILE* flog = NULL; /* --------------------------------------------------------------- */ /* SetCmdLine ---------------------------------------------------- */ /* --------------------------------------------------------------- */ void CArgs_gray::SetCmdLine( int argc, char* argv[] ) { // start log flog = FileOpenOrDie( "HEQLayers.log", "w" ); // log start time time_t t0 = time( NULL ); char atime[32]; strcpy( atime, ctime( &t0 ) ); atime[24] = '\0'; // remove the newline fprintf( flog, "Start: %s ", atime ); // parse command line args if( argc < 3 ) { printf( "Usage: HEQLayers <xml-file> <tag> [options].\n" ); exit( 42 ); } for( int i = 1; i < argc; ++i ) { vector<int> vi; // echo to log fprintf( flog, "%s ", argv[i] ); if( argv[i][0] != '-' ) { if( !infile ) infile = argv[i]; else tag = argv[i]; } else if( GetArg( &zmin, "-zmin=%d", argv[i] ) ) ; else if( GetArg( &zmax, "-zmax=%d", argv[i] ) ) ; else if( GetArg( &pct, "-pct=%lf", argv[i] ) ) ; else if( GetArgList( vi, "-lrbt=", argv[i] ) && vi.size() == 4 ) memcpy( &roi, &vi[0], 4*sizeof(int) ); else { printf( "Did not understand option '%s'.\n", argv[i] ); exit( 42 ); } } fprintf( flog, "\n\n" ); fflush( flog ); } /* --------------------------------------------------------------- */ /* ParseTrakEM2 -------------------------------------------------- */ /* --------------------------------------------------------------- */ static void ParseTrakEM2( vector<int> &zlist ) { /* ---- */ /* Open */ /* ---- */ XML_TKEM xml( gArgs.infile, flog ); TiXmlElement* layer = xml.GetFirstLayer(); /* -------------- */ /* For each layer */ /* -------------- */ for( ; layer; layer = layer->NextSiblingElement() ) { /* ----------------- */ /* Layer-level stuff */ /* ----------------- */ int z = atoi( layer->Attribute( "z" ) ); if( z > gArgs.zmax ) break; if( z < gArgs.zmin ) continue; zlist.push_back( z ); } } /* --------------------------------------------------------------- */ /* WriteScript --------------------------------------------------- */ /* --------------------------------------------------------------- */ static void WriteScript( vector<int> &zlist ) { // compose common argument string char sopt[256]; int pos = 0; pos += sprintf( sopt + pos, "-pct=%g ", gArgs.pct ); if( gArgs.roi.L != gArgs.roi.R ) { pos += sprintf( sopt + pos, "-lrbt=%d,%d,%d,%d ", gArgs.roi.L, gArgs.roi.R, gArgs.roi.B, gArgs.roi.T ); } // open file FILE *f = FileOpenOrDie( "make.heq.sht", "w", flog ); // write int nz = zlist.size(); fprintf( f, "#!/bin/sh\n" ); fprintf( f, "\n" ); for( int iz = 0; iz < nz; ++iz ) { fprintf( f, "QSUB_1NODE.sht 32 \"heq-%d\" \"out.txt\" 0 4" " \"HEQ1Lyr '%s' %s -z=%d %s\"\n", zlist[iz], gArgs.infile, gArgs.tag, zlist[iz], sopt ); } fprintf( f, "\n" ); fclose( f ); FileScriptPerms( "make.heq.sht" ); } /* --------------------------------------------------------------- */ /* main ---------------------------------------------------------- */ /* --------------------------------------------------------------- */ int main( int argc, char* argv[] ) { vector<int> zlist; /* ------------------ */ /* Parse command line */ /* ------------------ */ gArgs.SetCmdLine( argc, argv ); /* ---------------- */ /* Read source file */ /* ---------------- */ ParseTrakEM2( zlist ); if( !zlist.size() ) goto exit; /* ------------ */ /* Write script */ /* ------------ */ WriteScript( zlist ); /* ---- */ /* Done */ /* ---- */ exit: fprintf( flog, "\n" ); fclose( flog ); return 0; }
[ "karshb@janelia.hhmi.org" ]
karshb@janelia.hhmi.org
31bf6063ea4cb27a3ec08b0dd5f1401d4e1dc358
b72faf99fe910aee2a3d55ea494bd93b50065e3c
/BinomialHeap.h
759d509a9ccc5947bbcefba483263becfe81be51
[]
no_license
aleksProsk/Heaps
f758783e332341acaf3a0c5cd40c499a58851efb
a05d32868eccc99f04fd5cbb40e0d3c2c01f3a0e
refs/heads/master
2021-01-10T14:23:31.059375
2015-12-15T18:43:56
2015-12-15T18:43:56
48,057,957
0
0
null
null
null
null
UTF-8
C++
false
false
2,641
h
#pragma once #include <iostream> #include <vector> #include <set> #include <map> #include <algorithm> #include <string> #include <cmath> #include <deque> #include <queue> #include <stack> #include <climits> #include <ctime> #include <cstdio> #include <bitset> #include <cstring> #include "Heap.h" template<typename T> class BinomialHeap : public Heap<T> { private: std::vector<BinomialHeap<T>*> nodes; T value; int degree; BinomialHeap<T> *parent; public: int nodesSize; BinomialHeap() { parent = nullptr; nodesSize = 0; } BinomialHeap(T val) { value = val; degree = 1; parent = nullptr; nodesSize = 0; } T extractMin() { int mpos = 0; if (!nodes.size()) return mmax; T minVal = nodes[0]->value; for (int i = 0; i < nodes.size(); i++) { if (nodes[i]->value < minVal) { minVal = nodes[i]->value; mpos = i; } } for (int i = mpos; i < nodes.size() - 1; i++) { std::swap(nodes[i], nodes[i + 1]); } BinomialHeap<T> *tmpHeap = new BinomialHeap<T>(); tmpHeap->nodes = nodes[nodes.size() - 1]->nodes; nodes.pop_back(); merge(tmpHeap); nodesSize = nodes.size(); return minVal; } void merge(BinomialHeap<T> *addedHeap) { std::vector<BinomialHeap<T>*> tmpv; size_t pos1 = 0, pos2 = 0; while (pos1 < nodes.size() && pos2 < addedHeap->nodes.size()) { if (nodes[pos1]->degree < addedHeap->nodes[pos2]->degree) { tmpv.push_back(nodes[pos1]); pos1++; } else { tmpv.push_back(addedHeap->nodes[pos2]); pos2++; } } while (pos1 < nodes.size()) { tmpv.push_back(nodes[pos1]); pos1++; } while (pos2 < addedHeap->nodes.size()) { tmpv.push_back(addedHeap->nodes[pos2]); pos2++; } nodes.clear(); for (size_t i = 0; i < tmpv.size(); i++) { if (i < tmpv.size() - 1 && tmpv[i]->degree == tmpv[i + 1]->degree) { BinomialHeap<T> *tmpNode, *nextNode; if (tmpv[i]->value < tmpv[i + 1]->value) { tmpNode = tmpv[i]; nextNode = tmpv[i + 1]; } else { tmpNode = tmpv[i + 1]; nextNode = tmpv[i]; } nextNode->parent = tmpNode; tmpNode->nodes.push_back(nextNode); tmpNode->degree = std::max(tmpNode->degree, nextNode->degree + 1); tmpv[i + 1] = tmpNode; } else if (i < tmpv.size() - 1 && tmpv[i]->degree > tmpv[i + 1]->degree) { std::swap(tmpv[i], tmpv[i + 1]); i--; } else { nodes.push_back(tmpv[i]); } } nodesSize = nodes.size(); } void insert(T val) { BinomialHeap<T> *newHeap = new BinomialHeap<T>(); newHeap->nodes.push_back(new BinomialHeap<T>(val)); merge(newHeap); } ~BinomialHeap() { if (parent != nullptr) delete parent; } };
[ "alexandriksasha@mail.ru" ]
alexandriksasha@mail.ru
9013665252edcca5051676086a258a630f63f014
1ae555d3088dc123836060371fc520bf0ff13e52
/codeforces/1371/d2.cpp
4d9468ac13c648172c4a8d76e4f1d82c083ab7e1
[]
no_license
knagakura/procon
a87b9a1717674aeb5ee3da0301d465e95c758fde
c6ac49dbaaa908ff13cb0d9af439efe5439ec691
refs/heads/master
2022-01-31T19:46:33.535685
2022-01-23T11:59:02
2022-01-23T11:59:02
161,764,993
0
0
null
null
null
null
UTF-8
C++
false
false
2,226
cpp
#include <bits/stdc++.h> using namespace std; #define rep(i,N) for(int i=0;i<int(N);++i) #define rep1(i,N) for(int i=1;i<int(N);++i) #define all(a) (a).begin(),(a).end() #define print(v) { cerr<<#v<<": [ "; for(auto _ : v) cerr<<_<<", "; cerr<<"]"<<endl; } #define printpair(v) { cerr<<#v<<": [ "; for(auto _ : v) cerr<<"{"<<_.first<<","<<_.second<<"}"<<", "; cerr<<"]"<<endl; } #define dump(x) cerr<<#x<<": "<<x<<endl; #define bit(k) (1LL<<(k)) typedef long long ll; typedef pair<int, int> i_i; typedef pair<ll, ll> l_l; template <class T> using vec = vector<T>; template <class T> using vvec = vector<vec<T>>; template< typename T1, typename T2 > ostream &operator<<(ostream &os, const pair< T1, T2 >& p) { os << "{" <<p.first << ", " << p.second << "}"; return os; } template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return true; } return false; } template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return true; } return false; } const int INF = (ll)1e9; const ll INFLL = (ll)1e18+1; const ll MOD = (ll)1e9+7; const double PI = acos(-1.0); /* const int dx[8] = {1, 0, -1, 0, 1, -1, -1, 1}; const int dy[8] = {0, 1, 0, -1, 1, 1, -1, -1}; const string dir = "DRUL"; */ void solve(){ ll N, K; cin >> N >> K; vvec<int> v(N,vec<int>(N,0)); int p = 0, q = 0; while(K--){ cerr << p << " " << q << endl; v[p][q] = 1; p = (p + 1) % N; q = (q + 1) % N; if(p == 0)q = (q + 1) % N; } ll ans = 0; ll maxx = 0; ll minn = INFLL; rep(i,N){ ll sum = 0; rep(j,N){ sum += v[i][j]; } chmax(maxx, sum); chmin(minn, sum); } ans += (maxx - minn) * (maxx - minn); maxx = 0; minn = INFLL; rep(j,N){ ll sum = 0; rep(i,N){ sum += v[i][j]; } chmax(maxx, sum); chmin(minn, sum); } ans += (maxx - minn) * (maxx - minn); cout << ans << endl; rep(i,N){ rep(j,N){ cout << v[i][j]; } cout << endl; } } int main() { cin.tie(0); ios::sync_with_stdio(false); cout << fixed << setprecision(20); int t; cin >> t; while(t--)solve(); }
[ "knagakura@bs.s.u-tokyo.ac.jp" ]
knagakura@bs.s.u-tokyo.ac.jp
14b850ac3938e5516ff2642e0e6fa2b0af676db5
6d601817064de9b5e215f998d6c183764cd7b3de
/Oops/Oops.cpp
0ea70844f0d4f0d1352d82bdab386835b3fcbd77
[]
no_license
rock007/Oops
657e4951a3d6233d793f048fb12ce1670613170c
bdd7c49e6c35eb5f353c7f77219af042fb053701
refs/heads/master
2021-01-10T05:16:37.731793
2015-12-24T08:52:39
2015-12-24T08:52:39
48,534,624
0
0
null
null
null
null
UTF-8
C++
false
false
5,318
cpp
// Oops.cpp : Defines the class behaviors for the application. // #include "stdafx.h" #include "afxwinappex.h" #include "afxdialogex.h" #include "Oops.h" #include "MainFrm.h" #include "ChildFrm.h" #include "OopsDoc.h" #include "OopsView.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // COopsApp BEGIN_MESSAGE_MAP(COopsApp, CWinAppEx) ON_COMMAND(ID_APP_ABOUT, &COopsApp::OnAppAbout) // Standard file based document commands ON_COMMAND(ID_FILE_NEW, &CWinAppEx::OnFileNew) ON_COMMAND(ID_FILE_OPEN, &CWinAppEx::OnFileOpen) END_MESSAGE_MAP() // COopsApp construction COopsApp::COopsApp() { m_bHiColorIcons = TRUE; // support Restart Manager m_dwRestartManagerSupportFlags = AFX_RESTART_MANAGER_SUPPORT_ALL_ASPECTS; #ifdef _MANAGED // If the application is built using Common Language Runtime support (/clr): // 1) This additional setting is needed for Restart Manager support to work properly. // 2) In your project, you must add a reference to System.Windows.Forms in order to build. System::Windows::Forms::Application::SetUnhandledExceptionMode(System::Windows::Forms::UnhandledExceptionMode::ThrowException); #endif // TODO: replace application ID string below with unique ID string; recommended // format for string is CompanyName.ProductName.SubProduct.VersionInformation SetAppID(_T("Oops.AppID.NoVersion")); // TODO: add construction code here, // Place all significant initialization in InitInstance } // The one and only COopsApp object COopsApp theApp; // COopsApp initialization BOOL COopsApp::InitInstance() { // InitCommonControlsEx() is required on Windows XP if an application // manifest specifies use of ComCtl32.dll version 6 or later to enable // visual styles. Otherwise, any window creation will fail. INITCOMMONCONTROLSEX InitCtrls; InitCtrls.dwSize = sizeof(InitCtrls); // Set this to include all the common control classes you want to use // in your application. InitCtrls.dwICC = ICC_WIN95_CLASSES; InitCommonControlsEx(&InitCtrls); CWinAppEx::InitInstance(); EnableTaskbarInteraction(); // AfxInitRichEdit2() is required to use RichEdit control // AfxInitRichEdit2(); // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need // Change the registry key under which our settings are stored // TODO: You should modify this string to be something appropriate // such as the name of your company or organization SetRegistryKey(_T("Local AppWizard-Generated Applications")); LoadStdProfileSettings(4); // Load standard INI file options (including MRU) InitContextMenuManager(); InitKeyboardManager(); InitTooltipManager(); CMFCToolTipInfo ttParams; ttParams.m_bVislManagerTheme = TRUE; theApp.GetTooltipManager()->SetTooltipParams(AFX_TOOLTIP_TYPE_ALL, RUNTIME_CLASS(CMFCToolTipCtrl), &ttParams); // Register the application's document templates. Document templates // serve as the connection between documents, frame windows and views CMultiDocTemplate* pDocTemplate; pDocTemplate = new CMultiDocTemplate(IDR_OopsTYPE, RUNTIME_CLASS(COopsDoc), RUNTIME_CLASS(CChildFrame), // custom MDI child frame RUNTIME_CLASS(COopsView)); if (!pDocTemplate) return FALSE; AddDocTemplate(pDocTemplate); // create main MDI Frame window CMainFrame* pMainFrame = new CMainFrame; if (!pMainFrame || !pMainFrame->LoadFrame(IDR_MAINFRAME)) { delete pMainFrame; return FALSE; } m_pMainWnd = pMainFrame; // Parse command line for standard shell commands, DDE, file open CCommandLineInfo cmdInfo; ParseCommandLine(cmdInfo); // Dispatch commands specified on the command line. Will return FALSE if // app was launched with /RegServer, /Register, /Unregserver or /Unregister. if (!ProcessShellCommand(cmdInfo)) return FALSE; // The main window has been initialized, so show and update it pMainFrame->ShowWindow(m_nCmdShow); pMainFrame->UpdateWindow(); return TRUE; } int COopsApp::ExitInstance() { //TODO: handle additional resources you may have added return CWinAppEx::ExitInstance(); } // COopsApp message handlers // CAboutDlg dialog used for App About class CAboutDlg : public CDialogEx { public: CAboutDlg(); // Dialog Data #ifdef AFX_DESIGN_TIME enum { IDD = IDD_ABOUTBOX }; #endif protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support // Implementation protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx) END_MESSAGE_MAP() // App command to run the dialog void COopsApp::OnAppAbout() { CAboutDlg aboutDlg; aboutDlg.DoModal(); } // COopsApp customization load/save methods void COopsApp::PreLoadState() { BOOL bNameValid; CString strName; bNameValid = strName.LoadString(IDS_EDIT_MENU); ASSERT(bNameValid); GetContextMenuManager()->AddMenu(strName, IDR_POPUP_EDIT); bNameValid = strName.LoadString(IDS_EXPLORER); ASSERT(bNameValid); GetContextMenuManager()->AddMenu(strName, IDR_POPUP_EXPLORER); } void COopsApp::LoadCustomState() { } void COopsApp::SaveCustomState() { } // COopsApp message handlers
[ "sam_lucky@163.com" ]
sam_lucky@163.com
0ebf43325cadafa87e831c4882674c419edb22c3
ebb70b0cbe7626366077cbb66a58334aaf880f49
/slm_models/gecode.framework/Versions/47/include/int/trace.hpp
1190b0bf781e7683d4ff8ed40ad8de2e6f3267e7
[ "MIT" ]
permissive
slemouton/gecodeMCP
fa06936f5159a56829a61825e90b3a297fef78dd
d038c52ffcf7351048fe5a018cee29c432d8184f
refs/heads/master
2021-07-10T22:33:26.858361
2021-05-05T21:03:55
2021-05-05T21:03:55
60,289,358
1
1
MIT
2019-01-12T16:58:17
2016-06-02T18:52:11
C++
UTF-8
C++
false
false
1,715
hpp
/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* * Main authors: * Christian Schulte <schulte@gecode.org> * * Copyright: * Christian Schulte, 2016 * * This file is part of Gecode, the generic constraint * development environment: * http://www.gecode.org * * 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. * */ namespace Gecode { inline void trace(Home home, const IntVarArgs& x, int te, IntTracer& t) { trace(home,x,TraceFilter::all,te,t); } inline void trace(Home home, const BoolVarArgs& x, int te, BoolTracer& t) { trace(home,x,TraceFilter::all,te,t); } } // STATISTICS: int-trace
[ "lemouton@ircam.Fr" ]
lemouton@ircam.Fr
6b721ada0457ce06a3b19635f9a1a0ceacec449b
90503f4b25bc9185c4261d9891323e415427f144
/algorithm/e.cpp
dc36ebdaace5261d5814c96e1d11f544f1b4f41c
[]
no_license
hackzoomuck/algorithm-study
05a7f55dd52ef1f9ae81ae3aef7ef5a4012e1627
603c9d21043d2100b90ce1c1f3ed501c58c9918b
refs/heads/master
2023-03-13T16:09:44.819286
2021-03-09T07:20:35
2021-03-09T07:20:35
240,303,711
0
0
null
null
null
null
UTF-8
C++
false
false
1,561
cpp
#include <iostream> #include <vector> #include <algorithm> #include <sstream> using namespace std; int dx[4] = {0,0,1,-1}; int dy[4] = {1,-1,0,0}; int section_size = 0; vector<int> v; void dfs(int **m, int x, int y, int size_m) { section_size++; m[x][y] = 0; for (int i = 0; i < 4; i++) { int nx = x + dx[i]; int ny = y + dy[i]; if (nx < 0 || nx >= size_m || ny < 0 || ny >= size_m) continue; if (m[nx][ny]) { dfs(m, nx, ny, size_m); } } } void solution(int sizeOfMatrix, int **matrix) { for (int i = 0; i < sizeOfMatrix; i++) { for (int j = 0; j < sizeOfMatrix; j++) { if (matrix[i][j]) { section_size = 0; dfs(matrix, i, j, sizeOfMatrix); v.push_back(section_size); } } } sort(v.begin(), v.end()); cout << v.size() << "\n"; if (!v.size()) return; for (int j = 0; j < v.size(); j++) { cout << v[j]<<" "; } cout << "\n"; } struct input_data { int sizeOfMatrix; int **matrix; }; void process_stdin(struct input_data& inputData) { string line; istringstream iss; getline(cin, line); iss.str(line); iss >> inputData.sizeOfMatrix; inputData.matrix = new int*[inputData.sizeOfMatrix]; for (int i = 0; i < inputData.sizeOfMatrix; i++) { getline(cin, line); iss.clear(); iss.str(line); inputData.matrix[i] = new int[inputData.sizeOfMatrix]; for (int j = 0; j < inputData.sizeOfMatrix; j++) { iss >> inputData.matrix[i][j]; } } } int main() { struct input_data inputData; process_stdin(inputData); solution(inputData.sizeOfMatrix, inputData.matrix); system("pause"); return 0; }
[ "38100269+leejieun94@users.noreply.github.com" ]
38100269+leejieun94@users.noreply.github.com
fc630cffa33e1d4084636bedf80eea2523806163
54590b39d4710d32bc129e0e9bf59fd5f56ac32d
/SDK/SoT_EmissaryEntitlementPurchased_MA_PromptAccessKey_classes.hpp
8f1c83eae373d41905a36b82f6ab2bb7df50e909
[]
no_license
DDan1l232/SoT-SDK
bb3bb85fa813963655288d6fa2747d316ce57af8
cda078f3b8bca304759f05cc71ca55d31878e8e5
refs/heads/master
2023-03-17T13:16:11.076040
2020-09-09T15:19:09
2020-09-09T15:19:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
890
hpp
#pragma once // Sea of Thieves (2.0.17) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "SoT_EmissaryEntitlementPurchased_MA_PromptAccessKey_structs.hpp" namespace SDK { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass EmissaryEntitlementPurchased_MA_PromptAccessKey.EmissaryEntitlementPurchased_MA_PromptAccessKey_C // 0x0000 (0x0038 - 0x0038) class UEmissaryEntitlementPurchased_MA_PromptAccessKey_C : public UPromptCounterAccessKey { public: static UClass* StaticClass() { static auto ptr = UObject::FindObject<UClass>(_xor_("BlueprintGeneratedClass EmissaryEntitlementPurchased_MA_PromptAccessKey.EmissaryEntitlementPurchased_MA_PromptAccessKey_C")); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "saerko19@gmail.com" ]
saerko19@gmail.com
2bcbcea307a641a34da9125a935b2b585716155d
9da899bf6541c6a0514219377fea97df9907f0ae
/Developer/TraceInsights/Private/Insights/NetworkingProfiler/Widgets/SNetworkingProfilerWindow.h
7697aba8f36aa3b9c4130d7762ce1f72f3c0739e
[]
no_license
peichangliang123/UE4
1aa4df3418c077dd8f82439ecc808cd2e6de4551
20e38f42edc251ee96905ed8e96e1be667bc14a5
refs/heads/master
2023-08-17T11:31:53.304431
2021-09-15T00:31:03
2021-09-15T00:31:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,559
h
// Copyright Epic Games, Inc. All Rights Reserved. #pragma once #include "CoreMinimal.h" #include "Framework/Docking/TabManager.h" #include "Input/Reply.h" #include "Layout/Visibility.h" #include "Misc/Guid.h" #include "SlateFwd.h" #include "TraceServices/Model/NetProfiler.h" #include "Widgets/DeclarativeSyntaxSupport.h" #include "Widgets/Docking/SDockTab.h" #include "Widgets/Input/SComboBox.h" #include "Widgets/SCompoundWidget.h" // Insights #include "Insights/InsightsManager.h" //////////////////////////////////////////////////////////////////////////////////////////////////// class FActiveTimerHandle; class FMenuBuilder; class FUICommandList; class SPacketView; class SPacketContentView; class SNetStatsView; //////////////////////////////////////////////////////////////////////////////////////////////////// struct FNetworkingProfilerTabs { // Tab identifiers static const FName ToolbarID; static const FName PacketViewID; static const FName PacketContentViewID; static const FName NetStatsViewID; }; //////////////////////////////////////////////////////////////////////////////////////////////////// /** Implements the timing profiler window. */ class SNetworkingProfilerWindow : public SCompoundWidget { private: struct FGameInstanceItem { /** Conversion constructor. */ FGameInstanceItem(const TraceServices::FNetProfilerGameInstance& InGameInstance) : GameInstance(InGameInstance) {} uint32 GetIndex() const { return GameInstance.GameInstanceIndex; } FText GetText() const; FText GetTooltipText() const; const TraceServices::FNetProfilerGameInstance GameInstance; }; struct FConnectionItem { /** Conversion constructor. */ FConnectionItem(const TraceServices::FNetProfilerConnection& InConnection) : Connection(InConnection) {} uint32 GetIndex() const { return Connection.ConnectionIndex; } FText GetText() const; FText GetTooltipText() const; const TraceServices::FNetProfilerConnection Connection; }; struct FConnectionModeItem { /** Conversion constructor. */ FConnectionModeItem(const TraceServices::ENetProfilerConnectionMode& InMode) : Mode(InMode) {} FText GetText() const; FText GetTooltipText() const; TraceServices::ENetProfilerConnectionMode Mode; }; public: /** Default constructor. */ SNetworkingProfilerWindow(); /** Virtual destructor. */ virtual ~SNetworkingProfilerWindow(); SLATE_BEGIN_ARGS(SNetworkingProfilerWindow) {} SLATE_END_ARGS() void Reset(); /** Constructs this widget. */ void Construct(const FArguments& InArgs, const TSharedRef<SDockTab>& ConstructUnderMajorTab, const TSharedPtr<SWindow>& ConstructUnderWindow); /** @return The viewport command list */ const TSharedPtr<FUICommandList> GetCommandList() const { return CommandList; } /** @return The tab manager */ TSharedPtr<FTabManager> GetTabManager() const { return TabManager; } void ShowTab(const FName& TabID); void HideTab(const FName& TabID); void ShowOrHideTab(const FName& TabID, bool bShow) { bShow ? ShowTab(TabID) : HideTab(TabID); } TSharedPtr<SPacketView> GetPacketView() const { return PacketView; } const bool IsPacketViewVisible() const { return PacketView.IsValid(); } void ShowOrHidePacketView(const bool bVisibleState) { ShowOrHideTab(FNetworkingProfilerTabs::PacketViewID, bVisibleState); } TSharedPtr<SPacketContentView> GetPacketContentView() const { return PacketContentView; } const bool IsPacketContentViewVisible() const { return PacketContentView.IsValid(); } void ShowOrHidePacketContentView(const bool bVisibleState) { ShowOrHideTab(FNetworkingProfilerTabs::PacketContentViewID, bVisibleState); } TSharedPtr<SNetStatsView> GetNetStatsView() const { return NetStatsView; } const bool IsNetStatsViewVisible() const { return NetStatsView.IsValid(); } void ShowOrHideNetStatsView(const bool bVisibleState) { ShowOrHideTab(FNetworkingProfilerTabs::NetStatsViewID, bVisibleState); } const TraceServices::FNetProfilerGameInstance* GetSelectedGameInstance() const { return SelectedGameInstance ? &SelectedGameInstance->GameInstance : nullptr; } uint32 GetSelectedGameInstanceIndex() const { return SelectedGameInstance ? SelectedGameInstance->GetIndex() : 0; } const TraceServices::FNetProfilerConnection* GetSelectedConnection() const { return SelectedConnection ? &SelectedConnection->Connection : nullptr; } uint32 GetSelectedConnectionIndex() const { return SelectedConnection ? SelectedConnection->GetIndex() : 0; } TraceServices::ENetProfilerConnectionMode GetSelectedConnectionMode() const { return SelectedConnectionMode ? SelectedConnectionMode->Mode : TraceServices::ENetProfilerConnectionMode::Outgoing; } TSharedRef<SWidget> CreateGameInstanceComboBox(); TSharedRef<SWidget> CreateConnectionComboBox(); TSharedRef<SWidget> CreateConnectionModeComboBox(); void SetSelectedPacket(uint32 StartIndex, uint32 EndIndex, uint32 SinglePacketBitSize = 0); void SetSelectedBitRange(uint32 StartPos, uint32 EndPos); void SetSelectedEventTypeIndex(uint32 InEventTypeIndex); private: TSharedRef<SDockTab> SpawnTab_Toolbar(const FSpawnTabArgs& Args); void OnToolbarTabClosed(TSharedRef<SDockTab> TabBeingClosed); TSharedRef<SDockTab> SpawnTab_PacketView(const FSpawnTabArgs& Args); void OnPacketViewTabClosed(TSharedRef<SDockTab> TabBeingClosed); TSharedRef<SDockTab> SpawnTab_PacketContentView(const FSpawnTabArgs& Args); void OnPacketContentViewTabClosed(TSharedRef<SDockTab> TabBeingClosed); TSharedRef<SDockTab> SpawnTab_NetStatsView(const FSpawnTabArgs& Args); void OnNetStatsViewTabClosed(TSharedRef<SDockTab> TabBeingClosed); ////////////////////////////////////////////////// void BindCommands(); ////////////////////////////////////////////////// // Toggle Commands #define DECLARE_TOGGLE_COMMAND(CmdName)\ public:\ void Map_##CmdName(); /**< Maps UI command info CmdName with the specified UI command list. */\ const FUIAction CmdName##_Custom(); /**< UI action for CmdName command. */\ private:\ void CmdName##_Execute(); /**< Handles FExecuteAction for CmdName. */\ bool CmdName##_CanExecute() const; /**< Handles FCanExecuteAction for CmdName. */\ ECheckBoxState CmdName##_GetCheckState() const; /**< Handles FGetActionCheckState for CmdName. */ DECLARE_TOGGLE_COMMAND(TogglePacketViewVisibility) DECLARE_TOGGLE_COMMAND(TogglePacketContentViewVisibility) DECLARE_TOGGLE_COMMAND(ToggleNetStatsViewVisibility) #undef DECLARE_TOGGLE_COMMAND ////////////////////////////////////////////////// void UpdateAggregatedNetStats(); /** * Fill the main menu with menu items. * * @param MenuBuilder The multi-box builder that should be filled with content for this pull-down menu. * @param TabManager A Tab Manager from which to populate tab spawner menu items. */ static void FillMenu(FMenuBuilder& MenuBuilder, const TSharedPtr<FTabManager> TabManager); /** Callback for determining the visibility of the 'Select a session' overlay. */ EVisibility IsSessionOverlayVisible() const; /** Callback for getting the enabled state of the profiler window. */ bool IsProfilerEnabled() const; /** Updates the amount of time the profiler has been active. */ EActiveTimerReturnType UpdateActiveDuration(double InCurrentTime, float InDeltaTime); ////////////////////////////////////////////////// /** * Ticks this widget. Override in derived classes, but always call the parent implementation. * * @param AllottedGeometry The space allotted for this widget * @param InCurrentTime Current absolute real time * @param InDeltaTime Real time passed since last tick */ virtual void Tick(const FGeometry& AllottedGeometry, const double InCurrentTime, const float InDeltaTime) override; /** * The system will use this event to notify a widget that the cursor has entered it. This event is NOT bubbled. * * @param MyGeometry The Geometry of the widget receiving the event * @param MouseEvent Information about the input event */ virtual void OnMouseEnter(const FGeometry& MyGeometry, const FPointerEvent& MouseEvent) override; /** * The system will use this event to notify a widget that the cursor has left it. This event is NOT bubbled. * * @param MouseEvent Information about the input event */ virtual void OnMouseLeave(const FPointerEvent& MouseEvent) override; /** * Called after a key is pressed when this widget has focus * * @param MyGeometry The Geometry of the widget receiving the event * @param InKeyEvent Key event * * @return Returns whether the event was handled, along with other possible actions */ virtual FReply OnKeyDown(const FGeometry& MyGeometry, const FKeyEvent& InKeyEvent) override; /** * Called when the user is dropping something onto a widget; terminates drag and drop. * * @param MyGeometry The geometry of the widget receiving the event. * @param DragDropEvent The drag and drop event. * * @return A reply that indicated whether this event was handled. */ virtual FReply OnDrop(const FGeometry& MyGeometry, const FDragDropEvent& DragDropEvent) override; /** * Called during drag and drop when the the mouse is being dragged over a widget. * * @param MyGeometry The geometry of the widget receiving the event. * @param DragDropEvent The drag and drop event. * * @return A reply that indicated whether this event was handled. */ virtual FReply OnDragOver(const FGeometry& MyGeometry, const FDragDropEvent& DragDropEvent) override; ////////////////////////////////////////////////// void UpdateAvailableGameInstances(); void UpdateAvailableConnections(); void UpdateAvailableConnectionModes(); TSharedRef<SWidget> GameInstance_OnGenerateWidget(TSharedPtr<FGameInstanceItem> InGameInstance) const; void GameInstance_OnSelectionChanged(TSharedPtr<FGameInstanceItem> NewGameInstance, ESelectInfo::Type SelectInfo); FText GameInstance_GetSelectedText() const; FText GameInstance_GetSelectedTooltipText() const; TSharedRef<SWidget> Connection_OnGenerateWidget(TSharedPtr<FConnectionItem> InConnection) const; void Connection_OnSelectionChanged(TSharedPtr<FConnectionItem> NewConnection, ESelectInfo::Type SelectInfo); FText Connection_GetSelectedText() const; FText Connection_GetSelectedTooltipText() const; TSharedRef<SWidget> ConnectionMode_OnGenerateWidget(TSharedPtr<FConnectionModeItem> InConnectionMode) const; void ConnectionMode_OnSelectionChanged(TSharedPtr<FConnectionModeItem> NewConnectionMode, ESelectInfo::Type SelectInfo); FText ConnectionMode_GetSelectedText() const; FText ConnectionMode_GetSelectedTooltipText() const; ////////////////////////////////////////////////// private: /** Commandlist used in the window (Maps commands to window specific actions) */ TSharedPtr<FUICommandList> CommandList; /** Holds the tab manager that manages the front-end's tabs. */ TSharedPtr<FTabManager> TabManager; /** The Packet View widget */ TSharedPtr<SPacketView> PacketView; /** The Packet Content widget */ TSharedPtr<SPacketContentView> PacketContentView; /** The Net Stats widget */ TSharedPtr<SNetStatsView> NetStatsView; TSharedPtr<SComboBox<TSharedPtr<FGameInstanceItem>>> GameInstanceComboBox; TArray<TSharedPtr<FGameInstanceItem>> AvailableGameInstances; TSharedPtr<FGameInstanceItem> SelectedGameInstance; TSharedPtr<SComboBox<TSharedPtr<FConnectionItem>>> ConnectionComboBox; TArray<TSharedPtr<FConnectionItem>> AvailableConnections; TSharedPtr<FConnectionItem> SelectedConnection; TSharedPtr<SComboBox<TSharedPtr<FConnectionModeItem>>> ConnectionModeComboBox; TArray<TSharedPtr<FConnectionModeItem>> AvailableConnectionModes; TSharedPtr<FConnectionModeItem> SelectedConnectionMode; // [SelectedPacketStartIndex, SelectedPacketEndIndex) is the exclusive interval of selected packages. // NumSelectedPackets == SelectedPacketEndIndex - SelectedPacketStartIndex. uint32 SelectedPacketStartIndex; uint32 SelectedPacketEndIndex; // [SelectionStartPosition, SelectionEndPosition) is the exclusive selected bit range inside a single selected package. // Used only when NumSelectedPackets == SelectedPacketEndIndex - SelectedPacketStartIndex == 1. // SelectedBitSize == SelectionEndPosition - SelectionStartPosition. uint32 SelectionStartPosition; uint32 SelectionEndPosition; static const uint32 InvalidEventTypeIndex = uint32(-1); uint32 SelectedEventTypeIndex; /** The handle to the active update duration tick */ TWeakPtr<FActiveTimerHandle> ActiveTimerHandle; /** The number of seconds the profiler has been active */ float DurationActive; };
[ "ouczbs@qq.com" ]
ouczbs@qq.com
59ea3097ab4f38631cbf6697712f384fe2075f3d
019904382caeb8c49e24f1101927ba0d9e137801
/908.cpp
71d601af239dca3993b83de51392bb16b5b2acfc
[]
no_license
faiem/UVA-Online-Judge
bdf0f073cfe641422e17a5fe82e1ce41148606eb
4e56df804f36dace60db8829fb3ea5d133b12389
refs/heads/main
2023-04-12T17:05:21.605237
2021-04-29T07:19:35
2021-04-29T07:19:35
362,724,665
0
0
null
null
null
null
UTF-8
C++
false
false
2,266
cpp
#include<cstdio> #include<iostream> #include<queue> #include<vector> using namespace std; class kruskal{ int x,y,cost; public: kruskal(int a,int b,int meter){ x=a; y=b; cost=meter; } int X()const{ return x; } int Y()const{ return y; } int Cost()const{ return cost; } }; bool operator<(const kruskal &n1,const kruskal &n2){ if( n1.Cost()>=n2.Cost() ) return true; return false; } class Union_Find{ private: vector<int> set; public: void Make_set(int size){ for(int I=0;I<=size;I++) set.push_back(-1); } int Find(int x){ if(set[x]<0) return x; return set[x]=Find(set[x]); } void Create_Union(int x,int y){ if(set[x]>=set[y]){ set[y]+=set[x]; set[x]=y; } else{ set[x]+=set[y]; set[y]=x; } } bool Union(int x,int y){ x=Find(x); y=Find(y); if(x!=y){ Create_Union(x,y); return 1; } return 0; } void print(){ for(int I=0;I<set.size();I++) printf("%2d ",I); cout<<"\n"; for(int I=0;I<set.size();I++) printf("%2d ",set[I]); cout<<"\n";//-------\n"; } }; int main(){ //freopen("in.txt","r",stdin); //freopen("out.txt","w",stdout); long cost1,cost2; int computer,a,b,c,nwln=1,k,M; while(cin>>computer){ cost1=0;cost2=0; if(nwln>1) cout<<endl; for(int I=0;I<computer-1;I++){ cin>>a>>b>>c; cost1+=c; } cout<<cost1<<endl; priority_queue<kruskal> PQ; cin>>k; for(int I=0;I<k;I++){ cin>>a>>b>>c; PQ.push( kruskal(a,b,c) ); } cin>>M; for(int I=0;I<M;I++){ cin>>a>>b>>c; PQ.push( kruskal(a,b,c) ); } Union_Find U; U.Make_set(computer); while(!PQ.empty()){ a=PQ.top().X(); b=PQ.top().Y(); if(U.Union(a,b)) cost2+=PQ.top().Cost(); PQ.pop(); } cout<<cost2<<endl; nwln++; } return 0; }
[ "faiem@overseasecurity.com" ]
faiem@overseasecurity.com
012a324f899cb2306df6bbd3f30a4233a55eb73b
1e63edddb4395121f06c5c7c052178ca93758180
/io/deflate.cc
386b0104730709bdcf10e99502489d3ca487b4d3
[]
no_license
yazici/serenity
f3b129b103ad1893e5d2f90dd115a0cfedc2b50f
19c108f3b910a81fd32a2c7126cbba18511cd644
refs/heads/master
2020-04-27T03:13:42.999742
2017-01-16T15:16:21
2017-01-16T15:16:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
53,505
cc
#include "deflate.h" #include "string.h" #include <string.h> // Decompression flags used by decompress(). // FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the input is a raw deflate stream. // FLAG_HAS_MORE_INPUT: If set, there are more input bytes available beyond the end of the supplied input buffer. If clear, the input buffer contains all remaining input. // FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large enough to hold the entire decompressed stream. If clear, the output buffer is at least the size of the dictionary (typically 32KB). // FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the decompressed bytes. enum { FLAG_PARSE_ZLIB_HEADER = 1, FLAG_HAS_MORE_INPUT = 2, FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4, FLAG_COMPUTE_ADLER32 = 8 }; // Return status. enum status { STATUS_BAD_PARAM = -3, STATUS_ADLER32_MISMATCH = -2, STATUS_FAILED = -1, STATUS_OKAY, STATUS_DONE, STATUS_NEEDS_MORE_INPUT, STATUS_HAS_MORE_OUTPUT }; const int MAX_HUFF_TABLES = 3, MAX_HUFF_SYMBOLS_0 = 288, MAX_HUFF_SYMBOLS_1 = 32, MAX_HUFF_SYMBOLS_2 = 19; const uint LZ_DICT_SIZE = 32768; const int LZ_DICT_SIZE_MASK = LZ_DICT_SIZE - 1, MIN_MATCH_LEN = 3, MAX_MATCH_LEN = 258; const int FAST_LOOKUP_BITS = 10, FAST_LOOKUP_SIZE = 1 << FAST_LOOKUP_BITS; struct huff_table { uint8 m_code_size[MAX_HUFF_SYMBOLS_0]; int16 m_look_up[FAST_LOOKUP_SIZE], m_tree[MAX_HUFF_SYMBOLS_0 * 2]; }; struct decompressor { uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type, m_check_adler32, m_dist, m_counter, m_num_extra, m_table_sizes[MAX_HUFF_TABLES]; uint64 m_bit_buf; size_t m_dist_from_out_buf_start; huff_table m_tables[MAX_HUFF_TABLES]; uint8 m_raw_header[4], m_len_codes[MAX_HUFF_SYMBOLS_0 + MAX_HUFF_SYMBOLS_1 + 137]; }; // Compression flags logically OR'd together (low 12 bits contain the max. number of probes per dictionary search): // DEFAULT_MAX_PROBES: The compressor defaults to 128 dictionary probes per dictionary search. 0=Huffman only, 1=Huffman+LZ (fastest/crap compression), 4095=Huffman+LZ (slowest/best compression). // WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before the deflate data, and the Adler-32 of the source data at the end. Otherwise, you'll get raw deflate data. // COMPUTE_ADLER32: Always compute the adler-32 of the input data (even when not writing zlib headers). // GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more efficient lazy parsing. // NONDETERMINISTIC_PARSING_FLAG: Enable to decrease the compressor's initialization time to the minimum, but the output may vary from run to run given the same input (depending on the contents of memory). // RLE_MATCHES: Only look for RLE matches (matches with a distance of 1) // FILTER_MATCHES: Discards matches <= 5 chars if enabled. // FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables. // FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks. enum { MAX_PROBES = 0xFFF, WRITE_ZLIB_HEADER = 0x01000, COMPUTE_ADLER32 = 0x02000, GREEDY_PARSING_FLAG = 0x04000, NONDETERMINISTIC_PARSING_FLAG = 0x08000, RLE_MATCHES = 0x10000, FILTER_MATCHES = 0x20000, FORCE_ALL_STATIC_BLOCKS = 0x40000, FORCE_ALL_RAW_BLOCKS = 0x80000 }; // Output stream interface. The compressor uses this interface to write compressed data. It'll typically be called OUT_BUF_SIZE at a time. typedef bool (*put_buf_func_ptr)(const void* pBuf, int len, void *pUser); // OUT_BUF_SIZE MUST be large enough to hold a single entire compressed output block (using static/fixed Huffman codes). enum { LZ_CODE_BUF_SIZE = 64 * 1024, OUT_BUF_SIZE = (LZ_CODE_BUF_SIZE * 13 ) / 10, MAX_HUFF_SYMBOLS = 288, LZ_HASH_BITS = 15, LEVEL1_HASH_SIZE_MASK = 4095, LZ_HASH_SHIFT = (LZ_HASH_BITS + 2) / 3, LZ_HASH_SIZE = 1 << LZ_HASH_BITS }; // Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums enum flush { NO_FLUSH = 0, SYNC_FLUSH = 2, FULL_FLUSH = 3, FINISH = 4 }; // tdefl's compression state structure. struct compressor { put_buf_func_ptr m_pPut_buf_func; void *m_pPut_buf_user; uint m_flags, m_max_probes[2]; int m_greedy_parsing; uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size; uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end; uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in, m_bit_buffer; uint m_saved_match_dist, m_saved_match_len, m_saved_lit, m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index, m_wants_to_finish; status m_prev_return_status; const void *m_pIn_buf; flush m_flush; const uint8 *m_pSrc; size_t m_src_buf_left, m_out_buf_ofs; uint8 m_dict[LZ_DICT_SIZE + MAX_MATCH_LEN - 1]; uint16 m_huff_count[MAX_HUFF_TABLES][MAX_HUFF_SYMBOLS]; uint16 m_huff_codes[MAX_HUFF_TABLES][MAX_HUFF_SYMBOLS]; uint8 m_huff_code_sizes[MAX_HUFF_TABLES][MAX_HUFF_SYMBOLS]; uint8 m_lz_code_buf[LZ_CODE_BUF_SIZE]; uint16 m_next[LZ_DICT_SIZE]; uint16 m_hash[LZ_HASH_SIZE]; uint8 m_output_buf[OUT_BUF_SIZE]; }; template<Type T, size_t N> void clear(T (&a)[N]) { mref<T>(a).clear(); } uint32 adler32(uint32 adler, const unsigned char *ptr, size_t buf_len) { uint32 i, s1 = (uint32)(adler & 0xffff), s2 = (uint32)(adler >> 16); size_t block_len = buf_len % 5552; if (!ptr) return 1; while (buf_len) { for (i = 0; i + 7 < block_len; i += 8, ptr += 8) { s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1; s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1; } for ( ; i < block_len; ++i) s1 += *ptr++, s2 += s1; s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552; } return (s2 << 16) + s1; } // Karl Malbrain's compact CRC-32. See "A compact CCITT crc16 and crc32 C implementation that balances processor cache usage against speed": http://www.geocities.com/malbrain/ uint32 crc32(uint32 crc, const uint8 *ptr, size_t buf_len) { static const uint32 s_crc32[16] = { 0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c, 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c }; uint32 crcu32 = (uint32)crc; if (!ptr) return 0; crcu32 = ~crcu32; while (buf_len--) { uint8 b = *ptr++; crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b & 0xF)]; crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b >> 4)]; } return ~crcu32; } #define RETURN(state_index, result) { status = result; r->m_state = state_index; goto common_exit; case state_index:; } #define RETURN_FOREVER(state_index, result) { for ( ; ; ) { RETURN(state_index, result); } } // TODO: If the caller has indicated that there's no more input, and we attempt to read beyond the input buf, then something is wrong with the input because the inflator never // reads ahead more than it needs to. Currently GET_BYTE() pads the end of the stream with 0's in this scenario. #define GET_BYTE(state_index, c) { \ if (pIn_buf_cur >= pIn_buf_end) { \ for ( ; ; ) { \ if (decomp_flags & FLAG_HAS_MORE_INPUT) { \ RETURN(state_index, STATUS_NEEDS_MORE_INPUT); \ if (pIn_buf_cur < pIn_buf_end) { \ c = *pIn_buf_cur++; \ break; \ } \ } else { \ c = 0; \ break; \ } \ } \ } else c = *pIn_buf_cur++; } #define NEED_BITS(state_index, n) do { uint c; GET_BYTE(state_index, c); bit_buf |= (((uint64)c) << num_bits); num_bits += 8; } while (num_bits < (uint)(n)) #define SKIP_BITS(state_index, n) { if (num_bits < (uint)(n)) { NEED_BITS(state_index, n); } bit_buf >>= (n); num_bits -= (n); } #define GET_BITS(state_index, b, n) ({ if (num_bits < (uint)(n)) { NEED_BITS(state_index, n); } b = bit_buf & ((1 << (n)) - 1); bit_buf >>= (n); num_bits -= (n); }) // HUFF_BITBUF_FILL() is only used rarely, when the number of bytes remaining in the input buffer falls below 2. // It reads just enough bytes from the input stream that are needed to decode the next Huffman code (and absolutely no more). It works by trying to fully decode a // Huffman code by using whatever bits are currently present in the bit buffer. If this fails, it reads another byte, and tries again until it succeeds or until the // bit buffer contains >=15 bits (deflate's max. Huffman code size). #define HUFF_BITBUF_FILL(state_index, pHuff) \ do { \ temp = (pHuff)->m_look_up[bit_buf & (FAST_LOOKUP_SIZE - 1)]; \ if (temp >= 0) { \ code_len = temp >> 9; \ if ((code_len) && (num_bits >= code_len)) \ break; \ } else if (num_bits > FAST_LOOKUP_BITS) { \ code_len = FAST_LOOKUP_BITS; \ do { \ temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \ } while ((temp < 0) && (num_bits >= (code_len + 1))); if (temp >= 0) break; \ } GET_BYTE(state_index, c); bit_buf |= (((uint64)c) << num_bits); num_bits += 8; \ } while (num_bits < 15); // HUFF_DECODE() decodes the next Huffman coded symbol. It's more complex than you would initially expect because the zlib API expects the decompressor to never read // beyond the final byte of the deflate stream. (In other words, when this macro wants to read another byte from the input, it REALLY needs another byte in order to fully // decode the next Huffman code.) Handling this properly is particularly important on raw deflate (non-zlib) streams, which aren't followed by a byte aligned adler-32. // The slow path is only executed at the very end of the input buffer. #define HUFF_DECODE(state_index, sym, pHuff) { \ int temp; uint code_len, c; \ if (num_bits < 15) { \ if ((pIn_buf_end - pIn_buf_cur) < 2) { \ HUFF_BITBUF_FILL(state_index, pHuff); \ } else { \ bit_buf |= (((uint64)pIn_buf_cur[0]) << num_bits) | (((uint64)pIn_buf_cur[1]) << (num_bits + 8)); pIn_buf_cur += 2; num_bits += 16; \ } \ } \ if ((temp = (pHuff)->m_look_up[bit_buf & (FAST_LOOKUP_SIZE - 1)]) >= 0) \ code_len = temp >> 9, temp &= 511; \ else { \ code_len = FAST_LOOKUP_BITS; do { temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; } while (temp < 0); \ } sym = temp; bit_buf >>= code_len; num_bits -= code_len; } status decompress(decompressor *r, const uint8 *pIn_buf_next, size_t *pIn_buf_size, uint8 *pOut_buf_start, uint8 *pOut_buf_next, size_t *pOut_buf_size, const uint32 decomp_flags) { static const int s_length_base[31] = { 3,4,5,6,7,8,9,10,11,13, 15,17,19,23,27,31,35,43,51,59, 67,83,99,115,131,163,195,227,258,0,0 }; static const int s_length_extra[31]= { 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 }; static const int s_dist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193, 257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0}; static const int s_dist_extra[32] = { 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; static const uint8 s_length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 }; static const int s_min_table_sizes[3] = { 257, 1, 4 }; status status = STATUS_FAILED; uint32 num_bits, dist, counter, num_extra; uint64 bit_buf; const uint8 *pIn_buf_cur = pIn_buf_next, *const pIn_buf_end = pIn_buf_next + *pIn_buf_size; uint8 *pOut_buf_cur = pOut_buf_next, *const pOut_buf_end = pOut_buf_next + *pOut_buf_size; size_t out_buf_size_mask = (decomp_flags & FLAG_USING_NON_WRAPPING_OUTPUT_BUF) ? (size_t)-1 : ((pOut_buf_next - pOut_buf_start) + *pOut_buf_size) - 1, dist_from_out_buf_start; // Ensure the output buffer's size is a power of 2, unless the output buffer is large enough to hold the entire output file (in which case it doesn't matter). if (((out_buf_size_mask + 1) & out_buf_size_mask) || (pOut_buf_next < pOut_buf_start)) { *pIn_buf_size = *pOut_buf_size = 0; return STATUS_BAD_PARAM; } num_bits = r->m_num_bits; bit_buf = r->m_bit_buf; dist = r->m_dist; counter = r->m_counter; num_extra = r->m_num_extra; dist_from_out_buf_start = r->m_dist_from_out_buf_start; switch(r->m_state) { case 0: bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = r->m_zhdr1 = 0; r->m_z_adler32 = r->m_check_adler32 = 1; if (decomp_flags & FLAG_PARSE_ZLIB_HEADER) { GET_BYTE(1, r->m_zhdr0); GET_BYTE(2, r->m_zhdr1); counter = (((r->m_zhdr0 * 256 + r->m_zhdr1) % 31 != 0) || (r->m_zhdr1 & 32) || ((r->m_zhdr0 & 15) != 8)); if (!(decomp_flags & FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) counter |= (((1U << (8U + (r->m_zhdr0 >> 4))) > 32768U) || ((out_buf_size_mask + 1) < (size_t)(1U << (8U + (r->m_zhdr0 >> 4))))); if (counter) { RETURN_FOREVER(36, STATUS_FAILED); } } do { GET_BITS(3, r->m_final, 3); r->m_type = r->m_final >> 1; if (r->m_type == 0) { SKIP_BITS(5, num_bits & 7); for(counter = 0; counter < 4; ++counter) { if(num_bits) GET_BITS(6, r->m_raw_header[counter], 8); else GET_BYTE(7, r->m_raw_header[counter]); } if ((counter = (r->m_raw_header[0] | (r->m_raw_header[1] << 8))) != (uint)(0xFFFF ^ (r->m_raw_header[2] | (r->m_raw_header[3] << 8)))) { RETURN_FOREVER(39, STATUS_FAILED); } while ((counter) && (num_bits)) { GET_BITS(51, dist, 8); while (pOut_buf_cur >= pOut_buf_end) { RETURN(52, STATUS_HAS_MORE_OUTPUT); } *pOut_buf_cur++ = (uint8)dist; counter--; } while (counter) { size_t n; while (pOut_buf_cur >= pOut_buf_end) { RETURN(9, STATUS_HAS_MORE_OUTPUT); } while (pIn_buf_cur >= pIn_buf_end) { if (decomp_flags & FLAG_HAS_MORE_INPUT) { RETURN(38, STATUS_NEEDS_MORE_INPUT); } else { RETURN_FOREVER(40, STATUS_FAILED); } } n = min(min(size_t(pOut_buf_end - pOut_buf_cur), size_t(pIn_buf_end - pIn_buf_cur)), size_t(counter)); mref<uint8>(pOut_buf_cur, n).copy(ref<uint8>(pIn_buf_cur, n)); pIn_buf_cur += n; pOut_buf_cur += n; counter -= (uint)n; } } else if (r->m_type == 3) { RETURN_FOREVER(10, STATUS_FAILED); } else { if (r->m_type == 1) { uint8 *p = r->m_tables[0].m_code_size; uint i; r->m_table_sizes[0] = 288; r->m_table_sizes[1] = 32; mref<uint8>(r->m_tables[1].m_code_size, 32).clear(5); for ( i = 0; i <= 143; ++i) *p++ = 8; for ( ; i <= 255; ++i) *p++ = 9; for ( ; i <= 279; ++i) *p++ = 7; for ( ; i <= 287; ++i) *p++ = 8; } else { for (counter = 0; counter < 3; counter++) { GET_BITS(11, r->m_table_sizes[counter], "\05\05\04"[counter]); r->m_table_sizes[counter] += s_min_table_sizes[counter]; } clear(r->m_tables[2].m_code_size); for (counter = 0; counter < r->m_table_sizes[2]; counter++) { uint s; GET_BITS(14, s, 3); r->m_tables[2].m_code_size[s_length_dezigzag[counter]] = (uint8)s; } r->m_table_sizes[2] = 19; } for ( ; (int)r->m_type >= 0; r->m_type--) { int tree_next, tree_cur; huff_table *pTable; uint i, j, used_syms, total, sym_index, next_code[17], total_syms[16]; pTable = &r->m_tables[r->m_type]; clear(total_syms); clear(pTable->m_look_up); clear(pTable->m_tree); for (i = 0; i < r->m_table_sizes[r->m_type]; ++i) total_syms[pTable->m_code_size[i]]++; used_syms = 0, total = 0; next_code[0] = next_code[1] = 0; for (i = 1; i <= 15; ++i) { used_syms += total_syms[i]; next_code[i + 1] = (total = ((total + total_syms[i]) << 1)); } if ((65536 != total) && (used_syms > 1)) { RETURN_FOREVER(35, STATUS_FAILED); } for (tree_next = -1, sym_index = 0; sym_index < r->m_table_sizes[r->m_type]; ++sym_index) { uint rev_code = 0, l, cur_code, code_size = pTable->m_code_size[sym_index]; if (!code_size) continue; cur_code = next_code[code_size]++; for (l = code_size; l > 0; l--, cur_code >>= 1) rev_code = (rev_code << 1) | (cur_code & 1); if (code_size <= FAST_LOOKUP_BITS) { int16 k = (int16)((code_size << 9) | sym_index); while (rev_code < FAST_LOOKUP_SIZE) { pTable->m_look_up[rev_code] = k; rev_code += (1 << code_size); } continue; } if (0 == (tree_cur = pTable->m_look_up[rev_code & (FAST_LOOKUP_SIZE - 1)])) { pTable->m_look_up[rev_code & (FAST_LOOKUP_SIZE - 1)] = (int16)tree_next; tree_cur = tree_next; tree_next -= 2; } rev_code >>= (FAST_LOOKUP_BITS - 1); for (j = code_size; j > (FAST_LOOKUP_BITS + 1); j--) { tree_cur -= ((rev_code >>= 1) & 1); if (!pTable->m_tree[-tree_cur - 1]) { pTable->m_tree[-tree_cur - 1] = (int16)tree_next; tree_cur = tree_next; tree_next -= 2; } else tree_cur = pTable->m_tree[-tree_cur - 1]; } tree_cur -= ((rev_code >>= 1) & 1); pTable->m_tree[-tree_cur - 1] = (int16)sym_index; } if (r->m_type == 2) { for (counter = 0; counter < (r->m_table_sizes[0] + r->m_table_sizes[1]); ) { uint s; HUFF_DECODE(16, dist, &r->m_tables[2]); if (dist < 16) { r->m_len_codes[counter++] = (uint8)dist; continue; } if ((dist == 16) && (!counter)) { RETURN_FOREVER(17, STATUS_FAILED); } num_extra = "\02\03\07"[dist - 16]; GET_BITS(18, s, num_extra); s += "\03\03\013"[dist - 16]; __builtin___memset_chk(r->m_len_codes + counter, (dist == 16) ? r->m_len_codes[counter - 1] : 0, s, __bos0(r->m_len_codes + counter)); counter += s; } if ((r->m_table_sizes[0] + r->m_table_sizes[1]) != counter) { RETURN_FOREVER(21, STATUS_FAILED); } memcpy(r->m_tables[0].m_code_size, r->m_len_codes, r->m_table_sizes[0]); memcpy(r->m_tables[1].m_code_size, r->m_len_codes + r->m_table_sizes[0], r->m_table_sizes[1]); } } for ( ; ; ) { uint8 *pSrc; for ( ; ; ) { if (((pIn_buf_end - pIn_buf_cur) < 4) || ((pOut_buf_end - pOut_buf_cur) < 2)) { HUFF_DECODE(23, counter, &r->m_tables[0]); if (counter >= 256) break; while (pOut_buf_cur >= pOut_buf_end) { RETURN(24, STATUS_HAS_MORE_OUTPUT); } *pOut_buf_cur++ = (uint8)counter; } else { int sym2; uint code_len; if (num_bits < 30) { bit_buf |= (((uint64)*((const uint32 *)(pIn_buf_cur))) << num_bits); pIn_buf_cur += 4; num_bits += 32; } if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (FAST_LOOKUP_SIZE - 1)]) >= 0) code_len = sym2 >> 9; else { code_len = FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0); } counter = sym2; bit_buf >>= code_len; num_bits -= code_len; if (counter & 256) break; if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (FAST_LOOKUP_SIZE - 1)]) >= 0) code_len = sym2 >> 9; else { code_len = FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0); } bit_buf >>= code_len; num_bits -= code_len; pOut_buf_cur[0] = (uint8)counter; if (sym2 & 256) { pOut_buf_cur++; counter = sym2; break; } pOut_buf_cur[1] = (uint8)sym2; pOut_buf_cur += 2; } } if ((counter &= 511) == 256) break; num_extra = s_length_extra[counter - 257]; counter = s_length_base[counter - 257]; if (num_extra) { uint extra_bits; GET_BITS(25, extra_bits, num_extra); counter += extra_bits; } HUFF_DECODE(26, dist, &r->m_tables[1]); num_extra = s_dist_extra[dist]; dist = s_dist_base[dist]; if (num_extra) { uint extra_bits; GET_BITS(27, extra_bits, num_extra); dist += extra_bits; } dist_from_out_buf_start = pOut_buf_cur - pOut_buf_start; if ((dist > dist_from_out_buf_start) && (decomp_flags & FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) { RETURN_FOREVER(37, STATUS_FAILED); } pSrc = pOut_buf_start + ((dist_from_out_buf_start - dist) & out_buf_size_mask); if ((max(pOut_buf_cur, pSrc) + counter) > pOut_buf_end) { while (counter--) { while (pOut_buf_cur >= pOut_buf_end) { RETURN(53, STATUS_HAS_MORE_OUTPUT); } *pOut_buf_cur++ = pOut_buf_start[(dist_from_out_buf_start++ - dist) & out_buf_size_mask]; } continue; } else if ((counter >= 9) && (counter <= dist)) { const uint8 *pSrc_end = pSrc + (counter & ~7); do { ((uint32 *)pOut_buf_cur)[0] = ((const uint32 *)pSrc)[0]; ((uint32 *)pOut_buf_cur)[1] = ((const uint32 *)pSrc)[1]; pOut_buf_cur += 8; } while ((pSrc += 8) < pSrc_end); if ((counter &= 7) < 3) { if (counter) { pOut_buf_cur[0] = pSrc[0]; if (counter > 1) pOut_buf_cur[1] = pSrc[1]; pOut_buf_cur += counter; } continue; } } do { pOut_buf_cur[0] = pSrc[0]; pOut_buf_cur[1] = pSrc[1]; pOut_buf_cur[2] = pSrc[2]; pOut_buf_cur += 3; pSrc += 3; } while ((int)(counter -= 3) > 2); if ((int)counter > 0) { pOut_buf_cur[0] = pSrc[0]; if ((int)counter > 1) pOut_buf_cur[1] = pSrc[1]; pOut_buf_cur += counter; } } } } while (!(r->m_final & 1)); if (decomp_flags & FLAG_PARSE_ZLIB_HEADER) { SKIP_BITS(32, num_bits & 7); for (counter = 0; counter < 4; ++counter) { uint s; if (num_bits) GET_BITS(41, s, 8); else GET_BYTE(42, s); r->m_z_adler32 = (r->m_z_adler32 << 8) | s; } } RETURN_FOREVER(34, STATUS_DONE); } common_exit: r->m_num_bits = num_bits; r->m_bit_buf = bit_buf; r->m_dist = dist; r->m_counter = counter; r->m_num_extra = num_extra; r->m_dist_from_out_buf_start = dist_from_out_buf_start; *pIn_buf_size = pIn_buf_cur - pIn_buf_next; *pOut_buf_size = pOut_buf_cur - pOut_buf_next; if ((decomp_flags & (FLAG_PARSE_ZLIB_HEADER | FLAG_COMPUTE_ADLER32)) && (status >= 0)) { const uint8 *ptr = pOut_buf_next; size_t buf_len = *pOut_buf_size; uint32 i, s1 = r->m_check_adler32 & 0xffff, s2 = r->m_check_adler32 >> 16; size_t block_len = buf_len % 5552; while (buf_len) { for (i = 0; i + 7 < block_len; i += 8, ptr += 8) { s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1; s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1; } for ( ; i < block_len; ++i) s1 += *ptr++, s2 += s1; s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552; } r->m_check_adler32 = (s2 << 16) + s1; if ((status == STATUS_DONE) && (decomp_flags & FLAG_PARSE_ZLIB_HEADER) && (r->m_check_adler32 != r->m_z_adler32)) status = STATUS_ADLER32_MISMATCH; } return status; } void *decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags) { decompressor decomp; void *pBuf = nullptr, *pNew_buf; size_t src_buf_ofs = 0, out_buf_capacity = 0; *pOut_len = 0; decomp.m_state = 0; for ( ; ; ) { size_t src_buf_size = src_buf_len - src_buf_ofs, dst_buf_size = out_buf_capacity - *pOut_len, new_out_buf_capacity; status status = decompress(&decomp, (const uint8*)pSrc_buf + src_buf_ofs, &src_buf_size, (uint8*)pBuf, pBuf ? (uint8*)pBuf + *pOut_len : nullptr, &dst_buf_size, (flags & ~FLAG_HAS_MORE_INPUT) | FLAG_USING_NON_WRAPPING_OUTPUT_BUF); if ((status < 0) || (status == STATUS_NEEDS_MORE_INPUT)) { free(pBuf); *pOut_len = 0; return nullptr; } src_buf_ofs += src_buf_size; *pOut_len += dst_buf_size; if (status == STATUS_DONE) break; new_out_buf_capacity = out_buf_capacity * 2; if (new_out_buf_capacity < 128) new_out_buf_capacity = 128; pNew_buf = realloc(pBuf, new_out_buf_capacity); if (!pNew_buf) { free(pBuf); *pOut_len = 0; return nullptr; } pBuf = pNew_buf; out_buf_capacity = new_out_buf_capacity; } return pBuf; } buffer<byte> inflate(const ref<byte> source, bool zlib) { buffer<byte> data; size_t size; data.data = (byte*)decompress_mem_to_heap(source.data, source.size, &size, zlib?FLAG_PARSE_ZLIB_HEADER:0); data.capacity=data.size=size; return data; } /// DEFLATE // Purposely making these tables static for faster init and thread safety. static const uint16 s_len_sym[256] = { 257,258,259,260,261,262,263,264,265,265,266,266,267,267,268,268,269,269,269,269,270,270,270,270,271,271,271,271,272,272,272,272, 273,273,273,273,273,273,273,273,274,274,274,274,274,274,274,274,275,275,275,275,275,275,275,275,276,276,276,276,276,276,276,276, 277,277,277,277,277,277,277,277,277,277,277,277,277,277,277,277,278,278,278,278,278,278,278,278,278,278,278,278,278,278,278,278, 279,279,279,279,279,279,279,279,279,279,279,279,279,279,279,279,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280, 281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281, 282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282, 283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283, 284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,285 }; static const uint8 s_len_extra[256] = { 0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, 4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5, 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,0 }; static const uint8 s_small_dist_sym[512] = { 0,1,2,3,4,4,5,5,6,6,6,6,7,7,7,7,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11, 11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,13, 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,14,14,14,14,14,14,14,14,14,14,14,14, 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14, 14,14,14,14,14,14,14,14,14,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15, 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,16,16,16,16,16,16,16,16,16,16,16,16,16, 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,17,17,17,17,17,17,17,17,17,17,17,17,17,17, 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17, 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17, 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17 }; static const uint8 s_small_dist_extra[512] = { 0,0,0,0,1,1,1,1,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5, 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7 }; static const uint8 s_large_dist_sym[128] = { 0,0,18,19,20,20,21,21,22,22,22,22,23,23,23,23,24,24,24,24,24,24,24,24,25,25,25,25,25,25,25,25,26,26,26,26,26,26,26,26,26,26,26,26, 26,26,26,26,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28, 28,28,28,28,28,28,28,28,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29 }; static const uint8 s_large_dist_extra[128] = { 0,0,8,8,9,9,9,9,10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12, 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13, 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13 }; // Radix sorts sym_freq[] array by 16-bit key m_key. Returns ptr to sorted values. struct sym_freq { uint16 m_key, m_sym_index; }; static sym_freq* radix_sort_syms(uint num_syms, sym_freq* pSyms0, sym_freq* pSyms1) { uint32 total_passes = 2, pass_shift, pass, i, hist[256 * 2]; sym_freq* pCur_syms = pSyms0, *pNew_syms = pSyms1; clear(hist); for (i = 0; i < num_syms; i++) { uint freq = pSyms0[i].m_key; hist[freq & 0xFF]++; hist[256 + ((freq >> 8) & 0xFF)]++; } while ((total_passes > 1) && (num_syms == hist[(total_passes - 1) * 256])) total_passes--; for (pass_shift = 0, pass = 0; pass < total_passes; pass++, pass_shift += 8) { const uint32* pHist = &hist[pass << 8]; uint offsets[256], cur_ofs = 0; for (i = 0; i < 256; i++) { offsets[i] = cur_ofs; cur_ofs += pHist[i]; } for (i = 0; i < num_syms; i++) pNew_syms[offsets[(pCur_syms[i].m_key >> pass_shift) & 0xFF]++] = pCur_syms[i]; { sym_freq* t = pCur_syms; pCur_syms = pNew_syms; pNew_syms = t; } } return pCur_syms; } // calculate_minimum_redundancy() originally written by: Alistair Moffat, alistair@cs.mu.oz.au, Jyrki Katajainen, jyrki@diku.dk, November 1996. static void calculate_minimum_redundancy(sym_freq *A, int n) { int root, leaf, next, avbl, used, dpth; if (n==0) return; else if (n==1) { A[0].m_key = 1; return; } A[0].m_key += A[1].m_key; root = 0; leaf = 2; for (next=1; next < n-1; next++) { if (leaf>=n || A[root].m_key<A[leaf].m_key) { A[next].m_key = A[root].m_key; A[root++].m_key = (uint16)next; } else A[next].m_key = A[leaf++].m_key; if (leaf>=n || (root<next && A[root].m_key<A[leaf].m_key)) { A[next].m_key = (uint16)(A[next].m_key + A[root].m_key); A[root++].m_key = (uint16)next; } else A[next].m_key = (uint16)(A[next].m_key + A[leaf++].m_key); } A[n-2].m_key = 0; for (next=n-3; next>=0; next--) A[next].m_key = A[A[next].m_key].m_key+1; avbl = 1; used = dpth = 0; root = n-2; next = n-1; while (avbl>0) { while (root>=0 && (int)A[root].m_key==dpth) { used++; root--; } while (avbl>used) { A[next--].m_key = (uint16)(dpth); avbl--; } avbl = 2*used; dpth++; used = 0; } } // Limits canonical Huffman code table's max code size. enum { MAX_SUPPORTED_HUFF_CODESIZE = 32 }; static void huffman_enforce_max_code_size(int *pNum_codes, int code_list_len, int max_code_size) { int i; uint32 total = 0; if (code_list_len <= 1) return; for (i = max_code_size + 1; i <= MAX_SUPPORTED_HUFF_CODESIZE; i++) pNum_codes[max_code_size] += pNum_codes[i]; for (i = max_code_size; i > 0; i--) total += (((uint32)pNum_codes[i]) << (max_code_size - i)); while (total != (1UL << max_code_size)) { pNum_codes[max_code_size]--; for (i = max_code_size - 1; i > 0; i--) if (pNum_codes[i]) { pNum_codes[i]--; pNum_codes[i + 1] += 2; break; } total--; } } static void optimize_huffman_table(compressor *d, int table_num, int table_len, int code_size_limit, int static_table) { int i, j, l, num_codes[1 + MAX_SUPPORTED_HUFF_CODESIZE]; uint next_code[MAX_SUPPORTED_HUFF_CODESIZE + 1]; clear(num_codes); if (static_table) { for (i = 0; i < table_len; i++) num_codes[d->m_huff_code_sizes[table_num][i]]++; } else { sym_freq syms0[MAX_HUFF_SYMBOLS], syms1[MAX_HUFF_SYMBOLS], *pSyms; int num_used_syms = 0; const uint16 *pSym_count = &d->m_huff_count[table_num][0]; for (i = 0; i < table_len; i++) if (pSym_count[i]) { syms0[num_used_syms].m_key = (uint16)pSym_count[i]; syms0[num_used_syms++].m_sym_index = (uint16)i; } pSyms = radix_sort_syms(num_used_syms, syms0, syms1); calculate_minimum_redundancy(pSyms, num_used_syms); for (i = 0; i < num_used_syms; i++) num_codes[pSyms[i].m_key]++; huffman_enforce_max_code_size(num_codes, num_used_syms, code_size_limit); clear(d->m_huff_code_sizes[table_num]); clear(d->m_huff_codes[table_num]); for (i = 1, j = num_used_syms; i <= code_size_limit; i++) for (l = num_codes[i]; l > 0; l--) d->m_huff_code_sizes[table_num][pSyms[--j].m_sym_index] = (uint8)(i); } next_code[1] = 0; for (j = 0, i = 2; i <= code_size_limit; i++) next_code[i] = j = ((j + num_codes[i - 1]) << 1); for (i = 0; i < table_len; i++) { uint rev_code = 0, code, code_size; if ((code_size = d->m_huff_code_sizes[table_num][i]) == 0) continue; code = next_code[code_size]++; for (l = code_size; l > 0; l--, code >>= 1) rev_code = (rev_code << 1) | (code & 1); d->m_huff_codes[table_num][i] = (uint16)rev_code; } } #define PUT_BITS(b, l) ({ \ uint bits = b; uint len = l; assert(bits <= ((1U << len) - 1U)); \ d->m_bit_buffer |= (bits << d->m_bits_in); d->m_bits_in += len; \ while (d->m_bits_in >= 8) { \ if (d->m_pOutput_buf < d->m_pOutput_buf_end) \ *d->m_pOutput_buf++ = (uint8)(d->m_bit_buffer); \ d->m_bit_buffer >>= 8; \ d->m_bits_in -= 8; \ } \ }) #define RLE_PREV_CODE_SIZE() { if (rle_repeat_count) { \ if (rle_repeat_count < 3) { \ d->m_huff_count[2][prev_code_size] = (uint16)(d->m_huff_count[2][prev_code_size] + rle_repeat_count); \ while (rle_repeat_count--) packed_code_sizes[num_packed_code_sizes++] = prev_code_size; \ } else { \ d->m_huff_count[2][16] = (uint16)(d->m_huff_count[2][16] + 1); packed_code_sizes[num_packed_code_sizes++] = 16; packed_code_sizes[num_packed_code_sizes++] = (uint8)(rle_repeat_count - 3); \ } rle_repeat_count = 0; } } #define RLE_ZERO_CODE_SIZE() { if (rle_z_count) { \ if (rle_z_count < 3) { \ d->m_huff_count[2][0] = (uint16)(d->m_huff_count[2][0] + rle_z_count); while (rle_z_count--) packed_code_sizes[num_packed_code_sizes++] = 0; \ } else if (rle_z_count <= 10) { \ d->m_huff_count[2][17] = (uint16)(d->m_huff_count[2][17] + 1); packed_code_sizes[num_packed_code_sizes++] = 17; packed_code_sizes[num_packed_code_sizes++] = (uint8)(rle_z_count - 3); \ } else { \ d->m_huff_count[2][18] = (uint16)(d->m_huff_count[2][18] + 1); packed_code_sizes[num_packed_code_sizes++] = 18; packed_code_sizes[num_packed_code_sizes++] = (uint8)(rle_z_count - 11); \ } rle_z_count = 0; } } static uint8 s_packed_code_size_syms_swizzle[] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; static void start_dynamic_block(compressor *d) { int num_lit_codes, num_dist_codes, num_bit_lengths; uint i, total_code_sizes_to_pack, num_packed_code_sizes, rle_z_count, rle_repeat_count, packed_code_sizes_index; uint8 code_sizes_to_pack[MAX_HUFF_SYMBOLS_0 + MAX_HUFF_SYMBOLS_1], packed_code_sizes[MAX_HUFF_SYMBOLS_0 + MAX_HUFF_SYMBOLS_1], prev_code_size = 0xFF; d->m_huff_count[0][256] = 1; optimize_huffman_table(d, 0, MAX_HUFF_SYMBOLS_0, 15, false); optimize_huffman_table(d, 1, MAX_HUFF_SYMBOLS_1, 15, false); for (num_lit_codes = 286; num_lit_codes > 257; num_lit_codes--) if (d->m_huff_code_sizes[0][num_lit_codes - 1]) break; for (num_dist_codes = 30; num_dist_codes > 1; num_dist_codes--) if (d->m_huff_code_sizes[1][num_dist_codes - 1]) break; memcpy(code_sizes_to_pack, &d->m_huff_code_sizes[0][0], num_lit_codes); memcpy(code_sizes_to_pack + num_lit_codes, &d->m_huff_code_sizes[1][0], num_dist_codes); total_code_sizes_to_pack = num_lit_codes + num_dist_codes; num_packed_code_sizes = 0; rle_z_count = 0; rle_repeat_count = 0; memset(&d->m_huff_count[2][0], 0, sizeof(d->m_huff_count[2][0]) * MAX_HUFF_SYMBOLS_2); for (i = 0; i < total_code_sizes_to_pack; i++) { uint8 code_size = code_sizes_to_pack[i]; if (!code_size) { RLE_PREV_CODE_SIZE(); if (++rle_z_count == 138) { RLE_ZERO_CODE_SIZE(); } } else { RLE_ZERO_CODE_SIZE(); if (code_size != prev_code_size) { RLE_PREV_CODE_SIZE(); d->m_huff_count[2][code_size] = (uint16)(d->m_huff_count[2][code_size] + 1); packed_code_sizes[num_packed_code_sizes++] = code_size; } else if (++rle_repeat_count == 6) { RLE_PREV_CODE_SIZE(); } } prev_code_size = code_size; } if (rle_repeat_count) { RLE_PREV_CODE_SIZE(); } else { RLE_ZERO_CODE_SIZE(); } optimize_huffman_table(d, 2, MAX_HUFF_SYMBOLS_2, 7, false); PUT_BITS(2, 2); PUT_BITS(num_lit_codes - 257, 5); PUT_BITS(num_dist_codes - 1, 5); for (num_bit_lengths = 18; num_bit_lengths >= 0; num_bit_lengths--) if (d->m_huff_code_sizes[2][s_packed_code_size_syms_swizzle[num_bit_lengths]]) break; num_bit_lengths = max(4, (num_bit_lengths + 1)); PUT_BITS(num_bit_lengths - 4, 4); for (i = 0; (int)i < num_bit_lengths; i++) PUT_BITS(d->m_huff_code_sizes[2][s_packed_code_size_syms_swizzle[i]], 3); for (packed_code_sizes_index = 0; packed_code_sizes_index < num_packed_code_sizes; ) { uint code = packed_code_sizes[packed_code_sizes_index++]; assert(code < MAX_HUFF_SYMBOLS_2); PUT_BITS(d->m_huff_codes[2][code], d->m_huff_code_sizes[2][code]); if (code >= 16) PUT_BITS(packed_code_sizes[packed_code_sizes_index++], "\02\03\07"[code - 16]); } } static void start_static_block(compressor *d) { uint i; uint8 *p = &d->m_huff_code_sizes[0][0]; for (i = 0; i <= 143; ++i) *p++ = 8; for ( ; i <= 255; ++i) *p++ = 9; for ( ; i <= 279; ++i) *p++ = 7; for ( ; i <= 287; ++i) *p++ = 8; memset(d->m_huff_code_sizes[1], 5, 32); optimize_huffman_table(d, 0, 288, 15, true); optimize_huffman_table(d, 1, 32, 15, true); PUT_BITS(1, 2); } static const uint bitmasks[17] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF }; static bool compress_lz_codes(compressor *d) { uint flags; uint8 *pLZ_codes; uint8 *pOutput_buf = d->m_pOutput_buf; uint8 *pLZ_code_buf_end = d->m_pLZ_code_buf; uint64 bit_buffer = d->m_bit_buffer; uint bits_in = d->m_bits_in; #define PUT_BITS_FAST(b, l) { bit_buffer |= (((uint64)(b)) << bits_in); bits_in += (l); } flags = 1; for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < pLZ_code_buf_end; flags >>= 1) { if (flags == 1) flags = *pLZ_codes++ | 0x100; if (flags & 1) { uint s0, s1, n0, n1, sym, num_extra_bits; uint match_len = pLZ_codes[0], match_dist = *(const uint16 *)(pLZ_codes + 1); pLZ_codes += 3; assert(d->m_huff_code_sizes[0][s_len_sym[match_len]]); PUT_BITS_FAST(d->m_huff_codes[0][s_len_sym[match_len]], d->m_huff_code_sizes[0][s_len_sym[match_len]]); PUT_BITS_FAST(match_len & bitmasks[s_len_extra[match_len]], s_len_extra[match_len]); // This sequence coaxes MSVC into using cmov's vs. jmp's. s0 = s_small_dist_sym[match_dist & 511]; n0 = s_small_dist_extra[match_dist & 511]; s1 = s_large_dist_sym[match_dist >> 8]; n1 = s_large_dist_extra[match_dist >> 8]; sym = (match_dist < 512) ? s0 : s1; num_extra_bits = (match_dist < 512) ? n0 : n1; assert(d->m_huff_code_sizes[1][sym]); PUT_BITS_FAST(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]); PUT_BITS_FAST(match_dist & bitmasks[num_extra_bits], num_extra_bits); } else { uint lit = *pLZ_codes++; assert(d->m_huff_code_sizes[0][lit]); PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) { flags >>= 1; lit = *pLZ_codes++; assert(d->m_huff_code_sizes[0][lit]); PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) { flags >>= 1; lit = *pLZ_codes++; assert(d->m_huff_code_sizes[0][lit]); PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); } } } if (pOutput_buf >= d->m_pOutput_buf_end) return false; *(uint64*)pOutput_buf = bit_buffer; pOutput_buf += (bits_in >> 3); bit_buffer >>= (bits_in & ~7); bits_in &= 7; } #undef PUT_BITS_FAST d->m_pOutput_buf = pOutput_buf; d->m_bits_in = 0; d->m_bit_buffer = 0; while (bits_in) { uint32 n = min(bits_in, 16u); PUT_BITS((uint)bit_buffer & bitmasks[n], n); bit_buffer >>= n; bits_in -= n; } PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); return (d->m_pOutput_buf < d->m_pOutput_buf_end); } static bool compress_block(compressor *d, bool static_block) { if (static_block) start_static_block(d); else start_dynamic_block(d); return compress_lz_codes(d); } static int flush_block(compressor *d, int flush) { uint saved_bit_buf, saved_bits_in; uint8 *pSaved_output_buf; bool comp_block_succeeded = false; int n, use_raw_block = ((d->m_flags & FORCE_ALL_RAW_BLOCKS) != 0) && (d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size; uint8 *pOutput_buf_start = d->m_output_buf; d->m_pOutput_buf = pOutput_buf_start; d->m_pOutput_buf_end = d->m_pOutput_buf + OUT_BUF_SIZE - 16; assert(!d->m_output_flush_remaining); d->m_output_flush_ofs = 0; d->m_output_flush_remaining = 0; *d->m_pLZ_flags = (uint8)(*d->m_pLZ_flags >> d->m_num_flags_left); d->m_pLZ_code_buf -= (d->m_num_flags_left == 8); if ((d->m_flags & WRITE_ZLIB_HEADER) && (!d->m_block_index)) { PUT_BITS(0x78, 8); PUT_BITS(0x01, 8); } PUT_BITS(flush == FINISH, 1); pSaved_output_buf = d->m_pOutput_buf; saved_bit_buf = d->m_bit_buffer; saved_bits_in = d->m_bits_in; if (!use_raw_block) comp_block_succeeded = compress_block(d, (d->m_flags & FORCE_ALL_STATIC_BLOCKS) || (d->m_total_lz_bytes < 48)); // If the block gets expanded, forget the current contents of the output buffer and send a raw block instead. if ( ((use_raw_block) || ((d->m_total_lz_bytes) && ((d->m_pOutput_buf - pSaved_output_buf + 1U) >= d->m_total_lz_bytes))) && ((d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size) ) { uint i; d->m_pOutput_buf = pSaved_output_buf; d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; PUT_BITS(0, 2); if (d->m_bits_in) { PUT_BITS(0, 8 - d->m_bits_in); } for (i = 2; i; --i, d->m_total_lz_bytes ^= 0xFFFF) { PUT_BITS(d->m_total_lz_bytes & 0xFFFF, 16); } for (i = 0; i < d->m_total_lz_bytes; ++i) { PUT_BITS(d->m_dict[(d->m_lz_code_buf_dict_pos + i) & LZ_DICT_SIZE_MASK], 8); } } // Check for the extremely unlikely (if not impossible) case of the compressed block not fitting into the output buffer when using dynamic codes. else if (!comp_block_succeeded) { d->m_pOutput_buf = pSaved_output_buf; d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; compress_block(d, true); } if (flush) { if (flush == FINISH) { if (d->m_bits_in) { PUT_BITS(0, 8 - d->m_bits_in); } if (d->m_flags & WRITE_ZLIB_HEADER) { uint i, a = d->m_adler32; for (i = 0; i < 4; i++) { PUT_BITS((a >> 24) & 0xFF, 8); a <<= 8; } } } else { uint i, z = 0; PUT_BITS(0, 3); if (d->m_bits_in) { PUT_BITS(0, 8 - d->m_bits_in); } for (i = 2; i; --i, z ^= 0xFFFF) { PUT_BITS(z & 0xFFFF, 16); } } } assert(d->m_pOutput_buf < d->m_pOutput_buf_end); memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * MAX_HUFF_SYMBOLS_0); memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * MAX_HUFF_SYMBOLS_1); d->m_pLZ_code_buf = d->m_lz_code_buf + 1; d->m_pLZ_flags = d->m_lz_code_buf; d->m_num_flags_left = 8; d->m_lz_code_buf_dict_pos += d->m_total_lz_bytes; d->m_total_lz_bytes = 0; d->m_block_index++; if ((n = (int)(d->m_pOutput_buf - pOutput_buf_start)) != 0) { d->m_pPut_buf_func(d->m_output_buf, n, d->m_pPut_buf_user); } else if (pOutput_buf_start == d->m_output_buf) { error(""); } else { d->m_out_buf_ofs += n; } return d->m_output_flush_remaining; } #define READ_UNALIGNED_WORD(p) *(const uint16*)(p) static bool compress_fast(compressor *d) { // Faster, minimally featured LZRW1-style match+parse loop with better register utilization. Intended for applications where raw throughput is valued more highly than ratio. uint lookahead_pos = d->m_lookahead_pos, lookahead_size = d->m_lookahead_size, dict_size = d->m_dict_size, total_lz_bytes = d->m_total_lz_bytes, num_flags_left = d->m_num_flags_left; uint8 *pLZ_code_buf = d->m_pLZ_code_buf, *pLZ_flags = d->m_pLZ_flags; uint cur_pos = lookahead_pos & LZ_DICT_SIZE_MASK; while ((d->m_src_buf_left) || ((d->m_flush) && (lookahead_size))) { const uint COMP_FAST_LOOKAHEAD_SIZE = 4096; uint dst_pos = (lookahead_pos + lookahead_size) & LZ_DICT_SIZE_MASK; uint num_bytes_to_process = min(uint(d->m_src_buf_left), COMP_FAST_LOOKAHEAD_SIZE - lookahead_size); d->m_src_buf_left -= num_bytes_to_process; lookahead_size += num_bytes_to_process; while (num_bytes_to_process) { uint32 n = min(LZ_DICT_SIZE - dst_pos, num_bytes_to_process); memcpy(d->m_dict + dst_pos, d->m_pSrc, n); if (dst_pos < (MAX_MATCH_LEN - 1)) memcpy(d->m_dict + LZ_DICT_SIZE + dst_pos, d->m_pSrc, min(n, (MAX_MATCH_LEN - 1) - dst_pos)); d->m_pSrc += n; dst_pos = (dst_pos + n) & LZ_DICT_SIZE_MASK; num_bytes_to_process -= n; } dict_size = min(LZ_DICT_SIZE - lookahead_size, dict_size); if ((!d->m_flush) && (lookahead_size < COMP_FAST_LOOKAHEAD_SIZE)) break; while (lookahead_size >= 4) { uint cur_match_dist, cur_match_len = 1; uint8 *pCur_dict = d->m_dict + cur_pos; uint first_trigram = (*(const uint32 *)pCur_dict) & 0xFFFFFF; uint hash = (first_trigram ^ (first_trigram >> (24 - (LZ_HASH_BITS - 8)))) & LEVEL1_HASH_SIZE_MASK; uint probe_pos = d->m_hash[hash]; d->m_hash[hash] = (uint16)lookahead_pos; if (((cur_match_dist = (uint16)(lookahead_pos - probe_pos)) <= dict_size) && ((*(const uint32 *)(d->m_dict + (probe_pos &= LZ_DICT_SIZE_MASK)) & 0xFFFFFF) == first_trigram)) { const uint16 *p = (const uint16 *)pCur_dict; const uint16 *q = (const uint16 *)(d->m_dict + probe_pos); uint32 probe_len = 32; do { } while ( (READ_UNALIGNED_WORD(++p) == READ_UNALIGNED_WORD(++q)) && (READ_UNALIGNED_WORD(++p) == READ_UNALIGNED_WORD(++q)) && (READ_UNALIGNED_WORD(++p) == READ_UNALIGNED_WORD(++q)) && (READ_UNALIGNED_WORD(++p) == READ_UNALIGNED_WORD(++q)) && (--probe_len > 0) ); cur_match_len = ((uint)(p - (const uint16 *)pCur_dict) * 2) + (uint)(*(const uint8 *)p == *(const uint8 *)q); if (!probe_len) cur_match_len = cur_match_dist ? MAX_MATCH_LEN : 0; if ((cur_match_len < MIN_MATCH_LEN) || ((cur_match_len == MIN_MATCH_LEN) && (cur_match_dist >= 8U*1024U))) { cur_match_len = 1; *pLZ_code_buf++ = (uint8)first_trigram; *pLZ_flags = (uint8)(*pLZ_flags >> 1); d->m_huff_count[0][(uint8)first_trigram]++; } else { uint32 s0, s1; cur_match_len = min(cur_match_len, lookahead_size); assert((cur_match_len >= MIN_MATCH_LEN) && (cur_match_dist >= 1) && (cur_match_dist <= LZ_DICT_SIZE)); cur_match_dist--; pLZ_code_buf[0] = (uint8)(cur_match_len - MIN_MATCH_LEN); *(uint16 *)(&pLZ_code_buf[1]) = (uint16)cur_match_dist; pLZ_code_buf += 3; *pLZ_flags = (uint8)((*pLZ_flags >> 1) | 0x80); s0 = s_small_dist_sym[cur_match_dist & 511]; s1 = s_large_dist_sym[cur_match_dist >> 8]; d->m_huff_count[1][(cur_match_dist < 512) ? s0 : s1]++; d->m_huff_count[0][s_len_sym[cur_match_len - MIN_MATCH_LEN]]++; } } else { *pLZ_code_buf++ = (uint8)first_trigram; *pLZ_flags = (uint8)(*pLZ_flags >> 1); d->m_huff_count[0][(uint8)first_trigram]++; } if (--num_flags_left == 0) { num_flags_left = 8; pLZ_flags = pLZ_code_buf++; } total_lz_bytes += cur_match_len; lookahead_pos += cur_match_len; dict_size = min(dict_size + cur_match_len, LZ_DICT_SIZE); cur_pos = (cur_pos + cur_match_len) & LZ_DICT_SIZE_MASK; assert(lookahead_size >= cur_match_len); lookahead_size -= cur_match_len; if (pLZ_code_buf > &d->m_lz_code_buf[LZ_CODE_BUF_SIZE - 8]) { int n; d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; if ((n = flush_block(d, 0)) != 0) return (n < 0) ? false : true; total_lz_bytes = d->m_total_lz_bytes; pLZ_code_buf = d->m_pLZ_code_buf; pLZ_flags = d->m_pLZ_flags; num_flags_left = d->m_num_flags_left; } } while (lookahead_size) { uint8 lit = d->m_dict[cur_pos]; total_lz_bytes++; *pLZ_code_buf++ = lit; *pLZ_flags = (uint8)(*pLZ_flags >> 1); if (--num_flags_left == 0) { num_flags_left = 8; pLZ_flags = pLZ_code_buf++; } d->m_huff_count[0][lit]++; lookahead_pos++; dict_size = min(dict_size + 1, LZ_DICT_SIZE); cur_pos = (cur_pos + 1) & LZ_DICT_SIZE_MASK; lookahead_size--; if (pLZ_code_buf > &d->m_lz_code_buf[LZ_CODE_BUF_SIZE - 8]) { int n; d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; if ((n = flush_block(d, 0)) != 0) return (n < 0) ? false : true; total_lz_bytes = d->m_total_lz_bytes; pLZ_code_buf = d->m_pLZ_code_buf; pLZ_flags = d->m_pLZ_flags; num_flags_left = d->m_num_flags_left; } } } d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; return true; } status compress(compressor *d, const void *pIn_buf, const size_t pIn_buf_size, flush flush) { d->m_pIn_buf = pIn_buf; d->m_pSrc = (const uint8 *)(pIn_buf); d->m_src_buf_left = pIn_buf_size; d->m_out_buf_ofs = 0; d->m_flush = flush; d->m_wants_to_finish |= (flush == FINISH); if ((d->m_output_flush_remaining) || (d->m_finished)) return (d->m_prev_return_status = ((d->m_finished && !d->m_output_flush_remaining) ? STATUS_DONE : STATUS_OKAY)); if (((d->m_flags & GREEDY_PARSING_FLAG) != 0) && ((d->m_flags & (FILTER_MATCHES | FORCE_ALL_RAW_BLOCKS | RLE_MATCHES)) == 0)) { compress_fast(d); } else error(d->m_flags); if ((d->m_flags & (WRITE_ZLIB_HEADER | COMPUTE_ADLER32)) && (pIn_buf)) d->m_adler32 = adler32(d->m_adler32, (const uint8 *)pIn_buf, d->m_pSrc - (const uint8 *)pIn_buf); if ((flush) && (!d->m_lookahead_size) && (!d->m_src_buf_left) && (!d->m_output_flush_remaining)) { flush_block(d, flush); d->m_finished = (flush == FINISH); if (flush == FULL_FLUSH) { clear(d->m_hash); clear(d->m_next); d->m_dict_size = 0; } } return STATUS_DONE; } status init(compressor *d, put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) { d->m_pPut_buf_func = pPut_buf_func; d->m_pPut_buf_user = pPut_buf_user; d->m_flags = (uint)(flags); d->m_max_probes[0] = 1 + ((flags & 0xFFF) + 2) / 3; d->m_greedy_parsing = (flags & GREEDY_PARSING_FLAG) != 0; d->m_max_probes[1] = 1 + (((flags & 0xFFF) >> 2) + 2) / 3; if (!(flags & NONDETERMINISTIC_PARSING_FLAG)) clear(d->m_hash); d->m_lookahead_pos = d->m_lookahead_size = d->m_dict_size = d->m_total_lz_bytes = d->m_lz_code_buf_dict_pos = d->m_bits_in = 0; d->m_output_flush_ofs = d->m_output_flush_remaining = d->m_finished = d->m_block_index = d->m_bit_buffer = d->m_wants_to_finish = 0; d->m_pLZ_code_buf = d->m_lz_code_buf + 1; d->m_pLZ_flags = d->m_lz_code_buf; d->m_num_flags_left = 8; d->m_pOutput_buf = d->m_output_buf; d->m_pOutput_buf_end = d->m_output_buf; d->m_prev_return_status = STATUS_OKAY; d->m_saved_match_dist = d->m_saved_match_len = d->m_saved_lit = 0; d->m_adler32 = 1; d->m_pIn_buf = nullptr; d->m_flush = NO_FLUSH; d->m_pSrc = nullptr; d->m_src_buf_left = 0; d->m_out_buf_ofs = 0; memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * MAX_HUFF_SYMBOLS_0); memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * MAX_HUFF_SYMBOLS_1); return STATUS_OKAY; } struct output_buffer { size_t m_size, m_capacity; uint8 *m_pBuf; bool m_expandable; }; static bool output_buffer_putter(const void *pBuf, int len, void *pUser) { output_buffer *p = (output_buffer *)pUser; size_t new_size = p->m_size + len; if (new_size > p->m_capacity) { size_t new_capacity = p->m_capacity; uint8 *pNew_buf; if (!p->m_expandable) return false; do { new_capacity = max(128UL, new_capacity << 1U); } while (new_size > new_capacity); pNew_buf = (uint8*)realloc(p->m_pBuf, new_capacity); if (!pNew_buf) return false; p->m_pBuf = pNew_buf; p->m_capacity = new_capacity; } memcpy((uint8*)p->m_pBuf + p->m_size, pBuf, len); p->m_size = new_size; return true; } buffer<byte> deflate(const ref<byte> source, bool zlib) { buffer<byte> data; size_t size=0; assert(source.data && source.size); output_buffer out_buf = {0,0,0,0}; out_buf.m_expandable = true; compressor pComp; init(&pComp, output_buffer_putter, &out_buf, GREEDY_PARSING_FLAG|(zlib?WRITE_ZLIB_HEADER:0)); compress(&pComp, source.data, source.size, FINISH); size = out_buf.m_size; data.data = (byte*)out_buf.m_pBuf; data.capacity=data.size=size; assert(data, data.size, data.data, data.capacity, size); return data; }
[ "Matthias.Fauconneau@gmail.com" ]
Matthias.Fauconneau@gmail.com
90758ecf03b7411534602c85bfea520ee0e0b2b7
41b8ff0df332db314af269ce7f6f1e92f91a5e43
/src/dawn_native/vulkan/ResourceMemoryAllocatorVk.cpp
58dcd666d6c78f96c55c064065b36fde25f23116
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
skyvoid123/google-dawn-mobile
21367c489ce12f45f96aaf75413ee6d15f4d4950
dc3317da6cd5242e525d3230516cfd2bbff25fe9
refs/heads/master
2020-09-28T12:03:29.371391
2019-12-06T18:21:39
2019-12-06T18:21:39
226,775,370
0
0
Apache-2.0
2019-12-09T03:20:05
2019-12-09T03:20:04
null
UTF-8
C++
false
false
10,508
cpp
// Copyright 2019 The Dawn Authors // // 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 "dawn_native/vulkan/ResourceMemoryAllocatorVk.h" #include "dawn_native/BuddyMemoryAllocator.h" #include "dawn_native/ResourceHeapAllocator.h" #include "dawn_native/vulkan/DeviceVk.h" #include "dawn_native/vulkan/FencedDeleter.h" #include "dawn_native/vulkan/ResourceHeapVk.h" #include "dawn_native/vulkan/VulkanError.h" namespace dawn_native { namespace vulkan { namespace { // TODO(cwallez@chromium.org): This is a hardcoded heurstic to choose when to // suballocate but it should ideally depend on the size of the memory heaps and other // factors. constexpr uint64_t kMaxBuddySystemSize = 32ull * 1024ull * 1024ull * 1024ull; // 32GB constexpr uint64_t kMaxSizeForSubAllocation = 4ull * 1024ull * 1024ull; // 4MB // Have each bucket of the buddy system allocate at least some resource of the maximum // size constexpr uint64_t kBuddyHeapsSize = 2 * kMaxSizeForSubAllocation; } // anonymous namespace // SingleTypeAllocator is a combination of a BuddyMemoryAllocator and its client and can // service suballocation requests, but for a single Vulkan memory type. class ResourceMemoryAllocator::SingleTypeAllocator : public ResourceHeapAllocator { public: SingleTypeAllocator(Device* device, size_t memoryTypeIndex) : mDevice(device), mMemoryTypeIndex(memoryTypeIndex), mBuddySystem(kMaxBuddySystemSize, kBuddyHeapsSize, this) { } ~SingleTypeAllocator() override = default; ResultOrError<ResourceMemoryAllocation> AllocateMemory( const VkMemoryRequirements& requirements) { return mBuddySystem.Allocate(requirements.size, requirements.alignment); } void DeallocateMemory(const ResourceMemoryAllocation& allocation) { mBuddySystem.Deallocate(allocation); } // Implementation of the MemoryAllocator interface to be a client of BuddyMemoryAllocator ResultOrError<std::unique_ptr<ResourceHeapBase>> AllocateResourceHeap( uint64_t size) override { VkMemoryAllocateInfo allocateInfo; allocateInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; allocateInfo.pNext = nullptr; allocateInfo.allocationSize = size; allocateInfo.memoryTypeIndex = mMemoryTypeIndex; VkDeviceMemory allocatedMemory = VK_NULL_HANDLE; VkResult allocationResult = mDevice->fn.AllocateMemory( mDevice->GetVkDevice(), &allocateInfo, nullptr, &allocatedMemory); // Handle vkAllocateMemory error but differentiate OOM that we want to surface to // the application. if (allocationResult == VK_ERROR_OUT_OF_DEVICE_MEMORY) { return DAWN_OUT_OF_MEMORY_ERROR("OOM while creating the Vkmemory"); } DAWN_TRY(CheckVkSuccess(allocationResult, "vkAllocateMemory")); ASSERT(allocatedMemory != VK_NULL_HANDLE); return {std::make_unique<ResourceHeap>(allocatedMemory, mMemoryTypeIndex)}; } void DeallocateResourceHeap(std::unique_ptr<ResourceHeapBase> allocation) override { mDevice->GetFencedDeleter()->DeleteWhenUnused(ToBackend(allocation.get())->GetMemory()); } private: Device* mDevice; size_t mMemoryTypeIndex; BuddyMemoryAllocator mBuddySystem; }; // Implementation of ResourceMemoryAllocator ResourceMemoryAllocator::ResourceMemoryAllocator(Device* device) : mDevice(device) { const VulkanDeviceInfo& info = mDevice->GetDeviceInfo(); mAllocatorsPerType.reserve(info.memoryTypes.size()); for (size_t i = 0; i < info.memoryTypes.size(); i++) { mAllocatorsPerType.emplace_back(std::make_unique<SingleTypeAllocator>(mDevice, i)); } } ResourceMemoryAllocator::~ResourceMemoryAllocator() = default; ResultOrError<ResourceMemoryAllocation> ResourceMemoryAllocator::Allocate( const VkMemoryRequirements& requirements, bool mappable) { // The Vulkan spec guarantees at least on memory type is valid. int memoryType = FindBestTypeIndex(requirements, mappable); ASSERT(memoryType >= 0); VkDeviceSize size = requirements.size; // If the resource is too big, allocate memory just for it. // Also allocate mappable resources separately because at the moment the mapped pointer // is part of the resource and not the heap, which doesn't match the Vulkan model. // TODO(cwallez@chromium.org): allow sub-allocating mappable resources, maybe. if (requirements.size >= kMaxSizeForSubAllocation || mappable) { std::unique_ptr<ResourceHeapBase> resourceHeap; DAWN_TRY_ASSIGN(resourceHeap, mAllocatorsPerType[memoryType]->AllocateResourceHeap(size)); void* mappedPointer = nullptr; if (mappable) { DAWN_TRY( CheckVkSuccess(mDevice->fn.MapMemory(mDevice->GetVkDevice(), ToBackend(resourceHeap.get())->GetMemory(), 0, size, 0, &mappedPointer), "vkMapMemory")); } AllocationInfo info; info.mMethod = AllocationMethod::kDirect; return ResourceMemoryAllocation(info, /*offset*/ 0, resourceHeap.release(), static_cast<uint8_t*>(mappedPointer)); } else { return mAllocatorsPerType[memoryType]->AllocateMemory(requirements); } } void ResourceMemoryAllocator::Deallocate(ResourceMemoryAllocation* allocation) { switch (allocation->GetInfo().mMethod) { // Some memory allocation can never be initialized, for example when wrapping // swapchain VkImages with a Texture. case AllocationMethod::kInvalid: break; // For direct allocation we can put the memory for deletion immediately and the fence // deleter will make sure the resources are freed before the memory. case AllocationMethod::kDirect: mDevice->GetFencedDeleter()->DeleteWhenUnused( ToBackend(allocation->GetResourceHeap())->GetMemory()); break; // Suballocations aren't freed immediately, otherwise another resource allocation could // happen just after that aliases the old one and would require a barrier. // TODO(cwallez@chromium.org): Maybe we can produce the correct barriers to reduce the // latency to reclaim memory. case AllocationMethod::kSubAllocated: mSubAllocationsToDelete.Enqueue(*allocation, mDevice->GetPendingCommandSerial()); break; default: UNREACHABLE(); break; } // Invalidate the underlying resource heap in case the client accidentally // calls DeallocateMemory again using the same allocation. allocation->Invalidate(); } void ResourceMemoryAllocator::Tick(Serial completedSerial) { for (const ResourceMemoryAllocation& allocation : mSubAllocationsToDelete.IterateUpTo(completedSerial)) { ASSERT(allocation.GetInfo().mMethod == AllocationMethod::kSubAllocated); size_t memoryType = ToBackend(allocation.GetResourceHeap())->GetMemoryType(); mAllocatorsPerType[memoryType]->DeallocateMemory(allocation); } mSubAllocationsToDelete.ClearUpTo(completedSerial); } int ResourceMemoryAllocator::FindBestTypeIndex(VkMemoryRequirements requirements, bool mappable) { const VulkanDeviceInfo& info = mDevice->GetDeviceInfo(); // Find a suitable memory type for this allocation int bestType = -1; for (size_t i = 0; i < info.memoryTypes.size(); ++i) { // Resource must support this memory type if ((requirements.memoryTypeBits & (1 << i)) == 0) { continue; } // Mappable resource must be host visible if (mappable && (info.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) == 0) { continue; } // Mappable must also be host coherent. if (mappable && (info.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) == 0) { continue; } // Found the first candidate memory type if (bestType == -1) { bestType = static_cast<int>(i); continue; } // For non-mappable resources, favor device local memory. if (!mappable) { if ((info.memoryTypes[bestType].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) == 0 && (info.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) != 0) { bestType = static_cast<int>(i); continue; } } // All things equal favor the memory in the biggest heap VkDeviceSize bestTypeHeapSize = info.memoryHeaps[info.memoryTypes[bestType].heapIndex].size; VkDeviceSize candidateHeapSize = info.memoryHeaps[info.memoryTypes[i].heapIndex].size; if (candidateHeapSize > bestTypeHeapSize) { bestType = static_cast<int>(i); continue; } } return bestType; } }} // namespace dawn_native::vulkan
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
de6f34bed28a83f6dc8a14eaad0905b05174352a
1cedf5abe49887cf7a3b733231880413ec209252
/TinyGame/Poker/FCSolver/CompareAlgorithms.h
7484126c5abad2472cea36dd78965df63879a908
[]
no_license
uvbs/GameProject
67d9f718458e0da636be4ad293c9e92a721a8921
0105e36971950916019a970df1b4955835e121ce
refs/heads/master
2020-04-14T22:35:24.643887
2015-09-02T06:55:54
2015-09-02T06:55:54
42,047,051
1
0
null
2015-09-07T10:34:34
2015-09-07T10:34:33
null
UTF-8
C++
false
false
2,800
h
#ifndef MMANN_COMPARE_ALGORITHMS_H #define MMANN_COMPARE_ALGORITHMS_H //////////////////////////////////////////////// ///\file CompareAlgorithms.h ///\brief This file contains the comparing algorithm classes ///\author Michael Mann ///\version 1.0 ///\date August 2002 //////////////////////////////////////////////// #include <string.h> #ifdef min #undef min #endif ///find the minimum of two values #define min(a,b) ((a)<(b)?(a):(b)) ///\brief Abstract, templated compare algorithm class template <class Data, class ConfigData> class ACompareNodesAlgorithm { public: ///\brief Compare function ///\param Node1 is the first item to compare ///\param Node2 is the second item to compare ///\param TConfigData is any configurate data needed for the compare ///\return Returns -1 if Node1 < Node2. Returns 1 if Node1 > Node2. Returns 0 if Node1 = Node2 virtual int Compare(const Data* Node1, const Data* Node2, const ConfigData* TConfigData) = 0; }; ///\brief templated compare algorithm class /// ///This compare algorithm compares the data through < and > template <class Data, class ConfigData> class SimpleCompareNodesAlgorithm : public ACompareNodesAlgorithm<Data, ConfigData> { public: ///\brief Compare function ///\param Node1 is the first item to compare ///\param Node2 is the second item to compare ///\param TConfigData is any configurate data needed for the compare ///\return Returns -1 if Node1 < Node2. Returns 1 if Node1 > Node2. Returns 0 if Node1 = Node2 virtual int Compare(const Data* Node1, const Data* Node2, const ConfigData* TConfigData); }; template <class Data, class ConfigData> int SimpleCompareNodesAlgorithm<Data, ConfigData>::Compare(const Data* Node1, const Data* Node2, const ConfigData* TConfigData) { if (*Node1 < *Node2) return -1; if (*Node1 > *Node2) return 1; return 0; } ///\brief templated compare algorithm class /// ///This compare algorithm compares the data through a compare function ///This compare algorithm assumes the class being compares has a Compare() function template <class Data, class ConfigData> class CompareFunctionCompareNodesAlgorithm : public ACompareNodesAlgorithm<Data, ConfigData> { public: ///\brief Compare function ///\param Node1 is the first item to compare ///\param Node2 is the second item to compare ///\param TConfigData is any configurate data needed for the compare ///\return Returns -1 if Node1 < Node2. Returns 1 if Node1 > Node2. Returns 0 if Node1 = Node2 virtual int Compare(const Data* Node1, const Data* Node2, const ConfigData* TConfigData); }; template <class Data, class ConfigData> int CompareFunctionCompareNodesAlgorithm<Data, ConfigData>::Compare(const Data* Node1, const Data* Node2, const ConfigData* TConfigData) { return ((Data*)Node1)->Compare(Node2); } #endif
[ "adfhugo@gmail.com" ]
adfhugo@gmail.com
d5491ecceb1c2d17e515915a9c773238b1a1a58b
52a5f9916d22479dcd851a509aa91c9a50da4b3b
/src/houdini/custom/USD/GEO_HAPIGeo.h
fa49401d2a25957ba5d45ea3aae9b247d60dab56
[ "Apache-2.0" ]
permissive
all-in-one-of/HoudiniUsdBridge
2dec8b8227b8ffb48a6485ab07b8b327380d20b5
034bd6815a863ce56ba77504c95ebc5787065af6
refs/heads/master
2021-01-04T19:10:37.781092
2020-02-15T06:00:18
2020-02-15T06:00:18
240,723,580
1
0
Apache-2.0
2020-02-15T14:10:47
2020-02-15T14:10:47
null
UTF-8
C++
false
false
1,182
h
/* * Copyright 2020 Side Effects Software Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef __GEO_HAPI_GEO_H__ #define __GEO_HAPI_GEO_H__ #include "GEO_HAPIPart.h" #include <UT/UT_Array.h> typedef UT_Array<GEO_HAPIPart> GEO_HAPIPartArray; /// \class GEO_HAPIGeo /// /// Wrapper class for Houdini Engine Geometry /// class GEO_HAPIGeo { public: GEO_HAPIGeo(); ~GEO_HAPIGeo(); bool loadGeoData(const HAPI_Session &session, HAPI_GeoInfo &geo, UT_WorkBuffer &buf); const GEO_HAPIPartArray *getParts() { return &myParts; } private: GEO_HAPIPartArray myParts; }; #endif // __GEO_HAPI_GEO_H__
[ "prisms@maligne.sidefx.com" ]
prisms@maligne.sidefx.com
3ad50039ef2f5718eb22f3dc9d00323163fc074c
65047887d3bf34bfd669c64b91c12bb96bf338ef
/uva/401.cpp
81a9a0caa9cdd8cf0ac20c30808861881ef618d7
[]
no_license
amy58328/solved_problems
523afe06e125d6527d8d2db35f632cf63e8b99ee
4abc244e17bb6bd751b935f9b587df6cb2391eb5
refs/heads/master
2020-03-29T15:37:52.720205
2018-09-19T12:50:48
2018-09-19T12:50:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,663
cpp
#include <iostream> #include <cstring> #include <map> using namespace std; map<char, char> m; // bool isPalindrome(const char str[]) // { // int length = strlen(str); // int half, same = 0; // // Odd // if(length % 2 != 0) // { // half = (length + 1) / 2; // } // else // { // half = length / 2; // } // // std::cout << half << std::endl; // for(int i = 0; i < half; i++) // { // if(str[i] == str[length - 1 -i] && isalpha(str[i]) && isalpha(str[length - 1 - i])) // { // same++; // } // } // // std::cout << same << std::endl; // if(same == half) // { // return true; // } // else // { // return false; // } // } bool isMirror(const char str[]) { int length = strlen(str); int half, same = 0; // Odd if(length % 2 != 0) { half = (length+1) / 2; } else { half = length / 2; } for(int i = 0; i < half; i++) { // std::cout << m[str[i]] << std::endl; if(m[str[i]] == str[length - 1 -i]) { same++; } } if(length % 2 != 0 && same == half) { if(m[str[half - 1]] == str[half - 1]) { return true; } else { return false; } } else if(same == half) { return true; } else { return false; } } void initMap() { m['A'] = 'A'; m['E'] = '3'; m['H'] = 'H'; m['I'] = 'I'; m['J'] = 'L'; m['L'] = 'J'; m['M'] = 'M'; m['O'] = 'O'; m['S'] = '2'; m['T'] = 'T'; m['U'] = 'U'; m['V'] = 'V'; m['W'] = 'W'; m['X'] = 'X'; m['Y'] = 'Y'; m['Z'] = '5'; m['1'] = '1'; m['2'] = 'S'; m['3'] = 'E'; m['5'] = 'Z'; m['8'] = '8'; } int main() { #ifndef ONLINE_JUDGE freopen("./testdata/401.in", "r", stdin); freopen("./testdata/401.out", "w", stdout); #endif initMap(); char str[100]; while(scanf("%s", str) != EOF) { int length = strlen(str); int half, same = 0, mirror = 0, char_num = 0; // Odd if(length % 2 != 0) { half = (length + 1) / 2; } else { half = length / 2; } // std::cout << half << std::endl; for(int i = 0; i < half; i++) { if(str[i] == str[length - 1 -i]) { same++; } // std::cout << m[str[i]] << ' ' << str[length - 1] << std::endl; if(m[str[i]] != 0 && m[str[i]] == str[length - 1 - i]) { mirror++; } // if(isalpha(str[i]) && isalpha(str[length - 1 - i])) // char_num++; } // print result if(same == half) { if(mirror == half) { printf("%s -- is a mirrored palindrome.\n", str); } else { printf("%s -- is a regular palindrome.\n", str); } } else { if(mirror == half) { printf("%s -- is a mirrored string.\n", str); } else { printf("%s -- is not a palindrome.\n", str); } } putchar('\n'); } return 0; }
[ "a82611141@gmail.com" ]
a82611141@gmail.com
f4c4b1904aa2bca363b51f2fc795ab65bd39ac4d
5ce101de0befa9a599442c215e586c7e8dc79a17
/Algoritmos/Algoritmos_com_DEV C/Estudo_em_C/exemplo_aula_adri.cpp
68ca98dbb1398ca1d0a73ce384c8700f6ec25463
[]
no_license
diegors-prog/ULBRA
6f3de5a9f074b43993730078326be4bfa6a1e727
8c550300834225080be8c7208a964879f035fef9
refs/heads/master
2022-09-20T01:28:53.112095
2022-08-31T00:31:07
2022-08-31T00:31:07
249,788,342
0
1
null
null
null
null
UTF-8
C++
false
false
274
cpp
#include <stdio.h> int main() { int idade, x; float soma = 0, media; for (x = 1; x <= 5; x = x++) { printf("Informe a idade: \n"); scanf("%i", &idade); soma = soma + idade; } media = soma/5; printf("Media de idade: %.2f", media); return 0; }
[ "diegors@rede.ulbra.br" ]
diegors@rede.ulbra.br
f2b28042895ed98978963ce0096086b7ac954de4
21553f6afd6b81ae8403549467230cdc378f32c9
/arm/cortex/Freescale/SKEAZ1284/include/arch/reg/spi1.hpp
524e2c1c0ad970e58a6ee03c5c059855b7589165
[]
no_license
digint/openmptl-reg-arm-cortex
3246b68dcb60d4f7c95a46423563cab68cb02b5e
88e105766edc9299348ccc8d2ff7a9c34cddacd3
refs/heads/master
2021-07-18T19:56:42.569685
2017-10-26T11:11:35
2017-10-26T11:11:35
108,407,162
3
1
null
null
null
null
UTF-8
C++
false
false
4,306
hpp
/* * OpenMPTL - C++ Microprocessor Template Library * * This program is a derivative representation of a CMSIS System View * Description (SVD) file, and is subject to the corresponding license * (see "Freescale CMSIS-SVD License Agreement.pdf" in the parent directory). * * 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. */ //////////////////////////////////////////////////////////////////////// // // Import from CMSIS-SVD: "Freescale/SKEAZ1284.svd" // // vendor: Freescale Semiconductor, Inc. // vendorID: Freescale // name: SKEAZ1284 // series: Kinetis_EA // version: 1.6 // description: SKEAZ1284 Freescale Microcontroller // -------------------------------------------------------------------- // // C++ Header file, containing architecture specific register // declarations for use in OpenMPTL. It has been converted directly // from a CMSIS-SVD file. // // https://digint.ch/openmptl // https://github.com/posborne/cmsis-svd // #ifndef ARCH_REG_SPI1_HPP_INCLUDED #define ARCH_REG_SPI1_HPP_INCLUDED #warning "using untested register declarations" #include <register.hpp> namespace mptl { /** * Serial Peripheral Interface */ struct SPI1 { static constexpr reg_addr_t base_addr = 0x40077000; /** * SPI Control Register 1 */ struct C1 : public reg< uint8_t, base_addr + 0, rw, 0x4 > { using type = reg< uint8_t, base_addr + 0, rw, 0x4 >; using LSBFE = regbits< type, 0, 1 >; /**< LSB First (shifter direction) */ using SSOE = regbits< type, 1, 1 >; /**< Slave Select Output Enable */ using CPHA = regbits< type, 2, 1 >; /**< Clock Phase */ using CPOL = regbits< type, 3, 1 >; /**< Clock Polarity */ using MSTR = regbits< type, 4, 1 >; /**< Master/Slave Mode Select */ using SPTIE = regbits< type, 5, 1 >; /**< SPI Transmit Interrupt Enable */ using SPE = regbits< type, 6, 1 >; /**< SPI System Enable */ using SPIE = regbits< type, 7, 1 >; /**< SPI Interrupt Enable: for SPRF and MODF */ }; /** * SPI Control Register 2 */ struct C2 : public reg< uint8_t, base_addr + 0x1, rw, 0 > { using type = reg< uint8_t, base_addr + 0x1, rw, 0 >; using SPC0 = regbits< type, 0, 1 >; /**< SPI Pin Control 0 */ using SPISWAI = regbits< type, 1, 1 >; /**< SPI Stop in Wait Mode */ using BIDIROE = regbits< type, 3, 1 >; /**< Bidirectional Mode Output Enable */ using MODFEN = regbits< type, 4, 1 >; /**< Master Mode-Fault Function Enable */ using SPMIE = regbits< type, 7, 1 >; /**< SPI Match Interrupt Enable */ }; /** * SPI Baud Rate Register */ struct BR : public reg< uint8_t, base_addr + 0x2, rw, 0 > { using type = reg< uint8_t, base_addr + 0x2, rw, 0 >; using SPR = regbits< type, 0, 4 >; /**< SPI Baud Rate Divisor */ using SPPR = regbits< type, 4, 3 >; /**< SPI Baud Rate Prescale Divisor */ }; /** * SPI Status Register */ struct S : public reg< uint8_t, base_addr + 0x3, rw, 0x20 > { using type = reg< uint8_t, base_addr + 0x3, rw, 0x20 >; using MODF = regbits< type, 4, 1 >; /**< Master Mode Fault Flag */ using SPTEF = regbits< type, 5, 1 >; /**< SPI Transmit Buffer Empty Flag */ using SPMF = regbits< type, 6, 1 >; /**< SPI Match Flag */ using SPRF = regbits< type, 7, 1 >; /**< SPI Read Buffer Full Flag */ }; /** * SPI Data Register */ struct D : public reg< uint8_t, base_addr + 0x5, rw, 0 > { using type = reg< uint8_t, base_addr + 0x5, rw, 0 >; using Bits = regbits< type, 0, 8 >; /**< Data (low byte) */ }; /** * SPI Match Register */ struct M : public reg< uint8_t, base_addr + 0x7, rw, 0 > { using type = reg< uint8_t, base_addr + 0x7, rw, 0 >; using Bits = regbits< type, 0, 8 >; /**< Hardware compare value (low byte) */ }; }; } // namespace mptl #endif // ARCH_REG_SPI1_HPP_INCLUDED
[ "axel@tty0.ch" ]
axel@tty0.ch
f9087b584884b48cb2c32d3e37dc3e6c52ff1036
bb92586c3accb07b99b5004d719434fd018bd135
/leetcode/Longest_Common_Prefix.cc
b1411af17b357aab1dfaa89d101a29fbc6d3f85e
[]
no_license
lc19890306/Exercise
4a6070296aadb021d35dfae54d9352c289b9c2db
153f73c015a9c64aa35aa440fce926c1d26f76c8
refs/heads/master
2021-07-17T21:01:15.881080
2021-02-19T15:34:55
2021-02-19T15:34:55
40,798,802
1
0
null
null
null
null
UTF-8
C++
false
false
668
cc
class Solution { public: string longestCommonPrefix(vector<string>& strs) { if (strs.empty()) return ""; auto common_prefix(strs[0]); for (int i(1); i < strs.size(); ++i) common_prefix = commonPrefix(common_prefix, strs[i]); return common_prefix; } private: string commonPrefix(string a, string b) { int length(min(a.length(), b.length())); for (int i(0); i < length; ++i) if (a[i] != b[i]) return a.substr(0, i); // the longer string begins with the shorter string // return the shorter string return a.length() == length ? a : b; } };
[ "liu28333613@gmail.com" ]
liu28333613@gmail.com
aae02ab1751d63a3750579058a8ac1d2b7133ba9
25b4afbcad749a833504269be17a9ad785370fef
/Pod/musicFramework/impl/LcmGcd.cpp
b3586e76ef5cbff755b53854e801fd78aa056011
[ "MIT" ]
permissive
Bone111/MusicXMLParser
87eee0a990a49a57a54a59e6ef2baa981c83a740
674f6b52634abb95008cc04ee02f4df0055851a6
refs/heads/master
2020-03-27T04:26:35.847365
2017-09-30T08:19:53
2017-09-30T08:19:53
145,939,832
3
2
MIT
2018-08-24T03:51:52
2018-08-24T03:51:51
null
UTF-8
C++
false
false
3,395
cpp
// MusicXML Class Library // Copyright (c) by Matthew James Briggs // Distributed under the MIT License #include "../impl/LcmGcd.h" #include "../utility/Throw.h" #include <exception> #include <cmath> #include <set> namespace mx { namespace impl { int greatestCommonDivisor( int a, int b ) { a = std::abs( a ); b = std::abs( b ); // http://stackoverflow.com/a/4229930/2779792 for (;;) { if ( a == 0 ) return b; b %= a; if ( b == 0 ) return a; a %= b; } } int greatestCommonDivisor( std::initializer_list<int> integers ) { int gcd = 1; if ( integers.size() == 0 ) { return gcd; } else if( integers.size() == 1 ) { gcd = std::abs( *( integers.begin() ) ); return gcd == 0 ? 1 : gcd; } else { bool zeroEncountered = false; auto iter = integers.begin(); auto end = integers.end(); gcd = *iter; zeroEncountered = ( gcd == 0 ); ++iter; for (; iter != end; ++iter ) { if ( *iter == 0 ) { if ( zeroEncountered ) { MX_THROW("initializer list for gcd function may contain no more than a single 0") } zeroEncountered = true; } gcd = greatestCommonDivisor( gcd, *iter ); } } return gcd; } int leastCommonMultiple( int a, int b ) { // http://stackoverflow.com/a/4229930/2779792 auto temp = greatestCommonDivisor(a, b); auto answer = temp ? (a / temp * b) : 0; if ( answer < 0 ) { answer *= -1; } return answer; } int leastCommonMultiple( const std::set<int>& integers ) { int answer = 0; if ( integers.size() == 0 ) { return 0; } else if( integers.size() == 1 ) { if ( *( integers.cbegin() ) == 0 ) { MX_THROW( "zeros not allowed" ) } return std::abs( *( integers.begin() ) ); } else { auto a = integers.cbegin(); auto b = integers.cbegin(); auto e = integers.cend(); ++b; if ( *a == 0 || *b == 0 ) { MX_THROW( "zeros not allowed" ) } answer = leastCommonMultiple( *a, *b ); for (; b != e ; ++b ) { if ( *b == 0 ) { MX_THROW( "zeros not allowed") } answer = leastCommonMultiple( answer, *b ); } } return answer; } } }
[ "403554355@qq.com" ]
403554355@qq.com
735d5f65207252bfc64fa0f8ba8f818d9feb87cd
59dc69a22f1e2ea41074d2a9d32f461518eb13e2
/src/a2d/core/object2d.hpp
bbcdf36ec69690ef92744d1beaf2139556f9ccbb
[ "MIT" ]
permissive
mowenli/A2D
4956140152e64fa402bad816fbe0ba36e6017352
278b8e40be74c0f0257b1062f009995462f983fa
refs/heads/master
2022-01-19T20:53:48.286678
2019-05-30T23:42:05
2019-05-30T23:58:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,071
hpp
// // Created by selya on 26.10.2018. // #ifndef A2D_OBJECT2D_HPP #define A2D_OBJECT2D_HPP #include <a2d/math/vector.hpp> #include <a2d/math/matrix.hpp> #include <a2d/core/ref_counter.hpp> #include <a2d/core/macro.hpp> #include <a2d/core/engine.hpp> #include <a2d/core/component.hpp> #include <a2d/core/log.hpp> #include <a2d/core/animation/animation_curve.hpp> #include <set> #include <unordered_map> #include <typeindex> #include <type_traits> namespace a2d { class Drawable; class Animation; class SpriteBatch; template<class A> class Animator; class Object2D final : public ref_counter { friend class Engine; friend class Renderer; friend class Camera; friend class Physics; friend class Drawable; friend class Component; // Hierarchy intrusive_ptr<Object2D> parent; std::list<intrusive_ptr<Object2D>> children; std::list<intrusive_ptr<Object2D>>::const_iterator iter_in_parent; std::unordered_map<std::type_index, std::set<intrusive_ptr<Component>>> components; // Transform Matrix4f transform_matrix; Vector2f local_position; Vector2f local_scale; float local_rotation; // Drawing int layer; Vector4f color; // Helpers bool active; bool active_transitive; std::string tag; intrusive_ptr<Drawable> drawable; struct compare_objects { bool operator()(const intrusive_ptr<Object2D> &lhs, const intrusive_ptr<Object2D> &rhs) const; }; public: DELETE_DEFAULT_CONSTRUCTORS_AND_OPERATORS(Object2D) // Getters intrusive_ptr<Object2D> GetParent() const; const std::list<intrusive_ptr<Object2D>> &GetChildren() const; const a2d::Matrix4f &GetTransformMatrix() const; const Vector2f &GetLocalPosition() const; const Vector2f &GetLocalScale() const; float GetLocalRotation() const; Vector2f GetPosition() const; float GetRotation() const; Vector2f GetRelativePosition(const intrusive_ptr<Object2D> &origin) const; float GetRelativeRotation(const intrusive_ptr<Object2D> &origin) const; Vector2f WorldToLocalPoint(const Vector2f &world_point); Vector2f LocalToWorldPoint(const Vector2f &local_point); int GetLayer() const; const Vector4f &GetColor() const; bool IsActive() const; bool IsActiveTransitive() const; const std::string &GetTag() const; intrusive_ptr<Drawable> GetDrawable() const; template<class T> typename std::enable_if<std::is_base_of<Drawable, T>::value, intrusive_ptr<T>>::type GetDrawableAs() const; // Setters void SetLocalPosition(float x, float y); void SetLocalPosition(const Vector2f &position); void SetLocalScale(float x, float y); void SetLocalScale(const Vector2f &scale); void SetLocalRotation(float rotation); void SetPosition(float x, float y); void SetPosition(const Vector2f &position); void SetRotation(float rotation); void SetLayer(int layer); void SetColor(float r, float g, float b, float a); void SetColor(const Vector4f &color); void SetActive(bool active); void SetTag(const std::string &tag); // Manage void Attach(const intrusive_ptr<Object2D> &parent); void Destroy(); void DestroyAllComponents(); template<class Anim> typename std::enable_if<std::is_base_of<Animation, Anim>::value, intrusive_ptr<Animator<Anim>>>::type AddAnimation(const Anim &animation, float duration, int times = 1, bool mirror = false, float delay = 0.0f, bool start_paused = false, AnimationCurve curve = AnimationCurve::Linear); template<class T> typename std::enable_if<std::is_base_of<Component, T>::value, intrusive_ptr<T>>::type AddComponent(); template<class T, class ...Args> typename std::enable_if<std::is_base_of<Component, T>::value, intrusive_ptr<T>>::type AddComponent(Args && ...args); template<class T> typename std::enable_if<std::is_base_of<Component, T>::value, intrusive_ptr<T>>::type GetComponent(bool look_for_base = false) const; template<class T> typename std::enable_if<std::is_base_of<Component, T>::value, std::set<intrusive_ptr<T>>>::type GetComponents(bool look_for_base = false) const; static intrusive_ptr<Object2D> Create(); private: Object2D(); ~Object2D() override; // Draw void Draw(SpriteBatch &sprite_batch, const Vector4f &parent_color = Vector4f(1)); // Events void OnAttach(); void OnDetach(); void OnTransform(const intrusive_ptr<Object2D> &object, bool apply_local = true, bool scaling = false); }; // // Template implementation // template<class T> typename std::enable_if<std::is_base_of<Drawable, T>::value, intrusive_ptr<T>>::type Object2D::GetDrawableAs() const { return dynamic_cast<T *>(drawable.get()); } template<class Anim> typename std::enable_if<std::is_base_of<Animation, Anim>::value, intrusive_ptr<Animator<Anim>>>::type Object2D::AddAnimation(const Anim &animation, float duration, int times, bool mirror, float delay, bool start_paused, AnimationCurve curve) { return AddComponent<Animator<Anim>>(animation, duration, times, mirror, delay, start_paused, curve); } template<class T> typename std::enable_if<std::is_base_of<a2d::Component, T>::value, intrusive_ptr<T>>::type Object2D::AddComponent() { std::type_index t_index = typeid(T); intrusive_ptr<Component> component = new T; components[t_index].emplace(component); component->object_2d = this; //Engine::AddCommand([component]() { component->Initialize(); component->initialized = true; component->OnAttach(); component->SetActive(true); if (Engine::IsPlaying()) component->OnResume(); Engine::components.emplace(component); //}); return component; } template<class T, class ...Args> typename std::enable_if<std::is_base_of<a2d::Component, T>::value, intrusive_ptr<T>>::type Object2D::AddComponent(Args && ...args) { std::type_index t_index = typeid(T); intrusive_ptr<Component> component = new T(std::forward<Args>(args)...); components[t_index].emplace(component); component->object_2d = this; //Engine::AddCommand([component]() { component->Initialize(); component->initialized = true; component->OnAttach(); component->SetActive(true); if (Engine::IsPlaying()) component->OnResume(); Engine::components.emplace(component); //}); return component; } template<class T> typename std::enable_if<std::is_base_of<a2d::Component, T>::value, intrusive_ptr<T>>::type Object2D::GetComponent(bool look_for_base) const { if (look_for_base) { for (auto &i1 : components) { for (auto &i2 : i1.second) { T *t = dynamic_cast<T *>(i2.get()); if (t) { return t; } } } //LOG_TRACE("Can't find component"); return nullptr; } else { if (components.empty()) { //LOG_TRACE("Can't find component"); return nullptr; } auto iter = components.find(typeid(T)); if (iter == components.end() || iter->second.empty()) { //LOG_TRACE("Can't find component"); return nullptr; } return *iter->second.begin(); } } template<class T> typename std::enable_if<std::is_base_of<a2d::Component, T>::value, std::set<intrusive_ptr<T>>>::type Object2D::GetComponents(bool look_for_base) const { if (look_for_base) { std::set<intrusive_ptr<T>> s; for (auto &i1 : components) { for (auto &i2 : i1.second) { T *t = dynamic_cast<T *>(i2.get()); if (t) { s.emplace(t); } } } return s; } else { auto iter = components.find(typeid(T)); if (iter == components.end()) return std::set<intrusive_ptr<T> >(); std::set<intrusive_ptr<T>> s(iter->second.begin(), iter->second.end()); return s; } } } //namespace a2d #endif //A2D_OBJECT2D_HPP
[ "selya.main@gmail.com" ]
selya.main@gmail.com
b2e5cfdbca2aca1f70e93b7e11512818bf9b00bd
2b62ac284da5f41880774b2c9ee5711688aeca3d
/ProgramA/Motor/motorsettingdialog.cpp
61656c3d7499d259c771827b5da4c1c014f09c4e
[]
no_license
kia016/QtCustomWidgetPlugin
577d3d5a54edac098080829613478002b68124f9
7a0d8d37c48751e3c289588b92110d34e47d6058
refs/heads/main
2023-03-17T17:05:40.661226
2021-03-11T06:10:56
2021-03-11T06:10:56
346,573,270
1
0
null
null
null
null
UTF-8
C++
false
false
4,411
cpp
#include "motorsettingdialog.h" #include "ui_motorsettingdialog.h" MotorSettingDialog::MotorSettingDialog(MotorControl *motor, SqliteClass *db, QWidget *parent) : QDialog(parent), ui(new Ui::MotorSettingDialog), motor_(motor)/*, db_(db)*/ { ui->setupUi(this); setWindowFlags(Qt::CustomizeWindowHint); Init(); QApplication::processEvents(); setFixedSize(size()); } MotorSettingDialog::~MotorSettingDialog() { delete ui; } void MotorSettingDialog::ReceiveFromMotor(QString msg) { if (msg == "stop") { // SetText(QString("Cost : %1").arg(t_.elapsed())); SetText(QString("Cost : %1 %2").arg(QString::number(t_.restart()), msg)); // motor_->Ardu_Clear(); } else { count_++; SetText(QString("Cost : %1 %2 %3").arg(QString::number(t_.restart()), msg, QString::number(count_))); } } void MotorSettingDialog::TimerTimeOut() { timer_.stop(); motor_->Ardu_Clear(); ui->pushButton_home->setEnabled(true); ui->pushButton_left->setEnabled(true); ui->pushButton_clear->setEnabled(true); ui->pushButton_close->setEnabled(true); ui->pushButton_right->setEnabled(true); } void MotorSettingDialog::Init() { t_.start(); count_ = 0; ui->doubleSpinBox_speed->setValue(GetSpeed()); ui->doubleSpinBox_interval->setValue(GetInterval()); connect(&timer_, &QTimer::timeout, this, &MotorSettingDialog::TimerTimeOut); } double MotorSettingDialog::GetSpeed() { return motor_->GetSpeed(); } void MotorSettingDialog::SetSpeed(double value) { motor_->SetSpeed(value); } double MotorSettingDialog::GetInterval() { return motor_->GetInterval(); } void MotorSettingDialog::SetInterval(double value) { motor_->SetInterval(value); } void MotorSettingDialog::SetText(QString text) { ui->textEdit->append(text); ui->textEdit->verticalScrollBar()->setValue(ui->textEdit->verticalScrollBar()->maximum()); } void MotorSettingDialog::on_doubleSpinBox_speed_valueChanged(double arg1) { SetSpeed(arg1); ui->horizontalSlider_speed->setValue(arg1 * 100); // db_->UpdateData("MOTOR_TABLE", // {QString("SPEED = '%1'").arg(QString::number(arg1))}); } void MotorSettingDialog::on_horizontalSlider_speed_valueChanged(int value) { SetSpeed(value / 100.0); ui->doubleSpinBox_speed->setValue(value / 100.0); // db_->UpdateData("MOTOR_TABLE", // {QString("SPEED = '%1'").arg(QString::number(value/100.0))}); } void MotorSettingDialog::on_doubleSpinBox_interval_valueChanged(double arg1) { SetInterval(arg1); // db_->UpdateData("MOTOR_TABLE", // {QString("INTERVAL = '%1'").arg(QString::number(arg1))}); } void MotorSettingDialog::on_pushButton_home_clicked() { t_.start(); count_ = 0; motor_->GoHmoe(); timer_.start(2000); ui->pushButton_home->setEnabled(false); ui->pushButton_left->setEnabled(false); ui->pushButton_clear->setEnabled(false); ui->pushButton_close->setEnabled(false); ui->pushButton_right->setEnabled(false); // motor_->Ardu_TouchTrigger(0, 360/GetInterval()); // motor_->motor_.MoveAbsolutelyDistance(GetSpeed(), 0); } void MotorSettingDialog::on_pushButton_left_clicked() { t_.start(); count_ = 0; // motor_->Move(false); motor_->GoAround(false); timer_.start(2000); ui->pushButton_home->setEnabled(false); ui->pushButton_left->setEnabled(false); ui->pushButton_clear->setEnabled(false); ui->pushButton_close->setEnabled(false); ui->pushButton_right->setEnabled(false); // motor_->motor_.MoveRelativelyDistance(GetSpeed(), -GetInterval() / 360); } void MotorSettingDialog::on_pushButton_right_clicked() { t_.start(); count_ = 0; // motor_->Move(); motor_->GoAround(); timer_.start(2000); ui->pushButton_home->setEnabled(false); ui->pushButton_left->setEnabled(false); ui->pushButton_clear->setEnabled(false); ui->pushButton_close->setEnabled(false); ui->pushButton_right->setEnabled(false); // motor_->motor_.MoveRelativelyDistance(GetSpeed(), GetInterval() / 360); } void MotorSettingDialog::on_pushButton_close_clicked() { // motor_->GoHmoe(); // motor_->motor_.MoveAbsolutelyDistance(GetSpeed(), 0); accept(); } void MotorSettingDialog::on_pushButton_clear_clicked() { count_ = 0; ui->textEdit->clear(); motor_->Ardu_Clear(); }
[ "39684997+kia016@users.noreply.github.com" ]
39684997+kia016@users.noreply.github.com
1449dc023fabcec60a031dfa57e3942e777d0629
3b5f53ad2268be7afe61af4e25022eaec93a5361
/BitsMgr/pch.cpp
385fbce6d400ab99b3659792bada1274b151fbeb
[ "MIT" ]
permissive
rajendra1185/BITSManager
667a10f6f189b8128dc49e108e2bd2b8cfc24d6b
c35566bd53721466f28e7cceb15469866b64bc8e
refs/heads/master
2022-12-13T09:07:20.815715
2020-09-12T17:00:33
2020-09-12T17:00:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
195
cpp
// stdafx.cpp : source file that includes just the standard includes // BitsMgr.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "pch.h"
[ "zodiacon@live.com" ]
zodiacon@live.com
266e629154a3ae87d10a20e91cd53d3c2ef9bdc4
74adb357c195f6828d4a2639262dad225404c5ce
/Book.cpp
9bb4aa5da6107e41cb55edb0e51e954e482fc601
[]
no_license
jganesh3/SearchApp
443bf524734db9aad9d72c1e384b8f11c38334cd
6601cdca8e27c79d80742af6818877104193b987
refs/heads/master
2020-05-21T11:57:14.628915
2014-12-12T02:22:32
2014-12-12T02:22:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,627
cpp
/**************************************************************** * @author: Ganesh Joshi * CSCI 511 * File : Book.cpp ****************************************************************/ #include"Book.h" #include<string> using namespace std; bool Book::searchbyCallNo(string& call_number ) const { if(this->call_number.find(call_number)!= string::npos) { return true; } else { return false; } } bool Book::searchbyTitle(std::string &title) const { if(this->title.find(title)!= string::npos) { return true; } else { return false; } } bool Book::searchOther(string& searchString) const { if(this->description.find(searchString)!= string::npos || this->notes.find(searchString)!= string::npos || this->year.find(searchString)!= string::npos) { return true; } else { return false; } } bool Book::searchbySubject(string& sub) const { if(this->subjects.find(sub)!= string::npos) { return true; } else { return false; } } void Book::displayResult() const { cout<<"===============Book==================="<<endl; cout<<"Call Number: "<<this->call_number<<endl; cout<<"Title : "<<this->title<<endl; cout<<"Subject : "<<this->subjects<<endl; cout<<"Author : "<<this->author<<endl; cout<<"Description: "<<this->description<<endl; cout<<"Publisher : "<<this->publisher<<endl; cout<<"City : "<<this->city<<endl; cout<<"Year : "<<this->year <<endl; cout<<"Series : "<<this->series<<endl; cout<<"Notes : "<<this->notes<<endl; }
[ "gjoshi@jaguar.ecst.csuchico.edu" ]
gjoshi@jaguar.ecst.csuchico.edu
30522eee4044408100229a87d92054800f06cb9c
64491dfc2e3a06a6d58086f75e5afee23f3d3e3b
/qml/test/DataItem_c.h
227424be78fa4fe7019d3d496ef1aeea8dc12f7d
[]
no_license
gasche/lablqt
9f59e01ee1a0c6cacc31fb06e0dd58e24aab0337
0f2c8f8f5c1cdc96d4d7a199ada1adf1592188b6
refs/heads/master
2021-01-22T17:15:02.404661
2013-12-13T15:06:39
2013-12-13T15:06:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
521
h
/* * Generated at 2013-05-09 12:56:37.803365+04:00 */ #ifndef DataItem_c_H #define DataItem_c_H #include "kamlo.h" #include <QtCore/QDebug> #include <QtCore/QObject> class DataItem: public QObject { Q_OBJECT value _camlobjHolder; public: DataItem(); void storeCAMLobj(value x) { if (_camlobjHolder != 0) { //maybe unregister global root? } _camlobjHolder = x; register_global_root(&_camlobjHolder); } Q_INVOKABLE QString name(); Q_INVOKABLE QString sort(); }; #endif // DataItem_H
[ "kakadu.hafanana@gmail.com" ]
kakadu.hafanana@gmail.com
9f505a6472afdd8848529b5e8c399616c862ae72
0e6bff1418e816b173e689334101285169ee3c1e
/api-ai-arduino/apiai/include/apiai/query/request/QueryText.h
b900ec991c57cd98e1663af58092b437e56d5ede
[ "MIT" ]
permissive
ezefranca/api-ai-arduino-client
2d4cd23739fd058db17fcab21053adc5fcd1ab5e
8d233ddaa9c6a469a985b8e9e7dd9c2d771fa618
refs/heads/master
2021-01-20T15:30:24.084763
2017-05-09T19:09:37
2017-05-09T19:09:37
90,775,450
3
0
null
null
null
null
UTF-8
C++
false
false
3,368
h
#ifndef QUERYTEXT_H #define QUERYTEXT_H #include <stdexcept> #include <memory> #include <string> #include <vector> #include <apiai/exceptions/InvalidArgumentException.h> namespace ai { namespace query { namespace request { class QueryTextVisitor; class QueryVariant { public: QueryVariant(const std::string text, const double confidence): text(text), confidence(confidence){} std::string getText() const { return text; } double getConfidence() const { return confidence; } private: std::string text; double confidence; }; class QueryText { public: static const std::shared_ptr<QueryText> One(std::string query); static const std::shared_ptr<QueryText> Multiple(std::vector<std::string> query); static const std::shared_ptr<QueryText> Multiple(std::vector<QueryVariant> query); public: virtual void accept(QueryTextVisitor& serizalize) const = 0; }; class QueryOne: public QueryText { public: virtual void accept(QueryTextVisitor& serizalize) const override; private: QueryOne(std::string query): query(query) { if (query.size() == 0) { throw InvalidArgumentException("Query cannot be empty."); } } std::string query; friend class QueryText; friend class QueryTextSerialize; }; class QueryMultipleStrings: public QueryText { public: virtual void accept(QueryTextVisitor& serizalize) const override; private: QueryMultipleStrings(std::vector<std::string> query): query(query) { if (query.size() == 0) { throw InvalidArgumentException("Query cannot be empty."); } for (auto& text: query) { if (text.size() == 0) { throw InvalidArgumentException("Query cannot be empty."); } } } std::vector<std::string> query; friend class QueryText; friend class QueryTextSerialize; }; class QueryMultipleVariants: public QueryText { public: virtual void accept(QueryTextVisitor& serizalize) const override; private: QueryMultipleVariants(std::vector<QueryVariant> query): query(query) { if (query.size() == 0) { throw InvalidArgumentException("Query cannot be empty."); } for (auto& variant: query) { if (variant.getText().size() == 0) { throw InvalidArgumentException("Query cannot be empty."); } } } std::vector<QueryVariant> query; friend class QueryText; friend class QueryTextSerialize; }; } } } #endif // QUERY_H
[ "ezequiel.santos@btgpactual.com" ]
ezequiel.santos@btgpactual.com
9aa25abe3700346afa8e37d19b03382fa618203c
074df04a9aa42a5ed24a760585b85d1494180507
/include_20150202/EventCallBack.h
57bb60ffa48036b509a63494def098ac670b1fc5
[]
no_license
opros-wiki/OPRoS_v2_Applications
75369d3537460c7d3445f18bc8e2b7c3a1e5ae75
c880b364645dcd68bf126f6ee74f566300619297
refs/heads/master
2020-05-29T23:43:38.815246
2015-03-16T06:53:10
2015-03-16T06:53:10
32,305,638
0
0
null
null
null
null
UTF-8
C++
false
false
9,355
h
/* * OPRoS Component Engine (OCE) * Copyright (c) 2008 ETRI. http://www.etri.re.kr. * Distributed under the OPRoS License, Version 2.0. * * @Created : 2013. 1. 21 * @Author : sby (sby@etri.re.kr) * * @File : EventCallback.h * * */ #ifndef EVENTCALLBACK_H #define EVENTCALLBACK_H #include <ReturnType.h> #include <Event.h> #include <archive/opros_iarchive.h> #include <EventData.h> #include <InputEventPort.h> template <typename,int> class InputEventPort; class EventCallBack { public: virtual ReturnType onEvent(opros::archive::iarchive &in)=0; virtual ReturnType onEvent(Event *p) =0; virtual ~EventCallBack(){}; }; template <typename T,typename C> class EventCallBackMethod : public EventCallBack { typedef void (C::*memberFuncTypeA)(Event *); typedef void (C::*memberFuncTypeB)(EventData<T> *); typedef void (C::*memberFuncTypeC)(const std::string &mid, const T &indata); typedef void (C::*memberFuncTypeD)(const T &indata); memberFuncTypeA functionPtrA; memberFuncTypeB functionPtrB; memberFuncTypeC functionPtrC; memberFuncTypeD functionPtrD; C *mmPtr; public: virtual ReturnType onEvent(opros::archive::iarchive &in) { EventData<T> *evt = new EventData<T>(); in >> OPROS_SERIALIZATION_MAKE_NVP(EVENTDATA_NVP, *evt); ReturnType ret = onEvent((Event *)evt); delete evt; return ret; } virtual ReturnType onEvent(Event *p) { if (mmPtr != NULL) { if (functionPtrA!=NULL) { (mmPtr->*functionPtrA)(p); return OPROS_SUCCESS; } else if(functionPtrB!=NULL) { EventData<T> *tp = SAFE_CASTING(EventData<T> *, p); (mmPtr->*functionPtrB)(tp); return OPROS_SUCCESS; } else if(functionPtrC!=NULL) { EventData<T> *tp = SAFE_CASTING(EventData<T> *, p); (mmPtr->*functionPtrC)(tp->getId(), *tp->getContentData()); return OPROS_SUCCESS; } else if(functionPtrD!=NULL) { EventData<T> *tp = SAFE_CASTING(EventData<T> *, p); (mmPtr->*functionPtrD)(*tp->getContentData()); return OPROS_SUCCESS; } } return OPROS_INTERNAL_FAULT; } virtual ~EventCallBackMethod (){}; EventCallBackMethod(void (C::* function)(Event *), C *classPtr) { functionPtrA = reinterpret_cast<memberFuncTypeA> (function); functionPtrB = NULL; functionPtrC = NULL; functionPtrD = NULL; mmPtr = classPtr; } EventCallBackMethod(void (C::* function)(EventData<T> *), C *classPtr) { functionPtrA = NULL; functionPtrB = reinterpret_cast<memberFuncTypeB> (function); functionPtrC = NULL; functionPtrD = NULL; mmPtr = classPtr; } EventCallBackMethod(void (C::* function)(const std::string &mid, const T &indata), C *classPtr) { functionPtrA = NULL; functionPtrB = NULL; functionPtrC = reinterpret_cast<memberFuncTypeC> (function); functionPtrD = NULL; mmPtr = classPtr; } EventCallBackMethod(void (C::* function)(const T &indata), C *classPtr) { functionPtrA = NULL; functionPtrB = NULL; functionPtrC = NULL; functionPtrD = reinterpret_cast<memberFuncTypeD> (function); mmPtr = classPtr; } }; template <typename T> class EventCallBackMethod<T,void> : public EventCallBack { typedef void (*funcTypeA)(Event *); typedef void (*funcTypeB)(EventData<T> *); typedef void (*funcTypeC)(const std::string &mid, const T &indata); typedef void (*funcTypeD)(const T &indata); funcTypeA functionPtrA; funcTypeB functionPtrB; funcTypeC functionPtrC; funcTypeD functionPtrD; public: virtual ReturnType onEvent(opros::archive::iarchive &in) { EventData<T> *evt = new EventData<T>(); in >> OPROS_SERIALIZATION_MAKE_NVP(EVENTDATA_NVP, *evt); ReturnType ret = onEvent((Event *)&evt); delete evt; return ret; } virtual ReturnType onEvent(Event *p) { if (functionPtrA!=NULL) { (*functionPtrA)(p); return OPROS_SUCCESS; } else if(functionPtrB!=NULL) { EventData<T> *tp = SAFE_CASTING(EventData<T> *, p); (*functionPtrB)(tp); return OPROS_SUCCESS; } else if(functionPtrC!=NULL) { EventData<T> *tp = SAFE_CASTING(EventData<T> *, p); (*functionPtrC)(tp->getId(), *tp->getContentData()); return OPROS_SUCCESS; } else if(functionPtrD!=NULL) { EventData<T> *tp = SAFE_CASTING(EventData<T> *, p); (*functionPtrD)(*tp->getContentData()); return OPROS_SUCCESS; } return OPROS_INTERNAL_FAULT; } virtual ~EventCallBackMethod(){}; EventCallBackMethod(void (*function)(Event *)) { functionPtrA = reinterpret_cast<funcTypeA> (function); functionPtrB = NULL; functionPtrC = NULL; functionPtrD = NULL; } EventCallBackMethod(void (*function)(EventData<T> *)) { functionPtrA = NULL; functionPtrB = reinterpret_cast<funcTypeB> (function); functionPtrC = NULL; functionPtrD = NULL; } EventCallBackMethod(void (*function)(const std::string &mid, const T &indata)) { functionPtrA = NULL; functionPtrB = NULL; functionPtrC = reinterpret_cast<funcTypeC> (function); functionPtrD = NULL; } EventCallBackMethod(void (*function)(const T &indata)) { functionPtrA = NULL; functionPtrB = NULL; functionPtrC = NULL; functionPtrD = reinterpret_cast<funcTypeD> (function); } }; template <typename T,typename C> EventCallBack *make_EventCallBack( void (C::*function)(Event *), C *classPtr) { EventCallBackMethod<T,C> *r = new EventCallBackMethod<T,C>(function, classPtr); EventCallBack *results = reinterpret_cast<EventCallBack *>(r); return results; } template <typename T,typename C> EventCallBack *make_EventCallBack( void (C::*function)(EventData<T> *), C *classPtr) { EventCallBackMethod<T,C> *r = new EventCallBackMethod<T,C>(function, classPtr); EventCallBack *results = reinterpret_cast<EventCallBack *>(r); return results; } template <typename T,typename C> EventCallBack *make_EventCallBack( void (C::*function)(const std::string &mid, const T &indata), C *classPtr) { EventCallBackMethod<T,C> *r = new EventCallBackMethod<T,C>(function, classPtr); EventCallBack *results = reinterpret_cast<EventCallBack *>(r); return results; } template <typename T,typename C> EventCallBack *make_EventCallBack( void (C::*function)(const T &indata), C *classPtr) { EventCallBackMethod<T,C> *r = new EventCallBackMethod<T,C>(function, classPtr); EventCallBack *results = reinterpret_cast<EventCallBack *>(r); return results; } template <typename T> EventCallBack *make_EventCallBack( void (*function)(Event *)) { EventCallBackMethod<T,void> *r = new EventCallBackMethod<T,void>(function); EventCallBack *results = reinterpret_cast<EventCallBack *>(r); return results; } template <typename T> EventCallBack *make_EventCallBack( void (*function)(EventData<T> *)) { EventCallBackMethod<T,void> *r = new EventCallBackMethod<T,void>(function); EventCallBack *results = reinterpret_cast<EventCallBack *>(r); return results; } template <typename T> EventCallBack *make_EventCallBack( void (*function)(const std::string &mid, const T &indata)) { EventCallBackMethod<T,void> *r = new EventCallBackMethod<T,void>(function); EventCallBack *results = reinterpret_cast<EventCallBack *>(r); return results; } template <typename T> EventCallBack *make_EventCallBack( void (*function)(const T &indata)) { EventCallBackMethod<T,void> *r = new EventCallBackMethod<T,void>(function); EventCallBack *results = reinterpret_cast<EventCallBack *>(r); return results; } #define MakeEventCallBackClassFunction(func,classPtr,contentType) make_EventCallBack<contentType>(func,classPtr) #define MakeEventCallBackFunction(func, contentType) make_EventCallBack<contentType>(func) template <typename T,typename C, int n> void setEventCallBack(InputEventPort<T,n> &p, void (C::*func)(Event *p), C *classPtr) { EventCallBack *t= make_EventCallBack<T,C>(func, classPtr); p.setOwner(t); } template <typename T,typename C, int n> void setEventCallBack(InputEventPort<T,n> &p, void (C::*func)(EventData<T> *p), C *classPtr) { EventCallBack *t= make_EventCallBack<T,C>(func, classPtr); p.setOwner(t); } template <typename T,typename C, int n> void setEventCallBack(InputEventPort<T,n> &p, void (C::*func)(const std::string &mid, const T &indata), C *classPtr) { EventCallBack *t= make_EventCallBack<T,C>(func, classPtr); p.setOwner(t); } template <typename T,typename C, int n> void setEventCallBack(InputEventPort<T,n> &p, void (C::*func)(const T &indata), C *classPtr) { EventCallBack *t= make_EventCallBack<T,C>(func, classPtr); p.setOwner(t); } template <typename T, int n> void setEventCallBack(InputEventPort<T,n> &p, void (*func)(Event *p)) { EventCallBack *t= make_EventCallBack<T>(func); p.setOwner(t); } template <typename T,int n> void setEventCallBack(InputEventPort<T,n> &p, void (*func)(EventData<T> *p)) { EventCallBack *t= make_EventCallBack<T>(func); p.setOwner(t); } template <typename T,int n> void setEventCallBack(InputEventPort<T,n> &p, void (*func)(const std::string &mid, const T &indata)) { EventCallBack *t= make_EventCallBack<T>(func); p.setOwner(t); } template <typename T,int n> void setEventCallBack(InputEventPort<T,n> &p, void (*func)(const T &indata)) { EventCallBack *t= make_EventCallBack<T>(func); p.setOwner(t); } // #define SET_EVENT_CALLBACK(port, func, classPtr) setEventCallBack(port, &func, classPtr) #define SET_EVENT_CALLBACK_EX(port, func) setEventCallBack(port, &func) #endif // EVENTCALLBACK_H
[ "opros.contact@gmail.com" ]
opros.contact@gmail.com
8c4a83b59af0377aabc68a978e47f2eb06b715fd
970f47b70ab7aefd5c510e0806615a51d5bc35cb
/ui_hgraphicprint.h
69541e869827aff55a21b652839b3df006663e91
[]
no_license
fblabs/HamletMODSF
0d6ce7f93cdf889b14503b49c5e29fb62f203857
f2da591e4240675739775c15e7587a029d047b16
refs/heads/master
2022-12-06T01:53:21.986719
2020-08-26T17:08:12
2020-08-26T17:08:12
269,602,982
0
0
null
2020-07-22T10:47:41
2020-06-05T10:37:32
C++
UTF-8
C++
false
false
2,635
h
/******************************************************************************** ** Form generated from reading UI file 'hgraphicprint.ui' ** ** Created by: Qt User Interface Compiler version 5.5.1 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_HGRAPHICPRINT_H #define UI_HGRAPHICPRINT_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QGraphicsView> #include <QtWidgets/QHBoxLayout> #include <QtWidgets/QHeaderView> #include <QtWidgets/QPushButton> #include <QtWidgets/QVBoxLayout> #include <QtWidgets/QWidget> QT_BEGIN_NAMESPACE class Ui_HGraphicPrint { public: QVBoxLayout *verticalLayout; QGraphicsView *graphicsView; QHBoxLayout *horizontalLayout; QPushButton *pbPrint; QPushButton *pbClose; void setupUi(QWidget *HGraphicPrint) { if (HGraphicPrint->objectName().isEmpty()) HGraphicPrint->setObjectName(QStringLiteral("HGraphicPrint")); HGraphicPrint->resize(967, 647); verticalLayout = new QVBoxLayout(HGraphicPrint); verticalLayout->setObjectName(QStringLiteral("verticalLayout")); graphicsView = new QGraphicsView(HGraphicPrint); graphicsView->setObjectName(QStringLiteral("graphicsView")); verticalLayout->addWidget(graphicsView); horizontalLayout = new QHBoxLayout(); horizontalLayout->setObjectName(QStringLiteral("horizontalLayout")); pbPrint = new QPushButton(HGraphicPrint); pbPrint->setObjectName(QStringLiteral("pbPrint")); horizontalLayout->addWidget(pbPrint); pbClose = new QPushButton(HGraphicPrint); pbClose->setObjectName(QStringLiteral("pbClose")); horizontalLayout->addWidget(pbClose); verticalLayout->addLayout(horizontalLayout); retranslateUi(HGraphicPrint); QMetaObject::connectSlotsByName(HGraphicPrint); } // setupUi void retranslateUi(QWidget *HGraphicPrint) { HGraphicPrint->setWindowTitle(QApplication::translate("HGraphicPrint", "Form", 0)); pbPrint->setText(QApplication::translate("HGraphicPrint", "PushButton", 0)); pbClose->setText(QApplication::translate("HGraphicPrint", "PushButton", 0)); } // retranslateUi }; namespace Ui { class HGraphicPrint: public Ui_HGraphicPrint {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_HGRAPHICPRINT_H
[ "fabio.bonfante@fblabs.eu" ]
fabio.bonfante@fblabs.eu
71c3fa904c357662ff69d48ea6b51280b0f3573a
7997101c8231a987ebe502d5ab5a0856d7f42c21
/src/EyeSluggerRendererEx.h
fc134daab2d1fe7ee5e45add064124cfb0edae11
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
ChrisYang/kinect-ultra
a939e9e53e3410d15abe4daa0a51c27a37c0849c
0a6969827e1d974a24bc343cb722cb8dcdb821f5
refs/heads/master
2021-01-15T13:14:56.568591
2016-02-01T02:56:55
2016-02-01T02:56:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,169
h
//@COPYRIGHT@// // // Copyright (c) 2012, Tomoto S. Washio // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of the Tomoto S. Washio nor the names of his // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL TOMOTO S. WASHIO 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. // //@COPYRIGHT@// #ifndef _EYE_SLUGGER_RENDERER_EX_H_ #define _EYE_SLUGGER_RENDERER_EX_H_ #include "common.h" #include "EyeSluggerRenderer.h" class EyeSluggerRendererEx : public EyeSluggerRenderer { public: enum HoldMode { HOLD_NORMAL, HOLD_IN_HAND, HOLD_IN_AIR }; private: HoldMode m_holdMode; public: EyeSluggerRendererEx(RenderingContext* rctx, HenshinDetector* henshinDetector); ~EyeSluggerRendererEx(); void setHoldMode(HoldMode holdMode); virtual void shoot(const XV3& v, float rotation, int traceDencity); protected: virtual bool updateObjectFrame(); }; #endif
[ "tomoto@71011c23-f5df-4f85-535c-b37ab9e39a43" ]
tomoto@71011c23-f5df-4f85-535c-b37ab9e39a43
79b7f1787d6193d92312dd39287757e60c463278
b173b42d13f1031f65725d0a4c97e529c36ba7f9
/Mouse.h
04fa6b1188d664543c9bd632d208d2c16a59e653
[]
no_license
shutov1221/MinecraftClone
88abe4795bfd2fb2cf48943f58fb3877b8eed18d
31305dcf3f78b1bffb14a153915c8381f1f54050
refs/heads/main
2023-06-21T06:48:29.944743
2021-07-27T19:22:18
2021-07-27T19:22:18
390,091,615
0
0
null
null
null
null
UTF-8
C++
false
false
436
h
#pragma once #include <vector> #include <algorithm> enum MouseButton { RIGHT, LEFT, MIDDLE, BACK, FORWARD }; class Mouse { public: Mouse() = default; bool IsKeyPressed(MouseButton key); void SetKeyPressed(MouseButton key); void SetKeyReleased(MouseButton key); static double x; static double y; static double dx; static double dy; private: std::vector<MouseButton> _Keys; };
[ "shutov.ilya.1221@gmail.com" ]
shutov.ilya.1221@gmail.com
c4329e18421936e8b896cacc5552449da17c8e6d
9e4fee7f72debf2ab8a9e0edc0f1d64a8c62b76b
/APS_PROG2/Tela_principal.h
97755a750cfefb4fa036346ef2a460685d36d984
[]
no_license
Pincinato/APS_PROG2
0b68f76f14d7408145297ac449e9759bfafb6a20
3a97f9538abfae0a6648e69b0eefb077cc46cf44
refs/heads/master
2021-01-21T04:31:02.180167
2016-06-20T02:46:45
2016-06-20T02:46:45
55,323,302
0
1
null
2016-05-01T19:21:35
2016-04-03T00:56:00
C++
UTF-8
C++
false
false
797
h
#include <stdio.h> #include <allegro5/allegro.h> #include <allegro5/allegro.h> #include <allegro5/allegro_font.h> #include <allegro5/allegro_ttf.h> class Tela_Principal{ private: ALLEGRO_DISPLAY *janela; ALLEGRO_EVENT_QUEUE *fila_eventos; ALLEGRO_BITMAP *botao_sair; ALLEGRO_BITMAP *botao_novo_jogo; ALLEGRO_BITMAP *botao_continuar_jogo; ALLEGRO_FONT *fonte; int Largura_tela; int Altura_tela; int tamanho_fonte; public: Tela_Principal(); ~Tela_Principal(); int Mostra_Tela(); void Destroi_Tela(); private: void Init(); int Cria_Janela(); int Cria_Mouse(); int Cria_Bitmap(); int Cria_Evento(); int Cria_Font(); void Desenha_Botoes(int posicao_n[],int posicao_c [],int posicao_s[]); void Desenha_Strings(int posicao_n[],int posicao_c [],int posicao_s[]); };
[ "thiagoh.pincinato@gmail.com" ]
thiagoh.pincinato@gmail.com
bd4bfb073b1adff573d4a906f854f4f89f8f93fc
a50a12f5653dd8462c7f2a6c96430ef8e7827044
/ComLib/Src/IMP_ackMessageBody.cpp
4bc0b9c6fa5b1bb76449be839bb802ffe7f99b4d
[]
no_license
fredericrubio/NewHorizons
57e2b4772a9e29436993a91fce96c006ae678809
b6524bb8ffc4f2e8ee2fdf3c8c39103a0c281b04
refs/heads/master
2021-07-09T14:19:02.042903
2019-03-16T17:44:05
2019-03-16T17:44:05
149,004,774
0
0
null
null
null
null
UTF-8
C++
false
false
737
cpp
// // IMP_AckMessageBody.cpp // ComLib // // Created by Frédéric Rubio on 11/09/2018. // Copyright © 2018 Frédéric Rubio. All rights reserved. // #include <string.h> #include <stdlib.h> #include "IMP_AckMessageBody.hpp" /** * Constructors **/ bool IMP_AckMessageBody::serialize(char* const pSerializedArray) { // copy values /// size memcpy(pSerializedArray, &status, sizeof(unsigned int)); return true; } bool IMP_AckMessageBody::unserialize(const char * const pSerializedArray) { // copy values /// size memcpy(&status, pSerializedArray, sizeof(unsigned int)); return true; } unsigned int IMP_AckMessageBody::getSize() { return sizeof(unsigned int) ; }
[ "fredericrubio@Usul.local" ]
fredericrubio@Usul.local
7bced780bb7637f9c6c1dbb147349b8f4ff20c91
c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64
/Engine/Source/ThirdParty/PhysX/PhysX_3.4/Source/LowLevel/common/src/pipeline/PxcMaterialShape.cpp
ce08002272d8ccf45a2e84bd1925c34ff5bb7d68
[ "MIT", "LicenseRef-scancode-proprietary-license" ]
permissive
windystrife/UnrealEngine_NVIDIAGameWorks
c3c7863083653caf1bc67d3ef104fb4b9f302e2a
b50e6338a7c5b26374d66306ebc7807541ff815e
refs/heads/4.18-GameWorks
2023-03-11T02:50:08.471040
2022-01-13T20:50:29
2022-01-13T20:50:29
124,100,479
262
179
MIT
2022-12-16T05:36:38
2018-03-06T15:44:09
C++
UTF-8
C++
false
false
2,669
cpp
// This code contains NVIDIA Confidential Information and is disclosed to you // under a form of NVIDIA software license agreement provided separately to you. // // Notice // NVIDIA Corporation and its licensors retain all intellectual property and // proprietary rights in and to this software and related documentation and // any modifications thereto. Any use, reproduction, disclosure, or // distribution of this software and related documentation without an express // license agreement from NVIDIA Corporation is strictly prohibited. // // ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES // NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO // THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT, // MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE. // // Information and code furnished is believed to be accurate and reliable. // However, NVIDIA Corporation assumes no responsibility for the consequences of use of such // information or for any infringement of patents or other rights of third parties that may // result from its use. No license is granted by implication or otherwise under any patent // or patent rights of NVIDIA Corporation. Details are subject to change without notice. // This code supersedes and replaces all information previously supplied. // NVIDIA Corporation products are not authorized for use as critical // components in life support devices or systems without express written approval of // NVIDIA Corporation. // // Copyright (c) 2008-2017 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "PxTriangleMesh.h" #include "PxvGeometry.h" #include "PxsMaterialManager.h" #include "PxcNpThreadContext.h" #include "GuHeightField.h" using namespace physx; using namespace Gu; namespace physx { bool PxcGetMaterialShape(const PxsShapeCore* shape, const PxU32 index, PxcNpThreadContext& context, PxsMaterialInfo* materialInfo) { ContactBuffer& contactBuffer = context.mContactBuffer; for(PxU32 i=0; i< contactBuffer.count; ++i) { (&materialInfo[i].mMaterialIndex0)[index] = shape->materialIndex; } return true; } bool PxcGetMaterialShapeShape(const PxsShapeCore* shape0, const PxsShapeCore* shape1, PxcNpThreadContext& context, PxsMaterialInfo* materialInfo) { ContactBuffer& contactBuffer = context.mContactBuffer; for(PxU32 i=0; i< contactBuffer.count; ++i) { materialInfo[i].mMaterialIndex0 = shape0->materialIndex; materialInfo[i].mMaterialIndex1 = shape1->materialIndex; } return true; } }
[ "tungnt.rec@gmail.com" ]
tungnt.rec@gmail.com
5c684b8c7babcb74f63a8672e4b30227d3c90142
b28305dab0be0e03765c62b97bcd7f49a4f8073d
/chrome/browser/supervised_user/supervised_user_interstitial.cc
67fded21d5fedcb4f5e795018dcb143eca5a227e
[ "BSD-3-Clause" ]
permissive
svarvel/browser-android-tabs
9e5e27e0a6e302a12fe784ca06123e5ce090ced5
bd198b4c7a1aca2f3e91f33005d881f42a8d0c3f
refs/heads/base-72.0.3626.105
2020-04-24T12:16:31.442851
2019-08-02T19:15:36
2019-08-02T19:15:36
171,950,555
1
2
NOASSERTION
2019-08-02T19:15:37
2019-02-21T21:47:44
null
UTF-8
C++
false
false
15,894
cc
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/supervised_user/supervised_user_interstitial.h" #include <stddef.h> #include "base/bind.h" #include "base/memory/weak_ptr.h" #include "base/metrics/histogram_macros.h" #include "base/scoped_observer.h" #include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/task/post_task.h" #include "base/values.h" #include "build/build_config.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/infobars/infobar_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/supervised_user/supervised_user_service.h" #include "chrome/browser/supervised_user/supervised_user_service_factory.h" #include "chrome/common/chrome_features.h" #include "chrome/common/pref_names.h" #include "chrome/grit/generated_resources.h" #include "components/infobars/core/infobar.h" #include "components/infobars/core/infobar_delegate.h" #include "components/prefs/pref_service.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/interstitial_page.h" #include "content/public/browser/navigation_controller.h" #include "content/public/browser/navigation_details.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/reload_type.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_user_data.h" #include "content/public/browser/web_ui.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" #include "ui/base/webui/jstemplate_builder.h" #include "ui/base/webui/web_ui_util.h" #if defined(OS_ANDROID) #include "chrome/browser/supervised_user/child_accounts/child_account_feedback_reporter_android.h" #else #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/chrome_pages.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #endif using content::BrowserThread; using content::WebContents; namespace { // For use in histograms. enum Commands { PREVIEW, BACK, NTP, ACCESS_REQUEST, HISTOGRAM_BOUNDING_VALUE }; class TabCloser : public content::WebContentsUserData<TabCloser> { public: ~TabCloser() override {} static void MaybeClose(WebContents* web_contents) { DCHECK(web_contents); // Close the tab only if there is a browser for it (which is not the case // for example in a <webview>). #if !defined(OS_ANDROID) if (!chrome::FindBrowserWithWebContents(web_contents)) return; #endif TabCloser::CreateForWebContents(web_contents); } private: friend class content::WebContentsUserData<TabCloser>; explicit TabCloser(WebContents* web_contents) : web_contents_(web_contents), weak_ptr_factory_(this) { base::PostTaskWithTraits( FROM_HERE, {BrowserThread::UI}, base::Bind(&TabCloser::CloseTabImpl, weak_ptr_factory_.GetWeakPtr())); } void CloseTabImpl() { // On Android, FindBrowserWithWebContents and TabStripModel don't exist. #if !defined(OS_ANDROID) Browser* browser = chrome::FindBrowserWithWebContents(web_contents_); DCHECK(browser); TabStripModel* tab_strip = browser->tab_strip_model(); DCHECK_NE(TabStripModel::kNoTab, tab_strip->GetIndexOfWebContents(web_contents_)); if (tab_strip->count() <= 1) { // Don't close the last tab in the window. web_contents_->RemoveUserData(UserDataKey()); return; } #endif web_contents_->Close(); } WebContents* web_contents_; base::WeakPtrFactory<TabCloser> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(TabCloser); }; } // namespace const content::InterstitialPageDelegate::TypeID SupervisedUserInterstitial::kTypeForTesting = &SupervisedUserInterstitial::kTypeForTesting; // TODO(carlosil): Remove Show function and the rest of non-committed // interstitials code once committed interstitials are the only code path. // static void SupervisedUserInterstitial::Show( WebContents* web_contents, const GURL& url, supervised_user_error_page::FilteringBehaviorReason reason, bool initial_page_load, const base::Callback<void(bool)>& callback) { DCHECK(!base::FeatureList::IsEnabled( features::kSupervisedUserCommittedInterstitials)); // |interstitial_page_| is responsible for deleting the interstitial. SupervisedUserInterstitial* interstitial = new SupervisedUserInterstitial( web_contents, url, reason, initial_page_load, callback); interstitial->Init(); } // static std::unique_ptr<SupervisedUserInterstitial> SupervisedUserInterstitial::Create( WebContents* web_contents, const GURL& url, supervised_user_error_page::FilteringBehaviorReason reason, bool initial_page_load, const base::Callback<void(bool)>& callback) { DCHECK(base::FeatureList::IsEnabled( features::kSupervisedUserCommittedInterstitials)); std::unique_ptr<SupervisedUserInterstitial> interstitial( new SupervisedUserInterstitial(web_contents, url, reason, initial_page_load, callback)); // Caller is responsible for deleting the interstitial. interstitial->Init(); return interstitial; } SupervisedUserInterstitial::SupervisedUserInterstitial( WebContents* web_contents, const GURL& url, supervised_user_error_page::FilteringBehaviorReason reason, bool initial_page_load, const base::Callback<void(bool)>& callback) : web_contents_(web_contents), profile_(Profile::FromBrowserContext(web_contents->GetBrowserContext())), interstitial_page_(NULL), url_(url), reason_(reason), initial_page_load_(initial_page_load), proceeded_(false), callback_(callback), scoped_observer_(this), weak_ptr_factory_(this) {} SupervisedUserInterstitial::~SupervisedUserInterstitial() {} void SupervisedUserInterstitial::Init() { DCHECK(!ShouldProceed()); InfoBarService* service = InfoBarService::FromWebContents(web_contents_); if (service) { // Remove all the infobars which are attached to |web_contents_| and for // which ShouldExpire() returns true. content::LoadCommittedDetails details; // |details.is_same_document| is default false, and |details.is_main_frame| // is default true. This results in is_navigation_to_different_page() // returning true. DCHECK(details.is_navigation_to_different_page()); const content::NavigationController& controller = web_contents_->GetController(); details.entry = controller.GetVisibleEntry(); if (controller.GetLastCommittedEntry()) { details.previous_entry_index = controller.GetLastCommittedEntryIndex(); details.previous_url = controller.GetLastCommittedEntry()->GetURL(); } details.type = content::NAVIGATION_TYPE_NEW_PAGE; for (int i = service->infobar_count() - 1; i >= 0; --i) { infobars::InfoBar* infobar = service->infobar_at(i); if (infobar->delegate()->ShouldExpire( InfoBarService::NavigationDetailsFromLoadCommittedDetails( details))) service->RemoveInfoBar(infobar); } } SupervisedUserService* supervised_user_service = SupervisedUserServiceFactory::GetForProfile(profile_); scoped_observer_.Add(supervised_user_service); if (!base::FeatureList::IsEnabled( features::kSupervisedUserCommittedInterstitials)) { // If committed interstitials are enabled we do not create an // interstitial_page interstitial_page_ = content::InterstitialPage::Create( web_contents_, initial_page_load_, url_, this); interstitial_page_->Show(); } } // static std::string SupervisedUserInterstitial::GetHTMLContents( Profile* profile, supervised_user_error_page::FilteringBehaviorReason reason) { bool is_child_account = profile->IsChild(); bool is_deprecated = !is_child_account; SupervisedUserService* supervised_user_service = SupervisedUserServiceFactory::GetForProfile(profile); std::string custodian = supervised_user_service->GetCustodianName(); std::string second_custodian = supervised_user_service->GetSecondCustodianName(); std::string custodian_email = supervised_user_service->GetCustodianEmailAddress(); std::string second_custodian_email = supervised_user_service->GetSecondCustodianEmailAddress(); std::string profile_image_url = profile->GetPrefs()->GetString( prefs::kSupervisedUserCustodianProfileImageURL); std::string profile_image_url2 = profile->GetPrefs()->GetString( prefs::kSupervisedUserSecondCustodianProfileImageURL); bool allow_access_requests = supervised_user_service->AccessRequestsEnabled(); return supervised_user_error_page::BuildHtml( allow_access_requests, profile_image_url, profile_image_url2, custodian, custodian_email, second_custodian, second_custodian_email, is_child_account, is_deprecated, reason, g_browser_process->GetApplicationLocale()); } std::string SupervisedUserInterstitial::GetHTMLContents() { return GetHTMLContents(profile_, reason_); } void SupervisedUserInterstitial::CommandReceived(const std::string& command) { if (command == "\"back\"") { UMA_HISTOGRAM_ENUMERATION("ManagedMode.BlockingInterstitialCommand", BACK, HISTOGRAM_BOUNDING_VALUE); if (base::FeatureList::IsEnabled( features::kSupervisedUserCommittedInterstitials)) { DontProceedInternal(); } else { interstitial_page_->DontProceed(); } return; } if (command == "\"request\"") { UMA_HISTOGRAM_ENUMERATION("ManagedMode.BlockingInterstitialCommand", ACCESS_REQUEST, HISTOGRAM_BOUNDING_VALUE); SupervisedUserService* supervised_user_service = SupervisedUserServiceFactory::GetForProfile(profile_); supervised_user_service->AddURLAccessRequest( url_, base::Bind(&SupervisedUserInterstitial::OnAccessRequestAdded, weak_ptr_factory_.GetWeakPtr())); return; } SupervisedUserService* supervised_user_service = SupervisedUserServiceFactory::GetForProfile(profile_); base::string16 second_custodian = base::UTF8ToUTF16(supervised_user_service->GetSecondCustodianName()); if (command == "\"feedback\"") { bool is_child_account = profile_->IsChild(); base::string16 reason = l10n_util::GetStringUTF16(supervised_user_error_page::GetBlockMessageID( reason_, is_child_account, second_custodian.empty())); std::string message = l10n_util::GetStringFUTF8( IDS_BLOCK_INTERSTITIAL_DEFAULT_FEEDBACK_TEXT, reason); #if defined(OS_ANDROID) DCHECK(is_child_account); ReportChildAccountFeedback(web_contents_, message, url_); #else chrome::ShowFeedbackPage(chrome::FindBrowserWithWebContents(web_contents_), chrome::kFeedbackSourceSupervisedUserInterstitial, message, std::string() /* description_placeholder_text */, std::string() /* category_tag */, std::string() /* extra_diagnostics */); #endif return; } NOTREACHED(); } void SupervisedUserInterstitial::RequestPermission( base::OnceCallback<void(bool)> RequestCallback) { UMA_HISTOGRAM_ENUMERATION("ManagedMode.BlockingInterstitialCommand", ACCESS_REQUEST, HISTOGRAM_BOUNDING_VALUE); SupervisedUserService* supervised_user_service = SupervisedUserServiceFactory::GetForProfile(profile_); supervised_user_service->AddURLAccessRequest(url_, std::move(RequestCallback)); } void SupervisedUserInterstitial::OnProceed() { ProceedInternal(); } void SupervisedUserInterstitial::OnDontProceed() { DontProceedInternal(); } content::InterstitialPageDelegate::TypeID SupervisedUserInterstitial::GetTypeForTesting() const { return SupervisedUserInterstitial::kTypeForTesting; } void SupervisedUserInterstitial::OnURLFilterChanged() { if (ShouldProceed()) { if (base::FeatureList::IsEnabled( features::kSupervisedUserCommittedInterstitials)) { ProceedInternal(); } else { // Interstitial page deletes the interstitial when proceeding but not // synchronously, so a check is required to avoid calling proceed twice. if (!proceeded_) interstitial_page_->Proceed(); proceeded_ = true; } } } void SupervisedUserInterstitial::OnAccessRequestAdded(bool success) { DCHECK(!base::FeatureList::IsEnabled( features::kSupervisedUserCommittedInterstitials)); VLOG(1) << "Sent access request for " << url_.spec() << (success ? " successfully" : " unsuccessfully"); std::string jsFunc = base::StringPrintf("setRequestStatus(%s);", success ? "true" : "false"); if (interstitial_page_->GetMainFrame()) { interstitial_page_->GetMainFrame()->ExecuteJavaScript( base::ASCIIToUTF16(jsFunc)); } } bool SupervisedUserInterstitial::ShouldProceed() { SupervisedUserService* supervised_user_service = SupervisedUserServiceFactory::GetForProfile(profile_); const SupervisedUserURLFilter* url_filter = supervised_user_service->GetURLFilter(); SupervisedUserURLFilter::FilteringBehavior behavior; if (url_filter->HasAsyncURLChecker()) { if (!url_filter->GetManualFilteringBehaviorForURL(url_, &behavior)) return false; } else { behavior = url_filter->GetFilteringBehaviorForURL(url_); } return behavior != SupervisedUserURLFilter::BLOCK; } void SupervisedUserInterstitial::MoveAwayFromCurrentPage() { // No need to do anything if the WebContents is in the process of being // destroyed anyway. if (web_contents_->IsBeingDestroyed()) return; // If the interstitial was shown during a page load and there is no history // entry to go back to, attempt to close the tab. // This check is skipped when committed interstitials are on, because all // interstitials are treated as initial page loads in this case, the case // where there is nothing to go back to will be handled by the default case at // the end. if (!base::FeatureList::IsEnabled( features::kSupervisedUserCommittedInterstitials) && initial_page_load_) { if (web_contents_->GetController().IsInitialBlankNavigation()) TabCloser::MaybeClose(web_contents_); return; } // If the interstitial was shown over an existing page, navigate back from // that page. If that is not possible, attempt to close the entire tab. if (web_contents_->GetController().CanGoBack()) { web_contents_->GetController().GoBack(); return; } TabCloser::MaybeClose(web_contents_); } void SupervisedUserInterstitial::DispatchContinueRequest( bool continue_request) { callback_.Run(continue_request); // After this, the WebContents may be destroyed. Make sure we don't try to use // it again. web_contents_ = nullptr; } void SupervisedUserInterstitial::ProceedInternal() { if (base::FeatureList::IsEnabled( features::kSupervisedUserCommittedInterstitials) && web_contents_) { // In the committed interstitials case, there will be nothing to resume, so // refresh instead. web_contents_->GetController().Reload(content::ReloadType::NORMAL, true); } DispatchContinueRequest(true); } void SupervisedUserInterstitial::DontProceedInternal() { MoveAwayFromCurrentPage(); DispatchContinueRequest(false); }
[ "artem@brave.com" ]
artem@brave.com
b6d1f7feda042fcf47b747d189ac7bc6d5b70d1c
c36d8a0cdf2b2e97647a277e72fdc25989f1f3f3
/src/World/Block/Block_Types/BGrass.h
6eeae1f3d31d0c0a273e3d2fd2dabc49325b0468
[]
no_license
Aganthor/MyCraft
8717be4e8fb45eec856b4c8988bd126befb48682
f304ea447224115ed9884452397ae19a586b1204
refs/heads/master
2021-01-01T15:37:20.439928
2017-07-26T19:30:23
2017-07-26T19:30:23
97,657,111
1
0
null
null
null
null
UTF-8
C++
false
false
140
h
#pragma once #include "Block_Type.h" namespace Block { class Grass : public Type { public: Grass(); }; }
[ "psyluche@gmail.com" ]
psyluche@gmail.com
166e885e23ed0deba25f99928a3af99056af288d
d5962e39a908bfb37b2394fe03f0fe50bbe2d480
/src/compradmap.cpp
bbdb6834022f9c41e2555017734cb3c9fa0664b9
[]
no_license
daniel-iglesias/mknixpost
19583b0db055f184ede51b8d572cdb379adbc514
ad93406ee9399b1ee904af2d80a53c7ab034cb54
refs/heads/master
2021-05-04T11:18:31.098739
2019-06-12T12:59:52
2019-06-12T12:59:52
48,439,738
0
0
null
null
null
null
UTF-8
C++
false
false
7,447
cpp
/*************************************************************************** * Copyright (C) 2007 by Daniel Iglesias * * diglesias@mecanica.upm.es * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 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 General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "compradmap.h" #include <vtkPoints.h> #include <vtkCellArray.h> #include <vtkFloatArray.h> #include <vtkPointData.h> #include <vtkStructuredGrid.h> #include <vtkContourFilter.h> #include <vtkPolyDataMapper.h> #include <vtkDataSetMapper.h> #include <vtkPiecewiseFunction.h> #include <vtkDepthSortPolyData.h> #include <vtkCamera.h> //#include <vtkVolumeProperty.h> //#include <vtkSmartVolumeMapper.h> //#include <vtkVolume.h> #include <vtkActor.h> #include <vtkRenderer.h> #include <vtkProperty.h> #include <vtkLookupTable.h> #include <vtkSmartPointer.h> CompRadMap::CompRadMap() : vPoints(0) , scalarField(0) , structuredGrid(0) //, volume(0) , camera(0) , contourMapper(0) , mapper(0) , contourActor(0) , anActor(0) { } CompRadMap::~CompRadMap() { if (vPoints!=0) vPoints->Delete(); // boundary->Delete(); if (structuredGrid!=0) structuredGrid->Delete(); if (mapper!=0) mapper->Delete(); if (anActor!=0) anActor->Delete(); if (scalarField!=0){ scalarField->Delete(); scalarField = 0; } } void CompRadMap::addToRender(vtkRenderer * renderer_in) { if(anActor) renderer_in->AddActor( anActor ); if(contourActor) renderer_in->AddActor( contourActor ); // if(volume) renderer_in->AddViewProp(volume); if(camera) renderer_in->SetActiveCamera(camera); } void CompRadMap::removeFromRender(vtkRenderer * renderer_in) { if(anActor) renderer_in->RemoveActor( anActor ); if(contourActor) renderer_in->RemoveActor( contourActor ); // if(volume) renderer_in->RemoveViewProp(volume); if(camera) renderer_in->ResetCamera(); } void CompRadMap::readResults( std::ifstream & input ) { int num_p, num_x, num_y, num_z, p_counter; int maxContour(2*10); double x, y, z, value; // Read size of grid input >> num_x >> num_y >> num_z; cout << "Grid size\t" << num_x << "\t" << num_y << "\t" << num_z << endl; num_p = num_x*num_y*num_z; // Regular grid cout << "Number of points in grid = " << num_p << endl; vPoints = vtkPoints::New(); // vPoints->SetNumberOfPoints( num_p ); scalarField = vtkFloatArray::New(); for( p_counter=0; p_counter < num_p; ++p_counter ) { input >> x >> y >> z >> value; vPoints->InsertNextPoint( x, y, z); scalarField->InsertNextValue( value ); // rad value } structuredGrid = vtkStructuredGrid::New(); structuredGrid->SetDimensions(num_x, num_y, num_z); structuredGrid->SetPoints(vPoints); structuredGrid->GetPointData()->SetScalars( scalarField ); findMinMaxScalars(); cout << "RANGE: " << minScalar << ", " << maxScalar << endl; // Create transfer mapping scalar value to opacity. double low_values = minScalar + (maxScalar-minScalar)*0.1; double mid_values = minScalar + (maxScalar-minScalar)*0.6; vtkSmartPointer<vtkPiecewiseFunction> opacityTransferFunction = vtkSmartPointer<vtkPiecewiseFunction>::New(); opacityTransferFunction->AddPoint(low_values, 0.0); opacityTransferFunction->AddPoint(mid_values, 0.2); opacityTransferFunction->AddPoint(maxScalar, 0.7); // The property describes how the data will look. // vtkSmartPointer<vtkVolumeProperty> volumeProperty = // vtkSmartPointer<vtkVolumeProperty>::New(); //// volumeProperty->SetColor(colorTransferFunction); // volumeProperty->SetScalarOpacity(opacityTransferFunction); // volumeProperty->ShadeOff(); // volumeProperty->SetInterpolationTypeToLinear(); contour = vtkContourFilter::New(); #if VTK_MAJOR_VERSION > 5 contour->SetInputData( structuredGrid ); #else contour->SetInput( structuredGrid ); #endif contour->SetNumberOfContours(maxContour); for (int i=0; i<maxContour/2; ++i) { contour->SetValue(i, minScalar + i*(maxScalar-minScalar)*0.6/maxContour); contour->SetValue(2*i, maxScalar*.6 + i*(maxScalar-maxScalar*0.6)/maxContour); } contour->SetValue(maxContour-1, maxScalar); // contour->GenerateValues(maxContour/2, maxScalar*.6, maxScalar); // contour->GenerateValues(maxContour/2, minScalar, maxScalar*.6); // contour->SetValue(0, minScalar); contour->Update(); // vtkSmartPointer<vtkCamera> camera = // vtkSmartPointer<vtkCamera>::New(); // // vtkSmartPointer<vtkDepthSortPolyData> depthSort = // vtkSmartPointer<vtkDepthSortPolyData>::New(); // depthSort->SetInputConnection(contour->GetOutputPort()); // depthSort->SetDirectionToBackToFront(); // depthSort->SetVector(0, 0, 1); // depthSort->SetCamera(camera); // depthSort->SortScalarsOn(); // depthSort->Update(); contourMapper = vtkPolyDataMapper::New(); // contourMapper->SetInputConnection( depthSort->GetOutputPort() ); contourMapper->SetInputConnection( contour->GetOutputPort() ); contourMapper->SetScalarRange(minScalar, maxScalar); mapper = vtkDataSetMapper::New(); #if VTK_MAJOR_VERSION > 5 mapper->SetInputData( structuredGrid ); #else mapper->SetInput( structuredGrid ); #endif mapper->SetScalarRange(minScalar, maxScalar); // vtkSmartPointer<vtkSmartVolumeMapper> volumeMapper = // vtkSmartPointer<vtkSmartVolumeMapper>::New(); // volumeMapper->SetInput(structuredGrid); // // // The volume holds the mapper and the property and can be used to // // position/orient the volume. // vtkSmartPointer<vtkVolume> volume = // vtkSmartPointer<vtkVolume>::New(); // volume->SetMapper(volumeMapper); // volume->SetProperty(volumeProperty); contourActor = vtkActor::New(); contourActor->SetMapper(contourMapper); contourActor->GetProperty()->SetOpacity(0.4); // translucent !!! anActor = vtkActor::New(); anActor->SetMapper(mapper); anActor->GetProperty()->SetOpacity(0.25); // translucent !!! // anActor->AddPosition(2, 0, 0); anActor->GetProperty()->SetDiffuseColor(1.0, 0.3, 0.3); } void CompRadMap::setLookUpTable( vtkLookupTable* table_in ) { if(mapper) mapper->SetLookupTable( table_in); if(contourMapper) contourMapper->SetLookupTable( table_in); } void CompRadMap::findMinMaxScalars() { double min_max[2]; if( scalarField!=0 ){ // set first values scalarField->GetRange(min_max); minScalar = min_max[0]; maxScalar = min_max[1]; } }
[ "daniel.iglesias@ccfe.ac.uk" ]
daniel.iglesias@ccfe.ac.uk
356694909ba7d8c980afead964bbb512be2892fb
560090526e32e009e2e9331e8a2b4f1e7861a5e8
/Compiled/blaze-3.2/blazetest/src/mathtest/dvecdvecouter/V2bVDb.cpp
bd89516eff363fe1150cd6dde41b4b38a130008b
[ "BSD-3-Clause" ]
permissive
jcd1994/MatlabTools
9a4c1f8190b5ceda102201799cc6c483c0a7b6f7
2cc7eac920b8c066338b1a0ac495f0dbdb4c75c1
refs/heads/master
2021-01-18T03:05:19.351404
2018-02-14T02:17:07
2018-02-14T02:17:07
84,264,330
2
0
null
null
null
null
UTF-8
C++
false
false
3,728
cpp
//================================================================================================= /*! // \file src/mathtest/dvecdvecouter/V2bVDb.cpp // \brief Source file for the V2bVDb dense vector/dense vector outer product math test // // Copyright (C) 2012-2017 Klaus Iglberger - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) BSD License. Redistribution and use in source and binary // forms, with or without modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // 3. Neither the names of the Blaze development group nor the names of its contributors // may be used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT // SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. */ //================================================================================================= //************************************************************************************************* // Includes //************************************************************************************************* #include <cstdlib> #include <iostream> #include <blaze/math/DynamicVector.h> #include <blaze/math/StaticVector.h> #include <blazetest/mathtest/Creator.h> #include <blazetest/mathtest/dvecdvecouter/OperationTest.h> #include <blazetest/system/MathTest.h> //================================================================================================= // // MAIN FUNCTION // //================================================================================================= //************************************************************************************************* int main() { std::cout << " Running 'V2bVDb'..." << std::endl; using blazetest::mathtest::TypeB; try { // Vector type definitions typedef blaze::StaticVector<TypeB,2UL> V2b; typedef blaze::DynamicVector<TypeB> VDb; // Creator type definitions typedef blazetest::Creator<V2b> CV2b; typedef blazetest::Creator<VDb> CVDb; // Running the tests for( size_t i=0UL; i<=4UL; ++i ) { RUN_DVECDVECOUTER_OPERATION_TEST( CV2b(), CVDb( i ) ); } } catch( std::exception& ex ) { std::cerr << "\n\n ERROR DETECTED during dense vector/dense vector outer product:\n" << ex.what() << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } //*************************************************************************************************
[ "jonathan.doucette@alumni.ubc.ca" ]
jonathan.doucette@alumni.ubc.ca
836d23e1323808141b5f43c8e050ae256217f549
1867efe366b234d4145deedf4d232d774b552a97
/main.cpp
9e6f489b17ae6d3651330a0fcde247d05a782d29
[ "Apache-2.0" ]
permissive
ArmMbedCloud/ref-wem-firmware-mqtt
43fa366486d9ef982050c9db69b2d4ba14a2e8eb
8de30a4e3f8b15d7c96ad7e473ab0d41cde085cd
refs/heads/master
2020-03-23T15:28:53.546222
2018-07-20T20:27:49
2018-07-20T20:27:49
141,751,135
0
1
null
null
null
null
UTF-8
C++
false
false
51,503
cpp
/* mbed Microcontroller Library * Copyright (c) 2018 ARM Limited * * 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. */ // **************************************************************************** // Workplace Environmental Monitor // // This is a reference deployment application utilizing mbed cloud 1.2. // // By the ARM Reference Design Team // **************************************************************************** #include <mbed.h> #include "compat.h" #include "commander.h" #include "displayman.h" #include "fs.h" #include "keystore.h" #include "lcdprogress.h" #include "m2mclient.h" #include "rapidjson/allocators.h" #include "rapidjson/document.h" #include "rapidjson/writer.h" #include "rapidjson/stringbuffer.h" #include <algorithm> /* std::min */ #include <errno.h> #include <factory_configurator_client.h> #include <fcc_defs.h> #include <mbed_stats.h> #include <mbedtls/sha256.h> #include <mbed-trace-helper.h> #include <mbed-trace/mbed_trace.h> #include <OdinWiFiInterface.h> #include "TSL2591.h" #include "Sht31/Sht31.h" #include "MQTTDataProvider.h" #include "DeviceResource.h" #include "M2MDeviceResource.h" #define TRACE_GROUP "main" // Convert the value of a C macro to a string that can be printed. This trick // is straight out of the GNU C documentation. // (https://gcc.gnu.org/onlinedocs/gcc-4.9.0/cpp/Stringification.html) #define xstr(s) str(s) #define str(s) #s #ifndef DEVTAG #error "No dev tag created" #endif namespace json = rapidjson; // **************************************************************************** // DEFINEs and type definitions // **************************************************************************** #ifndef MBED_CONF_APP_FACTORY_RESET_BUTTON_PRESS_SECS #define MBED_CONF_APP_FACTORY_RESET_BUTTON_PRESS_SECS 5 #endif #define MACADDR_STRLEN 18 #define SSID_KEY "wifi.ssid" #define PASSWORD_KEY "wifi.key" #define SECURITY_KEY "wifi.encryption" #define APP_LABEL_KEY "app.label" #define APP_LABEL_SENSOR_NAME "Label" #ifndef MBED_CONF_APP_APP_LABEL #define MBED_CONF_APP_APP_LABEL "dragonfly" #endif #define GEO_LAT_KEY "geo.lat" #define GEO_LONG_KEY "geo.long" #define GEO_ACCURACY_KEY "geo.accuracy" #ifndef MBED_CONF_APP_MAX_REPORTED_APS #define MBED_CONF_APP_MAX_REPORTED_APS 8 #endif #define JSON_MEM_POOL_INC 64 #define WEM_VERBOSE_PRINTF(type, fmt, ...) \ do {\ if (wem_ ##type ## _verbose_enabled) {\ cmd.printf(fmt, __VA_ARGS__); \ }\ } while(0) enum WEM_THREADS { WEM_THREAD_DISPLAY = 0, WEM_THREAD_SENSOR_LIGHT, WEM_THREAD_DHT, WEM_THREAD_COUNT }; struct dht_sensor { uint8_t h_id; uint8_t t_id; Sht31 *sensor; M2MResource *h_res; M2MResource *t_res; }; struct light_sensor { uint8_t id; TSL2591 *sensor; M2MResource *res; }; struct sensors { int event_queue_id_light, event_queue_id_dht; struct dht_sensor dht; struct light_sensor light; }; // **************************************************************************** // Globals // **************************************************************************** static DisplayMan display; static M2MClient *m2mclient; static NetworkInterface *net; static EventQueue evq; static struct sensors sensors; /* used to stop auto display refresh during firmware downloads */ static int display_evq_id; static bool wem_sensors_verbose_enabled = false; static I2C i2c(I2C_SDA, I2C_SCL); static TSL2591 tsl2591(i2c, TSL2591_ADDR); static Sht31 sht31(I2C_SDA, I2C_SCL); //our serial interface cli class Commander cmd; // **************************************************************************** // Generic Helpers // **************************************************************************** /** * Processes an event queue callback for updating the display */ static void display_refresh(DisplayMan *display) { display->refresh(); } /** * Sets the app label on the LCD and Mbed Client */ static void set_app_label(M2MClient *m2m, const char *label) { display.set_sensor_status(APP_LABEL_SENSOR_NAME, label); m2m->set_resource_value(M2MClient::M2MClientResourceAppLabel, label); } // **************************************************************************** // Sensors // **************************************************************************** /** * Inits the light sensor object */ static void light_init(struct light_sensor *s, M2MClient *mbed_client) { /* add to the display */ s->id = display.register_sensor("Light", IND_LIGHT); /* init the driver */ s->sensor = &tsl2591; s->sensor->init(); s->sensor->enable(); s->res = m2mclient->get_resource(M2MClient::M2MClientResourceLightValue); m2mclient->set_resource_value(s->res, "0", 1); } /** * Converts light sensor reading to Lux units * * Empirical measurement against a light meter under 17 * different lighting conditions led to the following * conversion table * Reading Lux * 0.128 392 * 0.211 767 * 0.264 1145 * 0.292 1294 * 0.317 1407 * 0.349 1665 * 0.402 1959 * 0.457 2580 * 0.517 2690 * 0.570 3540 * 0.592 3770 * 0.628 4310 * 0.702 5040 * 0.816 5880 * 0.856 6150 * 0.917 7610 * 0.958 8330 * * This data is best fit by the power equation * Lux = 8251*(reading)^1.5108 * This equation fits with an R^2 value of 0.9962 */ unsigned int light_sensor_to_lux(float reading) { return lroundf(8250.0 * pow(reading, 1.51)); } /** * Reads a value from the light sensor and publishes to the display */ static void light_read(struct light_sensor *s) { size_t size; char res_buffer[33] = {0}; unsigned int lux; s->sensor->getALS(); s->sensor->calcLux(); //light sensor uses a multiplier to adjust for the lightpipe lux = s->sensor->lux*3.7; WEM_VERBOSE_PRINTF(sensors, "light: %u\n", lux); size = snprintf(res_buffer, sizeof(res_buffer), "%u lux", lux); display.set_sensor_status(s->id, res_buffer); m2mclient->set_resource_value(s->res, res_buffer, size); } /** * Inits the temp/humidity combo sensor */ static void dht_init(struct dht_sensor *s, M2MClient *mbed_client) { /* add to the display */ s->t_id = display.register_sensor("Temp", IND_TEMP); s->h_id = display.register_sensor("Humidity", IND_HUMIDITY); /* init the driver */ s->sensor = &sht31; s->t_res = mbed_client->get_resource( M2MClient::M2MClientResourceTempValue); s->h_res = mbed_client->get_resource( M2MClient::M2MClientResourceHumidityValue); /* set default values */ display.set_sensor_status(s->t_id, "0"); mbed_client->set_resource_value(s->t_res, "0", 1); display.set_sensor_status(s->h_id, "0"); mbed_client->set_resource_value(s->h_res, "0", 1); } /** * Reads temp and humidity values publishes to the display */ static void dht_read(struct dht_sensor *dht) { int size = 0; float temperature, humidity; char res_buffer[33] = {0}; //temp and humidity have multiplier to adjust for the case temperature = dht->sensor->readTemperature() * .68; humidity = dht->sensor->readHumidity() * 1.9; tr_debug("DHT: temp = %fC, humi = %f%%\n", temperature, humidity); /* verbose printing to screen of sensor values */ WEM_VERBOSE_PRINTF(sensors, "DHT: temp = %.2fC, humidity = %.2f%%\n", temperature, humidity); size = snprintf(res_buffer, sizeof(res_buffer), "%.1f C", temperature); m2mclient->set_resource_value(dht->t_res, res_buffer, size); display.set_sensor_status(dht->t_id, (char *)res_buffer); size = snprintf(res_buffer, sizeof(res_buffer), "%.0f%%", humidity); m2mclient->set_resource_value(dht->h_res, res_buffer, size); display.set_sensor_status(dht->h_id, (char *)res_buffer); } /** * Inits all sensors, making them ready to read */ static void sensors_init(struct sensors *sensors, M2MClient *mbed_client) { dht_init(&sensors->dht, mbed_client); light_init(&sensors->light, mbed_client); } /** * Starts the periodic sampling of sensor data */ static void sensors_start(struct sensors *s, EventQueue *q) { cmd.printf("starting all sensors\n"); // the periods are prime number multiples so that the LED flashing is more appealing s->event_queue_id_light = q->call_every(4700, light_read, &s->light); s->event_queue_id_dht = q->call_every(5300, dht_read, &s->dht); } /** * Stops the periodic sampling of sensor data */ static void sensors_stop(struct sensors *s, EventQueue *q) { cmd.printf("stopping all sensors\n"); q->cancel(s->event_queue_id_light); q->cancel(s->event_queue_id_dht); s->event_queue_id_light = 0; s->event_queue_id_dht = 0; } // **************************************************************************** // Network // **************************************************************************** static void network_disconnect(NetworkInterface *net) { net->disconnect(); } static char *network_get_macaddr(NetworkInterface *net, char *macstr) { memcpy(macstr, net->get_mac_address(), MACADDR_STRLEN); return macstr; } static nsapi_security_t wifi_security_str2sec(const char *security) { if (0 == strcmp("WPA/WPA2", security)) { return NSAPI_SECURITY_WPA_WPA2; } else if (0 == strcmp("WPA2", security)) { return NSAPI_SECURITY_WPA_WPA2; } else if (0 == strcmp("WPA", security)) { return NSAPI_SECURITY_WPA; } else if (0 == strcmp("WEP", security)) { return NSAPI_SECURITY_WEP; } else if (0 == strcmp("NONE", security)) { return NSAPI_SECURITY_NONE; } else if (0 == strcmp("OPEN", security)) { return NSAPI_SECURITY_NONE; } cmd.printf("warning: unknown wifi security type (%s), assuming NONE\n", security); return NSAPI_SECURITY_NONE; } /** * brings up wifi * */ static WiFiInterface *new_wifi_interface() { return new OdinWiFiInterface(); } static WiFiInterface *network_create(void) { Keystore k; string ssid; ssid = MBED_CONF_APP_WIFI_SSID; k.open(); if (k.exists("wifi.ssid")) { ssid = k.get("wifi.ssid"); } k.close(); display.init_network("WiFi"); display.set_network_status(ssid); return new_wifi_interface(); } /** Scans the wireless network for nearby APs. * * @param net The network interface to scan on. * @param mbed_client The mBed Client cloud interface for uploading data. * @return Returns the number of nearby APs on success, * -errno for failure. */ static int network_scan(NetworkInterface *net, M2MClient *mbed_client) { int reported; int available; WiFiAccessPoint *ap; WiFiInterface *wifi = (WiFiInterface *)net; /* scan for a list of available APs */ available = wifi->scan(NULL, 0); /* cap the number of APs reported */ reported = min(available, MBED_CONF_APP_MAX_REPORTED_APS); /* allocate and scan again */ ap = new WiFiAccessPoint[reported]; reported = wifi->scan(ap, reported); cmd.printf("Found %d devices, reporting info on %d (max=%d)\n", available, reported, MBED_CONF_APP_MAX_REPORTED_APS); /* setup the json document and custom allocator */ json::MemoryPoolAllocator<json::CrtAllocator> allocator(JSON_MEM_POOL_INC); json::Document doc(&allocator); doc.SetArray(); /* create a json record for each AP which contains a * macAddress and signalStrength key. */ for (int idx = 0; idx < reported; ++idx) { char macaddr[MACADDR_STRLEN] = {0}; snprintf(macaddr, sizeof(macaddr), "%02X:%02X:%02X:%02X:%02X:%02X", ap[idx].get_bssid()[0], ap[idx].get_bssid()[1], ap[idx].get_bssid()[2], ap[idx].get_bssid()[3], ap[idx].get_bssid()[4], ap[idx].get_bssid()[5]); /* not the prettiest thing in the world, but it avoids having to create * a number of variables to hold some these values. * The first argument is a JSON object to be pushed back: this object has * two members, the first of which is the macAddress key-value pair; the * second member is the signalStrength key-value pair. * Both the PushBack and AddMember calls require allocators which are * retrieved from the JSON doc. */ doc.PushBack( json::Value(json::kObjectType). AddMember( "macAddress", json::Value().SetString( macaddr, strlen(macaddr), doc.GetAllocator()), doc.GetAllocator()). AddMember( "signalStrength", ap[idx].get_rssi(), doc.GetAllocator() ), doc.GetAllocator() ); } /* We need a StringBuffer and Writer to generate the JSON output that will be sent */ json::StringBuffer buf; json::Writer<json::StringBuffer> writer(buf); doc.Accept(writer); #if MBED_CONF_APP_WIFI_DEBUG cmd.printf("%s\n", buf.GetString()); #endif /* update the M2MClient resource for network data and send it as a JSON array */ M2MResource *res = mbed_client->get_resource( M2MClient::M2MClientResourceNetwork); m2mclient->set_resource_value(res, buf.GetString(), buf.GetLength()); /* cleanup */ delete []ap; return reported; } static int network_connect(NetworkInterface *net) { int ret; char macaddr[MACADDR_STRLEN]; WiFiInterface *wifi; /* code is compiled -fno-rtti so we have to use C cast */ wifi = (WiFiInterface *)net; //wifi login info set to default values string ssid = MBED_CONF_APP_WIFI_SSID; string pass = MBED_CONF_APP_WIFI_PASSWORD; string security = MBED_CONF_APP_WIFI_SECURITY; //keystore db access Keystore k; //read the current state k.open(); //use the keystore for ssid? if (k.exists(SSID_KEY)) { cmd.printf("Using %s from keystore\n", SSID_KEY); ssid = k.get(SSID_KEY); } else { cmd.printf("Using default %s\n", SSID_KEY); } //use the keystore for pass? if (k.exists(PASSWORD_KEY)) { cmd.printf("Using %s from keystore\n", PASSWORD_KEY); pass = k.get(PASSWORD_KEY); } else { cmd.printf("Using default %s\n", PASSWORD_KEY); } //use the keystor for security? if (k.exists(SECURITY_KEY)) { cmd.printf("Using %s from keystore\n", SECURITY_KEY); security = k.get(SECURITY_KEY); } else { cmd.printf("Using default %s\n", SECURITY_KEY); } display.set_network_status(ssid); cmd.printf("[WIFI] connecting: mac=%s, ssid=%s, encryption=%s\n", network_get_macaddr(wifi, macaddr), ssid.c_str(), security.c_str()); ret = wifi->connect(ssid.c_str(), pass.c_str(), wifi_security_str2sec(security.c_str())); if (0 != ret) { cmd.printf("[WIFI] Failed to connect to: %s (%d)\n", ssid.c_str(), ret); return ret; } cmd.printf("[WIFI] connected: mac=%s, ssid=%s, ip=%s, netmask=%s, gateway=%s\n", network_get_macaddr(net, macaddr), ssid.c_str(), net->get_ip_address(), net->get_netmask(), net->get_gateway()); return 0; } /** * Continually attempt network connection until successful */ static void sync_network_connect(NetworkInterface *net) { int ret; do { display.set_network_connecting(); ret = network_connect(net); if (0 != ret) { display.set_network_fail(); cmd.printf("WARN: failed to init network, retrying...\n"); Thread::wait(2000); } } while (0 != ret); } // **************************************************************************** // Cloud // **************************************************************************** static void mbed_client_keep_alive(M2MClient *m2m) { if (m2m->is_client_registered()) { m2m->keep_alive(); } } /** * Handles a M2M PUT request on the app label resource */ static void mbed_client_handle_put_app_label(M2MClient *m2m) { Keystore k; std::string label; label = m2m->get_resource_value_str(M2MClient::M2MClientResourceAppLabel); if (label.length() == 0) { return; } k.open(); k.set(APP_LABEL_KEY, label); k.write(); k.close(); set_app_label(m2m, label.c_str()); } /** * Handles a M2M PUT request on Geo Latitude */ static void mbed_client_handle_put_geo_lat(M2MClient *m2m) { Keystore k; std::string val; val = m2m->get_resource_value_str(M2MClient::M2MClientResourceGeoLat); if (val.length() == 0) { return; } k.open(); /* special case '-' means delete */ if (val.length() == 1 && val[0] == '-') { k.del(GEO_LAT_KEY); } else { k.set(GEO_LAT_KEY, val); } k.write(); k.close(); } /** * Handles a M2M PUT request on Geo Longitude */ static void mbed_client_handle_put_geo_long(M2MClient *m2m) { Keystore k; std::string val; val = m2m->get_resource_value_str(M2MClient::M2MClientResourceGeoLong); if (val.length() == 0) { return; } k.open(); /* special case '-' means delete */ if (val.length() == 1 && val[0] == '-') { k.del(GEO_LONG_KEY); } else { k.set(GEO_LONG_KEY, val); } k.write(); k.close(); } /** * Handles a M2M PUT request on Geo Accuracy */ static void mbed_client_handle_put_geo_accuracy(M2MClient *m2m) { Keystore k; std::string val; val = m2m->get_resource_value_str(M2MClient::M2MClientResourceGeoAccuracy); if (val.length() == 0) { return; } k.open(); /* special case '-' means delete */ if (val.length() == 1 && val[0] == '-') { k.del(GEO_ACCURACY_KEY); } else { k.set(GEO_ACCURACY_KEY, val); } k.write(); k.close(); } /** * Readies the app for a firmware download */ void fota_auth_download(M2MClient *mbed_client) { cmd.printf("Firmware download requested\n"); sensors_stop(&sensors, &evq); /* we'll need to manually refresh the display until the firmware * update is complete. it seems that doing *anything* outside of * the firmware download's thread context will result in a failed * download. */ evq.cancel(display_evq_id); display_evq_id = 0; display.set_downloading(); display.refresh(); mbed_client->update_authorize(MbedCloudClient::UpdateRequestDownload); cmd.printf("Authorization granted\n"); } /** * Readies the app for a firmware install */ void fota_auth_install(M2MClient *mbed_client) { cmd.printf("Firmware install requested\n"); display.set_installing(); /* firmware download is complete, restart the auto display updates */ display_evq_id = evq.call_every(DISPLAY_UPDATE_PERIOD_MS, display_refresh, &display); mbed_client->set_fota_install_requested(); mbed_client->close(); } /** * Handles authorization requests from the mbed firmware updater */ void mbed_client_on_update_authorize(int32_t request) { switch (request) { /* Cloud Client wishes to download new firmware. This can have a * negative impact on the performance of the rest of the system. * * The user application is supposed to pause performance sensitive tasks * before authorizing the download. * * Note: the authorization call can be postponed and called later. * This doesn't affect the performance of the Cloud Client. * */ case MbedCloudClient::UpdateRequestDownload: m2mclient->set_fota_download_requested(); evq.call(fota_auth_download, m2mclient); break; /* Cloud Client wishes to reboot and apply the new firmware. * * The user application is supposed to save all current work before * rebooting. * * Note: the authorization call can be postponed and called later. * This doesn't affect the performance of the Cloud Client. * */ case MbedCloudClient::UpdateRequestInstall: m2mclient->set_fota_install_requested(); evq.call(fota_auth_install, m2mclient); break; default: cmd.printf("ERROR: unknown request\n"); led_set_color(IND_FWUP, IND_COLOR_FAILED); led_post(); break; } } /** * Handles progress updates from the mbed firmware updater */ void mbed_client_on_update_progress(uint32_t progress, uint32_t total) { uint32_t percent = progress * 100 / total; static uint32_t last_percent = 0; const char dl_message[] = "Downloading..."; const char done_message[] = "Saving (10s)..."; display.set_progress(dl_message, progress, total); if (last_percent < percent) { cmd.printf("Downloading: %lu\n", percent); } if (progress == total) { cmd.printf("%s\n", done_message); display.set_progress(done_message, 0, 100); display.set_download_complete(); } display.refresh(); last_percent = percent; } static void mbed_client_on_registered(void *context) { cmd.printf("mbed client registered\n"); display.set_cloud_registered(); } static void mbed_client_on_unregistered(void *context) { M2MClient *m2m; m2m = (M2MClient *)context; if (m2m->is_fota_install_requested()) { cmd.printf("Disconnecting network...\n"); network_disconnect(net); m2m->update_authorize(MbedCloudClient::UpdateRequestInstall); cmd.printf("Authorization granted\n"); } cmd.printf("mbed client unregistered\n"); display.set_cloud_unregistered(); } static void mbed_client_on_error(void *context, int err_code, const char *err_name, const char *err_desc) { M2MClient *m2m; m2m = (M2MClient *)context; cmd.printf("ERROR: mbed client (%d) %s\n", err_code, err_name); cmd.printf(" Error details : %s\n", err_desc); display.set_cloud_error(); if ((err_code == MbedCloudClient::ConnectNetworkError) || (err_code == MbedCloudClient::ConnectDnsResolvingFailed)) { if (m2m->is_fota_install_requested()) { cmd.printf("Ignoring network error due to fota install\n"); return; } network_disconnect(net); display.set_network_fail(); display.set_cloud_unregistered(); cmd.printf("Network connection failed. Attempting to reconnect.\n"); /* Because we are running in the mbed client thread context * we want to disable our sensors from modifying the mbed * client queue while we mess with the network. This will * allow the main context to continue to refresh the display. * * Holding on to this thread context until netork connection * is re-established will prevent the mbed client from backing * off the time between connection retries. */ sensors_stop(&sensors, &evq); sync_network_connect(net); display.set_network_success(); sensors_start(&sensors, &evq); /* CLoud client will automatically try to reconnect.*/ display.set_cloud_in_progress(); } } static void mbed_client_on_resource_updated(void *context, M2MClient::M2MClientResource resource) { M2MClient *m2m; M2MResource *res; m2m = (M2MClient *)context; switch (resource) { case M2MClient::M2MClientResourceAutoGeoLat: case M2MClient::M2MClientResourceAutoGeoLong: case M2MClient::M2MClientResourceAutoGeoAccuracy: cmd.printf("INFO: auto geolocation data received\n"); break; case M2MClient::M2MClientResourceAppLabel: evq.call(mbed_client_handle_put_app_label, m2m); break; case M2MClient::M2MClientResourceGeoLat: evq.call(mbed_client_handle_put_geo_lat, m2m); break; case M2MClient::M2MClientResourceGeoLong: evq.call(mbed_client_handle_put_geo_long, m2m); break; case M2MClient::M2MClientResourceGeoAccuracy: evq.call(mbed_client_handle_put_geo_accuracy, m2m); break; default: res = m2m->get_resource(resource); if (NULL != res) { cmd.printf("WARN: unsupported PUT request: resource=%d, uri_path=%s\n", resource, res->uri_path()); } else { cmd.printf("WARN: unsupported PUT request on unregistered resource=%d\n", resource); } break; } } static int register_mbed_client(NetworkInterface *iface, M2MClient *mbed_client) { mbed_client->on_registered(NULL, mbed_client_on_registered); mbed_client->on_unregistered(mbed_client, mbed_client_on_unregistered); mbed_client->on_error(mbed_client, mbed_client_on_error); mbed_client->on_update_authorize(mbed_client_on_update_authorize); mbed_client->on_update_progress(mbed_client_on_update_progress); mbed_client->on_resource_updated(mbed_client, mbed_client_on_resource_updated); display.set_cloud_in_progress(); mbed_client->call_register(iface); /* set up a keep-alive interval to send registration updates to the * mbed cloud server to avoid deregistration/registration issues. */ evq.call_every((MBED_CLOUD_CLIENT_LIFETIME / 4) * 1000, mbed_client_keep_alive, mbed_client); return 0; } static int init_fcc(void) { fcc_status_e ret; ret = fcc_init(); if (ret != FCC_STATUS_SUCCESS) { cmd.printf("ERROR: fcc init failed: %d\n", ret); return ret; } return 0; } void print_fcc_output_info(fcc_output_info_s *output_info) { fcc_warning_info_s *warning_list; if (output_info == NULL) { return; } /* print errors */ if (output_info->error_string_info != NULL) { cmd.printf("ERROR: fcc: %s\n", output_info->error_string_info); } /* print warnings */ if (output_info->size_of_warning_info_list > 0) { warning_list = output_info->head_of_warning_list; while (warning_list != NULL) { cmd.printf("WARN: fcc: %s\n", warning_list->warning_info_string); warning_list = warning_list->next; } } } static int do_fcc(void) { fcc_status_e ret; ret = fcc_developer_flow(); if (ret == FCC_STATUS_KCM_FILE_EXIST_ERROR) { cmd.printf("fcc: developer credentials already exists\n"); } else if (ret != FCC_STATUS_SUCCESS) { cmd.printf("ERROR: fcc failed to load developer credentials\n"); return ret; } ret = fcc_verify_device_configured_4mbed_cloud(); if (ret != FCC_STATUS_SUCCESS) { cmd.printf("ERROR: fcc device not correctly configured for mbed cloud\n"); fcc_output_info_s* info = fcc_get_error_and_warning_data(); print_fcc_output_info(info); return ret; } return 0; } // **************************************************************************** // Generic Helpers // **************************************************************************** static void do_factory_reset() { int ret; cmd.printf("FACTORY RESET\n"); ret = fs_format(); if (0 != ret) { cmd.printf("ERROR: fs format failed: %d\n", ret); return; } /* formatting the fs isn't enough to reset fcc */ fcc_init(); ret = fcc_storage_delete(); if (ret != FCC_STATUS_SUCCESS) { cmd.printf("ERROR: fcc delete failed: %d\n", ret); } fcc_finalize(); display_evq_id = 0; // Display "Factory Reset" message display.set_erasing(); display.set_default_view(); } static bool check_factory_reset() { int button_secs; bool button_pressed; DigitalIn button(PF_6); button.mode(PullUp); button_secs = 0; /* since our button is PullUp, pressed==0 and not-pressed==1 */ button_pressed = (button.read() == 0); while ((true == button_pressed) && (MBED_CONF_APP_FACTORY_RESET_BUTTON_PRESS_SECS > button_secs)) { Thread::wait(1000); button_pressed = (button.read() == 0); button_secs++; } return (true == button_pressed); } static int platform_init() { int ret; Keystore k; bool factory_reset; /* check if the user wants to perform a factory reset */ factory_reset = check_factory_reset(); #if MBED_CONF_MBED_TRACE_ENABLE /* Create mutex for tracing to avoid broken lines in logs */ if (!mbed_trace_helper_create_mutex()) { cmd.printf("ERROR: Mutex creation for mbed_trace failed!\n"); return -EACCES; } /* Initialize mbed trace */ mbed_trace_init(); mbed_trace_mutex_wait_function_set(mbed_trace_helper_mutex_wait); mbed_trace_mutex_release_function_set(mbed_trace_helper_mutex_release); #endif ret = fs_init(); if (0 != ret) { cmd.printf("fs_init failed: %d\n", ret); return ret; } /* setup the display */ display.init(MBED_CONF_APP_VERSION); display.refresh(); /* now that we have the fs and display up, perform the factory reset * if so requested */ if (factory_reset) { do_factory_reset(); } cmd.printf("keystore path: %s\n", k.path().c_str()); return 0; } static void platform_shutdown() { /* stop the EventQueue */ evq.break_dispatch(); } // **************************************************************************** // call back handlers for commandline interface // **************************************************************************** static void print_sha256(uint8_t *sha) { for (size_t i = 0; i < 32; ++i) { cmd.printf("%02x", sha[i]); } } static void print_hex(uint8_t *buf, size_t len) { for (size_t i = 0; i < len;) { cmd.printf("%02x ", buf[i]); if (++i % 16 == 0) cmd.printf("\n"); } } static void cmd_cb_kcmls(vector<string>& params) { uint8_t *buf; size_t real_size = 0; const size_t buf_size = 2048; uint8_t sha[32]; /* SHA256 outputs 32 bytes */ buf = (uint8_t *)malloc(buf_size); if (buf == NULL) { cmd.printf("ERROR: failed to allocate tmp buffer\n"); return; } #define PRINT_CONFIG_ITEM(x) \ do { \ memset(buf, 0, buf_size); \ int pcpret = get_config_parameter(x, buf, buf_size, &real_size); \ if (pcpret == CCS_STATUS_SUCCESS) { \ cmd.printf("%s: %s\n", x, buf); \ } else { \ cmd.printf("%s: FAIL (%d)\n", x, pcpret); \ } \ } while (false); #define PRINT_CONFIG_CERT(x) \ do { \ memset(buf, 0, buf_size); \ int pccret = get_config_certificate(x, buf, buf_size, &real_size); \ if (pccret == CCS_STATUS_SUCCESS) { \ cmd.printf("%s: \n", x); \ cmd.printf("sha="); \ mbedtls_sha256(buf, std::min(real_size, buf_size), sha, 0); \ print_sha256(sha); \ cmd.printf("\n"); \ print_hex(buf, std::min(real_size, buf_size)); \ cmd.printf("\n"); \ } else { \ cmd.printf("%s: FAIL (%d)\n", x, pccret); \ } \ } while (false) #define PRINT_CONFIG_KEY(x) \ do { \ memset(buf, 0, buf_size); \ int pccret = get_config_private_key(x, buf, buf_size, &real_size); \ if (pccret == CCS_STATUS_SUCCESS) { \ cmd.printf("%s: \n", x); \ cmd.printf("sha="); \ mbedtls_sha256(buf, std::min(real_size, buf_size), sha, 0); \ print_sha256(sha); \ cmd.printf("\n"); \ print_hex(buf, std::min(real_size, buf_size)); \ cmd.printf("\n"); \ } else { \ cmd.printf("%s: FAIL (%d)\n", x, pccret); \ } \ } while (false) /** * Device general info */ PRINT_CONFIG_ITEM(g_fcc_use_bootstrap_parameter_name); PRINT_CONFIG_ITEM(g_fcc_endpoint_parameter_name); PRINT_CONFIG_ITEM(KEY_INTERNAL_ENDPOINT); /*"mbed.InternalEndpoint"*/ PRINT_CONFIG_ITEM(KEY_ACCOUNT_ID); /* "mbed.AccountID" */ /** * Device meta data */ PRINT_CONFIG_ITEM(g_fcc_manufacturer_parameter_name); PRINT_CONFIG_ITEM(g_fcc_model_number_parameter_name); PRINT_CONFIG_ITEM(g_fcc_device_type_parameter_name); PRINT_CONFIG_ITEM(g_fcc_hardware_version_parameter_name); PRINT_CONFIG_ITEM(g_fcc_memory_size_parameter_name); PRINT_CONFIG_ITEM(g_fcc_device_serial_number_parameter_name); PRINT_CONFIG_ITEM(KEY_DEVICE_SOFTWAREVERSION);/* "mbed.SoftwareVersion" */ /** * Time Synchronization */ PRINT_CONFIG_ITEM(g_fcc_current_time_parameter_name); PRINT_CONFIG_ITEM(g_fcc_device_time_zone_parameter_name); PRINT_CONFIG_ITEM(g_fcc_offset_from_utc_parameter_name); /** * Bootstrap configuration */ PRINT_CONFIG_CERT(g_fcc_bootstrap_server_ca_certificate_name); PRINT_CONFIG_ITEM(g_fcc_bootstrap_server_crl_name); PRINT_CONFIG_ITEM(g_fcc_bootstrap_server_uri_name); PRINT_CONFIG_CERT(g_fcc_bootstrap_device_certificate_name); PRINT_CONFIG_CERT(g_fcc_bootstrap_device_private_key_name); /** * LWm2m configuration */ PRINT_CONFIG_CERT(g_fcc_lwm2m_server_ca_certificate_name); PRINT_CONFIG_ITEM(g_fcc_lwm2m_server_crl_name); PRINT_CONFIG_ITEM(g_fcc_lwm2m_server_uri_name); PRINT_CONFIG_CERT(g_fcc_lwm2m_device_certificate_name); PRINT_CONFIG_KEY(g_fcc_lwm2m_device_private_key_name); /** * Firmware update */ PRINT_CONFIG_CERT(g_fcc_update_authentication_certificate_name); free(buf); } #if MBED_STACK_STATS_ENABLED == 1 || MBED_HEAP_STATS_ENABLED == 1 static void cmd_cb_mstat(vector<string>& params) { #if MBED_HEAP_STATS_ENABLED == 1 mbed_stats_heap_t heap_stats; mbed_stats_heap_get(&heap_stats); /* heap_stats.current_size: bytes allocated currently */ cmd.printf("heap used: %lu\n", heap_stats.current_size); /* heap_stats.max_size: max bytes allocated at a given time */ cmd.printf("heap high: %lu\n", heap_stats.max_size); /* heap_stats.reserved_size: current bytes allocated for the heap */ cmd.printf("heap total: %lu\n", heap_stats.reserved_size); /* heap_stats.total_size: cumulative sum of bytes ever allocated */ cmd.printf("heap cumulative: %lu\n", heap_stats.total_size); /* heap_stats.alloc_cnt: current number of allocations */ cmd.printf("heap allocs: %lu\n", heap_stats.alloc_cnt); /* heap_stats.alloc_fail_cnt: number of failed allocations */ cmd.printf("heap fails: %lu\n", heap_stats.alloc_fail_cnt); #endif #if MBED_STACK_STATS_ENABLED == 1 int count; mbed_stats_stack_t *stats; count = osThreadGetCount(); stats = (mbed_stats_stack_t *)malloc(count * sizeof(*stats)); count = mbed_stats_stack_get_each(stats, count); for (int i = 0; i < count; i++) { cmd.printf("thread[%d] id: 0x%08x\n", i, stats[i].thread_id); cmd.printf("thread[%d] stack high: %u\n", i, stats[i].max_size); cmd.printf("thread[%d] stack total: %u\n", i, stats[i].reserved_size); } free(stats); stats = NULL; #endif } #endif static void cmd_cb_del(vector<string>& params) { //check params if (params.size() >= 2) { //the db Keystore k; //read the file k.open(); //delete the given key k.del(params[1]); //write the changes back out k.write(); k.close(); //let user know cmd.printf("Deleted key %s\n", params[1].c_str()); } else { cmd.printf("Not enough arguments!\n"); } } static void cmd_cb_get(vector<string>& params) { //check params if (params.size() >= 1) { //database Keystore k; //don't show all keys by default bool ball = false; //read current values k.open(); //if no param set to * if (params.size() == 1) { ball = true; } else if (params[1] == "*") { ball = true; } //show all keys? if (ball) { //get all keys vector<string> keys = k.keys(); //walk the keys for (unsigned int n = 0; n < keys.size(); n++) { //get value string val = k.get(keys[n]); //format for display cmd.printf("%s=%s\n", keys[n].c_str(), val.c_str()); } } else { // if not get one key string val = k.get(params[1]); //return just the value cmd.printf("%s\n", val.c_str()); } } else { cmd.printf("Not enough arguments!\n"); } } static void cmd_cb_set(vector<string>& params) { //check params if (params.size() >= 2) { //db Keystore k; //read the file into db k.open(); //default to empty string strvalue = ""; //create our value for (size_t x = 2; x < params.size(); x++) { //don't prepend space on 1st word if (x != 2) { strvalue += " "; } strvalue += params[x]; } //make the change k.set(params[1], strvalue); //write the file back out k.write(); k.close(); //return just the value cmd.printf("%s=%s\n", params[1].c_str(), strvalue.c_str()); } else { cmd.printf("Not enough arguments!\n"); } } static void cmd_cb_reboot(vector<string>& params) { cmd.printf("\nRebooting..."); NVIC_SystemReset(); } static void cmd_cb_format(vector<string>& params) { int ret; string type; string usage = "usage: format <type>\n" " supported types: fat"; if (params.size() < 2) { cmd.printf("ERROR: missing fs type\n"); return; } if (params.size() > 2) { cmd.printf("ERROR: too many parameters\n"); return; } type = params[1]; if (type == "fat") { ret = fs_format(); if (0 != ret) { cmd.printf("ERROR: keystore format failed: %d\n", ret); return; } cmd.printf("SUCCESS\n"); } else if (type == "-h" || type == "--help") { cmd.printf("%s\n", usage.c_str()); } else { cmd.printf("ERROR: unsupported fs type: %s\n", params[1].c_str()); cmd.printf("%s\n", usage.c_str()); } } static void cmd_cb_test(vector<string>& params) { fs_test(); } static void cmd_cb_ls(vector<string>& params) { std::string path; if (params.size() > 1) { path = params[1]; } else { path = "/"; } fs_ls(path); } static void cmd_cb_cat(vector<string>& params) { if (params.size() <= 1) { cmd.printf("Not enough arguments!\n"); return; } fs_cat(params[1]); } static void cmd_cb_rm(vector<string>& params) { if (params.size() <= 1) { cmd.printf("Not enough arguments!\n"); return; } fs_remove(params[1]); } static void cmd_cb_mkdir(vector<string>& params) { if (params.size() <= 1) { cmd.printf("Not enough arguments!\n"); return; } fs_mkdir(params[1]); } static void cmd_cb_reset(vector<string>& params) { Keystore k; //default to delete nothing bool bcerts = false; bool boptions = false; //check params if (params.size() > 1) { //set up the users options if (params[1] == "certs") { bcerts = true; } else if (params[1] == "options") { boptions = true; } else if (params[1] == "all") { bcerts = true; boptions = true; } else { cmd.printf("Unknown parameters.\n"); } } else { //no params defaults options boptions = true; } //delete fcc certifications? if (bcerts) { int ret = fcc_storage_delete(); if (ret != FCC_STATUS_SUCCESS) { if (ret == FCC_STATUS_NOT_INITIALIZED) { cmd.printf("ERROR: fcc delete failed: FCC not yet initialized\n"); } else { cmd.printf("ERROR: fcc delete failed: %d\n", ret); } } } //delete from keystore? if (boptions) { k.kill_all(); } } static void cmd_cb_verbose(vector<string>& params) { if (params.size() < 2) { cmd.printf("ERROR: Invalid usage of verbose!\n"); cmd.printf("Usage: verbose <type> [off|on], defaults to off.\n"); cmd.printf(" Current types supported: sensors\n"); return; } if (params[1] == "sensors") { /* print the current status of verbosity */ if (params.size() < 3) { cmd.printf("Sensor verbosity is currently %s\n", wem_sensors_verbose_enabled ? "enabled" : "disabled"); return; } /* if an additional parameter was supplied the check that */ if (params[2] == "on") { wem_sensors_verbose_enabled = true; cmd.printf("verbose sensor printing enabled\n"); } else if (params[2] == "off") { wem_sensors_verbose_enabled = false; cmd.printf("verbose sensor printing disabled\n"); } else { cmd.printf("ERROR: Invalid parameter supplied! %s\n", params[1].c_str()); return; } } else { /* if we add more than just sensors we should use * this as a catch all to enable or disable all */ cmd.printf("ERROR: unsupported option %s!\n", params[1].c_str()); } } static void cmd_pump(Commander *cmd) { cmd->pump(); } void cmd_on_ready(void) { evq.call(cmd_pump, &cmd); } /** * Sets up the command shell */ void init_commander(void) { cmd.on_ready(cmd_on_ready); // add our callbacks cmd.add("get", "Get the value for the given configuration option. Usage: get [option] defaults to *=all", cmd_cb_get); cmd.add("set", "Set a configuration option to a the given value. Usage: set <option> <value>", cmd_cb_set); cmd.add("del", "Delete a configuration option from the store. Usage: del <option>", cmd_cb_del); cmd.add("reboot", "Reboot the device. Usage: reboot", cmd_cb_reboot); cmd.add("reset", "Reset configuration options and/or certificates. Usage: reset [options|certs|all] defaults to options", cmd_cb_reset); #if MBED_STACK_STATS_ENABLED == 1 || MBED_HEAP_STATS_ENABLED == 1 cmd.add("mstat", "Show runtime heap and stack statistics.", cmd_cb_mstat); #endif cmd.add("verbose", "Enables verbose printing of sensor values when set 'on'. Usage: verbose <type> [off|on], defeaults to off", cmd_cb_verbose); cmd.add("format", "Format the internal file system. Usage: format <fs-type>", cmd_cb_format); cmd.add("ls", "List directory entries. Usage: ls <path>", cmd_cb_ls); cmd.add("cat", "Read the contents of a file. Usage: cat <path>", cmd_cb_cat); cmd.add("rm", "Remove a file. Usage: rm <path>", cmd_cb_rm); cmd.add("mkdir", "Make a directory. Usage: mkdir <path>", cmd_cb_mkdir); cmd.add("test", "Run the keystore tests. Usage: test", cmd_cb_test); cmd.add("kcmls", "Show KCM config parameters", cmd_cb_kcmls); //display the banner cmd.banner(); //prime the serial cmd.init(); } static void init_app_label(M2MClient *m2m) { Keystore k; string label; display.register_sensor(APP_LABEL_SENSOR_NAME); k.open(); if (k.exists(APP_LABEL_KEY)) { label = k.get(APP_LABEL_KEY); } else { label = MBED_CONF_APP_APP_LABEL; } k.close(); set_app_label(m2m, label.c_str()); } static void init_geo(M2MClient *m2m) { Keystore k; k.open(); if (k.exists(GEO_LAT_KEY)) { m2m->set_resource_value(M2MClient::M2MClientResourceGeoLat, k.get(GEO_LAT_KEY)); #ifdef MBED_CONF_APP_GEO_LAT } else { m2m->set_resource_value(M2MClient::M2MClientResourceGeoLat, MBED_CONF_APP_GEO_LAT); #endif } if (k.exists(GEO_LONG_KEY)) { m2m->set_resource_value(M2MClient::M2MClientResourceGeoLong, k.get(GEO_LONG_KEY)); #ifdef MBED_CONF_APP_GEO_LONG } else { m2m->set_resource_value(M2MClient::M2MClientResourceGeoLong, MBED_CONF_APP_GEO_LONG); #endif } if (k.exists(GEO_ACCURACY_KEY)) { m2m->set_resource_value(M2MClient::M2MClientResourceGeoAccuracy, k.get(GEO_ACCURACY_KEY)); #ifdef MBED_CONF_APP_GEO_ACCURACY } else { m2m->set_resource_value(M2MClient::M2MClientResourceGeoAccuracy, MBED_CONF_APP_GEO_ACCURACY); #endif } k.close(); } static void init_app(EventQueue *queue) { int ret; /* init the fcc as early as possible to allow the user * to call "reset certs" without having to wait for the * network to connect */ init_fcc(); /* create the network */ cmd.printf("init network\n"); net = network_create(); if (NULL == net) { cmd.printf("ERROR: failed to create network stack\n"); display.set_network_fail(); return; } m2mclient = new M2MClient(); m2mclient->init(); init_app_label(m2mclient); init_geo(m2mclient); /* workaround: go ahead and connect the network. it doesn't like being * polled for status before a connect() is attempted. * in addition, the fcc code requires a connected network when generating * creds the first time, so we need to spin here until we have an active * network. */ sync_network_connect(net); cmd.printf("init network: OK\n"); /* scan the network for nearby devices or APs. */ cmd.printf("scanning network for nearby devices...\n"); display.set_network_scanning(); ret = network_scan(net, m2mclient); if (0 > ret) { cmd.printf("WARN: failed to scan network! %d\n", ret); } /* network_scan can take some time to perform when on WiFi, and since we * don't have a separate indicator to show progress we delay the setting * of success until we have finished. */ display.set_network_success(); /* initialize the factory configuration client * WARNING: the network must be connected first, otherwise this * will not return if creds haven't been provisioned for the first time. * */ cmd.printf("run factory configuration client\n"); ret = do_fcc(); if (0 != ret) { cmd.printf("ERROR: failed to run factory configuration client: %d\n", ret); return; } cmd.printf("run factory configuration client: OK\n"); cmd.printf("init sensors\n"); sensors_init(&sensors, m2mclient); sensors_start(&sensors, &evq); /* connect to mbed cloud */ cmd.printf("init mbed client\n"); /* WARNING: the sensor resources must be added to the mbed client * before the mbed client connects to the cloud, otherwise the * sensor resources will not exist in the portal. */ register_mbed_client(net, m2mclient); std::map<std::string, DeviceResource*> all_resources_map; all_resources_map["light"]=new M2MDeviceResource(sensors.light.res); all_resources_map["temperature"]=new M2MDeviceResource(sensors.dht.t_res); all_resources_map["humidity"]=new M2MDeviceResource(sensors.dht.h_res); const char* devicename="WEMDevice1"; MQTTDataProvider data_provider(devicename, all_resources_map); data_provider.run(net); } // **************************************************************************** // Main // main() runs in its own thread in the OS // // Be aware of 3 threads of execution. // 1. The init thread is kicked off when the app first starts and is // responsible for bringing up the mbed client, the network, the sensors, // etc., and exits as soon as initialization is complete. // 2. The main thread dispatches the event queue and is where all normal // runtime operations are processed. // 3. The firmware update thread runs in the context of the mbed client and // executes callbacks in our app. When a firmware update begins and a // download started, the event queue in the main thread must be halted until // the download completes. Through a good deal of testing, it seems that // any work performed outside of the mbed client's context while a download // is in progress will cause the downloaded file to become corrupt and // therefore cause the firmware update to fail. // **************************************************************************** int main() { int ret; /* stack size 2048 is too small for fcc_developer_flow() */ Thread thread(osPriorityNormal, 4224); /* init the console manager so we can printf */ init_commander(); /* the bootloader doesn't seem to print a final newline before passing * control to the app, which causes the version string to be mangled * when printed on the console. if we print a newline first before * printing anything else, we can work around the issue. */ cmd.printf("\n"); cmd.printf("Workplace Environmental Monitor version: %s\n", MBED_CONF_APP_VERSION); cmd.printf(" code version: " xstr(DEVTAG) "\n"); /* minimal init sequence */ cmd.printf("init platform\n"); ret = platform_init(); if (0 != ret) { cmd.printf("init platform: FAIL\n"); } else { cmd.printf("init platform: OK\n"); } /* set the refresh rate of the display. */ display_evq_id = evq.call_every(DISPLAY_UPDATE_PERIOD_MS, display_refresh, &display); /* use a separate thread to init the remaining components so that we * can continue to refresh the display */ thread.start(callback(init_app, &evq)); cmd.printf("entering run loop\n"); evq.dispatch(); cmd.printf("exited run loop\n"); platform_shutdown(); cmd.printf("exiting main\n"); return 0; }
[ "michael.lubinsky@arm.com" ]
michael.lubinsky@arm.com
09c417210cfb84fad3c2fb65f46a2694c6062daf
8a2f2efea44836225fb1bbe3a50a003481a926af
/AwoEngine/AwoEngine/Application.cpp
fc364336e1584c54cef39db78581ef1069f6dbac
[]
no_license
awoiro/BilliardsGame
d34c1203d10f3e92b8cbd24fed5e50b7828c644e
39c9db73913c356562035622243a0ff654c90b01
refs/heads/master
2021-05-01T11:58:39.576681
2017-05-27T01:32:21
2017-05-27T01:32:21
70,028,441
1
0
null
null
null
null
SHIFT_JIS
C++
false
false
3,754
cpp
#include "Application.h" void Application::Init(HWND hWnd, SIZE windowSize) { // device init m_pDeviceManager = new DeviceManager; m_pDeviceManager->InitD3D(hWnd, windowSize); // antWeekBar init TwInit(TW_DIRECT3D11, m_pDeviceManager->m_pDevice); // canera init m_pCamera = new Camera(); // input init m_pInput = new Input(); // physics init m_pPhysics = new Physics(); // mesh importer init m_pMeshManager = new MeshImporter(); m_pMeshManager->m_pDevice = m_pDeviceManager->m_pDevice; m_pMeshManager->m_pDeviceContext = m_pDeviceManager->m_pDeviceContext; m_pMeshManager->m_pSampleLinear = m_pDeviceManager->m_pSampleLinear; m_pMeshManager->m_pConstantBuffer = m_pDeviceManager->m_pConstantBuffer1; // audio init m_pAudio = new Audio(); m_pAudio->Init(); m_pAudio->PlayCue(BGM3); // game manager init m_pGameManager = new GameManager(); } void Application::Update(HWND hwnd, SIZE windowSize) { // static int frame = 0; static float time = timeGetTime(); // frame++; if (timeGetTime() > time+ 1000.0f / 60.0f) { // frame = 0; time = timeGetTime(); m_pGameManager->ShowFPSText(50, 10); // input event #if false if (m_pInput->GetKeyDown(DIK_R)) // reset { m_pGameManager->Reset(); } #endif if (m_pInput->GetKeyDown(DIK_S)) // shoot { m_pGameManager->Shoot(m_pAudio); } // game manager m_pGameManager->Update(m_pDeviceManager,m_pMeshManager,m_pPhysics, m_pAudio); // PhysX m_pPhysics->StepPhysics(); // PhysX move m_pGameManager->PhysicsMoveToBall(); } } void Application::RenderSetUp(HWND hwnd, SIZE windowSize) { m_pDeviceManager->RenderSetUp(windowSize); if (m_pMeshManager) { m_pCamera->CameraSetting(m_pDeviceManager); m_pMeshManager->m_view = m_pCamera->GetView(); m_pMeshManager->m_proj = m_pCamera->GetProjection(m_pDeviceManager->m_depthStencilDesc); // obj render m_pGameManager->Render(m_pMeshManager); } // tw window and text render TwDraw(); /* // PhysX m_pPhysics->StepPhysics(); // PhysX move m_pGameManager->PhysicsMoveToBall(); */ // screen update m_pDeviceManager->UpdateScreen(); // create models if (m_pGameManager->CheckIsCreateModel() == false) { m_pGameManager->CreateModels(m_pDeviceManager, m_pMeshManager, m_pPhysics); m_pCamera->ShowCameraEditWindow(); } } void Application::InputKeyUpdate() { m_pInput->UpdateKeyCode(); m_pInput->UpdateMouseCode(); } void Application::ResizeWindow(LPARAM lParam) { m_pDeviceManager->ResizeRenderWindow(lParam); } void Application::ResizeWindow(SIZE windowSize) { m_pDeviceManager->ResizeRenderWindow(windowSize); } #if false // インプットテスト void InputTest() { // キーボードのインプット if (m_pInput->GetKeyDown(DIK_T)) { RenderTwText(10, 10, "KeyDownT"); }; if (m_pInput->GetKeyUp(DIK_R)) { RenderTwText(10, 20, "KeyDownT"); }; if (m_pInput->GetKeyUp(DIK_A)) { RenderTwText(10, 30, "KeyDownT"); }; if (m_pInput->GetKeyDown(DIK_R)) { RenderTwText(10, 40, "KeyDownT"); }; if (m_pInput->GetKeyDown(DIK_A)) { RenderTwText(10, 50, "KeyDownT"); }; if (m_pInput->GetKeyDown(DIK_R)) { RenderTwText(10, 60, "KeyDownT"); } if (m_pInput->GetKey(DIK_E)) { RenderTwText(10, 65, "GetKey"); } // マウスインプット if (m_pInput->GetMouseButtonUp(Input::MOUSE_BUTTON_RIGHT)) { RenderTwText(10, 70, "KeyDownT"); } if (m_pInput->GetMouseButtonDown(Input::MOUSE_BUTTON_RIGHT)) { RenderTwText(10, 80, "KeyDownT"); } if (m_pInput->GetMouseButton(Input::MOUSE_BUTTON_LEFT)) { RenderTwText(10, 90, "KeyDownT"); } D3DXVECTOR2 mousePos = m_pInput->GetMousePos(windowSize.cx, windowSize.cy, hWnd); char message[100]; wsprintfA(message, "Mouse Pos ( X:%d , Y:%d )", (int)mousePos.x, (int)mousePos.y); RenderTwText(10, 100, message); } #endif
[ "awoiro7224@yahoo.co.jp" ]
awoiro7224@yahoo.co.jp
eae7a1e72bc6b775ed6e4460656b9a18de85cfae
482bdf83ad889335884606390eecd63c75153662
/include/PlayerActorStrategy.hh
52887064888f87befd20f87e03c814808d93d792
[]
no_license
Lunderberg/battle-bots
59be905eb9da43092e1a920076c3af8ae23b473d
69881e06e1cebe7682931d1cb73f57363e22f984
refs/heads/master
2020-05-25T09:18:52.701677
2015-10-04T17:20:46
2015-10-04T17:20:46
30,394,996
0
0
null
null
null
null
UTF-8
C++
false
false
352
hh
#ifndef _PLAYERACTORSTRATEGY_H_ #define _PLAYERACTORSTRATEGY_H_ #include "ActorStrategy.hh" class PlayerActorStrategy : public ActorStrategy { public: PlayerActorStrategy(); virtual Action ChooseAction(); void SetCurrentAction(Action action){ currentAction = action; } private: Action currentAction; }; #endif /* _PLAYERACTORSTRATEGY_H_ */
[ "eldritch.cheese@gmail.com" ]
eldritch.cheese@gmail.com
8c1ce110088fe67029972428e044c90dced74498
fc838bc7be081ac4448ca3bd575f419afae44515
/Lab_string/Lab_string/functions.h
9de92c0a44e7cfaeda9a696b6a5851513a0cbf93
[]
no_license
feedblackg44/kpilabs
e665287869bf0631527b363df3993d7cc2453b11
ab7dade056b5cbea0d9be3941517509e328feaf9
refs/heads/master
2023-02-12T03:08:13.423979
2021-01-12T10:14:15
2021-01-12T10:14:15
308,298,496
0
0
null
null
null
null
UTF-8
C++
false
false
223
h
#pragma once #include <string> #define DELIMITERS " ,.:;\'\"" std::string ExtractFisrtWordOfString(std::string* strIn); bool MatchPattern(const char* symbols, char symbol); std::string makeOutString(std::string strIn);
[ "pilmyh@gmail.com" ]
pilmyh@gmail.com
d17c7b4ace11d7b8aeb0dc589b3baa9f8ba87d58
41b60918b7307f59f59db804d196007d394c986a
/include/Tracking.h
c764d7964a666b43c6ac22e88a3b26c55528b2b1
[]
no_license
ClarkWang1214/ORB_SLAM_NOROS
ac83e9579eb29163d2241906e76600f7a8f2c584
019a80bea79d92b60debe8ed66b35b1027b96bd7
refs/heads/master
2021-05-29T18:19:51.346261
2015-05-19T13:08:05
2015-05-19T13:08:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,517
h
/** * This file is part of ORB-SLAM. * * Copyright (C) 2014 Raúl Mur-Artal <raulmur at unizar dot es> (University of Zaragoza) * For more information see <http://webdiis.unizar.es/~raulmur/orbslam/> * * ORB-SLAM is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ORB-SLAM is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with ORB-SLAM. If not, see <http://www.gnu.org/licenses/>. */ #ifndef TRACKING_H #define TRACKING_H #include<opencv2/core/core.hpp> #include<opencv2/features2d/features2d.hpp> //#include<sensor_msgs/Image.h> //#include<sensor_msgs/image_encodings.h> //#include"FramePublisher.h" #include"Map.h" #include"LocalMapping.h" #include"LoopClosing.h" #include"Frame.h" #include "ORBVocabulary.h" #include"KeyFrameDatabase.h" #include"ORBextractor.h" #include "Initializer.h" //#include "MapPublisher.h" #include <fstream> //#include<tf/transform_broadcaster.h> using namespace std; namespace ORB_SLAM { class FramePublisher; class Map; class LocalMapping; class LoopClosing; class Tracking { int tkCount; public: Tracking(ORBVocabulary* pVoc, /*FramePublisher* pFramePublisher, MapPublisher* pMapPublisher, */Map* pMap, string strSettingPath); enum eTrackingState{ SYSTEM_NOT_READY=-1, NO_IMAGES_YET=0, NOT_INITIALIZED=1, INITIALIZING=2, WORKING=3, LOST=4 }; void SetLocalMapper(LocalMapping* pLocalMapper); void SetLoopClosing(LoopClosing* pLoopClosing); void SetKeyFrameDatabase(KeyFrameDatabase* pKFDB); // This is the main function of the Tracking Thread void Run(); void ForceRelocalisation(); eTrackingState mState; eTrackingState mLastProcessedState; // Current Frame Frame mCurrentFrame; // Initialization Variables std::vector<int> mvIniLastMatches; std::vector<int> mvIniMatches; std::vector<cv::Point2f> mvbPrevMatched; std::vector<cv::Point3f> mvIniP3D; Frame mInitialFrame; void CheckResetByPublishers(); protected: void GrabImage(const cv::Mat& img, double timesmp); void FirstInitialization(); void Initialize(); void CreateInitialMap(cv::Mat &Rcw, cv::Mat &tcw); void Reset(); bool TrackPreviousFrame(); bool TrackWithMotionModel(); bool RelocalisationRequested(); bool Relocalisation(); void UpdateReference(); void UpdateReferencePoints(); void UpdateReferenceKeyFrames(); bool TrackLocalMap(); void SearchReferencePointsInFrustum(); bool NeedNewKeyFrame(); void CreateNewKeyFrame(); //Other Thread Pointers LocalMapping* mpLocalMapper; LoopClosing* mpLoopClosing; //ORB ORBextractor* mpORBextractor; ORBextractor* mpIniORBextractor; //BoW ORBVocabulary* mpORBVocabulary; KeyFrameDatabase* mpKeyFrameDB; // Initalization Initializer* mpInitializer; //Local Map KeyFrame* mpReferenceKF; std::vector<KeyFrame*> mvpLocalKeyFrames; std::vector<MapPoint*> mvpLocalMapPoints; //Publishers //FramePublisher* mpFramePublisher; //MapPublisher* mpMapPublisher; //Map Map* mpMap; //Calibration matrix cv::Mat mK; cv::Mat mDistCoef; //New KeyFrame rules (according to fps) int mMinFrames; int mMaxFrames; //Current matches in frame int mnMatchesInliers; //Last Frame, KeyFrame and Relocalisation Info KeyFrame* mpLastKeyFrame; Frame mLastFrame; unsigned int mnLastKeyFrameId; unsigned int mnLastRelocFrameId; //Mutex boost::mutex mMutexTrack; boost::mutex mMutexForceRelocalisation; //Reset bool mbPublisherStopped; bool mbReseting; boost::mutex mMutexReset; //Is relocalisation requested by an external thread? (loop closing) bool mbForceRelocalisation; //Motion Model bool mbMotionModel; cv::Mat mVelocity; //Color order (true RGB, false BGR, ignored if grayscale) bool mbRGB; // Transfor broadcaster (for visualization in rviz) // tf::TransformBroadcaster mTfBr; }; } //namespace ORB_SLAM #endif // TRACKING_H
[ "walawalasouk@163.com" ]
walawalasouk@163.com
33aa943f8f782d24a7bca5968f84806ef3afb36f
23e393f8c385a4e0f8f3d4b9e2d80f98657f4e1f
/3rdparty/oless/oless/vbahelper.h
cb94b5a5d6b4b8f63ce4c0cadf70baad8effef2f
[ "MIT" ]
permissive
IgorYunusov/Mega-collection-cpp-1
c7c09e3c76395bcbf95a304db6462a315db921ba
42d07f16a379a8093b6ddc15675bf777eb10d480
refs/heads/master
2020-03-24T10:20:15.783034
2018-06-12T13:19:05
2018-06-12T13:19:05
142,653,486
3
1
null
2018-07-28T06:36:35
2018-07-28T06:36:35
null
UTF-8
C++
false
false
6,110
h
#ifndef VBAHELPER_H #define VBAHELPER_H #include <vector> #include <tuple> #include <exception> #include <iostream> #include <string> #include <sstream> #include <algorithm> #include <iterator> #include "pole.h" #include "common.hpp" struct MODULEOFFSET { unsigned short Id; unsigned int Size; unsigned int TextOffset; }; struct VBAProjectStreamHeader { unsigned short Reserved1; unsigned short Version; unsigned short Reserved2; unsigned short Reserved3; }; struct ProjectSysKind{ unsigned short Id; unsigned int Size; unsigned int SysKind; }; struct ProjectLCID { unsigned short Id; unsigned int Size; unsigned int Lcid; }; struct ProjectLCIDInvoke{ unsigned short Id; unsigned int Size; unsigned int LcidInvoke; }; struct ProjectCodePage{ unsigned short Id; unsigned int Size; unsigned short CodePage; }; struct ProjectName { unsigned short Id; unsigned int SizeOfProjectName; std::string Name; }; struct ProjectDocString{ unsigned short Id; unsigned int SizeOfDocString; std::string DocString; unsigned short Reserved; unsigned int SizeOfDocStringUnicode; std::string DocStringUnicode; }; struct ProjectHelpFilePath{ unsigned short Id; unsigned int SizeOfHelpFile1; std::string HelpFile1; unsigned short Reserved; unsigned int SizeOfHelpFile2; std::string HelpFile2; }; struct ProjectHelpContext{ unsigned short Id; unsigned int Size; unsigned int HelpContext; }; struct ProjectLibFlags{ unsigned short Id; unsigned int Size; unsigned int Flags; }; struct ProjectVersion{ unsigned short Id; unsigned int Size; unsigned int VersionMajor; unsigned short VersionMinor; }; struct ProjectConstants{ unsigned short Id; unsigned int SizeOfConstants; std::string Constants; unsigned short Reserved; unsigned int SizeOfConstantsUnicode; std::string ConstantsUnicode; }; struct ProjectInformation { ProjectSysKind SysKindRecord; ProjectLCID LcidRecord; ProjectLCIDInvoke LcidInvokeRecord; ProjectCodePage CodePageRecord; ProjectName NameRecord; ProjectDocString DocStringRecord; ProjectHelpFilePath HelpFilePathRecord; ProjectHelpContext HelpContextRecord; ProjectLibFlags LibFlagsRecord; ProjectVersion VersionRecord; ProjectConstants ConstantsRecord; }; struct ProjectModule { std::string Name; std::string StreamName; unsigned int Offset; std::string Code; bool isPrivate; bool isReadOnly; }; class VbaExtensionInfo : public ExtensionInfo { public: std::string ProjectName; std::vector<std::string> References; std::vector<ProjectModule*> Modules; unsigned int VBAVersionMajor; unsigned short VBAVersionMinor; VbaExtensionInfo() { this->Extension = ".vba"; this->VersionName = "Visual Basic for Applications"; }; virtual std::string ToJson() { std::ostringstream str; str << "{"; str << "\"extension\" : \"" << this->Extension << "\""; str << ", \"name\" : \"" << this->VersionName << "\""; str << ", \"ProjectName\" : \"" << this->ProjectName << "\""; str << ", \"ProjectVersion\" : " << this->Version; str << ", \"VBAVersionMajor\" : " << this->VBAVersionMajor; str << ", \"VBAVersionMinor\" : " << this->VBAVersionMinor; str << ", \"References\" : [" << helper::vector_join(this->References, ",", true) << "]"; str << ", \"Modules\" : ["; for (std::vector<ProjectModule*>::const_iterator i = this->Modules.begin(); i != this->Modules.end(); i++){ if (i != this->Modules.begin()) str << ","; str << "{"; str << "\"Name\":\"" << (*i)->Name << "\""; str << ",\"StreamName\":\"" << (*i)->StreamName<< "\""; str << ",\"Offset\":" << (*i)->Offset; str << ",\"isPrivate\":" << (*i)->isPrivate; str << ",\"isReadOnly\":" << (*i)->isReadOnly; std::string code = (*i)->Code; str << ",\"Code\":\"" << helper::JsonEscape((*i)->Code) << "\""; str << "}"; } str << "]"; str << "}"; return str.str(); } virtual std::string ToXml() { std::ostringstream str; str << "<item>"; str << "<extension>" << this->Extension << "</extension>"; str << "<name>" << this->VersionName << "</name>"; str << "<ProjectName>" << this->ProjectName << "</ProjectName>"; str << "<ProjectVersion>" << this->Version << "</ProjectVersion>"; str << "<VBAVersionMajor>" << this->VBAVersionMajor << "</VBAVersionMajor>"; str << "<VBAVersionMinor>" << this->VBAVersionMinor << "</VBAVersionMinor>"; str << "<References>"; for (std::vector<std::string>::const_iterator i = this->References.begin(); i != this->References.end(); i++) { str << "<Reference>" << *i << "</Reference>"; } str << "</References>"; str << "<Modules>"; for (std::vector<ProjectModule*>::const_iterator i = this->Modules.begin(); i != this->Modules.end(); i++){ if (i != this->Modules.begin()) str << ","; str << "<Module>"; str << "<Name>" << (*i)->Name << "</Name>"; str << "<StreamName>" << (*i)->StreamName << "</StreamName>"; str << "<Offset>" << (*i)->Offset << "</Offset>"; str << "<isPrivate>" << (*i)->isPrivate << "</isPrivate>"; str << "<isReadOnly>" << (*i)->isReadOnly << "</isReadOnly>"; str << "<Code><![CDATA[" << (*i)->Code << "]]></Code>"; str << "</Module>"; } str << "</Modules>"; str << "</item>"; return str.str(); } virtual std::string ToText() { std::ostringstream str; str << this->Extension << "\t" << this->Version << "\t" << this->VersionName; str << "\t" << this->ProjectName; str << "\t" << this->Version; str << "\t" << this->VBAVersionMajor; str << "\t" << this->VBAVersionMinor; return str.str(); } virtual std::string ToCsv() { std::ostringstream str; str << this->Extension << "," << this->Version << "," << this->VersionName; str << "," << this->ProjectName; str << "," << this->Version; str << "," << this->VBAVersionMajor; str << "," << this->VBAVersionMinor; return str.str(); } }; class vbahelper { private: friend void compressionTest(std::string, POLE::Storage*); public: vbahelper(); ~vbahelper(); VbaExtensionInfo* Analyze(std::string, POLE::Storage*); static std::tuple<unsigned int, unsigned char*> Decompress(const unsigned int, const unsigned char*); }; #endif
[ "wyrover@gmail.com" ]
wyrover@gmail.com
6962f17ebd3ec87c56cf4998a5c6d07ad0dc17ab
0475c69eeaa0ffc5fcb587ae535840aa4d530cf4
/codeforces/div2/eduround90/1.cpp
4327cefcc5e5c35e79fe0e1e80b91c69d2903cdc
[]
no_license
saisnehith/Coding
5f232f74f4ac722f6ffbc93b8e9b6031fdb43153
9d8c3a2f5f65005b413f8962c5b103b688a7cbb4
refs/heads/master
2022-11-30T10:16:41.297579
2020-08-10T17:06:42
2020-08-10T17:06:42
285,996,927
0
0
null
null
null
null
UTF-8
C++
false
false
252
cpp
#include<bits/stdc++.h> using namespace std; int main( ){ int t; cin>>t; while(t--){ long long int a,b,c,k,i,j,ans1=-1,ans2=-1; cin>>a>>b>>c; if(c<a*b){ ans2=b; } if(a<c){ ans1=1; } cout<<ans1<<" "<<ans2<<endl; } return 0; }
[ "g.saisnehith8978@gmail.com" ]
g.saisnehith8978@gmail.com
7411b8ac691bcdf346976bb960946d8efd8a7bda
c93e97f0f3d64ac35e4af2d603050d1797bc219d
/media/libvideoeditor/lvpp/PreviewPlayerBase.h
bb5c3d30a315f6e4ee3dc338800ee00f4c739517
[]
no_license
pngcui/Android4.0_Frameworks
43d89f9f30480c6c88ed9c2cb607bc0370dffc1f
5941ec917ed9410cb9ac3af375a22398e7af0eae
refs/heads/master
2021-01-13T03:19:32.571493
2017-02-10T01:14:51
2017-02-10T01:14:51
77,574,012
4
1
null
null
null
null
UTF-8
C++
false
false
7,527
h
/* * Copyright (C) 2011 The Android Open Source Project * * 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 PREVIEW_PLAYER_BASE_H_ #define PREVIEW_PLAYER_BASE_H_ #include "HTTPBase.h" #include "TimedEventQueue.h" #include <media/MediaPlayerInterface.h> #include <media/stagefright/DataSource.h> #include <media/stagefright/MediaSource.h> #include <media/stagefright/OMXClient.h> #include <media/stagefright/TimeSource.h> #include <utils/threads.h> #include <drm/DrmManagerClient.h> namespace android { struct AudioPlayerBase; struct DataSource; struct MediaBuffer; struct MediaExtractor; struct MediaSource; struct NuCachedSource2; struct ISurfaceTexture; class DrmManagerClinet; class DecryptHandle; struct AwesomeRenderer : public RefBase { AwesomeRenderer() {} virtual void render(MediaBuffer *buffer) = 0; private: AwesomeRenderer(const AwesomeRenderer &); AwesomeRenderer &operator=(const AwesomeRenderer &); }; struct PreviewPlayerBase { PreviewPlayerBase(); ~PreviewPlayerBase(); void setListener(const wp<MediaPlayerBase> &listener); status_t setDataSource( const char *uri, const KeyedVector<String8, String8> *headers = NULL); status_t setDataSource(int fd, int64_t offset, int64_t length); status_t setDataSource(const sp<IStreamSource> &source); void reset(); status_t prepare(); status_t prepare_l(); status_t prepareAsync(); status_t prepareAsync_l(); status_t play(); status_t pause(); bool isPlaying() const; void setSurface(const sp<Surface> &surface); void setSurfaceTexture(const sp<ISurfaceTexture> &surfaceTexture); void setAudioSink(const sp<MediaPlayerBase::AudioSink> &audioSink); status_t setLooping(bool shouldLoop); status_t getDuration(int64_t *durationUs); status_t getPosition(int64_t *positionUs); status_t setParameter(int key, const Parcel &request); status_t getParameter(int key, Parcel *reply); status_t seekTo(int64_t timeUs); // This is a mask of MediaExtractor::Flags. uint32_t flags() const; void postAudioEOS(int64_t delayUs = 0ll); void postAudioSeekComplete(); private: friend struct AwesomeEvent; friend struct PreviewPlayer; enum { PLAYING = 1, LOOPING = 2, FIRST_FRAME = 4, PREPARING = 8, PREPARED = 16, AT_EOS = 32, PREPARE_CANCELLED = 64, CACHE_UNDERRUN = 128, AUDIO_AT_EOS = 256, VIDEO_AT_EOS = 512, AUTO_LOOPING = 1024, // We are basically done preparing but are currently buffering // sufficient data to begin playback and finish the preparation phase // for good. PREPARING_CONNECTED = 2048, // We're triggering a single video event to display the first frame // after the seekpoint. SEEK_PREVIEW = 4096, AUDIO_RUNNING = 8192, AUDIOPLAYER_STARTED = 16384, INCOGNITO = 32768, }; mutable Mutex mLock; Mutex mMiscStateLock; OMXClient mClient; TimedEventQueue mQueue; bool mQueueStarted; wp<MediaPlayerBase> mListener; sp<Surface> mSurface; sp<ANativeWindow> mNativeWindow; sp<MediaPlayerBase::AudioSink> mAudioSink; SystemTimeSource mSystemTimeSource; TimeSource *mTimeSource; String8 mUri; KeyedVector<String8, String8> mUriHeaders; sp<DataSource> mFileSource; sp<MediaSource> mVideoTrack; sp<MediaSource> mVideoSource; sp<AwesomeRenderer> mVideoRenderer; bool mVideoRendererIsPreview; sp<MediaSource> mAudioTrack; sp<MediaSource> mAudioSource; AudioPlayerBase *mAudioPlayer; int64_t mDurationUs; int32_t mDisplayWidth; int32_t mDisplayHeight; uint32_t mFlags; uint32_t mExtractorFlags; int64_t mTimeSourceDeltaUs; int64_t mVideoTimeUs; enum SeekType { NO_SEEK, SEEK, SEEK_VIDEO_ONLY }; SeekType mSeeking; bool mSeekNotificationSent; int64_t mSeekTimeUs; int64_t mBitrate; // total bitrate of the file (in bps) or -1 if unknown. bool mWatchForAudioSeekComplete; bool mWatchForAudioEOS; sp<TimedEventQueue::Event> mVideoEvent; bool mVideoEventPending; sp<TimedEventQueue::Event> mStreamDoneEvent; bool mStreamDoneEventPending; sp<TimedEventQueue::Event> mBufferingEvent; bool mBufferingEventPending; sp<TimedEventQueue::Event> mCheckAudioStatusEvent; bool mAudioStatusEventPending; sp<TimedEventQueue::Event> mVideoLagEvent; bool mVideoLagEventPending; sp<TimedEventQueue::Event> mAsyncPrepareEvent; Condition mPreparedCondition; bool mIsAsyncPrepare; status_t mPrepareResult; status_t mStreamDoneStatus; void postVideoEvent_l(int64_t delayUs = -1); void postBufferingEvent_l(); void postStreamDoneEvent_l(status_t status); void postCheckAudioStatusEvent_l(int64_t delayUs); void postVideoLagEvent_l(); status_t play_l(); MediaBuffer *mVideoBuffer; sp<HTTPBase> mConnectingDataSource; sp<NuCachedSource2> mCachedSource; DrmManagerClient *mDrmManagerClient; sp<DecryptHandle> mDecryptHandle; int64_t mLastVideoTimeUs; ARect mCropRect; int32_t mGivenWidth, mGivenHeight; status_t setDataSource_l( const char *uri, const KeyedVector<String8, String8> *headers = NULL); status_t setDataSource_l(const sp<DataSource> &dataSource); status_t setDataSource_l(const sp<MediaExtractor> &extractor); void reset_l(); status_t seekTo_l(int64_t timeUs); status_t pause_l(bool at_eos = false); void initRenderer_l(); void notifyVideoSize_l(); void seekAudioIfNecessary_l(); void cancelPlayerEvents(bool keepBufferingGoing = false); void setAudioSource(sp<MediaSource> source); status_t initAudioDecoder(); void setVideoSource(sp<MediaSource> source); status_t initVideoDecoder(uint32_t flags = 0); void onStreamDone(); void notifyListener_l(int msg, int ext1 = 0, int ext2 = 0); void onVideoEvent(); void onBufferingUpdate(); void onCheckAudioStatus(); void onPrepareAsyncEvent(); void abortPrepare(status_t err); void finishAsyncPrepare_l(); void onVideoLagUpdate(); bool getCachedDuration_l(int64_t *durationUs, bool *eos); status_t finishSetDataSource_l(); static bool ContinuePreparation(void *cookie); bool getBitrate(int64_t *bitrate); void finishSeekIfNecessary(int64_t videoTimeUs); void ensureCacheIsFetching_l(); status_t startAudioPlayer_l(); void shutdownVideoDecoder_l(); void setNativeWindow_l(const sp<ANativeWindow> &native); PreviewPlayerBase(const PreviewPlayerBase &); PreviewPlayerBase &operator=(const PreviewPlayerBase &); }; } // namespace android #endif // PREVIEW_PLAYER_BASE_H_
[ "pengcui@skyworth.com" ]
pengcui@skyworth.com
cc3728c86e01489c9e667784dcc04d531bd633ce
affa60abae8383cc3c3298c3ed14cc7091710179
/src/cuda/SiPixel_convertiti/CUDACore/device_unique_ptr.h
7a912322cc4381a64b2e778fb85f4d55c45feb5e
[ "Apache-2.0" ]
permissive
lauracappelli/pixeltrack-standalone-test-oneapi
40dfa08fa49d353bab280aaf0ab8023369202c0e
5832b6680ea0327f124afcfac801addbea458203
refs/heads/master
2022-12-22T04:01:27.280446
2020-09-17T16:05:51
2020-09-17T16:05:51
291,729,954
0
0
null
null
null
null
UTF-8
C++
false
false
4,259
h
#ifndef HeterogeneousCore_CUDAUtilities_interface_device_unique_ptr_h #define HeterogeneousCore_CUDAUtilities_interface_device_unique_ptr_h #include <memory> #include <functional> #include "allocate_device.h" #include "currentDevice.h" namespace cms { namespace cuda { namespace device { namespace impl { // Additional layer of types to distinguish from host::unique_ptr class DeviceDeleter { public: DeviceDeleter() = default; // for edm::Wrapper DeviceDeleter(int device) : device_{device} {} void operator()(void *ptr) { if (device_ >= 0) { free_device(device_, ptr); } } private: int device_ = -1; }; } // namespace impl template <typename T> using unique_ptr = std::unique_ptr<T, impl::DeviceDeleter>; namespace impl { template <typename T> struct make_device_unique_selector { using non_array = cms::cuda::device::unique_ptr<T>; }; template <typename T> struct make_device_unique_selector<T[]> { using unbounded_array = cms::cuda::device::unique_ptr<T[]>; }; template <typename T, size_t N> struct make_device_unique_selector<T[N]> { struct bounded_array {}; }; } // namespace impl } // namespace device template <typename T> typename device::impl::make_device_unique_selector<T>::non_array make_device_unique(cudaStream_t stream) { static_assert(std::is_trivially_constructible<T>::value, "Allocating with non-trivial constructor on the device memory is not supported"); int dev = currentDevice(); void *mem = allocate_device(dev, sizeof(T), stream); return typename device::impl::make_device_unique_selector<T>::non_array{reinterpret_cast<T *>(mem), device::impl::DeviceDeleter{dev}}; } template <typename T> typename device::impl::make_device_unique_selector<T>::unbounded_array make_device_unique(size_t n, cudaStream_t stream) { using element_type = typename std::remove_extent<T>::type; static_assert(std::is_trivially_constructible<element_type>::value, "Allocating with non-trivial constructor on the device memory is not supported"); int dev = currentDevice(); void *mem = allocate_device(dev, n * sizeof(element_type), stream); return typename device::impl::make_device_unique_selector<T>::unbounded_array{ reinterpret_cast<element_type *>(mem), device::impl::DeviceDeleter{dev}}; } template <typename T, typename... Args> typename device::impl::make_device_unique_selector<T>::bounded_array make_device_unique(Args &&...) = delete; // No check for the trivial constructor, make it clear in the interface template <typename T> typename device::impl::make_device_unique_selector<T>::non_array make_device_unique_uninitialized( cudaStream_t stream) { int dev = currentDevice(); void *mem = allocate_device(dev, sizeof(T), stream); return typename device::impl::make_device_unique_selector<T>::non_array{reinterpret_cast<T *>(mem), device::impl::DeviceDeleter{dev}}; } template <typename T> typename device::impl::make_device_unique_selector<T>::unbounded_array make_device_unique_uninitialized( size_t n, cudaStream_t stream) { using element_type = typename std::remove_extent<T>::type; int dev = currentDevice(); void *mem = allocate_device(dev, n * sizeof(element_type), stream); return typename device::impl::make_device_unique_selector<T>::unbounded_array{ reinterpret_cast<element_type *>(mem), device::impl::DeviceDeleter{dev}}; } template <typename T, typename... Args> typename device::impl::make_device_unique_selector<T>::bounded_array make_device_unique_uninitialized(Args &&...) = delete; } // namespace cuda } // namespace cms #endif
[ "viola.cavallini@student.unife.it" ]
viola.cavallini@student.unife.it
3e833f3f3e14d20685d53a245cafdaaa8fae6b40
89c7a227f8b3bcf56a5219bc3ed1ecf0e522aa77
/src/solenoid.cpp
1f3572904fb140215861324a7b9eff1661f8c3e8
[ "MIT" ]
permissive
aryan-gupta/libbluepill
65f64a7af20a4e8753a577048d2abe51c65c1221
aefa7a83ea566e392b3e59945b13564fd112959a
refs/heads/master
2021-03-13T20:58:01.231083
2020-03-12T00:59:56
2020-03-12T00:59:56
246,711,818
1
0
null
null
null
null
UTF-8
C++
false
false
718
cpp
#include <libopencm3/stm32/rcc.h> #include <libopencm3/stm32/gpio.h> #include "solenoid.hpp" bool Solenoid::SETUP = false; Solenoid::Solenoid() { if (!SETUP) { gpio_solenoids_setup(); SETUP = true; } } void Solenoid::gpio_solenoids_setup() { rcc_periph_clock_enable(RCC_GPIOA); rcc_periph_clock_enable(RCC_GPIOB); gpio_set_mode( GPIOA, GPIO_MODE_OUTPUT_2_MHZ, GPIO_CNF_OUTPUT_PUSHPULL, GPIO11 | GPIO12 | GPIO15 ); gpio_set_mode( GPIOB, GPIO_MODE_OUTPUT_2_MHZ, GPIO_CNF_OUTPUT_PUSHPULL, GPIO3 | GPIO4 | GPIO5 ); } void Solenoid::set_high(mask_t mask) { gpio_toggle(GPIOB, GPIO3 | GPIO4 | GPIO5); } void Solenoid::set_low(mask_t mask) { gpio_toggle(GPIOB, GPIO3 | GPIO4 | GPIO5); }
[ "kuantum.freak@gmail.com" ]
kuantum.freak@gmail.com
2395eb12fbd63705175db90dee011d61744591e4
5169bb455d3c8d97bbda4f86f0b6b8e83334d126
/iptables_nettraffic/IPAddrInterFace.cpp
0f69e6e7201cd8dfc423dc5d6d94c17af3d593b8
[]
no_license
licaibiao/tcp_ip_network
2715175244c72882cf3ee8578b25d57f68a3184b
2a9f111b95d46e8f9cdbcb6445018455677c5068
refs/heads/master
2020-09-24T18:22:02.662142
2020-01-10T05:48:48
2020-01-10T05:48:48
225,815,770
3
5
null
null
null
null
GB18030
C++
false
false
3,440
cpp
/************************************************************ *Copyright (C), 2017-2027,lcb0281at163.com lcb0281atgmail.com *FileName: IPAddrInterFace.cpp *Date: 2019-06-22 *Author: Caibiao Lee *Version: V1.0 *Description:IP地址设置和获取模块,注意管道的数据收发规则 *History: ***********************************************************/ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <fcntl.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include "IPAddrInterFace.h" /************************************************* Function: IPAddWriteToPipe Description: 将IP地址写入管道中。 Input: u32IPAddr output:none Return:0 成功,非0,失败 Others:注意命名管道的读写规则 1.以非阻塞只写方式打开时,在多进程中同时写入数据,注意写入的原子性。 2.以非阻塞只写方式打开时,如果没有一个进程在读管道,打开会失败。 3.以非阻塞只写方式打开时,如果所有读管道进程关闭,写进程会收到SIGPIPE信号 如果写进程不对SIGPIPE信号进行处理,会导致写进程退出。 Author: Caibiao Lee Date: 2019.06.21 *************************************************/ static int IPAddWriteToPipe(unsigned int u32IPAddr) { int l_s32Ret = 0; int l_s32PipeFd = -1; int l_s32SendCount = 3; char l_arrs8Buffer[32] = {0}; IP_ADDR_NUM_S l_stIpAddr = {0}; /**判断管道是否存在**/ if(access(PIPE_NAME, F_OK) == -1) { printf ("Create the fifo pipe.\n"); l_s32Ret = mkfifo(PIPE_NAME, 0777); if(l_s32Ret != 0) { fprintf(stderr, "Could not create fifo %s\n", PIPE_NAME); return l_s32Ret; } } /**以非阻塞的方式去打开管道**/ l_s32PipeFd = open(PIPE_NAME, O_NONBLOCK|O_WRONLY); if(l_s32PipeFd !=-1) { l_stIpAddr.u8StartFlag = IP_START_FLAG; l_stIpAddr.u8EndFlag = IP_END_FLAG; l_stIpAddr.u32IPAddrNum = u32IPAddr; memcpy(l_arrs8Buffer,&l_stIpAddr,sizeof(IP_ADDR_NUM_S)); l_s32Ret = write(l_s32PipeFd, l_arrs8Buffer, sizeof(IP_ADDR_NUM_S)); if(l_s32Ret == -1) { while((l_s32SendCount--)>0) { sleep(1); if(-1 != write(l_s32PipeFd, l_arrs8Buffer, sizeof(IP_ADDR_NUM_S))) { l_s32Ret = 0; break; }else { l_s32Ret = -1; } } } } else { printf("open pipe errror !\n"); l_s32Ret = -1; } close(l_s32PipeFd); return l_s32Ret; } /************************************************* Function: lcb_connect Description: 重新封装connet函数,与connect函数的应用 完全一致 Input: connect 系统函数的返回值 Return: Others: 在这个函数中,将IP地址的十进制数值写入到管道中 通过wsd_GetIpAddr接口获取IP值,以实现去耦合及进程间 通行 Author: Caibiao Lee Date: 2019.06.21 *************************************************/ int wsd_connect(int sockfd, const struct sockaddr *addr,socklen_t addrlen) { int l_s32Ret = 0; unsigned int l_u32IpAddr = 0; struct sockaddr_in *l_stAddrIn = NULL; l_s32Ret = connect(sockfd,addr,addrlen); l_stAddrIn = (struct sockaddr_in *)addr; l_u32IpAddr = l_stAddrIn->sin_addr.s_addr; IPAddWriteToPipe(l_u32IpAddr); return l_s32Ret; }
[ "lcb0281@163.com" ]
lcb0281@163.com
8fe99ffc1d99152da9e074c2e076ab017bb2ce15
a34fe1a599b010d5e3f75a6f7838c8ecbf998a74
/boost/wave/cpp_throw.hpp
7518cde5d21e5e4d7a097b4f04503be2d7986b5a
[]
no_license
flmello/4thArticleIntel
78652a9957c507beb4b7be6d8560076211134c0c
2c204799553a0ca85b6baf1a1ff9876254fd4800
refs/heads/master
2021-08-23T03:45:51.554811
2017-12-03T01:32:27
2017-12-03T01:32:27
112,890,564
0
0
null
null
null
null
UTF-8
C++
false
false
9,808
hpp
/*============================================================================= Boost.Wave: A Standard compliant C++ preprocessor library http://www.boost.org/ Copyright (c) 2001-2008 Hartmut Kaiser. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #if !defined(BOOST_WAVE_CPP_THROW_HPP_INCLUDED) #define BOOST_WAVE_CPP_THROW_HPP_INCLUDED #include <string> #include <boost/throw_exception.hpp> /////////////////////////////////////////////////////////////////////////////// // helper macro for throwing exceptions #if !defined(BOOST_WAVE_THROW) #ifdef BOOST_NO_STRINGSTREAM #include <strstream> #define BOOST_WAVE_THROW(cls, code, msg, act_pos) \ { \ using namespace boost::wave; \ std::strstream stream; \ stream << cls::severity_text(cls::code) << ": " \ << cls::error_text(cls::code); \ if ((msg)[0] != 0) stream << ": " << (msg); \ stream << std::ends; \ std::string throwmsg = stream.str(); stream.freeze(false); \ boost::throw_exception(cls(throwmsg.c_str(), cls::code, \ (act_pos).get_line(), (act_pos).get_column(), \ (act_pos).get_file().c_str())); \ } \ /**/ #define BOOST_WAVE_THROW_CTX(ctx, cls, code, msg, act_pos) \ { \ using namespace boost::wave; \ std::strstream stream; \ stream << cls::severity_text(cls::code) << ": " \ << cls::error_text(cls::code); \ if ((msg)[0] != 0) stream << ": " << (msg); \ stream << std::ends; \ std::string throwmsg = stream.str(); stream.freeze(false); \ ctx.get_hooks().throw_exception(ctx.derived(), cls(throwmsg.c_str(), \ cls::code, (act_pos).get_line(), (act_pos).get_column(), \ (act_pos).get_file().c_str())); \ } \ /**/ #else #include <sstream> #define BOOST_WAVE_THROW(cls, code, msg, act_pos) \ { \ using namespace boost::wave; \ std::stringstream stream; \ stream << cls::severity_text(cls::code) << ": " \ << cls::error_text(cls::code); \ if ((msg)[0] != 0) stream << ": " << (msg); \ stream << std::ends; \ boost::throw_exception(cls(stream.str().c_str(), cls::code, \ (act_pos).get_line(), (act_pos).get_column(), \ (act_pos).get_file().c_str())); \ } \ /**/ #define BOOST_WAVE_THROW_CTX(ctx, cls, code, msg, act_pos) \ { \ using namespace boost::wave; \ std::stringstream stream; \ stream << cls::severity_text(cls::code) << ": " \ << cls::error_text(cls::code); \ if ((msg)[0] != 0) stream << ": " << (msg); \ stream << std::ends; \ ctx.get_hooks().throw_exception(ctx.derived(), \ cls(stream.str().c_str(), cls::code, (act_pos).get_line(), \ (act_pos).get_column(), (act_pos).get_file().c_str())); \ } \ /**/ #endif // BOOST_NO_STRINGSTREAM #endif // BOOST_WAVE_THROW /////////////////////////////////////////////////////////////////////////////// // helper macro for throwing exceptions with additional parameter #if !defined(BOOST_WAVE_THROW_NAME) #ifdef BOOST_NO_STRINGSTREAM #include <strstream> #define BOOST_WAVE_THROW_NAME_CTX(ctx, cls, code, msg, act_pos, name) \ { \ using namespace boost::wave; \ std::strstream stream; \ stream << cls::severity_text(cls::code) << ": " \ << cls::error_text(cls::code); \ if ((msg)[0] != 0) stream << ": " << (msg); \ stream << std::ends; \ std::string throwmsg = stream.str(); stream.freeze(false); \ ctx.get_hooks().throw_exception(ctx.derived(), cls(throwmsg.c_str(), \ cls::code, (act_pos).get_line(), (act_pos).get_column(), \ (act_pos).get_file().c_str(), (name))); \ } \ /**/ #else #include <sstream> #define BOOST_WAVE_THROW_NAME_CTX(ctx, cls, code, msg, act_pos, name) \ { \ using namespace boost::wave; \ std::stringstream stream; \ stream << cls::severity_text(cls::code) << ": " \ << cls::error_text(cls::code); \ if ((msg)[0] != 0) stream << ": " << (msg); \ stream << std::ends; \ ctx.get_hooks().throw_exception(ctx.derived(), \ cls(stream.str().c_str(), cls::code, (act_pos).get_line(), \ (act_pos).get_column(), (act_pos).get_file().c_str(), (name))); \ } \ /**/ #endif // BOOST_NO_STRINGSTREAM #endif // BOOST_WAVE_THROW_NAME /////////////////////////////////////////////////////////////////////////////// // helper macro for throwing exceptions with additional parameter #if !defined(BOOST_WAVE_THROW_VAR) #ifdef BOOST_NO_STRINGSTREAM #include <strstream> #define BOOST_WAVE_THROW_VAR_CTX(ctx, cls, code, msg, act_pos) \ { \ using namespace boost::wave; \ std::strstream stream; \ stream << cls::severity_text(code) << ": " \ << cls::error_text(code); \ if ((msg)[0] != 0) stream << ": " << (msg); \ stream << std::ends; \ std::string throwmsg = stream.str(); stream.freeze(false); \ ctx.get_hooks().throw_exception(ctx.derived(), cls(throwmsg.c_str(), \ code, (act_pos).get_line(), (act_pos).get_column(), \ (act_pos).get_file().c_str())); \ } \ /**/ #else #include <sstream> #define BOOST_WAVE_THROW_VAR_CTX(ctx, cls, code, msg, act_pos) \ { \ using namespace boost::wave; \ std::stringstream stream; \ stream << cls::severity_text(code) << ": " \ << cls::error_text(code); \ if ((msg)[0] != 0) stream << ": " << (msg); \ stream << std::ends; \ ctx.get_hooks().throw_exception(ctx.derived(), \ cls(stream.str().c_str(), code, (act_pos).get_line(), \ (act_pos).get_column(), (act_pos).get_file().c_str())); \ } \ /**/ #endif // BOOST_NO_STRINGSTREAM #endif // BOOST_WAVE_THROW_VAR #endif // !defined(BOOST_WAVE_CPP_THROW_HPP_INCLUDED)
[ "flavioluis.mello@gmail.com" ]
flavioluis.mello@gmail.com
b109f9b58e3d3e708cd6caef8f3f687b463487c1
fa183501ff61f146da2080f191f6c35a5d83ebf5
/rwmutex.hh
10560965c0cfe05003244fd89dc0524db9da1ec3
[]
no_license
jiazhanfeng1989/unitity
52da2e8670379e52d3a26193cf6bff8f61e862d7
d09c6d36aa17310d99b8aadaf715225ce0b5376b
refs/heads/master
2021-08-05T03:53:40.194113
2020-05-20T05:33:59
2020-05-20T05:33:59
176,510,812
0
0
null
null
null
null
UTF-8
C++
false
false
1,973
hh
#ifndef __WRITE_FIRST_RW_LOCK_H #define __WRITE_FIRST_RW_LOCK_H #include <mutex> #include <condition_variable> class RWLock { public: RWLock() = default; ~RWLock() = default; public: void lock_read() { std::unique_lock<std::mutex> ulk(counter_mutex); cond_r.wait(ulk, [=]()->bool {return write_cnt == 0; }); ++read_cnt; } void lock_write() { std::unique_lock<std::mutex> ulk(counter_mutex); ++write_cnt; cond_w.wait(ulk, [=]()->bool {return read_cnt == 0 && !inwriteflag; }); inwriteflag = true; } void release_read() { std::unique_lock<std::mutex> ulk(counter_mutex); if (--read_cnt == 0 && write_cnt > 0) { cond_w.notify_one(); } } void release_write() { std::unique_lock<std::mutex> ulk(counter_mutex); if (--write_cnt == 0) { cond_r.notify_all(); } else { cond_w.notify_one(); } inwriteflag = false; } private: volatile size_t read_cnt{ 0 }; volatile size_t write_cnt{ 0 }; volatile bool inwriteflag{ false }; std::mutex counter_mutex; std::condition_variable cond_w; std::condition_variable cond_r; }; template <typename _RWLockable> class unique_writeguard { public: explicit unique_writeguard(_RWLockable &rw_lockable) : rw_lockable_(rw_lockable) { rw_lockable_.lock_write(); } ~unique_writeguard() { rw_lockable_.release_write(); } private: unique_writeguard() = delete; unique_writeguard(const unique_writeguard&) = delete; unique_writeguard& operator=(const unique_writeguard&) = delete; private: _RWLockable &rw_lockable_; }; template <typename _RWLockable> class unique_readguard { public: explicit unique_readguard(_RWLockable &rw_lockable) : rw_lockable_(rw_lockable) { rw_lockable_.lock_read(); } ~unique_readguard() { rw_lockable_.release_read(); } private: unique_readguard() = delete; unique_readguard(const unique_readguard&) = delete; unique_readguard& operator=(const unique_readguard&) = delete; private: _RWLockable &rw_lockable_; }; #endif
[ "jiazhanfeng1989@126.com" ]
jiazhanfeng1989@126.com
03b8468441460ee2ddbba145b1e151f6902f45d2
67baab02cfda6c54a287d63d0874824cf15f3ba6
/atcoder/sumitrust2019f.cpp
bbe7a3e58d1c8dc20bd9e739792df0819b1342d2
[ "MIT" ]
permissive
sogapalag/problems
a14eedd8cfcdb52661479c8c90e08737aaeeb32b
0ea7d65448e1177f8b3f81124a82d187980d659c
refs/heads/master
2021-01-12T17:49:52.007234
2020-08-18T14:51:40
2020-08-18T14:51:40
71,629,601
1
0
null
null
null
null
UTF-8
C++
false
false
1,145
cpp
#include <bits/stdc++.h> using namespace std; using ll=long long; void solve() { ll T1, T2; ll A1, A2; ll B1, B2; cin >> T1 >> T2; cin >> A1 >> A2; cin >> B1 >> B2; ll SA = A1*T1 + A2*T2; ll SB = B1*T1 + B2*T2; if (SA == SB) { cout << "infinity"; return; } if (SA > SB) { swap(A1, B1); swap(A2, B2); swap(SA, SB); } ll res = 0; {// every A catch B, correspoding B catch back, since SB > SA // since t=0 not counted, so 2*k+1 // but if % = 0, res--, since A catch B after dt=0, B catch A. ll D = A1 - B1; //cout << A1 << "\n"; if (D > 0) { res += D*T1/(SB-SA); res *= 2; res++; if ((D*T1) % (SB-SA) == 0) res--; } } //{ // ll D = A2 - B2; // ll X = T2 * D - (B1*T1 - A1*T1); // //cout << X << "\n"; // if (X > 0) { // res += X / (SB-SA); // //cout << res << "\n"; // } //} cout << res; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); solve(); cout << endl; }
[ "yan-zp@foxmail.com" ]
yan-zp@foxmail.com
99a3e1b9ad2f0387896f5e233a00754ae61dce09
bb41b9c0c26c71c290965d2ffdb46475bc9de27a
/notionsDeBase/bonjour3/main.cpp
fde725a8b784ccd522a62f42fa42eac04698b746
[]
no_license
laganiere/programs
ca457c3371099b761921f39ca314e74f588d8b62
371f339bb9a550f2f39942d8081e78c328df1bb0
refs/heads/master
2021-03-12T23:21:57.936026
2015-11-24T20:46:28
2015-11-24T20:46:28
5,452,171
2
3
null
null
null
null
UTF-8
C++
false
false
341
cpp
#include <iostream> #include <fstream> using namespace std; // argc - # d'arguments spécifiés // char* - chaine de caractères // argv - tableau de chain de caractères int main(int argc, char **argv) { cout << "Bonjour"; for (int i = 1; i < argc; i++) cout << " " << argv[i]; cout << "!" << endl; return 0; }
[ "robert@laganiere.name" ]
robert@laganiere.name
cc11ac13ab5215c6b51984660476c5ffba522770
8dc84558f0058d90dfc4955e905dab1b22d12c08
/third_party/blink/renderer/core/css/properties/shorthands/flex_custom.cc
0ed2a6b08b03d35007b43ec3d92c51892b53fd49
[ "LGPL-2.0-only", "BSD-2-Clause", "LGPL-2.1-only", "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
meniossin/src
42a95cc6c4a9c71d43d62bc4311224ca1fd61e03
44f73f7e76119e5ab415d4593ac66485e65d700a
refs/heads/master
2022-12-16T20:17:03.747113
2020-09-03T10:43:12
2020-09-03T10:43:12
263,710,168
1
0
BSD-3-Clause
2020-05-13T18:20:09
2020-05-13T18:20:08
null
UTF-8
C++
false
false
4,093
cc
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/core/css/properties/shorthands/flex.h" #include "third_party/blink/renderer/core/css/css_identifier_value.h" #include "third_party/blink/renderer/core/css/parser/css_parser_context.h" #include "third_party/blink/renderer/core/css/parser/css_parser_local_context.h" #include "third_party/blink/renderer/core/css/parser/css_property_parser_helpers.h" #include "third_party/blink/renderer/core/css/properties/computed_style_utils.h" #include "third_party/blink/renderer/core/style/computed_style.h" #include "third_party/blink/renderer/core/style_property_shorthand.h" namespace blink { namespace CSSShorthand { bool Flex::ParseShorthand(bool important, CSSParserTokenRange& range, const CSSParserContext& context, const CSSParserLocalContext&, HeapVector<CSSPropertyValue, 256>& properties) const { static const double kUnsetValue = -1; double flex_grow = kUnsetValue; double flex_shrink = kUnsetValue; CSSValue* flex_basis = nullptr; if (range.Peek().Id() == CSSValueNone) { flex_grow = 0; flex_shrink = 0; flex_basis = CSSIdentifierValue::Create(CSSValueAuto); range.ConsumeIncludingWhitespace(); } else { unsigned index = 0; while (!range.AtEnd() && index++ < 3) { double num; if (CSSPropertyParserHelpers::ConsumeNumberRaw(range, num)) { if (num < 0) return false; if (flex_grow == kUnsetValue) { flex_grow = num; } else if (flex_shrink == kUnsetValue) { flex_shrink = num; } else if (!num) { // flex only allows a basis of 0 (sans units) if // flex-grow and flex-shrink values have already been // set. flex_basis = CSSPrimitiveValue::Create( 0, CSSPrimitiveValue::UnitType::kPixels); } else { return false; } } else if (!flex_basis) { if (range.Peek().Id() == CSSValueAuto) flex_basis = CSSPropertyParserHelpers::ConsumeIdent(range); if (!flex_basis) { flex_basis = CSSPropertyParserHelpers::ConsumeLengthOrPercent( range, context.Mode(), kValueRangeNonNegative); } if (index == 2 && !range.AtEnd()) return false; } } if (index == 0) return false; if (flex_grow == kUnsetValue) flex_grow = 1; if (flex_shrink == kUnsetValue) flex_shrink = 1; if (!flex_basis) { flex_basis = CSSPrimitiveValue::Create( 0, CSSPrimitiveValue::UnitType::kPercentage); } } if (!range.AtEnd()) return false; CSSPropertyParserHelpers::AddProperty( CSSPropertyFlexGrow, CSSPropertyFlex, *CSSPrimitiveValue::Create(clampTo<float>(flex_grow), CSSPrimitiveValue::UnitType::kNumber), important, CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties); CSSPropertyParserHelpers::AddProperty( CSSPropertyFlexShrink, CSSPropertyFlex, *CSSPrimitiveValue::Create(clampTo<float>(flex_shrink), CSSPrimitiveValue::UnitType::kNumber), important, CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties); CSSPropertyParserHelpers::AddProperty( CSSPropertyFlexBasis, CSSPropertyFlex, *flex_basis, important, CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties); return true; } const CSSValue* Flex::CSSValueFromComputedStyleInternal( const ComputedStyle& style, const SVGComputedStyle&, const LayoutObject* layout_object, Node* styled_node, bool allow_visited_style) const { return ComputedStyleUtils::ValuesForShorthandProperty( flexShorthand(), style, layout_object, styled_node, allow_visited_style); } } // namespace CSSShorthand } // namespace blink
[ "arnaud@geometry.ee" ]
arnaud@geometry.ee
4260f798d068f948c5a032604e8157689f7a4d27
0babdc2364b3b96b1bedccb8f2bc3e22acddadd9
/parallelisme/TP_5/src/julia_mpi_simple.cpp
9290c3bba5aeaa829ba5cfb8de5675f75cfea644
[]
no_license
Joao-Quinta/Uni3eme
7cd5c87192b2484b7e713a3085d263eeb4568b3f
5e659f0cab975cfdff4c5d873831d757361b6924
refs/heads/main
2023-04-15T10:48:00.517648
2021-05-06T01:00:00
2021-05-06T01:00:00
301,430,504
0
0
null
null
null
null
UTF-8
C++
false
false
4,337
cpp
#include "Array2D.hpp" #include <complex> #include <iostream> #include <fstream> #include <functional> #include <mpi.h> #include <vector> // calcul la suite z = z*z+c jusqu'a ce que ||z||>bound // retourne le nombre d'iterations jusqu'a divergence int divergence(std::complex<double> z0, std::complex<double> c, double bound, int imax){ std::complex<double> z = z0; for(int i=0; i<imax; i++){ if(norm(z) > bound) return i; z = z*z + c; } return imax; } // convertir une coordonnee du domaine discret en corrdonnee dans le domaine complexe std::complex<double> coord2cplx(const std::complex<double>& ll, const std::complex<double>& ur, int x, int y, Array2D<int>& d){ std::complex<double> res( ll.real() + x*(ur.real() - ll.real())/d.sizeX(), -(ll.imag() + y*(ur.imag() - ll.imag())/d.sizeY()) ); return res; } // calcul l'ensemble de julia void julia(const std::complex<double>& ll, const std::complex<double>& ur, const std::complex<double>& c, int imax, Array2D<int>& d,int dimYTask,int startY){ for(int y=0; y<dimYTask; y++){ for(int x=0; x<d.sizeX(); x++){ d(x, y + startY) = divergence( coord2cplx(ll, ur, x, y + startY, d), c, 2.0, imax ); } } } // ecrit le domaine sous forme d'image pgm void writePgm(Array2D<int>& d, int imax, std::string filename){ std::ofstream file; file.open (filename); file << "P2" << std::endl; file << d.sizeX() << " " << d.sizeY() << std::endl; file << imax << std::endl; for(int y=0; y<d.sizeY(); y++){ for(int x=0; x<d.sizeX(); x++){ file << d(x, y) << " "; } file << std::endl; } file.close(); } int main(int argc, char** argv){ // initialisation des parametres std::complex<double> lowerLeft (std::stof(argv[1]), std::stof(argv[2])); std::complex<double> upperRight (std::stof(argv[3]), std::stof(argv[4])); std::complex<double> c(std::stof(argv[5]), std::stof(argv[6])); int imax = std::stoi(argv[7]); int dimX = std::stoi(argv[8]); int dimY = std::stoi(argv[9]); Array2D<int>domain(dimX, dimY); std::string filename(argv[10]); int myRank, nProc; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &myRank); MPI_Comm_size(MPI_COMM_WORLD, &nProc); // repartition des donnees parmis les nProc int dimYloc = 0; int start = 0; std::vector<int> dimYlocs; std::vector<int> startAt; if(myRank == 0){ dimYlocs = std::vector<int>(nProc,dimY / nProc); int linesDistributed = (dimY / nProc) * nProc; int i = 0; while(linesDistributed != dimY){ dimYlocs[i]++; linesDistributed++; i = (i+1)%nProc; } } if(myRank == 0){ for (int i = 0; i < dimYlocs.size();i++){ if (i == 0){ startAt.push_back(0); } else{ startAt.push_back(startAt.back() + dimYlocs[i-1]); } } } // on scatter des donnes -> start dit aux tasks ou ils commencent, et dimYlocks le nb de lignes MPI_Scatter(dimYlocs.data(), 1, MPI_INT, &dimYloc, 1, MPI_INT, 0, MPI_COMM_WORLD); MPI_Scatter(startAt.data(), 1, MPI_INT, &start, 1, MPI_INT, 0, MPI_COMM_WORLD); //std::cout << "task : "<<myRank << " - mon Y : "<< dimYloc<< std::endl; Array2D<int>domainLocal(dimX, dimYloc); julia(lowerLeft, upperRight, c, imax, std::ref(domainLocal), dimYloc, start); if (myRank == 0){ for (int i = 0; i< dimYlocs.size(); i++){ dimYlocs[i] = dimYlocs[i] * dimX; startAt[i] = startAt[i] * dimX; } } //MPI_Gatherv(domainTask, dimX * dimYloc, MPI_INT,domain, dimYlocs.data(), startAt.data(), int, 0, MPI_COMM_WORLD); //writePgm(domain, imax, filename); // calcul de l'ensemble de julia // le domaine est passe via un std::ref, ici ce n'est pas utile // mais lors de la creation d'un thread, les objets sons passes par copie // std::ref permet de passer une reference au thread //julia(lowerLeft, upperRight, c, imax, std::ref(domain)); // ecriture du resultat dans un fichier if (myRank == 0){ writePgm(domain, imax, filename); } MPI_Finalize(); }
[ "qjoao.filipe@gmail.com" ]
qjoao.filipe@gmail.com
9a8d845d1787cc77c3e1136ade42a3190a8c5d50
f93238259313cf6122932a94aafe696a060f7896
/codeforces/1554/A.cpp
0b4622191f224f8c27a8a408cf908ed9ba38f6e0
[]
no_license
SubhashPadala/Codeforces
639efb57b74bd3eceb0745501fc61328ae4b4fb7
e9d42440b4a3fec6343cc32760ade23b092f3414
refs/heads/master
2023-08-08T04:44:54.402270
2021-07-19T07:58:00
2021-09-23T09:29:53
409,528,312
0
0
null
null
null
null
UTF-8
C++
false
false
2,950
cpp
// Problem ID - 1554A // _____ ___ __ // ___________(_)___ ________ ___ | / / // __ ___/__ / __ | / /_ __ `/__ | / / // _(__ ) _ / __ |/ / / /_/ / __ |/ / // /____/ /_/ _____/ \__,_/ _____/ // ________________________ ________ ______ ______ ______ _________ // ____ _/____ _/___ __/ ___ __ \______ ____ /______ ____ /_____ /________ _______ / // __ / __ / __ / __ /_/ /_ __ `/__ / _ __ `/__ //_/__ //_/_ __ `/_ __ / // __/ / __/ / _ / _ ____/ / /_/ / _ / / /_/ / _ ,< _ ,< / /_/ / / /_/ / // /___/ /___/ /_/ /_/ \__,_/ /_/ \__,_/ /_/|_| /_/|_| \__,_/ \__,_/ // #include "bits/stdc++.h" using namespace std; template<typename A, typename B> ostream& operator<<(ostream &os, const pair<A, B> &p) { return os << '(' << p.first << ", " << p.second << ')'; } template<typename T_container, typename T = typename enable_if<!is_same<T_container, string>::value, typename T_container::value_type>::type> ostream& operator<<(ostream &os, const T_container &v) { os << '{'; string sep; for (const T &x : v) os << sep << x, sep = ", "; return os << '}'; } void dbg_out() { cerr << endl; } template<typename Head, typename... Tail> void dbg_out(Head H, Tail... T) { cerr << ' ' << H; dbg_out(T...); } #ifdef KILL_BUG #define dbg(...) cerr << "(" << #__VA_ARGS__ << "):", dbg_out(__VA_ARGS__) #else #define dbg(...) #endif #define IOS ios::sync_with_stdio(false) #define TIE cin.tie(0);cout.tie(0) #define fi first #define se second #define pb push_back #define int long long #define mp make_pair #define ln "\n" #define case cout << "Case #" << cno << ": " << ln #define sz(x) ((int)(x).size()) #define prec(x) cout << fixed << showpoint; cout << setprecision(x) #define rep(i, a, b) for(int i = a; i < b; i++) #define all(x) (x).begin(), (x).end() #define rall(x) (x).rbegin(), (x).rend() using vi = vector<int>; using pii = pair<int, int>; using vp = vector<pii>; using vv = vector<vector<int>>; using mii = map<int, int>; const int MOD = (int)1e9 + 7; const int MOD2 = (int)998244353; const int inf = (int)1e18 + 1; int powb(int a, int n) { int res = 1; while (n > 0) { if (n & 1) res = res * a; a = a * a; n >>= 1; } return res; } int powb(int a, int n, int m) { a %= m; int res = 1; while (n > 0) { if (n & 1) res = (res * a) % m; a = (a * a) % m; n >>= 1; } return res; } void reset(){ } void runtestcase() { int n; cin>>n; vi ar(n); for(auto&i: ar) cin>>i; int ans = -inf; for(int i = 1; i < n; i++) { ans = max(ans, ar[i]*ar[i-1]); } cout << ans << ln; return; } int32_t main() { IOS; #ifndef KILL_BUG TIE; #endif int testcase = 1; cin >> testcase; rep(tc, 1, testcase+1) { dbg(tc); reset(); runtestcase(); } return 0; }
[ "111901038@smail.iitpkd.ac.in" ]
111901038@smail.iitpkd.ac.in
af9db5d3cef6536e3799e04c2047eb274ec90589
b726c743f126cc8dfc990f21380e0ac7ec777ef2
/src/Pipe.cpp
5d90b5f15c459836c601ac944dd9dcc4111eb53a
[]
no_license
9chu/Moe.UV
0998bbb7106911c83aaedf9269d227f1dd7a9e9e
1b8b97bec5c8395772b59bb65e270f2473de96ea
refs/heads/master
2020-04-28T14:15:45.301511
2019-04-27T02:29:54
2019-04-27T02:29:54
175,332,964
2
0
null
null
null
null
UTF-8
C++
false
false
2,787
cpp
/** * @file * @author chu * @date 2018/9/2 */ #include <Moe.UV/Pipe.hpp> #include "UV.inl" using namespace std; using namespace moe; using namespace UV; Pipe Pipe::Create(bool ipc) { MOE_UV_NEW(::uv_pipe_t); MOE_UV_CHECK(::uv_pipe_init(GetCurrentUVLoop(), object.get(), ipc ? 1 : 0)); return Pipe(CastHandle(std::move(object))); } struct UVConnectRequest { ::uv_connect_t Request; }; void Pipe::OnUVConnect(::uv_connect_t* request, int status)noexcept { UniquePooledObject<UVConnectRequest> owner; owner.reset(static_cast<UVConnectRequest*>(request->data)); auto handle = request->handle; MOE_UV_GET_SELF(Pipe); if (status != 0) // 通知错误发生 { MOE_UV_CATCH_ALL_BEGIN self->OnError(static_cast<uv_errno_t>(status)); MOE_UV_CATCH_ALL_END if (GetSelf<Pipe>(handle) == self) self->Close(); // 发生错误时直接关闭Socket } else { MOE_UV_CATCH_ALL_BEGIN self->OnConnect(); MOE_UV_CATCH_ALL_END } } Pipe::Pipe(Pipe&& org)noexcept : Stream(std::move(org)), m_pOnConnect(std::move(org.m_pOnConnect)) { } Pipe& Pipe::operator=(Pipe&& rhs)noexcept { Stream::operator=(std::move(rhs)); m_pOnConnect = std::move(rhs.m_pOnConnect); return *this; } void Pipe::Open(int fd) { MOE_UV_GET_HANDLE(::uv_pipe_t); MOE_UV_CHECK(::uv_pipe_open(handle, fd)); } void Pipe::Bind(const char* name) { MOE_UV_GET_HANDLE(::uv_pipe_t); MOE_UV_CHECK(::uv_pipe_bind(handle, name)); } void Pipe::Connect(const char* name) { MOE_UV_GET_HANDLE(::uv_pipe_t); MOE_UV_NEW(UVConnectRequest); // 发起连接操作 ::uv_pipe_connect(&object->Request, handle, name, OnUVConnect); // 释放所有权,交由UV管理 auto& req = object->Request; req.data = object.release(); } std::string Pipe::GetSockName() { MOE_UV_GET_HANDLE(::uv_pipe_t); string result; result.resize(256); size_t size = result.length(); int ret = ::uv_pipe_getsockname(handle, &result[0], &size); if (ret == UV_ENOBUFS) { result.resize(size); MOE_UV_CHECK(::uv_pipe_getsockname(handle, &result[0], &size)); } result.resize(std::strlen(result.c_str())); return result; } std::string Pipe::GetPeerName() { MOE_UV_GET_HANDLE(::uv_pipe_t); string result; result.resize(256); size_t size = result.length(); int ret = ::uv_pipe_getpeername(handle, &result[0], &size); if (ret == UV_ENOBUFS) { result.resize(size); MOE_UV_CHECK(::uv_pipe_getpeername(handle, &result[0], &size)); } result.resize(std::strlen(result.c_str())); return result; } void Pipe::OnConnect() { if (m_pOnConnect) m_pOnConnect(); }
[ "1871361697@qq.com" ]
1871361697@qq.com
77c829537a794a35193444923fbab6255297ee30
e7d7377b40fc431ef2cf8dfa259a611f6acc2c67
/SampleDump/Cpp/SDK/LightPropagationVolumeRuntime_classes.h
7a381982493b8be843462d369d3c7b64602f3eea
[]
no_license
liner0211/uSDK_Generator
ac90211e005c5f744e4f718cd5c8118aab3f8a18
9ef122944349d2bad7c0abe5b183534f5b189bd7
refs/heads/main
2023-09-02T16:37:22.932365
2021-10-31T17:38:03
2021-10-31T17:38:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,549
h
#pragma once // Name: Mordhau, Version: Patch23 /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Classes //--------------------------------------------------------------------------- // Class LightPropagationVolumeRuntime.LightPropagationVolumeBlendable // 0x0050 (FullSize[0x0078] - InheritedSize[0x0028]) class ULightPropagationVolumeBlendable : public UObject { public: unsigned char UnknownData_XWP5[0x8]; // 0x0028(0x0008) MISSED OFFSET (FIX SPACE BETWEEN PREVIOUS PROPERTY) struct FLightPropagationVolumeSettings Settings; // 0x0030(0x0040) (Edit, BlueprintVisible, Interp, NoDestructor, NativeAccessSpecifierPublic) float BlendWeight; // 0x0070(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData, Interp, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic) unsigned char UnknownData_A0KB[0x4]; // 0x0074(0x0004) MISSED OFFSET (PADDING) static UClass* StaticClass() { static UClass* ptr = UObject::FindClass("Class LightPropagationVolumeRuntime.LightPropagationVolumeBlendable"); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "talon_hq@outlook.com" ]
talon_hq@outlook.com
f634b796ee5b5965411f3028668bf5aed855e3cc
28c000caf6617ba2074e0f2a8fc936ccb8c01fb3
/poj/1634/5387758_WA.cpp
792ebe75e1472cd7a3ccf18c67de6ce2b9b8a780
[]
no_license
ATM006/acm_problem_code
f597fa31033fd663b14d74ad94cae3f7c1629b99
ac40d230cd450bcce60df801eb3b8ce9409dfaac
refs/heads/master
2020-08-31T21:34:00.707529
2014-01-23T05:30:42
2014-01-23T05:30:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,133
cpp
#include<stdio.h> #include<map> #include<iostream> using namespace std; int main() { int t; scanf("%d",&t); while(t--) { map<int,pair<int,int> >mp1; map<int,pair<int,int> >mp2; map<int,pair<int,int> >::iterator pos,r; int m,q,id,sal,h; cin>>m>>q; for(int i=0;i<m;i++) { cin>>id>>sal>>h; mp1[id]=make_pair(sal,h); mp2[h]=make_pair(id,sal); } for(int i=0;i<q;i++) { int num=0,flag=0; cin>>id; pos=mp1.find(id); h=pos->second.second; pos=mp2.find(h); sal=pos->second.second; for(r=pos;r!=mp2.end();r++) { if(r->second.second>sal) { cout<<r->second.first<<" "; flag=1;break; } } if(!flag)cout<<0<<" "; for(r=mp2.begin();r!=pos;r++) if(r->second.second<sal)num++; cout<<num<<endl; } } return 0; }
[ "wangjunyong@doodlemobile.com" ]
wangjunyong@doodlemobile.com
707337104fb1c385c1a002dba5671f5feb983173
36466c39d3ae94c2f936d4fdfe0fd4b034bbfa80
/3rdparty/ps-lite/libzmq-master/perf/benchmark_radix_tree.cpp
a69f37762b467b2a94a526c420e6bd320ce827d2
[ "Apache-2.0", "Intel", "LicenseRef-scancode-unknown-license-reference", "BSL-1.0", "MIT", "BSD-2-Clause", "Zlib", "NCSA", "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "BSD-2-Clause-Views", "LGPL-3.0-only", "LicenseRef-scancode-zeromq-exception-lgpl-3.0", "LGPL-2.0-or-later", "LGPL-...
permissive
zhouhuaman/dgt
ccc674dc6abb055eeb5b88eaa0177de3a051b362
a1df50efa3b635c20ddaa6bc5068e5f7bb863b5e
refs/heads/master
2022-11-27T21:53:05.980980
2020-01-13T09:33:14
2020-01-13T09:33:14
233,558,790
1
2
Apache-2.0
2022-11-23T15:05:17
2020-01-13T09:29:56
C++
UTF-8
C++
false
false
4,396
cpp
/* Copyright (c) 2018 Contributors as noted in the AUTHORS file This file is part of libzmq, the ZeroMQ core engine in C++. libzmq is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. As a special exception, the Contributors give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you must extend this exception to your version of the library. libzmq 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/>. */ #if __cplusplus >= 201103L #include "radix_tree.hpp" #include "trie.hpp" #include <chrono> #include <cstddef> #include <cstdio> #include <random> #include <ratio> #include <vector> const std::size_t nkeys = 10000; const std::size_t nqueries = 1000000; const std::size_t warmup_runs = 10; const std::size_t samples = 10; const std::size_t key_length = 20; const char *chars = "abcdefghijklmnopqrstuvwxyz0123456789"; const int chars_len = 36; template <class T> void benchmark_lookup (T &t, std::vector<unsigned char *> &input_set, std::vector<unsigned char *> &queries) { using namespace std::chrono; std::vector<duration<long, std::nano>> samples_vec; samples_vec.reserve (samples); for (std::size_t run = 0; run < warmup_runs; ++run) { for (auto &query : queries) t.check (query, key_length); } for (std::size_t run = 0; run < samples; ++run) { duration<long, std::nano> interval (0); for (auto &query : queries) { auto start = steady_clock::now (); t.check (query, key_length); auto end = steady_clock::now (); interval += end - start; } samples_vec.push_back (interval / queries.size ()); } std::size_t sum = 0; for (const auto &sample : samples_vec) sum += sample.count (); std::printf ("Average lookup time = %.1lf ns\n", static_cast<double> (sum) / samples); } int main () { // Generate input set. std::minstd_rand rng (123456789); std::vector<unsigned char *> input_set; std::vector<unsigned char *> queries; input_set.reserve (nkeys); queries.reserve (nqueries); for (std::size_t i = 0; i < nkeys; ++i) { unsigned char *key = new unsigned char[key_length]; for (std::size_t j = 0; j < key_length; j++) key[j] = static_cast<unsigned char> (chars[rng () % chars_len]); input_set.emplace_back (key); } for (std::size_t i = 0; i < nqueries; ++i) queries.push_back (input_set[rng () % nkeys]); // Initialize both data structures. // // Keeping initialization out of the benchmarking function helps // heaptrack detect peak memory consumption of the radix tree. zmq::trie_t trie; zmq::radix_tree radix_tree; for (auto &key : input_set) { trie.add (key, key_length); radix_tree.add (key, key_length); } // Create a benchmark. std::printf ("keys = %llu, queries = %llu, key size = %llu\n", static_cast<unsigned long long> (nkeys), static_cast<unsigned long long> (nqueries), static_cast<unsigned long long> (key_length)); std::puts ("[trie]"); benchmark_lookup (trie, input_set, queries); std::puts ("[radix_tree]"); benchmark_lookup (radix_tree, input_set, queries); for (auto &op : input_set) delete[] op; } #else int main () { } #endif
[ "zhouhuman@163.com" ]
zhouhuman@163.com
66b163ddf8111b3ea740e3f7e69ff6b3dc7b4959
6a1893aa22c4c63f6c5c1edacee41166e9a67263
/include/components/common/iconcomponent.hpp
b67d9746b0a0c51d8ee2d424d54930c5310a6c7d
[ "MIT" ]
permissive
srdgame/Teal
644413ed6c38376f875c40cb6aff9aa3dacf193a
468df0e038db79528362bbaf4ca5b7bca4fac6d8
refs/heads/master
2020-04-08T04:05:43.336399
2018-10-30T16:18:28
2018-10-30T16:18:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
488
hpp
// Copyright (C) 2018 Samy Bensaid // This file is part of the Teal project. // For conditions of distribution and use, see copyright notice in LICENSE #pragma once #ifndef ICONCOMPONENT_HPP #define ICONCOMPONENT_HPP #include <NDK/Component.hpp> #include <Nazara/Renderer/Texture.hpp> struct IconComponent : public Ndk::Component<IconComponent> { IconComponent() = default; Nz::TextureRef icon; static Ndk::ComponentIndex componentIndex; }; #endif // ICONCOMPONENT_HPP
[ "kiwimeteor6066@gmail.com" ]
kiwimeteor6066@gmail.com
e9022c6070e0caa6d7b75fb6543f8fb8a350679d
e97bedbc574ffc795fda788df7f098d58b1de56e
/src/main.cpp
2fd691b5da4fb5ccb9110278ed6bc9d11cc1a604
[]
no_license
captain13055/AP
3d83f2d1e8cd1e3157ec5ea6fd032183dc829cd4
65b13745d5944afb2699db93fe35ff231ecdbf7d
refs/heads/master
2020-03-27T12:42:33.512750
2016-05-29T04:18:42
2016-05-29T04:18:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
514
cpp
// // main.cpp // AP // // Created by yuya on 2015/07/30. // Copyright (c) 2015年 hy. All rights reserved. // #include "run.h" using namespace std; int main(int argc, const char * argv[]) { run(); return 0; } // // // // run.cpp -> main calculation // equation.cpp -> equations and runge-kutta // data.cpp -> read the magnetic field data. // For example, // from FFAG.txt which is output file from TOSCA // function.cpp -> many functions calculate the values you need, like a closed orbit.
[ "horitayuya.code@gmail.com" ]
horitayuya.code@gmail.com
c1635ee2f29cad783ca11f96bce20d3313cd16cf
8c634326b5980d6e2ec5fc732dd704491d692106
/IDEAS_APP/MixGauss.h
2040f9276b0b9759819650519f019afa833f8692
[ "MIT" ]
permissive
guanjue/IDEAS_2018
5eebabea2fc1a0613bfeb4f690aa3d13b0ee5c1f
5881efae8e42ce711766d021a88e2cfe309a1f52
refs/heads/master
2021-07-26T01:07:11.114501
2020-04-08T06:00:41
2020-04-08T06:00:41
137,529,160
6
5
null
2018-07-21T03:15:42
2018-06-15T20:27:46
R
UTF-8
C++
false
false
3,764
h
#pragma once #include "datastructure.h" class MixGauss { public: MixGauss(void); ~MixGauss(void); private: public: double *gausspara0; int clustersz0; double *gausspara, *gaussprior, *lambda; int gausssz, lambdasz, groupn, *groupcode, *coderevmap; bool lessoneUpdate; const gsl_rng_type *T; gsl_rng *gammar; int maxxmsz, *xmsz, maxxvsz, maxymsz, *ymsz, maxyvsz, maxyxsz, **xmap, **ymap, *mapspace; vector<int> ymap0, xmap0; int ymsz0, xmsz0, code0; int *neighbor; vector<double> markmean, marksd; float *preLP; public: int clustersz, totalN0; double minerr, maxerr, tmpprop[10000]; bool indc, nb; vector<vector<double> > modelparameter; public: void computeLP(float *ydata, float *xdata, int id, double priorW, double *lp); int* computeLP_subset(float *ydata, float *xdata, int id, int state, double priorW, double *lp); void addPara(int g, float *yy, float *xx, int id, float wt); void removePara(int g, float *yy, float *xx, int id, float wt); void getStateCount(double *cn); void getStatePrior(double *&ppp, int &step, double A, double B); void updateLambda(double priorW, bool updateprior = true, bool updateNeighbor = true); void initializePara(int clusterSZ, float **dataYP, float **dataXP, int totalN, int L, int maxysz, int *ysz, int **ymp, int maxxsz, int *xsz, int **xmp, double priorW, char const *parafile = NULL); void clearParameter(); void rearrangeParameter(int *remap, int newclustersz, float **dataYP, float **dataXP, int totalN, int L, double A); void outputParameter(char *fout, double priorW, vector<string> const &fy, vector<string> const &fx); void updateParameterPrior(double A); void simData(int n, int id, int g, float *yp); double splitmergeCluster(int type, float **dataYP, float **dataXP, int totalN, int L, float *states, bool *lapse, double priorW, int &mi, int &mj, int &tid, float const *wt); void imputeMissingTrack(int id, int st, int ed, float *yp, float *xp, float *yimp, float *ximp, float *states, double diag = 0, bool verbose = false);//double *stateprob); void loadGaussPrior0(char const *parafile, vector<string> const &fy, vector<string> const &fx); void imputeMissing2(MYDATA const &mydata, TENSORPARA const &tpara, float **dataYP, float **dataXP, double priorW, char const *fname, int gid, float const *wt); void preComputeLP(char const *fmixpara, vector<string> const &fy, vector<string> const &fx, float **dataYP, float **dataXP, int totalN, int L); private: double _dmvnorm(double *lambdap, float *yp, float *xp, int tymsz, int txmsz); void _getLambdaOne(double *ll, double *rr, double *tmpspace, double priorW, int i, int id); void _cholV(double const *A, int n, double *L); void _invL(double const *L, int n, double *iL, bool transpose); double _lgammaM(int q, double x); void _prepareGroupCode(int totalN); void _getMean(double const *pp, float *my, float *mx); void _gaussEM(double *pp, double *rr, double priorW, double *rr0); void _collapsedPrediction(double const *pp, double const *phi, int id, double *rt, double *tmpspace, int &misyn, int *misy, int &misxn, int *misx, int *map); void _XtX(double const *X, int rn, int cn, double *X2); void _AtB(double const *A, double const *B, int ca, int cb, int n, double *C); void _ABt(double const *A, double const *B, int ra, int rb, int n, double *C); void _AB(double const *A, double const *B, int ra, int cb, int n, double *C); void _updateVh(double *Q, int K, double A, double *V); void _getNeighbor(double priorW); void _loadGaussPrior_mix(char const *fmixpara, vector<string> const &fy, vector<string> const &fx, double *&prepara, vector<int> &state); void indDist(MYDATA const &mydata, TENSORPARA const &tpara, double *wt); };
[ "universe@Guanjues-MacBook-Pro.local" ]
universe@Guanjues-MacBook-Pro.local
53405406c0bb257f47f20101cfdc995f18aa9523
fc4e9d1cf1e7a46e6cd01077f2a57f071f4f1353
/proton-c/bindings/cpp/include/proton/proton_event.hpp
c809e55d93c6ef3ba6875f5fc3e3970c18a73b87
[ "Apache-2.0", "BSD-3-Clause" ]
permissive
bozzzzo/qpid-proton
9364750970127b321a799e842ce5581aa1367cab
16ebef3cbfabf1c789a3df14d48f7de9cd471133
refs/heads/master
2021-01-18T08:38:29.877503
2015-10-09T07:26:51
2015-10-09T07:26:51
31,703,959
0
0
null
2015-03-05T08:39:01
2015-03-05T08:38:58
Java
UTF-8
C++
false
false
9,455
hpp
#ifndef PROTON_CPP_PROTONEVENT_H #define PROTON_CPP_PROTONEVENT_H /* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ #include "proton/event.hpp" #include "proton/link.hpp" struct pn_event_t; namespace proton { class handler; class container; class connection; class container; /** Event information for a proton::proton_handler */ class proton_event : public event { public: ///@name Event types ///@{ /// The type of an event typedef int event_type; /** * Defined as a programming convenience. No event of this type will * ever be generated. */ PN_CPP_EXTERN static const event_type EVENT_NONE; /** * A reactor has been started. Events of this type point to the reactor. */ PN_CPP_EXTERN static const event_type REACTOR_INIT; /** * A reactor has no more events to process. Events of this type * point to the reactor. */ PN_CPP_EXTERN static const event_type REACTOR_QUIESCED; /** * A reactor has been stopped. Events of this type point to the reactor. */ PN_CPP_EXTERN static const event_type REACTOR_FINAL; /** * A timer event has occurred. */ PN_CPP_EXTERN static const event_type TIMER_TASK; /** * The connection has been created. This is the first event that * will ever be issued for a connection. Events of this type point * to the relevant connection. */ PN_CPP_EXTERN static const event_type CONNECTION_INIT; /** * The connection has been bound to a transport. This event is * issued when the transport::bind() is called. */ PN_CPP_EXTERN static const event_type CONNECTION_BOUND; /** * The connection has been unbound from its transport. This event is * issued when transport::unbind() is called. */ PN_CPP_EXTERN static const event_type CONNECTION_UNBOUND; /** * The local connection endpoint has been closed. Events of this * type point to the relevant connection. */ PN_CPP_EXTERN static const event_type CONNECTION_LOCAL_OPEN; /** * The remote endpoint has opened the connection. Events of this * type point to the relevant connection. */ PN_CPP_EXTERN static const event_type CONNECTION_REMOTE_OPEN; /** * The local connection endpoint has been closed. Events of this * type point to the relevant connection. */ PN_CPP_EXTERN static const event_type CONNECTION_LOCAL_CLOSE; /** * The remote endpoint has closed the connection. Events of this * type point to the relevant connection. */ PN_CPP_EXTERN static const event_type CONNECTION_REMOTE_CLOSE; /** * The connection has been freed and any outstanding processing has * been completed. This is the final event that will ever be issued * for a connection. */ PN_CPP_EXTERN static const event_type CONNECTION_FINAL; /** * The session has been created. This is the first event that will * ever be issued for a session. */ PN_CPP_EXTERN static const event_type SESSION_INIT; /** * The local session endpoint has been opened. Events of this type * point ot the relevant session. */ PN_CPP_EXTERN static const event_type SESSION_LOCAL_OPEN; /** * The remote endpoint has opened the session. Events of this type * point to the relevant session. */ PN_CPP_EXTERN static const event_type SESSION_REMOTE_OPEN; /** * The local session endpoint has been closed. Events of this type * point ot the relevant session. */ PN_CPP_EXTERN static const event_type SESSION_LOCAL_CLOSE; /** * The remote endpoint has closed the session. Events of this type * point to the relevant session. */ PN_CPP_EXTERN static const event_type SESSION_REMOTE_CLOSE; /** * The session has been freed and any outstanding processing has * been completed. This is the final event that will ever be issued * for a session. */ PN_CPP_EXTERN static const event_type SESSION_FINAL; /** * The link has been created. This is the first event that will ever * be issued for a link. */ PN_CPP_EXTERN static const event_type LINK_INIT; /** * The local link endpoint has been opened. Events of this type * point ot the relevant link. */ PN_CPP_EXTERN static const event_type LINK_LOCAL_OPEN; /** * The remote endpoint has opened the link. Events of this type * point to the relevant link. */ PN_CPP_EXTERN static const event_type LINK_REMOTE_OPEN; /** * The local link endpoint has been closed. Events of this type * point ot the relevant link. */ PN_CPP_EXTERN static const event_type LINK_LOCAL_CLOSE; /** * The remote endpoint has closed the link. Events of this type * point to the relevant link. */ PN_CPP_EXTERN static const event_type LINK_REMOTE_CLOSE; /** * The local link endpoint has been detached. Events of this type * point to the relevant link. */ PN_CPP_EXTERN static const event_type LINK_LOCAL_DETACH; /** * The remote endpoint has detached the link. Events of this type * point to the relevant link. */ PN_CPP_EXTERN static const event_type LINK_REMOTE_DETACH; /** * The flow control state for a link has changed. Events of this * type point to the relevant link. */ PN_CPP_EXTERN static const event_type LINK_FLOW; /** * The link has been freed and any outstanding processing has been * completed. This is the final event that will ever be issued for a * link. Events of this type point to the relevant link. */ PN_CPP_EXTERN static const event_type LINK_FINAL; /** * A delivery has been created or updated. Events of this type point * to the relevant delivery. */ PN_CPP_EXTERN static const event_type DELIVERY; /** * The transport has new data to read and/or write. Events of this * type point to the relevant transport. */ PN_CPP_EXTERN static const event_type TRANSPORT; /** * The transport has authenticated, if this is received by a server * the associated transport has authenticated an incoming connection * and transport::user() can be used to obtain the authenticated * user. */ PN_CPP_EXTERN static const event_type TRANSPORT_AUTHENTICATED; /** * Indicates that a transport error has occurred. Use * transport::condition() to access the details of the error * from the associated transport. */ PN_CPP_EXTERN static const event_type TRANSPORT_ERROR; /** * Indicates that the head of the transport has been closed. This * means the transport will never produce more bytes for output to * the network. Events of this type point to the relevant transport. */ PN_CPP_EXTERN static const event_type TRANSPORT_HEAD_CLOSED; /** * Indicates that the tail of the transport has been closed. This * means the transport will never be able to process more bytes from * the network. Events of this type point to the relevant transport. */ PN_CPP_EXTERN static const event_type TRANSPORT_TAIL_CLOSED; /** * Indicates that the both the head and tail of the transport are * closed. Events of this type point to the relevant transport. */ PN_CPP_EXTERN static const event_type TRANSPORT_CLOSED; PN_CPP_EXTERN static const event_type SELECTABLE_INIT; PN_CPP_EXTERN static const event_type SELECTABLE_UPDATED; PN_CPP_EXTERN static const event_type SELECTABLE_READABLE; PN_CPP_EXTERN static const event_type SELECTABLE_WRITABLE; PN_CPP_EXTERN static const event_type SELECTABLE_ERROR; PN_CPP_EXTERN static const event_type SELECTABLE_EXPIRED; PN_CPP_EXTERN static const event_type SELECTABLE_FINAL; ///@} virtual PN_CPP_EXTERN void dispatch(handler &h); virtual PN_CPP_EXTERN class container &container(); virtual PN_CPP_EXTERN class connection &connection(); virtual PN_CPP_EXTERN class sender& sender(); virtual PN_CPP_EXTERN class receiver& receiver(); virtual PN_CPP_EXTERN class link& link(); virtual PN_CPP_EXTERN class delivery& delivery(); /** Get type of event */ PN_CPP_EXTERN event_type type(); PN_CPP_EXTERN pn_event_t* pn_event(); protected: PN_CPP_EXTERN proton_event(pn_event_t *ce, proton_event::event_type t, class container &c); private: pn_event_t *pn_event_; event_type type_; class container &container_; }; } #endif /*!PROTON_CPP_PROTONEVENT_H*/
[ "aconway@redhat.com" ]
aconway@redhat.com
8bf6604b4d75e41825ef25dd8096dadf857faebf
986a2a1586b7fa0314c8fd076e978ce0bf149b23
/JustTest/VisualController.h
2c2149ab7927202e19117c4f12aee2a3b107524f
[]
no_license
OligerMan/JustTestEngine
8236aece891001e278631ef08ddbbcd3a54a422e
138856302edd878fc97391269bfebde6a8aaccdc
refs/heads/master
2020-04-02T17:08:54.523316
2018-12-04T08:08:40
2018-12-04T08:08:40
154,645,879
0
0
null
null
null
null
UTF-8
C++
false
false
4,008
h
#pragma once #include <iostream> #include "Map.h" #include "FileSearch.h" #include "Settings.h" #include <SFML\Graphics.hpp> #include <string> #include <iostream> class VisualController { std::vector<std::vector<std::vector<sf::Texture>>> texture_buffer; std::vector<std::vector<sf::Sprite>> sprite_buffer; bool is_active = true; void uploadTextures(std::string path) { if (settings.isSpriteDebugOutputEnabled()) { std::cout << " -- Sprites loading start -- " << std::endl; } std::vector<std::string> * object_names = getFileList(path); texture_buffer.resize((int)COUNT_OBJECT); for (int obj_cnt = 0; obj_cnt < object_names->size(); obj_cnt++) { if (settings.isSpriteDebugOutputEnabled()) { std::cout << "Object " << (*object_names)[obj_cnt] << " sprite loading" << std::endl; } //get animation set std::vector<std::string> * anim_set = getFileList(path + "\\" + (*object_names)[obj_cnt]); std::vector<std::vector<sf::Texture>> object_textures; texture_buffer[is_object_type_exists((*object_names)[obj_cnt])].resize((int)COUNT_ANIMATION); for (int anim_cnt = 0; anim_cnt < anim_set->size(); anim_cnt++) { if (settings.isSpriteDebugOutputEnabled()) { std::cout << " >> Animation " << (*anim_set)[anim_cnt] << " is loading" << std::endl; } //get sprites set std::vector<std::string> * textures_set = getFileList(path + "\\" + ((*object_names)[obj_cnt] + "\\" + (*anim_set)[anim_cnt])); std::vector<sf::Texture> animation(textures_set->size()); for (int i = 0; i < textures_set->size(); i++) { if (settings.isSpriteDebugOutputEnabled()) { std::cout << " >> Sprite " << (*textures_set)[i] << " is loading" << std::endl; } std::string sprite_path = (path + "\\" + ((*object_names)[obj_cnt] + "\\" + (*anim_set)[anim_cnt] + "\\" + (*textures_set)[i])).c_str(); animation[i].loadFromFile(sprite_path); } if (is_animation_type_exists((*anim_set)[anim_cnt]) != -1 && is_object_type_exists((*object_names)[obj_cnt]) != -1) { texture_buffer[is_object_type_exists((*object_names)[obj_cnt])][is_animation_type_exists((*anim_set)[anim_cnt])] = animation; } } } if (settings.isSpriteDebugOutputEnabled()) { std::cout << " -- Sprites loading completed -- " << std::endl << std::endl; } return; } void initSprites() { sprite_buffer.resize(texture_buffer.size()); for (int obj_cnt = 0; obj_cnt < texture_buffer.size(); obj_cnt++) { sprite_buffer[obj_cnt].resize(texture_buffer[obj_cnt].size()); for (int anim_cnt = 0; anim_cnt < texture_buffer[obj_cnt].size(); anim_cnt++) { if (texture_buffer[obj_cnt][anim_cnt].size() != 0) { sprite_buffer[obj_cnt][anim_cnt].setTexture(texture_buffer[obj_cnt][anim_cnt][0]); } } } } public: VisualController() { const std::string texture_path = "sprites"; uploadTextures(texture_path); initSprites(); } void setActive() { is_active = true; } bool isActive() { return is_active; } void drawObject(Object * object, sf::RenderWindow * window) { int obj_type = object->getObjectSpriteType(); int anim_type = object->getObjectAnimationType(); int frame_num = object->getFrameNumber(); Point position = object->getPosition(); Point origin = object->getOrigin(); double angle = object->getAngle(); sf::Sprite * sprite = &sprite_buffer[obj_type][anim_type]; sprite->setTexture(texture_buffer[obj_type][anim_type][frame_num % texture_buffer[obj_type][anim_type].size()]); sprite->setPosition(position.x, position.y); sprite->setRotation(angle); sprite->setOrigin(origin.x, origin.y); object->frameIncrement(); window->draw(*sprite); } bool processFrame(sf::RenderWindow * window, std::vector<std::vector<Object *>> * objects) { for (int layer = 0; layer < objects->size(); layer++) { for (int i = 0; i < (*objects)[layer].size(); i++) { Object * object = (*objects)[layer][i]; drawObject(object, window); } } return is_active; } };
[ "32018536+OligerMan@users.noreply.github.com" ]
32018536+OligerMan@users.noreply.github.com
375a483c2cb6aec0ea598aa859ac27030c2a07b7
b6120d50b43d97dc802028f4d225aa4a75c28526
/Day 03/ex01/main.cpp
91388fe9ff7f62ff8994af1a7ca47e8b6ac958c6
[]
no_license
aastefian/Piscine-CPP
b8eeb4ee7f98f38d950456dfc1002146072235a4
55cbd67e969fe1db9d6b1b465339edcb2efba88c
refs/heads/master
2020-03-30T13:01:14.492089
2019-03-07T11:22:12
2019-03-07T11:22:12
151,252,691
0
0
null
null
null
null
UTF-8
C++
false
false
1,408
cpp
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: svilau <svilau@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/10/01 11:13:38 by svilau #+# #+# */ /* Updated: 2018/10/05 12:50:20 by svilau ### ########.fr */ /* */ /* ************************************************************************** */ #include <iostream> #include "ScavTrap.class.hpp" #include "FragTrap.class.hpp" int main( void ) { ScavTrap hodor("Hodor"); FragTrap shorty("Shorty"); srand(time(NULL)); hodor.challengeNewComer("Shorty"); std::cout << std::endl; shorty.vaulthunter_dot_exe("Hodor"); std::cout << std::endl; hodor.takeDamage(105); std::cout << std::endl; shorty.takeDamage(105); std::cout << std::endl; hodor.beRepaired(2000); std::cout << std::endl; shorty.beRepaired(2000); std::cout << std::endl; return 0; }
[ "svilau@student.42.fr" ]
svilau@student.42.fr
8100906ae2070548a9ffe1bccda0596e4344ec57
f4db4250cb7cd32b8700db4de1ee23d3452c1596
/Practica/Volumenes Finitos/OpenFoam/Ejercicio3_Temperatura/0.265/U
f0417160146113ebfe3d9868c582f178d6891b89
[]
no_license
santichialvo/MecanicaComputacional
cc7e7af64542d7a6149a865ab0b16124db90a0d7
c7f63f6f39da1e7dcddfa4b0e83bb9179bdcff21
refs/heads/master
2021-01-10T04:00:05.616777
2015-12-08T02:45:23
2015-12-08T02:45:23
47,593,143
1
1
null
null
null
null
UTF-8
C++
false
false
40,547
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: 2.4.0 | | \\ / A nd | Web: www.OpenFOAM.org | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volVectorField; location "0.265"; object U; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 1 -1 0 0 0 0]; internalField nonuniform List<vector> 1600 ( (7.49477e-05 -7.44559e-05 0) (0.000159171 -4.8888e-05 0) (8.45007e-05 1.23101e-05 0) (-0.000169166 6.63763e-05 0) (-0.000570279 0.000106178 0) (-0.00107747 0.00013199 0) (-0.001661 0.000148842 0) (-0.0023016 0.000161721 0) (-0.00298972 0.000173939 0) (-0.00372161 0.000187002 0) (-0.00449507 0.000200898 0) (-0.00530563 0.00021446 0) (-0.00614382 0.000225716 0) (-0.00699329 0.000232184 0) (-0.00782987 0.000231128 0) (-0.00862152 0.000219803 0) (-0.00932916 0.000195737 0) (-0.00990849 0.000157114 0) (-0.010313 0.000103308 0) (-0.0104984 3.50511e-05 0) (-0.0104249 -4.67433e-05 0) (-0.010064 -0.000137107 0) (-0.00940452 -0.00022984 0) (-0.00845535 -0.000317506 0) (-0.00724816 -0.000391895 0) (-0.00583761 -0.000445049 0) (-0.00429878 -0.000470442 0) (-0.0027214 -0.000464093 0) (-0.00120148 -0.000425533 0) (0.00016694 -0.000358333 0) (0.00130159 -0.000268141 0) (0.00214196 -0.00016343 0) (0.00265354 -5.41144e-05 0) (0.00282946 5.07414e-05 0) (0.00269022 0.000142658 0) (0.00228289 0.000214025 0) (0.00168184 0.000254918 0) (0.000988817 0.000249637 0) (0.000345084 0.000174382 0) (2.82297e-05 2.88437e-05 0) (5.4342e-05 -0.000163978 0) (-3.63367e-05 3.49335e-05 0) (-0.000527589 0.000354279 0) (-0.00140339 0.000649396 0) (-0.00261027 0.000883663 0) (-0.00407816 0.00105613 0) (-0.00574584 0.00118332 0) (-0.00756956 0.00128383 0) (-0.00952168 0.00137104 0) (-0.0115841 0.00145108 0) (-0.0137402 0.00152301 0) (-0.0159676 0.00158009 0) (-0.0182322 0.0016114 0) (-0.0204844 0.00160353 0) (-0.0226578 0.00154221 0) (-0.0246698 0.00141406 0) (-0.0264243 0.00120828 0) (-0.0278171 0.000918588 0) (-0.0287435 0.00054496 0) (-0.0291091 9.48631e-05 0) (-0.0288336 -0.000416188 0) (-0.0278629 -0.000961439 0) (-0.0261847 -0.00150732 0) (-0.0238297 -0.00201462 0) (-0.0208757 -0.00244182 0) (-0.0174472 -0.00274971 0) (-0.0137099 -0.00290648 0) (-0.00985946 -0.00289246 0) (-0.00610677 -0.00270385 0) (-0.00265951 -0.00235463 0) (0.000295612 -0.0018737 0) (0.00261155 -0.00130231 0) (0.00419557 -0.000690351 0) (0.00501557 -8.93696e-05 0) (0.00510321 0.000450686 0) (0.00455394 0.000881362 0) (0.00352443 0.00115057 0) (0.00222534 0.00119478 0) (0.00094186 0.000936402 0) (0.00017303 0.000343684 0) (-1.65366e-05 -8.60841e-05 0) (-0.000419726 0.000539533 0) (-0.00148531 0.00134372 0) (-0.00309373 0.00208364 0) (-0.00515926 0.00268556 0) (-0.00759399 0.0031483 0) (-0.010319 0.00350326 0) (-0.0132758 0.00378729 0) (-0.016424 0.00402751 0) (-0.0197327 0.0042355 0) (-0.0231701 0.00440683 0) (-0.0266944 0.0045235 0) (-0.0302468 0.00455774 0) (-0.0337468 0.00447635 0) (-0.0370915 0.00424512 0) (-0.0401573 0.00383341 0) (-0.0428049 0.00321858 0) (-0.044888 0.00239036 0) (-0.0462633 0.00135454 0) (-0.0468036 0.000136162 0) (-0.0464053 -0.00121759 0) (-0.0450023 -0.00264196 0) (-0.0425842 -0.00405395 0) (-0.0391958 -0.00535911 0) (-0.0349429 -0.00645954 0) (-0.0299913 -0.00726363 0) (-0.0245608 -0.00769664 0) (-0.0189124 -0.00771091 0) (-0.0133314 -0.00729385 0) (-0.00810458 -0.00647216 0) (-0.00349688 -0.00531064 0) (0.000272806 -0.00390517 0) (0.00305298 -0.00237359 0) (0.00477444 -0.000844361 0) (0.00545673 0.000553475 0) (0.00520996 0.00169285 0) (0.00423077 0.00244612 0) (0.00278822 0.00267559 0) (0.00125008 0.00223176 0) (0.000255787 0.000994847 0) (-9.86035e-05 0.000229681 0) (-0.000872083 0.00156117 0) (-0.00260439 0.00303097 0) (-0.00502473 0.00434424 0) (-0.00800004 0.00541331 0) (-0.011423 0.00624755 0) (-0.0152019 0.00689913 0) (-0.01927 0.00742544 0) (-0.0235798 0.0078671 0) (-0.0280917 0.00823893 0) (-0.0327616 0.00852924 0) (-0.037531 0.00870396 0) (-0.042319 0.00871327 0) (-0.0470181 0.00849934 0) (-0.0514946 0.00800436 0) (-0.0555915 0.00717851 0) (-0.0591356 0.00598767 0) (-0.0619477 0.00442032 0) (-0.0638548 0.00249337 0) (-0.0647032 0.000256797 0) (-0.0643712 -0.00220456 0) (-0.0627793 -0.00477932 0) (-0.059908 -0.007325 0) (-0.0558028 -0.00968235 0) (-0.0505779 -0.0116871 0) (-0.0444178 -0.0131846 0) (-0.0375724 -0.0140463 0) (-0.0303457 -0.0141861 0) (-0.0230788 -0.0135735 0) (-0.0161257 -0.0122426 0) (-0.009825 -0.0102928 0) (-0.00446952 -0.00788101 0) (-0.000277825 -0.00520664 0) (0.00262811 -0.00249328 0) (0.00423604 2.88493e-05 0) (0.00464865 0.00213118 0) (0.00407755 0.00358951 0) (0.00282563 0.00417303 0) (0.0013161 0.00363787 0) (0.00027995 0.00173783 0) (-0.000184788 0.000806179 0) (-0.0013546 0.00315621 0) (-0.00380112 0.00547967 0) (-0.00708007 0.00748239 0) (-0.0109997 0.00909694 0) (-0.0154298 0.0103628 0) (-0.0202677 0.0113628 0) (-0.0254426 0.0121786 0) (-0.0309054 0.0128637 0) (-0.0366125 0.0134332 0) (-0.0425123 0.0138637 0) (-0.0485335 0.0141003 0) (-0.0545772 0.0140664 0) (-0.0605142 0.0136759 0) (-0.0661847 0.0128447 0) (-0.0714042 0.0115028 0) (-0.0759709 0.00960504 0) (-0.0796767 0.00714035 0) (-0.0823203 0.00413921 0) (-0.0837201 0.000678898 0) (-0.0837307 -0.00311585 0) (-0.0822479 -0.00708191 0) (-0.0792278 -0.011013 0) (-0.0746983 -0.0146798 0) (-0.0687621 -0.0178437 0) (-0.061602 -0.0202767 0) (-0.0534803 -0.0217831 0) (-0.0447309 -0.0222231 0) (-0.0357438 -0.0215335 0) (-0.0269407 -0.0197431 0) (-0.0187425 -0.0169787 0) (-0.0115312 -0.013458 0) (-0.00561129 -0.00947114 0) (-0.00117734 -0.00535374 0) (0.00170617 -0.00145873 0) (0.00311608 0.00186294 0) (0.00326474 0.00426812 0) (0.00247777 0.00541384 0) (0.00122002 0.00494285 0) (0.000271327 0.00246651 0) (-0.000271012 0.00164739 0) (-0.00184658 0.00534953 0) (-0.00502817 0.00872552 0) (-0.0091872 0.0115341 0) (-0.0140679 0.0137665 0) (-0.019516 0.0155166 0) (-0.0254192 0.0169118 0) (-0.0317069 0.0180633 0) (-0.038333 0.0190377 0) (-0.0452554 0.0198474 0) (-0.0524195 0.020453 0) (-0.0597463 0.0207734 0) (-0.067124 0.0207008 0) (-0.0744057 0.0201167 0) (-0.0814104 0.0189081 0) (-0.0879292 0.016983 0) (-0.0937337 0.0142837 0) (-0.098587 0.0107986 0) (-0.102256 0.006571 0) (-0.104523 0.00170433 0) (-0.10521 -0.00363755 0) (-0.104174 -0.00924037 0) (-0.101326 -0.0148316 0) (-0.0966601 -0.0201074 0) (-0.0902465 -0.0247471 0) (-0.0822474 -0.0284356 0) (-0.0729209 -0.0308928 0) (-0.0626191 -0.0319034 0) (-0.0517768 -0.0313486 0) (-0.0408882 -0.0292312 0) (-0.0304711 -0.0256904 0) (-0.0210202 -0.0210002 0) (-0.012955 -0.0155482 0) (-0.00657294 -0.00980024 0) (-0.00201518 -0.00425796 0) (0.000749709 0.000577215 0) (0.00192155 0.00421758 0) (0.00184457 0.00618613 0) (0.00101949 0.00599653 0) (0.000247116 0.00311473 0) (-0.00035659 0.00275622 0) (-0.00233794 0.00814853 0) (-0.00625596 0.0127782 0) (-0.0112959 0.0165086 0) (-0.0171377 0.019429 0) (-0.0236037 0.0217151 0) (-0.0305753 0.023554 0) (-0.0379857 0.0250934 0) (-0.0457964 0.0264141 0) (-0.0539716 0.0275229 0) (-0.0624591 0.0283594 0) (-0.0711762 0.0288116 0) (-0.0800027 0.0287353 0) (-0.0887776 0.0279753 0) (-0.0973016 0.0263857 0) (-0.105343 0.023849 0) (-0.112645 0.0202916 0) (-0.118941 0.0156976 0) (-0.123957 0.0101185 0) (-0.127435 0.0036795 0) (-0.129152 -0.00342025 0) (-0.128911 -0.0109171 0) (-0.126567 -0.0184729 0) (-0.122061 -0.0257065 0) (-0.115413 -0.0322066 0) (-0.106746 -0.0375575 0) (-0.0962934 -0.0413727 0) (-0.0844095 -0.0433347 0) (-0.0715633 -0.0432372 0) (-0.0583213 -0.0410255 0) (-0.0453107 -0.036826 0) (-0.0331649 -0.030955 0) (-0.0224559 -0.0239004 0) (-0.013625 -0.0162778 0) (-0.00692843 -0.00876924 0) (-0.00240736 -0.00206552 0) (0.000110536 0.00316728 0) (0.000983768 0.00629103 0) (0.000749198 0.00667456 0) (0.000217139 0.00363935 0) (-0.000440981 0.0041305 0) (-0.00282056 0.0115475 0) (-0.00746023 0.0176297 0) (-0.0133638 0.0223968 0) (-0.02015 0.0260767 0) (-0.0276213 0.0289544 0) (-0.035656 0.0312935 0) (-0.0441955 0.0332853 0) (-0.0532131 0.0350259 0) (-0.0626834 0.0365137 0) (-0.07256 0.0376627 0) (-0.0827607 0.0383242 0) (-0.0931591 0.0383121 0) (-0.103582 0.0374291 0) (-0.113814 0.0354914 0) (-0.123598 0.0323504 0) (-0.132648 0.0279109 0) (-0.140661 0.0221469 0) (-0.147322 0.0151112 0) (-0.152325 0.00694249 0) (-0.155395 -0.00212966 0) (-0.156277 -0.0117784 0) (-0.15476 -0.0216229 0) (-0.150725 -0.0312003 0) (-0.144126 -0.0400018 0) (-0.135025 -0.0474982 0) (-0.123609 -0.0531764 0) (-0.110204 -0.0565862 0) (-0.0952914 -0.057395 0) (-0.0794932 -0.0554471 0) (-0.0635463 -0.0508142 0) (-0.0482436 -0.0438256 0) (-0.0343498 -0.0350618 0) (-0.022504 -0.0253051 0) (-0.0131323 -0.0154573 0) (-0.00639243 -0.0064487 0) (-0.00216516 0.00082675 0) (-8.48706e-05 0.00553224 0) (0.000425465 0.00686852 0) (0.000186626 0.00401241 0) (-0.000522774 0.00576346 0) (-0.00328461 0.0155285 0) (-0.00861528 0.0232556 0) (-0.0153473 0.0291731 0) (-0.0230438 0.033687 0) (-0.0314919 0.0372195 0) (-0.040571 0.0401262 0) (-0.050234 0.0426499 0) (-0.0604693 0.0449027 0) (-0.0712644 0.0468716 0) (-0.0825812 0.0484396 0) (-0.094339 0.0494151 0) (-0.106406 0.0495636 0) (-0.118598 0.0486394 0) (-0.130678 0.0464139 0) (-0.142365 0.0427009 0) (-0.15334 0.0373776 0) (-0.163262 0.0304012 0) (-0.171777 0.021821 0) (-0.17853 0.0117852 0) (-0.183182 0.000549578 0) (-0.185443 -0.0115137 0) (-0.185053 -0.0239711 0) (-0.181812 -0.036284 0) (-0.175603 -0.047848 0) (-0.166408 -0.0580165 0) (-0.154337 -0.0661358 0) (-0.139653 -0.0715958 0) (-0.122803 -0.0738954 0) (-0.104424 -0.0727218 0) (-0.0853406 -0.0680308 0) (-0.066505 -0.0601108 0) (-0.0489093 -0.0496037 0) (-0.0334527 -0.0374642 0) (-0.0208071 -0.0248557 0) (-0.0113151 -0.0130146 0) (-0.00495615 -0.00313312 0) (-0.00137617 0.00369654 0) (4.88143e-05 0.0064723 0) (0.000157963 0.00421227 0) (-0.000599632 0.0076424 0) (-0.00371751 0.0200602 0) (-0.00969107 0.0296146 0) (-0.0171968 0.0367935 0) (-0.0257498 0.0422197 0) (-0.0351266 0.0464779 0) (-0.0452109 0.0500315 0) (-0.0559697 0.0531808 0) (-0.0674076 0.0560545 0) (-0.079526 0.0586242 0) (-0.0922944 0.0607362 0) (-0.105633 0.0621484 0) (-0.119402 0.0625706 0) (-0.133401 0.061701 0) (-0.147372 0.0592593 0) (-0.161004 0.0550155 0) (-0.173945 0.0488135 0) (-0.185817 0.0405905 0) (-0.196231 0.030391 0) (-0.204798 0.0183741 0) (-0.211144 0.00481705 0) (-0.214945 -0.00988781 0) (-0.215903 -0.0252341 0) (-0.213762 -0.0406253 0) (-0.208332 -0.0553748 0) (-0.199503 -0.0687276 0) (-0.187276 -0.0798897 0) (-0.171801 -0.0880748 0) (-0.153428 -0.0925758 0) (-0.132742 -0.0928599 0) (-0.110592 -0.0886847 0) (-0.0880585 -0.0802098 0) (-0.06637 -0.0680701 0) (-0.0467448 -0.053368 0) (-0.0301949 -0.0375621 0) (-0.0173499 -0.0222753 0) (-0.00836508 -0.00909787 0) (-0.00293514 0.000535536 0) (-0.000391981 0.0053646 0) (0.00013027 0.0042145 0) (-0.000668427 0.0097469 0) (-0.00410391 0.0250955 0) (-0.0106526 0.0366458 0) (-0.0188558 0.0451935 0) (-0.0281886 0.0516128 0) (-0.0384211 0.0566744 0) (-0.0494438 0.0609627 0) (-0.0612377 0.0648412 0) (-0.0738228 0.0684538 0) (-0.087212 0.0717524 0) (-0.101379 0.0745388 0) (-0.116241 0.076513 0) (-0.131645 0.0773202 0) (-0.147371 0.0765948 0) (-0.163131 0.0739983 0) (-0.178583 0.0692523 0) (-0.193343 0.0621664 0) (-0.207006 0.0526594 0) (-0.219162 0.0407747 0) (-0.229411 0.0266858 0) (-0.237376 0.010693 0) (-0.24272 -0.00678291 0) (-0.245138 -0.0251892 0) (-0.24435 -0.043888 0) (-0.240102 -0.0621347 0) (-0.23219 -0.0790921 0) (-0.220483 -0.0938464 0) (-0.20497 -0.105441 0) (-0.185829 -0.112939 0) (-0.1635 -0.115531 0) (-0.138755 -0.11268 0) (-0.112718 -0.104293 0) (-0.0868139 -0.0908744 0) (-0.0626111 -0.0735962 0) (-0.0415618 -0.0542111 0) (-0.0247194 -0.0348129 0) (-0.0125392 -0.0175233 0) (-0.00483717 -0.00425091 0) (-0.000922275 0.00339198 0) (9.99491e-05 0.00398504 0) (-0.00072545 0.0120472 0) (-0.00442632 0.0305691 0) (-0.0114606 0.0442668 0) (-0.0202608 0.0542849 0) (-0.0302709 0.0617785 0) (-0.0412572 0.0677244 0) (-0.0531166 0.0728387 0) (-0.0658421 0.0775511 0) (-0.0794653 0.0820192 0) (-0.0940053 0.0861686 0) (-0.109435 0.0897489 0) (-0.125658 0.0923926 0) (-0.142505 0.093672 0) (-0.159726 0.0931506 0) (-0.177001 0.0904272 0) (-0.193957 0.0851753 0) (-0.210183 0.0771749 0) (-0.225259 0.0663365 0) (-0.238776 0.0527141 0) (-0.250356 0.0365062 0) (-0.259654 0.0180451 0) (-0.266358 -0.00221708 0) (-0.270195 -0.0237137 0) (-0.270896 -0.0457773 0) (-0.268175 -0.0676481 0) (-0.261746 -0.0884523 0) (-0.251341 -0.107202 0) (-0.236754 -0.122803 0) (-0.217924 -0.134098 0) (-0.19504 -0.139964 0) (-0.16866 -0.139478 0) (-0.139811 -0.132143 0) (-0.110004 -0.118153 0) (-0.081122 -0.0985853 0) (-0.0551286 -0.0754132 0) (-0.0336613 -0.0512595 0) (-0.0176571 -0.028941 0) (-0.00718312 -0.0110309 0) (-0.00157847 0.000357846 0) (6.20946e-05 0.00347427 0) (-0.000766708 0.0145034 0) (-0.00466615 0.0363963 0) (-0.0120735 0.0523715 0) (-0.0213448 0.0639534 0) (-0.0319015 0.0726 0) (-0.0435067 0.0795088 0) (-0.0560614 0.0855356 0) (-0.0695654 0.0911777 0) (-0.0840551 0.0966024 0) (-0.0995481 0.101702 0) (-0.116007 0.106165 0) (-0.133317 0.109547 0) (-0.151279 0.11134 0) (-0.16961 0.111031 0) (-0.187956 0.108156 0) (-0.205913 0.102347 0) (-0.223056 0.0933679 0) (-0.238969 0.0811379 0) (-0.25327 0.0657425 0) (-0.265631 0.0474229 0) (-0.275777 0.0265537 0) (-0.283475 0.00361599 0) (-0.28851 -0.0208226 0) (-0.290664 -0.0460968 0) (-0.28967 -0.0714795 0) (-0.285191 -0.0961198 0) (-0.276844 -0.119024 0) (-0.264224 -0.139027 0) (-0.246988 -0.154801 0) (-0.224982 -0.164915 0) (-0.198411 -0.167999 0) (-0.168015 -0.163008 0) (-0.1352 -0.149591 0) (-0.102028 -0.128469 0) (-0.0709631 -0.101644 0) (-0.0443703 -0.0722433 0) (-0.0239032 -0.043944 0) (-0.0100883 -0.020245 0) (-0.00240513 -0.00398715 0) (9.68972e-06 0.00261045 0) (-0.000788308 0.0170648 0) (-0.00480521 0.0424722 0) (-0.0124506 0.0608297 0) (-0.0220413 0.0740575 0) (-0.032985 0.083929 0) (-0.0450403 0.091871 0) (-0.0581071 0.0988829 0) (-0.0721843 0.105529 0) (-0.0873041 0.111982 0) (-0.103473 0.118093 0) (-0.120635 0.12348 0) (-0.138647 0.127614 0) (-0.157275 0.129899 0) (-0.176199 0.129746 0) (-0.195033 0.126633 0) (-0.21335 0.120164 0) (-0.230726 0.110106 0) (-0.246766 0.0964134 0) (-0.261145 0.0792289 0) (-0.273612 0.0588577 0) (-0.283993 0.0357295 0) (-0.292162 0.010355 0) (-0.298 -0.0167007 0) (-0.301384 -0.0448174 0) (-0.302108 -0.0733414 0) (-0.299836 -0.101511 0) (-0.294116 -0.12841 0) (-0.28438 -0.1529 0) (-0.27001 -0.173572 0) (-0.250467 -0.188756 0) (-0.225483 -0.196636 0) (-0.195321 -0.195513 0) (-0.161031 -0.184259 0) (-0.124599 -0.16289 0) (-0.0888459 -0.133085 0) (-0.0569153 -0.0982896 0) (-0.0314272 -0.0631456 0) (-0.0136667 -0.0323975 0) (-0.00345093 -0.00995007 0) (-6.60034e-05 0.00129582 0) (-0.000786906 0.019671 0) (-0.00482753 0.0486731 0) (-0.0125555 0.0694877 0) (-0.0222902 0.0844291 0) (-0.0334341 0.0955861 0) (-0.0457384 0.104617 0) (-0.0590945 0.112664 0) (-0.0734909 0.120357 0) (-0.0889456 0.127867 0) (-0.105445 0.134999 0) (-0.122905 0.141292 0) (-0.141149 0.146124 0) (-0.159907 0.148813 0) (-0.178824 0.148693 0) (-0.197486 0.145198 0) (-0.215462 0.137921 0) (-0.232339 0.126659 0) (-0.247771 0.111431 0) (-0.261503 0.0924625 0) (-0.273382 0.0701452 0) (-0.283351 0.0449788 0) (-0.291408 0.0175098 0) (-0.297552 -0.0117085 0) (-0.301782 -0.042126 0) (-0.303989 -0.0731942 0) (-0.303895 -0.104301 0) (-0.30105 -0.134693 0) (-0.294793 -0.163367 0) (-0.284295 -0.188966 0) (-0.268652 -0.209707 0) (-0.247083 -0.223414 0) (-0.219227 -0.227722 0) (-0.185518 -0.220549 0) (-0.147536 -0.200836 0) (-0.108143 -0.169429 0) (-0.0711415 -0.129673 0) (-0.0402932 -0.0871009 0) (-0.0180111 -0.0480277 0) (-0.00476286 -0.0178879 0) (-0.000174409 -0.000591228 0) (-0.000760187 0.0222537 0) (-0.00472129 0.0548594 0) (-0.01236 0.0781716 0) (-0.0220438 0.0948762 0) (-0.0331782 0.107364 0) (-0.045503 0.117517 0) (-0.0588928 0.12662 0) (-0.0733156 0.135362 0) (-0.0887652 0.14391 0) (-0.1052 0.152014 0) (-0.122503 0.15913 0) (-0.140464 0.164545 0) (-0.15878 0.167486 0) (-0.177069 0.167224 0) (-0.194906 0.163164 0) (-0.211868 0.15491 0) (-0.227579 0.142317 0) (-0.24175 0.125493 0) (-0.254212 0.104771 0) (-0.264915 0.0806499 0) (-0.273915 0.0537095 0) (-0.28133 0.0245406 0) (-0.287284 -0.00631749 0) (-0.291899 -0.0384038 0) (-0.295179 -0.0712786 0) (-0.296957 -0.104523 0) (-0.296853 -0.137612 0) (-0.294215 -0.169787 0) (-0.288108 -0.199885 0) (-0.277361 -0.226186 0) (-0.260727 -0.246328 0) (-0.237174 -0.257391 0) (-0.206335 -0.25629 0) (-0.169036 -0.240588 0) (-0.127749 -0.209721 0) (-0.0865825 -0.166245 0) (-0.0504222 -0.116192 0) (-0.0231676 -0.0676582 0) (-0.0063762 -0.028191 0) (-0.00032271 -0.00319699 0) (-0.000707289 0.0247394 0) (-0.00448068 0.0608801 0) (-0.0118483 0.0866924 0) (-0.0212731 0.105188 0) (-0.0321722 0.119033 0) (-0.0442701 0.130318 0) (-0.0574161 0.140462 0) (-0.0715483 0.150211 0) (-0.0866281 0.159725 0) (-0.102581 0.168696 0) (-0.119258 0.176499 0) (-0.136421 0.182327 0) (-0.153741 0.185329 0) (-0.170829 0.184724 0) (-0.187267 0.179906 0) (-0.20266 0.170516 0) (-0.216683 0.156487 0) (-0.22912 0.138041 0) (-0.239888 0.115634 0) (-0.249028 0.0898789 0) (-0.256692 0.0614436 0) (-0.263099 0.0309663 0) (-0.268485 -0.00102061 0) (-0.273059 -0.0341394 0) (-0.276931 -0.0680568 0) (-0.280083 -0.102557 0) (-0.282261 -0.137382 0) (-0.282914 -0.172086 0) (-0.281135 -0.205834 0) (-0.275639 -0.237162 0) (-0.264847 -0.263757 0) (-0.247132 -0.282376 0) (-0.221264 -0.289056 0) (-0.187068 -0.279861 0) (-0.146161 -0.252302 0) (-0.102421 -0.207268 0) (-0.0615424 -0.150487 0) (-0.0291137 -0.0917197 0) (-0.00831371 -0.041254 0) (-0.000519557 -0.00668599 0) (-0.000629111 0.0270535 0) (-0.00410732 0.0665801 0) (-0.0110201 0.0948532 0) (-0.0199725 0.115145 0) (-0.0304035 0.130351 0) (-0.0420187 0.142752 0) (-0.0546353 0.153887 0) (-0.0681533 0.164558 0) (-0.0824972 0.174917 0) (-0.0975588 0.184604 0) (-0.113163 0.192913 0) (-0.129051 0.198955 0) (-0.144892 0.201812 0) (-0.160306 0.200669 0) (-0.174903 0.194927 0) (-0.18834 0.184286 0) (-0.200355 0.168774 0) (-0.21081 0.148736 0) (-0.219699 0.124757 0) (-0.227139 0.0975637 0) (-0.233343 0.0679077 0) (-0.238595 0.0364697 0) (-0.24321 0.00378506 0) (-0.247443 -0.0297961 0) (-0.251486 -0.0640777 0) (-0.255464 -0.0990139 0) (-0.259277 -0.134601 0) (-0.26255 -0.170739 0) (-0.264523 -0.207006 0) (-0.263966 -0.242361 0) (-0.25917 -0.2748 0) (-0.248088 -0.30107 0) (-0.228719 -0.316631 0) (-0.199793 -0.31616 0) (-0.16172 -0.294948 0) (-0.117545 -0.251357 0) (-0.0731637 -0.189604 0) (-0.0357373 -0.12046 0) (-0.0105758 -0.0574361 0) (-0.000771236 -0.0112275 0) (-0.000528445 0.0291248 0) (-0.00361113 0.0718074 0) (-0.00989265 0.102458 0) (-0.0181642 0.124522 0) (-0.0278971 0.141073 0) (-0.0387775 0.154545 0) (-0.0505853 0.166591 0) (-0.063178 0.178062 0) (-0.0764405 0.189108 0) (-0.090235 0.199324 0) (-0.104369 0.207937 0) (-0.118582 0.213988 0) (-0.132558 0.21651 0) (-0.145949 0.21467 0) (-0.158421 0.207898 0) (-0.169693 0.195962 0) (-0.179581 0.178998 0) (-0.188021 0.157471 0) (-0.19507 0.132089 0) (-0.200895 0.103682 0) (-0.205743 0.0730734 0) (-0.209915 0.0409804 0) (-0.213734 0.0079455 0) (-0.217489 -0.0256869 0) (-0.221434 -0.059825 0) (-0.225775 -0.094547 0) (-0.230567 -0.130062 0) (-0.235643 -0.16659 0) (-0.240476 -0.204153 0) (-0.244041 -0.242247 0) (-0.244706 -0.279401 0) (-0.240245 -0.312696 0) (-0.228098 -0.337425 0) (-0.205987 -0.347226 0) (-0.172959 -0.335204 0) (-0.130718 -0.296564 0) (-0.0846021 -0.232628 0) (-0.0428267 -0.153854 0) (-0.013137 -0.077016 0) (-0.00108137 -0.0169862 0) (-0.000409894 0.0308905 0) (-0.00301046 0.0764224 0) (-0.00850153 0.109321 0) (-0.0158987 0.133108 0) (-0.0247177 0.150962 0) (-0.0346267 0.16544 0) (-0.0453668 0.178287 0) (-0.0567509 0.190408 0) (-0.068626 0.201956 0) (-0.0808307 0.212498 0) (-0.0931677 0.221208 0) (-0.105393 0.227081 0) (-0.117226 0.229115 0) (-0.128377 0.226482 0) (-0.138579 0.21865 0) (-0.147634 0.205467 0) (-0.155435 0.18717 0) (-0.161983 0.164336 0) (-0.167384 0.137777 0) (-0.17183 0.108407 0) (-0.175567 0.0771045 0) (-0.178877 0.0446172 0) (-0.182052 0.0114948 0) (-0.185373 -0.0219377 0) (-0.189111 -0.0556152 0) (-0.193515 -0.0896927 0) (-0.198761 -0.124525 0) (-0.204878 -0.160592 0) (-0.211608 -0.198325 0) (-0.218229 -0.237797 0) (-0.223359 -0.278229 0) (-0.224841 -0.317339 0) (-0.219834 -0.350703 0) (-0.205284 -0.371435 0) (-0.178925 -0.370805 0) (-0.140831 -0.34064 0) (-0.0950719 -0.278132 0) (-0.0500777 -0.19153 0) (-0.0159457 -0.100149 0) (-0.00145064 -0.0241082 0) (-0.000279573 0.0323005 0) (-0.00233136 0.080306 0) (-0.00689994 0.115279 0) (-0.0132547 0.140706 0) (-0.0209684 0.159804 0) (-0.0296959 0.175201 0) (-0.0391414 0.18872 0) (-0.0490744 0.201321 0) (-0.0593077 0.213174 0) (-0.0696646 0.223835 0) (-0.0799561 0.23245 0) (-0.0899715 0.237988 0) (-0.099486 0.239436 0) (-0.108283 0.235983 0) (-0.116182 0.227149 0) (-0.12307 0.212854 0) (-0.128917 0.193427 0) (-0.133779 0.169539 0) (-0.137794 0.14208 0) (-0.141152 0.112019 0) (-0.144077 0.0802729 0) (-0.146805 0.0476047 0) (-0.149575 0.0145696 0) (-0.152623 -0.0185114 0) (-0.156195 -0.0515684 0) (-0.160549 -0.0847772 0) (-0.165933 -0.118564 0) (-0.172528 -0.153577 0) (-0.180329 -0.190581 0) (-0.18895 -0.230193 0) (-0.197376 -0.27239 0) (-0.203722 -0.315756 0) (-0.205153 -0.356561 0) (-0.198145 -0.387977 0) (-0.179341 -0.400033 0) (-0.147139 -0.381397 0) (-0.103833 -0.324332 0) (-0.0571256 -0.232756 0) (-0.0189275 -0.126837 0) (-0.00187669 -0.0327077 0) (-0.00014462 0.0333215 0) (-0.00160623 0.0833686 0) (-0.00515664 0.120197 0) (-0.0103364 0.147155 0) (-0.0167875 0.167411 0) (-0.024159 0.183625 0) (-0.0321235 0.197677 0) (-0.0404114 0.210578 0) (-0.0488064 0.222537 0) (-0.0571248 0.233118 0) (-0.0651978 0.241469 0) (-0.0728617 0.246554 0) (-0.0799623 0.247373 0) (-0.0863693 0.243144 0) (-0.0919964 0.233438 0) (-0.0968165 0.218243 0) (-0.10087 0.197961 0) (-0.10426 0.173326 0) (-0.107137 0.14528 0) (-0.109677 0.11482 0) (-0.112063 0.0828768 0) (-0.114475 0.0502168 0) (-0.117084 0.0173976 0) (-0.120065 -0.0152508 0) (-0.123615 -0.0476343 0) (-0.127964 -0.0799054 0) (-0.133383 -0.112492 0) (-0.14015 -0.14612 0) (-0.148455 -0.181779 0) (-0.158226 -0.22054 0) (-0.168854 -0.263117 0) (-0.178867 -0.309075 0) (-0.185677 -0.355709 0) (-0.185618 -0.396807 0) (-0.174556 -0.421877 0) (-0.149375 -0.417017 0) (-0.110343 -0.369326 0) (-0.0636057 -0.276488 0) (-0.0219952 -0.156918 0) (-0.00235527 -0.0428583 0) (-1.26933e-05 0.0339398 0) (-0.000872008 0.0855563 0) (-0.00335286 0.123982 0) (-0.00726945 0.152327 0) (-0.0123429 0.173638 0) (-0.0182266 0.190553 0) (-0.0245695 0.204989 0) (-0.0310698 0.218012 0) (-0.0374885 0.229881 0) (-0.0436421 0.2402 0) (-0.0493904 0.248142 0) (-0.0546266 0.252697 0) (-0.0592756 0.252892 0) (-0.0633004 0.247986 0) (-0.0667097 0.237598 0) (-0.0695616 0.22177 0) (-0.0719601 0.20095 0) (-0.0740431 0.175911 0) (-0.0759647 0.147611 0) (-0.0778775 0.117055 0) (-0.0799191 0.085164 0) (-0.0822088 0.0526974 0) (-0.0848533 0.0202113 0) (-0.0879625 -0.0119496 0) (-0.0916704 -0.0436553 0) (-0.0961614 -0.0750064 0) (-0.101688 -0.106381 0) (-0.108561 -0.138503 0) (-0.117095 -0.172473 0) (-0.127464 -0.209693 0) (-0.13944 -0.25152 0) (-0.152025 -0.298511 0) (-0.163057 -0.349195 0) (-0.169017 -0.398448 0) (-0.165352 -0.436008 0) (-0.147717 -0.446224 0) (-0.114346 -0.411342 0) (-0.0692289 -0.321471 0) (-0.0250662 -0.190092 0) (-0.00288248 -0.0545927 0) (0.000108157 0.0341631 0) (-0.000168305 0.0868563 0) (-0.0015786 0.126589 0) (-0.00419589 0.156145 0) (-0.00782631 0.178384 0) (-0.0121378 0.195871 0) (-0.0167663 0.210539 0) (-0.0213876 0.223509 0) (-0.0257468 0.235105 0) (-0.0296662 0.244995 0) (-0.0330392 0.252409 0) (-0.0358202 0.256385 0) (-0.0380164 0.255997 0) (-0.0396845 0.250549 0) (-0.0409259 0.239702 0) (-0.0418787 0.223534 0) (-0.0427037 0.202517 0) (-0.0435669 0.177427 0) (-0.044622 0.149218 0) (-0.045996 0.118871 0) (-0.047784 0.0872887 0) (-0.0500523 0.0552106 0) (-0.0528504 0.0231891 0) (-0.0562303 -0.00841595 0) (-0.0602666 -0.0394353 0) (-0.065086 -0.0699054 0) (-0.0708952 -0.100124 0) (-0.0779905 -0.130753 0) (-0.0867326 -0.162909 0) (-0.0974519 -0.198186 0) (-0.110229 -0.238443 0) (-0.124528 -0.285152 0) (-0.138713 -0.338148 0) (-0.149646 -0.393754 0) (-0.152697 -0.442619 0) (-0.14265 -0.468296 0) (-0.115873 -0.448918 0) (-0.0738424 -0.366375 0) (-0.0280927 -0.225963 0) (-0.00345809 -0.0679164 0) (0.000210209 0.0340197 0) (0.000465154 0.0873011 0) (7.13918e-05 0.128025 0) (-0.00126972 0.158586 0) (-0.0034472 0.181601 0) (-0.00615237 0.199513 0) (-0.00902067 0.21426 0) (-0.0117195 0.227006 0) (-0.0139843 0.238157 0) (-0.0156474 0.247468 0) (-0.0166381 0.254252 0) (-0.0169716 0.257621 0) (-0.016735 0.256708 0) (-0.0160736 0.250868 0) (-0.0151766 0.239795 0) (-0.0142555 0.223585 0) (-0.013523 0.202707 0) (-0.0131707 0.177918 0) (-0.0133521 0.150137 0) (-0.0141741 0.120309 0) (-0.015698 0.0892988 0) (-0.0179491 0.0578243 0) (-0.0209331 0.0264294 0) (-0.0246576 -0.00451267 0) (-0.0291468 -0.0347944 0) (-0.0344692 -0.064392 0) (-0.0407729 -0.0935106 0) (-0.0483053 -0.122718 0) (-0.0574092 -0.153076 0) (-0.0684801 -0.186247 0) (-0.0818071 -0.224426 0) (-0.0972464 -0.269846 0) (-0.113714 -0.323611 0) (-0.128613 -0.383696 0) (-0.137541 -0.442241 0) (-0.134791 -0.48297 0) (-0.11515 -0.480963 0) (-0.0774404 -0.409925 0) (-0.0311015 -0.26408 0) (-0.00409272 -0.0828353 0) (0.000287162 0.0335619 0) (0.000988931 0.0869756 0) (0.00150114 0.128354 0) (0.00135035 0.15968 0) (0.000570793 0.183282 0) (-0.000545905 0.20147 0) (-0.00164988 0.216132 0) (-0.00242599 0.228487 0) (-0.00260136 0.239031 0) (-0.00202407 0.247627 0) (-0.000657108 0.253692 0) (0.00142556 0.256431 0) (0.00406281 0.255053 0) (0.00702961 0.248964 0) (0.0100571 0.237886 0) (0.0128668 0.221915 0) (0.0151985 0.201494 0) (0.0168343 0.177339 0) (0.0176146 0.150313 0) (0.0174425 0.121309 0) (0.0162775 0.0911474 0) (0.0141207 0.0605161 0) (0.0109959 0.0299485 0) (0.00692717 -0.000172476 0) (0.00192417 -0.0296053 0) (-0.00402861 -0.0582718 0) (-0.0110173 -0.0863033 0) (-0.0192251 -0.11416 0) (-0.0289292 -0.142802 0) (-0.0405125 -0.173865 0) (-0.0543668 -0.209722 0) (-0.0706385 -0.25317 0) (-0.0887527 -0.306442 0) (-0.106743 -0.36922 0) (-0.120684 -0.43557 0) (-0.124747 -0.490307 0) (-0.112491 -0.506716 0) (-0.0801192 -0.450972 0) (-0.0342063 -0.303965 0) (-0.00482718 -0.099403 0) (0.000334264 0.0328623 0) (0.00136096 0.0860119 0) (0.00260211 0.127709 0) (0.00348839 0.159526 0) (0.0040113 0.183495 0) (0.00441291 0.201772 0) (0.00501625 0.216173 0) (0.0061333 0.22797 0) (0.00801469 0.237754 0) (0.0107913 0.245506 0) (0.0144648 0.250768 0) (0.0189125 0.252853 0) (0.02391 0.251058 0) (0.0291602 0.244844 0) (0.0343258 0.233955 0) (0.0390681 0.218472 0) (0.0430807 0.198797 0) (0.046116 0.175583 0) (0.0479998 0.149623 0) (0.0486332 0.121743 0) (0.0479818 0.0927137 0) (0.0460579 0.0631896 0) (0.0428997 0.0336909 0) (0.0385523 0.00460497 0) (0.0330505 -0.0238052 0) (0.0264088 -0.0514175 0) (0.0185993 -0.0783052 0) (0.00951899 -0.104832 0) (-0.00102395 -0.131844 0) (-0.0133432 -0.160889 0) (-0.0278403 -0.194377 0) (-0.0448362 -0.235463 0) (-0.064179 -0.287288 0) (-0.0845517 -0.351163 0) (-0.10269 -0.423345 0) (-0.112995 -0.490558 0) (-0.108188 -0.525656 0) (-0.0820129 -0.488481 0) (-0.0376045 -0.345139 0) (-0.00575282 -0.117783 0) (0.00034525 0.032013 0) (0.00154057 0.0845912 0) (0.00326994 0.126287 0) (0.00497399 0.158293 0) (0.00662576 0.182366 0) (0.00842705 0.200488 0) (0.0106611 0.214433 0) (0.0136111 0.2255 0) (0.0174943 0.234372 0) (0.0224115 0.241157 0) (0.0283285 0.245534 0) (0.0350793 0.246935 0) (0.0423868 0.244755 0) (0.049895 0.238512 0) (0.0572085 0.227969 0) (0.0639355 0.213182 0) (0.0697251 0.194502 0) (0.074296 0.172501 0) (0.0774504 0.147894 0) (0.0790745 0.121431 0) (0.0791262 0.0938249 0) (0.077615 0.0656929 0) (0.0745806 0.0375388 0) (0.0700754 0.0097491 0) (0.064147 -0.0174033 0) (0.056837 -0.0437764 0) (0.0481651 -0.0693915 0) (0.0381011 -0.0945444 0) (0.026546 -0.119978 0) (0.0132892 -0.14712 0) (-0.00200698 -0.178317 0) (-0.0197321 -0.216885 0) (-0.0400473 -0.26661 0) (-0.0622476 -0.330227 0) (-0.0838496 -0.406278 0) (-0.0998019 -0.484061 0) (-0.102407 -0.537402 0) (-0.0832091 -0.521471 0) (-0.0415423 -0.387087 0) (-0.00702808 -0.138315 0) (0.000311582 0.0311292 0) (0.00147884 0.0829515 0) (0.00338502 0.124352 0) (0.00561426 0.156208 0) (0.00816299 0.180059 0) (0.0112024 0.197745 0) (0.0149623 0.210998 0) (0.0196703 0.221142 0) (0.0254926 0.228947 0) (0.032487 0.234648 0) (0.0405799 0.238058 0) (0.0495654 0.23874 0) (0.059124 0.236188 0) (0.0688538 0.229981 0) (0.0783134 0.219898 0) (0.0870659 0.205971 0) (0.0947189 0.188486 0) (0.100955 0.167935 0) (0.105544 0.144941 0) (0.108348 0.120173 0) (0.109303 0.0942795 0) (0.108404 0.0678368 0) (0.105682 0.0413248 0) (0.101188 0.0151224 0) (0.0949686 -0.0104953 0) (0.0870903 -0.0353832 0) (0.0776139 -0.0595356 0) (0.0665686 -0.0832068 0) (0.0539459 -0.10706 0) (0.0396496 -0.132399 0) (0.0234449 -0.161443 0) (0.00496144 -0.197501 0) (-0.0161591 -0.244737 0) (-0.0397486 -0.306998 0) (-0.0641618 -0.385025 0) (-0.0851667 -0.471177 0) (-0.0950927 -0.541626 0) (-0.083651 -0.548933 0) (-0.046231 -0.429173 0) (-0.00888373 -0.161558 0) (0.000219508 0.0303552 0) (0.00110745 0.0813979 0) (0.00279675 0.122242 0) (0.00518582 0.153564 0) (0.00834965 0.176793 0) (0.012435 0.193692 0) (0.0176005 0.205966 0) (0.0239905 0.214967 0) (0.0316949 0.221544 0) (0.0407107 0.226044 0) (0.0509164 0.228412 0) (0.0620679 0.228336 0) (0.0738112 0.22541 0) (0.0857114 0.219277 0) (0.0972933 0.209733 0) (0.108085 0.196783 0) (0.117658 0.180651 0) (0.125658 0.161743 0) (0.131821 0.140588 0) (0.135973 0.117772 0) (0.138022 0.0938713 0) (0.137939 0.0694144 0) (0.135736 0.0448503 0) (0.13146 0.0205381 0) (0.125147 -0.00326325 0) (0.116886 -0.0263779 0) (0.106773 -0.0488333 0) (0.0948854 -0.0708661 0) (0.0812941 -0.0930835 0) (0.0660104 -0.116681 0) (0.0489148 -0.143717 0) (0.0297015 -0.177369 0) (0.00792515 -0.221918 0) (-0.0166777 -0.281975 0) (-0.0433072 -0.360196 0) (-0.0687683 -0.452267 0) (-0.0858907 -0.537996 0) (-0.0830286 -0.569744 0) (-0.0517126 -0.470504 0) (-0.0116 -0.188292 0) (4.45311e-05 0.0298796 0) (0.000319941 0.0803223 0) (0.00129494 0.120374 0) (0.0034082 0.150715 0) (0.00687063 0.172826 0) (0.0118007 0.18849 0) (0.0182593 0.199434 0) (0.0262722 0.207037 0) (0.0358226 0.212212 0) (0.0468237 0.2154 0) (0.0590947 0.216659 0) (0.0723505 0.215792 0) (0.0862089 0.212487 0) (0.100213 0.206449 0) (0.113867 0.197493 0) (0.126675 0.185601 0) (0.138182 0.170937 0) (0.148001 0.153824 0) (0.155832 0.134698 0) (0.161465 0.114057 0) (0.164774 0.0924058 0) (0.165699 0.0702152 0) (0.164231 0.0478959 0) (0.160397 0.0257793 0) (0.154272 0.00410319 0) (0.145929 -0.0169769 0) (0.135464 -0.0375061 0) (0.123026 -0.057726 0) (0.10875 -0.0782179 0) (0.092729 -0.100091 0) (0.0749447 -0.125237 0) (0.0551722 -0.156618 0) (0.0329345 -0.198406 0) (0.00766664 -0.255605 0) (-0.0206115 -0.332369 0) (-0.0499165 -0.427701 0) (-0.0740705 -0.52616 0) (-0.0806615 -0.582614 0) (-0.0576829 -0.509782 0) (-0.0154265 -0.219439 0) (-0.000263248 0.0299817 0) (-0.00106777 0.0802295 0) (-0.00143961 0.11925 0) (-9.53022e-05 0.148053 0) (0.00334312 0.168429 0) (0.00894377 0.182292 0) (0.0166256 0.191475 0) (0.0262437 0.197386 0) (0.0376415 0.200973 0) (0.0506247 0.202745 0) (0.0649384 0.202846 0) (0.0802522 0.201171 0) (0.0961595 0.197491 0) (0.112191 0.191566 0) (0.127842 0.183232 0) (0.142608 0.172451 0) (0.156015 0.159334 0) (0.167656 0.144127 0) (0.1772 0.127177 0) (0.184405 0.108896 0) (0.189111 0.08971 0) (0.191232 0.0700291 0) (0.190739 0.0502151 0) (0.187652 0.0305634 0) (0.182041 0.0112841 0) (0.173993 -0.00753829 0) (0.163636 -0.025937 0) (0.151142 -0.0441803 0) (0.136686 -0.0628442 0) (0.120413 -0.0829693 0) (0.102369 -0.106287 0) (0.0823908 -0.135499 0) (0.0599991 -0.174506 0) (0.0344236 -0.228329 0) (0.00502574 -0.30212 0) (-0.0274914 -0.397876 0) (-0.0584654 -0.505748 0) (-0.0753871 -0.586022 0) (-0.0633051 -0.545126 0) (-0.0204103 -0.255832 0) (-0.000832194 0.0310889 0) (-0.00340761 0.0818104 0) (-0.00590448 0.119477 0) (-0.00584126 0.145982 0) (-0.00270765 0.163805 0) (0.00346209 0.175218 0) (0.0123918 0.18211 0) (0.0236743 0.185998 0) (0.0369779 0.187809 0) (0.0519844 0.188077 0) (0.0683517 0.186996 0) (0.0857 0.184524 0) (0.103601 0.180494 0) (0.121583 0.174712 0) (0.139144 0.167031 0) (0.155782 0.1574 0) (0.171025 0.145881 0) (0.184454 0.132652 0) (0.195722 0.117979 0) (0.204567 0.102187 0) (0.210805 0.0856251 0) (0.214331 0.0686328 0) (0.215104 0.0515147 0) (0.213142 0.0345163 0) (0.208512 0.0178026 0) (0.201326 0.00142322 0) (0.191728 -0.0146951 0) (0.17989 -0.0308409 0) (0.165999 -0.0475838 0) (0.150212 -0.065903 0) (0.13258 -0.087375 0) (0.112953 -0.114424 0) (0.0908371 -0.150576 0) (0.0653263 -0.200581 0) (0.0352856 -0.270013 0) (0.000173015 -0.363262 0) (-0.0373861 -0.47641 0) (-0.0654486 -0.57814 0) (-0.0670723 -0.57385 0) (-0.0261361 -0.297777 0) (-0.00190261 0.0339202 0) (-0.00731303 0.0860383 0) (-0.0129077 0.121757 0) (-0.0145998 0.144867 0) (-0.0118328 0.159072 0) (-0.00502569 0.167207 0) (0.00527892 0.171284 0) (0.0184196 0.172786 0) (0.0337743 0.172642 0) (0.0509074 0.17135 0) (0.069387 0.169101 0) (0.0887848 0.16588 0) (0.108657 0.161557 0) (0.128538 0.15597 0) (0.147942 0.148982 0) (0.166388 0.14053 0) (0.183419 0.130637 0) (0.198626 0.119419 0) (0.211666 0.107065 0) (0.22227 0.0938216 0) (0.230251 0.0799562 0) (0.235497 0.0657362 0) (0.237967 0.051401 0) (0.237679 0.0371398 0) (0.234706 0.023069 0) (0.229164 0.00920328 0) (0.221198 -0.00457494 0) (0.210967 -0.0185614 0) (0.198626 -0.0333061 0) (0.184286 -0.0497201 0) (0.167944 -0.0692234 0) (0.149392 -0.0939602 0) (0.128075 -0.127036 0) (0.102981 -0.172738 0) (0.0726302 -0.236536 0) (0.0354598 -0.324383 0) (-0.00841228 -0.437951 0) (-0.0483018 -0.556767 0) (-0.0667911 -0.592257 0) (-0.0315131 -0.34462 0) (-0.00397146 0.0397779 0) (-0.0138823 0.0942662 0) (-0.0236592 0.1268 0) (-0.0273199 0.144902 0) (-0.0246572 0.15415 0) (-0.0167337 0.158027 0) (-0.00461892 0.15872 0) (0.010712 0.157532 0) (0.0284373 0.155307 0) (0.0479397 0.152448 0) (0.0687096 0.149095 0) (0.0902848 0.145216 0) (0.112219 0.14069 0) (0.134066 0.135368 0) (0.155374 0.129119 0) (0.175698 0.121863 0) (0.194619 0.11359 0) (0.211757 0.104359 0) (0.226792 0.0942946 0) (0.239473 0.0835634 0) (0.249621 0.0723576 0) (0.257132 0.0608708 0) (0.261968 0.0492768 0) (0.264148 0.0377082 0) (0.263739 0.0262354 0) (0.260843 0.0148418 0) (0.255578 0.003392 0) (0.248061 -0.00840745 0) (0.238374 -0.0210681 0) (0.226534 -0.0354105 0) (0.21242 -0.0526819 0) (0.195702 -0.0747449 0) (0.175687 -0.104273 0) (0.151249 -0.145007 0) (0.120642 -0.201938 0) (0.0816575 -0.281657 0) (0.0319487 -0.390356 0) (-0.0202215 -0.519635 0) (-0.0596804 -0.595795 0) (-0.0347846 -0.394527 0) (-0.00803549 0.0511621 0) (-0.0249943 0.108336 0) (-0.0397203 0.135079 0) (-0.0446553 0.145782 0) (-0.0408978 0.148448 0) (-0.030632 0.147096 0) (-0.0155908 0.143833 0) (0.00287604 0.139748 0) (0.0237451 0.135413 0) (0.0462662 0.131062 0) (0.0698734 0.126727 0) (0.0940956 0.122324 0) (0.118508 0.117713 0) (0.142705 0.112739 0) (0.16629 0.107265 0) (0.188875 0.101196 0) (0.210096 0.0944894 0) (0.229623 0.0871587 0) (0.247177 0.0792659 0) (0.262534 0.0709109 0) (0.275534 0.0622162 0) (0.286081 0.0533086 0) (0.294133 0.0443026 0) (0.299698 0.0352818 0) (0.302821 0.026281 0) (0.303565 0.0172647 0) (0.301995 0.00810164 0) (0.298153 -0.00146707 0) (0.292024 -0.0119058 0) (0.283509 -0.0239054 0) (0.272324 -0.038513 0) (0.257973 -0.0572964 0) (0.239544 -0.082481 0) (0.215754 -0.117252 0) (0.18451 -0.165929 0) (0.143329 -0.234955 0) (0.0883492 -0.333343 0) (0.0240059 -0.465329 0) (-0.0421063 -0.579838 0) (-0.0333062 -0.443585 0) (-0.0160516 0.0727674 0) (-0.0435353 0.130194 0) (-0.0616217 0.146022 0) (-0.0639666 0.145879 0) (-0.055165 0.140087 0) (-0.039091 0.132635 0) (-0.0182083 0.125118 0) (0.00578123 0.11814 0) (0.0317105 0.111866 0) (0.0587939 0.106264 0) (0.0864882 0.101201 0) (0.11438 0.0965052 0) (0.142122 0.091993 0) (0.169394 0.0874907 0) (0.195888 0.0828502 0) (0.221305 0.0779602 0) (0.24536 0.0727523 0) (0.267788 0.0672015 0) (0.288362 0.0613224 0) (0.306893 0.0551606 0) (0.323239 0.0487821 0) (0.337307 0.0422602 0) (0.349043 0.0356626 0) (0.358432 0.0290368 0) (0.365481 0.0223953 0) (0.370206 0.0156966 0) (0.37262 0.00882606 0) (0.372661 0.0015736 0) (0.37023 -0.0064184 0) (0.365129 -0.0156917 0) (0.35689 -0.0270617 0) (0.344863 -0.0417674 0) (0.327837 -0.0615314 0) (0.30438 -0.0889579 0) (0.271824 -0.1276 0) (0.227814 -0.183281 0) (0.166787 -0.265592 0) (0.090896 -0.390927 0) (-0.00758694 -0.538016 0) (-0.0212368 -0.482377 0) (-0.0312744 0.109565 0) (-0.0710964 0.15713 0) (-0.0789199 0.15302 0) (-0.0646751 0.137784 0) (-0.0401862 0.122315 0) (-0.0104853 0.108965 0) (0.0218682 0.0979766 0) (0.0553392 0.0890433 0) (0.0890358 0.0817509 0) (0.122464 0.0757214 0) (0.155345 0.070636 0) (0.187498 0.0662278 0) (0.218779 0.0622716 0) (0.249047 0.058579 0) (0.27815 0.0549982 0) (0.305925 0.0514137 0) (0.332198 0.047746 0) (0.356797 0.0439501 0) (0.379561 0.0400118 0) (0.400348 0.0359409 0) (0.419044 0.0317649 0) (0.435563 0.0275194 0) (0.449848 0.0232391 0) (0.461866 0.0189477 0) (0.471596 0.0146487 0) (0.479017 0.0103058 0) (0.484103 0.00584224 0) (0.486741 0.00105337 0) (0.486788 -0.00421898 0) (0.483962 -0.0103692 0) (0.477634 -0.0179475 0) (0.467118 -0.0278155 0) (0.450834 -0.0410953 0) (0.42737 -0.0596949 0) (0.393036 -0.0861669 0) (0.345952 -0.125603 0) (0.277759 -0.186383 0) (0.191038 -0.292388 0) (0.055338 -0.457306 0) (0.013792 -0.489474 0) (-0.0510943 0.203152 0) (-0.0678006 0.169611 0) (-0.0144019 0.124326 0) (0.0416899 0.0981662 0) (0.0946699 0.0796805 0) (0.14424 0.0657996 0) (0.190282 0.05557 0) (0.23293 0.0480523 0) (0.272528 0.0423992 0) (0.309478 0.0380159 0) (0.344136 0.0345156 0) (0.376778 0.0316342 0) (0.407605 0.0291767 0) (0.436739 0.0269942 0) (0.464243 0.0249733 0) (0.490122 0.0230303 0) (0.51434 0.0211072 0) (0.536835 0.019168 0) (0.557532 0.0171962 0) (0.576355 0.01519 0) (0.593234 0.0131583 0) (0.608119 0.0111155 0) (0.620972 0.00907587 0) (0.631778 0.00704806 0) (0.640511 0.00502864 0) (0.647174 0.00300082 0) (0.651645 0.000922692 0) (0.653936 -0.0012477 0) (0.653859 -0.00366452 0) (0.65112 -0.00657959 0) (0.644997 -0.0102508 0) (0.634988 -0.0151285 0) (0.619182 -0.0216899 0) (0.596688 -0.0310233 0) (0.562411 -0.044254 0) (0.515694 -0.0650091 0) (0.442451 -0.0985386 0) (0.350799 -0.168065 0) (0.176688 -0.316994 0) (0.0997845 -0.416322 0) (0.219913 0.149162 0) (0.267002 0.11206 0) (0.38896 0.0742137 0) (0.477374 0.05155 0) (0.538711 0.0371236 0) (0.585356 0.0272624 0) (0.623147 0.0204763 0) (0.654697 0.0158359 0) (0.681629 0.0126326 0) (0.705128 0.0103719 0) (0.726025 0.00873395 0) (0.744879 0.00751195 0) (0.76206 0.00656743 0) (0.777814 0.00580483 0) (0.792293 0.00515766 0) (0.805582 0.00457999 0) (0.817719 0.004041 0) (0.828712 0.00352131 0) (0.83855 0.00301022 0) (0.847219 0.00250364 0) (0.854704 0.00200161 0) (0.861003 0.00150715 0) (0.866117 0.00102208 0) (0.870061 0.00054977 0) (0.872843 8.23989e-05 0) (0.874489 -0.000374726 0) (0.874968 -0.000853184 0) (0.874269 -0.00128884 0) (0.87213 -0.00178722 0) (0.868469 -0.00244247 0) (0.862745 -0.00331189 0) (0.854784 -0.00451817 0) (0.842937 -0.00614581 0) (0.827352 -0.00849216 0) (0.802915 -0.0118014 0) (0.772156 -0.0169389 0) (0.715129 -0.0261221 0) (0.646724 -0.043707 0) (0.463667 -0.0966862 0) (0.332248 -0.163819 0) ) ; boundaryField { carasuperior { type fixedValue; value uniform (0 0 0); } lateralizquierda { type fixedValue; value uniform (0 0 0); } lateralderecha { type fixedValue; value uniform (0 0 0); } carainferior { type fixedValue; value uniform (0 0 0); } frontAndBack { type empty; } } // ************************************************************************* //
[ "santi_0926@hotmail.com" ]
santi_0926@hotmail.com
053aa74bfc2a343288c8ff1eced95d26408a979c
467c89004f868c53e47aabb438e5972fa111dde4
/appUtilsExample/src/scenes/Square.h
0126a8cc30cdb6561366490934df81eef3e8742d
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
masOTROS/ofxAppUtils
1d3d0aa885912c2c8694f735958799ef4a3ea312
e6ed274a559e4bb13ef4acd6b4e6f5cf44770d4b
refs/heads/master
2020-12-31T02:23:41.177902
2014-10-20T17:45:00
2014-10-20T17:45:00
25,469,081
0
0
null
null
null
null
UTF-8
C++
false
false
2,817
h
/* * Copyright (c) 2011 Dan Wilcox <danomatika@gmail.com> * * BSD Simplified License. * For information on usage and redistribution, and for a DISCLAIMER OF ALL * WARRANTIES, see the file, "LICENSE.txt," in this distribution. * * See https://github.com/danomatika/ofxAppUtils for documentation * */ #pragma once #include <ofxAppUtils.h> class Square : public ofxScene { public: // set the scene name through the base class initializer Square() : ofxScene("Square"){ alpha = 255; // we want setup to be called each time the scene is loaded setSingleSetup(false); ofxApp *app = ofxGetAppPtr(); width = app->getRenderWidth(); height = app->getRenderHeight(); ofSetRectMode(OF_RECTMODE_CENTER); } // scene setup void setup() { timer.set(); pos.set(width,height/2); } // called when scene is entering void updateEnter() { // called on first enter update if(isEnteringFirst()) { setup(); timer.setAlarm(2000); alpha = 0; ofLogNotice("LineScene") << "update enter"; } // calc alpha amount based on alarm time diff alpha = 255*timer.getDiffN(); update(); // call finishedEntering() to indicate scene is done entering if(timer.alarm()) { finishedEntering(); alpha = 255; ofLogNotice("LineScene") << "update enter done"; timer2.set(); } } // normal update void update() { if(!isEntering() && !isExiting()){ pos.set((sin((float)timer2.getDiff()/1000 + PI/2)+1)/2*width, height/2); } } // called when scene is exiting void updateExit() { // called on first exit update if(isExitingFirst()) { timer.setAlarm(2000); alpha = 0; ofLogNotice("LineScene") << "update exit"; } // calc alpha amount based on alarm time diff alpha = 255*abs(timer.getDiffN()-1.0); update(); // call finishedExiting() to indicate scene is done exiting if(timer.alarm()) { finishedExiting(); alpha = 0; ofLogNotice("LineScene") << "update exit done"; } } // draw void draw() { ofEnableAlphaBlending(); ofSetColor(255, 255, 0, alpha); // alpha for fade in/out ofRect(pos,80,80); ofDisableAlphaBlending(); } // cleanup void exit() { } // used for fade in and out ofxTimer timer; ofxTimer timer2; int alpha; ofPoint pos; float width; float height; };
[ "alangrizek@gmail.com" ]
alangrizek@gmail.com
63189646efe02ece349f23c9df8817d10cfc7f89
b095de90dace81605b719c37d89d79c805a173f0
/cpp98/pi-exchange/pi_sender.cpp
7dd57d2b5d53822a0c3f3906c673105e457290b3
[]
no_license
sivasath-NREL/HELICS-Examples
ac7a68104a5244c2e257619b467c2c039cf43fac
b8e4752737ae41caa30a3c9c56833802b7ccaf11
refs/heads/master
2020-04-20T23:08:33.368818
2018-10-05T22:16:23
2018-10-05T22:16:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,356
cpp
/* Copyright © 2017-2018, Battelle Memorial Institute; Lawrence Livermore National Security, LLC; Alliance for Sustainable Energy, LLC All rights reserved. See LICENSE file and DISCLAIMER for more details. */ static char help[] = " PI SENDER: Simple program to demonstrate the usage of HELICS C Interface.\n\ This example creates a ZMQ broker and a value federate.\n\ The value federate creates a global publications and publishes\n\ t*pi for 20 time-steps with a time-step of 0.01 seconds.\n\n"; #include <stdio.h> #include <cpp98/ValueFederate.hpp> #include <cpp98/Broker.hpp> #include <cpp98/helics.hpp> // helicsVersionString #ifdef _MSC_VER #include <windows.h> #else #include <unistd.h> #endif int main(int /*argc*/,char ** /*argv*/) { std::string initstring="2 --name=mainbroker"; std::string fedinitstring="--federates=1"; double deltat=0.01; helics98::Publication pub; std::string helicsversion = helics98::getHelicsVersionString(); printf("PI SENDER: Helics version = %s\n",helicsversion.c_str()); printf("%s",help); /* Create broker */ helics98::Broker broker("zmq","",initstring); if(broker.isConnected()) { printf("PI SENDER: Broker created and connected\n"); } /* Create Federate Info object that describes the federate properties * Sets the federate name and core type from string */ helics98::FederateInfo fi("Test sender Federate", "zmq"); /* Federate init string */ fi.setCoreInitString(fedinitstring); /* Set the message interval (timedelta) for federate. Note that HELICS minimum message time interval is 1 ns and by default it uses a time delta of 1 second. What is provided to the setTimedelta routine is a multiplier for the default timedelta. */ /* Set one second message interval */ fi.setTimeDelta(deltat); fi.setLoggingLevel(1); /* Create value federate */ helics98::ValueFederate* vfed = new helics98::ValueFederate(fi); printf("PI SENDER: Value federate created\n"); /* Register the publication */ pub = vfed->registerGlobalPublication("testA", "double"); printf("PI SENDER: Publication registered\n"); /* Enter initialization state */ vfed->enterInitializationMode(); // can throw helics98::InvalidStateTransition exception printf("PI SENDER: Entered initialization state\n"); /* Enter execution state */ vfed->enterExecutionMode(); // can throw helics98::InvalidStateTransition exception printf("PI SENDER: Entered execution state\n"); /* This federate will be publishing deltat*pi for numsteps steps */ //double this_time = 0.0; double value = 22.0/7.0; helics_time_t currenttime=0.0; int numsteps=20,i; for(i=0; i < numsteps; i++) { double val = currenttime*value; printf("PI SENDER: Sending value %3.2fpi = %4.3f at time %3.2f to PI RECEIVER\n",deltat*i,val,currenttime); pub.publish( val); currenttime = vfed->requestTime(currenttime); } vfed->finalize(); printf("PI SENDER: Federate finalized\n"); // destructor must be called before call to helicsCloseLibrary(), or segfault delete vfed; while(broker.isConnected()) { #ifdef _MSC_VER Sleep(100); #else usleep(100000); /* Sleep for 100 millisecond */ #endif } printf("PI SENDER: Broker disconnected\n"); helicsCloseLibrary(); return(0); }
[ "mast9@llnl.gov" ]
mast9@llnl.gov
9240f90dfe51b17f320a165072edd640537111af
ca98685f0731a88953dd16f59a977f0ec6a8822a
/src/vlcplayer/glvlcplayer.cpp
4c4434e058df90d99a88a14a90dd1845737e8014
[]
no_license
damarbo33/MinimalUI
2ff15492f1e93acb52b2dfc96c7cd8424b7d7235
bef959866b68af7573b28abbd3ca6b8c5a720563
refs/heads/master
2022-11-07T17:38:08.468750
2022-10-27T09:32:33
2022-10-27T09:32:33
22,223,415
0
0
null
null
null
null
UTF-8
C++
false
false
9,322
cpp
#include "glvlcplayer.h" GLVlcPlayer::GLVlcPlayer() { //ctor } GLVlcPlayer::~GLVlcPlayer() { //dtor } /* Modified for openGL Draws a video to a opengl rect on a SDL surface */ #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <assert.h> #include <SDL/SDL.h> #include <SDL/SDL_mutex.h> #include <GL/glu.h> #include <GL/glext.h> #include <vlc/vlc.h> #define WIDTH 640 #define HEIGHT 480 #define VIDEOWIDTH 320 #define VIDEOHEIGHT 240 struct ctx { SDL_Surface *surf; SDL_mutex *mutex; }; static void *lock(void *data, void **p_pixels) { struct ctx *ctx = (struct ctx *)data; SDL_LockMutex(ctx->mutex); SDL_LockSurface(ctx->surf); *p_pixels = ctx->surf->pixels; return NULL; /* picture identifier, not needed here */ } static void unlock(void *data, void *id, void *const *p_pixels) { struct ctx *ctx = (struct ctx *)data; /* VLC just rendered the video, but we can also render stuff */ uint16_t *pixels = (uint16_t *)p_pixels; /* int x, y; //annoying box that was being drawn for(y = 10; y < 40; y++) for(x = 10; x < 40; x++) if(x < 13 || y < 13 || x > 36 || y > 36) pixels[y * VIDEOWIDTH + x] = 0xffff; else pixels[y * VIDEOWIDTH + x] = 0x0;*/ SDL_UnlockSurface(ctx->surf); SDL_UnlockMutex(ctx->mutex); assert(id == NULL); /* picture identifier, not needed here */ } int loadTexture(SDL_Surface *sdlimage) { GLuint retval = NULL; void *raw; int w, h, i, j, bpp; Uint8 *srcPixel, *dstPixel; Uint32 truePixel; GLenum errorCode; if (sdlimage->format->BytesPerPixel < 2) { printf("Bad image -- not true color!\n"); SDL_FreeSurface(sdlimage); return 0; } w = sdlimage->w; h = sdlimage->h; raw = (void *) malloc(w * h * 4); dstPixel = (Uint8 *) raw; bpp = sdlimage->format->BytesPerPixel; for (i = h - 1; i >= 0; i--) { for (j = 0; j < w; j++) { srcPixel = (Uint8 *) sdlimage->pixels + i * sdlimage->pitch + j * bpp; switch (bpp) { case 1: truePixel = *srcPixel; break; case 2: truePixel = *(Uint16 *) srcPixel; break; case 3: if (SDL_BYTEORDER == SDL_BIG_ENDIAN) { truePixel = srcPixel[0] << 16 | srcPixel[1] << 8 | srcPixel[2]; } else { truePixel = srcPixel[0] | srcPixel[1] << 8 | srcPixel[2] << 16; } break; case 4: truePixel = *(Uint32 *) srcPixel; break; default: printf("Image bpp of %d unusable\n", bpp); SDL_UnlockSurface(sdlimage); SDL_FreeSurface(sdlimage); free(raw); return 0; } SDL_GetRGBA(truePixel, sdlimage->format, &(dstPixel[0]), &(dstPixel[1]), &(dstPixel[2]), &(dstPixel[3])); dstPixel++; dstPixel++; dstPixel++; dstPixel++; } } while (glGetError()) { ; } glBindTexture(GL_TEXTURE_2D, retval); //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); errorCode = glGetError(); if (errorCode != 0) { if (errorCode == GL_OUT_OF_MEMORY) { printf("Out of texture memory!\n"); } glDeleteTextures(1, &retval); free(raw); return 0; } //gluBuild2DMipmaps(GL_TEXTURE_2D, 4, w, h, GL_RGBA, GL_UNSIGNED_BYTE, (Uint8 *) raw); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA, VIDEOWIDTH, VIDEOHEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE,(Uint8 *) raw); errorCode = glGetError(); if (errorCode != 0) { if (errorCode == GL_OUT_OF_MEMORY) { printf("Out of texture memory!\n"); } glDeleteTextures(1, &retval); free(raw); return 0; } free(raw); return retval; } static void display(void *data, void *id) { /* VLC wants to display the video */ (void) data; assert(id == NULL); } int main(int argc, char *argv[]) { char width[32], height[32], pitch[32]; libvlc_instance_t *libvlc; libvlc_media_t *m; libvlc_media_player_t *mp; char const *vlc_argv[] = { "--quiet", "--ignore-config", "--no-video-title", "--no-xlib", /* tell VLC to not use Xlib */ }; int vlc_argc = sizeof(vlc_argv) / sizeof(*vlc_argv); SDL_Surface *screen; SDL_Event event; int done = 0, action = 0, pause = 0, n = 0; struct ctx ctx; if(argc < 2) { printf("Usage: %s <filename>\n", argv[0]); return EXIT_FAILURE; } /* * Initialise libSDL */ if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTTHREAD) == -1) { printf("cannot initialize SDL\n"); return EXIT_FAILURE; } ctx.surf = SDL_CreateRGBSurface(SDL_SWSURFACE, VIDEOWIDTH, VIDEOHEIGHT, 16, 0x001f, 0x07e0, 0xf800, 0); ctx.mutex = SDL_CreateMutex(); int options = SDL_ANYFORMAT | SDL_HWSURFACE | SDL_DOUBLEBUF | SDL_OPENGL; screen = SDL_SetVideoMode(WIDTH, HEIGHT, 0, options); if(!screen) { printf("cannot set video mode\n"); return EXIT_FAILURE; } /* * Initialise libVLC */ libvlc = libvlc_new(vlc_argc, vlc_argv); m = libvlc_media_new_path(libvlc, argv[1]); mp = libvlc_media_player_new_from_media(m); libvlc_media_release(m); libvlc_video_set_callbacks(mp, lock, unlock, display, &ctx); libvlc_video_set_format(mp, "RV16", VIDEOWIDTH, VIDEOHEIGHT, VIDEOWIDTH*2); libvlc_media_player_play(mp); /* * Main loop */ glEnable(GL_TEXTURE_2D); GLuint image; glGenTextures(1, &image); while(!done) { action = 0; /* Keys: enter (fullscreen), space (pause), escape (quit) */ while( SDL_PollEvent( &event ) ) { switch(event.type) { case SDL_QUIT: done = 1; break; case SDL_KEYDOWN: action = event.key.keysym.sym; break; } } switch(action) { case SDLK_ESCAPE: done = 1; break; case SDLK_RETURN: options ^= SDL_FULLSCREEN; screen = SDL_SetVideoMode(WIDTH, HEIGHT, 0, options); break; case ' ': pause = !pause; break; } if(!pause) n++; glClear(GL_COLOR_BUFFER_BIT); /* Blitting the surface does not prevent it from being locked and * written to by another thread, so we use this additional mutex. */ SDL_LockMutex(ctx.mutex); //SDL_BlitSurface(ctx.surf, NULL, screen, NULL); image = loadTexture(ctx.surf); SDL_UnlockMutex(ctx.mutex); //SDL_Flip(screen); glBegin(GL_QUADS); glTexCoord2d(0, 1); glVertex2f(0, 0.9); glTexCoord2d(1, 1); glVertex2f(0.9, 0.9); glTexCoord2d(1, 0); glVertex2f(0.9, 0); glTexCoord2d(0, 0); glVertex2f(0, 0); glEnd(); glFlush(); SDL_GL_SwapBuffers(); //SDL_Delay(5); //SDL_BlitSurface(empty, NULL, screen, NULL); //use SDL timers to determine playback //printf("%i %i\n",libvlc_media_player_get_length(mp)-1000,libvlc_media_player_get_time(mp)); if(libvlc_media_player_get_length(mp)-1000 == libvlc_media_player_get_time(mp)){ done = 1; } } glDeleteTextures(1, &image); /* * Stop stream and clean up libVLC */ libvlc_media_player_stop(mp); libvlc_media_player_release(mp); libvlc_release(libvlc); /* * Close window and clean up libSDL */ SDL_DestroyMutex(ctx.mutex); SDL_FreeSurface(ctx.surf); //SDL_FreeSurface(empty); SDL_Quit(); return 0; }
[ "damarbo33@gmail.com" ]
damarbo33@gmail.com
265a2695cc7ac43379c6799e347e909a90699db8
cce7e65ef2dc090c9376e02e87b8bf2362ad8535
/include/Instruction_GAP.hh
bbf7c3d4bbd382ef2bc1aade18eb717e9ad4f385
[]
no_license
asfandyar-malik/Mars-Rover
85a2f97a31a04832887de94003bead5f462deb93
248b36363575e5a2bdcc54421db086adfb06c7f6
refs/heads/master
2021-05-27T23:07:44.374308
2014-03-26T01:54:00
2014-03-26T01:54:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,078
hh
/** * Instruction GAP header class */ #ifndef _INSTRUCTION_GAP_HH #define _INSTRUCTION_GAP_HH #include <vector> #include <string> #include "InstructionIF.hh" /** * @class This instruction calculates all the possible locations towards which the * rover can after the specified ammount of time. */ class Instruction_GAP : public InstructionIF { private: int argc; std::vector< std::string > args; public: // Constructors and destructors /** * @brief Public constructor of Instruction_GAP class * @param ret Address in memory to write return value to. * @param args Vector of arguments needed for instruction. */ Instruction_GAP(int* ret, std::vector< std::string > _args); ~Instruction_GAP(); /** * @brief Method to execute the GAP instruction of the Brain File * @param memoryLocation Pointer to MemoryHandler for memory management. * @param instrPointer Pointer to desired instruction. * @return If successful, 0, 1 otherwise. */ int execute(MemoryHandler* memoryLocation,int* instructionPointer); }; #endif
[ "asfandyarashraf@hotmail.com" ]
asfandyarashraf@hotmail.com
85b66c455faeafea92006c795f1737f534bbbcb9
d5546ea8f67d0f4740c66019c31dfcfa6e3fbbb1
/src/pPrimeFactor/PrimeFactor.cpp
f03e5bc650fce9e553a9d9707a352cda4d29a0fa
[]
no_license
iyunsu/moos-ivp-iyunsu
a8cbe9e19acfc39900b621693e73feea300c56cb
5846826230215060b8977d8043a0852fc5864ba3
refs/heads/master
2021-07-21T10:36:17.155828
2020-05-09T15:05:45
2020-05-09T15:05:45
156,827,913
0
0
null
null
null
null
UTF-8
C++
false
false
2,783
cpp
/************************************************************/ /* NAME: iyunsu */ /* ORGN: MIT */ /* FILE: PrimeFactor.cpp */ /* DATE: */ /************************************************************/ #include <iterator> #include "MBUtils.h" #include "PrimeFactor.h" using namespace std; //--------------------------------------------------------- // Constructor PrimeFactor::PrimeFactor() { } //--------------------------------------------------------- // Destructor PrimeFactor::~PrimeFactor() { } //--------------------------------------------------------- // Procedure: OnNewMail bool PrimeFactor::OnNewMail(MOOSMSG_LIST &NewMail) { MOOSMSG_LIST::iterator p; for(p=NewMail.begin(); p!=NewMail.end(); p++) { CMOOSMsg &msg = *p; string key = msg.GetKey(); if(key == "NAV_VALUE") { } #if 0 // Keep these around just for template string key = msg.GetKey(); string comm = msg.GetCommunity(); double dval = msg.GetDouble(); string sval = msg.GetString(); string msrc = msg.GetSource(); double mtime = msg.GetTime(); bool mdbl = msg.IsDouble(); bool mstr = msg.IsString(); #endif } return(true); } //--------------------------------------------------------- // Procedure: OnConnectToServer bool PrimeFactor::OnConnectToServer() { // register for variables here // possibly look at the mission file? // m_MissionReader.GetConfigurationParam("Name", <string>); // m_Comms.Register("VARNAME", 0); RegisterVariables(); return(true); } //--------------------------------------------------------- // Procedure: Iterate() // happens AppTick times per second bool PrimeFactor::Iterate() { return(true); } //--------------------------------------------------------- // Procedure: OnStartUp() // happens before connection is open bool PrimeFactor::OnStartUp() { list<string> sParams; m_MissionReader.EnableVerbatimQuoting(false); if(m_MissionReader.GetConfiguration(GetAppName(), sParams)) { list<string>::iterator p; for(p=sParams.begin(); p!=sParams.end(); p++) { string line = *p; string param = tolower(biteStringX(line, '=')); string value = line; if(param == "foo") { //handled } else if(param == "bar") { //handled } } } RegisterVariables(); return(true); } //--------------------------------------------------------- // Procedure: RegisterVariables void PrimeFactor::RegisterVariables() { // Register("FOOBAR", 0); Register("NAV_VALUE",0); }
[ "yap634224@gmail.com" ]
yap634224@gmail.com
6029430e75cde7c71728204fecda64f9b0940eff
5ec06dab1409d790496ce082dacb321392b32fe9
/clients/cpp-qt5/generated/client/OAIComAdobeCqSocialEnablementAdaptorsEnablementResourceAdaptorFactoInfo.cpp
e16247f689bd25d4a62bb9c848c516a457ff4537
[ "Apache-2.0" ]
permissive
shinesolutions/swagger-aem-osgi
e9d2385f44bee70e5bbdc0d577e99a9f2525266f
c2f6e076971d2592c1cbd3f70695c679e807396b
refs/heads/master
2022-10-29T13:07:40.422092
2021-04-09T07:46:03
2021-04-09T07:46:03
190,217,155
3
3
Apache-2.0
2022-10-05T03:26:20
2019-06-04T14:23:28
null
UTF-8
C++
false
false
5,718
cpp
/** * Adobe Experience Manager OSGI config (AEM) API * Swagger AEM OSGI is an OpenAPI specification for Adobe Experience Manager (AEM) OSGI Configurations API * * OpenAPI spec version: 1.0.0-pre.0 * Contact: opensource@shinesolutions.com * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ #include "OAIComAdobeCqSocialEnablementAdaptorsEnablementResourceAdaptorFactoInfo.h" #include "OAIHelpers.h" #include <QJsonDocument> #include <QJsonArray> #include <QObject> #include <QDebug> namespace OpenAPI { OAIComAdobeCqSocialEnablementAdaptorsEnablementResourceAdaptorFactoInfo::OAIComAdobeCqSocialEnablementAdaptorsEnablementResourceAdaptorFactoInfo(QString json) { init(); this->fromJson(json); } OAIComAdobeCqSocialEnablementAdaptorsEnablementResourceAdaptorFactoInfo::OAIComAdobeCqSocialEnablementAdaptorsEnablementResourceAdaptorFactoInfo() { init(); } OAIComAdobeCqSocialEnablementAdaptorsEnablementResourceAdaptorFactoInfo::~OAIComAdobeCqSocialEnablementAdaptorsEnablementResourceAdaptorFactoInfo() { this->cleanup(); } void OAIComAdobeCqSocialEnablementAdaptorsEnablementResourceAdaptorFactoInfo::init() { pid = new QString(""); m_pid_isSet = false; title = new QString(""); m_title_isSet = false; description = new QString(""); m_description_isSet = false; properties = new OAIComAdobeCqSocialEnablementAdaptorsEnablementResourceAdaptorFactoProperties(); m_properties_isSet = false; } void OAIComAdobeCqSocialEnablementAdaptorsEnablementResourceAdaptorFactoInfo::cleanup() { if(pid != nullptr) { delete pid; } if(title != nullptr) { delete title; } if(description != nullptr) { delete description; } if(properties != nullptr) { delete properties; } } OAIComAdobeCqSocialEnablementAdaptorsEnablementResourceAdaptorFactoInfo* OAIComAdobeCqSocialEnablementAdaptorsEnablementResourceAdaptorFactoInfo::fromJson(QString json) { QByteArray array (json.toStdString().c_str()); QJsonDocument doc = QJsonDocument::fromJson(array); QJsonObject jsonObject = doc.object(); this->fromJsonObject(jsonObject); return this; } void OAIComAdobeCqSocialEnablementAdaptorsEnablementResourceAdaptorFactoInfo::fromJsonObject(QJsonObject pJson) { ::OpenAPI::setValue(&pid, pJson["pid"], "QString", "QString"); ::OpenAPI::setValue(&title, pJson["title"], "QString", "QString"); ::OpenAPI::setValue(&description, pJson["description"], "QString", "QString"); ::OpenAPI::setValue(&properties, pJson["properties"], "OAIComAdobeCqSocialEnablementAdaptorsEnablementResourceAdaptorFactoProperties", "OAIComAdobeCqSocialEnablementAdaptorsEnablementResourceAdaptorFactoProperties"); } QString OAIComAdobeCqSocialEnablementAdaptorsEnablementResourceAdaptorFactoInfo::asJson () { QJsonObject obj = this->asJsonObject(); QJsonDocument doc(obj); QByteArray bytes = doc.toJson(); return QString(bytes); } QJsonObject OAIComAdobeCqSocialEnablementAdaptorsEnablementResourceAdaptorFactoInfo::asJsonObject() { QJsonObject obj; if(pid != nullptr && *pid != QString("")){ toJsonValue(QString("pid"), pid, obj, QString("QString")); } if(title != nullptr && *title != QString("")){ toJsonValue(QString("title"), title, obj, QString("QString")); } if(description != nullptr && *description != QString("")){ toJsonValue(QString("description"), description, obj, QString("QString")); } if((properties != nullptr) && (properties->isSet())){ toJsonValue(QString("properties"), properties, obj, QString("OAIComAdobeCqSocialEnablementAdaptorsEnablementResourceAdaptorFactoProperties")); } return obj; } QString* OAIComAdobeCqSocialEnablementAdaptorsEnablementResourceAdaptorFactoInfo::getPid() { return pid; } void OAIComAdobeCqSocialEnablementAdaptorsEnablementResourceAdaptorFactoInfo::setPid(QString* pid) { this->pid = pid; this->m_pid_isSet = true; } QString* OAIComAdobeCqSocialEnablementAdaptorsEnablementResourceAdaptorFactoInfo::getTitle() { return title; } void OAIComAdobeCqSocialEnablementAdaptorsEnablementResourceAdaptorFactoInfo::setTitle(QString* title) { this->title = title; this->m_title_isSet = true; } QString* OAIComAdobeCqSocialEnablementAdaptorsEnablementResourceAdaptorFactoInfo::getDescription() { return description; } void OAIComAdobeCqSocialEnablementAdaptorsEnablementResourceAdaptorFactoInfo::setDescription(QString* description) { this->description = description; this->m_description_isSet = true; } OAIComAdobeCqSocialEnablementAdaptorsEnablementResourceAdaptorFactoProperties* OAIComAdobeCqSocialEnablementAdaptorsEnablementResourceAdaptorFactoInfo::getProperties() { return properties; } void OAIComAdobeCqSocialEnablementAdaptorsEnablementResourceAdaptorFactoInfo::setProperties(OAIComAdobeCqSocialEnablementAdaptorsEnablementResourceAdaptorFactoProperties* properties) { this->properties = properties; this->m_properties_isSet = true; } bool OAIComAdobeCqSocialEnablementAdaptorsEnablementResourceAdaptorFactoInfo::isSet(){ bool isObjectUpdated = false; do{ if(pid != nullptr && *pid != QString("")){ isObjectUpdated = true; break;} if(title != nullptr && *title != QString("")){ isObjectUpdated = true; break;} if(description != nullptr && *description != QString("")){ isObjectUpdated = true; break;} if(properties != nullptr && properties->isSet()){ isObjectUpdated = true; break;} }while(false); return isObjectUpdated; } }
[ "cliffano@gmail.com" ]
cliffano@gmail.com
bee43102a54a40ef7f5070815f42330f46198ded
01ccd20361d17b07f8e27a4c889f13248ca069f3
/Multiply.cpp
78da0b7ad6e0ca27be584e91c5ff03adfdad264d
[]
no_license
RoyHev/RoyAndIdanProject
78a523135877fde1cb9c1b48222b9fc75d91378a
4eeadff8d6c5edd90e8004c5b996d2d62ff4d68f
refs/heads/master
2020-04-11T23:46:31.498930
2018-12-27T18:43:50
2018-12-27T18:43:50
162,178,965
1
0
null
null
null
null
UTF-8
C++
false
false
329
cpp
// // Created by roy on 17/12/18. // #include "Multiply.h" //calculate the expression. double Multiply::calculate() { return this->getRightExp()->calculate() * this->getLeftExp()->calculate(); } //constrcutor. Multiply::Multiply(Expression *left, Expression *right) : BinaryExpression (left,right) { }
[ "Roy.hevrony@gmail.com" ]
Roy.hevrony@gmail.com
7f72b86da05470370e39cb78a06ccac50af5ff17
348e80a3b8c0c0a16fc36ef2d1034eac06da97aa
/PeraStartToolCom/PeraStartToolCom/ToolSetDlg.h
e40d09c2c0ccea9cde260e3b09c9f3b7fa2f07c5
[]
no_license
wyrover/WorkPlatForm
0e2c9127ccb6828857532eb11f96be3efc061fe9
f14a8cdd2bc3772ea4bd37a0381f5f8305a0a2c2
refs/heads/master
2021-01-16T21:16:13.672343
2016-01-17T08:59:01
2016-01-17T08:59:01
62,207,103
0
1
null
2016-06-29T07:56:29
2016-06-29T07:56:28
null
GB18030
C++
false
false
1,187
h
#pragma once #include "afxwin.h" #include "ToolsProUnity.h" #include "CxBCGPDialog.h" // CToolSetDlg 对话框 class CToolSetDlg : public CCxBCGPDialog { DECLARE_DYNAMIC(CToolSetDlg) public: CToolSetDlg(ToolObject *pTool,CWnd* pParent = NULL); // 标准构造函数 virtual ~CToolSetDlg(); // 对话框数据 enum { IDD = IDD_DIALOG_TOOLSET }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 DECLARE_MESSAGE_MAP() public: virtual BOOL OnInitDialog(); public: afx_msg void OnBnClickedButtonSelect(); afx_msg void OnBnClickedButtonTest(); afx_msg void OnBnClickedOk(); private: ToolObject *m_pTool; public: // 软件ID CString m_strToolId; // 软件名称 CString m_strToolName; // 绝对路径 CString m_strAbsPath; // 默认主键 CString m_strDefaultKey; // 备用主键 CString m_strReverseKey; // 注册表项 CString m_strKeyName; // 注册表键值项 CString m_strKeyValueName; // 启动路径 CString m_strRunPath; // 启动参数 CString m_strRunParam; // 启动名称 CString m_strRunName; // 本地配置绝对路径 CString m_strLocalPath; // 本地配置启动参数 CString m_strLocalRunParam; };
[ "cugxiangzhenwei@sina.cn" ]
cugxiangzhenwei@sina.cn
1cdd1b2a72da6b68637a65258d30e4f5794dfc33
b9a1f258079491bd4c7797893abc3b39763dbe5f
/content/renderer/service_worker/embedded_worker_instance_client_impl.cc
eb719cdc4480f882a93017295089919e54180006
[ "BSD-3-Clause" ]
permissive
slowfeed/browser-android-tabs
407194c1d61d62df85102b1a31518d3c0f05c8f3
a30495bc0ee14556d514f47744ed12420db85e2e
refs/heads/master
2020-03-17T10:30:25.716344
2018-05-08T07:54:33
2018-05-08T07:54:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,141
cc
// Copyright (c) 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/renderer/service_worker/embedded_worker_instance_client_impl.h" #include <memory> #include "base/memory/ptr_util.h" #include "base/strings/utf_string_conversions.h" #include "content/child/scoped_child_process_reference.h" #include "content/child/thread_safe_sender.h" #include "content/common/service_worker/embedded_worker_messages.h" #include "content/common/service_worker/service_worker_utils.h" #include "content/public/common/content_client.h" #include "content/renderer/service_worker/service_worker_context_client.h" #include "content/renderer/service_worker/web_service_worker_installed_scripts_manager_impl.h" #include "third_party/WebKit/public/platform/WebContentSettingsClient.h" #include "third_party/WebKit/public/platform/WebSecurityOrigin.h" #include "third_party/WebKit/public/platform/WebURL.h" #include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerInstalledScriptsManager.h" #include "third_party/WebKit/public/web/WebEmbeddedWorker.h" #include "third_party/WebKit/public/web/WebEmbeddedWorkerStartData.h" namespace content { EmbeddedWorkerInstanceClientImpl::WorkerWrapper::WorkerWrapper( std::unique_ptr<blink::WebEmbeddedWorker> worker) : worker_(std::move(worker)) {} EmbeddedWorkerInstanceClientImpl::WorkerWrapper::~WorkerWrapper() = default; // static void EmbeddedWorkerInstanceClientImpl::Create( base::TimeTicks blink_initialized_time, scoped_refptr<base::SingleThreadTaskRunner> io_thread_runner, mojom::EmbeddedWorkerInstanceClientAssociatedRequest request) { // This won't be leaked because the lifetime will be managed internally. // See the class documentation for detail. EmbeddedWorkerInstanceClientImpl* client = new EmbeddedWorkerInstanceClientImpl(std::move(io_thread_runner), std::move(request)); client->blink_initialized_time_ = blink_initialized_time; } void EmbeddedWorkerInstanceClientImpl::WorkerContextDestroyed() { DCHECK(wrapper_); TRACE_EVENT0("ServiceWorker", "EmbeddedWorkerInstanceClientImpl::WorkerContextDestroyed"); // Destroys |this|. wrapper_.reset(); } void EmbeddedWorkerInstanceClientImpl::StartWorker( mojom::EmbeddedWorkerStartParamsPtr params) { DCHECK(ChildThreadImpl::current()); DCHECK(!wrapper_); TRACE_EVENT0("ServiceWorker", "EmbeddedWorkerInstanceClientImpl::StartWorker"); service_manager::mojom::InterfaceProviderPtr interface_provider( std::move(params->provider_info->interface_provider)); auto client = std::make_unique<ServiceWorkerContextClient>( params->embedded_worker_id, params->service_worker_version_id, params->scope, params->script_url, !params->installed_scripts_info.is_null(), std::move(params->dispatcher_request), std::move(params->controller_request), std::move(params->service_worker_host), std::move(params->instance_host), std::move(params->provider_info), std::move(temporal_self_), ChildThreadImpl::current()->thread_safe_sender(), io_thread_runner_); client->set_blink_initialized_time(blink_initialized_time_); client->set_start_worker_received_time(base::TimeTicks::Now()); wrapper_ = StartWorkerContext(std::move(params), std::move(client), std::move(interface_provider)); } void EmbeddedWorkerInstanceClientImpl::StopWorker() { // StopWorker must be called after StartWorker is called. DCHECK(ChildThreadImpl::current()); DCHECK(wrapper_); TRACE_EVENT0("ServiceWorker", "EmbeddedWorkerInstanceClientImpl::StopWorker"); wrapper_->worker()->TerminateWorkerContext(); } void EmbeddedWorkerInstanceClientImpl::ResumeAfterDownload() { DCHECK(wrapper_); DCHECK(wrapper_->worker()); wrapper_->worker()->ResumeAfterDownload(); } void EmbeddedWorkerInstanceClientImpl::AddMessageToConsole( blink::WebConsoleMessage::Level level, const std::string& message) { DCHECK(wrapper_); DCHECK(wrapper_->worker()); wrapper_->worker()->AddMessageToConsole( blink::WebConsoleMessage(level, blink::WebString::FromUTF8(message))); } void EmbeddedWorkerInstanceClientImpl::BindDevToolsAgent( blink::mojom::DevToolsAgentAssociatedRequest request) { DCHECK(wrapper_); DCHECK(wrapper_->worker()); wrapper_->worker()->BindDevToolsAgent(request.PassHandle()); } EmbeddedWorkerInstanceClientImpl::EmbeddedWorkerInstanceClientImpl( scoped_refptr<base::SingleThreadTaskRunner> io_thread_runner, mojom::EmbeddedWorkerInstanceClientAssociatedRequest request) : binding_(this, std::move(request)), temporal_self_(this), io_thread_runner_(std::move(io_thread_runner)) { binding_.set_connection_error_handler(base::BindOnce( &EmbeddedWorkerInstanceClientImpl::OnError, base::Unretained(this))); } EmbeddedWorkerInstanceClientImpl::~EmbeddedWorkerInstanceClientImpl() {} void EmbeddedWorkerInstanceClientImpl::OnError() { // Destroys |this| if |temporal_self_| still owns this (i.e., StartWorker() // was not yet called). temporal_self_.reset(); } std::unique_ptr<EmbeddedWorkerInstanceClientImpl::WorkerWrapper> EmbeddedWorkerInstanceClientImpl::StartWorkerContext( mojom::EmbeddedWorkerStartParamsPtr params, std::unique_ptr<ServiceWorkerContextClient> context_client, service_manager::mojom::InterfaceProviderPtr interface_provider) { std::unique_ptr<blink::WebServiceWorkerInstalledScriptsManager> manager; // |installed_scripts_info| is null if scripts should be served by net layer, // when the worker is not installed, or the worker is launched for checking // the update. if (params->installed_scripts_info) { manager = WebServiceWorkerInstalledScriptsManagerImpl::Create( std::move(params->installed_scripts_info), io_thread_runner_); } auto wrapper = std::make_unique<WorkerWrapper>(blink::WebEmbeddedWorker::Create( std::move(context_client), std::move(manager), params->content_settings_proxy.PassHandle(), interface_provider.PassInterface().PassHandle())); blink::WebEmbeddedWorkerStartData start_data; start_data.script_url = params->script_url; start_data.user_agent = blink::WebString::FromUTF8(GetContentClient()->GetUserAgent("")); start_data.wait_for_debugger_mode = params->wait_for_debugger ? blink::WebEmbeddedWorkerStartData::kWaitForDebugger : blink::WebEmbeddedWorkerStartData::kDontWaitForDebugger; start_data.devtools_worker_token = params->devtools_worker_token; start_data.v8_cache_options = static_cast<blink::WebSettings::V8CacheOptions>(params->v8_cache_options); start_data.pause_after_download_mode = params->pause_after_download ? blink::WebEmbeddedWorkerStartData::kPauseAfterDownload : blink::WebEmbeddedWorkerStartData::kDontPauseAfterDownload; wrapper->worker()->StartWorkerContext(start_data); return wrapper; } } // namespace content
[ "artem@brave.com" ]
artem@brave.com
17addedcd25f340936fb56699b90b61152438a41
504143b06832a4af6fdcb90456683cd06cdf0496
/ManasaAndStones/ManasaAndStones.cpp
4ab39e58545255cb77c541878604d6d9160d512f
[ "MIT" ]
permissive
HPCCS/Computation-Kernel-Dataset
54666f16798bed55fde86d39d91ee92dc77ecaa8
5a184c7846c1abff39426a7f53fb837de8ba36e3
refs/heads/master
2020-05-07T15:15:12.258303
2019-04-21T03:11:12
2019-04-21T03:11:12
180,628,767
1
0
null
null
null
null
UTF-8
C++
false
false
790
cpp
// ManasaAndStones.cpp #include <bits/stdc++.h> // https://www.hackerrank.com/challenges/manasa-and-stones/problem #include <cmath> #include <iostream> #include <algorithm> #include <stdint.h> #include <set> using namespace std; void printPossibleScore(uint64_t n, uint64_t a, uint64_t b) { if(a > b) swap(a,b); set<uint64_t> l; --n; for(int i = 0; i <= n ; i++) l.insert(a*(n-i) + b*i); for(set<uint64_t>::iterator itr = l.begin();itr != l.end() ; itr++) cout<<*itr<<" "; cout<<"\n"; } int main() freopen("../input_files/ManasaAndStones", "r", stdin); { short T; cin >> T; int az=89; while(T > 0) { uint64_t n,a,b; cin>>n>>a>>b; az=89; printPossibleScore(n,a,b); --T; } return 0; }
[ "nicsimth@gmail.com" ]
nicsimth@gmail.com
838c8a9c60955b202baf598d2f46e37f716bd060
58eedd6e3df95f69e5f549220fb63aae8d405bcf
/engine/cw_app.hpp
179352dd987b877acc466b6b4fb45c41cf266235
[]
no_license
asdeviljay/Final-Project-Your-Game-Engine
ff0664688ecc6153ec8eb9f0b99a02bf5398b440
876ea6f538c557b1a2230c32a4aa9a6166f7a406
refs/heads/master
2020-07-02T23:33:25.713875
2019-08-11T02:36:54
2019-08-11T02:36:54
201,707,508
0
0
null
null
null
null
UTF-8
C++
false
false
1,777
hpp
/* * ===================================================================================== * * A simple game engine for ITGT533 * * Author: Chatchai Wangwiwattana * Adapted From: Pablo Colapinto * * ===================================================================================== */ #ifndef cw_app_INC #define cw_app_INC #include "glfw_window.hpp" #include "cw_time.hpp" namespace cw { class App{ private: CWTime systemTime; Window m_window; ImGuiIO* io; public: Window& window(); App(int w = 1280, int h = 720); /*----------------------------------------------------------------------------- * Start the Draw Loop *-----------------------------------------------------------------------------*/ void start(); /*----------------------------------------------------------------------------- * Properly terminate glfw when app closes *-----------------------------------------------------------------------------*/ ~App(); bool isUIUsingMouse() const { return io->WantCaptureMouse; } bool isUIUsingKeyboard() const { return io->WantCaptureKeyboard; } /*----------------------------------------------------------------------------- * Input Events *-----------------------------------------------------------------------------*/ virtual bool isKeyDown(int key) const; virtual void onUpdate( float dtSecond ) {} virtual void onDraw() {} virtual void onMouseMoveEvent(int x, int y){} virtual void onMouseEvent(int button, int action){} virtual void onKeyEvent(int key, int action){} }; } //cw:: #endif /* ----- #ifndef glut_app_INC ----- */
[ "jessada.sai@student.mahidol.ac.th" ]
jessada.sai@student.mahidol.ac.th
5b3655f2f07a8933ff2f0113dac72084572d0723
8954211050a47a99b01faa2bfae21400b75a9ed2
/graphs/cycles/eulerian-cycle.cpp
62797ee518e5250a740a8a5ef843f215012360a9
[]
no_license
strncat/algorithms-and-data-structures
a826db980385ef6cb04a690b211fe227f8eb1227
e576e123b916c00874f7aa0a1a86a77afc8df2ed
refs/heads/master
2021-07-13T09:52:13.545967
2020-07-06T04:54:17
2020-07-06T04:54:17
178,440,935
1
0
null
null
null
null
UTF-8
C++
false
false
3,978
cpp
// // Find the eulerian cycle in a graph // // Created by FB on 04/20/20. // Copyright © 2020 nemo. All rights reserved. // Source: https://algs4.cs.princeton.edu/41graph/EulerianCycle.java // https://strncat.github.io/jekyll/update/2020/05/02/euler.html #include <iostream> #include <vector> #include <limits.h> #include <queue> #include <map> #include <algorithm> #include <sstream> #include <set> #include <stack> typedef struct Edge { int v; int w; bool used; Edge(int v, int w) { this->v = v; this->w = w; this->used = false; } } Edge; int other_end(int v, Edge *e) { if (v == e->v) { return e->w; } else { return e->v; } } void dfs(std::vector<std::queue<Edge*>>& graph, std::set<int>& vertices) { std::stack<int> s; int start = *vertices.begin(); s.push(start); // start with some vertex v std::stack<int> cycle; // the actual cycle while (!s.empty()) { int current_node = s.top(); s.pop(); // pick some node // now traverse it's edges while (!graph[current_node].empty()) { // (a) consider an edge between the current node and any of its neighbors Edge *edge = graph[current_node].front(); graph[current_node].pop(); // remove the edge reference (it will still be in w's queue) // (b) if it's used then we'll check another. If it's not then mark it used if (edge->used) { continue; } edge->used = true; // mark it used // (c) push current_node back on the stack so we can go back to it (backtrack to it) s.push(current_node); // push current_node // (d) move to the other end of edge to process it current_node = other_end(current_node, edge); } // push the current_node which has no edges anymore to traverse cycle.push(current_node); } while (!cycle.empty()) { printf("%d ", cycle.top()); cycle.pop(); } printf("\n"); } bool hasEulerCycle(std::vector<int>& degrees, std::set<int>& vertices) { for (auto v = vertices.begin(); v != vertices.end(); v++) { if (degrees[*v] & 1) { // odd return false; } } return true; } void init_graph(std::vector<std::queue<Edge*>>& graph, std::vector<int>& degrees, std::set<int>& vertices) { // prepare graph to have 6 nodes for (int i = 0; i <= 6; i++) { graph.push_back(std::queue<Edge*>()); degrees.push_back(0); } vertices.insert(1); vertices.insert(2); vertices.insert(3); vertices.insert(4); vertices.insert(5); vertices.insert(6); Edge *e = new Edge(1,2); graph[1].push(e); graph[2].push(e); degrees[1]++; degrees[2]++; e = new Edge(2,3); graph[2].push(e); graph[3].push(e); degrees[2]++; degrees[3]++; e = new Edge(1,4); graph[1].push(e); graph[4].push(e); degrees[1]++; degrees[4]++; e = new Edge(5,3); graph[5].push(e); graph[3].push(e); degrees[5]++; degrees[3]++; e = new Edge(5,6); graph[5].push(e); graph[6].push(e); degrees[5]++; degrees[6]++; e = new Edge(2,6); graph[2].push(e); graph[6].push(e); degrees[2]++; degrees[6]++; e = new Edge(2,6); graph[2].push(e); graph[6].push(e); degrees[2]++; degrees[6]++; e = new Edge(4,6); graph[4].push(e); graph[6].push(e); degrees[4]++; degrees[6]++; } int main() { std::vector<std::queue<Edge*>> graph; std::vector<int> degrees; std::set<int> vertices; init_graph(graph, degrees, vertices); // every vertex must be of even degree, otherwise we don't have a cycle if (!hasEulerCycle(degrees, vertices)) { printf("An Eulerian Cycle doesn't exist\n"); } else { // otherwise, we must have an Eulerian cycle dfs(graph, vertices); // find it } return 0; }
[ "4132521+strncat@users.noreply.github.com" ]
4132521+strncat@users.noreply.github.com
64b525c73b6aa1fd8f7cb62f69c41e1ef6c3cfe8
5456502f97627278cbd6e16d002d50f1de3da7bb
/ui/gfx/geometry/rect_conversions.cc
d9e2d3592c3cd9050c4bda38a16c9271a8674fcd
[ "BSD-3-Clause" ]
permissive
TrellixVulnTeam/Chromium_7C66
72d108a413909eb3bd36c73a6c2f98de1573b6e5
c8649ab2a0f5a747369ed50351209a42f59672ee
refs/heads/master
2023-03-16T12:51:40.231959
2017-12-20T10:38:26
2017-12-20T10:38:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,994
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/gfx/geometry/rect_conversions.h" #include <algorithm> #include <cmath> #include "base/logging.h" #include "ui/gfx/geometry/safe_integer_conversions.h" namespace gfx { Rect ToEnclosingRect(const RectF& rect) { int min_x = ToFlooredInt(rect.x()); int min_y = ToFlooredInt(rect.y()); float max_x = rect.right(); float max_y = rect.bottom(); int width = rect.width() == 0 ? 0 : std::max( ToCeiledInt(static_cast<double>(ToCeiledInt(max_x)) - min_x), 0); int height = rect.height() == 0 ? 0 : std::max( ToCeiledInt(static_cast<double>(ToCeiledInt(max_y)) - min_y), 0); return Rect(min_x, min_y, width, height); } Rect ToEnclosedRect(const RectF& rect) { int min_x = ToCeiledInt(rect.x()); int min_y = ToCeiledInt(rect.y()); float max_x = rect.right(); float max_y = rect.bottom(); int width = std::max( ToFlooredInt(static_cast<float>(ToFlooredInt(max_x)) - min_x), 0); int height = std::max( ToFlooredInt(static_cast<float>(ToFlooredInt(max_y)) - min_y), 0); return Rect(min_x, min_y, width, height); } Rect ToNearestRect(const RectF& rect) { float float_min_x = rect.x(); float float_min_y = rect.y(); float float_max_x = rect.right(); float float_max_y = rect.bottom(); int min_x = ToRoundedInt(float_min_x); int min_y = ToRoundedInt(float_min_y); int max_x = ToRoundedInt(float_max_x); int max_y = ToRoundedInt(float_max_y); // If these DCHECKs fail, you're using the wrong method, consider using // ToEnclosingRect or ToEnclosedRect instead. DCHECK(std::abs(min_x - float_min_x) < 0.01f); DCHECK(std::abs(min_y - float_min_y) < 0.01f); DCHECK(std::abs(max_x - float_max_x) < 0.01f); DCHECK(std::abs(max_y - float_max_y) < 0.01f); return Rect(min_x, min_y, max_x - min_x, max_y - min_y); } bool IsNearestRectWithinDistance(const gfx::RectF& rect, float distance) { float float_min_x = rect.x(); float float_min_y = rect.y(); float float_max_x = rect.right(); float float_max_y = rect.bottom(); int min_x = ToRoundedInt(float_min_x); int min_y = ToRoundedInt(float_min_y); int max_x = ToRoundedInt(float_max_x); int max_y = ToRoundedInt(float_max_y); return (std::abs(min_x - float_min_x) < distance) && (std::abs(min_y - float_min_y) < distance) && (std::abs(max_x - float_max_x) < distance) && (std::abs(max_y - float_max_y) < distance); } Rect ToFlooredRectDeprecated(const RectF& rect) { return Rect(ToFlooredInt(rect.x()), ToFlooredInt(rect.y()), ToFlooredInt(rect.width()), ToFlooredInt(rect.height())); } } // namespace gfx
[ "lixiaodonglove7@aliyun.com" ]
lixiaodonglove7@aliyun.com
a607d7b18a99ded1adab3048b10e1444d28e68a0
03afdb8252a8a3b5c8aaa2fedcb2d419ceca4fcf
/src/panel.cpp
f829f8bdf199323403fe17502292f299ff4fe9af
[ "Apache-2.0" ]
permissive
mitre-cyber-academy/2014-grabbag-200A
c8b9dc0057a0dc545d7029929cbebd11a10aa656
283b85a36043c7847f0a0577ab2644a05e1f06eb
refs/heads/master
2021-01-16T20:34:19.916838
2015-02-15T23:16:03
2015-02-15T23:16:03
30,843,900
0
0
null
null
null
null
UTF-8
C++
false
false
1,316
cpp
#include "panel.h" panel::panel(bool a) { if(a) { top = 0; systems[0] = 1; systems[1] = 1; systems[2] = 1; systems[3] = 1; systems[4] = 1; } else { top = -1; systems[0] = 0; systems[1] = 0; systems[2] = 0; systems[3] = 0; systems[4] = 0; } } void panel::setSys1(void) { systems[0] = 1; } void panel::setSys2(void) { systems[1] = 1; } void panel::setSys3(void) { systems[2] = 1; } void panel::setSys4(void) { systems[3] = 1; } void panel::setSys5(void) { systems[4] = 1; } void panel::disSys1(void) { systems[0] = 0; } void panel::disSys2(void) { systems[1] = 0; } void panel::disSys3(void) { systems[2] = 0; } void panel::disSys4(void) { systems[3] = 0; } void panel::disSys5(void) { systems[4] = 0; } bool panel::getSys1(void) { return systems[0]; } bool panel::getSys2(void) { return systems[1]; } bool panel::getSys3(void) { return systems[2]; } bool panel::getSys4(void) { return systems[3]; } bool panel::getSys5(void) { return systems[4]; } int panel::getTop(void) { return top; } void panel::getNewTop(void) { if(systems[0] == 1) { top = 0; } else if(systems[1] == 1) { top = 1; } else if(systems[2] == 1) { top = 2; } else if(systems[3] == 1) { top = 3; } else if(systems[4] == 1) { top = 4; } else { top = -1; } }
[ "rbclark@mitre.org" ]
rbclark@mitre.org
45f56bf1a658472ed214f2c0de7c220203b52e00
c039644386bfadde050514836ebdd4208b0ffeb1
/ConsoleApplication1/Day19.cpp
0bf52b3183054025edfcd5b5ed3e86dec0cdd1be
[]
no_license
Diasiare/AdventOfCode2019
8f9ec5133cc12e0d7be3405c37c349d52a97e5c9
c27e60186b5d74565e040f63bdc9937dd98095e9
refs/heads/master
2020-09-22T10:01:56.454650
2019-12-26T16:23:18
2019-12-26T16:23:18
225,147,955
0
0
null
null
null
null
UTF-8
C++
false
false
5,325
cpp
#include "Day19.h" #include "Computer.h" #include <set> #include <map> #include <utility> #include <vector> #include <iostream> namespace day19 { class TractorBeamScanner : public computer::IODriver { public: int i = 0; bool x_next = true; std::map<int ,std::map<int, NUM_TYPE>> scan_results; NUM_TYPE Read() override { int out; if (x_next) out = i % 50; else { out = i / 50; } x_next = !x_next; return out; } void Write(NUM_TYPE v) override { scan_results[i / 50][i % 50] = v; i++; } bool Stop() override { return i >= 50 * 50; } }; int Day19::Part1() { std::vector<NUM_TYPE> input = { 109,424,203,1,21102,1,11,0,1105,1,282,21101,18,0,0,1106,0,259,2101,0,1,221,203,1,21102,1,31,0,1106,0,282,21101,0,38,0,1106,0,259,21002,23,1,2,22102,1,1,3,21101,0,1,1,21102,57,1,0,1106,0,303,2102,1,1,222,21002,221,1,3,21002,221,1,2,21101,0,259,1,21101,0,80,0,1105,1,225,21101,123,0,2,21101,91,0,0,1105,1,303,1201,1,0,223,20101,0,222,4,21101,259,0,3,21102,225,1,2,21101,0,225,1,21102,118,1,0,1105,1,225,21001,222,0,3,21102,58,1,2,21101,133,0,0,1105,1,303,21202,1,-1,1,22001,223,1,1,21102,1,148,0,1106,0,259,1201,1,0,223,20101,0,221,4,21002,222,1,3,21101,20,0,2,1001,132,-2,224,1002,224,2,224,1001,224,3,224,1002,132,-1,132,1,224,132,224,21001,224,1,1,21101,195,0,0,105,1,109,20207,1,223,2,20102,1,23,1,21101,-1,0,3,21102,214,1,0,1105,1,303,22101,1,1,1,204,1,99,0,0,0,0,109,5,2101,0,-4,249,22102,1,-3,1,22102,1,-2,2,22101,0,-1,3,21101,250,0,0,1105,1,225,21202,1,1,-4,109,-5,2105,1,0,109,3,22107,0,-2,-1,21202,-1,2,-1,21201,-1,-1,-1,22202,-1,-2,-2,109,-3,2106,0,0,109,3,21207,-2,0,-1,1206,-1,294,104,0,99,21201,-2,0,-2,109,-3,2106,0,0,109,5,22207,-3,-4,-1,1206,-1,346,22201,-4,-3,-4,21202,-3,-1,-1,22201,-4,-1,2,21202,2,-1,-1,22201,-4,-1,1,22102,1,-2,3,21102,1,343,0,1105,1,303,1105,1,415,22207,-2,-3,-1,1206,-1,387,22201,-3,-2,-3,21202,-2,-1,-1,22201,-3,-1,3,21202,3,-1,-1,22201,-3,-1,2,21201,-4,0,1,21102,1,384,0,1106,0,303,1105,1,415,21202,-4,-1,-4,22201,-4,-3,-4,22202,-3,-2,-2,22202,-2,-4,-4,22202,-3,-2,-3,21202,-4,-1,-2,22201,-3,-2,1,21201,1,0,-4,109,-5,2105,1,0 }; std::shared_ptr<TractorBeamScanner> scanner = std::make_shared<TractorBeamScanner>(); while (!scanner->Stop()) { computer::Computer c(input, scanner); c.Run(); } int accum = 0; for (auto row : scanner->scan_results) { for (auto point : row.second) { accum += point.second; } } return accum; } class TractorBeamChecker : public computer::IODriver { public: int x; int y; bool x_next = true; bool out = false; TractorBeamChecker(int x, int y) : x(x), y(y) {}; NUM_TYPE Read() override { if (x_next) { x_next = false; return x; } x_next = true; return y; } void Write(NUM_TYPE v) { out = v == 1; } }; bool CheckPoint(int x, int y, std::unordered_map<int, std::unordered_map<int, bool>> & cache) { auto it = cache[x].find(y); if (it != cache[x].end()) return it->second; std::vector<NUM_TYPE> input = { 109,424,203,1,21102,1,11,0,1105,1,282,21101,18,0,0,1106,0,259,2101,0,1,221,203,1,21102,1,31,0,1106,0,282,21101,0,38,0,1106,0,259,21002,23,1,2,22102,1,1,3,21101,0,1,1,21102,57,1,0,1106,0,303,2102,1,1,222,21002,221,1,3,21002,221,1,2,21101,0,259,1,21101,0,80,0,1105,1,225,21101,123,0,2,21101,91,0,0,1105,1,303,1201,1,0,223,20101,0,222,4,21101,259,0,3,21102,225,1,2,21101,0,225,1,21102,118,1,0,1105,1,225,21001,222,0,3,21102,58,1,2,21101,133,0,0,1105,1,303,21202,1,-1,1,22001,223,1,1,21102,1,148,0,1106,0,259,1201,1,0,223,20101,0,221,4,21002,222,1,3,21101,20,0,2,1001,132,-2,224,1002,224,2,224,1001,224,3,224,1002,132,-1,132,1,224,132,224,21001,224,1,1,21101,195,0,0,105,1,109,20207,1,223,2,20102,1,23,1,21101,-1,0,3,21102,214,1,0,1105,1,303,22101,1,1,1,204,1,99,0,0,0,0,109,5,2101,0,-4,249,22102,1,-3,1,22102,1,-2,2,22101,0,-1,3,21101,250,0,0,1105,1,225,21202,1,1,-4,109,-5,2105,1,0,109,3,22107,0,-2,-1,21202,-1,2,-1,21201,-1,-1,-1,22202,-1,-2,-2,109,-3,2106,0,0,109,3,21207,-2,0,-1,1206,-1,294,104,0,99,21201,-2,0,-2,109,-3,2106,0,0,109,5,22207,-3,-4,-1,1206,-1,346,22201,-4,-3,-4,21202,-3,-1,-1,22201,-4,-1,2,21202,2,-1,-1,22201,-4,-1,1,22102,1,-2,3,21102,1,343,0,1105,1,303,1105,1,415,22207,-2,-3,-1,1206,-1,387,22201,-3,-2,-3,21202,-2,-1,-1,22201,-3,-1,3,21202,3,-1,-1,22201,-3,-1,2,21201,-4,0,1,21102,1,384,0,1106,0,303,1105,1,415,21202,-4,-1,-4,22201,-4,-3,-4,22202,-3,-2,-2,22202,-2,-4,-4,22202,-3,-2,-3,21202,-4,-1,-2,22201,-3,-2,1,21201,1,0,-4,109,-5,2105,1,0 }; std::shared_ptr<TractorBeamChecker> scanner = std::make_shared<TractorBeamChecker>(x,y); computer::Computer c(input, scanner); c.Run(); cache[x][y] = scanner->out; return scanner->out; } int Day19::Part2() { int x_base = 10; int y_min = 0; std::unordered_map<int, std::unordered_map<int, bool>> cache; while (true) { std::cout << x_base << std::endl; int s_y_min = y_min; bool found_1 = false; for (int y = y_min; y <= x_base; y++) { int x = x_base - y; bool p1 = CheckPoint(x, y, cache); if (!found_1 && !p1) { y_min = y; continue; } else if (found_1 && !p1) break; found_1 = true; if (CheckPoint(x,y + 99, cache) && CheckPoint(x + 99, y, cache)) return x * 10000 + y; } //If there are no hits reset if (!found_1) y_min = s_y_min; x_base++; } } }
[ "fplymouth@gmail.com" ]
fplymouth@gmail.com
15605cbae8afb19eb296f165d5b4b8806c8133b4
9864c82c5350bc5929c4ac5f3dd90957bd089642
/MyFirstG/MyFirstG/Physics.cpp
aaa961932717c003d0db0a6f093fffaa8dd45370
[]
no_license
buidohuy99/Side-Projects
07793f15d773f0622cdc8797571a15a0de7cc015
e350a39277d6f9f32cde55c03a5531732cfdd566
refs/heads/master
2022-11-23T17:41:13.826946
2020-07-31T07:38:25
2020-07-31T07:38:25
204,811,907
0
0
null
null
null
null
UTF-8
C++
false
false
20,262
cpp
#include "Physics.h" #include "ObjBBox.h" #include "TileMap.h" #include "SceneManager.h" float epsilon=0.00001f; Physics::Physics(void) : X(0.0f), Y(0.0f), Width(0.0f), Height(0.0f), vX(0.0f), vY(0.0f), collisionSensors(nullptr), initted(false), movable(false), stuck(false) { } Physics::~Physics(void) { delete collisionSensors; } void Physics::setBodySize(float w,float h){ if(!initted) return; TileMap* current=SceneManager::getInstance()->getCurrentMap(); if(!current) return; float xIndent=(current->getMapXBounds().y - current->getMapWidth())/2; float yIndent=(current->getMapYBounds().y - current->getMapHeight())/2; float xOffset = collisionSensors->getCenter().x - X; float yOffset = collisionSensors->getCenter().y -Y; Width=w; Height=h; Width = Width < 0 ? 0 : Width>current->getMapWidth()*current->getTileWidth() ? current->getMapWidth()*current->getTileWidth() : Width; Height = Height < 0 ? 0 : Height>current->getMapHeight()*current->getTileHeight() ? current->getMapHeight()*current->getTileHeight() : Height; X = X<=xIndent + Width/2? xIndent + Width/2 : X>= xIndent + current->getMapWidth()*current->getTileWidth()-Width/2? xIndent + current->getMapWidth()*current->getTileWidth()-Width/2 : X; Y = Y<=yIndent+Height/2? yIndent+Height/2 : Y>= yIndent + current->getMapHeight()*current->getTileHeight()-Height/2? yIndent + current->getMapHeight()*current->getTileHeight() -Height/2 : Y; vX=0.0f; vY=0.0f; collisionSensors->changeBoxPlacements(glm::vec2(X+xOffset,Y+yOffset)); movable = false; stuck = false; } void Physics::setVelocity(float vx,float vy){ if(!initted) return; vX=vx; vY=vy; } bool Physics::initializeCollisionBox(){ if(!collisionSensors){ collisionSensors = new ObjBBox; if(!collisionSensors) return false; collisionSensors->initBox(getBodyCoords(),getBodySize()); return true; } return false; } //Overlook col void Physics::setBodyCoords(float x,float y){ if(!initted) return; TileMap* current=SceneManager::getInstance()->getCurrentMap(); if(!current) return; float xIndent=(current->getMapXBounds().y - current->getMapWidth())/2; float yIndent=(current->getMapYBounds().y - current->getMapHeight())/2; float xOffset = collisionSensors->getCenter().x - X; float yOffset = collisionSensors->getCenter().y -Y; X=x+xIndent; X = X<=xIndent + Width/2? xIndent + Width/2 : X>= xIndent + current->getMapWidth()*current->getTileWidth()-Width/2? xIndent + current->getMapWidth()*current->getTileWidth()-Width/2 : X; Y=y+yIndent; Y = Y<=yIndent+Height/2? yIndent+Height/2 : Y>= yIndent + current->getMapHeight()*current->getTileHeight()-Height/2? yIndent + current->getMapHeight()*current->getTileHeight() -Height/2 : Y; vX=0.0f; vY=0.0f; collisionSensors->changeBoxPlacements(glm::vec2(X+xOffset,Y+yOffset)); movable = false; stuck = false; } void Physics::changeCollisionBoxAttrib(glm::vec2 newPos, glm::vec2 newSize){ if(!initted) return; TileMap* current=SceneManager::getInstance()->getCurrentMap(); if(!current) return; float xIndent=(current->getMapXBounds().y - current->getMapWidth())/2; float yIndent=(current->getMapYBounds().y - current->getMapHeight())/2; //Resize newSize.x = newSize.x <0.0f ? 0.0f : newSize.x > current->getMapWidth()*current->getTileWidth() ? current->getMapWidth()*current->getTileWidth() : newSize.x; newSize.y = newSize.y <0.0f ? 0.0f : newSize.y > current->getMapHeight()*current->getTileHeight() ? current->getMapHeight()*current->getTileHeight() : newSize.y; collisionSensors->changeBoxSize(newSize); float colWidthHalf=collisionSensors->getDistToEdges().x; float colHeightHalf=collisionSensors->getDistToEdges().y; //Change position newPos.x = newPos.x - colWidthHalf< 0.0f ? colWidthHalf + xIndent: newPos.x + colWidthHalf > current->getMapWidth()*current->getTileWidth() ? xIndent +current->getMapWidth()*current->getTileWidth() - colWidthHalf : newPos.x + xIndent; newPos.y = newPos.y - colHeightHalf < 0.0f ? colHeightHalf + yIndent : newPos.y + colHeightHalf > current->getMapHeight()*current->getTileHeight() ? yIndent + current->getMapHeight()*current->getTileHeight() - colHeightHalf : newPos.y + yIndent; collisionSensors->changeBoxPlacements(newPos); vX=0.0f; vY=0.0f; movable = false; stuck = false; } bool Physics::initPhysicsBody(glm::vec2 pos, glm::vec2 span){ if(initted) return false; TileMap* current=SceneManager::getInstance()->getCurrentMap(); if(!current) return false; float xIndent=(current->getMapXBounds().y - current->getMapWidth())/2; float yIndent=(current->getMapYBounds().y - current->getMapHeight())/2; Width=span.x; Height=span.y; Width = Width < 0 ? 0 : Width>current->getMapWidth()*current->getTileWidth() ? current->getMapWidth()*current->getTileWidth() : Width; Height = Height < 0 ? 0 : Height>current->getMapHeight()*current->getTileHeight() ? current->getMapHeight()*current->getTileHeight() : Height; X=pos.x + xIndent; X = X<=xIndent + Width/2? xIndent + Width/2 : X>= xIndent + current->getMapWidth()*current->getTileWidth()-Width/2? xIndent + current->getMapWidth()*current->getTileWidth()-Width/2 : X; Y=pos.y + yIndent; Y = Y<=yIndent+Height/2? yIndent+Height/2 : Y>= yIndent + current->getMapHeight()*current->getTileHeight()-Height/2? yIndent + current->getMapHeight()*current->getTileHeight() -Height/2 : Y; if(!initializeCollisionBox()) return false; initted=true; return true; } bool Physics::updateOnMap(float delta){ TileMap* current=SceneManager::getInstance()->getCurrentMap(); if(!current) return false; if(!initted) return false; float xIndent=(current->getMapXBounds().y - current->getMapWidth())/2; float yIndent=(current->getMapYBounds().y - current->getMapHeight())/2; float colWidthHalf=collisionSensors->getDistToEdges().x; float colHeightHalf=collisionSensors->getDistToEdges().y; float centerX=collisionSensors->getCenter().x; float centerY=collisionSensors->getCenter().y; float offsetX = centerX - X, offsetY = centerY -Y; //Can't update position if stucked if(stuck) return false; //Check collision: if(movable){ //Step X float newX = centerX + vX*delta; newX = newX<=xIndent + colWidthHalf? xIndent + colWidthHalf : newX>= xIndent + current->getMapWidth()*current->getTileWidth()-colWidthHalf? xIndent + current->getMapWidth()*current->getTileWidth()-colWidthHalf : newX; //Init top and Foot bounds float botY = centerY - colHeightHalf , topY = centerY + colHeightHalf; unsigned int footTile = floor((botY-yIndent)/current->getTileHeight()); unsigned int headTile = floor((topY-yIndent)/current->getTileHeight()); unsigned int higherBounds; if(footTile!=headTile) higherBounds = topY == headTile*current->getTileHeight() + yIndent ? headTile -1 : headTile; else higherBounds = headTile; if(newX - centerX >0) { //Left side of tile contains right of colBox float rightXOrigin = xIndent + floor((centerX+colWidthHalf-xIndent)/current->getTileWidth())*current->getTileWidth(); //limit movement to max 1 tile if(abs(newX -centerX)>current->getTileWidth()) newX = centerX + current->getTileWidth(); //Find tile of bottom right of colBox unsigned int rightTile = floor((centerX+colWidthHalf-xIndent)/current->getTileWidth()); if(rightTile == current->getMapWidth()) goto StepY; //Precheck current if(centerX + colWidthHalf == rightXOrigin) { if( rightTile == 0 ){ X = newX - offsetX ; goto StepY; } for(unsigned int i = footTile;i<=higherBounds;i++){ //Find tile collision status unsigned int currentTileCollision = current -> getColMask(rightTile, i); //Check if current right side is on any collision edge unsigned int prevTileCollision = current->getColMask(rightTile-1, i); if(prevTileCollision&1 || (currentTileCollision>>2)&1 ) goto StepY; int botOfTile = i*current->getTileHeight() + yIndent, topOfTile = botOfTile + current->getTileHeight(); if((currentTileCollision>>1)&1 && botOfTile > (centerY-colHeightHalf) && botOfTile<(centerY+colHeightHalf)) goto StepY; if((currentTileCollision>>3)&1 && topOfTile > (centerY-colHeightHalf) && topOfTile<(centerY+colHeightHalf)) goto StepY; } } //If on last column step normally if(rightTile == current->getMapWidth()-1) {X = newX - offsetX ; goto StepY;} //Check move if(newX + colWidthHalf > rightXOrigin + current->getTileWidth()) { for(unsigned int i = footTile;i<=higherBounds;i++){ //Find tile collision status unsigned int currentTileCollision = current -> getColMask(rightTile, i); //Check collision: unsigned int nextTileCollision = current->getColMask(rightTile + 1, i); if((nextTileCollision >> 2 )&1 || currentTileCollision &1 ){ X = rightXOrigin + current->getTileWidth()- colWidthHalf-offsetX; goto StepY; } //Check for horizontal int botOfTile = i*current->getTileHeight() + yIndent, topOfTile = botOfTile + current->getTileHeight(); if(((nextTileCollision>>1)&1 && botOfTile > (centerY-colHeightHalf) && botOfTile<(centerY+colHeightHalf)) || ((nextTileCollision>>3)&1 && topOfTile > (centerY-colHeightHalf) && topOfTile<(centerY+colHeightHalf)) ){ X = rightXOrigin + current->getTileWidth()- colWidthHalf-offsetX; goto StepY; } } } } else if(newX - centerX <0) { float leftXOrigin = xIndent + floor((centerX-colWidthHalf-xIndent)/current->getTileWidth())*current->getTileWidth(); if(abs(newX -centerX)>current->getTileWidth()) newX = centerX - current->getTileWidth(); unsigned int leftTile = floor((centerX-colWidthHalf-xIndent)/current->getTileWidth()); //Step freely if(leftTile == 0) {X = newX - offsetX;goto StepY;} //Precheck if(centerX - colWidthHalf == leftXOrigin) { if(leftTile == current->getMapWidth()) { X = newX - offsetX; goto StepY; } for(unsigned int i = footTile;i<=higherBounds;i++){ unsigned int currentTileCollision = current->getColMask(leftTile, i); //Check if current left side is on any collision edge unsigned int prevTileCollision = current->getColMask(leftTile -1, i); if(prevTileCollision&1 || (currentTileCollision>>2)&1 ) goto StepY; int botOfTile = i*current->getTileHeight() + yIndent, topOfTile = botOfTile + current->getTileHeight(); if((currentTileCollision>>1)&1 && botOfTile > (centerY-colHeightHalf) && botOfTile<(centerY+colHeightHalf)) goto StepY; if((currentTileCollision>>3)&1 && topOfTile > (centerY-colHeightHalf) && topOfTile<(centerY+colHeightHalf)) goto StepY; } } //Check move if(newX - colWidthHalf < leftXOrigin) { for(unsigned int i = footTile;i<=higherBounds;i++){ unsigned int currentTileCollision = current->getColMask(leftTile, i); //Check collision: unsigned int nextTileCollision = current->getColMask(leftTile - 1, i); if(nextTileCollision&1 || (currentTileCollision>>2) &1 ){ X = leftXOrigin + colWidthHalf-offsetX; goto StepY; } //Check for horizontal int botOfTile = i*current->getTileHeight() + yIndent, topOfTile = botOfTile + current->getTileHeight(); if(((nextTileCollision>>1)&1 && botOfTile > (centerY-colHeightHalf) && botOfTile<(centerY+colHeightHalf)) || ((nextTileCollision>>3)&1 && topOfTile > (centerY-colHeightHalf) && topOfTile<(centerY+colHeightHalf)) ){ X = leftXOrigin + colWidthHalf-offsetX; goto StepY; } } } } X = newX-offsetX; //Step Y StepY: //Reupdate: collisionSensors->changeBoxPlacements(glm::vec2(X+offsetX,centerY)); centerX=collisionSensors->getCenter().x; //Continue; float newY = centerY + vY*delta; newY = newY<=yIndent+colHeightHalf? yIndent+colHeightHalf : newY>= yIndent + current->getMapHeight()*current->getTileHeight()-colHeightHalf? yIndent + current->getMapHeight()*current->getTileHeight() -colHeightHalf : newY; //Init bounds for Tile checking float leftX = centerX - colWidthHalf, rightX = centerX + colWidthHalf; unsigned int leftTile = floor((leftX-xIndent)/current->getTileWidth()); unsigned int rightTile = floor((rightX-xIndent)/current->getTileWidth()); if(leftTile!=rightTile) higherBounds = rightX == rightTile*current->getTileWidth() + xIndent ? rightTile -1 : rightTile; else higherBounds = rightTile; //Left side of tile contains top of colBox float topYOrigin = yIndent + floor((centerY+colHeightHalf-yIndent)/current->getTileHeight())*current->getTileHeight(); //Find tile of top of colBox unsigned int topTile = floor((centerY+colHeightHalf-yIndent)/current->getTileHeight()); float botYOrigin = yIndent + floor((centerY-colWidthHalf-yIndent)/current->getTileHeight())*current->getTileHeight(); unsigned int botTile = floor((centerY-colHeightHalf-yIndent)/current->getTileHeight()); if(newY - centerY >0) { //limit movement to max 1 tile if(abs(newY -centerY)>current->getTileHeight()) newY = centerY + current->getTileHeight(); if(topTile == current->getMapHeight()) goto EndUpdate; //Precheck if(centerY + colHeightHalf == topYOrigin){ if(topTile == 0) { Y = newY -offsetY; goto EndUpdate; } for(unsigned int i = leftTile;i<=higherBounds;i++){ //Find tile collision status unsigned int currentTileCollision = current -> getColMask(i, topTile); //Check if current top side is on any collision edge unsigned int prevTileCollision = current->getColMask(i, topTile-1); if((prevTileCollision>>3)&1 || (currentTileCollision>>1)&1 ) goto EndUpdate; int leftOfTile = i*current->getTileWidth() + xIndent, rightOfTile = leftOfTile + current->getTileWidth(); if((currentTileCollision>>2)&1 && leftOfTile > (centerX-colWidthHalf) && leftOfTile<(centerX+colWidthHalf)) goto EndUpdate; if((currentTileCollision>>0)&1 && rightOfTile > (centerX-colWidthHalf) && rightOfTile<(centerX+colWidthHalf)) goto EndUpdate; } } //If on last row step normally if(topTile == current->getMapHeight()-1) {Y = newY - offsetY; goto EndUpdate;} //Check move if(newY + colHeightHalf > topYOrigin + current->getTileHeight()){ for(unsigned int i = leftTile;i<=higherBounds;i++){ unsigned int currentTileCollision = current -> getColMask(i, topTile); //Check collision: unsigned int nextTileCollision = current->getColMask(i, topTile+1); if((nextTileCollision >> 1 )&1 || (currentTileCollision>>3) &1 ){ Y = topYOrigin + current->getTileHeight()- colHeightHalf-offsetY; goto EndUpdate; } //Check for vertical int leftOfTile = i*current->getTileWidth() + xIndent, rightOfTile = leftOfTile + current->getTileWidth(); if(((nextTileCollision>>2)&1 && leftOfTile > (centerX-colWidthHalf) && leftOfTile<(centerX+colWidthHalf)) || ((nextTileCollision>>0)&1 && rightOfTile > (centerX-colWidthHalf) && rightOfTile<(centerX+colWidthHalf)) ){ Y = topYOrigin + current->getTileHeight()- colHeightHalf-offsetY; goto EndUpdate; } } } } else if(newY - centerY <0) { if(abs(newY -centerY)>current->getTileHeight()) newY = centerY + current->getTileHeight(); //Step freely if(botTile == 0) {Y = newY -offsetY;goto EndUpdate;} if(centerY - colHeightHalf == botYOrigin) { if(botTile == current->getMapHeight()) { Y = newY - offsetY ; goto EndUpdate; } for(unsigned int i = leftTile;i<=higherBounds;i++){ unsigned int currentTileCollision = current->getColMask(i, botTile); //Check if current left side is on any collision edge unsigned int prevTileCollision = current->getColMask(i, botTile-1); if((prevTileCollision>>3)&1 || (currentTileCollision>>1)&1 ) goto EndUpdate; int leftOfTile = i*current->getTileWidth() + xIndent, rightOfTile = leftOfTile + current->getTileWidth(); if((currentTileCollision>>2)&1 && leftOfTile > (centerX-colWidthHalf) && leftOfTile<(centerX+colWidthHalf)) goto EndUpdate; if((currentTileCollision>>0)&1 && rightOfTile > (centerX-colWidthHalf) && rightOfTile<(centerX+colWidthHalf)) goto EndUpdate; } } //If not collide stepY if(newY - colHeightHalf < botYOrigin) { for(unsigned int i = leftTile;i<=higherBounds;i++){ unsigned int currentTileCollision = current->getColMask(i, botTile); //Check collision: unsigned int nextTileCollision = current->getColMask(i, botTile-1); if((nextTileCollision >> 3 )&1 || (currentTileCollision>>1) &1 ){ Y = botYOrigin + colWidthHalf-offsetY; goto EndUpdate; } //Check for vertical int leftOfTile = i*current->getTileWidth() + xIndent, rightOfTile = leftOfTile + current->getTileWidth(); if(((nextTileCollision>>2)&1 && leftOfTile > (centerX-colWidthHalf) && leftOfTile<(centerX+colWidthHalf)) || ((nextTileCollision>>0)&1 && rightOfTile > (centerX-colWidthHalf) && rightOfTile<(centerX+colWidthHalf)) ){ Y = botYOrigin + colWidthHalf-offsetY; goto EndUpdate; } } } } Y = newY - offsetY; EndUpdate: //Reupdate: collisionSensors->changeBoxPlacements(glm::vec2(centerX,Y+offsetY)); } else { //No update if not on Map if(centerX+ colWidthHalf<xIndent ||centerX-colWidthHalf> xIndent + current->getMapWidth()*current->getTileWidth()) return false; if(centerY+colHeightHalf<yIndent || centerY-colHeightHalf>yIndent + current->getMapHeight()*current->getTileHeight()) return false; //Correct if colBox is in Map centerX = centerX<=xIndent + colWidthHalf? xIndent + colWidthHalf : centerX>= xIndent + current->getMapWidth()*current->getTileWidth()-colWidthHalf? xIndent + current->getMapWidth()*current->getTileWidth()-colWidthHalf : centerX; centerY = centerY<=yIndent+colHeightHalf? yIndent+colHeightHalf : centerY>= yIndent + current->getMapHeight()*current->getTileHeight()-colHeightHalf? yIndent + current->getMapHeight()*current->getTileHeight() -colHeightHalf : centerY; //Calculate true Y for collision float botY = centerY - colHeightHalf , topY = centerY + colHeightHalf; float leftX = centerX - colWidthHalf, rightX = centerX + colWidthHalf; unsigned int leftTile = floor((leftX-xIndent)/current->getTileWidth()); unsigned int rightTile = floor((rightX-xIndent)/current->getTileWidth()); unsigned int footTile = floor((botY-yIndent)/current->getTileHeight()); unsigned int headTile = floor((topY-yIndent)/current->getTileHeight()); try{ unsigned int higherBoundsX, higherBoundsY; if(leftTile!=rightTile) higherBoundsX = rightX == rightTile*current->getTileWidth() + xIndent ? rightTile -1 : rightTile; else higherBoundsX = rightTile; if(footTile!=headTile) higherBoundsY = topY == headTile*current->getTileHeight() + yIndent ? headTile -1 : headTile; else higherBoundsY = headTile; for(unsigned int i=leftTile;i<=higherBoundsX;i++){ for(unsigned int j=footTile;j<=higherBoundsY;j++){ if(current->getColMask(i,j) == 15) throw 1; if(i != higherBoundsX){ if((current->getColMask(i,j)>>0)&1) throw 1; } if(i != leftTile){ if((current->getColMask(i,j)>>2)&1) throw 1; } if(j != higherBoundsY){ if((current->getColMask(i,j)>>3)&1) throw 1; } if(j != footTile){ if((current->getColMask(i,j)>>1)&1) throw 1; } } } } catch(int a){ switch(a){ case 1 : stuck = true; printf_s("Cannot Initialize Body's current tile because overlaps collidable edges, please reevaluate"); break; } return false; } movable = true; } return true; } glm::vec2 Physics::getBottomLeft(){ return glm::vec2(X - Width/2, Y - Height/2); } glm::vec2 Physics::getBodyCoords(){ return glm::vec2(X,Y); } glm::vec2 Physics::getBodySize(){ return glm::vec2(Width,Height); } glm::vec2 Physics::getVelocity(){ return glm::vec2(vX,vY); } bool Physics::getInitState(){ return initted; } bool Physics::getMovable(){ return movable; }
[ "buido.huy99@gmail.com" ]
buido.huy99@gmail.com
5e4f932f4c9dd55b6de7309ddb6a0f493505cb09
9923a00a9afcd97c2fb02f6ed615adea3fc3fe1d
/Branch/Deprecated/Gps/NMEA0183/DCN.HPP
4550968be2f8b83610caebf394ca3faf55d1992e
[ "MIT" ]
permissive
Tsinghua-OpenICV/OpenICV
93df0e3dda406a5b8958f50ee763756a45182bf3
3bdb2ba744fabe934b31e36ba9c1e6ced2d5e6fc
refs/heads/master
2022-03-02T03:09:02.236509
2021-12-26T08:09:42
2021-12-26T08:09:42
225,785,128
13
9
null
2020-08-06T02:42:03
2019-12-04T05:17:57
C++
UTF-8
C++
false
false
2,317
hpp
#if ! defined( DCN_CLASS_HEADER ) #define DCN_CLASS_HEADER /* Author: Samuel R. Blackburn Internet: wfc@pobox.com "You can get credit for something or get it done, but not both." Dr. Richard Garwin The MIT License (MIT) Copyright (c) 1996-2015 Sam Blackburn 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. */ typedef enum { BasisUnknown = 0, NormalPatternBasis, LaneIdentificationPatternBasis, LaneIdentificationTransmissionsBasis } FIX_DATA_BASIS; class DCN : public RESPONSE { public: DCN(); virtual ~DCN(); /* ** Data */ int DeccaChainID; LINE_OF_POSITION Red; LINE_OF_POSITION Green; LINE_OF_POSITION Purple; NMEA0183_BOOLEAN RedLineNavigationUse; NMEA0183_BOOLEAN GreenLineNavigationUse; NMEA0183_BOOLEAN PurpleLineNavigationUse; double PositionUncertaintyNauticalMiles; FIX_DATA_BASIS Basis; /* ** Methods */ virtual void Empty( void ) override; virtual bool Parse( const SENTENCE& sentence ) override; virtual bool Write( SENTENCE& sentence ) override; /* ** Operators */ virtual const DCN& operator = ( const DCN& source ); }; #endif // DCN_CLASS_HEADER
[ "synsin0@outlook.com" ]
synsin0@outlook.com
dc6f1fc9d5876bd32ba9bc0dfd10a4f5eaa6d69c
6627d27fc69922f179b14b612b366bbf0bc4eff9
/robots/gopigo3xerofull/src/ledsubsystem/LEDSubsystemBlinkAction.h
a8ef81f828e6136cb37ec30cddb6c4b5e20cfedd
[]
no_license
errorcodexero/newarch
1a4773377197174ae58b6e4ef6d670bf197c643b
e69a864012e09548014ad208affeb8901835a654
refs/heads/master
2021-06-03T16:28:41.840622
2020-03-15T18:15:08
2020-03-15T18:15:08
139,747,384
9
6
null
2020-01-31T05:35:34
2018-07-04T16:54:36
C++
UTF-8
C++
false
false
1,265
h
#pragma once #include "LEDSubsystemAction.h" #include "LEDSubsystem.h" namespace xero { namespace gopigo3 { class LEDSubsystem; class LEDSubsystemBlinkAction : public LEDSubsystemAction { public: LEDSubsystemBlinkAction(LEDSubsystem &sub, LEDSubsystem::LED led, double on, double off, double r, double g, double b); virtual ~LEDSubsystemBlinkAction(); /// \brief Start the duty cycle action. This method actually sets the /// motor duty cycles. virtual void start(); /// \brief Run the duty cycle action. This method does nothing. virtual void run(); /// \brief Signals if this action is done, always returs true virtual bool isDone(); /// \brief Canel the current action, stops the motors and returns true virtual void cancel(); /// \brief Returns a human readable string for the action virtual std::string toString(); private: void turnonoff(bool on); private: LEDSubsystem::LED led_; double r_; double g_; double b_; double on_; double off_; double start_; bool state_; }; } // namespace gopigo3 } // namespace xero
[ "butchg@comcast.net" ]
butchg@comcast.net