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
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 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
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
ffdf5c631296bafb3c52141acf90273505d77966
ba8603ae6f0df3480c85c51f3717dfdda0435ea2
/Source/VehicleCombatGameCPP/Base/Base_TimerItem.h
54587a31b18395360a066c929d4973460ea9d3de
[]
no_license
Needix/VehicularCombatGame_CPP
909abba06e1908761ab2d870164511a8e9befcfc
2c6d9ca5812b1329b2d7be83e9cd6796a2b09bb0
refs/heads/master
2020-03-18T02:33:18.395607
2018-06-10T19:53:59
2018-06-10T19:53:59
134,196,255
1
0
null
null
null
null
UTF-8
C++
false
false
581
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "Engine/Texture2D.h" #include "Base/Base_Item.h" #include "Base_TimerItem.generated.h" /** * A item which gets enabled after a click and stays active for a certain amount of time */ UCLASS() class VEHICLECOMBATGAMECPP_API ABase_TimerItem : public ABase_Item { GENERATED_BODY() private: bool IsEnabled = false; protected: float Timer = 0; protected: virtual void UseTick(float delta); public: void Tick(float delta) override; };
[ "needcoding@gmail.com" ]
needcoding@gmail.com
e7cbfb502b4aca4306369cb6654f6e275b149345
b61f44a0d3bb70ff42b1627f2fd064d0ceb20561
/src/version.h
f74fe6e4460bae3987d0b40cec0bae580bb40f9b
[ "MIT" ]
permissive
xrobau/stablecoin
1e1dd664ff59f0f78816a8804ab59f74c16fc819
664c5d22f7abf4a6621c36d3961e4e0d9ae20131
refs/heads/master
2021-01-15T23:27:59.504027
2013-06-23T21:13:53
2013-06-23T21:13:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,667
h
// Copyright (c) 2012 The Bitcoin developers // Copyright (c) 2012 Litecoin Developers // Copyright (c) 2013 StableCoin Developers // Copyright (c) 2013 StableCoin Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_VERSION_H #define BITCOIN_VERSION_H #include <string> // // client versioning // // These need to be macro's, as version.cpp's voodoo requires it #define CLIENT_VERSION_MAJOR 0 #define CLIENT_VERSION_MINOR 6 #define CLIENT_VERSION_REVISION 3 #define CLIENT_VERSION_BUILD 0 static const int CLIENT_VERSION = 1000000 * CLIENT_VERSION_MAJOR + 10000 * CLIENT_VERSION_MINOR + 100 * CLIENT_VERSION_REVISION + 1 * CLIENT_VERSION_BUILD; extern const std::string CLIENT_NAME; extern const std::string CLIENT_BUILD; extern const std::string CLIENT_DATE; // // network protocol versioning // static const int PROTOCOL_VERSION = 60001; // earlier versions not supported as of Feb 2012, and are disconnected static const int MIN_PROTO_VERSION = 209; // nTime field added to CAddress, starting with this version; // if possible, avoid requesting addresses nodes older than this static const int CADDR_TIME_VERSION = 31402; // only request blocks from nodes outside this range of versions static const int NOBLKS_VERSION_START = 32000; static const int NOBLKS_VERSION_END = 32400; // BIP 0031, pong message, is enabled for all versions AFTER this one static const int BIP0031_VERSION = 60000; #endif
[ "stablecoin@live.com" ]
stablecoin@live.com
9dd991c87db2d51b0b34183098531e736ce22d4c
0e76671d6bff742b45b10eeadf373d72414c05c1
/benchmarks/bm1_put_get.cpp
eb57731bdcaaa7fc7ccc835d7607659018afaceb
[]
no_license
victorj44/851_project
35e6f3916d1756b7d01fc2dd1141928099037946
d4f671310f75fef4988e483a89a0d6cd32e669ae
refs/heads/master
2021-01-19T05:53:24.000214
2012-05-18T01:48:02
2012-05-18T01:48:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,248
cpp
/* ************************************** * benchmark 1 - pure reads * 10^6 elements in hash maps * 10^8 gets per hash map * - C++11 unordered_map * - Boost hash_map * - gcc/ext hash_map * - linear hashing w/ tabulation * - linear hashing w/ mult.hash. * - quadr hashing w/ tabulation * - quadr hashing w/ mult.hash. */ #include <cstdio> #include <sys/time.h> #include <unistd.h> #include <ctime> #include <tr1/unordered_map> //#include <boost/unordered_map.hpp> #include <ext/hash_map> #include "../tabulationHash/tabulationHash.h" #include "../multiplicationHash/multiplicationHash.h" #include "../linearProbing/linearHash.h" #include "../quadraticProbing/quadraticProbing.h" #include "../cuckooHashing/cuckooHashing.h" const int64 NELEM = 1000*1000; const int64 HMSIZE = 2*1000*1000; //hash map size; effectively load = NELEM/HMSIZE; const int64 NREADS = 1;//*1000*1000; int64 elems[NELEM]; //keys inserted int64 perm[NELEM]; //random permutation of those keys double timediff(struct timeval before, struct timeval after) { return ((after.tv_sec * 1000000 + after.tv_usec) - (before.tv_sec * 1000000 + before.tv_usec))/1000000.0; } void testC11um() { std::tr1::unordered_map<int64, int64> hm; struct timeval before, after; //start timer; gettimeofday(&before, NULL); for (int i = 0; i < NELEM; i++) hm[elems[i]] = 10; //we don't care about the value int value = 123; int ncalls = 0; for (int i = 0; i < NREADS; i++) for (int j = 0; j < NELEM; j++) { value = hm[perm[j]]; ncalls++; //just to make sure the compiler won't optimize us "out" } //finish timer; gettimeofday(&after, NULL); printf("%lf sec\n", timediff(before, after)); } void testBoostHm() { //skip boost for now before i figure out how to install it printf("boost not tested\n"); } void testGccExtHm() { //gnu hash_map does not support 64-bit keys... what a fail //i hope this would correctly, despite that keys will be downcasted to 32bits __gnu_cxx::hash_map<int, long long> hm; struct timeval before, after; //start timer; gettimeofday(&before, NULL); for (int i = 0; i < NELEM; i++) hm[elems[i]] = (int64)10; //we don't care about the value int value = 123; int ncalls = 0; for (int i = 0; i < NREADS; i++) for (int j = 0; j < NELEM; j++) { value = hm[perm[j]]; ncalls++; //just to make sure the compiler won't optimize us "out" } //finish timer; gettimeofday(&after, NULL); printf("%lf sec\n", timediff(before, after)); } void testHMB(HashMapBase<int64> *hm) { struct timeval before, after; //start timer; gettimeofday(&before, NULL); for (int i = 0; i < NELEM; i++) hm->put(elems[i], 10); //hm[elems[i]] = (int64)10; //we don't care about the value int64 value = 123; int ncalls = 0; for (int i = 0; i < NREADS; i++) for (int j = 0; j < NELEM; j++) { //value = hm[perm[j]]; hm->get(perm[j], value); ncalls++; //just to make sure the compiler won't optimize us "out" } //finish timer; gettimeofday(&after, NULL); printf("%lf sec\n", timediff(before, after)); } int main() { printf("***** MAKE SURE IT'S COMPILED WITH -O2!\n"); srand(time(NULL)); for (int i = 0; i < NELEM; i++) elems[i] = rand(); for (int i = 0; i < NELEM; i++) perm[i] = elems[rand() % NELEM]; printf("C++11 Unordered Map:\n"); testC11um(); printf("Boost hash_map:\n"); testBoostHm(); printf("GCC/ext hash_map:\n"); testGccExtHm(); HashFunction *tabh = new TabulationHash(HMSIZE); HashFunction *mulh = new MultiplicationHash(HMSIZE); printf("*** Linear with tabulation:\n"); HashMapBase<int64> *hm = new LinearHash<int64>(HMSIZE, tabh); testHMB(hm); delete hm; hm = new LinearHash<int64>(HMSIZE, mulh); printf("*** Linear with multiplication:\n"); testHMB(hm); delete hm; hm = new QuadraticProbing<int64>(HMSIZE, tabh); printf("**** Quadratic with tabulation:\n"); testHMB(hm); delete hm; hm = new QuadraticProbing<int64>(HMSIZE, mulh); printf("**** Quadratic with multiplication:\n"); testHMB(hm); delete hm; int d = 4; // The number of Cuckoo tables HashFunction **tabhArr = new HashFunction*[d]; HashFunction **mulhArr = new HashFunction*[d]; for (int i = 0; i < d; ++i) { tabhArr[i] = new TabulationHash(HMSIZE); mulhArr[i] = new MultiplicationHash(HMSIZE); } hm = new CuckooHashing<int64>(HMSIZE, tabhArr, d); printf("***** Cuckoo with tabulation:\n"); testHMB(hm); delete hm; hm = new CuckooHashing<int64>(HMSIZE, mulhArr, d); printf("***** Cuckoo with multiplication:\n"); testHMB(hm); delete hm; /*HashFunction **tabhSmallArr = new HashFunction*[d]; HashFunction **mulhSmallArr = new HashFunction*[d]; for (int i = 0; i < d; ++i) { tabhSmallArr[i] = new TabulationHash(HMSIZE / d); mulhSmallArr[i] = new MultiplicationHash(HMSIZE / d); } hm = new CuckooHashing<int64>(HMSIZE / d, tabhSmallArr, d); printf("***** Cuckoo with small table and tabulation:\n"); testHMB(hm); delete hm; hm = new CuckooHashing<int64>(HMSIZE / d, mulhSmallArr, d); printf("***** Cuckoo with small table and multiplication:\n"); testHMB(hm); delete hm; */ return 0; }
[ "sanja89@gmail.com" ]
sanja89@gmail.com
ff6b90234be409103027b8cd595bbd7970ae4676
4476dd05f9be3b80d95037d49f6b52c1569ab27b
/060/square.cc
8ebd3d04e57f4fcc33a7290e575c559344fc11e8
[]
no_license
haampie/project-euler
481e55815c42a0252cac5fddb18da78757a45665
000dc0a4b58a001b9538b7782fcf5098d509d76e
refs/heads/master
2021-01-04T02:31:55.545112
2018-11-09T18:57:15
2018-11-09T18:57:15
71,645,124
0
0
null
null
null
null
UTF-8
C++
false
false
1,109
cc
#include <iostream> #include <vector> #include <algorithm> #include <iomanip> // 10^k p1 + p2 mod 30 = 10*(p1 mod 30) + (p2 mod 30) mod 30 // 10^k p2 + p1 mod 30 = 10*(p2 mod 30) + (p1 mod 30) mod 30 // Idea: take two potential primes p1 & p2, not divisable // by 2, 3 and 5, and see whether 10^k p1 + p2 and vice versa // is part of a 30-wheel modulo class. inline bool is_candidate(size_t x, size_t y, std::vector<size_t> const &wheel) { return std::binary_search(wheel.begin(), wheel.end(), (10 * x + y) % 30) && std::binary_search(wheel.begin(), wheel.end(), (10 * y + x) % 30); } int main() { std::vector<size_t> wheel{1, 7, 11, 13, 17, 19, 23, 29}; std::cout << std::setw(4) << ' '; for (size_t y = 0; y != wheel.size(); ++y) std::cout << std::setw(4) << wheel[y]; std::cout << '\n'; for (size_t y = 0; y != wheel.size(); ++y) { std::cout << std::setw(4) << wheel[y]; for (size_t x = 0; x != wheel.size(); ++x) { std::cout << std::setw(4) << (is_candidate(wheel[x], wheel[y], wheel) ? 'y' : 'n'); } std::cout << '\n'; } std::cout << '\n'; }
[ "harmenstoppels@gmail.com" ]
harmenstoppels@gmail.com
03d814bb5bc849b8cedc6cade8f69f01639cabcc
64c27514d5d29150121ca2b97b43b042f706cd5f
/Contest/BKDN_Stack_Queue/DS3_3/main.cpp
e396ac1af771cc7d65b5ce0ca6957a62c8e9e98e
[]
no_license
tienit150198/ACM
f4fdb8eaeccd3db02624c593e56f0fa5d233bee1
a17c9ae1402376167dec5dd49a8aa508ad824285
refs/heads/master
2020-06-12T09:50:50.137304
2019-06-28T13:27:48
2019-06-28T13:27:48
194,261,865
1
0
null
null
null
null
UTF-8
C++
false
false
644
cpp
#include <bits/stdc++.h> #define ll long long int #define Max 1000007 #define fast ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); using namespace std; ll n, num = 1; stack<ll> s; int main() { fast // freopen("input.in", "r", stdin); cin >> n; while(n--){ ll q, x; cin >> q; if(q == 1){ cin >> x; if(s.empty()){ s.push(x); }else s.push(max(x,s.top())); }else if(q == 2){ if(!s.empty()) s.pop(); }else if(q == 3){ cout << s.top() << endl; } } return 0; }
[ "tienit150198@gmail.com" ]
tienit150198@gmail.com
8ec980de3e1d4023f6eb2388d9c7df3f56dc189a
1865967c509eecfe1de951fcffd956af8ac7ca9e
/GeeksForGeeks_TopicWise/Queues/Queue Using Two Stacks.cpp
0160202b590c649c20b8d7d0b4b6574d144c4b34
[]
no_license
avinashmallik62/SDE_PROBLEMS
ba11441725278184dad9cc32229741cb13dffe06
40ad7fac9325b1710d4a9dd03e55fff3e9d427a2
refs/heads/main
2022-12-20T17:15:04.041098
2020-10-06T18:44:50
2020-10-06T18:44:50
300,574,941
2
8
null
2020-10-07T10:42:41
2020-10-02T10:09:19
C++
UTF-8
C++
false
false
1,264
cpp
#include<bits/stdc++.h> using namespace std; class StackQueue{ private: stack<int> s1; stack<int> s2; public: void push(int B); int pop(); }; int main() { int T; cin>>T; while(T--) { StackQueue *sq = new StackQueue(); int Q; cin>>Q; while(Q--){ int QueryType=0; cin>>QueryType; if(QueryType==1) { int a; cin>>a; sq->push(a); }else if(QueryType==2){ cout<<sq->pop()<<" "; } } cout<<endl; } } // } Driver Code Ends /* The structure of the class is class StackQueue{ private: // These are STL stacks ( http://goo.gl/LxlRZQ ) stack<int> s1; stack<int> s2; public: void push(int); int pop(); }; */ /* The method push to push element into the queue */ void StackQueue :: push(int x) { s1.push(x); } /*The method pop which return the element poped out of the queue*/ int StackQueue :: pop() { if(s1.empty()) return -1; while(s1.size() != 1) { s2.push(s1.top()); s1.pop(); } int ans = s1.top(); s1.pop(); while(!s2.empty()) { s1.push(s2.top()); s2.pop(); } return ans; }
[ "silentknight5245@gmail.com" ]
silentknight5245@gmail.com
9369547c90c1976cddf490793ba2d595396931f3
9618aeab5df07ffd1d4f204c8cc3af1a2345d420
/ui/ozone/platform/wayland/wayland_buffer_manager_unittest.cc
6c262a840f83569cc20523909e0817c7d11d2cfe
[ "BSD-3-Clause" ]
permissive
dmt3o/chromium
3709c0c73e37aec82dc44d2bbe234d1f1829c32f
d368d5937f235033bd495a57005587ab275536b4
refs/heads/master
2022-12-19T04:43:33.801508
2020-10-02T02:56:57
2020-10-02T02:56:57
279,344,900
0
0
BSD-3-Clause
2020-10-02T02:50:00
2020-07-13T15:43:43
null
UTF-8
C++
false
false
49,260
cc
// Copyright 2019 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/ozone/platform/wayland/gpu/wayland_buffer_manager_gpu.h" #include "ui/ozone/platform/wayland/host/wayland_buffer_manager_host.h" #include <drm_fourcc.h> #include <memory> #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/test/mock_callback.h" #include "mojo/public/cpp/system/platform_handle.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/gfx/linux/drm_util_linux.h" #include "ui/ozone/platform/wayland/gpu/wayland_surface_gpu.h" #include "ui/ozone/platform/wayland/host/wayland_connection.h" #include "ui/ozone/platform/wayland/host/wayland_zwp_linux_dmabuf.h" #include "ui/ozone/platform/wayland/test/mock_surface.h" #include "ui/ozone/platform/wayland/test/mock_zwp_linux_dmabuf.h" #include "ui/ozone/platform/wayland/test/test_zwp_linux_buffer_params.h" #include "ui/ozone/platform/wayland/test/wayland_test.h" using testing::_; namespace ui { namespace { using MockTerminateGpuCallback = base::MockCallback<base::OnceCallback<void(std::string)>>; constexpr gfx::Size kDefaultSize(1024, 768); struct InputData { bool has_file = false; gfx::Size size; uint32_t planes_count = 0; std::vector<uint32_t> strides; std::vector<uint32_t> offsets; std::vector<uint64_t> modifiers; uint32_t format = 0; uint32_t buffer_id = 0; }; class MockSurfaceGpu : public WaylandSurfaceGpu { public: MockSurfaceGpu(WaylandBufferManagerGpu* buffer_manager, gfx::AcceleratedWidget widget) : buffer_manager_(buffer_manager), widget_(widget) { buffer_manager_->RegisterSurface(widget_, this); } ~MockSurfaceGpu() { buffer_manager_->UnregisterSurface(widget_); } MOCK_METHOD2(OnSubmission, void(uint32_t buffer_id, const gfx::SwapResult& swap_result)); MOCK_METHOD2(OnPresentation, void(uint32_t buffer_id, const gfx::PresentationFeedback& feedback)); private: WaylandBufferManagerGpu* const buffer_manager_; const gfx::AcceleratedWidget widget_; DISALLOW_COPY_AND_ASSIGN(MockSurfaceGpu); }; } // namespace class WaylandBufferManagerTest : public WaylandTest { public: WaylandBufferManagerTest() = default; ~WaylandBufferManagerTest() override = default; void SetUp() override { WaylandTest::SetUp(); manager_host_ = connection_->buffer_manager_host(); EXPECT_TRUE(manager_host_); // Use the helper methods below, which automatically set the termination // callback and bind the interface again if the manager failed. manager_host_->SetTerminateGpuCallback(callback_.Get()); auto interface_ptr = manager_host_->BindInterface(); buffer_manager_gpu_->Initialize(std::move(interface_ptr), {}, false); } protected: base::ScopedFD MakeFD() { base::FilePath temp_path; EXPECT_TRUE(base::CreateTemporaryFile(&temp_path)); auto file = base::File(temp_path, base::File::FLAG_READ | base::File::FLAG_WRITE | base::File::FLAG_CREATE_ALWAYS); return base::ScopedFD(file.TakePlatformFile()); } // Sets the terminate gpu callback expectation, calls OnChannelDestroyed, // sets the same callback again and re-establishes mojo connection again // for convenience. void SetTerminateCallbackExpectationAndDestroyChannel( MockTerminateGpuCallback* callback, bool fail) { if (!fail) { // To avoid warning messages as "Expected to be never called, but has 0 // WillOnce()s", split the expecations based on the expected call times. EXPECT_CALL(*callback, Run(_)).Times(0); } else { EXPECT_CALL(*callback, Run(_)) .Times(1) .WillRepeatedly(::testing::Invoke([this, callback](std::string) { manager_host_->OnChannelDestroyed(); manager_host_->SetTerminateGpuCallback(callback->Get()); auto interface_ptr = manager_host_->BindInterface(); // Recreate the gpu side manager (the production code does the // same). buffer_manager_gpu_ = std::make_unique<WaylandBufferManagerGpu>(); buffer_manager_gpu_->Initialize(std::move(interface_ptr), {}, false); })); } } void CreateDmabufBasedBufferAndSetTerminateExpectation( bool fail, uint32_t buffer_id, base::ScopedFD fd = base::ScopedFD(), const gfx::Size& size = kDefaultSize, const std::vector<uint32_t>& strides = {1}, const std::vector<uint32_t>& offsets = {2}, const std::vector<uint64_t>& modifiers = {3}, uint32_t format = DRM_FORMAT_R8, uint32_t planes_count = 1) { if (!fd.is_valid()) fd = MakeFD(); SetTerminateCallbackExpectationAndDestroyChannel(&callback_, fail); buffer_manager_gpu_->CreateDmabufBasedBuffer( std::move(fd), kDefaultSize, strides, offsets, modifiers, format, planes_count, buffer_id); Sync(); } void CreateShmBasedBufferAndSetTerminateExpecation( bool fail, uint32_t buffer_id, const gfx::Size& size = kDefaultSize, size_t length = 0) { SetTerminateCallbackExpectationAndDestroyChannel(&callback_, fail); if (!length) length = size.width() * size.height() * 4; buffer_manager_gpu_->CreateShmBasedBuffer(MakeFD(), length, size, buffer_id); Sync(); } void DestroyBufferAndSetTerminateExpectation(gfx::AcceleratedWidget widget, uint32_t buffer_id, bool fail) { SetTerminateCallbackExpectationAndDestroyChannel(&callback_, fail); buffer_manager_gpu_->DestroyBuffer(widget, buffer_id); Sync(); } void ProcessCreatedBufferResourcesWithExpectation(size_t expected_size, bool fail) { auto params_vector = server_.zwp_linux_dmabuf_v1()->buffer_params(); // To ensure, no other buffers are created, test the size of the vector. EXPECT_EQ(params_vector.size(), expected_size); for (auto* mock_params : params_vector) { if (!fail) { zwp_linux_buffer_params_v1_send_created(mock_params->resource(), mock_params->buffer_resource()); } else { zwp_linux_buffer_params_v1_send_failed(mock_params->resource()); } } } std::unique_ptr<WaylandWindow> CreateWindow( PlatformWindowType type = PlatformWindowType::kWindow, gfx::AcceleratedWidget parent_widget = gfx::kNullAcceleratedWidget) { testing::Mock::VerifyAndClearExpectations(&delegate_); PlatformWindowInitProperties properties; properties.bounds = gfx::Rect(0, 0, 800, 600); properties.type = type; properties.parent_widget = parent_widget; auto new_window = WaylandWindow::Create(&delegate_, connection_.get(), std::move(properties)); EXPECT_TRUE(new_window); Sync(); EXPECT_NE(new_window->GetWidget(), gfx::kNullAcceleratedWidget); return new_window; } MockTerminateGpuCallback callback_; WaylandBufferManagerHost* manager_host_; private: DISALLOW_COPY_AND_ASSIGN(WaylandBufferManagerTest); }; TEST_P(WaylandBufferManagerTest, CreateDmabufBasedBuffers) { constexpr uint32_t kDmabufBufferId = 1; EXPECT_CALL(*server_.zwp_linux_dmabuf_v1(), CreateParams(_, _, _)).Times(1); CreateDmabufBasedBufferAndSetTerminateExpectation(false /*fail*/, kDmabufBufferId); DestroyBufferAndSetTerminateExpectation(gfx::kNullAcceleratedWidget, kDmabufBufferId, false /*fail*/); } TEST_P(WaylandBufferManagerTest, VerifyModifiers) { constexpr uint32_t kDmabufBufferId = 1; constexpr uint32_t kFourccFormatR8 = DRM_FORMAT_R8; constexpr uint64_t kFormatModiferLinear = DRM_FORMAT_MOD_LINEAR; const std::vector<uint64_t> kFormatModifiers{DRM_FORMAT_MOD_INVALID, kFormatModiferLinear}; // Tests that fourcc format is added, but invalid modifier is ignored first. // Then, when valid modifier comes, it is stored. for (const auto& modifier : kFormatModifiers) { uint32_t modifier_hi = modifier >> 32; uint32_t modifier_lo = modifier & UINT32_MAX; zwp_linux_dmabuf_v1_send_modifier(server_.zwp_linux_dmabuf_v1()->resource(), kFourccFormatR8, modifier_hi, modifier_lo); Sync(); auto buffer_formats = connection_->zwp_dmabuf()->supported_buffer_formats(); DCHECK_EQ(buffer_formats.size(), 1u); DCHECK_EQ(buffer_formats.begin()->first, GetBufferFormatFromFourCCFormat(kFourccFormatR8)); auto modifiers = buffer_formats.begin()->second; if (modifier == DRM_FORMAT_MOD_INVALID) { DCHECK_EQ(modifiers.size(), 0u); } else { DCHECK_EQ(modifiers.size(), 1u); DCHECK_EQ(modifiers[0], modifier); } } EXPECT_CALL(*server_.zwp_linux_dmabuf_v1(), CreateParams(_, _, _)).Times(1); CreateDmabufBasedBufferAndSetTerminateExpectation( false /*fail*/, kDmabufBufferId, base::ScopedFD(), kDefaultSize, {1}, {2}, {kFormatModiferLinear}, kFourccFormatR8, 1); Sync(); auto params_vector = server_.zwp_linux_dmabuf_v1()->buffer_params(); EXPECT_EQ(params_vector.size(), 1u); EXPECT_EQ(params_vector[0]->modifier_hi_, kFormatModiferLinear >> 32); EXPECT_EQ(params_vector[0]->modifier_lo_, kFormatModiferLinear & UINT32_MAX); // Clean up. DestroyBufferAndSetTerminateExpectation(gfx::kNullAcceleratedWidget, kDmabufBufferId, false /*fail*/); } TEST_P(WaylandBufferManagerTest, CreateShmBasedBuffers) { constexpr uint32_t kShmBufferId = 1; CreateShmBasedBufferAndSetTerminateExpecation(false /*fail*/, kShmBufferId); DestroyBufferAndSetTerminateExpectation(gfx::kNullAcceleratedWidget, kShmBufferId, false /*fail*/); } TEST_P(WaylandBufferManagerTest, ValidateDataFromGpu) { const InputData kBadInputs[] = { // All zeros. {}, // Valid file but zeros everywhereelse. {true}, // Valid file, invalid size, zeros elsewhere. {true, {kDefaultSize.width(), 0}}, {true, {0, kDefaultSize.height()}}, // Valid file and size but zeros in other fields. {true, kDefaultSize}, // Vectors have different lengths. {true, kDefaultSize, 1, {1}, {2, 3}, {4, 5, 6}}, // Vectors have same lengths but strides have a zero. {true, kDefaultSize, 1, {0}, {2}, {6}}, // Vectors are valid but buffer format is not. {true, kDefaultSize, 1, {1}, {2}, {6}}, // Everything is correct but the buffer ID is zero. {true, kDefaultSize, 1, {1}, {2}, {6}, DRM_FORMAT_R8}, }; for (const auto& bad : kBadInputs) { EXPECT_CALL(*server_.zwp_linux_dmabuf_v1(), CreateParams(_, _, _)).Times(0); base::ScopedFD dummy; CreateDmabufBasedBufferAndSetTerminateExpectation( true /*fail*/, bad.buffer_id, bad.has_file ? MakeFD() : std::move(dummy), bad.size, bad.strides, bad.offsets, bad.modifiers, bad.format, bad.planes_count); } } TEST_P(WaylandBufferManagerTest, CreateAndDestroyBuffer) { const uint32_t kBufferId1 = 1; const uint32_t kBufferId2 = 2; const gfx::AcceleratedWidget widget = window_->GetWidget(); // This section tests that it is impossible to create buffers with the same // id if they haven't been assigned to any surfaces yet. { EXPECT_CALL(*server_.zwp_linux_dmabuf_v1(), CreateParams(_, _, _)).Times(2); CreateDmabufBasedBufferAndSetTerminateExpectation(false /*fail*/, kBufferId1); CreateDmabufBasedBufferAndSetTerminateExpectation(false /*fail*/, kBufferId2); // Can't create buffer with existing id. CreateDmabufBasedBufferAndSetTerminateExpectation(true /*fail*/, kBufferId2); } // ... impossible to create buffers with the same id if one of them // has already been attached to a surface. { EXPECT_CALL(*server_.zwp_linux_dmabuf_v1(), CreateParams(_, _, _)).Times(1); CreateDmabufBasedBufferAndSetTerminateExpectation(false /*fail*/, kBufferId1); buffer_manager_gpu_->CommitBuffer(widget, kBufferId1, window_->GetBounds()); CreateDmabufBasedBufferAndSetTerminateExpectation(true /*fail*/, kBufferId1); } // ... impossible to destroy non-existing buffer. { // Either it is attached... DestroyBufferAndSetTerminateExpectation(widget, kBufferId1, true /*fail*/); // Or not attached. DestroyBufferAndSetTerminateExpectation(gfx::kNullAcceleratedWidget, kBufferId1, true /*fail*/); } // ... impossible to try to destroy an attached buffer if the widget is not // specified. { EXPECT_CALL(*server_.zwp_linux_dmabuf_v1(), CreateParams(_, _, _)).Times(1); CreateDmabufBasedBufferAndSetTerminateExpectation(false /*fail*/, kBufferId1); buffer_manager_gpu_->CommitBuffer(widget, kBufferId1, window_->GetBounds()); DestroyBufferAndSetTerminateExpectation(gfx::kNullAcceleratedWidget, kBufferId1, true /*fail*/); } // Still can destroy the buffer even if it has not been attached to any // widgets. { EXPECT_CALL(*server_.zwp_linux_dmabuf_v1(), CreateParams(_, _, _)).Times(1); CreateDmabufBasedBufferAndSetTerminateExpectation(false /*fail*/, kBufferId1); DestroyBufferAndSetTerminateExpectation(widget, kBufferId1, false /*fail*/); } // ... impossible to destroy buffers twice. { EXPECT_CALL(*server_.zwp_linux_dmabuf_v1(), CreateParams(_, _, _)).Times(3); CreateDmabufBasedBufferAndSetTerminateExpectation(false /*fail*/, kBufferId1); // Attach to a surface. buffer_manager_gpu_->CommitBuffer(widget, kBufferId1, window_->GetBounds()); // Created non-attached buffer as well. CreateDmabufBasedBufferAndSetTerminateExpectation(false /*fail*/, kBufferId2); DestroyBufferAndSetTerminateExpectation(widget, kBufferId1, false /*fail*/); // Can't destroy the buffer with non-existing id (the manager cleared the // state after the previous failure). DestroyBufferAndSetTerminateExpectation(widget, kBufferId1, true /*fail*/); // Non-attached buffer must have been also destroyed (we can't destroy it // twice) if there was a failure. DestroyBufferAndSetTerminateExpectation(gfx::kNullAcceleratedWidget, kBufferId2, true /*fail*/); // Create and destroy non-attached buffer twice. CreateDmabufBasedBufferAndSetTerminateExpectation(false /*fail*/, kBufferId2); DestroyBufferAndSetTerminateExpectation(gfx::kNullAcceleratedWidget, kBufferId2, false /*fail*/); DestroyBufferAndSetTerminateExpectation(gfx::kNullAcceleratedWidget, kBufferId2, true /*fail*/); } } TEST_P(WaylandBufferManagerTest, CommitBufferNonExistingBufferId) { EXPECT_CALL(*server_.zwp_linux_dmabuf_v1(), CreateParams(_, _, _)).Times(1); CreateDmabufBasedBufferAndSetTerminateExpectation(false /*fail*/, 1u); // Can't commit for non-existing buffer id. SetTerminateCallbackExpectationAndDestroyChannel(&callback_, true /*fail*/); buffer_manager_gpu_->CommitBuffer(window_->GetWidget(), 5u, window_->GetBounds()); Sync(); } TEST_P(WaylandBufferManagerTest, CommitBufferNullWidget) { constexpr uint32_t kBufferId = 1; EXPECT_CALL(*server_.zwp_linux_dmabuf_v1(), CreateParams(_, _, _)).Times(1); CreateDmabufBasedBufferAndSetTerminateExpectation(false /*fail*/, kBufferId); // Can't commit for non-existing widget. SetTerminateCallbackExpectationAndDestroyChannel(&callback_, true /*fail*/); buffer_manager_gpu_->CommitBuffer(gfx::kNullAcceleratedWidget, kBufferId, window_->GetBounds()); Sync(); } TEST_P(WaylandBufferManagerTest, EnsureCorrectOrderOfCallbacks) { constexpr uint32_t kBufferId1 = 1; constexpr uint32_t kBufferId2 = 2; const gfx::AcceleratedWidget widget = window_->GetWidget(); const gfx::Rect bounds = gfx::Rect({0, 0}, kDefaultSize); window_->SetBounds(bounds); MockSurfaceGpu mock_surface_gpu(buffer_manager_gpu_.get(), widget_); auto* linux_dmabuf = server_.zwp_linux_dmabuf_v1(); EXPECT_CALL(*linux_dmabuf, CreateParams(_, _, _)).Times(2); CreateDmabufBasedBufferAndSetTerminateExpectation(false /*fail*/, kBufferId1); CreateDmabufBasedBufferAndSetTerminateExpectation(false /*fail*/, kBufferId2); Sync(); ProcessCreatedBufferResourcesWithExpectation(2u /* expected size */, false /* fail */); auto* mock_surface = server_.GetObject<wl::MockSurface>(widget); constexpr uint32_t kNumberOfCommits = 3; EXPECT_CALL(*mock_surface, Attach(_, _, _)).Times(kNumberOfCommits); EXPECT_CALL(*mock_surface, Frame(_)).Times(kNumberOfCommits); EXPECT_CALL(*mock_surface, Commit()).Times(kNumberOfCommits); // All the other expectations must come in order. ::testing::InSequence sequence; EXPECT_CALL(mock_surface_gpu, OnSubmission(kBufferId1, gfx::SwapResult::SWAP_ACK)) .Times(1); // wp_presentation must not exist now. This means that the buffer // manager must send synthetized presentation feedbacks. ASSERT_TRUE(!connection_->presentation()); EXPECT_CALL(mock_surface_gpu, OnPresentation(kBufferId1, _)).Times(1); buffer_manager_gpu_->CommitBuffer(widget, kBufferId1, bounds); Sync(); // As long as there hasn't any previous buffer attached (nothing to release // yet), it must be enough to just send a frame callback back. mock_surface->SendFrameCallback(); Sync(); // Commit second buffer now. buffer_manager_gpu_->CommitBuffer(widget, kBufferId2, bounds); Sync(); EXPECT_CALL(mock_surface_gpu, OnSubmission(kBufferId2, gfx::SwapResult::SWAP_ACK)) .Times(1); EXPECT_CALL(mock_surface_gpu, OnPresentation(kBufferId2, _)).Times(1); mock_surface->ReleasePrevAttachedBuffer(); mock_surface->SendFrameCallback(); Sync(); // wp_presentation is available now. auto* mock_wp_presentation = server_.EnsureWpPresentation(); ASSERT_TRUE(mock_wp_presentation); Sync(); // Now, the wp_presentation object exists and there must be a real feedback // sent. Ensure the order now. ASSERT_TRUE(connection_->presentation()); EXPECT_CALL(*mock_wp_presentation, Feedback(_, _, mock_surface->resource(), _)) .Times(1); // Commit second buffer now. buffer_manager_gpu_->CommitBuffer(widget, kBufferId1, bounds); Sync(); // Even though, the server send the presentation feeedback, the host manager // must make sure the order of the submission and presentation callbacks is // correct. Thus, no callbacks must be received by the MockSurfaceGpu. EXPECT_CALL(mock_surface_gpu, OnSubmission(_, _)).Times(0); EXPECT_CALL(mock_surface_gpu, OnPresentation(_, _)).Times(0); mock_wp_presentation->SendPresentationCallback(); Sync(); EXPECT_CALL(mock_surface_gpu, OnSubmission(kBufferId1, gfx::SwapResult::SWAP_ACK)) .Times(1); EXPECT_CALL(mock_surface_gpu, OnPresentation(kBufferId1, _)).Times(1); // Now, send the release callback. The host manager must send the submission // and presentation callbacks in correct order. mock_surface->ReleasePrevAttachedBuffer(); Sync(); DestroyBufferAndSetTerminateExpectation(widget, kBufferId1, false /*fail*/); DestroyBufferAndSetTerminateExpectation(widget, kBufferId2, false /*fail*/); } TEST_P(WaylandBufferManagerTest, DestroyedBuffersGeneratePresentationFeedbackFailure) { constexpr uint32_t kBufferId1 = 1; constexpr uint32_t kBufferId2 = 2; constexpr uint32_t kBufferId3 = 3; const gfx::AcceleratedWidget widget = window_->GetWidget(); const gfx::Rect bounds = gfx::Rect({0, 0}, kDefaultSize); window_->SetBounds(bounds); MockSurfaceGpu mock_surface_gpu(buffer_manager_gpu_.get(), widget_); auto* linux_dmabuf = server_.zwp_linux_dmabuf_v1(); EXPECT_CALL(*linux_dmabuf, CreateParams(_, _, _)).Times(3); CreateDmabufBasedBufferAndSetTerminateExpectation(false /*fail*/, kBufferId1); CreateDmabufBasedBufferAndSetTerminateExpectation(false /*fail*/, kBufferId2); CreateDmabufBasedBufferAndSetTerminateExpectation(false /*fail*/, kBufferId3); Sync(); ProcessCreatedBufferResourcesWithExpectation(3u /* expected size */, false /* fail */); auto* mock_surface = server_.GetObject<wl::MockSurface>(widget); auto* mock_wp_presentation = server_.EnsureWpPresentation(); ASSERT_TRUE(mock_wp_presentation); constexpr uint32_t kNumberOfCommits = 3; EXPECT_CALL(*mock_surface, Attach(_, _, _)).Times(kNumberOfCommits); EXPECT_CALL(*mock_surface, Frame(_)).Times(kNumberOfCommits); EXPECT_CALL(*mock_surface, Commit()).Times(kNumberOfCommits); EXPECT_CALL(*mock_wp_presentation, Feedback(_, _, mock_surface->resource(), _)) .Times(3); Sync(); ::testing::InSequence s; // wp_presentation_feedback should work now. ASSERT_TRUE(connection_->presentation()); // Commit the first buffer and expect OnSubmission immediately. EXPECT_CALL(mock_surface_gpu, OnPresentation(_, _)).Times(0); EXPECT_CALL(mock_surface_gpu, OnSubmission(kBufferId1, gfx::SwapResult::SWAP_ACK)) .Times(1); buffer_manager_gpu_->CommitBuffer(widget, kBufferId1, bounds); mock_surface->SendFrameCallback(); Sync(); // Deliberately drop the presentation feedback for the first buffer, // since we will destroy it. mock_wp_presentation->set_presentation_callback(nullptr); // Commit second buffer now. buffer_manager_gpu_->CommitBuffer(widget, kBufferId2, bounds); mock_surface->SendFrameCallback(); Sync(); // Destroy the first buffer, which should trigger submission for the second // buffer. EXPECT_CALL(mock_surface_gpu, OnSubmission(kBufferId2, gfx::SwapResult::SWAP_ACK)) .Times(1); DestroyBufferAndSetTerminateExpectation(widget, kBufferId1, /*fail=*/false); mock_surface->DestroyPrevAttachedBuffer(); mock_surface->SendFrameCallback(); Sync(); // Deliberately drop the presentation feedback for the second buffer, // since we will destroy it. mock_wp_presentation->set_presentation_callback(nullptr); // Commit buffer 3 then send the presentation callback for it. This should // not call OnPresentation as OnSubmission hasn't been called yet. EXPECT_CALL(mock_surface_gpu, OnPresentation(_, _)).Times(0); buffer_manager_gpu_->CommitBuffer(widget, kBufferId3, bounds); mock_surface->SendFrameCallback(); mock_wp_presentation->SendPresentationCallback(); Sync(); // Destroy buffer 2, which should trigger OnSubmission for buffer 3, and // OnPresentation for buffer 1, 2, and 3. EXPECT_CALL(mock_surface_gpu, OnSubmission(kBufferId3, gfx::SwapResult::SWAP_ACK)) .Times(1); EXPECT_CALL( mock_surface_gpu, OnPresentation( kBufferId1, ::testing::Field( &gfx::PresentationFeedback::flags, ::testing::Eq(gfx::PresentationFeedback::Flags::kFailure)))) .Times(1); EXPECT_CALL( mock_surface_gpu, OnPresentation( kBufferId2, ::testing::Field( &gfx::PresentationFeedback::flags, ::testing::Eq(gfx::PresentationFeedback::Flags::kFailure)))) .Times(1); EXPECT_CALL(mock_surface_gpu, OnPresentation(kBufferId3, _)).Times(1); DestroyBufferAndSetTerminateExpectation(widget, kBufferId2, /*fail=*/false); mock_surface->DestroyPrevAttachedBuffer(); mock_surface->SendFrameCallback(); mock_wp_presentation->SendPresentationCallback(); Sync(); DestroyBufferAndSetTerminateExpectation(widget, kBufferId3, false /*fail*/); } // This test ensures that a discarded presentation feedback sent prior receiving // results for the previous presentation feedback does not make them // automatically failed. TEST_P(WaylandBufferManagerTest, EnsureDiscardedPresentationDoesNotMakePreviousFeedbacksFailed) { constexpr uint32_t kBufferId1 = 1; constexpr uint32_t kBufferId2 = 2; constexpr uint32_t kBufferId3 = 3; // Enable wp_presentation support. auto* mock_wp_presentation = server_.EnsureWpPresentation(); ASSERT_TRUE(mock_wp_presentation); const gfx::AcceleratedWidget widget = window_->GetWidget(); const gfx::Rect bounds = gfx::Rect({0, 0}, kDefaultSize); window_->SetBounds(bounds); MockSurfaceGpu mock_surface_gpu(buffer_manager_gpu_.get(), widget_); auto* linux_dmabuf = server_.zwp_linux_dmabuf_v1(); EXPECT_CALL(*linux_dmabuf, CreateParams(_, _, _)).Times(3); CreateDmabufBasedBufferAndSetTerminateExpectation(false /*fail*/, kBufferId1); CreateDmabufBasedBufferAndSetTerminateExpectation(false /*fail*/, kBufferId2); CreateDmabufBasedBufferAndSetTerminateExpectation(false /*fail*/, kBufferId3); Sync(); ProcessCreatedBufferResourcesWithExpectation(3u /* expected size */, false /* fail */); auto* mock_surface = server_.GetObject<wl::MockSurface>(widget); constexpr uint32_t kNumberOfCommits = 3; EXPECT_CALL(*mock_surface, Attach(_, _, _)).Times(kNumberOfCommits); EXPECT_CALL(*mock_surface, Frame(_)).Times(kNumberOfCommits); EXPECT_CALL(*mock_surface, Commit()).Times(kNumberOfCommits); // All the other expectations must come in order. ::testing::InSequence sequence; EXPECT_CALL(mock_surface_gpu, OnSubmission(kBufferId1, gfx::SwapResult::SWAP_ACK)) .Times(1); EXPECT_CALL(mock_surface_gpu, OnPresentation(_, _)).Times(0); // Commit first buffer buffer_manager_gpu_->CommitBuffer(widget, kBufferId1, bounds); Sync(); // Will be sent later. auto* presentation_callback1 = mock_wp_presentation->ReleasePresentationCallback(); mock_surface->SendFrameCallback(); Sync(); EXPECT_CALL(mock_surface_gpu, OnSubmission(kBufferId2, gfx::SwapResult::SWAP_ACK)) .Times(1); EXPECT_CALL(mock_surface_gpu, OnPresentation(_, _)).Times(0); // Commit second buffer buffer_manager_gpu_->CommitBuffer(widget, kBufferId2, bounds); Sync(); // Will be sent later. auto* presentation_callback2 = mock_wp_presentation->ReleasePresentationCallback(); // Release previous buffer and commit third buffer. mock_surface->ReleasePrevAttachedBuffer(); mock_surface->SendFrameCallback(); Sync(); EXPECT_CALL(mock_surface_gpu, OnSubmission(kBufferId3, gfx::SwapResult::SWAP_ACK)) .Times(1); EXPECT_CALL(mock_surface_gpu, OnPresentation(_, _)).Times(0); // Commit third buffer buffer_manager_gpu_->CommitBuffer(widget, kBufferId3, bounds); Sync(); mock_surface->ReleasePrevAttachedBuffer(); Sync(); // Even though WaylandBufferManagerHost stores the previous stores // presentation feedbacks and waits for their value, the current last one // mustn't result in the previous marked as failed. Thus, no feedback must be // actually sent to the MockSurfaceGpu as it's required to send feedbacks in // order. EXPECT_CALL(mock_surface_gpu, OnPresentation(_, _)).Times(0); mock_wp_presentation->SendPresentationCallbackDiscarded(); Sync(); // Now, start to send all the previous callbacks. EXPECT_CALL(mock_surface_gpu, OnPresentation( kBufferId1, ::testing::Field( &gfx::PresentationFeedback::flags, ::testing::Eq(gfx::PresentationFeedback::Flags::kVSync)))) .Times(1); mock_wp_presentation->set_presentation_callback(presentation_callback1); mock_wp_presentation->SendPresentationCallback(); Sync(); // Now, send the second presentation feedback. It will send both second and // third feedback that was discarded. EXPECT_CALL(mock_surface_gpu, OnPresentation( kBufferId2, ::testing::Field( &gfx::PresentationFeedback::flags, ::testing::Eq(gfx::PresentationFeedback::Flags::kVSync)))) .Times(1); EXPECT_CALL( mock_surface_gpu, OnPresentation( kBufferId3, ::testing::Field( &gfx::PresentationFeedback::flags, ::testing::Eq(gfx::PresentationFeedback::Flags::kFailure)))) .Times(1); mock_wp_presentation->set_presentation_callback(presentation_callback2); mock_wp_presentation->SendPresentationCallback(); Sync(); DestroyBufferAndSetTerminateExpectation(widget, kBufferId1, false /*fail*/); DestroyBufferAndSetTerminateExpectation(widget, kBufferId2, false /*fail*/); DestroyBufferAndSetTerminateExpectation(widget, kBufferId3, false /*fail*/); } TEST_P(WaylandBufferManagerTest, TestCommitBufferConditions) { constexpr uint32_t kDmabufBufferId = 1; constexpr uint32_t kDmabufBufferId2 = 2; const gfx::AcceleratedWidget widget = window_->GetWidget(); auto* mock_surface = server_.GetObject<wl::MockSurface>(widget); auto* linux_dmabuf = server_.zwp_linux_dmabuf_v1(); EXPECT_CALL(*linux_dmabuf, CreateParams(_, _, _)).Times(1); CreateDmabufBasedBufferAndSetTerminateExpectation(false /*fail*/, kDmabufBufferId); // Part 1: the surface mustn't have a buffer attached until // zwp_linux_buffer_params_v1_send_created is called. Instead, the buffer must // be set as pending buffer. EXPECT_CALL(*mock_surface, Attach(_, _, _)).Times(0); EXPECT_CALL(*mock_surface, Frame(_)).Times(0); EXPECT_CALL(*mock_surface, Commit()).Times(0); buffer_manager_gpu_->CommitBuffer(widget, kDmabufBufferId, window_->GetBounds()); Sync(); EXPECT_CALL(*mock_surface, Attach(_, _, _)).Times(1); EXPECT_CALL(*mock_surface, Frame(_)).Times(1); EXPECT_CALL(*mock_surface, Commit()).Times(1); ProcessCreatedBufferResourcesWithExpectation(1u /* expected size */, false /* fail */); Sync(); // Once the client receives a "...send_created" call, it must destroy the // params resource. EXPECT_TRUE(linux_dmabuf->buffer_params().empty()); // Part 2: the surface mustn't have a buffer attached until frame callback is // sent by the server. EXPECT_CALL(*linux_dmabuf, CreateParams(_, _, _)).Times(1); CreateDmabufBasedBufferAndSetTerminateExpectation(false /*fail*/, kDmabufBufferId2); ProcessCreatedBufferResourcesWithExpectation(1u /* expected size */, false /* fail */); Sync(); EXPECT_CALL(*mock_surface, Attach(_, _, _)).Times(0); EXPECT_CALL(*mock_surface, Frame(_)).Times(0); EXPECT_CALL(*mock_surface, Commit()).Times(0); buffer_manager_gpu_->CommitBuffer(widget, kDmabufBufferId2, window_->GetBounds()); Sync(); // After the frame callback is sent, the pending buffer will be committed. EXPECT_CALL(*mock_surface, Attach(_, _, _)).Times(1); EXPECT_CALL(*mock_surface, Frame(_)).Times(1); EXPECT_CALL(*mock_surface, Commit()).Times(1); mock_surface->SendFrameCallback(); Sync(); DestroyBufferAndSetTerminateExpectation(widget, kDmabufBufferId, false /*fail*/); DestroyBufferAndSetTerminateExpectation(widget, kDmabufBufferId2, false /*fail*/); } // Tests the surface does not have buffers attached until it's configured at // least once. TEST_P(WaylandBufferManagerTest, TestCommitBufferConditionsAckConfigured) { constexpr uint32_t kDmabufBufferId = 1; // Exercise three window types that create different windows - toplevel, popup // and subsurface. std::vector<PlatformWindowType> window_types{PlatformWindowType::kWindow, PlatformWindowType::kPopup, PlatformWindowType::kTooltip}; for (const auto& type : window_types) { // If the type is not kWindow, provide default created window as parent of // the newly created window. auto temp_window = CreateWindow(type, type != PlatformWindowType::kWindow ? widget_ : gfx::kNullAcceleratedWidget); auto widget = temp_window->GetWidget(); // Subsurface doesn't have an interface for sending configure events. // Thus, WaylandAuxiliaryWindow notifies the manager that the window is // activated upon creation of the subsurface. Skip calling Show() and call // later then. if (type != PlatformWindowType::kTooltip) temp_window->Show(false); Sync(); auto* mock_surface = server_.GetObject<wl::MockSurface>(widget); auto* linux_dmabuf = server_.zwp_linux_dmabuf_v1(); EXPECT_CALL(*linux_dmabuf, CreateParams(_, _, _)).Times(1); CreateDmabufBasedBufferAndSetTerminateExpectation(false /*fail*/, kDmabufBufferId); Sync(); ProcessCreatedBufferResourcesWithExpectation(1u /* expected size */, false /* fail */); EXPECT_CALL(*mock_surface, Attach(_, _, _)).Times(0); EXPECT_CALL(*mock_surface, Frame(_)).Times(0); EXPECT_CALL(*mock_surface, Commit()).Times(0); buffer_manager_gpu_->CommitBuffer(widget, kDmabufBufferId, window_->GetBounds()); Sync(); if (type != PlatformWindowType::kTooltip) { DCHECK(mock_surface->xdg_surface()); ActivateSurface(mock_surface->xdg_surface()); } else { // See the comment near Show() call above. temp_window->Show(false); } EXPECT_CALL(*mock_surface, Attach(_, _, _)).Times(1); EXPECT_CALL(*mock_surface, Frame(_)).Times(1); EXPECT_CALL(*mock_surface, Commit()).Times(1); Sync(); temp_window.reset(); DestroyBufferAndSetTerminateExpectation(widget, kDmabufBufferId, false /*fail*/); Sync(); } } // The buffer that is not originally attached to any of the surfaces, // must be attached when a commit request comes. Also, it must setup a buffer // release listener and OnSubmission must be called for that buffer if it is // released. TEST_P(WaylandBufferManagerTest, AnonymousBufferAttachedAndReleased) { constexpr uint32_t kBufferId1 = 1; constexpr uint32_t kBufferId2 = 2; constexpr uint32_t kBufferId3 = 3; const gfx::AcceleratedWidget widget = window_->GetWidget(); const gfx::Rect bounds = gfx::Rect({0, 0}, kDefaultSize); window_->SetBounds(bounds); MockSurfaceGpu mock_surface_gpu(buffer_manager_gpu_.get(), widget_); auto* linux_dmabuf = server_.zwp_linux_dmabuf_v1(); EXPECT_CALL(*linux_dmabuf, CreateParams(_, _, _)).Times(1); CreateDmabufBasedBufferAndSetTerminateExpectation(false /*fail*/, kBufferId1); Sync(); ProcessCreatedBufferResourcesWithExpectation(1u /* expected size */, false /* fail */); auto* mock_surface = server_.GetObject<wl::MockSurface>(widget); constexpr uint32_t kNumberOfCommits = 3; EXPECT_CALL(*mock_surface, Attach(_, _, _)).Times(kNumberOfCommits); EXPECT_CALL(*mock_surface, Frame(_)).Times(kNumberOfCommits); EXPECT_CALL(*mock_surface, Commit()).Times(kNumberOfCommits); // All the other expectations must come in order. ::testing::InSequence sequence; EXPECT_CALL(mock_surface_gpu, OnSubmission(kBufferId1, gfx::SwapResult::SWAP_ACK)) .Times(1); EXPECT_CALL(mock_surface_gpu, OnPresentation(kBufferId1, _)).Times(1); // Commit second buffer now. buffer_manager_gpu_->CommitBuffer(widget, kBufferId1, bounds); Sync(); mock_surface->SendFrameCallback(); Sync(); // Now synchronously create a second buffer and commit it. The release // callback must be setup and OnSubmission must be called. EXPECT_CALL(*linux_dmabuf, CreateParams(_, _, _)).Times(1); CreateDmabufBasedBufferAndSetTerminateExpectation(false /*fail*/, kBufferId2); Sync(); ProcessCreatedBufferResourcesWithExpectation(1u /* expected size */, false /* fail */); EXPECT_CALL(mock_surface_gpu, OnSubmission(kBufferId2, gfx::SwapResult::SWAP_ACK)) .Times(1); EXPECT_CALL(mock_surface_gpu, OnPresentation(kBufferId2, _)).Times(1); // Commit second buffer now. buffer_manager_gpu_->CommitBuffer(widget, kBufferId2, bounds); Sync(); mock_surface->ReleasePrevAttachedBuffer(); Sync(); mock_surface->SendFrameCallback(); // Now asynchronously create another buffer so that a commit request // comes earlier than it is created by the Wayland compositor, but it can // released once the buffer is committed and processed (that is, it must be // able to setup a buffer release callback). EXPECT_CALL(*linux_dmabuf, CreateParams(_, _, _)).Times(1); CreateDmabufBasedBufferAndSetTerminateExpectation(false /*fail*/, kBufferId3); Sync(); EXPECT_CALL(mock_surface_gpu, OnSubmission(kBufferId3, gfx::SwapResult::SWAP_ACK)) .Times(0); EXPECT_CALL(mock_surface_gpu, OnPresentation(kBufferId3, _)).Times(0); buffer_manager_gpu_->CommitBuffer(widget, kBufferId3, bounds); Sync(); EXPECT_CALL(mock_surface_gpu, OnSubmission(kBufferId3, gfx::SwapResult::SWAP_ACK)) .Times(1); EXPECT_CALL(mock_surface_gpu, OnPresentation(kBufferId3, _)).Times(1); // Now, create the buffer from the Wayland compositor side and let the buffer // manager complete the commit request. ProcessCreatedBufferResourcesWithExpectation(1u /* expected size */, false /* fail */); Sync(); mock_surface->ReleasePrevAttachedBuffer(); Sync(); DestroyBufferAndSetTerminateExpectation(widget, kBufferId1, false /*fail*/); DestroyBufferAndSetTerminateExpectation(widget, kBufferId2, false /*fail*/); DestroyBufferAndSetTerminateExpectation(widget, kBufferId3, false /*fail*/); } TEST_P(WaylandBufferManagerTest, DestroyBufferForDestroyedWindow) { constexpr uint32_t kBufferId = 1; auto temp_window = CreateWindow(); auto widget = temp_window->GetWidget(); EXPECT_CALL(*server_.zwp_linux_dmabuf_v1(), CreateParams(_, _, _)).Times(1); CreateDmabufBasedBufferAndSetTerminateExpectation(false /*fail*/, kBufferId); Sync(); buffer_manager_gpu_->CommitBuffer(widget, kBufferId, temp_window->GetBounds()); Sync(); temp_window.reset(); DestroyBufferAndSetTerminateExpectation(widget, kBufferId, false /*fail*/); } TEST_P(WaylandBufferManagerTest, DestroyedWindowNoSubmissionSingleBuffer) { constexpr uint32_t kBufferId = 1; auto temp_window = CreateWindow(); auto widget = temp_window->GetWidget(); auto bounds = temp_window->GetBounds(); EXPECT_CALL(*server_.zwp_linux_dmabuf_v1(), CreateParams(_, _, _)).Times(1); CreateDmabufBasedBufferAndSetTerminateExpectation(false /*fail*/, kBufferId); ProcessCreatedBufferResourcesWithExpectation(1u /* expected size */, false /* fail */); Sync(); MockSurfaceGpu mock_surface_gpu(buffer_manager_gpu_.get(), widget); // All the other expectations must come in order. ::testing::InSequence sequence; EXPECT_CALL(mock_surface_gpu, OnSubmission(_, _)).Times(0); EXPECT_CALL(mock_surface_gpu, OnPresentation(_, _)).Times(0); temp_window.reset(); buffer_manager_gpu_->CommitBuffer(widget, kBufferId, bounds); Sync(); DestroyBufferAndSetTerminateExpectation(widget, kBufferId, false /*fail*/); } TEST_P(WaylandBufferManagerTest, DestroyedWindowNoSubmissionMultipleBuffers) { constexpr uint32_t kBufferId1 = 1; constexpr uint32_t kBufferId2 = 2; auto temp_window = CreateWindow(); temp_window->Show(false); Sync(); auto widget = temp_window->GetWidget(); auto bounds = temp_window->GetBounds(); auto* mock_surface = server_.GetObject<wl::MockSurface>(widget); ASSERT_TRUE(mock_surface); ActivateSurface(mock_surface->xdg_surface()); Sync(); EXPECT_CALL(*server_.zwp_linux_dmabuf_v1(), CreateParams(_, _, _)).Times(1); CreateDmabufBasedBufferAndSetTerminateExpectation(false /*fail*/, kBufferId1); ProcessCreatedBufferResourcesWithExpectation(1u /* expected size */, false /* fail */); Sync(); MockSurfaceGpu mock_surface_gpu(buffer_manager_gpu_.get(), widget); // All the other expectations must come in order. ::testing::InSequence sequence; EXPECT_CALL(mock_surface_gpu, OnSubmission(_, _)).Times(1); EXPECT_CALL(mock_surface_gpu, OnPresentation(_, _)).Times(1); buffer_manager_gpu_->CommitBuffer(widget, kBufferId1, bounds); Sync(); mock_surface->SendFrameCallback(); Sync(); EXPECT_CALL(*server_.zwp_linux_dmabuf_v1(), CreateParams(_, _, _)).Times(1); CreateDmabufBasedBufferAndSetTerminateExpectation(false /*fail*/, kBufferId2); ProcessCreatedBufferResourcesWithExpectation(1u /* expected size */, false /* fail */); Sync(); EXPECT_CALL(mock_surface_gpu, OnSubmission(kBufferId2, gfx::SwapResult::SWAP_ACK)) .Times(1); EXPECT_CALL(mock_surface_gpu, OnPresentation(kBufferId2, _)).Times(1); buffer_manager_gpu_->CommitBuffer(widget, kBufferId2, bounds); Sync(); mock_surface->ReleasePrevAttachedBuffer(); Sync(); EXPECT_CALL(mock_surface_gpu, OnSubmission(_, _)).Times(0); EXPECT_CALL(mock_surface_gpu, OnPresentation(_, _)).Times(0); temp_window.reset(); buffer_manager_gpu_->CommitBuffer(widget, kBufferId1, bounds); Sync(); DestroyBufferAndSetTerminateExpectation(widget, kBufferId1, false /*fail*/); DestroyBufferAndSetTerminateExpectation(widget, kBufferId2, false /*fail*/); } // This test verifies that submitting the buffer more than once results in // OnSubmission callback as Wayland compositor is not supposed to release the // buffer committed twice. TEST_P(WaylandBufferManagerTest, SubmitSameBufferMultipleTimes) { constexpr uint32_t kBufferId1 = 1; constexpr uint32_t kBufferId2 = 2; const gfx::AcceleratedWidget widget = window_->GetWidget(); const gfx::Rect bounds = window_->GetBounds(); MockSurfaceGpu mock_surface_gpu(buffer_manager_gpu_.get(), widget); auto* linux_dmabuf = server_.zwp_linux_dmabuf_v1(); EXPECT_CALL(*linux_dmabuf, CreateParams(_, _, _)).Times(2); CreateDmabufBasedBufferAndSetTerminateExpectation(false /*fail*/, kBufferId1); CreateDmabufBasedBufferAndSetTerminateExpectation(false /*fail*/, kBufferId2); Sync(); ProcessCreatedBufferResourcesWithExpectation(2u /* expected size */, false /* fail */); EXPECT_CALL(mock_surface_gpu, OnSubmission(kBufferId1, gfx::SwapResult::SWAP_ACK)) .Times(1); ASSERT_TRUE(!connection_->presentation()); EXPECT_CALL(mock_surface_gpu, OnPresentation(kBufferId1, _)).Times(1); auto* mock_surface = server_.GetObject<wl::MockSurface>(widget); EXPECT_CALL(*mock_surface, Attach(_, _, _)).Times(1); EXPECT_CALL(*mock_surface, Frame(_)).Times(1); EXPECT_CALL(*mock_surface, DamageBuffer(0, 0, bounds.width(), bounds.height())) .Times(1); EXPECT_CALL(*mock_surface, Commit()).Times(1); buffer_manager_gpu_->CommitBuffer(widget, kBufferId1, bounds); Sync(); testing::Mock::VerifyAndClearExpectations(&mock_surface_gpu); testing::Mock::VerifyAndClearExpectations(mock_surface); EXPECT_CALL(mock_surface_gpu, OnSubmission(_, _)).Times(0); EXPECT_CALL(mock_surface_gpu, OnPresentation(_, _)).Times(0); mock_surface->SendFrameCallback(); Sync(); EXPECT_CALL(*mock_surface, Attach(_, _, _)).Times(1); EXPECT_CALL(*mock_surface, Frame(_)).Times(1); EXPECT_CALL(*mock_surface, DamageBuffer(0, 0, bounds.width(), bounds.height())) .Times(1); EXPECT_CALL(*mock_surface, Commit()).Times(1); // Commit second buffer now. buffer_manager_gpu_->CommitBuffer(widget, kBufferId2, bounds); Sync(); testing::Mock::VerifyAndClearExpectations(&mock_surface_gpu); testing::Mock::VerifyAndClearExpectations(mock_surface); EXPECT_CALL(mock_surface_gpu, OnSubmission(kBufferId2, gfx::SwapResult::SWAP_ACK)) .Times(1); EXPECT_CALL(mock_surface_gpu, OnPresentation(kBufferId2, _)).Times(1); EXPECT_CALL(*mock_surface, Attach(_, _, _)).Times(0); EXPECT_CALL(*mock_surface, Frame(_)).Times(0); EXPECT_CALL(*mock_surface, DamageBuffer(_, _, _, _)).Times(0); EXPECT_CALL(*mock_surface, Commit()).Times(0); mock_surface->ReleasePrevAttachedBuffer(); mock_surface->SendFrameCallback(); Sync(); testing::Mock::VerifyAndClearExpectations(&mock_surface_gpu); testing::Mock::VerifyAndClearExpectations(mock_surface); // Now, commit the buffer with the |kBufferId2| again and make sure the // manager manually sends the submission callback as long as the compositor is // not going to release a buffer as it was the same buffer submitted more than // once. EXPECT_CALL(mock_surface_gpu, OnSubmission(kBufferId2, gfx::SwapResult::SWAP_ACK)) .Times(1); EXPECT_CALL(mock_surface_gpu, OnPresentation(kBufferId2, _)).Times(1); EXPECT_CALL(*mock_surface, Attach(_, _, _)).Times(0); EXPECT_CALL(*mock_surface, Frame(_)).Times(1); EXPECT_CALL(*mock_surface, DamageBuffer(0, 0, bounds.width(), bounds.height())) .Times(1); EXPECT_CALL(*mock_surface, Commit()).Times(1); // Commit second buffer now. buffer_manager_gpu_->CommitBuffer(widget, kBufferId2, bounds); Sync(); testing::Mock::VerifyAndClearExpectations(&mock_surface_gpu); testing::Mock::VerifyAndClearExpectations(mock_surface); EXPECT_CALL(mock_surface_gpu, OnSubmission(_, _)).Times(0); EXPECT_CALL(mock_surface_gpu, OnPresentation(_, _)).Times(0); EXPECT_CALL(*mock_surface, Attach(_, _, _)).Times(0); EXPECT_CALL(*mock_surface, Frame(_)).Times(0); EXPECT_CALL(*mock_surface, DamageBuffer(_, _, _, _)).Times(0); EXPECT_CALL(*mock_surface, Commit()).Times(0); // It must be ok if Wayland compositor decides to release the buffer at some // point. mock_surface->ReleasePrevAttachedBuffer(); mock_surface->SendFrameCallback(); Sync(); testing::Mock::VerifyAndClearExpectations(&mock_surface_gpu); testing::Mock::VerifyAndClearExpectations(mock_surface); // If we commit another buffer now, the manager host must not automatically // trigger OnSubmission and OnPresentation callbacks. EXPECT_CALL(mock_surface_gpu, OnSubmission(_, _)).Times(0); EXPECT_CALL(mock_surface_gpu, OnPresentation(_, _)).Times(0); EXPECT_CALL(*mock_surface, Attach(_, _, _)).Times(1); EXPECT_CALL(*mock_surface, Frame(_)).Times(1); EXPECT_CALL(*mock_surface, DamageBuffer(0, 0, bounds.width(), bounds.height())) .Times(1); EXPECT_CALL(*mock_surface, Commit()).Times(1); buffer_manager_gpu_->CommitBuffer(widget, kBufferId1, bounds); Sync(); testing::Mock::VerifyAndClearExpectations(&mock_surface_gpu); testing::Mock::VerifyAndClearExpectations(mock_surface); // Now, they must be triggered once the buffer is released. EXPECT_CALL(mock_surface_gpu, OnSubmission(kBufferId1, gfx::SwapResult::SWAP_ACK)) .Times(1); EXPECT_CALL(mock_surface_gpu, OnPresentation(kBufferId1, _)).Times(1); mock_surface->ReleasePrevAttachedBuffer(); mock_surface->SendFrameCallback(); Sync(); testing::Mock::VerifyAndClearExpectations(&mock_surface_gpu); DestroyBufferAndSetTerminateExpectation(widget, kBufferId1, false /*fail*/); DestroyBufferAndSetTerminateExpectation(widget, kBufferId2, false /*fail*/); } INSTANTIATE_TEST_SUITE_P(XdgVersionStableTest, WaylandBufferManagerTest, ::testing::Values(kXdgShellStable)); INSTANTIATE_TEST_SUITE_P(XdgVersionV6Test, WaylandBufferManagerTest, ::testing::Values(kXdgShellV6)); } // namespace ui
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
83909c587b927194e8fb9da5b6256da4c599fefb
cd10a6c464d7017b864da05ce0e8ed2a484c5b09
/src/chain.h
c42874d90749c07564f04acb35eeec172e160da0
[ "MIT" ]
permissive
mirzaei-ce/core-filbit
63b4482f30d7212c73480c1206464201422f2e79
415073034f471c38a60223af52b8da76c302ae1c
refs/heads/master
2021-08-14T19:07:34.947832
2017-11-16T14:54:42
2017-11-16T14:54:42
110,984,372
0
0
null
null
null
null
UTF-8
C++
false
false
12,528
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-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. #ifndef FILBIT_CHAIN_H #define FILBIT_CHAIN_H #include "arith_uint256.h" #include "primitives/block.h" #include "pow.h" #include "tinyformat.h" #include "uint256.h" #include <vector> struct CDiskBlockPos { int nFile; unsigned int nPos; ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { READWRITE(VARINT(nFile)); READWRITE(VARINT(nPos)); } CDiskBlockPos() { SetNull(); } CDiskBlockPos(int nFileIn, unsigned int nPosIn) { nFile = nFileIn; nPos = nPosIn; } friend bool operator==(const CDiskBlockPos &a, const CDiskBlockPos &b) { return (a.nFile == b.nFile && a.nPos == b.nPos); } friend bool operator!=(const CDiskBlockPos &a, const CDiskBlockPos &b) { return !(a == b); } void SetNull() { nFile = -1; nPos = 0; } bool IsNull() const { return (nFile == -1); } std::string ToString() const { return strprintf("CBlockDiskPos(nFile=%i, nPos=%i)", nFile, nPos); } }; enum BlockStatus { //! Unused. BLOCK_VALID_UNKNOWN = 0, //! Parsed, version ok, hash satisfies claimed PoW, 1 <= vtx count <= max, timestamp not in future BLOCK_VALID_HEADER = 1, //! All parent headers found, difficulty matches, timestamp >= median previous, checkpoint. Implies all parents //! are also at least TREE. BLOCK_VALID_TREE = 2, /** * Only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid, no duplicate txids, * sigops, size, merkle root. Implies all parents are at least TREE but not necessarily TRANSACTIONS. When all * parent blocks also have TRANSACTIONS, CBlockIndex::nChainTx will be set. */ BLOCK_VALID_TRANSACTIONS = 3, //! Outputs do not overspend inputs, no double spends, coinbase output ok, no immature coinbase spends, BIP30. //! Implies all parents are also at least CHAIN. BLOCK_VALID_CHAIN = 4, //! Scripts & signatures ok. Implies all parents are also at least SCRIPTS. BLOCK_VALID_SCRIPTS = 5, //! All validity bits. BLOCK_VALID_MASK = BLOCK_VALID_HEADER | BLOCK_VALID_TREE | BLOCK_VALID_TRANSACTIONS | BLOCK_VALID_CHAIN | BLOCK_VALID_SCRIPTS, BLOCK_HAVE_DATA = 8, //! full block available in blk*.dat BLOCK_HAVE_UNDO = 16, //! undo data available in rev*.dat BLOCK_HAVE_MASK = BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO, BLOCK_FAILED_VALID = 32, //! stage after last reached validness failed BLOCK_FAILED_CHILD = 64, //! descends from failed block BLOCK_FAILED_MASK = BLOCK_FAILED_VALID | BLOCK_FAILED_CHILD, }; /** The block chain is a tree shaped structure starting with the * genesis block at the root, with each block potentially having multiple * candidates to be the next block. A blockindex may have multiple pprev pointing * to it, but at most one of them can be part of the currently active branch. */ class CBlockIndex { public: //! pointer to the hash of the block, if any. Memory is owned by this CBlockIndex const uint256* phashBlock; //! pointer to the index of the predecessor of this block CBlockIndex* pprev; //! pointer to the index of some further predecessor of this block CBlockIndex* pskip; //! height of the entry in the chain. The genesis block has height 0 int nHeight; //! Which # file this block is stored in (blk?????.dat) int nFile; //! Byte offset within blk?????.dat where this block's data is stored unsigned int nDataPos; //! Byte offset within rev?????.dat where this block's undo data is stored unsigned int nUndoPos; //! (memory only) Total amount of work (expected number of hashes) in the chain up to and including this block arith_uint256 nChainWork; //! Number of transactions in this block. //! Note: in a potential headers-first mode, this number cannot be relied upon unsigned int nTx; //! (memory only) Number of transactions in the chain up to and including this block. //! This value will be non-zero only if and only if transactions for this block and all its parents are available. //! Change to 64-bit type when necessary; won't happen before 2030 unsigned int nChainTx; //! Verification status of this block. See enum BlockStatus unsigned int nStatus; //! block header int nVersion; uint256 hashMerkleRoot; unsigned int nTime; unsigned int nBits; unsigned int nNonce; //! (memory only) Sequential id assigned to distinguish order in which blocks are received. uint32_t nSequenceId; void SetNull() { phashBlock = NULL; pprev = NULL; pskip = NULL; nHeight = 0; nFile = 0; nDataPos = 0; nUndoPos = 0; nChainWork = arith_uint256(); nTx = 0; nChainTx = 0; nStatus = 0; nSequenceId = 0; nVersion = 0; hashMerkleRoot = uint256(); nTime = 0; nBits = 0; nNonce = 0; } CBlockIndex() { SetNull(); } CBlockIndex(const CBlockHeader& block) { SetNull(); nVersion = block.nVersion; hashMerkleRoot = block.hashMerkleRoot; nTime = block.nTime; nBits = block.nBits; nNonce = block.nNonce; } CDiskBlockPos GetBlockPos() const { CDiskBlockPos ret; if (nStatus & BLOCK_HAVE_DATA) { ret.nFile = nFile; ret.nPos = nDataPos; } return ret; } CDiskBlockPos GetUndoPos() const { CDiskBlockPos ret; if (nStatus & BLOCK_HAVE_UNDO) { ret.nFile = nFile; ret.nPos = nUndoPos; } return ret; } CBlockHeader GetBlockHeader() const { CBlockHeader block; block.nVersion = nVersion; if (pprev) block.hashPrevBlock = pprev->GetBlockHash(); block.hashMerkleRoot = hashMerkleRoot; block.nTime = nTime; block.nBits = nBits; block.nNonce = nNonce; return block; } uint256 GetBlockHash() const { return *phashBlock; } int64_t GetBlockTime() const { return (int64_t)nTime; } enum { nMedianTimeSpan=11 }; int64_t GetMedianTimePast() const { int64_t pmedian[nMedianTimeSpan]; int64_t* pbegin = &pmedian[nMedianTimeSpan]; int64_t* pend = &pmedian[nMedianTimeSpan]; const CBlockIndex* pindex = this; for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev) *(--pbegin) = pindex->GetBlockTime(); std::sort(pbegin, pend); return pbegin[(pend - pbegin)/2]; } std::string ToString() const { return strprintf("CBlockIndex(pprev=%p, nHeight=%d, merkle=%s, hashBlock=%s)", pprev, nHeight, hashMerkleRoot.ToString(), GetBlockHash().ToString()); } //! Check whether this block index entry is valid up to the passed validity level. bool IsValid(enum BlockStatus nUpTo = BLOCK_VALID_TRANSACTIONS) const { assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed. if (nStatus & BLOCK_FAILED_MASK) return false; return ((nStatus & BLOCK_VALID_MASK) >= nUpTo); } //! Raise the validity level of this block index entry. //! Returns true if the validity was changed. bool RaiseValidity(enum BlockStatus nUpTo) { assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed. if (nStatus & BLOCK_FAILED_MASK) return false; if ((nStatus & BLOCK_VALID_MASK) < nUpTo) { nStatus = (nStatus & ~BLOCK_VALID_MASK) | nUpTo; return true; } return false; } //! Build the skiplist pointer for this entry. void BuildSkip(); //! Efficiently find an ancestor of this block. CBlockIndex* GetAncestor(int height); const CBlockIndex* GetAncestor(int height) const; }; /** Used to marshal pointers into hashes for db storage. */ class CDiskBlockIndex : public CBlockIndex { public: uint256 hashPrev; CDiskBlockIndex() { hashPrev = uint256(); } explicit CDiskBlockIndex(const CBlockIndex* pindex) : CBlockIndex(*pindex) { hashPrev = (pprev ? pprev->GetBlockHash() : uint256()); } ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { if (!(nType & SER_GETHASH)) READWRITE(VARINT(nVersion)); READWRITE(VARINT(nHeight)); READWRITE(VARINT(nStatus)); READWRITE(VARINT(nTx)); if (nStatus & (BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO)) READWRITE(VARINT(nFile)); if (nStatus & BLOCK_HAVE_DATA) READWRITE(VARINT(nDataPos)); if (nStatus & BLOCK_HAVE_UNDO) READWRITE(VARINT(nUndoPos)); // block header READWRITE(this->nVersion); READWRITE(hashPrev); READWRITE(hashMerkleRoot); READWRITE(nTime); READWRITE(nBits); READWRITE(nNonce); } uint256 GetBlockHash() const { CBlockHeader block; block.nVersion = nVersion; block.hashPrevBlock = hashPrev; block.hashMerkleRoot = hashMerkleRoot; block.nTime = nTime; block.nBits = nBits; block.nNonce = nNonce; return block.GetHash(); } std::string ToString() const { std::string str = "CDiskBlockIndex("; str += CBlockIndex::ToString(); str += strprintf("\n hashBlock=%s, hashPrev=%s)", GetBlockHash().ToString(), hashPrev.ToString()); return str; } }; /** An in-memory indexed chain of blocks. */ class CChain { private: std::vector<CBlockIndex*> vChain; public: /** Returns the index entry for the genesis block of this chain, or NULL if none. */ CBlockIndex *Genesis() const { return vChain.size() > 0 ? vChain[0] : NULL; } /** Returns the index entry for the tip of this chain, or NULL if none. */ CBlockIndex *Tip() const { return vChain.size() > 0 ? vChain[vChain.size() - 1] : NULL; } /** Returns the index entry at a particular height in this chain, or NULL if no such height exists. */ CBlockIndex *operator[](int nHeight) const { if (nHeight < 0 || nHeight >= (int)vChain.size()) return NULL; return vChain[nHeight]; } /** Compare two chains efficiently. */ friend bool operator==(const CChain &a, const CChain &b) { return a.vChain.size() == b.vChain.size() && a.vChain[a.vChain.size() - 1] == b.vChain[b.vChain.size() - 1]; } /** Efficiently check whether a block is present in this chain. */ bool Contains(const CBlockIndex *pindex) const { return (*this)[pindex->nHeight] == pindex; } /** Find the successor of a block in this chain, or NULL if the given index is not found or is the tip. */ CBlockIndex *Next(const CBlockIndex *pindex) const { if (Contains(pindex)) return (*this)[pindex->nHeight + 1]; else return NULL; } /** Return the maximal height in the chain. Is equal to chain.Tip() ? chain.Tip()->nHeight : -1. */ int Height() const { return vChain.size() - 1; } /** Set/initialize a chain with a given tip. */ void SetTip(CBlockIndex *pindex); /** Return a CBlockLocator that refers to a block in this chain (by default the tip). */ CBlockLocator GetLocator(const CBlockIndex *pindex = NULL) const; /** Find the last common block between this chain and a block index entry. */ const CBlockIndex *FindFork(const CBlockIndex *pindex) const; }; #endif // FILBIT_CHAIN_H
[ "mirzaei@ce.sharif.edu" ]
mirzaei@ce.sharif.edu
b3f748f44300de582a845bbe33b93afae2018eb8
322586fd62facf9563df4e2ba99d2cc10ee74c6b
/160/src_2_4.cpp
4ee0d4b4f946d6baced34eedab3ec66b1005e734
[]
no_license
WavesUR/leetcode-study
82fe60ccb65b243a82731951257ad36186bd5784
0564b36237dbb50087bc7dd51932df1f5eb37e83
refs/heads/master
2021-01-13T12:19:03.696019
2018-12-03T05:19:12
2018-12-03T05:19:12
77,957,433
0
0
null
null
null
null
UTF-8
C++
false
false
1,687
cpp
#include <iostream> #include <cstring> #include <string> #include <sstream> #include <vector> #include <algorithm> #include <cmath> #include <cctype> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { int len_a = 0, len_b = 0; ListNode* cur_a = headA; ListNode* cur_b = headB; while(cur_a){ len_a++; cur_a = cur_a ->next; } while(cur_b){ len_b++; cur_b = cur_b -> next; } if(!cur_a || !cur_b){ return NULL; } cur_a = headA; cur_b = headB; if(len_a > len_b){ while(len_a != len_b){ cur_a = cur_a -> next; len_a--; } }else if(len_a < len_b){ while(len_a != len_b){ cur_b = cur_b -> next; len_b--; } } while(cur_a && cur_b){ if(cur_a == cur_b){ return cur_a; }else{ cur_b = cur_b -> next; cur_a = cur_a -> next; } } return NULL; } }; int main(){ ListNode *head = NULL; ListNode *head1 = NULL; for(int i = 5; i >=0; i=i-2){ ListNode *node = new ListNode(i); node->next = head; head = node; } for(int i = 8; i >=0; i=i-1){ ListNode *node = new ListNode(i); node->next = head1; head1 = node; } Solution solution; head1 = solution.getIntersectionNode(head,head1); while(head1){ cout << head1->val << " "; head1 = head1->next; } cout << endl; return 0; }
[ "waves.ur.ee@gmail.com" ]
waves.ur.ee@gmail.com
f2dff4da3e67705842ace22702a008ba27b12e23
53fb17dd707829a99cfdb1df690a2d7daaf6f998
/Point.cpp
2f365f68a99c41a7aeb9d493b5a41a41224d675c
[]
no_license
leefige/Metro-helper
ea30d78548ec059183d92ecd1080f0e835050ac6
589ae22e6dfbbaf7dc81623b46142673b34c686b
refs/heads/master
2020-12-31T07:43:44.807563
2017-06-08T17:42:38
2017-06-08T17:42:38
86,557,416
2
0
null
2017-05-22T12:24:19
2017-03-29T08:31:28
C++
UTF-8
C++
false
false
722
cpp
// // Created by 乔逸凡 on 2017/3/31. // #include "Point.h" #include <cmath> Point Point::operator - (const Point &b) { Point c; c.x = x - b.x; c.y = y - b.y; return c; } Point Point::operator + (const Point &b) { Point c; c.x = x + b.x; c.y = y + b.y; return c; } double Point::len() { return sqrt(x * x + y * y); } double dist(Point a, Point b) { return (a - b).len(); } Point::Point(double x, double y) : x(x), y(y) {} bool Point::operator == (const Point &rhs) const { return x == rhs.x && y == rhs.y; } bool Point::operator != (const Point &rhs) const { return !(rhs == *this); } double Point::xx() { return x; } double Point::yy() { return y; }
[ "LegaDyan@gmail.com" ]
LegaDyan@gmail.com
79b3757c47828a19145c371cb8702dd9d66f3ebf
3ae80dbc18ed3e89bedf846d098b2a98d8e4b776
/src/Media/Decoder/G711muLawDecoder.cpp
fa3a5952764f9e575fe39f46420a8b9b8d391b2a
[]
no_license
sswroom/SClass
deee467349ca249a7401f5d3c177cdf763a253ca
9a403ec67c6c4dfd2402f19d44c6573e25d4b347
refs/heads/main
2023-09-01T07:24:58.907606
2023-08-31T11:24:34
2023-08-31T11:24:34
329,970,172
10
7
null
null
null
null
UTF-8
C++
false
false
4,977
cpp
#include "Stdafx.h" #include "MyMemory.h" #include "Media/Decoder/G711muLawDecoder.h" Media::Decoder::G711muLawDecoder::G711muLawDecoder(Media::IAudioSource *sourceAudio) { Media::AudioFormat fmt; this->sourceAudio = 0; this->readBuff = 0; this->readBuffSize = 0; this->align = 0; sourceAudio->GetFormat(&fmt); if (fmt.formatId != 0x7) return; if (fmt.bitpersample != 8) return; this->sourceAudio = sourceAudio; this->align = (UOSInt)fmt.nChannels << 1; } Media::Decoder::G711muLawDecoder::~G711muLawDecoder() { if (this->readBuff) { MemFree(this->readBuff); this->readBuff = 0; } } void Media::Decoder::G711muLawDecoder::GetFormat(AudioFormat *format) { if (this->sourceAudio) { Media::AudioFormat fmt; this->sourceAudio->GetFormat(&fmt); format->formatId = 1; format->bitpersample = 16; format->frequency = fmt.frequency; format->nChannels = fmt.nChannels; format->bitRate = fmt.frequency * fmt.nChannels << 4; format->align = (UInt32)fmt.nChannels * 2; format->other = 0; format->intType = Media::AudioFormat::IT_NORMAL; format->extraSize = 0; format->extra = 0; } else { format->formatId = 0; format->bitpersample = 0; format->frequency = 0; format->nChannels = 0; format->bitRate = 0; format->align = 0; format->other = 0; format->intType = Media::AudioFormat::IT_NORMAL; format->extraSize = 0; format->extra = 0; } } UInt32 Media::Decoder::G711muLawDecoder::SeekToTime(UInt32 time) { if (this->sourceAudio) { return this->sourceAudio->SeekToTime(time); } return 0; } Bool Media::Decoder::G711muLawDecoder::Start(Sync::Event *evt, UOSInt blkSize) { if (this->sourceAudio) { this->sourceAudio->Start(0, blkSize >> 1); this->readEvt = evt; if (this->readEvt) this->readEvt->Set(); return true; } return false; } void Media::Decoder::G711muLawDecoder::Stop() { if (this->sourceAudio) { this->sourceAudio->Stop(); } this->readEvt = 0; } UOSInt Media::Decoder::G711muLawDecoder::ReadBlock(Data::ByteArray blk) { static Int16 table[] = { -32124, -31100, -30076, -29052, -28028, -27004, -25980, -24956, -23932, -22908, -21884, -20860, -19836, -18812, -17788, -16764, -15996, -15484, -14972, -14460, -13948, -13436, -12924, -12412, -11900, -11388, -10876, -10364, -9852, -9340, -8828, -8316, -7932, -7676, -7420, -7164, -6908, -6652, -6396, -6140, -5884, -5628, -5372, -5116, -4860, -4604, -4348, -4092, -3900, -3772, -3644, -3516, -3388, -3260, -3132, -3004, -2876, -2748, -2620, -2492, -2364, -2236, -2108, -1980, -1884, -1820, -1756, -1692, -1628, -1564, -1500, -1436, -1372, -1308, -1244, -1180, -1116, -1052, -988, -924, -876, -844, -812, -780, -748, -716, -684, -652, -620, -588, -556, -524, -492, -460, -428, -396, -372, -356, -340, -324, -308, -292, -276, -260, -244, -228, -212, -196, -180, -164, -148, -132, -120, -112, -104, -96, -88, -80, -72, -64, -56, -48, -40, -32, -24, -16, -8, 0, 32124, 31100, 30076, 29052, 28028, 27004, 25980, 24956, 23932, 22908, 21884, 20860, 19836, 18812, 17788, 16764, 15996, 15484, 14972, 14460, 13948, 13436, 12924, 12412, 11900, 11388, 10876, 10364, 9852, 9340, 8828, 8316, 7932, 7676, 7420, 7164, 6908, 6652, 6396, 6140, 5884, 5628, 5372, 5116, 4860, 4604, 4348, 4092, 3900, 3772, 3644, 3516, 3388, 3260, 3132, 3004, 2876, 2748, 2620, 2492, 2364, 2236, 2108, 1980, 1884, 1820, 1756, 1692, 1628, 1564, 1500, 1436, 1372, 1308, 1244, 1180, 1116, 1052, 988, 924, 876, 844, 812, 780, 748, 716, 684, 652, 620, 588, 556, 524, 492, 460, 428, 396, 372, 356, 340, 324, 308, 292, 276, 260, 244, 228, 212, 196, 180, 164, 148, 132, 120, 112, 104, 96, 88, 80, 72, 64, 56, 48, 40, 32, 24, 16, 8, 0}; if (this->align == 0 || this->sourceAudio == 0) { if (this->readEvt) this->readEvt->Set(); return 0; } blk = blk.WithSize(blk.GetSize() / this->align * this->align); UOSInt readSize; UOSInt sofst = blk.GetSize() >> 1; UOSInt dofst = 0; UOSInt cnt; readSize = this->sourceAudio->ReadBlock(blk.SubArray(sofst, sofst)); cnt = readSize; while (cnt-- > 0) { *(Int16*)&blk[dofst] = table[blk[sofst]]; dofst += 2; sofst++; } if (this->readEvt) this->readEvt->Set(); return readSize << 1; } UOSInt Media::Decoder::G711muLawDecoder::GetMinBlockSize() { return this->align; }
[ "sswroom@yahoo.com" ]
sswroom@yahoo.com
da6b44fa0e4323198587b9730831710220b30505
0467000a05e2838d70319011c7e27cc355a9577a
/rmSquarterNumber.cpp
23242c41c97feaf57b89d863fd9fd059817ff622
[]
no_license
Newstar1994/algorithm
5d747bc3f127399f1b5caf92c897b0cfe93ba5fb
0c8ca4eee52951787d1f41cda765a3cc31e5ee86
refs/heads/master
2020-03-28T20:29:14.871356
2018-09-26T05:19:25
2018-09-26T05:19:25
149,075,098
0
0
null
null
null
null
UTF-8
C++
false
false
741
cpp
#include <stdio.h> #include <math.h> #include <iostream> /* for i to n, remove the complete squarter number and sort the left number using index for 1 to n - m; where m is the numbers of complete squarter number before; loop the above opeater and find the laste one left number. */ using namespace std; int find_x(int n) { int pre = 1; while (true) { int tmp = sqrt((double)(pre)); int next = pre + tmp; if (next == (tmp+1) * (tmp+1)) next++; if (next> n) return pre; else pre = next; } } int main() { int n; while (true) { cout << "Input n: "; cin >> n; int ans = find_x(n); cout << "Ouptut: " << ans << endl; cout << "--------------------" << endl; } return 0; }
[ "xiegx@xiegengxindeMacBook-Air.local" ]
xiegx@xiegengxindeMacBook-Air.local
cf20979c8524ed59e22dace89a5a319d7df20b11
9aa5f7142ab1cb6bec933610eee14eaa9247ac1e
/src/chainparams.h
dfea881844c43f55cf2bccf2f37d52c1c3e08c33
[ "MIT" ]
permissive
deyoonoo/deyoonoo
09327ce4c2d09b5b2c2695563272be6df0c2a100
c4e83850a73b5e1ffc3ec8de463e690a3b5c71f3
refs/heads/master
2020-09-26T07:55:32.671735
2019-12-06T02:49:37
2019-12-06T02:49:37
226,208,496
0
0
null
null
null
null
UTF-8
C++
false
false
11,125
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2018 The PIVX developers // Copyright (c) 2019 The CryptoDev developers // Copyright (c) 2019 The deyoonoo developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_CHAINPARAMS_H #define BITCOIN_CHAINPARAMS_H #include "chainparamsbase.h" #include "checkpoints.h" #include "primitives/block.h" #include "protocol.h" #include "uint256.h" #include "libzerocoin/Params.h" #include <vector> typedef unsigned char MessageStartChars[MESSAGE_START_SIZE]; struct CDNSSeedData { std::string name, host; CDNSSeedData(const std::string& strName, const std::string& strHost) : name(strName), host(strHost) {} }; /** * CChainParams defines various tweakable parameters of a given instance of the * DON system. There are three: the main network on which people trade goods * and services, the public test network which gets reset from time to time and * a regression test mode which is intended for private networks only. It has * minimal difficulty to ensure that blocks can be found instantly. */ class CChainParams { public: enum Base58Type { PUBKEY_ADDRESS, SCRIPT_ADDRESS, SECRET_KEY, // BIP16 EXT_PUBLIC_KEY, // BIP32 EXT_SECRET_KEY, // BIP32 EXT_COIN_TYPE, // BIP44 MAX_BASE58_TYPES }; const uint256& HashGenesisBlock() const { return hashGenesisBlock; } const MessageStartChars& MessageStart() const { return pchMessageStart; } const std::vector<unsigned char>& AlertKey() const { return vAlertPubKey; } int GetDefaultPort() const { return nDefaultPort; } const uint256& ProofOfWorkLimit() const { return bnProofOfWorkLimit; } int SubsidyHalvingInterval() const { return nSubsidyHalvingInterval; } /** Used to check majorities for block version upgrade */ int EnforceBlockUpgradeMajority() const { return nEnforceBlockUpgradeMajority; } int RejectBlockOutdatedMajority() const { return nRejectBlockOutdatedMajority; } int ToCheckBlockUpgradeMajority() const { return nToCheckBlockUpgradeMajority; } int MaxReorganizationDepth() const { return nMaxReorganizationDepth; } /** Used if GenerateBitcoins is called with a negative number of threads */ int DefaultMinerThreads() const { return nMinerThreads; } const CBlock& GenesisBlock() const { return genesis; } /** Make miner wait to have peers to avoid wasting work */ bool MiningRequiresPeers() const { return fMiningRequiresPeers; } /** Headers first syncing is disabled */ bool HeadersFirstSyncingActive() const { return fHeadersFirstSyncingActive; }; /** Default value for -checkmempool and -checkblockindex argument */ bool DefaultConsistencyChecks() const { return fDefaultConsistencyChecks; } /** Allow mining of a min-difficulty block */ bool AllowMinDifficultyBlocks() const { return fAllowMinDifficultyBlocks; } /** Skip proof-of-work check: allow mining of any difficulty block */ bool SkipProofOfWorkCheck() const { return fSkipProofOfWorkCheck; } /** Make standard checks */ bool RequireStandard() const { return fRequireStandard; } int64_t TargetTimespan() const { return nTargetTimespan; } int64_t TargetSpacing() const { return nTargetSpacing; } int64_t Interval() const { return nTargetTimespan / nTargetSpacing; } int COINBASE_MATURITY() const { return nMaturity; } CAmount MaxMoneyOut() const { return nMaxMoneyOut; } /** The masternode count that we will allow the see-saw reward payments to be off by */ int MasternodeCountDrift() const { return nMasternodeCountDrift; } /** Make miner stop after a block is found. In RPC, don't return until nGenProcLimit blocks are generated */ bool MineBlocksOnDemand() const { return fMineBlocksOnDemand; } /** In the future use NetworkIDString() for RPC fields */ bool TestnetToBeDeprecatedFieldRPC() const { return fTestnetToBeDeprecatedFieldRPC; } /** Return the BIP70 network string (main, test or regtest) */ std::string NetworkIDString() const { return strNetworkID; } const std::vector<CDNSSeedData>& DNSSeeds() const { return vSeeds; } const std::vector<unsigned char>& Base58Prefix(Base58Type type) const { return base58Prefixes[type]; } const std::vector<CAddress>& FixedSeeds() const { return vFixedSeeds; } virtual const Checkpoints::CCheckpointData& Checkpoints() const = 0; int PoolMaxTransactions() const { return nPoolMaxTransactions; } /** Return the number of blocks in a budget cycle */ int GetBudgetCycleBlocks() const { return nBudgetCycleBlocks; } /** Spork key and Masternode Handling **/ std::string SporkKey() const { return strSporkKey; } std::string SporkKeyOld() const { return strSporkKeyOld; } int64_t NewSporkStart() const { return nEnforceNewSporkKey; } int64_t RejectOldSporkKey() const { return nRejectOldSporkKey; } std::string ObfuscationPoolDummyAddress() const { return strObfuscationPoolDummyAddress; } int64_t StartMasternodePayments() const { return nStartMasternodePayments; } int64_t Budget_Fee_Confirmations() const { return nBudget_Fee_Confirmations; } CBaseChainParams::Network NetworkID() const { return networkID; } /** Zerocoin **/ std::string Zerocoin_Modulus() const { return zerocoinModulus; } libzerocoin::ZerocoinParams* Zerocoin_Params(bool useModulusV1) const; int Zerocoin_MaxSpendsPerTransaction() const { return nMaxZerocoinSpendsPerTransaction; } CAmount Zerocoin_MintFee() const { return nMinZerocoinMintFee; } int Zerocoin_MintRequiredConfirmations() const { return nMintRequiredConfirmations; } int Zerocoin_RequiredAccumulation() const { return nRequiredAccumulation; } int Zerocoin_DefaultSpendSecurity() const { return nDefaultSecurityLevel; } int Zerocoin_HeaderVersion() const { return nZerocoinHeaderVersion; } int Zerocoin_RequiredStakeDepth() const { return nZerocoinRequiredStakeDepth; } /** Height or Time Based Activations **/ int ModifierUpgradeBlock() const { return nModifierUpdateBlock; } int LAST_POW_BLOCK() const { return nLastPOWBlock; } int Zerocoin_StartHeight() const { return nZerocoinStartHeight; } int Zerocoin_Block_EnforceSerialRange() const { return nBlockEnforceSerialRange; } int Zerocoin_Block_RecalculateAccumulators() const { return nBlockRecalculateAccumulators; } int Zerocoin_Block_FirstFraudulent() const { return nBlockFirstFraudulent; } int Zerocoin_Block_LastGoodCheckpoint() const { return nBlockLastGoodCheckpoint; } int Zerocoin_StartTime() const { return nZerocoinStartTime; } int Block_Enforce_Invalid() const { return nBlockEnforceInvalidUTXO; } int Zerocoin_Block_V2_Start() const { return nBlockZerocoinV2; } // fake serial attack int Zerocoin_Block_EndFakeSerial() const { return nFakeSerialBlockheightEnd; } CAmount GetSupplyBeforeFakeSerial() const { return nSupplyBeforeFakeSerial; } int Zerocoin_Block_Double_Accumulated() const { return nBlockDoubleAccumulated; } CAmount InvalidAmountFiltered() const { return nInvalidAmountFiltered; }; protected: CChainParams() {} uint256 hashGenesisBlock; MessageStartChars pchMessageStart; //! Raw pub key bytes for the broadcast alert signing key. std::vector<unsigned char> vAlertPubKey; int nDefaultPort; uint256 bnProofOfWorkLimit; int nMaxReorganizationDepth; int nSubsidyHalvingInterval; int nEnforceBlockUpgradeMajority; int nRejectBlockOutdatedMajority; int nToCheckBlockUpgradeMajority; int64_t nTargetTimespan; int64_t nTargetSpacing; int nLastPOWBlock; int nMasternodeCountDrift; int nMaturity; int nModifierUpdateBlock; CAmount nMaxMoneyOut; int nMinerThreads; std::vector<CDNSSeedData> vSeeds; std::vector<unsigned char> base58Prefixes[MAX_BASE58_TYPES]; CBaseChainParams::Network networkID; std::string strNetworkID; CBlock genesis; std::vector<CAddress> vFixedSeeds; bool fMiningRequiresPeers; bool fAllowMinDifficultyBlocks; bool fDefaultConsistencyChecks; bool fRequireStandard; bool fMineBlocksOnDemand; bool fSkipProofOfWorkCheck; bool fTestnetToBeDeprecatedFieldRPC; bool fHeadersFirstSyncingActive; int nPoolMaxTransactions; int nBudgetCycleBlocks; std::string strSporkKey; std::string strSporkKeyOld; int64_t nEnforceNewSporkKey; int64_t nRejectOldSporkKey; std::string strObfuscationPoolDummyAddress; int64_t nStartMasternodePayments; std::string zerocoinModulus; int nMaxZerocoinSpendsPerTransaction; CAmount nMinZerocoinMintFee; CAmount nInvalidAmountFiltered; int nMintRequiredConfirmations; int nRequiredAccumulation; int nDefaultSecurityLevel; int nZerocoinHeaderVersion; int64_t nBudget_Fee_Confirmations; int nZerocoinStartHeight; int nZerocoinStartTime; int nZerocoinRequiredStakeDepth; int nBlockEnforceSerialRange; int nBlockRecalculateAccumulators; int nBlockFirstFraudulent; int nBlockLastGoodCheckpoint; int nBlockEnforceInvalidUTXO; int nBlockZerocoinV2; int nBlockDoubleAccumulated; // fake serial attack int nFakeSerialBlockheightEnd = 0; CAmount nSupplyBeforeFakeSerial = 0; }; /** * Modifiable parameters interface is used by test cases to adapt the parameters in order * to test specific features more easily. Test cases should always restore the previous * values after finalization. */ class CModifiableParams { public: //! Published setters to allow changing values in unit test cases virtual void setSubsidyHalvingInterval(int anSubsidyHalvingInterval) = 0; virtual void setEnforceBlockUpgradeMajority(int anEnforceBlockUpgradeMajority) = 0; virtual void setRejectBlockOutdatedMajority(int anRejectBlockOutdatedMajority) = 0; virtual void setToCheckBlockUpgradeMajority(int anToCheckBlockUpgradeMajority) = 0; virtual void setDefaultConsistencyChecks(bool aDefaultConsistencyChecks) = 0; virtual void setAllowMinDifficultyBlocks(bool aAllowMinDifficultyBlocks) = 0; virtual void setSkipProofOfWorkCheck(bool aSkipProofOfWorkCheck) = 0; }; /** * Return the currently selected parameters. This won't change after app startup * outside of the unit tests. */ const CChainParams& Params(); /** Return parameters for the given network. */ CChainParams& Params(CBaseChainParams::Network network); /** Get modifiable network parameters (UNITTEST only) */ CModifiableParams* ModifiableParams(); /** Sets the params returned by Params() to those for the given network. */ void SelectParams(CBaseChainParams::Network network); /** * Looks for -regtest or -testnet and then calls SelectParams as appropriate. * Returns false if an invalid combination is given. */ bool SelectParamsFromCommandLine(); #endif // BITCOIN_CHAINPARAMS_H
[ "debian@guest.guest" ]
debian@guest.guest
ed2879e4a615271683a41e2b0551ffd479bf2dac
bda7d1bfc800e1bcf6a6e60ae3338b0d4f984881
/src/CULT/ChromaticPoint.cpp
0f181b0223db903205d1141ac3637d3ebb025114
[]
no_license
sylla-linoha/CULT
c0bb7f14d54cdba70ff310ff4a67d4402a0f86b5
ea5d453cd82b6361a1b735128b6a69b705316267
refs/heads/master
2022-10-06T06:28:21.591192
2012-01-30T10:26:57
2012-01-30T10:26:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
438
cpp
#include <iostream> #include <cstdlib> #include "ChromaticPoint.h" using namespace cv; using namespace std; ChromaticPoint::ChromaticPoint(Point _pt, double _dist) :leftPt(_pt), dist(_dist){} Point ChromaticPoint::getPt() { return leftPt; } void ChromaticPoint::setPt(Point pt) { leftPt = pt; } double ChromaticPoint::getDist() { return dist; } void ChromaticPoint::setDist(double _dist) { dist = _dist; }
[ "admin@cybunk.com" ]
admin@cybunk.com
004548f47c60f9aa7f183ea06962a9973b29e916
703d887e869b7d510eec309d7bfb0acc2da59c10
/damBreakmodified/0.95/nut
bc7bf5dab4db54e0c752b56a9d66d4f7d53ebbec
[]
no_license
luiscascelli/OpenFoam
a063df7af02b89abdc36268aaa21f5b012963b74
9ff3218c8ba584fe15017c766aed9afccf5ddd00
refs/heads/master
2023-08-01T00:12:25.059964
2021-09-14T19:37:54
2021-09-14T19:37:54
406,498,391
0
0
null
null
null
null
UTF-8
C++
false
false
70,002
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 8 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "0.95"; object nut; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 2 -1 0 0 0 0]; internalField nonuniform List<scalar> 1924 ( 0.0016315 0.00176681 0.00221151 0.00234029 0.0018187 0.00233549 0.00239385 0.00239505 0.00244187 0.00219779 0.00244376 0.00251067 0.0018613 0.00250808 0.0026827 0.0026753 0.00188613 0.00259645 0.00153627 0.00259645 0.00175366 0.00206332 0.00183602 0.00269774 0.00206164 0.0023806 0.00236569 0.002033 0.0017972 0.00251789 0.00188547 0.00217134 0.00160619 0.00186899 0.00204312 0.00182721 0.00222269 0.00187833 0.00253808 0.00191005 0.00233713 0.00179777 0.00236309 0.00178128 0.00229338 0.0017422 0.00156586 0.00236648 0.00109769 0.00136342 0.00156875 0.00186283 0.00202403 0.00148443 0.00175461 0.00221883 0.00151708 0.00228634 0.00213658 0.00240965 0.00171377 0.0026192 0.00167961 0.00249643 0.00141479 0.00236557 0.00248383 0.00187953 0.00176321 0.00161977 0.00182002 0.00261488 0.00250672 0.00253005 0.00257092 0.00189107 0.0024172 0.00258804 0.00242019 0.00162648 0.00276083 0.0023521 0.0023763 0.00175753 0.00152588 0.00185573 0.0021303 0.00267762 0.0011734 0.00181972 0.00245333 0.00238172 0.00176552 0.00189037 0.00186883 0.00120017 0.00241578 0.00275515 0.00238501 0.00189068 0.00210766 0.00186765 0.00236904 0.00236724 0.00192648 0.0026648 0.0018823 0.00197751 0.0024242 0.00181266 0.00241978 0.00180171 0.00189246 0.00243645 0.00246544 0.00168594 0.00219518 0.00267478 0.00177567 0.00246738 0.0012744 0.000318191 0.00152804 0.00168403 0.00253877 0.00200739 0.00193824 0.00263134 0.00182309 0.000391002 0.00249239 0.00201643 0.000201507 0.00242975 0.00189626 0.0019345 0.00195416 0.00185358 0.0027067 0.00198653 0.00229839 0.0025367 0.000102808 0.000113557 0.0022305 0.00122893 0.00199912 0.00189416 0.00244178 0.00171808 0.00237178 0.000157479 0.0019516 0.00201493 0.00232018 0.00202994 0.000321739 0.00205854 0.00249008 0.000255109 0.00248113 0.00182472 0.00217189 0.000320266 0.00229961 0.00195889 0.00203068 0.000241902 0.00249719 0.00185005 0.00174027 0.00233084 0.00268756 0.0023938 0.0022892 0.00210318 0.00249099 0.000402405 0.00176116 0.00217037 0.00220459 0.0027134 0.00251978 0.00204821 0.000913961 0.00174415 0.0020038 0.00224403 0.00251341 0.0024854 0.00202835 0.00238998 0.0025737 0.00230975 0.00203334 0.000159776 0.00225782 0.00213581 0.00215151 0.00214163 0.000302109 0.00182468 0.00195332 0.00239444 0.00179243 0.00223783 0.00230507 0.00202234 0.00193986 0.000153724 0.000326245 0.00186562 0.00272741 0.0020522 0.00226372 0.00261818 0.00244592 0.00205827 0.00238808 0.00265325 0.00206246 0.00234548 0.00196752 0.00272067 0.00244223 0.00227319 0.00257394 0.00271699 0.00205738 0.00214165 0.000272225 0.00240299 0.00219495 0.000364427 0.00226163 0.000194221 0.00275669 0.00238899 0.00196588 0.000162892 0.0027092 0.00223043 0.00276179 0.00204442 0.000346907 0.00194307 0.00244554 0.00236829 0.002557 0.00271039 0.00187248 0.000287842 0.00207609 0.00188264 0.00256493 0.00273629 0.00239633 0.00217611 0.00210162 0.0024419 0.00210916 0.00197962 0.00240721 0.00258452 0.00218518 0.00261036 0.00174291 0.00269148 0.00182739 0.000273369 0.00211464 0.00237486 0.0017105 0.00225155 0.00241287 0.00277185 0.00249358 0.00227072 0.00193606 0.00219021 0.000275751 0.000117935 0.00240498 0.00210801 0.00128577 0.00251034 0.00264938 0.000305418 0.00244502 0.00221348 0.0020249 0.00255195 0.00226426 0.00276336 0.00140448 0.00230106 0.00272928 0.00205427 0.00267392 0.00275816 0.000180955 0.00194846 0.00277754 0.00244412 0.00249439 0.00231106 0.0017531 0.00278068 0.00215298 0.00234937 0.00198453 0.00166071 0.00212518 0.00194557 0.00259397 0.00177161 0.00214324 0.00248711 0.00203698 0.00213166 0.00258478 0.00210327 0.0020631 0.00234716 0.00234298 0.00274953 0.0022611 0.00224765 0.00236534 0.00266836 0.00217952 0.00248828 0.00192258 0.00257857 0.00265488 0.00227546 0.00242768 0.00212664 0.002196 0.00206849 0.00273943 0.00241651 0.00200102 0.00206291 0.00273254 0.0026223 0.000235315 0.00254125 0.00163832 0.00233976 0.00233575 0.000288888 0.000514111 0.00277369 0.00198954 0.00272323 0.000832092 0.00249102 0.00211925 0.00112222 0.00229155 0.00275314 0.00277772 0.00243376 0.00228191 0.00222351 0.00195496 0.00205622 0.00221016 0.00213502 0.00278828 0.00215709 0.00222166 0.00271296 0.00240036 0.000358851 0.00274766 0.00272447 0.00210418 0.0025663 0.00261909 0.00270574 0.00227782 0.00214833 0.00214349 0.00279059 0.00263435 0.00248354 0.00240344 0.00221919 0.000461224 0.00191681 0.00229616 0.00249407 0.00226449 0.000128132 0.00237933 0.00201593 0.00272451 0.00266954 0.00132243 0.0026864 0.00204124 0.00188197 7.28119e-05 0.00244254 0.00278597 0.00251894 0.00210933 0.00235707 0.00230656 0.00190424 0.00257735 0.00233779 0.00229071 0.0024068 0.0027704 0.00275572 0.00185128 0.00240377 0.00276063 0.00204131 0.00278415 0.00200391 0.00221303 0.00278105 0.00264331 0.00252798 0.00195067 0.0024198 0.00244819 0.00275986 0.00242952 0.0018831 0.00227008 0.00242397 0.00278507 0.00163077 0.00233863 0.00212605 0.00212102 0.00239723 0.00217162 0.00207248 0.00256317 0.000162874 0.00234582 0.00266624 0.00231304 0.002486 0.00271967 0.00192311 0.00217171 0.00273504 0.00238355 0.00231028 0.00279241 0.00273422 0.00184911 0.00261925 0.00274356 0.00200968 0.00175513 0.00178448 0.00203978 0.00249245 0.00251789 0.00230247 0.0024238 0.00241851 0.00229623 0.00190035 0.00259887 0.0027937 0.00199599 0.00272865 0.00249265 0.00257546 0.00256466 0.00266811 0.00236352 0.00235615 0.00245253 0.00252369 0.0019628 0.00224991 0.00241665 0.00270796 0.00243607 0.00266922 0.00168828 0.00243407 0.00189123 0.0024046 0.00275758 0.00278574 0.00261535 0.00245827 0.00239803 0.00234407 0.00276343 0.00272843 0.00208078 0.00207722 0.00199142 0.0023693 0.00273105 0.00232671 0.00192295 0.0027852 0.00270829 0.00277679 0.00247619 0.00218999 0.00249349 0.00249972 0.00202434 0.00231672 0.0024273 0.00266281 0.00187145 0.0027252 0.00275934 0.00279191 0.00220861 0.00230832 0.00263327 0.00169506 0.00229003 0.00237617 0.00178205 0.00262698 0.00190392 0.00179322 0.00200741 0.00252057 0.00236181 0.00198584 0.00179036 0.00213968 0.00196116 0.00238321 0.00160779 0.0026923 0.00279497 0.00242473 0.00253244 0.00247531 0.00255817 0.00275558 0.00240101 0.00245945 0.00270233 0.00188958 0.00234508 0.0017669 0.00169302 0.00153488 0.00221642 0.00248314 0.0020963 0.001852 0.00193843 0.00246442 0.00206738 0.00188805 0.0027425 0.00246038 0.00257198 0.00193438 0.00279061 0.00243771 0.00229039 0.00247834 0.00265359 0.00249951 0.00172018 0.00199866 0.00276011 0.00177139 0.00199314 0.00261591 0.0024759 0.00248432 0.00139246 0.00161506 0.00272364 0.0016224 0.00277722 0.00241614 0.00216768 0.00188356 0.000289804 0.00144992 0.00155071 0.00277602 0.0025019 0.00266559 0.0025218 0.00173246 0.00112122 0.00271632 0.00238498 0.00247361 0.00190528 0.00262931 0.00231932 0.00271991 0.00192755 0.00164079 0.00213198 0.00271938 0.0017122 0.00270443 0.0019726 0.00255976 0.00222504 0.00200321 0.00128824 0.00240592 0.0027911 0.00275832 0.00245888 0.0020186 0.0024311 0.00261028 0.00163555 0.00260428 0.00232484 0.00170312 0.00266278 0.00234723 0.00269981 0.00168307 0.00189267 0.0011605 0.00227604 0.0021017 0.0023983 0.00279669 0.00245434 0.00246667 0.00193573 0.00216147 0.00218366 0.00270024 0.00200187 0.00269315 0.00242051 0.0020308 0.00186827 0.00247202 0.0020912 0.00227174 0.00161488 0.00248528 0.0018032 0.00270712 0.00212107 0.00169535 0.00183589 0.00157712 0.00263921 0.00279253 0.00248799 0.00246818 0.00203823 0.00265 0.00188162 0.00191537 0.00196813 0.00273068 0.00168868 0.00273695 0.00269115 0.00277939 0.00248082 0.00270036 0.00152564 0.00162994 0.00274482 0.0027131 0.00255173 0.00251926 0.00202356 0.00243608 0.00250134 0.00182487 0.00277035 0.00154948 0.00246758 0.00244261 0.0025391 0.00215763 0.00186425 0.00268294 0.00162684 0.00267051 0.00194994 0.0019931 0.00275062 0.00170179 0.00226967 0.00197107 0.00143136 0.00232474 0.00244485 0.00210077 0.00278699 0.00189286 0.00187945 0.00153307 0.00244668 0.00170134 0.00204286 0.00233901 0.00246813 0.00179639 0.00265993 0.00111779 0.00265485 0.00260751 0.00271431 0.00154283 0.00268618 0.00028484 0.000157909 0.001274 0.00196575 0.00279759 0.00246877 0.00163063 0.00229296 0.00198003 0.00252274 0.00202935 0.00250512 0.00238721 0.00255535 0.00174851 0.00145938 0.00248413 0.00272701 0.000202263 0.00253135 0.0004154 0.00191594 0.00154532 0.0018838 0.00279527 0.00201422 0.00214566 0.00254895 0.0023403 0.00234478 0.00228736 0.00246384 0.00131881 0.00134232 0.00259153 0.00253015 0.00248732 0.00268392 0.00277786 0.00200344 0.00156055 0.00204983 0.00194903 0.00149738 0.00213948 0.00265274 0.00206397 0.00221688 0.00242046 0.00196914 0.00274077 0.00190165 0.00203696 0.00147264 0.00236366 0.00167246 0.00267602 0.00249537 0.00197462 0.00269626 0.00255202 0.00270228 0.00224608 0.0026759 0.00237859 0.00158905 0.00183814 0.00269688 0.00241532 0.0019798 0.00275247 0.00276155 0.0013252 0.00225916 0.00187375 0.0016978 0.00195705 0.00203515 0.0024216 0.00267969 0.00267876 0.00240316 0.00263617 0.00245284 0.00193031 0.00257943 0.00278967 0.00226937 0.000241354 0.00187798 0.00149251 0.00256121 0.00149038 0.00202429 0.00183643 0.00175604 0.00234696 0.00265165 0.00146588 0.00250303 0.00279631 0.00196465 0.00252203 0.00245406 0.00152473 0.00268725 0.0026955 0.00188542 0.00206259 0.00200543 0.00205999 0.00266657 0.00255134 0.00279626 6.84785e-05 0.0026445 0.000261642 0.00207814 0.00206254 0.000843202 0.00183018 0.00210009 0.00199284 0.00259906 0.0018708 0.00255036 0.00247776 0.00144201 0.00266697 0.0026707 0.00230669 0.00179511 0.00190166 0.00143456 0.00259163 0.0025277 0.00266162 0.00229652 0.00250656 0.00167811 0.00238001 0.00144925 0.00204911 0.00146215 0.00157591 0.00278324 0.00187696 0.00159405 0.00249968 0.00192636 0.00246938 0.00267278 0.00159378 0.000233666 0.00218664 0.00241295 0.00188018 0.00258501 0.00253155 0.0021162 0.00202927 0.00237923 0.00263488 0.0024831 0.00250864 0.00195626 0.00272853 0.000198204 0.00267259 0.00271397 0.00273055 0.00277512 0.00264223 0.00169761 0.00269967 0.00152102 0.0025499 0.00189277 0.00128074 0.0020987 0.0020171 0.00266585 0.00143481 0.00208973 0.0026589 0.00209736 0.00241209 0.00278497 8.77519e-05 0.00131225 0.00243131 0.00141443 0.00208241 0.001912 0.00259469 0.00257911 0.00269131 0.00198166 0.00147675 0.00280076 0.00156017 0.00269442 0.0023596 0.00260968 0.00209341 0.00194151 0.00262218 0.00205645 0.00184419 0.0022538 0.00193532 0.00256324 0.00187199 0.0020969 0.00243543 0.00258736 0.00013355 0.00279871 0.00149813 0.000270689 0.00214428 0.00196899 0.0022524 0.00146296 0.00267521 0.00175854 0.00204067 0.000205406 0.0018781 0.00252853 9.83735e-05 0.00160821 0.000156419 0.00150479 0.00259651 0.00196573 0.00276598 0.00188344 0.00265757 0.00141177 0.00234742 0.0026606 0.00200225 0.00214023 0.00142142 0.0025869 0.00189188 0.00258577 0.00212488 0.00269413 0.00238472 0.00213007 0.00213783 0.00250558 0.00199965 0.00265618 0.00213038 0.00165896 0.00190769 0.00209664 0.00247235 0.00199028 0.00222569 0.00237917 0.00186544 0.00195507 0.00235066 0.00273362 0.0019308 0.00187427 0.00258202 0.00183064 0.00253634 0.00255768 0.00157177 0.00207009 0.00140011 0.00178811 0.00258412 0.00188085 0.00192994 0.00269096 0.00272009 0.00275692 0.00214237 0.00195168 0.0014184 0.00263299 0.00213299 0.00276893 0.00279566 0.00213746 0.00211329 0.00188168 0.00202212 0.00269434 0.00267848 0.00270497 0.000114386 0.00257263 0.00260587 0.00222634 0.00189384 0.00241674 0.00243394 0.00246908 0.0018814 0.00167465 0.00279873 0.0025135 0.00126726 0.00130324 0.0019177 0.00271334 0.00226242 0.00200901 0.00156603 0.00268124 0.00268631 0.00248055 0.00261387 0.00214794 0.00277899 0.00218094 0.00216835 0.00223108 0.00193993 0.00266468 0.00150921 0.00196447 0.00274096 0.00260308 0.00211519 0.00266469 0.00242564 0.00185854 0.00216851 0.0015724 0.00186619 0.00236895 0.00153532 0.00257722 0.00268973 0.0020497 0.0027705 0.00137239 0.00266291 0.00137748 0.00195346 0.00186433 0.00215877 0.0023287 0.000267319 0.0026006 0.00185477 0.002029 0.000586967 0.00213269 0.00187139 0.00112134 0.00149817 0.00183158 0.00265313 0.00213026 0.00264631 0.00217339 0.00190109 0.00257424 0.000589349 0.000584674 0.00197185 0.00213946 0.00269123 0.00271907 0.00233857 0.00141281 0.00185644 0.00192277 0.00171664 0.000592367 0.00219416 0.00101955 0.00159834 0.002203 0.00253875 0.00216874 0.00147265 0.0025116 8.61673e-05 9.29918e-05 0.00259912 0.00153036 0.00196111 0.00273913 0.00186276 0.00209576 0.00220873 0.00148829 0.00262835 0.00274928 0.00278582 0.00203417 0.00222282 0.00184566 0.000592545 0.00260229 0.00259419 0.00247314 0.00268277 0.00182793 0.00184715 0.0020584 0.00279055 0.00277724 0.00129181 0.00187935 0.0026182 0.000119051 0.00126952 0.0015045 0.00193245 0.000587717 0.00197947 0.00190659 0.000582505 0.000206959 0.00223371 0.00277799 0.00267222 0.00257051 0.00268598 0.00269588 0.00153008 0.00241546 0.00204377 0.00213639 0.00218512 0.000129645 0.000589694 0.00196857 0.00025467 0.00131716 0.00213667 0.00270351 0.0019172 0.00268991 0.0018133 0.00160393 0.00134939 0.00265354 0.00254863 0.00214236 0.00221897 0.00247686 0.00252192 0.00248448 0.00150281 0.00265598 0.00175442 0.00218291 0.00181975 0.000268752 0.00193594 0.00222183 0.0021499 0.000591641 0.00183517 0.00220958 0.00226436 0.000578915 0.00261338 0.00128984 0.00210748 0.00181565 0.00142546 0.00242838 0.00269081 0.0021699 0.00181988 0.00233329 0.00176036 0.00199683 0.00141044 0.00265889 0.00258967 0.00182951 0.00268239 0.00147232 0.00264345 0.00206491 0.00183461 0.00263616 0.0019168 0.00277233 9.07061e-05 0.000108975 0.00221916 0.00197805 0.0018641 0.00193066 0.00268771 0.0015031 0.00140791 0.00101394 0.000595311 0.00277923 0.00193687 0.00221427 0.00273613 0.00260857 0.0025837 0.00263025 0.00179694 0.00234929 0.00177736 0.00268113 0.0025521 0.0022368 0.00125883 0.00123849 0.00267781 0.00187241 0.00215645 0.00179604 0.000159382 0.00217096 0.00181047 0.00256294 0.00169775 0.00248244 0.000579846 0.00277129 0.00177879 0.000336165 0.00215934 0.00252226 0.00177048 0.000130354 0.00167479 0.00191794 0.00144177 0.00158364 0.00181038 0.00175187 0.00272868 0.00219137 0.00277303 0.00134779 0.00143881 0.00271098 0.00203556 0.00266759 0.00216189 0.00171231 0.00141862 0.00119526 0.00242768 0.00259988 0.000269492 0.00253393 0.000602832 0.0022269 0.00265854 0.00220262 0.00199561 0.00256498 0.00183431 0.00249545 0.00132277 0.00225726 0.00140906 0.00262412 0.00265072 0.00220196 0.00187043 0.000292178 0.00222788 0.00192495 0.0012739 0.00269245 0.00253517 0.00270454 0.00244285 0.000293298 0.00175794 0.00264578 0.00263803 0.000294503 0.0013079 0.00191216 0.00276581 0.00247644 0.00132387 0.00257452 0.00221216 0.000181075 0.00261447 0.00249706 0.00254579 0.00184677 0.0021805 0.000291121 0.00259032 0.00275865 0.00144797 0.00235629 0.00269282 0.00160939 0.00217308 0.00221128 0.00148066 0.0027679 0.00149102 0.00269224 0.000291608 0.000292731 0.00142437 0.0017162 0.0025657 0.00012954 0.00218184 0.00250952 0.000375814 0.00237328 0.00187566 0.00263722 0.00270377 0.000186656 0.000293318 0.00254066 0.00266537 0.000613993 8.05538e-05 8.61199e-05 0.00129078 0.00141736 0.00253843 0.00124832 0.00209052 0.00267942 0.00219794 0.00244829 0.00267105 0.00217361 0.000120568 0.00219921 0.000288976 0.000290265 0.00268628 0.00265761 0.00130657 0.000294249 0.00221151 0.00130932 0.00203807 0.000383869 0.00134376 0.000386012 0.00225841 0.0002695 0.0015095 0.00159041 0.000395203 0.002701 0.000277089 0.00246142 0.00192188 0.000563661 0.000395108 0.00251042 0.000391253 0.00276711 0.000175554 0.0004076 0.00185275 0.00121616 0.00250986 0.00256835 0.000161868 0.000295625 0.000406794 0.00221892 0.00143343 0.00230248 0.0022241 0.00259211 0.00190378 0.00263364 0.00218814 0.00193123 0.00218021 0.00039122 0.00261356 0.00182619 0.00237439 0.00276317 0.00219132 0.00145833 0.00209076 0.00012866 0.00125827 0.000386564 0.0027006 0.00273511 0.00216972 0.00187478 0.00238978 0.00128189 0.00245922 0.00219034 0.000298548 0.00276461 0.0026839 0.0013822 0.000616328 0.00270129 0.00244884 0.00265172 0.00267593 0.00211094 0.000386363 0.00220628 0.00213122 0.000377028 0.0022939 0.00269959 0.000619614 0.00257416 0.00275722 0.00268982 0.000388844 0.00261826 0.00221727 0.00209716 0.000354017 0.00218847 0.00185886 0.00259671 0.00209931 0.000283833 0.00221278 0.00270484 0.00221203 0.00270287 0.00217883 0.00263799 0.00137627 0.00269713 0.00121198 0.00269871 0.00134895 0.00233079 0.000111427 0.00063544 0.000628887 0.00030363 0.0019391 0.000273811 0.00219943 0.00239022 0.00119688 0.000284906 0.000126484 0.00138718 0.00210659 0.00275209 0.00273008 0.00142332 0.00275847 0.00275639 0.000305427 0.00215193 0.00131394 0.00213289 0.00221225 0.00241664 0.00219136 0.00189927 0.00136694 0.002698 0.00039685 0.0020885 0.00221209 0.00270056 0.0021597 0.00122386 0.000189127 0.00266744 0.000440087 0.000188274 0.00199259 0.000191241 0.00211377 0.00270142 0.000190234 0.00216693 0.000599398 0.000187042 0.00216298 0.00271207 0.000290642 0.000197269 0.000199324 0.00213631 0.00192026 0.00214611 0.00269326 0.0018757 0.00219975 0.00265557 0.00201675 8.06748e-05 7.76156e-05 0.000187633 0.00198186 0.00230506 0.00201824 0.000643277 0.00220263 0.00024881 0.000635665 0.00217809 0.00207332 0.000639435 0.000299242 0.00142964 0.00126454 0.000184547 0.000646269 0.0019738 0.000128653 0.00270223 0.00217397 0.00211231 0.0027496 0.00215784 0.000191893 0.000189378 0.00234269 0.001993 0.000182022 0.00270591 0.000396847 0.00216495 0.0018607 0.000111546 0.000266499 0.000281924 0.000582567 0.00143385 0.00269507 0.00271286 0.00208476 0.00204042 0.00271611 0.00270635 0.00203199 0.0027168 0.00217695 0.000160796 0.00273277 0.00271454 0.00192754 0.000307401 0.00275384 0.000188266 0.00271235 0.00168375 0.000240893 0.000263668 0.00274675 0.00216007 0.00206261 0.00201316 0.000290442 0.00196876 0.000112617 0.000302612 0.000626686 0.0020707 0.00272756 0.00271646 0.00206196 0.00274948 0.00202083 0.000647393 0.00198816 0.000309662 0.000311669 0.00269048 0.000134626 0.00210251 0.000634167 0.00214041 0.00274114 0.0018717 0.00270895 0.0018336 0.00268099 0.00106915 0.00272824 0.000188812 0.00013651 0.00211964 0.000320409 0.000134849 0.00273752 0.00200335 0.00197733 0.000311412 0.00208096 0.000289021 0.000557406 0.0027214 0.00273648 0.000314474 0.000643366 0.00201781 0.000317738 0.00271937 0.00199096 0.00015683 0.00198787 0.00267106 0.00198091 0.000633342 0.00184636 0.00274005 0.000135575 0.0001293 0.00273209 0.00106348 0.00214576 0.00273841 0.00273305 0.00274629 0.00198061 0.00181708 0.000322284 0.00272747 0.00272347 0.0020205 0.00274088 0.00202724 0.00269407 0.000226915 0.000104338 0.00191907 0.00274489 0.00269764 0.00131916 0.00210262 0.000440287 0.000282738 0.00272276 0.00268385 0.000446495 0.00273316 0.000401526 0.000189472 0.00191095 0.0019255 0.00197297 0.00189736 0.000315923 0.000317926 0.00186005 0.000650878 0.000435868 0.000445155 0.00187899 0.00135767 0.00193807 0.0027108 0.00191585 0.000214198 9.29563e-05 0.00271705 0.00186643 0.00269951 0.000647673 0.000323151 0.00271669 0.00272625 0.00179662 0.00269208 0.00183998 0.00265895 0.00272103 0.000437715 0.000320063 0.001911 0.000631698 0.00180317 0.000217108 0.00265982 0.000215686 0.000523165 0.000269126 0.00268526 0.000316295 0.00270516 0.000649754 0.00189386 0.00267754 0.000215127 0.000437117 0.00187587 0.000385181 0.000406599 0.000188907 0.00267672 0.000129135 0.0026666 0.000210368 0.00182955 0.00268014 0.00259207 0.000317903 0.000323308 0.000646934 0.000647488 0.000437641 0.000647793 0.000211436 0.00020722 0.00258378 0.00264674 0.00264027 0.00187391 0.000310314 0.000202345 0.000444985 0.00183351 0.00261019 0.0025391 0.00188036 0.00266965 0.00263248 0.00188104 0.000284112 0.000615721 0.0018702 0.000314447 0.00060058 0.000267412 0.000514705 0.00244801 0.00253218 7.96666e-05 0.000166556 0.000204842 6.43659e-05 0.000548087 9.28624e-05 0.000179988 0.000391104 0.00023155 0.000416751 0.000193666 0.000182137 0.000406452 0.000183468 0.000189272 0.000400483 0.000646991 0.000319729 0.000323341 0.000306451 0.000635527 0.000323393 0.000648186 0.000244652 0.000177544 0.000171433 0.000394324 0.000180244 0.000185273 0.000413923 0.000323591 0.00242032 0.00250441 0.00260538 0.00265825 0.00263941 0.00028201 0.000122079 0.00164825 0.00138003 0.00159914 0.000110703 0.00130095 0.00190625 0.00116498 0.00131963 0.000278115 0.000188782 0.00251144 0.00153765 0.000150768 0.000113123 0.000120062 0.00190177 0.000836954 0.00174126 0.00195482 0.00011142 0.00156402 0.00210852 0.0016072 7.71256e-05 7.59917e-05 9.04846e-05 7.43114e-05 0.000113655 7.39025e-05 8.02606e-05 7.64057e-05 0.00213126 0.000290399 0.00138313 7.22639e-05 5.32071e-05 5.81472e-05 0.000248318 0.00208327 0.00188481 8.33643e-05 6.54978e-05 6.36296e-05 0.00137623 0.00147283 0.000177547 0.00136069 0.0025602 0.00116976 0.000807775 0.000186984 8.03286e-05 0.000255619 0.000158195 0.000270197 0.000165967 0.000165732 0.000161064 5.12417e-05 5.40281e-05 0.00211086 0.00207871 0.00104853 0.0025865 9.93285e-05 0.000171799 0.000167981 0.000984406 0.00145779 0.000184551 0.00203878 0.00100243 0.00162171 0.00157135 7.18736e-05 0.00143427 0.00106762 0.00117859 0.000178937 0.00278329 0.00135994 0.00202959 9.07961e-05 0.000989613 0.0027655 0.000970236 0.000147379 7.04434e-05 0.00164366 0.00198308 0.00274437 0.000839003 0.00113569 6.21841e-05 0.00197113 0.00276123 0.00119095 0.00278098 0.0019339 0.000174533 0.00192166 0.00276963 0.00132198 0.00187738 0.00133372 0.00122699 0.00116403 4.76987e-05 0.00189127 0.000144388 6.48467e-05 0.0027512 ) ; boundaryField { patch0 { type nutkWallFunction; Cmu 0.09; kappa 0.41; E 9.8; value nonuniform List<scalar> 4010 ( 0.000164234 0.000164234 0.000204775 0.000204775 0.000206561 0.000206561 0.000225102 0.000225102 0.000211363 0.000211363 0.000245277 0.000245277 0.000260285 0.000260285 0.000273999 0.000273999 0.000278863 0.000278863 0.000205188 0.000205188 0.00027919 0.00027919 0.000285497 0.000285497 0.000215495 0.000215495 0.000285301 0.000285301 0.000300867 0.000300867 0.000302238 0.000302238 0.000215806 0.000215806 0.000292948 0.000292948 0.000147567 0.000147567 0.000293256 0.000293256 0.000191527 0.000191527 0.000238204 0.000238204 0.000186124 0.000186124 0.00029609 0.00029609 0.000238219 0.000238219 0.000273538 0.000273538 0.000272319 0.000272319 0.000189216 0.000189216 0.000206515 0.000206515 0.000283476 0.000283476 0.000200666 0.000200666 0.000247821 0.000247821 0.000167541 0.000167541 0.000214598 0.000214598 0.000191229 0.000191229 0.000185 0.000185 0.000250802 0.000250802 0.000206263 0.000206263 0.000284935 0.000284935 0.000218898 0.000218898 0.000260305 0.000260305 0.000180769 0.000180769 0.000262491 0.000262491 0.000191441 0.000191441 0.00026269 0.00026269 0.000203652 0.000203652 0.000148616 0.000148616 0.000270808 0.000270808 0.000106792 0.000106792 0.000158422 0.000158422 0.000159676 0.000159676 0.000215533 0.000215533 0.000227804 0.000227804 0.000142926 0.000142926 0.000205267 0.000205267 0.0002071 0.0002071 0.00014461 0.00014461 0.000262155 0.000262155 0.00019753 0.00019753 0.000275971 0.000275971 0.000195098 0.000195098 0.000296824 0.000296824 0.000191623 0.000191623 0.000283862 0.000283862 0.000134832 0.000134832 0.000270824 0.000270824 0.000284074 0.000284074 0.000219406 0.000219406 0.000205833 0.000205833 0.000164448 0.000164448 0.000198698 0.000198698 0.000295151 0.000295151 0.000285145 0.000285145 0.000288047 0.000288047 0.000292107 0.000292107 0.000206077 0.000206077 0.000276157 0.000276157 0.000287464 0.000287464 0.000276388 0.000276388 0.000185681 0.000185681 0.000309144 0.000309144 0.000270943 0.000270943 0.000271981 0.000271981 0.000204601 0.000204601 0.000155233 0.000155233 0.000215475 0.000215475 0.000197089 0.000197089 0.000297177 0.000297177 0.000113694 0.000113694 0.000203334 0.000203334 0.000279252 0.000279252 0.000274251 0.000274251 0.000206389 0.000206389 0.00021624 0.00021624 0.000216326 0.000216326 0.000115714 0.000115714 0.00027608 0.00027608 0.000308279 0.000308279 0.000274908 0.000274908 0.000204847 0.000204847 0.000216067 0.000216067 0.000216212 0.000216212 0.00027347 0.00027347 0.000272974 0.000272974 0.0002135 0.0002135 0.000292239 0.000292239 0.000218468 0.000218468 0.000225365 0.000225365 0.000278161 0.000278161 0.000211101 0.000211101 0.00027652 0.00027652 0.000210096 0.000210096 0.000208482 0.000208482 0.000278591 0.000278591 0.000280812 0.000280812 0.000196886 0.000196886 0.000207435 0.000207435 0.00029897 0.00029897 0.000192362 0.000192362 0.00028116 0.00028116 0.000129526 0.000129526 3.46751e-05 3.46751e-05 0.000175771 0.000175771 0.000196642 0.000196642 0.000289382 0.000289382 0.000223214 0.000223214 0.000211077 0.000211077 0.000289058 0.000289058 0.000212695 0.000212695 4.18083e-05 4.18083e-05 0.000283317 0.000283317 0.000232021 0.000232021 2.08313e-05 2.08313e-05 0.00027742 0.00027742 0.000216611 0.000216611 0.000214091 0.000214091 0.000213229 0.000213229 0.000215291 0.000215291 0.000296666 0.000296666 0.000218087 0.000218087 0.000215205 0.000215205 0.000289226 0.000289226 1.22205e-05 1.22205e-05 1.22205e-05 9.86593e-06 9.86593e-06 9.86593e-06 0.000217202 0.000217202 0.000118648 0.000118648 0.000228718 0.000228718 0.000205908 0.000205908 0.000279615 0.000279615 0.000178467 0.000178467 0.000271448 0.000271448 1.81632e-05 1.81632e-05 1.81632e-05 0.000217045 0.000217045 0.000222725 0.000222725 0.000228845 0.000228845 0.000223799 0.000223799 3.50296e-05 3.50296e-05 0.00020666 0.00020666 0.000283088 0.000283088 3.01862e-05 3.01862e-05 0.000283348 0.000283348 0.000211615 0.000211615 0.000237909 0.000237909 3.48827e-05 3.48827e-05 0.000262992 0.000262992 0.000216565 0.000216565 0.000223794 0.000223794 2.69783e-05 2.69783e-05 0.000283998 0.000283998 0.000211859 0.000211859 0.000203302 0.000203302 0.000244268 0.000244268 0.000294955 0.000294955 0.00027559 0.00027559 0.000230731 0.000230731 0.000238006 0.000238006 0.000282865 0.000282865 4.84808e-05 4.84808e-05 0.000178742 0.000178742 0.000224286 0.000224286 0.000253308 0.000253308 0.000302082 0.000302082 0.000286412 0.000286412 0.000233301 0.000233301 9.04922e-05 9.04922e-05 0.000167721 0.000167721 0.000222363 0.000222363 0.000257714 0.000257714 0.000285448 0.000285448 0.000283541 0.000283541 0.000231344 0.000231344 0.00025769 0.00025769 0.000291468 0.000291468 0.000237789 0.000237789 0.000235432 0.000235432 1.84088e-05 1.84088e-05 1.84088e-05 0.000260891 0.000260891 0.000242183 0.000242183 0.000246285 0.000246285 0.00024626 0.00024626 3.3605e-05 3.3605e-05 0.00018357 0.00018357 0.00021603 0.00021603 0.000273561 0.000273561 0.000209054 0.000209054 0.000257075 0.000257075 0.000237303 0.000237303 0.0002079 0.0002079 0.000223205 0.000223205 1.72163e-05 1.72163e-05 1.72163e-05 3.54772e-05 3.54772e-05 0.000217059 0.000217059 0.000299046 0.000299046 0.000237769 0.000237769 0.000260825 0.000260825 0.000287235 0.000287235 0.000276628 0.000276628 0.000234549 0.000234549 0.000250298 0.000250298 0.000291564 0.000291564 0.0002335 0.0002335 0.000257903 0.000257903 0.000217292 0.000217292 0.000298451 0.000298451 0.000278294 0.000278294 0.000262298 0.000262298 0.000291266 0.000291266 0.000298232 0.000298232 0.000238256 0.000238256 0.000246694 0.000246694 3.05955e-05 3.05955e-05 0.000276239 0.000276239 0.00025119 0.00025119 4.38707e-05 4.38707e-05 0.000260946 0.000260946 2.32435e-05 2.32435e-05 2.32435e-05 0.000302876 0.000302876 0.000263648 0.000263648 0.000220444 0.000220444 1.87394e-05 1.87394e-05 1.87394e-05 0.000306004 0.000306004 0.000258137 0.000258137 0.000308376 0.000308376 0.000210227 0.000210227 4.04814e-05 4.04814e-05 0.000224146 0.000224146 0.000279524 0.000279524 0.000271141 0.000271141 0.000287555 0.000287555 0.000300479 0.000300479 0.000173653 0.000173653 3.16337e-05 3.16337e-05 0.000230311 0.000230311 0.00021868 0.00021868 0.000289866 0.000289866 0.000300052 0.000300052 0.000272421 0.000272421 0.000252685 0.000252685 0.000238188 0.000238188 0.000274628 0.000274628 0.000242221 0.000242221 0.000228393 0.000228393 0.00027692 0.00027692 0.000286012 0.000286012 0.000242877 0.000242877 0.000292701 0.000292701 0.000170029 0.000170029 0.000296239 0.000296239 0.000212871 0.000212871 3.02464e-05 3.02464e-05 0.000239339 0.000239339 0.000272056 0.000272056 0.000199889 0.000199889 0.00026059 0.00026059 0.000276363 0.000276363 0.000310509 0.000310509 0.000284013 0.000284013 0.000261821 0.000261821 0.000223863 0.000223863 0.000251901 0.000251901 3.03069e-05 3.03069e-05 1.38659e-05 1.38659e-05 1.38659e-05 0.000276066 0.000276066 0.00023139 0.00023139 0.000123892 0.000123892 0.000285884 0.000285884 0.000293866 0.000293866 3.33804e-05 3.33804e-05 0.00027961 0.00027961 0.000256653 0.000256653 0.000232971 0.000232971 0.000286955 0.000286955 0.000261568 0.000261568 0.000311764 0.000311764 0.000151329 0.000151329 0.000224949 0.000224949 0.000299326 0.000299326 0.000211321 0.000211321 0.000293786 0.000293786 0.000305425 0.000305425 2.06331e-05 2.06331e-05 2.06331e-05 0.000225244 0.000225244 0.000313439 0.000313439 0.000276978 0.000276978 0.000284169 0.000284169 0.000266682 0.000266682 0.000203145 0.000203145 0.000309636 0.000309636 0.000250086 0.000250086 0.000268666 0.000268666 0.000213014 0.000213014 0.000166285 0.000166285 0.000233135 0.000233135 0.000223858 0.000223858 0.000292676 0.000292676 0.000205225 0.000205225 0.000247074 0.000247074 0.000283607 0.000283607 0.000234888 0.000234888 0.000246256 0.000246256 0.000291762 0.000291762 0.000222731 0.000222731 0.000226076 0.000226076 0.000268498 0.000268498 0.000269682 0.000269682 0.000307044 0.000307044 0.000261593 0.000261593 0.00025874 0.00025874 0.000270329 0.000270329 0.000292975 0.000292975 0.000251254 0.000251254 0.000284205 0.000284205 0.000202084 0.000202084 0.000292451 0.000292451 0.000292088 0.000292088 0.000263003 0.000263003 0.000277641 0.000277641 0.000243352 0.000243352 0.000240234 0.000240234 0.000236606 0.000236606 0.000304661 0.000304661 0.000276596 0.000276596 0.000231798 0.000231798 0.000212325 0.000212325 0.000299893 0.000299893 0.000293768 0.000293768 2.56381e-05 2.56381e-05 0.000289549 0.000289549 0.000164401 0.000164401 0.000268841 0.000268841 0.000254707 0.000254707 3.15707e-05 3.15707e-05 5.49673e-05 5.49673e-05 0.000314196 0.000314196 0.000205134 0.000205134 0.000302217 0.000302217 8.32261e-05 8.32261e-05 0.000284093 0.000284093 0.000246046 0.000246046 0.000108977 0.000108977 0.00025861 0.00025861 0.000310183 0.000310183 0.000313739 0.000313739 0.00027814 0.00027814 0.000248975 0.000248975 0.000234062 0.000234062 0.000226773 0.000226773 0.000213928 0.000213928 0.00024179 0.00024179 0.000236692 0.000236692 0.000309165 0.000309165 0.00024902 0.00024902 0.000253377 0.000253377 0.00030702 0.00030702 0.000275893 0.000275893 4.22884e-05 4.22884e-05 0.00030674 0.00030674 0.000299743 0.000299743 0.000242881 0.000242881 0.000292053 0.000292053 0.000296625 0.000296625 0.000300387 0.000300387 0.000263185 0.000263185 0.000243904 0.000243904 0.000247008 0.000247008 0.000308367 0.000308367 0.000290047 0.000290047 0.000282688 0.000282688 0.0002761 0.0002761 0.000240323 0.000240323 5.26076e-05 5.26076e-05 0.000201563 0.000201563 0.000264861 0.000264861 0.000283667 0.000283667 0.000246157 0.000246157 1.01291e-05 1.01291e-05 1.01291e-05 0.000270471 0.000270471 0.000233726 0.000233726 0.000298968 0.000298968 0.000298599 0.000298599 0.000126733 0.000126733 0.000295413 0.000295413 0.000210398 0.000210398 0.000218181 0.000218181 8.77215e-06 8.77215e-06 8.77215e-06 0.000279047 0.000279047 0.000312096 0.000312096 0.000286798 0.000286798 0.000243108 0.000243108 0.000263811 0.000263811 0.000266503 0.000266503 0.000200666 0.000200666 0.000292671 0.000292671 0.000252677 0.000252677 0.000249733 0.000249733 0.000264986 0.000264986 0.000310459 0.000310459 0.000312487 0.000312487 0.000216654 0.000216654 0.000274892 0.000274892 0.000313042 0.000313042 0.000224766 0.000224766 0.000311829 0.000311829 0.000206541 0.000206541 0.000241545 0.000241545 0.000315191 0.000315191 0.00028976 0.00028976 0.00028601 0.00028601 0.000224565 0.000224565 0.000278056 0.000278056 0.00027943 0.00027943 0.000309405 0.000309405 0.000278942 0.000278942 0.000217771 0.000217771 0.000246892 0.000246892 0.000278117 0.000278117 0.000314195 0.000314195 0.000181105 0.000181105 0.00025274 0.00025274 0.000240919 0.000240919 0.000246876 0.000246876 0.000269573 0.000269573 0.000252166 0.000252166 0.000194955 0.000194955 0.000291775 0.000291775 1.96598e-05 1.96598e-05 1.96598e-05 0.000270696 0.000270696 0.000293395 0.000293395 0.00026654 0.00026654 0.000282755 0.000282755 0.000300794 0.000300794 0.000206391 0.000206391 0.000242775 0.000242775 0.00030001 0.00030001 0.00027004 0.00027004 0.000265875 0.000265875 0.000308638 0.000308638 0.000309432 0.000309432 0.000214183 0.000214183 0.00029765 0.00029765 0.000304058 0.000304058 0.000232906 0.000232906 0.000202403 0.000202403 0.000189691 0.000189691 0.000210387 0.000210387 0.000283374 0.000283374 0.000286349 0.000286349 0.000251023 0.000251023 0.000270091 0.000270091 0.000275332 0.000275332 0.000250341 0.000250341 0.000202061 0.000202061 0.000293392 0.000293392 0.000312574 0.000312574 0.000210684 0.000210684 0.000302814 0.000302814 0.000281724 0.000281724 0.000292457 0.000292457 0.000292033 0.000292033 0.000298587 0.000298587 0.000272902 0.000272902 0.000265123 0.000265123 0.00028082 0.00028082 0.000287618 0.000287618 0.000228075 0.000228075 0.000245436 0.000245436 0.000269217 0.000269217 0.000307493 0.000307493 0.000279129 0.000279129 0.000292521 0.000292521 0.000187525 0.000187525 0.000279046 0.000279046 0.000214134 0.000214134 0.000275017 0.000275017 0.000312947 0.000312947 0.000312055 0.000312055 0.00029739 0.00029739 0.000280431 0.000280431 0.000267957 0.000267957 0.000265749 0.000265749 0.000313728 0.000313728 0.000305369 0.000305369 0.000242031 0.000242031 0.000239262 0.000239262 0.000205929 0.000205929 0.000258979 0.000258979 0.000310104 0.000310104 0.000263797 0.000263797 0.000203975 0.000203975 0.000315323 0.000315323 0.000300957 0.000300957 0.000311115 0.000311115 0.000281932 0.000281932 0.00025387 0.00025387 0.000283849 0.000283849 0.000284643 0.000284643 0.000233938 0.000233938 0.000266671 0.000266671 0.000278088 0.000278088 0.000300988 0.000300988 0.000210088 0.000210088 0.000309461 0.000309461 0.00030638 0.00030638 0.000313887 0.000313887 0.000241919 0.000241919 0.000266157 0.000266157 0.000296958 0.000296958 0.000184265 0.000184265 0.000252582 0.000252582 0.000262589 0.000262589 0.000200433 0.000200433 0.000294931 0.000294931 0.000202075 0.000202075 0.000188903 0.000188903 0.000214427 0.000214427 0.000286005 0.000286005 0.000258794 0.000258794 0.000210937 0.000210937 0.000205992 0.000205992 0.000234318 0.000234318 0.000227836 0.000227836 0.000254864 0.000254864 0.000159473 0.000159473 0.000296213 0.000296213 0.000312046 0.000312046 0.000267105 0.000267105 0.000286612 0.000286612 0.000281902 0.000281902 0.000291503 0.000291503 0.000302738 0.000302738 0.000260768 0.000260768 0.000280954 0.000280954 0.000304722 0.000304722 0.000217867 0.000217867 0.000259122 0.000259122 0.000188032 0.000188032 0.00017264 0.00017264 0.000156473 0.000156473 0.000247055 0.000247055 0.000278073 0.000278073 0.000234824 0.000234824 0.000209751 0.000209751 0.000212917 0.000212917 0.000280266 0.000280266 0.00024043 0.00024043 0.0002207 0.0002207 0.000304156 0.000304156 0.000280353 0.000280353 0.000290585 0.000290585 0.000225026 0.000225026 0.00030989 0.00030989 0.000276488 0.000276488 0.000252569 0.000252569 0.000282111 0.000282111 0.000293427 0.000293427 0.000281814 0.000281814 0.000178735 0.000178735 0.000216237 0.000216237 0.000313587 0.000313587 0.000194636 0.000194636 0.000229715 0.000229715 0.000296927 0.000296927 0.000282905 0.000282905 0.000280333 0.000280333 0.000132852 0.000132852 0.000159073 0.000159073 0.000309929 0.000309929 0.000154878 0.000154878 0.000311081 0.000311081 0.000276118 0.000276118 0.000237306 0.000237306 0.000202818 0.000202818 3.19394e-05 3.19394e-05 0.000138761 0.000138761 0.000151923 0.000151923 0.000315193 0.000315193 0.000285186 0.000285186 0.000292024 0.000292024 0.000286294 0.000286294 0.00018133 0.00018133 0.000108959 0.000108959 0.000308918 0.000308918 0.00025968 0.00025968 0.000279236 0.000279236 0.000216366 0.000216366 0.0002961 0.0002961 0.000267576 0.000267576 0.000302492 0.000302492 0.000224926 0.000224926 0.000154694 0.000154694 0.000233543 0.000233543 0.000305973 0.000305973 0.000180265 0.000180265 0.000296526 0.000296526 0.000228357 0.000228357 0.000290981 0.000290981 0.000246886 0.000246886 0.000221033 0.000221033 0.000123763 0.000123763 0.000274391 0.000274391 0.000313294 0.000313294 0.000309312 0.000309312 0.000280329 0.000280329 0.000233501 0.000233501 0.000278045 0.000278045 0.000294582 0.000294582 0.000164542 0.000164542 0.000293659 0.000293659 0.000268675 0.000268675 0.000178898 0.000178898 0.000300547 0.000300547 0.000255048 0.000255048 0.000295991 0.000295991 0.000168399 0.000168399 0.000219639 0.000219639 0.000112502 0.000112502 0.000247853 0.000247853 0.00019859 0.00019859 0.000260794 0.000260794 0.000312935 0.000312935 0.000280015 0.000280015 0.000273536 0.000273536 0.000219153 0.000219153 0.000236788 0.000236788 0.000243311 0.000243311 0.000306795 0.000306795 0.000230889 0.000230889 0.000305709 0.000305709 0.000262941 0.000262941 0.000235066 0.000235066 0.00020275 0.00020275 0.000274862 0.000274862 0.000198735 0.000198735 0.000248551 0.000248551 0.000166654 0.000166654 0.000278263 0.000278263 0.00020703 0.00020703 0.000301187 0.000301187 0.000232336 0.000232336 0.000179068 0.000179068 0.000214567 0.000214567 0.000153838 0.000153838 0.000297646 0.000297646 0.000308049 0.000308049 0.000278617 0.000278617 0.000279454 0.000279454 0.000232578 0.000232578 0.000297194 0.000297194 0.000202975 0.000202975 0.000211746 0.000211746 0.000227948 0.000227948 0.000303016 0.000303016 0.000195025 0.000195025 0.000302241 0.000302241 0.000305868 0.000305868 0.000310523 0.000310523 0.000283443 0.000283443 0.000306252 0.000306252 0.000149753 0.000149753 0.000161395 0.000161395 0.000312278 0.000312278 0.000309077 0.000309077 0.000289631 0.000289631 0.000286224 0.000286224 0.000234843 0.000234843 0.000279335 0.000279335 0.000285637 0.000285637 0.000169767 0.000169767 0.000314772 0.000314772 0.000156585 0.000156585 0.000280729 0.000280729 0.000272145 0.000272145 0.000288024 0.000288024 0.000241672 0.000241672 0.000213844 0.000213844 0.000305677 0.000305677 0.000170274 0.000170274 0.000295142 0.000295142 0.00022702 0.00022702 0.000229803 0.000229803 0.000308115 0.000308115 0.000171121 0.000171121 0.000247545 0.000247545 0.000224659 0.000224659 0.000136351 0.000136351 0.000252398 0.000252398 0.000269056 0.000269056 0.000242583 0.000242583 0.000316211 0.000316211 0.000219637 0.000219637 0.000201784 0.000201784 0.000149682 0.000149682 0.000269796 0.000269796 0.000159202 0.000159202 0.000230334 0.000230334 0.000270205 0.000270205 0.000274924 0.000274924 0.000191847 0.000191847 0.000303048 0.000303048 0.000109141 0.000109141 0.00029388 0.00029388 0.000292768 0.000292768 0.000301731 0.000301731 0.00015157 0.00015157 0.000301091 0.000301091 3.38334e-05 3.38334e-05 1.47416e-05 1.47416e-05 1.47416e-05 0.000122495 0.000122495 0.000223653 0.000223653 0.000312591 0.000312591 0.000277397 0.000277397 0.000166084 0.000166084 0.000257589 0.000257589 0.000228439 0.000228439 0.000286723 0.000286723 0.000234533 0.000234533 0.000286141 0.000286141 0.000259674 0.000259674 0.000290667 0.000290667 0.000174338 0.000174338 0.000139246 0.000139246 0.000278249 0.000278249 0.000305834 0.000305834 2.28693e-05 2.28693e-05 0.000287379 0.000287379 4.52017e-05 4.52017e-05 0.000211783 0.000211783 0.000150756 0.000150756 0.000218701 0.000218701 0.000305949 0.000305949 0.000233921 0.000233921 0.000241101 0.000241101 0.000290127 0.000290127 0.000258995 0.000258995 0.000264201 0.000264201 0.000249998 0.000249998 0.00027546 0.00027546 0.000126445 0.000126445 0.000128457 0.000128457 0.000294552 0.000294552 0.000286162 0.000286162 0.000279736 0.000279736 0.000303966 0.000303966 0.000310128 0.000310128 0.000232306 0.000232306 0.000163822 0.000163822 0.000237713 0.000237713 0.000226922 0.000226922 0.000151644 0.000151644 0.000245941 0.000245941 0.00029736 0.00029736 0.000238887 0.000238887 0.000209554 0.000209554 0.000267991 0.000267991 0.000220964 0.000220964 0.000311934 0.000311934 0.000214917 0.000214917 0.000236375 0.000236375 0.000149169 0.000149169 0.000258103 0.000258103 0.000168483 0.000168483 0.00029821 0.00029821 0.000285213 0.000285213 0.000221958 0.000221958 0.000295613 0.000295613 0.000288469 0.000288469 0.000306812 0.000306812 0.000247718 0.000247718 0.000305023 0.000305023 0.000248486 0.000248486 0.00016603 0.00016603 0.000210524 0.000210524 0.000307396 0.000307396 0.000273661 0.000273661 0.000230127 0.000230127 0.000307944 0.000307944 0.000313946 0.000313946 0.000126702 0.000126702 0.000245527 0.000245527 0.000218464 0.000218464 0.000196234 0.000196234 0.000209623 0.000209623 0.000236158 0.000236158 0.00027184 0.00027184 0.000300772 0.000300772 0.000304516 0.000304516 0.000259765 0.000259765 0.000295872 0.000295872 0.000278094 0.000278094 0.000214742 0.000214742 0.000290836 0.000290836 0.00031637 0.00031637 0.000228365 0.000228365 2.69136e-05 2.69136e-05 0.000204291 0.000204291 0.000145982 0.000145982 0.000292186 0.000292186 0.00014535 0.00014535 0.000235014 0.000235014 0.000213175 0.000213175 0.00017079 0.00017079 0.000255687 0.000255687 0.000301838 0.000301838 0.000147534 0.000147534 0.000286191 0.000286191 0.000316627 0.000316627 0.000228613 0.000228613 0.000287247 0.000287247 0.000278117 0.000278117 0.000153037 0.000153037 0.000300842 0.000300842 0.00030213 0.00030213 0.00021865 0.00021865 0.000239337 0.000239337 0.00023228 0.00023228 0.000239063 0.000239063 0.00029696 0.00029696 0.000291468 0.000291468 0.000304074 0.000304074 8.26878e-06 8.26878e-06 8.26878e-06 0.000294967 0.000294967 2.89671e-05 2.89671e-05 0.000240613 0.000240613 0.00023911 0.00023911 8.42416e-05 8.42416e-05 0.000209518 0.000209518 0.00024237 0.00024237 0.000230946 0.000230946 0.000296169 0.000296169 0.000218331 0.000218331 0.000290285 0.000290285 0.000279167 0.000279167 0.000140093 0.000140093 0.000296261 0.000296261 0.000299339 0.000299339 0.000252437 0.000252437 0.000170587 0.000170587 0.000204294 0.000204294 0.000136735 0.000136735 0.000290693 0.000290693 0.000288854 0.000288854 0.000302629 0.000302629 0.000251595 0.000251595 0.000282591 0.000282591 0.000168988 0.000168988 0.000270126 0.000270126 0.000138464 0.000138464 0.000237165 0.000237165 0.00013997 0.00013997 0.000151588 0.000151588 0.000309541 0.000309541 0.000210648 0.000210648 0.000150182 0.000150182 0.000285499 0.000285499 0.000224602 0.000224602 0.000261154 0.000261154 0.000300401 0.000300401 0.000150172 0.000150172 2.60853e-05 2.60853e-05 0.000238749 0.000238749 0.000273743 0.000273743 0.000219071 0.000219071 0.000294931 0.000294931 0.000276643 0.000276643 0.000238934 0.000238934 0.00023555 0.00023555 0.000270267 0.000270267 0.000289236 0.000289236 0.000284095 0.000284095 0.000286898 0.000286898 0.000227782 0.000227782 0.000304752 0.000304752 2.24458e-05 2.24458e-05 0.000303373 0.000303373 0.00030907 0.00030907 0.000310882 0.000310882 0.000315094 0.000315094 0.000296558 0.000296558 0.000170706 0.000170706 0.00030434 0.00030434 0.000145869 0.000145869 0.00028492 0.00028492 0.000210625 0.000210625 0.000123241 0.000123241 0.000243023 0.000243023 0.000234227 0.000234227 0.000303844 0.000303844 0.000144482 0.000144482 0.000242306 0.000242306 0.000302882 0.000302882 0.000242914 0.000242914 0.000262649 0.000262649 0.000315731 0.000315731 1.04644e-05 1.04644e-05 1.04644e-05 0.00012603 0.00012603 0.000275118 0.000275118 0.000141771 0.000141771 0.000241159 0.000241159 0.000205084 0.000205084 0.000289715 0.000289715 0.000290375 0.000290375 0.000302622 0.000302622 0.000230033 0.000230033 0.000139988 0.000139988 0.000309286 0.000309286 0.00014843 0.00014843 0.000301749 0.000301749 0.000264086 0.000264086 0.000296248 0.000296248 0.000238621 0.000238621 0.000226218 0.000226218 0.000297598 0.000297598 0.000235966 0.000235966 0.000211062 0.000211062 0.000247546 0.000247546 0.00022538 0.00022538 0.00029287 0.00029287 0.000218408 0.000218408 0.000238928 0.000238928 0.000270819 0.000270819 0.000288344 0.000288344 1.55426e-05 1.55426e-05 0.000303385 0.000303385 0.000141857 0.000141857 2.99141e-05 2.99141e-05 0.000241219 0.000241219 0.00022913 0.00022913 0.000247658 0.000247658 0.000139403 0.000139403 0.000299771 0.000299771 0.000166296 0.000166296 0.000235216 0.000235216 2.36149e-05 2.36149e-05 2.36149e-05 0.000218859 0.000218859 0.000289169 0.000289169 1.16956e-05 1.16956e-05 1.16956e-05 0.000151805 0.000151805 1.88952e-05 1.88952e-05 1.88952e-05 0.000144485 0.000144485 0.000296266 0.000296266 0.000182178 0.000182178 0.000305035 0.000305035 0.000219542 0.000219542 0.000293172 0.000293172 0.00013501 0.00013501 0.000267057 0.000267057 0.000302316 0.000302316 0.000232702 0.000232702 0.00023909 0.00023909 0.000136864 0.000136864 0.000291429 0.000291429 0.000201444 0.000201444 0.000277141 0.000277141 0.000245075 0.000245075 0.000305241 0.000305241 0.000261654 0.000261654 0.000231105 0.000231105 0.00023816 0.00023816 0.000286764 0.000286764 0.00022493 0.00022493 0.000298077 0.000298077 0.000231994 0.000231994 0.000167118 0.000167118 0.000201051 0.000201051 0.000242546 0.000242546 0.000283188 0.000283188 0.000231188 0.000231188 0.000247175 0.000247175 0.000245091 0.000245091 0.000217682 0.000217682 0.000216007 0.000216007 0.000267596 0.000267596 0.000304722 0.000304722 0.000225159 0.000225159 0.000218624 0.000218624 0.000282559 0.000282559 0.00020952 0.00020952 0.000290104 0.000290104 0.000292505 0.000292505 0.00014823 0.00014823 0.000237494 0.000237494 0.000134641 0.000134641 0.000170654 0.000170654 0.000295256 0.000295256 0.00021924 0.00021924 0.000224868 0.000224868 0.000301118 0.000301118 0.000298212 0.000298212 0.000313433 0.000313433 0.000206291 0.000206291 0.000227409 0.000227409 0.000135142 0.000135142 0.000299745 0.000299745 0.000238145 0.000238145 0.000314489 0.000314489 0.0003165 0.0003165 0.000239264 0.000239264 0.000237318 0.000237318 0.000214447 0.000214447 0.000231733 0.000231733 0.000306937 0.000306937 0.000304105 0.000304105 0.000308109 0.000308109 1.3472e-05 1.3472e-05 0.000278592 0.000278592 0.00029245 0.00029245 0.000250428 0.000250428 0.000199792 0.000199792 0.000267386 0.000267386 0.000278391 0.000278391 0.000274175 0.000274175 0.000174827 0.000174827 0.000160894 0.000160894 0.000315005 0.000315005 0.000287678 0.000287678 0.000122291 0.000122291 0.000125429 0.000125429 0.000210407 0.000210407 0.000297398 0.000297398 0.000209201 0.000209201 0.000233314 0.000233314 0.000147974 0.000147974 0.000300296 0.000300296 0.00029467 0.00029467 0.000284211 0.000284211 0.000298052 0.000298052 0.000240006 0.000240006 0.000301285 0.000301285 0.000236025 0.000236025 0.000234654 0.000234654 0.000254892 0.000254892 0.000226165 0.000226165 0.000303292 0.000303292 0.000143038 0.000143038 0.000228685 0.000228685 0.000300977 0.000300977 0.000291725 0.000291725 0.000244324 0.000244324 0.000303084 0.000303084 0.000277745 0.000277745 0.000216616 0.000216616 0.000235082 0.000235082 0.000149141 0.000149141 0.000217769 0.000217769 0.000265564 0.000265564 0.000145245 0.000145245 0.00027837 0.00027837 0.000303854 0.000303854 0.000233103 0.000233103 0.000299932 0.000299932 0.00013143 0.00013143 0.000300162 0.000300162 0.000131845 0.000131845 0.000227619 0.000227619 0.000217285 0.000217285 0.000234196 0.000234196 0.000254886 0.000254886 2.96146e-05 2.96146e-05 0.00029632 0.00029632 0.000214235 0.000214235 0.000231065 0.000231065 6.76575e-05 6.76575e-05 0.000238883 0.000238883 0.000214828 0.000214828 0.000109171 0.000109171 0.00014211 0.00014211 0.00019766 0.00019766 0.000295573 0.000295573 0.000230334 0.000230334 0.000300838 0.000300838 0.000247833 0.000247833 0.000200842 0.000200842 0.000292798 0.000292798 6.77383e-05 6.77383e-05 6.75573e-05 6.75573e-05 0.000229604 0.000229604 0.000237726 0.000237726 0.000300988 0.000300988 0.00029811 0.00029811 0.000255759 0.000255759 0.00013458 0.00013458 0.000215031 0.000215031 0.000224361 0.000224361 0.000171883 0.000171883 6.80019e-05 6.80019e-05 0.00023718 0.00023718 9.97242e-05 9.97242e-05 0.00017279 0.00017279 0.000241357 0.000241357 0.00029053 0.00029053 0.000234581 0.000234581 0.000140087 0.000140087 0.000287677 0.000287677 1.0328e-05 1.0328e-05 1.0328e-05 1.11143e-05 1.11143e-05 1.11143e-05 0.000294453 0.000294453 0.000144805 0.000144805 0.000228444 0.000228444 0.000311693 0.000311693 0.000217477 0.000217477 0.000242051 0.000242051 0.000253634 0.000253634 0.00014121 0.00014121 0.00029852 0.00029852 0.0003127 0.0003127 0.000315942 0.000315942 0.000221591 0.000221591 0.000245529 0.000245529 0.000214101 0.000214101 6.79243e-05 6.79243e-05 0.00028595 0.00028595 0.000295802 0.000295802 0.000283556 0.000283556 0.000300146 0.000300146 0.000211368 0.000211368 0.000215337 0.000215337 0.000235011 0.000235011 0.000313788 0.000313788 0.000301746 0.000301746 0.000124227 0.000124227 0.00020378 0.00020378 0.000297588 0.000297588 1.39848e-05 1.39848e-05 1.39848e-05 0.000122392 0.000122392 0.000142841 0.000142841 0.00022395 0.00022395 6.74426e-05 6.74426e-05 0.000229025 0.000229025 0.000205483 0.000205483 6.7437e-05 6.7437e-05 2.33211e-05 2.33211e-05 0.000244038 0.000244038 0.000301381 0.000301381 0.000299336 0.000299336 0.000292154 0.000292154 0.00030489 0.00030489 0.000306893 0.000306893 0.000144807 0.000144807 0.0002741 0.0002741 0.000188853 0.000188853 0.000230976 0.000230976 0.000240568 0.000240568 1.51432e-05 1.51432e-05 1.51432e-05 6.76776e-05 6.76776e-05 0.000229236 0.000229236 2.82776e-05 2.82776e-05 0.000126409 0.000126409 0.000233371 0.000233371 0.000299521 0.000299521 0.000221853 0.000221853 0.000306152 0.000306152 0.000183706 0.000183706 0.000173252 0.000173252 0.000129148 0.000129148 0.000291288 0.000291288 0.000291496 0.000291496 0.000230955 0.000230955 0.000229176 0.000229176 0.000282665 0.000282665 0.000288803 0.000288803 0.000284825 0.000284825 0.000144585 0.000144585 0.000301888 0.000301888 0.000178185 0.000178185 0.00024785 0.00024785 0.000202786 0.000202786 2.97838e-05 2.97838e-05 0.000221567 0.000221567 0.000255997 0.000255997 0.000233201 0.000233201 6.78687e-05 6.78687e-05 0.000214472 0.000214472 0.000241502 0.000241502 0.000230048 0.000230048 6.98518e-05 6.98518e-05 0.000297185 0.000297185 0.000123883 0.000123883 0.00023912 0.00023912 0.00021251 0.00021251 0.000135827 0.000135827 0.00027694 0.00027694 0.000300675 0.000300675 0.000241106 0.000241106 0.000203062 0.000203062 0.000258547 0.000258547 0.000193893 0.000193893 0.0002294 0.0002294 0.000134257 0.000134257 0.00029529 0.00029529 0.000294091 0.000294091 0.000202342 0.000202342 0.000304755 0.000304755 0.000140066 0.000140066 0.000300692 0.000300692 0.000211926 0.000211926 0.000170861 0.000170861 0.000299512 0.000299512 0.00021422 0.00021422 0.000314797 0.000314797 1.08844e-05 1.08844e-05 1.08844e-05 1.30383e-05 1.30383e-05 1.30383e-05 0.000256012 0.000256012 0.000221177 0.000221177 0.000202901 0.000202901 0.000178744 0.000178744 0.000300559 0.000300559 0.000142644 0.000142644 0.000134339 0.000134339 9.93892e-05 9.93892e-05 6.81178e-05 6.81178e-05 0.00031536 0.00031536 0.000221293 0.000221293 0.000255619 0.000255619 0.00031129 0.00031129 0.000296551 0.000296551 0.000293396 0.000293396 0.000298956 0.000298956 0.000185297 0.000185297 0.000267119 0.000267119 0.000197735 0.000197735 0.000304739 0.000304739 0.000290028 0.000290028 0.000244445 0.000244445 0.000121241 0.000121241 0.000119497 0.000119497 0.000303617 0.000303617 0.000214843 0.000214843 0.000230918 0.000230918 0.000210139 0.000210139 1.8978e-05 1.8978e-05 1.8978e-05 0.000237842 0.000237842 0.000211794 0.000211794 0.000291145 0.000291145 0.00018103 0.00018103 0.000284585 0.000284585 6.74375e-05 6.74375e-05 0.000300891 0.000300891 0.000166161 0.000166161 3.6408e-05 3.6408e-05 0.000231104 0.000231104 0.000288562 0.000288562 0.000196722 0.000196722 1.52456e-05 1.52456e-05 1.52456e-05 0.000157105 0.000157105 0.000215058 0.000215058 0.00013738 0.00013738 0.000171167 0.000171167 0.000200507 0.000200507 0.000196174 0.000196174 0.000310418 0.000310418 0.000238139 0.000238139 0.000301079 0.000301079 0.000129061 0.000129061 0.000137222 0.000137222 0.000298057 0.000298057 0.00023452 0.00023452 0.000302992 0.000302992 0.000234777 0.000234777 0.000186719 0.000186719 0.000135312 0.000135312 0.000115186 0.000115186 0.000277255 0.000277255 0.000295304 0.000295304 2.97794e-05 2.97794e-05 0.000288194 0.000288194 6.89365e-05 6.89365e-05 0.000256691 0.000256691 0.000300419 0.000300419 0.000251687 0.000251687 0.000231943 0.000231943 0.000291244 0.000291244 0.000210741 0.000210741 0.000285924 0.000285924 0.000126723 0.000126723 0.000249408 0.000249408 0.000134551 0.000134551 0.00029703 0.00029703 0.000298599 0.000298599 0.000248281 0.000248281 0.00021623 0.00021623 3.50923e-05 3.50923e-05 3.50923e-05 0.000256559 0.000256559 0.000215898 0.000215898 0.000122496 0.000122496 0.000303564 0.000303564 0.000288178 0.000288178 0.000294664 0.000294664 0.000280268 0.000280268 3.51626e-05 3.51626e-05 3.51626e-05 0.000191359 0.000191359 0.000300181 0.000300181 0.000289319 0.000289319 3.52822e-05 3.52822e-05 3.52822e-05 0.000125415 0.000125415 0.000213022 0.000213022 0.000314139 0.000314139 0.000282474 0.000282474 0.000126949 0.000126949 0.000292601 0.000292601 0.000252829 0.000252829 2.0626e-05 2.0626e-05 0.000296734 0.000296734 0.000285965 0.000285965 0.000289181 0.000289181 0.000208056 0.000208056 0.000249289 0.000249289 3.50248e-05 3.50248e-05 3.50248e-05 0.000294179 0.000294179 0.000313474 0.000313474 0.000139823 0.000139823 0.00026667 0.00026667 0.000300858 0.000300858 0.000163105 0.000163105 0.000245657 0.000245657 0.000251132 0.000251132 0.000140699 0.000140699 0.000312499 0.000312499 0.000141566 0.000141566 0.000301198 0.000301198 3.49246e-05 3.49246e-05 3.49246e-05 3.50513e-05 3.50513e-05 3.50513e-05 0.000135485 0.000135485 0.000187186 0.000187186 0.000291466 0.000291466 1.51762e-05 1.51762e-05 1.51762e-05 0.000233715 0.000233715 0.000287072 0.000287072 4.03659e-05 4.03659e-05 0.000268413 0.000268413 0.00021693 0.00021693 0.000294792 0.000294792 0.000307438 0.000307438 2.11808e-05 2.11808e-05 3.51325e-05 3.51325e-05 3.51325e-05 0.000288788 0.000288788 0.000297846 0.000297846 7.28235e-05 7.28235e-05 9.65827e-06 9.65827e-06 9.65827e-06 1.03086e-05 1.03086e-05 1.03086e-05 0.000124055 0.000124055 0.000134834 0.000134834 0.000288492 0.000288492 0.000120348 0.000120348 0.000238091 0.000238091 0.000304233 0.000304233 0.000246372 0.000246372 0.000280014 0.000280014 0.000303073 0.000303073 0.000233048 0.000233048 1.41973e-05 1.41973e-05 1.41973e-05 0.000247941 0.000247941 3.49127e-05 3.49127e-05 3.49127e-05 3.51554e-05 3.51554e-05 3.51554e-05 0.000302737 0.000302737 0.000297297 0.000297297 0.000125257 0.000125257 3.52434e-05 3.52434e-05 3.52434e-05 0.000254885 0.000254885 0.000125636 0.000125636 0.000233357 0.000233357 4.14597e-05 4.14597e-05 0.000128937 0.000128937 4.22152e-05 4.22152e-05 0.000258515 0.000258515 2.97896e-05 2.97896e-05 0.00014272 0.00014272 0.000150344 0.000150344 4.24519e-05 4.24519e-05 0.000306885 0.000306885 3.05346e-05 3.05346e-05 0.000281978 0.000281978 0.000224292 0.000224292 6.47126e-05 6.47126e-05 4.24532e-05 4.24532e-05 0.00028645 0.00028645 4.63778e-05 4.63778e-05 0.00030285 0.00030285 2.00876e-05 2.00876e-05 4.39795e-05 4.39795e-05 0.000214421 0.000214421 0.00011756 0.00011756 0.000282806 0.000282806 0.00029167 0.00029167 1.86256e-05 1.86256e-05 1.86256e-05 3.53603e-05 3.53603e-05 3.53603e-05 4.39685e-05 4.39685e-05 0.000251598 0.000251598 0.000136479 0.000136479 0.000261442 0.000261442 0.000252073 0.000252073 0.000293971 0.000293971 0.000222141 0.000222141 0.000293944 0.000293944 0.000251143 0.000251143 0.000201938 0.000201938 0.000251811 0.000251811 4.22028e-05 4.22028e-05 0.000296359 0.000296359 0.000193339 0.000193339 0.00027004 0.00027004 0.000312913 0.000312913 0.000250803 0.000250803 0.000138684 0.000138684 0.000216879 0.000216879 1.50824e-05 1.50824e-05 1.50824e-05 0.000121085 0.000121085 4.17875e-05 4.17875e-05 0.000307062 0.000307062 0.000310919 0.000310919 0.000240886 0.000240886 0.000218523 0.000218523 0.000272879 0.000272879 0.000123545 0.000123545 0.000280619 0.000280619 0.000251239 0.000251239 3.55734e-05 3.55734e-05 3.55734e-05 0.000312618 0.000312618 0.000299618 0.000299618 0.000132104 0.000132104 7.43286e-05 7.43286e-05 0.000298264 0.000298264 0.000278127 0.000278127 0.000295652 0.000295652 0.000298627 0.000298627 0.000219136 0.000219136 4.16342e-05 4.16342e-05 0.000251344 0.000251344 0.000234243 0.000234243 4.08481e-05 4.08481e-05 0.000262237 0.000262237 0.000306511 0.000306511 7.17456e-05 7.17456e-05 0.000289243 0.000289243 0.000312125 0.000312125 0.00030517 0.00030517 4.18596e-05 4.18596e-05 0.000295995 0.000295995 0.000251293 0.000251293 0.000233478 0.000233478 3.81395e-05 3.81395e-05 0.00025288 0.00025288 0.000216732 0.000216732 0.000294506 0.000294506 0.000218739 0.000218739 3.40653e-05 3.40653e-05 3.40653e-05 0.000250905 0.000250905 0.000297877 0.000297877 0.000254992 0.000254992 0.000302241 0.000302241 0.000251874 0.000251874 0.00029428 0.00029428 0.000131244 0.000131244 0.000305751 0.000305751 0.000117003 0.000117003 0.000301852 0.000301852 0.000129298 0.000129298 0.000266104 0.000266104 1.31375e-05 1.31375e-05 1.31375e-05 7.67835e-05 7.67835e-05 7.61976e-05 7.61976e-05 3.63145e-05 3.63145e-05 3.63145e-05 0.000219291 0.000219291 3.02076e-05 3.02076e-05 0.000253934 0.000253934 0.000272948 0.000272948 0.000115666 0.000115666 3.13779e-05 3.13779e-05 1.48424e-05 1.48424e-05 1.48424e-05 0.000133529 0.000133529 0.000236931 0.000236931 0.000309035 0.000309035 0.000310326 0.000310326 0.000135407 0.000135407 0.000311543 0.000311543 0.000305307 0.000305307 3.32428e-05 3.32428e-05 0.000246809 0.000246809 0.000126127 0.000126127 0.000247252 0.000247252 0.000250666 0.000250666 0.000275894 0.000275894 0.000253124 0.000253124 0.000221919 0.000221919 0.000130707 0.000130707 0.000296152 0.000296152 4.32256e-05 4.32256e-05 0.000223657 0.000223657 0.000250555 0.000250555 0.00030533 0.00030533 0.000248995 0.000248995 0.000118048 0.000118048 2.16493e-05 2.16493e-05 2.16493e-05 0.000297199 0.000297199 5.22481e-05 5.22481e-05 2.15441e-05 2.15441e-05 2.15441e-05 0.000197277 0.000197277 2.18253e-05 2.18253e-05 2.18253e-05 0.000245524 0.000245524 0.000305991 0.000305991 2.16921e-05 2.16921e-05 2.16921e-05 0.000248286 0.000248286 7.25604e-05 7.25604e-05 2.1689e-05 2.1689e-05 2.1689e-05 0.000250228 0.000250228 0.000304454 0.000304454 3.19861e-05 3.19861e-05 2.35197e-05 2.35197e-05 2.35197e-05 2.28056e-05 2.28056e-05 2.28056e-05 0.000239658 0.000239658 0.000200848 0.000200848 0.000247958 0.000247958 0.000300734 0.000300734 0.000219373 0.000219373 0.000253856 0.000253856 0.000296005 0.000296005 0.000186563 0.000186563 9.6843e-06 9.6843e-06 9.6843e-06 9.33115e-06 9.33115e-06 9.33115e-06 2.15095e-05 2.15095e-05 2.15095e-05 0.000227968 0.000227968 0.000259798 0.000259798 0.000230038 0.000230038 7.78946e-05 7.78946e-05 0.000252548 0.000252548 2.76728e-05 2.76728e-05 7.65373e-05 7.65373e-05 0.00024879 0.00024879 0.000240869 0.000240869 7.71498e-05 7.71498e-05 3.2809e-05 3.2809e-05 0.000136153 0.000136153 0.000121664 0.000121664 2.11043e-05 2.11043e-05 2.11043e-05 7.8165e-05 7.8165e-05 0.000193663 0.000193663 1.50584e-05 1.50584e-05 1.50584e-05 0.000299749 0.000299749 0.000250285 0.000250285 0.000241849 0.000241849 0.000298777 0.000298777 0.000248757 0.000248757 2.19161e-05 2.19161e-05 2.19161e-05 2.1645e-05 2.1645e-05 2.1645e-05 0.000257312 0.000257312 0.000208243 0.000208243 2.08756e-05 2.08756e-05 2.08756e-05 0.000304477 0.000304477 4.28966e-05 4.28966e-05 0.000250316 0.000250316 0.000217755 0.000217755 1.31405e-05 1.31405e-05 1.31405e-05 3.18627e-05 3.18627e-05 3.18627e-05 3.33595e-05 3.33595e-05 3.33595e-05 6.97268e-05 6.97268e-05 0.000136598 0.000136598 0.000297053 0.000297053 0.000303646 0.000303646 0.000241993 0.000241993 0.000237379 0.000237379 0.000306693 0.000306693 0.000299717 0.000299717 0.000233444 0.000233444 0.000304061 0.000304061 0.000247568 0.000247568 1.83966e-05 1.83966e-05 1.83966e-05 0.000305886 0.000305886 0.000300923 0.000300923 0.000212033 0.000212033 3.35873e-05 3.35873e-05 0.000305986 0.000305986 2.15124e-05 2.15124e-05 2.15124e-05 0.000303304 0.000303304 0.000157409 0.000157409 2.92355e-05 2.92355e-05 2.92355e-05 2.91643e-05 2.91643e-05 0.000298536 0.000298536 0.000245741 0.000245741 0.000237191 0.000237191 0.000234045 0.000234045 3.44879e-05 3.44879e-05 3.44879e-05 0.000228495 0.000228495 1.32483e-05 1.32483e-05 1.32483e-05 3.31229e-05 3.31229e-05 7.28128e-05 7.28128e-05 0.000236942 0.000236942 0.000305066 0.000305066 0.000307038 0.000307038 0.000237721 0.000237721 0.000312079 0.000312079 0.00023495 0.00023495 7.83308e-05 7.83308e-05 0.000230785 0.000230785 3.70416e-05 3.70416e-05 3.70416e-05 3.72772e-05 3.72772e-05 3.72772e-05 0.000296558 0.000296558 1.56771e-05 1.56771e-05 1.56771e-05 0.000235793 0.000235793 7.45526e-05 7.45526e-05 0.000244354 0.000244354 0.000311388 0.000311388 0.000219018 0.000219018 0.000306336 0.000306336 0.000181015 0.000181015 0.000301435 0.000301435 0.000104429 0.000104429 0.00030537 0.00030537 2.16328e-05 2.16328e-05 2.16328e-05 1.59413e-05 1.59413e-05 1.59413e-05 0.000241649 0.000241649 3.74531e-05 3.74531e-05 3.74531e-05 1.57119e-05 1.57119e-05 1.57119e-05 0.000306507 0.000306507 0.000232963 0.000232963 0.000229528 0.000229528 3.74834e-05 3.74834e-05 3.74834e-05 0.000240558 0.000240558 3.4453e-05 3.4453e-05 3.4453e-05 6.67529e-05 6.67529e-05 0.000304512 0.000304512 0.000310655 0.000310655 3.78681e-05 3.78681e-05 3.78681e-05 7.49606e-05 7.49606e-05 0.000233119 0.000233119 3.73159e-05 3.73159e-05 3.73159e-05 0.000309005 0.000309005 0.000230481 0.000230481 1.80844e-05 1.80844e-05 1.80844e-05 0.00023062 0.00023062 0.000300487 0.000300487 0.000230303 0.000230303 7.45307e-05 7.45307e-05 0.000215685 0.000215685 0.000306695 0.000306695 1.58185e-05 1.58185e-05 1.58185e-05 1.51408e-05 1.51408e-05 1.51408e-05 0.000305973 0.000305973 0.000103911 0.000103911 0.000242274 0.000242274 0.000306618 0.000306618 0.000297393 0.000297393 0.000311643 0.000311643 0.00023059 0.00023059 0.000189136 0.000189136 3.77862e-05 3.77862e-05 3.77862e-05 0.000298172 0.000298172 0.000307349 0.000307349 0.000234285 0.000234285 0.000310559 0.000310559 0.00023519 0.00023519 0.00029882 0.00029882 2.54337e-05 2.54337e-05 1.23361e-05 1.23361e-05 1.23361e-05 0.000224043 0.000224043 0.0003082 0.0003082 0.000297654 0.000297654 0.000126589 0.000126589 0.00021579 0.00021579 4.90788e-05 4.90788e-05 3.40717e-05 3.40717e-05 3.40717e-05 0.000307292 0.000307292 0.00030334 0.00030334 4.96035e-05 4.96035e-05 0.000306615 0.000306615 4.3359e-05 4.3359e-05 2.16791e-05 2.16791e-05 2.16791e-05 0.000223176 0.000223176 0.000224428 0.000224428 0.000229239 0.000229239 0.000221076 0.000221076 3.81255e-05 3.81255e-05 3.81255e-05 3.81428e-05 3.81428e-05 3.81428e-05 0.000217741 0.000217741 7.57048e-05 7.57048e-05 4.86716e-05 4.86716e-05 4.93629e-05 4.93629e-05 0.000219597 0.000219597 0.000129886 0.000129886 0.000225629 0.000225629 0.000306042 0.000306042 0.00022321 0.00022321 2.4104e-05 2.4104e-05 1.10588e-05 1.10588e-05 1.10588e-05 0.000307023 0.000307023 0.000218314 0.000218314 0.000302887 0.000302887 7.78708e-05 7.78708e-05 3.79118e-05 3.79118e-05 3.79118e-05 0.00030667 0.00030667 0.000308361 0.000308361 0.000177346 0.000177346 0.000304859 0.000304859 0.000215347 0.000215347 0.000285178 0.000285178 0.000305353 0.000305353 4.84887e-05 4.84887e-05 3.82623e-05 3.82623e-05 3.82623e-05 0.000222806 0.000222806 7.57672e-05 7.57672e-05 0.000175054 0.000175054 2.54663e-05 2.54663e-05 2.54663e-05 0.00029257 0.00029257 2.53852e-05 2.53852e-05 2.53852e-05 6.30449e-05 6.30449e-05 3.22866e-05 3.22866e-05 3.22866e-05 0.000302824 0.000302824 3.80228e-05 3.80228e-05 3.80228e-05 0.000305475 0.000305475 7.74697e-05 7.74697e-05 0.000221088 0.000221088 0.000300683 0.000300683 2.51761e-05 2.51761e-05 2.51761e-05 4.83679e-05 4.83679e-05 0.000219253 0.000219253 4.17493e-05 4.17493e-05 4.60421e-05 4.60421e-05 2.27733e-05 2.27733e-05 2.27733e-05 0.000301088 0.000301088 1.51221e-05 1.51221e-05 1.51221e-05 0.000301482 0.000301482 2.45963e-05 2.45963e-05 2.45963e-05 0.000214215 0.000214215 0.000302795 0.000302795 0.000275406 0.000275406 3.8122e-05 3.8122e-05 3.8122e-05 3.90077e-05 3.90077e-05 3.90077e-05 7.77432e-05 7.77432e-05 7.79054e-05 7.79054e-05 4.88225e-05 4.88225e-05 7.59869e-05 7.59869e-05 2.49623e-05 2.49623e-05 2.49623e-05 2.41895e-05 2.41895e-05 2.41895e-05 0.000276926 0.000276926 0.000299382 0.000299382 0.00029932 0.00029932 0.000218793 0.000218793 3.73651e-05 3.73651e-05 3.73651e-05 2.35536e-05 2.35536e-05 2.35536e-05 4.99962e-05 4.99962e-05 0.000186889 0.000186889 0.000287633 0.000287633 0.000287625 0.000287625 0.0002019 0.0002019 0.000294708 0.000294708 0.000298145 0.000298145 0.00021972 0.00021972 3.45533e-05 3.45533e-05 3.45533e-05 7.32384e-05 7.32384e-05 0.000218617 0.000218617 3.73916e-05 3.73916e-05 3.73916e-05 7.14295e-05 7.14295e-05 3.26848e-05 3.26848e-05 3.26848e-05 5.99493e-05 5.99493e-05 0.000252684 0.000252684 0.000280594 0.000280594 9.56036e-06 9.56036e-06 9.56036e-06 1.91106e-05 1.91106e-05 2.05941e-05 2.05941e-05 2.05941e-05 2.05941e-05 7.78155e-06 7.78155e-06 7.78155e-06 7.78155e-06 6.40608e-05 6.40608e-05 1.10633e-05 1.10633e-05 1.10633e-05 2.07756e-05 2.07756e-05 2.07756e-05 4.25344e-05 4.25344e-05 2.65182e-05 2.65182e-05 2.65182e-05 4.54175e-05 4.54175e-05 2.23297e-05 2.23297e-05 2.23297e-05 2.09071e-05 2.09071e-05 2.09071e-05 4.41384e-05 4.41384e-05 2.11291e-05 2.11291e-05 2.11291e-05 2.16631e-05 2.16631e-05 2.16631e-05 4.33339e-05 4.33339e-05 7.84755e-05 7.84755e-05 3.82844e-05 3.82844e-05 3.82844e-05 3.89482e-05 3.89482e-05 3.89482e-05 3.71415e-05 3.71415e-05 3.71415e-05 7.51209e-05 7.51209e-05 3.90505e-05 3.90505e-05 3.90505e-05 7.80275e-05 7.80275e-05 2.91274e-05 2.91274e-05 2.91274e-05 2.04996e-05 2.04996e-05 2.04996e-05 1.9977e-05 1.9977e-05 1.9977e-05 4.29833e-05 4.29833e-05 2.08974e-05 2.08974e-05 2.08974e-05 2.13662e-05 2.13662e-05 2.13662e-05 4.50615e-05 4.50615e-05 3.90779e-05 3.90779e-05 3.90779e-05 0.000247242 0.000247242 0.000284851 0.000284851 0.000282224 0.000282224 0.000297327 0.000297327 0.000298598 0.000298598 3.10781e-05 3.10781e-05 1.43342e-05 1.43342e-05 1.43342e-05 0.000154655 0.000154655 0.000132309 0.000132309 0.000150185 0.000150185 1.30962e-05 1.30962e-05 1.30962e-05 0.00012493 0.00012493 0.000199569 0.000199569 0.000112517 0.000112517 0.00012655 0.00012655 3.06316e-05 3.06316e-05 2.14785e-05 2.14785e-05 0.000285368 0.000285368 0.000144945 0.000144945 1.74301e-05 1.74301e-05 1.74301e-05 1.33371e-05 1.33371e-05 1.33371e-05 1.40275e-05 1.40275e-05 1.40275e-05 0.000206354 0.000206354 8.36511e-05 8.36511e-05 0.000162572 0.000162572 0.000204201 0.000204201 1.31289e-05 1.31289e-05 1.31289e-05 0.000150113 0.000150113 0.000218023 0.000218023 0.000151029 0.000151029 9.29469e-06 9.29469e-06 9.29469e-06 9.15885e-06 9.15885e-06 9.15885e-06 1.07929e-05 1.07929e-05 1.07929e-05 8.94732e-06 8.94732e-06 8.94732e-06 1.33969e-05 1.33969e-05 1.33969e-05 8.89987e-06 8.89987e-06 8.89987e-06 9.62668e-06 9.62668e-06 9.62668e-06 9.19002e-06 9.19002e-06 9.19002e-06 0.000239571 0.000239571 3.17225e-05 3.17225e-05 0.000131759 0.000131759 8.69565e-06 8.69565e-06 8.69565e-06 6.45449e-06 6.45449e-06 6.45449e-06 7.04197e-06 7.04197e-06 7.04197e-06 2.75694e-05 2.75694e-05 0.000221398 0.000221398 0.000218028 0.000218028 9.97998e-06 9.97998e-06 9.97998e-06 7.90622e-06 7.90622e-06 7.90622e-06 7.68738e-06 7.68738e-06 7.68738e-06 0.000131291 0.000131291 0.000139568 0.000139568 2.02964e-05 2.02964e-05 0.000130795 0.000130795 0.000289905 0.000289905 0.000113346 0.000113346 8.10244e-05 8.10244e-05 2.12929e-05 2.12929e-05 9.63376e-06 9.63376e-06 9.63376e-06 2.83703e-05 2.83703e-05 1.82483e-05 1.82483e-05 2.98512e-05 2.98512e-05 1.90725e-05 1.90725e-05 1.90561e-05 1.90561e-05 1.85545e-05 1.85545e-05 6.21886e-06 6.21886e-06 6.21886e-06 6.55723e-06 6.55723e-06 6.55723e-06 0.000209888 0.000209888 0.000231561 0.000231561 0.000102491 0.000102491 0.0002875 0.0002875 1.18056e-05 1.18056e-05 1.96432e-05 1.96432e-05 1.92249e-05 1.92249e-05 9.67671e-05 9.67671e-05 0.000168595 0.000168595 2.10124e-05 2.10124e-05 0.000211993 0.000211993 9.84496e-05 9.84496e-05 0.000156719 0.000156719 0.000162377 0.000162377 8.65482e-06 8.65482e-06 8.65482e-06 0.000165714 0.000165714 0.00010428 0.00010428 0.000113803 0.000113803 2.04147e-05 2.04147e-05 0.000311635 0.000311635 0.000129834 0.000129834 0.000211236 0.000211236 1.08559e-05 1.08559e-05 1.08559e-05 9.73602e-05 9.73602e-05 0.000303326 0.000303326 9.55819e-05 9.55819e-05 1.70455e-05 1.70455e-05 8.49315e-06 8.49315e-06 8.49315e-06 0.000169433 0.000169433 0.000206722 0.000206722 0.000300825 0.000300825 8.37892e-05 8.37892e-05 0.00010994 0.00010994 7.52776e-06 7.52776e-06 7.52776e-06 0.000208195 0.000208195 0.000309135 0.000309135 0.000114784 0.000114784 0.0003109 0.0003109 0.000212642 0.000212642 1.99812e-05 1.99812e-05 0.00020227 0.00020227 0.000304023 0.000304023 0.000127061 0.000127061 0.000214303 0.000214303 0.000128105 0.000128105 0.000118429 0.000118429 0.000112771 0.000112771 5.77316e-06 5.77316e-06 5.77316e-06 0.000220028 0.000220028 1.67599e-05 1.67599e-05 7.83979e-06 7.83979e-06 7.83979e-06 0.000301617 0.000301617 ) ; } } // ************************************************************************* //
[ "luis.cascelli@gmail.com" ]
luis.cascelli@gmail.com
81590f2b6b334eb7e5228c5bc0bb137803f90efc
5c2720f0eea3c45e8619385f087d91fff23f2675
/1080.cpp
6e3eb5190868e97577d50222ccff6a0ea7bb1d75
[]
no_license
Whituru/BAEKJOON_OnlineJudge
2f3eaebe489e2009d6b655b78266e42144270ae9
8c67e1945b83680cf3f861de2fef6b9f7fe7ea1b
refs/heads/main
2023-06-11T19:54:52.164278
2021-07-02T11:49:23
2021-07-02T11:49:23
372,219,023
0
0
null
null
null
null
UTF-8
C++
false
false
992
cpp
#include <iostream> #include <vector> #include <algorithm> #include <string> #include <map> #include <array> using namespace std; int arr[50][50]; int cnt = 0; void flip(int x, int y){ if(arr[x][y] == 1){ //다르니까 뒤집자. cnt++; for(int i=x; i<x+3; i++){ for(int j=y; j<y+3; j++){ if(arr[i][j] == 1){ arr[i][j] = 0; } else { arr[i][j] = 1; } } } } } int main() { int N, M; cin >> N >> M; string A[50]; string B[50]; for(int i=0; i<N; i++){ cin >> A[i]; } for(int i=0; i<N; i++){ cin >> B[i]; } for(int i=0; i<N; i++){ for(int j=0; j<M; j++){ if(A[i][j] == B[i][j]){ arr[i][j] = 0; } else { arr[i][j] = 1; } } } for(int i=0; i<N-2; i++){ for(int j=0; j<M-2; j++){ flip(i,j); } } int tmp= 0; for(int i=0; i<N; i++){ for(int j=0; j<M; j++){ if(arr[i][j] == 1) {tmp = 1;} } } if(tmp == 1){ cout << -1 << endl; } else { cout << cnt << endl; } return 0; }
[ "hentsru5619@gmail.com" ]
hentsru5619@gmail.com
87c7c4960103b97688394d1e6460ceabc7d6e1cb
2f78e134c5b55c816fa8ee939f54bde4918696a5
/code/ai/ainavgraphmanager.h
c23dbf1db80d5812405643e013a044e711d823db
[]
no_license
narayanr7/HeavenlySword
b53afa6a7a6c344e9a139279fbbd74bfbe70350c
a255b26020933e2336f024558fefcdddb48038b2
refs/heads/master
2022-08-23T01:32:46.029376
2020-05-26T04:45:56
2020-05-26T04:45:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,736
h
/*************************************************************************************************** * * CLASS CAINavGraphManager * * DESCRIPTION * * NOTES * ***************************************************************************************************/ #ifndef _AINAVGRAPHMANAGER_H #define _AINAVGRAPHMANAGER_H class AIObjectAvoidance; class CAINavNodeAABB; class CAINavNodeRegion; class CAINavPath; class AIGroupNavBrain; class AISafeZone; class AITestManager; class CEntity; class AIIntermediateNavData; class AINavData; class CKeywords; #include "ai/aidefines.h" #include "ai/ainavdata.h" #include "ai/aidebugwall.h" enum AINAVNODE_AABB_CREATE_STATE { AINAVNODE_AABB_CREATE_STATE_START = 0, AINAVNODE_AABB_CREATE_STATE_END, }; enum INGRAPH_RETURN { INGRAPH_SAME_TRI, INGRAPH_DIFFERNT_TRI, INGRAPH_START_OUT, INGRAPH_END_OUT, INGRAPH_BOTH_OUT, INGRAPH_ERROR, }; /*************************************************************************************************** * * STRUCT AINavHint * * DESCRIPTION * ***************************************************************************************************/ struct AINavHint { AINavHint() : m_Region(-1), m_Tri(-1) {} short m_Region; short m_Tri; }; /*************************************************************************************************** * * struct AINavCache * * DESCRIPTION * ***************************************************************************************************/ struct AINavCache { AINavHint m_aobHints[5]; }; /*************************************************************************************************** * * CLASS * * DESCRIPTION * ***************************************************************************************************/ class CAINavGraphManager : public Singleton<CAINavGraphManager> { public: CAINavGraphManager( void ); ~CAINavGraphManager( void ); void LevelUnload(); void Update( float fTimeChange ); void DebugRender(); bool IsDebugRenderOn() const { return m_bRender; }; bool m_bRender; bool HasNavData() const; CPoint GetRandomPosInGraph() const; CPoint GetNearestPosInGraph( const CPoint &pos ) const; int GetNearestNode( const CPoint &obPos ) const; CPoint GetRandomReachablePosInGraph( const CPoint &obPos ) const; // replacements for all the member functions we used to have on AABB nodes bool NodeContains( int nodeNum, const CPoint& obPos ) const; int GetConnection( int nodeA, int nodeB ) const; CPoint GetConnectionPos( int connectionNum ) const; int GetNumConnections( int nodeNum ) const; int GetConnected( int nodeNum, int connectionNum ) const; CPoint GetNodePos( int nodeNum ) const; CPoint GetRandomPosInNode( int nodeNum ) const; CKeywords* GetNodeKeywords( int nodeNum ) const; bool IsPosLegal( const CPoint& pos, CKeywords* keywords ) const; void AddRegion( CAINavNodeRegion* const ); CAINavPath* MakePath( const CPoint& obFrom, const CPoint& obTo, CKeywords* ); bool InGraph( const CPoint& obPos, const CKeywords* pobKeys = 0, AINavHint* pHint = 0 ) const; bool InGraph( const CPoint& obPos, const float radius, const CKeywords* pobKeys = 0, AINavCache* pCache = 0 ) const; INGRAPH_RETURN InGraph( const CPoint& obP1, const CPoint& obP2, CMatrix* pIntersectResult, const CKeywords* pobKeys = 0 ) const; bool InSafeZone( const CPoint& obPos, const float radius = 0.0f ) const; int GetNumNodes() const; AIObjectAvoidance* GetRepulsion() const { return m_pobRepulsion; } static bool HasLineOfSight( const CPoint& obFrom, const CPoint& obTo, const CEntity* pobIgnoreEntity, const float ); static bool HasLineOfSightWithWidth( const CPoint& obFrom, const CPoint& obTo, const CEntity* pobIgnoreEntity, const float, const float ); static void CAINavGraphManager::ClampPointToFloor( CPoint& obPos ); bool LineContainedByGraph( CPoint& from, CPoint& to, int& nodeHint ); void AddWall( AIDebugWall* const pobWall ) { m_obDebugWalls.push_back( pobWall ); } void AddSafeZone( AISafeZone* const pobZone ) { m_safeZone = pobZone; } AISafeZone* GetSafeZone( void) const { return m_safeZone; } void SetPathfindTestTarget( const CPoint& obTarget ) { m_obPathfindTestTarget = obTarget; m_bPathfindTestTargetChanged = true; } CPoint GetPathfindTestTarget() const { return m_obPathfindTestTarget; } void SetPathfindTestRun( bool bRun ) { m_bPathfindTestRun = bRun; m_bPathfindTestTargetChanged = true; } bool GetPathfindTestRun() const { return m_bPathfindTestRun; } bool HasPathfindTestChanged() { return m_bPathfindTestTargetChanged; } void AcknowledgePathfindTestChange() { m_bPathfindTestTargetChanged = false; } void SetPathfindTestObstaclePos( const CPoint& obObstaclePos ) { m_obPathfindTestObstaclePos = obObstaclePos; } // Functions to be invoked by keyboard/script void CreateNewAABB(); private: void FirstFrameInit( void ); typedef ntstd::List<CAINavNodeAABB*, Mem::MC_AI> AINavNodeAABBList; AINavNodeAABBList m_obNavNodes; // list of nodes in the level CAINavNodeAABB* m_pobCurrentNode; // the most recently created node AINAVNODE_AABB_CREATE_STATE m_eCreateState; // will the next "create" button press begin or end an AABB AINavNodeRegionList m_obNavRegions; // list of region nodes in the level // structures for loading nav data AIIntermediateNavData* m_pobIntermediateData; AINavData* m_pobNavData; CPoint m_obTestStartPoint; CPoint m_obTestEndPoint; CPoint m_obPathfindTestTarget; CPoint m_obPathfindTestObstaclePos; CEntity* m_obPathfindTestObstacle; bool m_bPathfindTestRun; bool m_bPathfindTestTargetChanged; bool m_bDrawPathfindTestTarget; unsigned m_uNumNodes; AIObjectAvoidance* m_pobRepulsion; int m_iLastNodeAdded; bool m_bFirstFrame; AIGroupNavBrain* m_pobGroupNav; AIDebugWallList m_obDebugWalls; CAINavPath* m_pobTestPath; AISafeZone* m_safeZone; }; /*************************************************************************************************** * * CLASS * * DESCRIPTION * ***************************************************************************************************/ class AITest { public: AITest(); virtual ~AITest(); virtual void Update() = 0; private: }; /*************************************************************************************************** * * CLASS * * DESCRIPTION * ***************************************************************************************************/ class AITestWander : public AITest { public: AITestWander(); virtual ~AITestWander(); virtual void Update(); private: }; #endif
[ "hopefullyidontgetbanned735@gmail.com" ]
hopefullyidontgetbanned735@gmail.com
d0757d209a50f96f6fbfc9ce5b62dc7c9d0a5375
e05ee73f59fa33c462743b30cbc5d35263383e89
/sparse/src/zpcg.cpp
e5940d4165ef5f319001672c144bd8d996ebfea5
[]
no_license
bhrnjica/magma
33c9e8a89f9bc2352f70867a48ec2dab7f94a984
88c8ca1a668055859a1cb9a31a204b702b688df5
refs/heads/master
2021-10-09T18:49:50.396412
2019-01-02T13:51:33
2019-01-02T13:51:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,548
cpp
/* -- MAGMA (version 2.4.0) -- Univ. of Tennessee, Knoxville Univ. of California, Berkeley Univ. of Colorado, Denver @date June 2018 @author Hartwig Anzt @precisions normal z -> s d c */ #include "magmasparse_internal.h" #define RTOLERANCE lapackf77_dlamch( "E" ) #define ATOLERANCE lapackf77_dlamch( "E" ) /******************************************************************************* Purpose ------- Solves a system of linear equations A * X = B where A is a complex Hermitian N-by-N positive definite matrix A. This is a GPU implementation of the preconditioned Conjugate Gradient method. Arguments --------- @param[in] A magma_z_matrix input matrix A @param[in] b magma_z_matrix RHS b @param[in,out] x magma_z_matrix* solution approximation @param[in,out] solver_par magma_z_solver_par* solver parameters @param[in] precond_par magma_z_preconditioner* preconditioner @param[in] queue magma_queue_t Queue to execute in. @ingroup magmasparse_zposv *******************************************************************************/ extern "C" magma_int_t magma_zpcg( magma_z_matrix A, magma_z_matrix b, magma_z_matrix *x, magma_z_solver_par *solver_par, magma_z_preconditioner *precond_par, magma_queue_t queue ) { magma_int_t info = MAGMA_NOTCONVERGED; // prepare solver feedback solver_par->solver = Magma_PCG; solver_par->numiter = 0; solver_par->spmv_count = 0; // solver variables magmaDoubleComplex alpha, beta; double nom0, r0, res, nomb; magmaDoubleComplex den, gammanew, gammaold = MAGMA_Z_MAKE(1.0,0.0); // local variables magmaDoubleComplex c_zero = MAGMA_Z_ZERO, c_one = MAGMA_Z_ONE; magma_int_t dofs = A.num_rows* b.num_cols; // GPU workspace magma_z_matrix r={Magma_CSR}, rt={Magma_CSR}, p={Magma_CSR}, q={Magma_CSR}, h={Magma_CSR}; CHECK( magma_zvinit( &r, Magma_DEV, A.num_rows, b.num_cols, c_zero, queue )); CHECK( magma_zvinit( &rt,Magma_DEV, A.num_rows, b.num_cols, c_zero, queue )); CHECK( magma_zvinit( &p, Magma_DEV, A.num_rows, b.num_cols, c_zero, queue )); CHECK( magma_zvinit( &q, Magma_DEV, A.num_rows, b.num_cols, c_zero, queue )); CHECK( magma_zvinit( &h, Magma_DEV, A.num_rows, b.num_cols, c_zero, queue )); // solver setup CHECK( magma_zresidualvec( A, b, *x, &r, &nom0, queue)); // preconditioner CHECK( magma_z_applyprecond_left( MagmaNoTrans, A, r, &rt, precond_par, queue )); CHECK( magma_z_applyprecond_right( MagmaNoTrans, A, rt, &h, precond_par, queue )); magma_zcopy( dofs, h.dval, 1, p.dval, 1, queue ); // p = h CHECK( magma_z_spmv( c_one, A, p, c_zero, q, queue )); // q = A p solver_par->spmv_count++; den = magma_zdotc( dofs, p.dval, 1, q.dval, 1, queue ); // den = p dot q solver_par->init_res = nom0; nomb = magma_dznrm2( dofs, b.dval, 1, queue ); if ( nomb == 0.0 ){ nomb=1.0; } if ( (r0 = nomb * solver_par->rtol) < ATOLERANCE ){ r0 = ATOLERANCE; } solver_par->final_res = solver_par->init_res; solver_par->iter_res = solver_par->init_res; if ( solver_par->verbose > 0 ) { solver_par->res_vec[0] = (real_Double_t)nom0; solver_par->timing[0] = 0.0; } if ( nom0 < r0 ) { info = MAGMA_SUCCESS; goto cleanup; } // check positive definite if ( MAGMA_Z_ABS(den) <= 0.0 ) { info = MAGMA_NONSPD; goto cleanup; } //Chronometry real_Double_t tempo1, tempo2; tempo1 = magma_sync_wtime( queue ); solver_par->numiter = 0; solver_par->spmv_count = 0; // start iteration do { solver_par->numiter++; // preconditioner CHECK( magma_z_applyprecond_left( MagmaNoTrans, A, r, &rt, precond_par, queue )); CHECK( magma_z_applyprecond_right( MagmaNoTrans, A, rt, &h, precond_par, queue )); gammanew = magma_zdotc( dofs, r.dval, 1, h.dval, 1, queue ); // gn = < r,h> if ( solver_par->numiter == 1 ) { magma_zcopy( dofs, h.dval, 1, p.dval, 1, queue ); // p = h } else { beta = (gammanew/gammaold); // beta = gn/go magma_zscal( dofs, beta, p.dval, 1, queue ); // p = beta*p magma_zaxpy( dofs, c_one, h.dval, 1, p.dval, 1, queue ); // p = p + h } CHECK( magma_z_spmv( c_one, A, p, c_zero, q, queue )); // q = A p solver_par->spmv_count++; den = magma_zdotc( dofs, p.dval, 1, q.dval, 1, queue ); // den = p dot q alpha = gammanew / den; magma_zaxpy( dofs, alpha, p.dval, 1, x->dval, 1, queue ); // x = x + alpha p magma_zaxpy( dofs, -alpha, q.dval, 1, r.dval, 1, queue ); // r = r - alpha q gammaold = gammanew; res = magma_dznrm2( dofs, r.dval, 1, queue ); if ( solver_par->verbose > 0 ) { tempo2 = magma_sync_wtime( queue ); if ( (solver_par->numiter)%solver_par->verbose == 0 ) { solver_par->res_vec[(solver_par->numiter)/solver_par->verbose] = (real_Double_t) res; solver_par->timing[(solver_par->numiter)/solver_par->verbose] = (real_Double_t) tempo2-tempo1; } } if ( res/nomb <= solver_par->rtol || res <= solver_par->atol ){ break; } } while ( solver_par->numiter+1 <= solver_par->maxiter ); tempo2 = magma_sync_wtime( queue ); solver_par->runtime = (real_Double_t) tempo2-tempo1; double residual; CHECK( magma_zresidualvec( A, b, *x, &r, &residual, queue)); solver_par->iter_res = res; solver_par->final_res = residual; if ( solver_par->numiter < solver_par->maxiter ) { info = MAGMA_SUCCESS; } else if ( solver_par->init_res > solver_par->final_res ) { if ( solver_par->verbose > 0 ) { if ( (solver_par->numiter)%solver_par->verbose == 0 ) { solver_par->res_vec[(solver_par->numiter)/solver_par->verbose] = (real_Double_t) res; solver_par->timing[(solver_par->numiter)/solver_par->verbose] = (real_Double_t) tempo2-tempo1; } } info = MAGMA_SLOW_CONVERGENCE; if( solver_par->iter_res < solver_par->rtol*nomb || solver_par->iter_res < solver_par->atol ) { info = MAGMA_SUCCESS; } } else { if ( solver_par->verbose > 0 ) { if ( (solver_par->numiter)%solver_par->verbose == 0 ) { solver_par->res_vec[(solver_par->numiter)/solver_par->verbose] = (real_Double_t) res; solver_par->timing[(solver_par->numiter)/solver_par->verbose] = (real_Double_t) tempo2-tempo1; } } info = MAGMA_DIVERGENCE; } cleanup: magma_zmfree(&r, queue ); magma_zmfree(&rt, queue ); magma_zmfree(&p, queue ); magma_zmfree(&q, queue ); magma_zmfree(&h, queue ); solver_par->info = info; return info; } /* magma_zcg */
[ "sinkingsugar@gmail.com" ]
sinkingsugar@gmail.com
f6d628e48bb09288efdc289dcbb7cb9ff9cd6b23
fd6fa97508400a0fb24f374e2b356dbd3b9a5f98
/src/aggregatefunctminexpression.cpp
ad8cf923c0d5e539bc06c02cd8c52c65bbdc164e
[ "BSD-3-Clause" ]
permissive
zacharywhitley/gcx-engine
d0a715480a9b85af7a740281f8ae1933fab9dff8
4e8a2a6c2d55cae29698a3e67daee1215676bb93
refs/heads/master
2020-05-29T10:33:12.251064
2019-05-28T20:41:56
2019-05-28T20:41:56
189,096,646
0
0
null
null
null
null
UTF-8
C++
false
false
4,730
cpp
/* | Author: Michael Schmidt; | Gunnar Jehl | | ************************* SOFTWARE LICENSE AGREEMENT *********************** | This source code is published under the BSD License. | | See file 'LICENSE.txt' that comes with this distribution or | http://dbis.informatik.uni-freiburg.de/index.php?project=GCX/license.php | for the full license agreement. | | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE | ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE | LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR | CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF | SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS | INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) | ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE | POSSIBILITY OF SUCH DAMAGE. | **************************************************************************** */ /*! @file * @brief Implementations of header file aggregatefunctminexpression.h. * @details Implementations of constructors, destructor and functions of the corresponding header file aggregatefunctminexpression.h. * @author Michael Schmidt * @author Gunnar Jehl * @version 2.1 * @license Software License Agreement (BSD License) */ #include "aggregatefunctminexpression.h" AggregateFunctMinExpression::AggregateFunctMinExpression(VarExpression * _var): AggregateFunctExpression(et_aggregatefunctmin, _var) { } AggregateFunctMinExpression::AggregateFunctMinExpression(VarStepExpression * _varstep): AggregateFunctExpression(et_aggregatefunctmin, _varstep) { } AggregateFunctMinExpression::~AggregateFunctMinExpression() { } void AggregateFunctMinExpression::eval(OutputStream & eos, Environment * env, unsigned modus) { switch (modus) { case EVAL_QUERY: { bool empty_sequence = true; long double min_val = calculateValue(eos, env, modus, empty_sequence); if (!empty_sequence) { const char *min_str = MiscFunctions::getStringFromNumerical(min_val); eos << min_str; delete[]min_str; } else { eos << OUTPUT_MIN_ON_EMPTY_SEQUENCE; } break; } case EVAL_QUERY_SILENT: { bool empty_sequence = true; long double min_val = calculateValue(eos, env, modus, empty_sequence); if (!empty_sequence) { cur_val.setNumVal(min_val); } else { const char *min_empty_val = new char[strlen(OUTPUT_MIN_ON_EMPTY_SEQUENCE) + 1]; strcpy((char *) min_empty_val, OUTPUT_MIN_ON_EMPTY_SEQUENCE); cur_val.setStrVal(min_empty_val); } break; } case EVAL_SIGNOFF: forexp->eval(eos, env, EVAL_SIGNOFF); break; default: throw RuntimeException ("AggregateFunctMinExpression: Illegal Evaluation Mode", eid_runtime_illegalmode); break; } } long double AggregateFunctMinExpression::calculateValue(OutputStream & eos, Environment * env, unsigned modus, bool & empty_sequence) { var ? bit->init(env->getNodeBinding(var->getId())) : bit->init(env->getNodeBinding(varstep->getId())); long double min_ret = 0; long double count = 0; long double result = 0; const char *pcd = NULL; while (BufferNode * cur = bit->getNext(READ_UP_TO_CLOSE_CONTEXT, LOCK_CONTEXT_ALWAYS_CLEAR)) { empty_sequence = false; count++; pcd = cur->getPCDataRepresentation(); if (count > 1) { result = min(result, MiscFunctions::getNumericFromString(pcd)); } else { result = MiscFunctions::getNumericFromString(pcd); } free((char *) pcd); forexp->evalSignOffForBinding(eos, env, cur); } bit->clear(); if (!empty_sequence) { min_ret = MiscFunctions::getRoundFrom(result); } return min_ret; }
[ "mschmidt00@ad718d26-2018-4b5f-a52a-3114c437cfa5" ]
mschmidt00@ad718d26-2018-4b5f-a52a-3114c437cfa5
f39d3dddc2402f9e1889a16c13732387d7d80cb2
bf1fb2462ee6d990e3fe60c82cd284b4c253e6ce
/hogarPersonas.cpp
33fd052f933124e295999af1a8785bad217d4e6c
[]
no_license
Ejercicios-Desarrollo/D.Software1-Ejercicios-Modulo-1
ef4c5792ce871c7dfcb4a82e0512c17a248dc269
521f6e07e996f890d31c137e53e6db7aba6edc07
refs/heads/master
2022-03-08T15:47:06.408675
2019-08-15T00:53:21
2019-08-15T00:53:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,646
cpp
// hogarPersonas.cpp : Este archivo contiene la función "main". La ejecución del programa comienza y termina ahí. // /*Modelar un hogar, que tenga distintas partes de la casa, viven 4 personas inicialmente, con nombre, apellido, edad saber donde duerme cada una de las personas, la habitación tiene coordenada y quiero saber si una habitación es contigua a la otra coordenada(x,y), tengo la direccion a izq y der de los vecinos*/ #include "pch.h" #include <iostream> #include <sstream> #include <vector> #include<string> using namespace std; struct persona { string nombre; string apellido; int edad; }; struct habitacion { persona p; int numHabitacion; int habitacionIzq; int habitacionDer; }; struct hogar { habitacion habitaciones[4]; }; int main() { int num; hogar hogar; for (int i = 0; i < 4; i++) { hogar.habitaciones[i].numHabitacion = i; hogar.habitaciones[i].habitacionDer = i + 1; hogar.habitaciones[i].habitacionIzq = i - 1; cout << "Habitacion " << i << endl; cout << "Ingresa tu nombre: "; cin >> hogar.habitaciones[i].p.nombre; cout << endl << "Ingresa tu apellido: "; cin >> hogar.habitaciones[i].p.apellido; cout << endl << "Ingresa tu edad: "; cin >> hogar.habitaciones[i].p.edad; cout << endl << endl; } cout << "Ingresa num de habitacion: "; cin >> num; cout << hogar.habitaciones[num].p.nombre << " esta a la derecha de " << hogar.habitaciones[(hogar.habitaciones[num].habitacionIzq)].p.nombre; cout << endl << "y a la izquierda de " << hogar.habitaciones[(hogar.habitaciones[num].habitacionDer)].p.nombre; }
[ "noreply@github.com" ]
Ejercicios-Desarrollo.noreply@github.com
64cfe73beac670b7dafe208c1ea1000f0e1665a0
41c4c7421bf346e246e550334ee0cc19f8f17485
/DesignMode/Subtraction.cpp
90bbe91e2049457696f1d31a1345f3484415813b
[]
no_license
xingyuan1hao/DesignPattern
31e89ede424269f64f256b130db9086266acf030
add44c2b82fe3d4e69c02b2592685aeff4173a7e
refs/heads/master
2020-04-05T03:59:58.567733
2018-12-05T10:50:35
2018-12-05T10:50:35
156,534,374
0
0
null
null
null
null
UTF-8
C++
false
false
183
cpp
#include "StdAfx.h" #include "Subtraction.h" Subtraction::Subtraction(void) { } Subtraction::~Subtraction(void) { } double Subtraction::getResult() { return numberA - numberB; }
[ "ahhlin@163.com" ]
ahhlin@163.com
59868dcfca6f01a1e754f3fd4b0c0e763035643c
89292be10b520779772588bbd90184e4f6d00748
/net/spdy/hpack_huffman_table.cc
5372b97704f66ad9f4a32ed07cf455aaee3c055a
[ "BSD-3-Clause" ]
permissive
anirudhSK/chromium
2cd85630932a05fa065a5d9a1703de33e9b5c483
a8f23c87e656ab9ba49de9ccccbc53f614cdcb41
refs/heads/master
2016-09-11T03:25:35.744751
2014-03-14T15:59:45
2014-03-14T15:59:45
10,112,188
2
2
null
null
null
null
UTF-8
C++
false
false
10,522
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 "net/spdy/hpack_huffman_table.h" #include <algorithm> #include <cmath> #include "base/logging.h" #include "net/spdy/hpack_input_stream.h" #include "net/spdy/hpack_output_stream.h" namespace net { using base::StringPiece; using std::string; namespace { // How many bits to index in the root decode table. const uint8 kDecodeTableRootBits = 9; // Maximum number of bits to index in successive decode tables. const uint8 kDecodeTableBranchBits = 6; // Number of decode iterations required for a 32-bit code. const int kDecodeIterations = static_cast<int>( std::ceil((32.f - kDecodeTableRootBits) / kDecodeTableBranchBits)); bool SymbolLengthAndIdCompare(const HpackHuffmanSymbol& a, const HpackHuffmanSymbol& b) { if (a.length == b.length) { return a.id < b.id; } return a.length < b.length; } bool SymbolIdCompare(const HpackHuffmanSymbol& a, const HpackHuffmanSymbol& b) { return a.id < b.id; } } // namespace HpackHuffmanTable::DecodeEntry::DecodeEntry() : next_table_index(0), length(0), symbol_id(0) { } HpackHuffmanTable::DecodeEntry::DecodeEntry(uint8 next_table_index, uint8 length, uint16 symbol_id) : next_table_index(next_table_index), length(length), symbol_id(symbol_id) { } size_t HpackHuffmanTable::DecodeTable::size() const { return size_t(1) << indexed_length; } HpackHuffmanTable::HpackHuffmanTable() {} HpackHuffmanTable::~HpackHuffmanTable() {} bool HpackHuffmanTable::Initialize(const HpackHuffmanSymbol* input_symbols, size_t symbol_count) { CHECK(!IsInitialized()); std::vector<Symbol> symbols(symbol_count); // Validate symbol id sequence, and copy into |symbols|. for (size_t i = 0; i != symbol_count; i++) { if (i != input_symbols[i].id) { failed_symbol_id_ = i; return false; } symbols[i] = input_symbols[i]; } // Order on length and ID ascending, to verify symbol codes are canonical. std::sort(symbols.begin(), symbols.end(), SymbolLengthAndIdCompare); if (symbols[0].code != 0) { failed_symbol_id_ = 0; return false; } for (size_t i = 1; i != symbols.size(); i++) { unsigned code_shift = 32 - symbols[i-1].length; uint32 code = symbols[i-1].code + (1 << code_shift); if (code != symbols[i].code) { failed_symbol_id_ = symbols[i].id; return false; } if (code < symbols[i-1].code) { // An integer overflow occurred. This implies the input // lengths do not represent a valid Huffman code. failed_symbol_id_ = symbols[i].id; return false; } } if (symbols.back().length < 8) { // At least one code (such as an EOS symbol) must be 8 bits or longer. // Without this, some inputs will not be encodable in a whole number // of bytes. return false; } pad_bits_ = static_cast<uint8>(symbols.back().code >> 24); BuildDecodeTables(symbols); // Order on symbol ID ascending. std::sort(symbols.begin(), symbols.end(), SymbolIdCompare); BuildEncodeTable(symbols); return true; } void HpackHuffmanTable::BuildEncodeTable(const std::vector<Symbol>& symbols) { for (size_t i = 0; i != symbols.size(); i++) { const Symbol& symbol = symbols[i]; CHECK_EQ(i, symbol.id); code_by_id_.push_back(symbol.code); length_by_id_.push_back(symbol.length); } } void HpackHuffmanTable::BuildDecodeTables(const std::vector<Symbol>& symbols) { AddDecodeTable(0, kDecodeTableRootBits); // We wish to maximize the flatness of the DecodeTable hierarchy (subject to // the |kDecodeTableBranchBits| constraint), and to minimize the size of // child tables. To achieve this, we iterate in order of descending code // length. This ensures that child tables are visited with their longest // entry first, and that the child can therefore be minimally sized to hold // that entry without fear of introducing unneccesary branches later. for (std::vector<Symbol>::const_reverse_iterator it = symbols.rbegin(); it != symbols.rend(); ++it) { uint8 table_index = 0; while (true) { const DecodeTable table = decode_tables_[table_index]; // Mask and shift the portion of the code being indexed into low bits. uint32 index = (it->code << table.prefix_length); index = index >> (32 - table.indexed_length); CHECK_LT(index, table.size()); DecodeEntry entry = Entry(table, index); uint8 total_indexed = table.prefix_length + table.indexed_length; if (total_indexed >= it->length) { // We're writing a terminal entry. entry.length = it->length; entry.symbol_id = it->id; entry.next_table_index = table_index; SetEntry(table, index, entry); break; } if (entry.length == 0) { // First visit to this placeholder. We need to create a new table. CHECK_EQ(entry.next_table_index, 0); entry.length = it->length; entry.next_table_index = AddDecodeTable( total_indexed, // Becomes the new table prefix. std::min<uint8>(kDecodeTableBranchBits, entry.length - total_indexed)); SetEntry(table, index, entry); } CHECK_NE(entry.next_table_index, table_index); table_index = entry.next_table_index; } } // Fill shorter table entries into the additional entry spots they map to. for (size_t i = 0; i != decode_tables_.size(); i++) { const DecodeTable& table = decode_tables_[i]; uint8 total_indexed = table.prefix_length + table.indexed_length; size_t j = 0; while (j != table.size()) { const DecodeEntry& entry = Entry(table, j); if (entry.length != 0 && entry.length < total_indexed) { // The difference between entry & table bit counts tells us how // many additional entries map to this one. size_t fill_count = 1 << (total_indexed - entry.length); CHECK_LE(j + fill_count, table.size()); for (size_t k = 1; k != fill_count; k++) { CHECK_EQ(Entry(table, j + k).length, 0); SetEntry(table, j + k, entry); } j += fill_count; } else { j++; } } } } uint8 HpackHuffmanTable::AddDecodeTable(uint8 prefix, uint8 indexed) { CHECK_LT(decode_tables_.size(), 255u); { DecodeTable table; table.prefix_length = prefix; table.indexed_length = indexed; table.entries_offset = decode_entries_.size(); decode_tables_.push_back(table); } decode_entries_.resize(decode_entries_.size() + (size_t(1) << indexed)); return static_cast<uint8>(decode_tables_.size() - 1); } const HpackHuffmanTable::DecodeEntry& HpackHuffmanTable::Entry( const DecodeTable& table, uint32 index) const { DCHECK_LT(index, table.size()); DCHECK_LT(table.entries_offset + index, decode_entries_.size()); return decode_entries_[table.entries_offset + index]; } void HpackHuffmanTable::SetEntry(const DecodeTable& table, uint32 index, const DecodeEntry& entry) { CHECK_LT(index, table.size()); CHECK_LT(table.entries_offset + index, decode_entries_.size()); decode_entries_[table.entries_offset + index] = entry; } bool HpackHuffmanTable::IsInitialized() const { return !code_by_id_.empty(); } void HpackHuffmanTable::EncodeString(StringPiece in, HpackOutputStream* out) const { size_t bit_remnant = 0; for (size_t i = 0; i != in.size(); i++) { uint16 symbol_id = static_cast<uint8>(in[i]); CHECK_GT(code_by_id_.size(), symbol_id); // Load, and shift code to low bits. unsigned length = length_by_id_[symbol_id]; uint32 code = code_by_id_[symbol_id] >> (32 - length); bit_remnant = (bit_remnant + length) % 8; if (length > 24) { out->AppendBits(static_cast<uint8>(code >> 24), length - 24); length = 24; } if (length > 16) { out->AppendBits(static_cast<uint8>(code >> 16), length - 16); length = 16; } if (length > 8) { out->AppendBits(static_cast<uint8>(code >> 8), length - 8); length = 8; } out->AppendBits(static_cast<uint8>(code), length); } if (bit_remnant != 0) { // Pad current byte as required. out->AppendBits(pad_bits_ >> bit_remnant, 8 - bit_remnant); } } bool HpackHuffmanTable::DecodeString(HpackInputStream* in, size_t out_capacity, string* out) const { out->clear(); // Current input, stored in the high |bits_available| bits of |bits|. uint32 bits = 0; size_t bits_available = 0; bool peeked_success = in->PeekBits(&bits_available, &bits); while (true) { const DecodeTable* table = &decode_tables_[0]; uint32 index = bits >> (32 - kDecodeTableRootBits); for (int i = 0; i != kDecodeIterations; i++) { DCHECK_LT(index, table->size()); DCHECK_LT(Entry(*table, index).next_table_index, decode_tables_.size()); table = &decode_tables_[Entry(*table, index).next_table_index]; // Mask and shift the portion of the code being indexed into low bits. index = (bits << table->prefix_length) >> (32 - table->indexed_length); } const DecodeEntry& entry = Entry(*table, index); if (entry.length > bits_available) { if (!peeked_success) { // Unable to read enough input for a match. If only a portion of // the last byte remains, this is a successful EOF condition. in->ConsumeByteRemainder(); return !in->HasMoreData(); } } else if (entry.length == 0) { // The input is an invalid prefix, larger than any prefix in the table. return false; } else { if (out->size() == out_capacity) { // This code would cause us to overflow |out_capacity|. return false; } if (entry.symbol_id < 256) { // Assume symbols >= 256 are used for padding. out->push_back(static_cast<char>(entry.symbol_id)); } in->ConsumeBits(entry.length); bits = bits << entry.length; bits_available -= entry.length; } peeked_success = in->PeekBits(&bits_available, &bits); } NOTREACHED(); return false; } } // namespace net
[ "jgraettinger@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98" ]
jgraettinger@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98
7f26331951e96d29f955822193e70de9dead3d5b
7300301d5d42b0ac5de65dbb6b59ab1a954af41b
/csacademy/practice/attack-and-speed.cpp
d4a3f3d13015af4b8c637185074c29757042c4e0
[]
no_license
carnivorous-hotdog/cp
c46bf7824895d302c518b0e1289e7e65458caa5e
41c7eee3770b5efc8bcb7213780499754959ec81
refs/heads/master
2022-08-21T19:32:37.964118
2020-05-24T12:29:03
2020-05-24T12:29:03
241,745,227
0
0
null
null
null
null
UTF-8
C++
false
false
1,348
cpp
#include <bits/stdc++.h> using namespace std; #define vi vector<int> #define vii vector<int, int> #define ll long long #define pb push_back #define mp make_pair #define endl '\n' #define idk ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #ifdef LOCAL #define trace(...) __f(#__VA_ARGS__, __VA_ARGS__) template <typename Arg1>void __f(const char* name, Arg1&& arg1){cout<<name<<" : "<<arg1<<"\n";} template <typename Arg1, typename... Args>void __f(const char* names, Arg1&& arg1, Args&&... args) {const char* comma=strchr(names+1,',');cout.write(names,comma-names)<<" : "<<arg1<<" |";__f(comma+1, args...);} #define traceloop(x,a) { cerr<<#a<<": "; for(ll ix=0;ix<x;ix++) cerr<<a[ix]<<" "; cerr<<endl; } #else #define trace(...) 42 #define traceloop(...) 42 #endif const int MOD=1e9+7; //////////////////////// code starts /////////////////////// int main(){ idk #ifdef LOCAL //freopen("input.txt", "r", stdin); //freopen("output.txt", "w", stdout); #endif ll a, s, k, x, y; cin >> a >> s >> k >> x >> y; double xx = 1.0 * (a - s - k * y) / (x + y); // trace(xx); bool ok = true; if ((ll)xx != xx) ok = false; cout << (ok ? -1 * (ll)xx : -1) << endl; #ifdef LOCAL cerr << "Time elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC << " s.\n"; #endif return 0; }
[ "makkoncept.cp@gmail.com" ]
makkoncept.cp@gmail.com
62c6899681b30ebe0929095ce51d2968d22c87c9
dac5254630fefae851da7c843dcab7f6a6af9703
/Win32/Sources/Application/Preferences_Dialog/CPreferencesDialog.cp
8ce48085066fc45ffc06931894ead572e40d7a48
[ "Apache-2.0" ]
permissive
gpreviato/Mulberry-Mail
dd4e3618468fff36361bd2aeb0a725593faa0f8d
ce5c56ca7044e5ea290af8d3d2124c1d06f36f3a
refs/heads/master
2021-01-20T03:31:39.515653
2017-09-21T13:09:55
2017-09-21T13:09:55
18,178,314
5
2
null
null
null
null
UTF-8
C++
false
false
43,052
cp
/* Copyright (c) 2007-2009 Cyrus Daboo. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // CPreferencesDialog.cpp : implementation file // #include "CPreferencesDialog.h" #include "CAdbkManagerView.h" #include "CAdbkManagerWindow.h" #include "CAdbkSearchWindow.h" #include "CAddressBookDoc.h" #include "CAddressBookView.h" #include "CAddressBookWindow.h" #include "CCalendarStoreWindow.h" #include "CCalendarView.h" #include "CCalendarWindow.h" #include "CAdminLock.h" #include "CCopyToMenu.h" #include "CErrorHandler.h" #include "CFontCache.h" #include "CIdentityPopup.h" #include "CIMAPClient.h" #include "CLetterWindow.h" #include "CMailboxWindow.h" #include "CMboxList.h" #include "CMessageView.h" #include "CMulberryApp.h" #include "COptionsProtocol.h" #include "CPrefsSimple.h" #include "CPrefsAccounts.h" #include "CPrefsAlerts.h" #include "CPrefsDisplay.h" #include "CPrefsFormatting.h" #include "CPrefsMailbox.h" #include "CPrefsMessage.h" #include "CPrefsLetter.h" #include "CPrefsSecurity.h" #include "CPrefsIdentity.h" #include "CPrefsAddress.h" #include "CPrefsCalendar.h" #include "CPrefsAttachments.h" #include "CPrefsSpelling.h" #include "CPluginManager.h" #include "CPreferencesFile.h" #include "CPreferenceKeys.h" #include "CRemotePrefsSets.h" #include "CSDIFrame.h" #include "CServerView.h" #include "CRulesWindow.h" #include "CServerWindow.h" #include "CTextListChoice.h" #include "CUnicodeUtils.h" const char* cPanelNames[] = {"", "Account", "Alerts", "Display", "Styled", "Mailbox", "Message", "Letter", "Security", "Identities", "Address", "Calendar", "Attachments", "Spelling", "Speech", NULL}; const int cSecurityIndex = 8; ///////////////////////////////////////////////////////////////////////////// // CPreferencesDialog dialog IMPLEMENT_DYNAMIC(CPreferencesDialog, CHelpPropertySheet) CPreferencesDialog::CPreferencesDialog(CWnd* pParent /*=NULL*/) : CHelpPropertySheet(_T("Preferences"), pParent), mCopyPrefs(*CPreferences::sPrefs) { mCurrentPrefsFile = NULL; mLoadedNewPrefs = false; mWindowsReset = false; mAccountNew = false; mAccountRename = false; mPrefsSimple = NULL; mPrefsAccounts = NULL; mPrefsAlerts = NULL; mPrefsDisplay = NULL; mPrefsFormatting = NULL; mPrefsMailbox = NULL; mPrefsMessage = NULL; mPrefsLetter = NULL; mPrefsSecurity = NULL; mPrefsIdentity = NULL; mPrefsAddress = NULL; mPrefsCalendar = NULL; mPrefsAttachments = NULL; mPrefsSpelling = NULL; // Force to advanced to get dialog height correctly set up bool old_value = mCopyPrefs.mSimple.GetValue(); SetSimple(false, true); mCopyPrefs.mSimple.SetValue(old_value, false); } CPreferencesDialog::~CPreferencesDialog() { delete mPrefsSimple; delete mPrefsAccounts; delete mPrefsAlerts; delete mPrefsDisplay; delete mPrefsFormatting; delete mPrefsMailbox; delete mPrefsMessage; delete mPrefsLetter; delete mPrefsSecurity; delete mPrefsIdentity; delete mPrefsAddress; delete mPrefsCalendar; delete mPrefsAttachments; delete mPrefsSpelling; } BEGIN_MESSAGE_MAP(CPreferencesDialog, CHelpPropertySheet) //{{AFX_MSG_MAP(CPreferencesDialog) ON_BN_CLICKED(IDOK, OnOK) ON_BN_CLICKED(IDCANCEL, OnCancel) ON_BN_CLICKED(IDC_PREFSSIMPLEBTN, OnPrefsSimpleBtn) ON_BN_CLICKED(IDC_PREFSADVANCEDBTN, OnPrefsAdvancedBtn) ON_BN_CLICKED(IDC_PREFSLOCALBTN, OnPrefsLocalBtn) ON_BN_CLICKED(IDC_PREFSREMOTEBTN, OnPrefsRemoteBtn) ON_BN_CLICKED(IDC_PREFSOPENBTN, OnPrefsOpenBtn) ON_BN_CLICKED(IDC_PREFSSAVEASBTN, OnPrefsSaveAsBtn) ON_BN_CLICKED(IDC_PREFSSAVEDEFAULTBTN, OnPrefsSaveDefaultBtn) //}}AFX_MSG_MAP END_MESSAGE_MAP() void CPreferencesDialog::InitPrefs(void) { // Do data exchange if (mCopyPrefs.mSimple.GetValue()) mPrefsSimple->SetPrefs(&mCopyPrefs); else { mPrefsAccounts->SetPrefs(&mCopyPrefs); mPrefsAlerts->SetPrefs(&mCopyPrefs); mPrefsDisplay->SetPrefs(&mCopyPrefs); mPrefsFormatting->SetPrefs(&mCopyPrefs); mPrefsMailbox->SetPrefs(&mCopyPrefs); mPrefsMessage->SetPrefs(&mCopyPrefs); mPrefsLetter->SetPrefs(&mCopyPrefs); if (mPrefsSecurity) mPrefsSecurity->SetPrefs(&mCopyPrefs); mPrefsIdentity->SetPrefs(&mCopyPrefs); mPrefsAddress->SetPrefs(&mCopyPrefs); if (mPrefsCalendar) mPrefsCalendar->SetPrefs(&mCopyPrefs); mPrefsAttachments->SetPrefs(&mCopyPrefs); if (mPrefsSpelling) mPrefsSpelling->SetPrefs(&mCopyPrefs); } } void CPreferencesDialog::ResetPrefs(void) { // Do data exchange if (mCopyPrefs.mSimple.GetValue()) mPrefsSimple->ResetPrefs(&mCopyPrefs); else { mPrefsAccounts->ResetPrefs(&mCopyPrefs); mPrefsAlerts->ResetPrefs(&mCopyPrefs); mPrefsDisplay->ResetPrefs(&mCopyPrefs); mPrefsFormatting->ResetPrefs(&mCopyPrefs); mPrefsMailbox->ResetPrefs(&mCopyPrefs); mPrefsMessage->ResetPrefs(&mCopyPrefs); mPrefsLetter->ResetPrefs(&mCopyPrefs); if (mPrefsSecurity) mPrefsSecurity->ResetPrefs(&mCopyPrefs); mPrefsIdentity->ResetPrefs(&mCopyPrefs); mPrefsAddress->ResetPrefs(&mCopyPrefs); if (mPrefsCalendar) mPrefsCalendar->ResetPrefs(&mCopyPrefs); mPrefsAttachments->ResetPrefs(&mCopyPrefs); if (mPrefsSpelling) mPrefsSpelling->ResetPrefs(&mCopyPrefs); } } // Update prefs from panel void CPreferencesDialog::UpdateCopyPrefs(void) { // Force active page to update in case of existing changes GetActivePage()->UpdateData(true); // Make sheets update prefs if (mCopyPrefs.mSimple.GetValue()) mPrefsSimple->UpdatePrefs(&mCopyPrefs); else { mPrefsAccounts->UpdatePrefs(&mCopyPrefs); mPrefsAlerts->UpdatePrefs(&mCopyPrefs); mPrefsDisplay->UpdatePrefs(&mCopyPrefs); mPrefsFormatting->UpdatePrefs(&mCopyPrefs); mPrefsMailbox->UpdatePrefs(&mCopyPrefs); mPrefsMessage->UpdatePrefs(&mCopyPrefs); mPrefsLetter->UpdatePrefs(&mCopyPrefs); if (mPrefsSecurity) mPrefsSecurity->UpdatePrefs(&mCopyPrefs); mPrefsIdentity->UpdatePrefs(&mCopyPrefs); mPrefsAddress->UpdatePrefs(&mCopyPrefs); if (mPrefsCalendar) mPrefsCalendar->UpdatePrefs(&mCopyPrefs); mPrefsAttachments->UpdatePrefs(&mCopyPrefs); if (mPrefsSpelling) mPrefsSpelling->UpdatePrefs(&mCopyPrefs); } } ///////////////////////////////////////////////////////////////////////////// // CPreferencesDialog message handlers BOOL CPreferencesDialog::OnInitDialog() { const short cBtnWidth = 82; const short cBtnAdjust = 8; const short cBtnHeight = 22; const short cBtnGap = 30; const short cBtnSmallGap = 20; const short cBtnExtraGap = 20; BOOL result = CHelpPropertySheet::OnInitDialog(); // Set flags m_psh.dwFlags &= ~PSH_HASHELP; // Disable help button m_psh.dwFlags &= ~PSH_NOAPPLYNOW; // Disable Apply Now button ModifyStyleEx(0, WS_EX_CONTEXTHELP | DS_CENTER); // Add context help and center it // Move and add extra buttons // Resize CRect wndRect; GetWindowRect(wndRect); MoveWindow(wndRect.left, wndRect.top, wndRect.Width() + 100, wndRect.Height() - 25, false); CPoint btnPos; btnPos.x = wndRect.right - 4 + cBtnAdjust; btnPos.y = wndRect.top + 40; ScreenToClient(&btnPos); // Adjust for Win32s //if (afxData.bWin31) // btnPos.x -= 15; // Move OK btn CWnd* btn = GetDlgItem(IDOK); btn->SetWindowPos(NULL, btnPos.x, btnPos.y, cBtnWidth, cBtnHeight, SWP_NOZORDER); btn = btn->GetParent(); btn = btn->GetParent(); // Move Cancel btn btnPos.Offset(0, cBtnGap); btn = GetDlgItem(IDCANCEL); btn->SetWindowPos(NULL, btnPos.x, btnPos.y, cBtnWidth, cBtnHeight, SWP_NOZORDER); // Hide Apply & Help btn = GetDlgItem(ID_APPLY_NOW); btn->ShowWindow(SW_HIDE); btn = GetDlgItem(IDHELP); btn->ShowWindow(SW_HIDE); // Position supplementary buttons CRect btnRect; btnRect.left = btnPos.x; btnRect.right = btnRect.left + cBtnWidth; btnRect.top = btnPos.y + cBtnExtraGap; btnRect.bottom = btnRect.top + cBtnHeight; btnRect.DeflateRect(-cBtnAdjust, 0); // Create simple button btnRect.OffsetRect(0, cBtnGap); CString s; s.LoadString(IDS_PREFSSIMPLEBTN); mPrefsSimpleBtn.Create(s, BS_AUTORADIOBUTTON | WS_CHILD | WS_VISIBLE | WS_TABSTOP, btnRect, this, IDC_PREFSSIMPLEBTN); mPrefsSimpleBtn.SetFont(CMulberryApp::sAppFont); mPrefsSimpleBtn.SetCheck(mCopyPrefs.mSimple.GetValue()); // Create advanced button btnRect.OffsetRect(0, cBtnSmallGap); s.LoadString(IDS_PREFSADVANCEDBTN); mPrefsAdvancedBtn.Create(s, BS_AUTORADIOBUTTON | WS_CHILD | WS_VISIBLE | WS_TABSTOP, btnRect, this, IDC_PREFSADVANCEDBTN); mPrefsAdvancedBtn.SetFont(CMulberryApp::sAppFont); mPrefsAdvancedBtn.SetCheck(!mCopyPrefs.mSimple.GetValue()); // Create storage area btnRect.OffsetRect(0, cBtnGap); s.LoadString(IDS_PREFSSTORAGEAREA); CRect r = CRect(btnRect.left, btnRect.top + cBtnGap - cBtnAdjust, btnRect.right, btnRect.top + 5 * cBtnGap + cBtnSmallGap + cBtnSmallGap/2); mStorageArea.Create(s, WS_CHILD | WS_VISIBLE | BS_GROUPBOX, r, this, IDC_STATIC); mStorageArea.SetFont(CMulberryApp::sAppFont); btnRect.DeflateRect(cBtnAdjust, 0); // Create local button btnRect.OffsetRect(0, cBtnGap + cBtnSmallGap/2); s.LoadString(IDS_PREFSLOCALBTN); mPrefsLocalBtn.Create(s, BS_AUTORADIOBUTTON | WS_GROUP | WS_CHILD | WS_VISIBLE | WS_TABSTOP, btnRect, this, IDC_PREFSLOCALBTN); mPrefsLocalBtn.SetFont(CMulberryApp::sAppFont); mPrefsLocalBtn.ShowWindow(mCopyPrefs.mSimple.GetValue() ? SW_HIDE : SW_SHOW); // Create remote button btnRect.OffsetRect(0, cBtnSmallGap); s.LoadString(IDS_PREFSREMOTEBTN); mPrefsRemoteBtn.Create(s, BS_AUTORADIOBUTTON | WS_CHILD | WS_VISIBLE | WS_TABSTOP, btnRect, this, IDC_PREFSREMOTEBTN); mPrefsRemoteBtn.SetFont(CMulberryApp::sAppFont); mPrefsRemoteBtn.ShowWindow(mCopyPrefs.mSimple.GetValue() ? SW_HIDE : SW_SHOW); // Local/remote captions mLocal = true; btnRect.DeflateRect(20, 0); s.LoadString(IDS_PREFSLOCALBTN); mPrefsLocalCaption.Create(s, WS_CHILD | WS_VISIBLE, btnRect, this, IDC_STATIC); mPrefsLocalCaption.SetFont(CMulberryApp::sAppFont); mPrefsLocalCaption.ShowWindow(mCopyPrefs.mSimple.GetValue() && mLocal ? SW_SHOW : SW_HIDE); s.LoadString(IDS_PREFSREMOTEBTN); mPrefsRemoteCaption.Create(s, WS_CHILD | WS_VISIBLE, btnRect, this, IDC_STATIC); mPrefsRemoteCaption.SetFont(CMulberryApp::sAppFont); mPrefsRemoteCaption.ShowWindow(mCopyPrefs.mSimple.GetValue() && !mLocal ? SW_SHOW : SW_HIDE); btnRect.DeflateRect(-20, 0); // Create open button btnRect.OffsetRect(0, cBtnGap); s.LoadString(IDS_PREFSOPENBTN); mPrefsOpenBtn.Create(s, WS_GROUP | WS_CHILD | WS_VISIBLE | WS_TABSTOP, btnRect, this, IDC_PREFSOPENBTN); mPrefsOpenBtn.SetFont(CMulberryApp::sAppFont); // Create save as button btnRect.OffsetRect(0, cBtnGap); s.LoadString(IDS_PREFSSAVEASBTN); mPrefsSaveAsBtn.Create(s, WS_CHILD | WS_VISIBLE | WS_TABSTOP, btnRect, this, IDC_PREFSSAVEASBTN); mPrefsSaveAsBtn.SetFont(CMulberryApp::sAppFont); // Create save default button btnRect.OffsetRect(0, cBtnGap); s.LoadString(IDS_PREFSSAVEDEFAULTBTN); mPrefsSaveDefaultBtn.Create(s, WS_CHILD | WS_VISIBLE | WS_TABSTOP, btnRect, this, IDC_PREFSSAVEDEFAULTBTN); mPrefsSaveDefaultBtn.SetFont(CMulberryApp::sAppFont); // Set prefs file to current app file and change title mCurrentPrefsFile = CMulberryApp::sCurrentPrefsFile; SetWindowTitle(); // Handle admin lockouts if (CAdminLock::sAdminLock.mNoLocalPrefs) { mPrefsLocalBtn.EnableWindow(false); mPrefsLocalBtn.SetCheck(0); mPrefsRemoteBtn.SetCheck(1); mLocal = false; } if (CAdminLock::sAdminLock.mNoRemotePrefs) { mPrefsRemoteBtn.EnableWindow(false); mPrefsLocalBtn.SetCheck(1); mPrefsRemoteBtn.SetCheck(0); mLocal = true; } if (mCurrentPrefsFile) { mPrefsLocalBtn.SetCheck(!mCurrentPrefsFile->IsRemote()); mPrefsRemoteBtn.SetCheck(mCurrentPrefsFile->IsRemote()); mLocal = !mCurrentPrefsFile->IsRemote(); } // Set button states mPrefsSaveDefaultBtn.EnableWindow(CAdminLock::sAdminLock.mAllowDefault || (mPrefsRemoteBtn.GetCheck() == 1)); // Disable Save and open buttons button if not allowed if (CAdminLock::sAdminLock.mNoLocalPrefs && CAdminLock::sAdminLock.mNoRemotePrefs) { mPrefsOpenBtn.EnableWindow(false); mPrefsSaveAsBtn.EnableWindow(false); } // Init'd to advanced in constructor - so change here if different if (mCopyPrefs.mSimple.GetValue()) SetSimple(mCopyPrefs.mSimple.GetValue(), true); return result; } // Set title void CPreferencesDialog::SetWindowTitle(void) { // Load string title cdstring title; title.FromResource("UI::Preferences::Title"); // If no current file say no file or default if allowed if (!mCurrentPrefsFile) { cdstring subtitle; subtitle.FromResource(CAdminLock::sAdminLock.mAllowDefault ? "UI::Preferences::DefaultTitle" : "UI::Preferences::NoTitle"); title += subtitle; } // Otherwise just get its name else { // If remote replace name if (mCurrentPrefsFile->IsRemote()) title.FromResource("UI::Preferences::RemoteTitle"); title += mCurrentPrefsFile->GetSpecifier(); } // Now set window title CUnicodeUtils::SetWindowTextUTF8(this, title); } void CPreferencesDialog::OnOK() { // Force active page to update in case of existing changes UpdateCopyPrefs(); // Prefs must be valid before exit if (!mCopyPrefs.Valid(true)) return; // Update current panel name UpdateLastPanel(); // Do default OK action EndDialog(IDOK); } void CPreferencesDialog::UpdateLastPanel() { // Get name of current panel if not simple if (GetPageCount() > 1) { int index = GetActiveIndex(); if (!CPluginManager::sPluginManager.HasSecurity() && (index >= cSecurityIndex - 1)) index++; mCopyPrefs.mLastPanel.SetValue(cPanelNames[index + 1]); CPreferences::sPrefs->mLastPanel.SetValue(cPanelNames[index + 1]); } } void CPreferencesDialog::SetLastPanel() { int panel = 0; if (!mCopyPrefs.mLastPanel.GetValue().empty()) { const char** p = cPanelNames; while(*++p) { if (mCopyPrefs.mLastPanel.GetValue() == *p) break; } if (*p) panel = p - cPanelNames - 1; if (!CPluginManager::sPluginManager.HasSecurity()) { if (panel == cSecurityIndex - 1) panel = 0; else if (panel > cSecurityIndex - 1) panel--; } } SetActivePage(panel); } void CPreferencesDialog::UpdatePrefs() { // Make a copy of the prefs to copy CPreferences* newPrefs = new CPreferences(mCopyPrefs); // Always save existing current file if (mCurrentPrefsFile) { // Save new prefs mCurrentPrefsFile->SetPrefs(newPrefs); mCurrentPrefsFile->SavePrefs(true, false); } // Try to create default prefs file else if (CAdminLock::sAdminLock.mAllowDefault) { // Create new default prefs file mCurrentPrefsFile = new CPreferencesFile(true, false); // Save new prefs mCurrentPrefsFile->SetPrefs(newPrefs); mCurrentPrefsFile->SavePrefs(true, false); } // Try to save in new file else if (!CAdminLock::sAdminLock.mNoLocalPrefs || !CAdminLock::sAdminLock.mNoRemotePrefs) { // Create new file to save as mCurrentPrefsFile = new CPreferencesFile(false, false); if (mLocal ? !PrefsLocalSaveAs() : !PrefsRemoteSaveAs()) { // Free unwanted objects and cancel OK action delete mCurrentPrefsFile; mCurrentPrefsFile = NULL; delete newPrefs; return; } } // If current file is not previous if (mCurrentPrefsFile != CMulberryApp::sCurrentPrefsFile) { // Delete old prefs file delete CMulberryApp::sCurrentPrefsFile; // Make apps current file the new one CMulberryApp::sCurrentPrefsFile = mCurrentPrefsFile; } // Make changes based on prefs - will reset default MakeChanges(newPrefs); // Reset cabinets if required if (mAccountNew && CMailAccountManager::sMailAccountManager) CMailAccountManager::sMailAccountManager->UpdateFavourites(); // Reset windows if required if (mWindowsReset) { // Do each server window { cdmutexprotect<CServerWindow::CServerWindowList>::lock _lock(CServerWindow::sServerWindows); for(CServerWindow::CServerWindowList::iterator iter1 = CServerWindow::sServerWindows->begin(); iter1 != CServerWindow::sServerWindows->end(); iter1++) (*iter1)->ResetState(); } // Do each mailbox window { cdmutexprotect<CMailboxWindow::CMailboxWindowList>::lock _lock(CMailboxWindow::sMboxWindows); for(CMailboxWindow::CMailboxWindowList::iterator iter = CMailboxWindow::sMboxWindows->begin(); iter != CMailboxWindow::sMboxWindows->end(); iter++) (*iter)->ResetState(); } // Do each address book window { cdmutexprotect<CAddressBookWindow::CAddressBookWindowList>::lock _lock(CAddressBookWindow::sAddressBookWindows); for(CAddressBookWindow::CAddressBookWindowList::iterator iter = CAddressBookWindow::sAddressBookWindows->begin(); iter != CAddressBookWindow::sAddressBookWindows->end(); iter++) (*iter)->ResetState(); } // Address book manager window if (CAdbkManagerWindow::sAdbkManager) CAdbkManagerWindow::sAdbkManager->ResetState(); // Address book search window if (CAdbkSearchWindow::sAdbkSearch) CAdbkSearchWindow::sAdbkSearch->ResetState(); // Calendar manager window if (CCalendarStoreWindow::sCalendarStoreManager) CCalendarStoreWindow::sCalendarStoreManager->ResetState(); // Do each calendar window { cdmutexprotect<CCalendarWindow::CCalendarWindowList>::lock _lock(CCalendarWindow::sCalendarWindows); for(CCalendarWindow::CCalendarWindowList::iterator iter = CCalendarWindow::sCalendarWindows->begin(); iter != CCalendarWindow::sCalendarWindows->end(); iter++) (*iter)->ResetState(); } } } void CPreferencesDialog::OnCancel() { // Delete prefs file object if not same as existing if (mCurrentPrefsFile != CMulberryApp::sCurrentPrefsFile) delete mCurrentPrefsFile; mCurrentPrefsFile = NULL; // Do menu list reset if it changed if (mForceMenuListReset) { // Force mailbox menu reset CCopyToMenu::SetMenuOptions(CPreferences::sPrefs->mUseCopyToMboxes.GetValue(), CPreferences::sPrefs->mUseAppendToMboxes.GetValue()); CCopyToMenu::DirtyMenuList(); } // Update last panel now UpdateLastPanel(); // Do default cancel action EndDialog(IDCANCEL); } // Check for and act on change void CPreferencesDialog::MakeChanges(CPreferences* newPrefs) { bool refresh_server = false; bool refresh_mailbox = false; bool refresh_message = false; bool refresh_letter = false; bool refresh_adbkmanager = false; bool refresh_adbksearch = false; bool refresh_addressbook = false; bool refresh_calendar = false; bool refresh_rules = false; bool refresh_mrus = false; // Check for change of style or colour in mailbox window if ((CPreferences::sPrefs->mServerOpenStyle.GetValue() != newPrefs->mServerOpenStyle.GetValue()) || (CPreferences::sPrefs->mServerClosedStyle.GetValue() != newPrefs->mServerClosedStyle.GetValue()) || (CPreferences::sPrefs->mServerBkgndStyle.GetValue() != newPrefs->mServerBkgndStyle.GetValue()) || (CPreferences::sPrefs->mFavouriteBkgndStyle.GetValue() != newPrefs->mFavouriteBkgndStyle.GetValue()) || (CPreferences::sPrefs->mHierarchyBkgndStyle.GetValue() != newPrefs->mHierarchyBkgndStyle.GetValue()) || (CPreferences::sPrefs->mMboxRecentStyle.GetValue() != newPrefs->mMboxRecentStyle.GetValue()) || (CPreferences::sPrefs->mMboxUnseenStyle.GetValue() != newPrefs->mMboxUnseenStyle.GetValue()) || (CPreferences::sPrefs->mMboxOpenStyle.GetValue() != newPrefs->mMboxOpenStyle.GetValue()) || (CPreferences::sPrefs->mMboxFavouriteStyle.GetValue() != newPrefs->mMboxFavouriteStyle.GetValue()) || (CPreferences::sPrefs->mMboxClosedStyle.GetValue() != newPrefs->mMboxClosedStyle.GetValue())) { refresh_server = true; } // Check for change of style or colour if ((CPreferences::sPrefs->unseen.GetValue() != newPrefs->unseen.GetValue()) || (CPreferences::sPrefs->seen.GetValue() != newPrefs->seen.GetValue()) || (CPreferences::sPrefs->answered.GetValue() != newPrefs->answered.GetValue()) || (CPreferences::sPrefs->important.GetValue() != newPrefs->important.GetValue()) || (CPreferences::sPrefs->deleted.GetValue() != newPrefs->deleted.GetValue()) || (CPreferences::sPrefs->mMultiAddress.GetValue() != newPrefs->mMultiAddress.GetValue())) { refresh_mailbox = true; } // Check for change of font or size in list display //if ((CPreferences::sPrefs->mListTextTraits.GetValue().size != mCopyPrefs.mListTextTraits.GetValue().size) || // ::PLstrcmp(CPreferences::sPrefs->mListTextTraits.GetValue().fontName, mCopyPrefs.mListTextTraits.GetValue().fontName) != 0) { // Always force change as Font object must be replaced refresh_server = true; refresh_mailbox = true; refresh_message = true; refresh_letter = true; refresh_adbkmanager = true; refresh_adbksearch = true; refresh_addressbook = true; refresh_calendar = true; refresh_rules = true; //CFontCache::ResetFonts(newPrefs); } // Always change font as object is static in prefs /* // Check for change of font or size LOGFONT info1; LOGFONT info2; CPreferences::sPrefs->mTextFont.GetValue().GetLogFont(&info1); newPrefs->mTextFont.GetLogFont(&info2); if ((info1.lfHeight != info2.lfHeight) || (info1.lfWidth != info2.lfWidth) || (info1.lfEscapement != info2.lfEscapement) || (info1.lfOrientation != info2.lfOrientation) || (info1.lfItalic != info2.lfItalic) || (info1.lfStrikeOut != info2.lfStrikeOut) || (info1.lfCharSet != info2.lfCharSet) || (info1.lfOutPrecision != info2.lfOutPrecision) || (info1.lfClipPrecision != info2.lfClipPrecision) || (info1.lfQuality != info2.lfQuality) || (info1.lfPitchAndFamily != info2.lfPitchAndFamily) || (::strcmp(info1.lfFaceName, info2.lfFaceName) != 0)) */ { refresh_message = true; refresh_letter = true; } // Check for change of smart address filters bool smart_change = (CPreferences::sPrefs->mSmartAddressList.GetValue().size() != newPrefs->mSmartAddressList.GetValue().size()); if (!smart_change) { for(int i = 0; i < CPreferences::sPrefs->mSmartAddressList.GetValue().size(); i++) { if (CPreferences::sPrefs->mSmartAddressList.GetValue()[i] != newPrefs->mSmartAddressList.GetValue()[i]) { smart_change = true; break; } } } // Always resync identities if (true) { // Iterate over all letter windows cdmutexprotect<CLetterWindow::CLetterWindowList>::lock _lock(CLetterWindow::sLetterWindows); for(CLetterWindow::CLetterWindowList::iterator iter = CLetterWindow::sLetterWindows->begin(); iter != CLetterWindow::sLetterWindows->end(); iter++) (*iter)->SyncIdentities(newPrefs->mIdentities.GetValue()); } // Check for change in MRU number if (CMailAccountManager::sMailAccountManager && (CPreferences::sPrefs->mMRUMaximum.GetValue() != newPrefs->mMRUMaximum.GetValue())) refresh_mrus = true; // Replace old prefs with copy of new newPrefs->SetAsDefault(); // Now do window refreshing AFTER setting the default prefs to the new set // as some of the windows will use the default prefs values if (refresh_server) { // Iterate over all server windows cdmutexprotect<CServerView::CServerViewList>::lock _lock(CServerView::sServerViews); for(CServerView::CServerViewList::iterator iter = CServerView::sServerViews->begin(); iter != CServerView::sServerViews->end(); iter++) { (*iter)->ResetFont(CFontCache::GetListFont()); (*iter)->Invalidate(); // Needed to get list items drawn in new colours } } if (refresh_mailbox) { // Iterate over all mailbox windows cdmutexprotect<CMailboxView::CMailboxViewList>::lock _lock(CMailboxView::sMailboxViews); for(CMailboxView::CMailboxViewList::iterator iter = CMailboxView::sMailboxViews->begin(); iter != CMailboxView::sMailboxViews->end(); iter++) (*iter)->ResetFont(CFontCache::GetListFont()); } if (refresh_message) { // NB IMPORTANT: message window and message views are separate right now // Eventually the message window will contain the message view so only the view // will need to be updated // Iterate over all message windows { cdmutexprotect<CMessageWindow::CMessageWindowList>::lock _lock(CMessageWindow::sMsgWindows); for(CMessageWindow::CMessageWindowList::iterator iter = CMessageWindow::sMsgWindows->begin(); iter != CMessageWindow::sMsgWindows->end(); iter++) (*iter)->ResetFont(CFontCache::GetListFont(), CFontCache::GetDisplayFont()); } // Iterate over all message views { cdmutexprotect<CMessageView::CMessageViewList>::lock _lock(CMessageView::sMsgViews); for(CMessageView::CMessageViewList::iterator iter = CMessageView::sMsgViews->begin(); iter != CMessageView::sMsgViews->end(); iter++) (*iter)->ResetFont(CFontCache::GetListFont(), CFontCache::GetDisplayFont()); } } if (refresh_letter) { // Iterate over all letter windows cdmutexprotect<CLetterWindow::CLetterWindowList>::lock _lock(CLetterWindow::sLetterWindows); for(CLetterWindow::CLetterWindowList::iterator iter = CLetterWindow::sLetterWindows->begin(); iter != CLetterWindow::sLetterWindows->end(); iter++) (*iter)->ResetFont(CFontCache::GetListFont(), CFontCache::GetDisplayFont()); } if (refresh_adbkmanager) { // Iterate over all adbk manager windows cdmutexprotect<CAdbkManagerView::CAdbkManagerViewList>::lock _lock(CAdbkManagerView::sAdbkManagerViews); for(CAdbkManagerView::CAdbkManagerViewList::iterator iter = CAdbkManagerView::sAdbkManagerViews->begin(); iter != CAdbkManagerView::sAdbkManagerViews->end(); iter++) (*iter)->ResetFont(CFontCache::GetListFont()); } if (refresh_adbksearch && CAdbkSearchWindow::sAdbkSearch) CAdbkSearchWindow::sAdbkSearch->ResetFont(CFontCache::GetListFont()); if (refresh_addressbook) { // Iterate over all address books cdmutexprotect<CAddressBookView::CAddressBookViewList>::lock _lock(CAddressBookView::sAddressBookViews); for(CAddressBookView::CAddressBookViewList::iterator iter = CAddressBookView::sAddressBookViews->begin(); iter != CAddressBookView::sAddressBookViews->end(); iter++) (*iter)->ResetFont(CFontCache::GetListFont()); } if (refresh_calendar) { // Iterate over all calendar manager windows cdmutexprotect<CCalendarStoreView::CCalendarStoreViewList>::lock _lock1(CCalendarStoreView::sCalendarStoreViews); for(CCalendarStoreView::CCalendarStoreViewList::iterator iter = CCalendarStoreView::sCalendarStoreViews->begin(); iter != CCalendarStoreView::sCalendarStoreViews->end(); iter++) (*iter)->ResetFont(CFontCache::GetListFont()); // Iterate over all calendars cdmutexprotect<CCalendarView::CCalendarViewList>::lock _lock2(CCalendarView::sCalendarViews); for(CCalendarView::CCalendarViewList::iterator iter = CCalendarView::sCalendarViews->begin(); iter != CCalendarView::sCalendarViews->end(); iter++) (*iter)->ResetFont(CFontCache::GetListFont()); } if (refresh_rules && CRulesWindow::sRulesWindow) { // Reset the lists and then the font CRulesWindow::sRulesWindow->ResetTable(); CRulesWindow::sRulesWindow->ResetFont(CFontCache::GetListFont()); } // Check for change in MRU number if (refresh_mrus && CMailAccountManager::sMailAccountManager) CMailAccountManager::sMailAccountManager->CleanMRUHistory(newPrefs->mMRUMaximum.GetValue()); if (smart_change) { // Iterate over all mailbox windows cdmutexprotect<CMailboxView::CMailboxViewList>::lock _lock(CMailboxView::sMailboxViews); for(CMailboxView::CMailboxViewList::iterator iter = CMailboxView::sMailboxViews->begin(); iter != CMailboxView::sMailboxViews->end(); iter++) (*iter)->RefreshSmartAddress(); } } void CPreferencesDialog::OnPrefsSimpleBtn() { // Only if not already if (!mPrefsSimple) SetSimple(true); } void CPreferencesDialog::OnPrefsAdvancedBtn() { // Only if not already if (mPrefsSimple) SetSimple(false); } void CPreferencesDialog::SetSimple(bool simple, bool init) { // Prevent flashing bool locked = (m_hWnd != NULL) ? LockWindowUpdate() : false; if (m_hWnd != NULL) { mPrefsLocalBtn.ShowWindow(simple ? SW_HIDE : SW_SHOW); mPrefsRemoteBtn.ShowWindow(simple ? SW_HIDE : SW_SHOW); mPrefsLocalCaption.ShowWindow(simple && mLocal ? SW_SHOW : SW_HIDE); mPrefsRemoteCaption.ShowWindow(simple && !mLocal ? SW_SHOW : SW_HIDE); } if (simple) { // Update current panel name before doing switch UpdateLastPanel(); // Add simple page AddPage(mPrefsSimple = new CPrefsSimple); if (!init) // Update current preferences from panels UpdateCopyPrefs(); // Now set prefs value mCopyPrefs.mSimple.SetValue(simple); // Force current panels to reset prefs InitPrefs(); // Remove advanced pages if (mPrefsAccounts) RemovePage(mPrefsAccounts); if (mPrefsAlerts) RemovePage(mPrefsAlerts); if (mPrefsDisplay) RemovePage(mPrefsDisplay); if (mPrefsFormatting) RemovePage(mPrefsFormatting); if (mPrefsMailbox) RemovePage(mPrefsMailbox); if (mPrefsMessage) RemovePage(mPrefsMessage); if (mPrefsLetter) RemovePage(mPrefsLetter); if (mPrefsSecurity) RemovePage(mPrefsSecurity); if (mPrefsIdentity) RemovePage(mPrefsIdentity); if (mPrefsAddress) RemovePage(mPrefsAddress); if (mPrefsCalendar) RemovePage(mPrefsCalendar); if (mPrefsAttachments) RemovePage(mPrefsAttachments); if (mPrefsSpelling) RemovePage(mPrefsSpelling); delete mPrefsAccounts; delete mPrefsAlerts; delete mPrefsDisplay; delete mPrefsFormatting; delete mPrefsMailbox; delete mPrefsMessage; delete mPrefsLetter; delete mPrefsSecurity; delete mPrefsIdentity; delete mPrefsAddress; delete mPrefsCalendar; delete mPrefsAttachments; delete mPrefsSpelling; mPrefsAccounts = NULL; mPrefsAlerts = NULL; mPrefsDisplay = NULL; mPrefsFormatting = NULL; mPrefsMailbox = NULL; mPrefsMessage = NULL; mPrefsLetter = NULL; mPrefsSecurity = NULL; mPrefsIdentity = NULL; mPrefsAddress = NULL; mPrefsCalendar = NULL; mPrefsAttachments = NULL; mPrefsSpelling = NULL; } else { // Add advanced pages AddPage(mPrefsAccounts = new CPrefsAccounts); AddPage(mPrefsAlerts = new CPrefsAlerts); AddPage(mPrefsDisplay = new CPrefsDisplay); AddPage(mPrefsFormatting = new CPrefsFormatting); AddPage(mPrefsMailbox = new CPrefsMailbox); AddPage(mPrefsMessage = new CPrefsMessage); AddPage(mPrefsLetter = new CPrefsLetter); if (CPluginManager::sPluginManager.HasSecurity()) AddPage(mPrefsSecurity = new CPrefsSecurity); AddPage(mPrefsIdentity = new CPrefsIdentity); AddPage(mPrefsAddress = new CPrefsAddress); // Remove unwanted prefs panels by hiding buttons if (!CAdminLock::sAdminLock.mPreventCalendars) AddPage(mPrefsCalendar = new CPrefsCalendar); AddPage(mPrefsAttachments = new CPrefsAttachments); if (CPluginManager::sPluginManager.HasSpelling()) AddPage(mPrefsSpelling = new CPrefsSpelling); if (!init) // Update current preferences from panels UpdateCopyPrefs(); // Now set prefs value mCopyPrefs.mSimple.SetValue(simple); // Force current panels to reset prefs InitPrefs(); // Remove simple page if (mPrefsSimple) RemovePage(mPrefsSimple); delete mPrefsSimple; mPrefsSimple = NULL; // Set to last used page SetLastPanel(); } if (locked) { UnlockWindowUpdate(); RedrawWindow(NULL, NULL, RDW_INVALIDATE); } } #pragma mark ____________________________Storage Related void CPreferencesDialog::OnPrefsLocalBtn() { // Only if not local if (!mLocal) { mLocal = true; mPrefsSaveDefaultBtn.EnableWindow(CAdminLock::sAdminLock.mAllowDefault); // Change state of prefs file if (mCurrentPrefsFile) mCurrentPrefsFile->SetRemote(false); } } void CPreferencesDialog::OnPrefsRemoteBtn() { // Only if not already if (!mLocal) return; // Force active page to update in case of existing changes UpdateCopyPrefs(); if (!CAdminLock::sAdminLock.mAllowDefault) mPrefsSaveDefaultBtn.EnableWindow(true); // Must have valid remote IP if (!mCopyPrefs.mRemoteAccounts.GetValue().size()) { CErrorHandler::PutStopAlertRsrc("Alerts::Preferences::NoRemoteAccount"); // Reset buttons mPrefsLocalBtn.SetCheck(true); mPrefsRemoteBtn.SetCheck(false); // Force to remote panel SetActivePage(0); } else if (mCopyPrefs.mRemoteAccounts.GetValue().front()->GetServerIP().empty()) { const cdstring& name = mCopyPrefs.mRemoteAccounts.GetValue().front()->GetName(); CErrorHandler::PutStopAlertRsrcStr("Alerts::Preferences::Invalid_RemoteServerIP", name); // Reset buttons mPrefsLocalBtn.SetCheck(true); mPrefsRemoteBtn.SetCheck(false); // Force to account panel SetActivePage(0); } else if (!CMulberryApp::sApp->BeginRemote(&mCopyPrefs)) { mPrefsLocalBtn.SetCheck(true); mPrefsRemoteBtn.SetCheck(false); if (!CAdminLock::sAdminLock.mAllowDefault) mPrefsSaveDefaultBtn.EnableWindow(false); } else { // Do logoff to kill connection CMulberryApp::sOptionsProtocol->Logoff(); mLocal = false; mPrefsSaveDefaultBtn.EnableWindow(true); } // Change state of prefs file if (mCurrentPrefsFile && !mLocal) mCurrentPrefsFile->SetRemote(true); } void CPreferencesDialog::OnPrefsOpenBtn() { bool opened = false; if (mLocal) opened = PrefsLocalOpen(); else opened = PrefsRemoteOpen(); // Must force reset of mailbox menu lists and cabinet contents if (opened) { // Indicate new prefs SetLoadedNewPrefs(true); // Reset prefs changed flags SetAccountNew(false); SetAccountRename(false); GetRenames().clear(); SetForceWindowReset(false); // Mark popups as dirty for new prefs set CCopyToMenu::DirtyMenuList(); SetForceMenuListReset(true); } } void CPreferencesDialog::OnPrefsSaveAsBtn() { // Force active page to update in case of existing changes UpdateCopyPrefs(); // Allow save of invalid prefs if (mLocal) PrefsLocalSaveAs(); else PrefsRemoteSaveAs(); } void CPreferencesDialog::OnPrefsSaveDefaultBtn() { // Force active page to update in case of existing changes UpdateCopyPrefs(); // Prefs must be valid before save if (!mCopyPrefs.Valid(true)) return; if (mLocal) PrefsLocalSaveDefault(); else PrefsRemoteSaveDefault(); } bool CPreferencesDialog::PrefsLocalOpen() { // Do standard open dialog // prompt the user (with all document templates) CString filter = _T("Preferences File (*.mbp)"); filter += '|'; filter += '*'; filter += cPrefFileExtension; filter += "||"; CFileDialog dlgFile(true, NULL, NULL, OFN_HIDEREADONLY | OFN_FILEMUSTEXIST, filter, CSDIFrame::GetAppTopWindow()); // Check for good reply if (dlgFile.DoModal() == IDOK) { // Save copy of existing preferences CPreferences temp(mCopyPrefs); // Create file object CPreferencesFile* new_file = new CPreferencesFile(false, false); // Set prefs file to new file and copy prefs new_file->SetSpecifier(cdstring(dlgFile.GetPathName())); new_file->SetSpecified(true); new_file->SetPrefs(&mCopyPrefs); // Read in new prefs (open as local do not resolve to remote) if (new_file->VerifyRead(false)) { // Delete prefs file object if not same as existing if (mCurrentPrefsFile != CMulberryApp::sCurrentPrefsFile) delete mCurrentPrefsFile; mCurrentPrefsFile = new_file; // Need to sync new prefs simple/advanced state with old mCopyPrefs.mSimple.SetValue(temp.mSimple.GetValue()); // Set new prefs values in all panels ResetPrefs(); GetActivePage()->UpdateData(false); // Reset title SetWindowTitle(); } else { delete new_file; // Restore existing prefs mCopyPrefs = temp; return false; } return true; } return false; } bool CPreferencesDialog::PrefsLocalSaveAs() { CString saveAsName; // Use current file if any if (mCurrentPrefsFile) saveAsName = mCurrentPrefsFile->GetSpecifier(); else { // Set default name cdstring temp; temp.FromResource("UI::Preferences::DefaultTitle"); saveAsName = temp; } // Do standard save as dialog // prompt the user (with all document templates) cdstring filter = "Preferences File (*.mbp)"; filter += '|'; filter += '*'; filter += cPrefFileExtension; filter += "||"; CFileDialog dlgFile(false, cdstring(cPrefFileExtension).win_str(), saveAsName, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, filter.win_str(), CSDIFrame::GetAppTopWindow()); // Check for good reply if (dlgFile.DoModal() == IDOK) { // Reset prefs file object if same as existing if (mCurrentPrefsFile == CMulberryApp::sCurrentPrefsFile) mCurrentPrefsFile = NULL; // Create file object if required if (!mCurrentPrefsFile) mCurrentPrefsFile = new CPreferencesFile(false, false); // Save current prefs in file mCurrentPrefsFile->SetRemote(false); mCurrentPrefsFile->SetPrefs(&mCopyPrefs); mCurrentPrefsFile->DoSaveAs(dlgFile.GetPathName()); mCurrentPrefsFile->SetSpecified(true); // Reset window title SetWindowTitle(); return true; } else return false; } void CPreferencesDialog::PrefsLocalSaveDefault() { // Force active page to update in case of existing changes UpdateCopyPrefs(); // Prefs must be valid before save if (!mCopyPrefs.Valid(true)) return; // Create new System Folder prefs file CPreferencesFile* temp = new CPreferencesFile(true, false); // Save current prefs in System Folder temp->SetPrefs(&mCopyPrefs); temp->SavePrefs(false, true); // Finished with file delete temp; } bool CPreferencesDialog::PrefsRemoteOpen() { // Make sure set is read in // Must be logged in to server if (CMulberryApp::sApp->BeginRemote(&mCopyPrefs)) { CMulberryApp::sRemotePrefs->ListRemoteSets(); // Do logoff to kill connection CMulberryApp::sOptionsProtocol->Logoff(); } else return false; // Create the dialog CTextListChoice dlog(CSDIFrame::GetAppTopWindow()); dlog.mSingleSelection = true; dlog.mSelectFirst = true; dlog.mButtonTitle = "Open"; dlog.mTextListDescription = "Remote Preferences:"; // Add default name first dlog.mItems.push_back(cDefaultPrefsSetKey_2_0); // Add the rest for(cdstrvect::const_iterator iter = CMulberryApp::sRemotePrefs->GetRemoteSets().begin(); iter != CMulberryApp::sRemotePrefs->GetRemoteSets().end(); iter++) dlog.mItems.push_back(*iter); // Let Dialog process events if (dlog.DoModal() == IDOK) { // Get selection from list cdstring remote = cDefaultPrefsSetKey_2_0; if (dlog.mSelection.front()) remote = CMulberryApp::sRemotePrefs->GetRemoteSets().at(dlog.mSelection.front() - 1); // Save copy of existing preferences CPreferences temp(mCopyPrefs); // Create file object CPreferencesFile* new_file = new CPreferencesFile(false, true); // Set prefs file to new file and copy prefs new_file->SetSpecifier(remote); new_file->SetSpecified(false); new_file->SetPrefs(&mCopyPrefs); // Read in new prefs if (new_file->VerifyRead(false)) { // Delete prefs file object if not same as existing if (mCurrentPrefsFile != CMulberryApp::sCurrentPrefsFile) delete mCurrentPrefsFile; mCurrentPrefsFile = new_file; // Need to sync new prefs simple/advanced state with old mCopyPrefs.mSimple.SetValue(temp.mSimple.GetValue()); // Set new prefs values in all panels ResetPrefs(); GetActivePage()->UpdateData(false); // Reset title SetWindowTitle(); } else { delete new_file; // Restore existing prefs mCopyPrefs = temp; return false; } return true; } return false; } bool CPreferencesDialog::PrefsRemoteSaveAs() { cdstring saveAsName; // Use current file if any if (mCurrentPrefsFile) { // If remote replace name saveAsName = mCurrentPrefsFile->GetSpecifier(); if (!mCurrentPrefsFile->IsRemote()) { cdstring temp; const char* p = ::strrchr(saveAsName.c_str(), '\\'); if (p) temp = ++p; else temp = saveAsName; p = ::strrchr(temp.c_str(), '.'); if (p) *const_cast<char*>(p) = 0; saveAsName = temp; } } // Make sure set is read in // Must be logged in to server if (CMulberryApp::sApp->BeginRemote(&mCopyPrefs)) { CMulberryApp::sRemotePrefs->ListRemoteSets(); // Do logoff to kill connection CMulberryApp::sOptionsProtocol->Logoff(); } else return false; // Create the dialog CTextListChoice dlog(CSDIFrame::GetAppTopWindow()); dlog.mSingleSelection = true; dlog.mUseEntry = true; dlog.mButtonTitle = "Save As..."; dlog.mTextListDescription = "Remote Preferences:"; dlog.mTextListEnter = saveAsName; dlog.mTextListEnterDescription = "Save Preferences As:"; // Add default name first dlog.mItems.push_back(cDefaultPrefsSetKey_2_0); // Add the rest for(cdstrvect::const_iterator iter = CMulberryApp::sRemotePrefs->GetRemoteSets().begin(); iter != CMulberryApp::sRemotePrefs->GetRemoteSets().end(); iter++) dlog.mItems.push_back(*iter); // Let Dialog process events while(true) { if (dlog.DoModal() == IDOK) { // Get selection from list saveAsName = dlog.mTextListEnter; // Check for duplicate cdstring duplicate; if (CMulberryApp::sRemotePrefs->IsDuplicateName(saveAsName, duplicate)) { // Warn replace if (CErrorHandler::PutCautionAlertRsrcStr(true, "Alerts::Preferences::DuplicateSaveAsSet", duplicate) == CErrorHandler::Cancel) // Stop dialog OK continue; } // Login here so that all operations take place on a single connection StProtocolLogin login(CMulberryApp::sOptionsProtocol); // Delete any duplicate set first if (!duplicate.empty()) CMulberryApp::sRemotePrefs->DeleteSet(duplicate); // Reset prefs file object if same as existing if (mCurrentPrefsFile == CMulberryApp::sCurrentPrefsFile) mCurrentPrefsFile = NULL; // Create file object if required if (!mCurrentPrefsFile) mCurrentPrefsFile = new CPreferencesFile(false, true); // Save current prefs in file mCurrentPrefsFile->SetRemote(true); mCurrentPrefsFile->SetSpecifier(saveAsName); mCurrentPrefsFile->SetSpecified(false); mCurrentPrefsFile->SetPrefs(&mCopyPrefs); mCurrentPrefsFile->SavePrefs(false, true); // Add to sets CMulberryApp::sRemotePrefs->GetRemoteSets().push_back(saveAsName); CMulberryApp::sRemotePrefs->UpdateRemoteSets(); // Reset window title SetWindowTitle(); return true; } else return false; } } void CPreferencesDialog::PrefsRemoteSaveDefault() { // Delete existing set first if required if (::GetKeyState(VK_MENU) < 0) { // Must be logged in to server if (CMulberryApp::sApp->BeginRemote(GetCopyPrefs())) { // Delete default set cdstring set = cDefaultPrefsSetKey_2_0; CMulberryApp::sRemotePrefs->DeleteSet(set); // Do logoff to kill connection CMulberryApp::sOptionsProtocol->Logoff(); } } // Create new default remote prefs file CPreferencesFile* temp = new CPreferencesFile(true, true); temp->CreateDefault(); // Save current prefs as default remote temp->SetPrefs(&mCopyPrefs); temp->SavePrefs(false, true); // Finished with file delete temp; }
[ "svnusers@a91246af-f21b-0410-bd1c-c3c7fc455132" ]
svnusers@a91246af-f21b-0410-bd1c-c3c7fc455132
e3ed932c7623fc6b749ea994630bafa3623c5997
2a7e77565c33e6b5d92ce6702b4a5fd96f80d7d0
/fuzzedpackages/PReMiuM/src/include/PReMiuMModel.h
99d7c61fa5e0aed206a4e733fff65c5dd8ef16bf
[]
no_license
akhikolla/testpackages
62ccaeed866e2194652b65e7360987b3b20df7e7
01259c3543febc89955ea5b79f3a08d3afe57e95
refs/heads/master
2023-02-18T03:50:28.288006
2021-01-18T13:23:32
2021-01-18T13:23:32
329,981,898
7
1
null
null
null
null
UTF-8
C++
false
false
126,437
h
/// \file PReMiuMModel.h /// \author David Hastie /// \brief Header file for model specification for PReMiuMpp /// \note (C) Copyright David Hastie and Silvia Liverani, 2012. /// PReMiuM++ is free software; you can redistribute it and/or modify it under the /// terms of the GNU Lesser General Public License as published by the Free Software /// Foundation; either version 3 of the License, or (at your option) any later /// version. /// PReMiuM++ 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 PReMiuM++ in the documentation directory. If not, see /// <http://www.gnu.org/licenses/>. /// The external linear algebra library Eigen, parts of which are included in the /// lib directory is released under the LGPL3+ licence. See comments in file headers /// for details. /// The Boost C++ header library, parts of which are included in the lib directory /// is released under the Boost Software Licence, Version 1.0, a copy of which is /// included in the documentation directory. #ifndef DIPBACMODEL_H_ #define DIPBACMODEL_H_ // Standard includes #include<cmath> #include<vector> #include<iostream> #include<fstream> #include<string> #include<numeric> #include<limits> #include<map> #include<boost/math/distributions/normal.hpp> #include<boost/math/distributions/gamma.hpp> #include<boost/math/distributions/beta.hpp> #include<boost/math/distributions/students_t.hpp> #include<boost/math/special_functions/gamma.hpp> #include<Eigen/Core> #include<Eigen/Cholesky> #include<Eigen/LU> // Custom includes #include<MCMC/model.h> #include<MCMC/state.h> #include<Math/random.h> #include<Math/distribution.h> #include<Math/mathfunctions.h> #include<PReMiuMData.h> #include<PReMiuMOptions.h> using std::vector; using std::ifstream; using std::ofstream; using std::string; using std::accumulate; using std::numeric_limits; using namespace Eigen; using boost::math::normal_distribution; using boost::math::gamma_distribution; using boost::math::beta_distribution; using boost::math::students_t_distribution; using boost::math::lgamma; class pReMiuMHyperParams{ public: // Default constructor pReMiuMHyperParams() {}; // Default virtual destructor ~pReMiuMHyperParams() {}; // Set sizes void setSizes(const unsigned int& nCovariates, const unsigned int& nDiscreteCov, const unsigned int& nContinuousCov, const string covariateType, const bool useIndependentNormal, const bool useHyperpriorR1, const bool useSeparationPrior){ if (covariateType.compare("Discrete")==0){ _aPhi.resize(nCovariates); } else if (covariateType.compare("Normal")==0){ _mu0.setZero(nCovariates); if (useIndependentNormal) { _Tau0_Indep.setZero(nCovariates); _R0_Indep.setZero(nCovariates); } else { _Tau0.setZero(nCovariates, nCovariates); _workSqrtTau0.setZero(nCovariates, nCovariates); _R0.setZero(nCovariates, nCovariates); _workInverseR0.setZero(nCovariates, nCovariates); } if (useSeparationPrior) { _beta_taus0.setZero(nCovariates); _Tau00.setZero(nCovariates, nCovariates); _workSqrtTau00.setZero(nCovariates, nCovariates); } if (useHyperpriorR1) { _R00.setZero(nCovariates, nCovariates); _workInverseR00.setZero(nCovariates, nCovariates); } } else if (covariateType.compare("Mixed")==0 ){ _aPhi.resize(nDiscreteCov); _mu0.setZero(nContinuousCov); if (useIndependentNormal) { _R0_Indep.setZero(nContinuousCov); _Tau0_Indep.setZero(nContinuousCov); } else { _Tau0.setZero(nContinuousCov, nContinuousCov); _workSqrtTau0.setZero(nContinuousCov, nContinuousCov); _R0.setZero(nContinuousCov, nContinuousCov); _workInverseR0.setZero(nContinuousCov, nContinuousCov); } if (useSeparationPrior) { _beta_taus0.setZero(nContinuousCov); _Tau00.setZero(nContinuousCov, nContinuousCov); _workSqrtTau00.setZero(nContinuousCov, nContinuousCov); } if (useHyperpriorR1) { _R00.setZero(nContinuousCov, nContinuousCov); _workInverseR00.setZero(nContinuousCov, nContinuousCov); } } } // Set defaults void setDefaults(const pReMiuMData& dataset, const pReMiuMOptions& options){ unsigned int nSubjects = dataset.nSubjects(); //unsigned int nCov = dataset.nCovariates(); //unsigned int nDiscreteCov = dataset.nDiscreteCovs(); //unsigned int nContinuousCov = dataset.nContinuousCovs(); // For alpha _shapeAlpha=2.0; _rateAlpha=1.0; if(options.covariateType().compare("Discrete")==0 || options.covariateType().compare("Mixed")==0 ){ // For Phi for(unsigned int j=0;j<_aPhi.size();j++){ _aPhi[j]=1.0; } } if(options.covariateType().compare("Normal")==0 || options.covariateType().compare("Mixed")==0 ){ unsigned int nContCovs=_mu0.size(); // Values for mu, Tau0, R0, kappa0, kappa1 // In the following it is useful to have the rows of X as // Eigen vectors vector<VectorXd> xi(nSubjects); for(unsigned int i=0;i<nSubjects;i++){ xi[i].setZero(nContCovs); for(unsigned int j=0;j<nContCovs;j++){ xi[i](j)=dataset.continuousX(i,j); } } // First compute the hyper prior parameters // First compute the hyper parameter for mu_c VectorXd mu0=VectorXd::Zero(nContCovs); VectorXd Tau0_Indep= VectorXd::Zero(nContCovs); VectorXd R0_Indep = VectorXd::Zero(nContCovs); VectorXd beta_taus0 = VectorXd::Zero(nContCovs); MatrixXd Sigma0=MatrixXd::Zero(nContCovs,nContCovs); for(unsigned int j=0;j<nContCovs;j++){ double meanX=0.0; double minX=0; double maxX=0; for(unsigned int i=0;i<nSubjects;i++){ double tmpX = xi[i](j); meanX+= tmpX; if(tmpX<minX||i==0){ minX=tmpX; } if(tmpX>maxX||i==0){ maxX=tmpX; } } meanX/=(double)(nSubjects-1); double rangeX = maxX-minX; mu0(j)=meanX; Sigma0(j,j)=rangeX*rangeX; Tau0_Indep(j) = 1.0 / (rangeX*rangeX); R0_Indep(j) = 10.0 / (rangeX*rangeX); beta_taus0(j) = sqrt(10.0) / (rangeX); } if (options.useIndependentNormal()) { _Tau0_Indep = Tau0_Indep; _R0_Indep = R0_Indep; } else { MatrixXd Tau0 = Sigma0.inverse(); _Tau0 = Tau0; LLT<MatrixXd> llt; _workSqrtTau0 = (llt.compute(Tau0)).matrixU(); _workLogDetTau0 = log(Tau0.determinant()); } if (options.useSeparationPrior()) { _beta_taus0 = beta_taus0; _alpha_taus = 2; _alpha_taus0 = 0.2; } if (options.useHyperpriorR1()) { MatrixXd R00 = Sigma0.inverse(); R00 = R00/(double) (nContCovs+2) ; _R00 = R00; _workInverseR00 = R00.inverse(); _workLogDetR00 = log(R00.determinant()); } if (options.useSeparationPrior()) { MatrixXd Tau00 = Sigma0.inverse(); _Tau00 = Tau00; LLT<MatrixXd> llt; _workSqrtTau00 = (llt.compute(Tau00)).matrixU(); _workLogDetTau00 = log(Tau00.determinant()); } _mu0=mu0; // Now we compute the hyper parameters for Tau_c // First we compute the sample covariance MatrixXd R = MatrixXd::Zero(nContCovs, nContCovs); if (options.useHyperpriorR1()|| options.useSeparationPrior()) { for (unsigned int j = 0; j<nContCovs; j++) { R(j, j) = 1; } } else { for (unsigned int i = 0; i<nSubjects; i++) { R += (xi[i] - mu0)*((xi[i] - mu0).transpose()); } R /= (double)nSubjects; R *= (double)nContCovs; } _workInverseR0 = R; R = R.inverse(); _R0 = R; _workLogDetR0 = log(R.determinant()); if (options.useHyperpriorR1()||options.useSeparationPrior()) { //For kappa1 _shapeKappa1 = 0.5; _scaleKappa1 = nContCovs / 2; } if (options.useIndependentNormal()) { _kappa0 = 0.2; _kappa1 = 2; } else { _kappa0 = nContCovs+2; } if (options.useHyperpriorR1()) { _kappa00 = nContCovs + 2; } _nu0=0.01; } _muTheta = 0.0; _sigmaTheta = 2.5; _dofTheta = 7; _muBeta = 0.0; _sigmaBeta = 2.5; _dofBeta = 7; _shapeTauEpsilon = 5.0; _rateTauEpsilon = 0.5; _aRho = 0.5; _bRho = 0.5; _atomRho= 0.5; _shapeSigmaSqY = 2.5; _scaleSigmaSqY = 2.5; _pQuantile = 0.5; _rSlice =0.75; _truncationEps = 0.000001; _shapeTauCAR=0.001; _rateTauCAR=0.001; _shapeNu = 2.5; _scaleNu = 1; } double shapeAlpha() const{ return _shapeAlpha; } void shapeAlpha(const double& s){ _shapeAlpha = s; } double rateAlpha() const{ return _rateAlpha; } void rateAlpha(const double& r){ _rateAlpha = r; } double shapeKappa1() const { return _shapeKappa1; } void shapeKappa1(const double& s) { _shapeKappa1 = s; } double scaleKappa1() const { return _scaleKappa1; } void scaleKappa1(const double& r) { _scaleKappa1 = r; } vector<double> aPhi() const{ return _aPhi; } void aPhi(const vector<double>& a){ _aPhi = a; } double aPhi(const unsigned int& j) const{ return _aPhi[j]; } /// \brief Return the hyper parameter Tau0Mu0 const VectorXd& mu0() const{ return _mu0; } /// \brief Set the hyper parameter Tau0Mu0 void mu0(const VectorXd& m0){ _mu0 = m0; } /// \brief Return the hyper parameter Tau0 const MatrixXd& Tau0() const{ return _Tau0; } /// \brief Set the hyper parameter Tau0 void Tau0(const MatrixXd& T0) { _Tau0 = T0; _workLogDetTau0 = log(T0.determinant()); LLT<MatrixXd> llt; _workSqrtTau0=(llt.compute(T0)).matrixU(); } // \brief Return the hyper parameter Tau00 const MatrixXd& Tau00() const { return _Tau00; } /// \brief Set the hyper parameter Tau00 void Tau00(const MatrixXd& T0) { _Tau00 = T0; _workLogDetTau00 = log(T0.determinant()); LLT<MatrixXd> llt; _workSqrtTau00 = (llt.compute(T0)).matrixU(); } /// \brief Return the hyper parameter Tau0_Indep const VectorXd& Tau0_Indep() const { return _Tau0_Indep; } /// \brief Set the hyper parameter Tau0_Indep void Tau0_Indep(const VectorXd& T0) { _Tau0_Indep = T0; } /// \brief Return the hyper parameter R0 const MatrixXd& R0() const{ return _R0; } /// \brief Set the hyper parameter R0 void R0(const MatrixXd& R) { _R0 = R; _workLogDetR0 = log(R.determinant()); _workInverseR0 = R.inverse(); } /// \brief Return the hyper parameter R00 const MatrixXd& R00() const { return _R00; } /// \brief Set the hyper parameter R00 void R00(const MatrixXd& R) { _R00 = R; _workLogDetR00 = log(R.determinant()); _workInverseR00 = R.inverse(); } /// \brief Return the hyper parameter R0_Indep const VectorXd& R0_Indep() const { return _R0_Indep; } /// \brief Set the hyper parameter R0_Indep void R0_Indep(const VectorXd& R) { _R0_Indep= R; } //when the separation prior is used const VectorXd& beta_taus0() const { return _beta_taus0; } //when the separation prior is used void beta_taus0(const VectorXd& beta) { _beta_taus0 = beta; } /// \brief Return the hyper parameter kappa0 const double& kappa0() const{ return _kappa0; } /// \brief Set the hyper parameter kappa0 void kappa0(const double& k0){ _kappa0 = k0; } /// \brief Return the hyper parameter kappa00 const double& kappa00() const { return _kappa00; } /// \brief Set the hyper parameter kappa00 void kappa00(const double& k0) { _kappa00 = k0; } /// \brief Return the hyper parameter kappa1 const double& kappa1() const{ return _kappa1; } /// \brief Set the hyper parameter kappa1 void kappa1(const double& k0){ _kappa1 = k0; } /// when the separation prior is used const double& alpha_taus0() const { return _alpha_taus0; } /// when the separation prior is used void alpha_taus0(const double& alpha) { _alpha_taus0 = alpha; } /// when the separation prior is used const double& alpha_taus() const { return _alpha_taus; } /// when the separation prior is used void alpha_taus(const double& alpha) { _alpha_taus = alpha; } /// \brief Return the hyper parameter nu0 const double& nu0() const{ return _nu0; } /// \brief Set the hyper parameter nu0 void nu0(const double& n0){ _nu0 = n0; } double muTheta() const{ return _muTheta; } void muTheta(const double& mu){ _muTheta = mu; } double sigmaTheta() const{ return _sigmaTheta; } void sigmaTheta(const double& sigma){ _sigmaTheta = sigma; } unsigned int dofTheta() const{ return _dofTheta; } void dofTheta(const unsigned int& dof){ _dofTheta = dof; } double muBeta() const{ return _muBeta; } void muBeta(const double& mu){ _muBeta = mu; } double sigmaBeta() const{ return _sigmaBeta; } void sigmaBeta(const double& sigma){ _sigmaBeta = sigma; } unsigned int dofBeta() const{ return _dofBeta; } void dofBeta(const unsigned int& dof){ _dofBeta = dof; } double shapeTauEpsilon() const{ return _shapeTauEpsilon; } void shapeTauEpsilon(const double& a){ _shapeTauEpsilon = a; } double rateTauEpsilon() const{ return _rateTauEpsilon; } void rateTauEpsilon(const double& b){ _rateTauEpsilon = b; } double aRho() const{ return _aRho; } void aRho(const double& a){ _aRho = a; } double bRho() const{ return _bRho; } void bRho(const double& b){ _bRho = b; } double atomRho() const{ return _atomRho; } void atomRho(const double& atom){ _atomRho = atom; } double shapeSigmaSqY() const{ return _shapeSigmaSqY; } void shapeSigmaSqY(const double& s){ _shapeSigmaSqY = s; } double scaleSigmaSqY() const{ return _scaleSigmaSqY; } void scaleSigmaSqY(const double& r){ _scaleSigmaSqY = r; } double pQuantile() const{ return _pQuantile; } void pQuantile(const double& p){ _pQuantile = p; } double shapeNu() const{ return _shapeNu; } void shapeNu(const double& s){ _shapeNu = s; } double scaleNu() const{ return _scaleNu; } void scaleNu(const double& r){ _scaleNu = r; } double rSlice() const{ return _rSlice; } void rSlice(const double& rSl){ _rSlice=rSl; } double truncationEps() const{ return _truncationEps; } void truncationEps(const double& eps){ _truncationEps=eps; } const MatrixXd& workSqrtTau0() const{ return _workSqrtTau0; } double workLogDetTau0() const{ return _workLogDetTau0; } const MatrixXd& workSqrtTau00() const { return _workSqrtTau00; } double workLogDetTau00() const { return _workLogDetTau00; } const MatrixXd& workInverseR0() const{ return _workInverseR0; } double workLogDetR0() const{ return _workLogDetR0; } const MatrixXd& workInverseR00() const { return _workInverseR00; } double workLogDetR00() const { return _workLogDetR00; } double workXiSlice(unsigned int c) const{ return (1-_rSlice)*pow(_rSlice,(double)c); } double shapeTauCAR() const{ return _shapeTauCAR; } void shapeTauCAR(const double& a){ _shapeTauCAR = a; } double rateTauCAR() const{ return _rateTauCAR; } void rateTauCAR(const double& b){ _rateTauCAR = b; } vector<double> initAlloc() const{ return _initAlloc; } void initAlloc(const vector<double>& c){ _initAlloc = c; } double initAlloc(const unsigned int& j) const{ return _initAlloc[j]; } // Copy operator pReMiuMHyperParams& operator=(const pReMiuMHyperParams& hyperParams){ _shapeAlpha = hyperParams.shapeAlpha(); _rateAlpha = hyperParams.rateAlpha(); _shapeKappa1 = hyperParams.shapeKappa1(); _scaleKappa1 = hyperParams.scaleKappa1(); _aPhi = hyperParams.aPhi(); _mu0 = hyperParams.mu0(); _Tau0 = hyperParams.Tau0(); _Tau00 = hyperParams.Tau00(); _Tau0_Indep = hyperParams.Tau0_Indep(); _R0 = hyperParams.R0(); _R00 = hyperParams.R00(); _R0_Indep = hyperParams.R0_Indep(); _kappa0 = hyperParams.kappa0(); _alpha_taus0 = hyperParams.alpha_taus0(); _alpha_taus = hyperParams.alpha_taus(); _beta_taus0 = hyperParams.beta_taus0(); _kappa00 = hyperParams.kappa00(); _kappa1 = hyperParams.kappa1(); _nu0 = hyperParams.nu0(); _muTheta = hyperParams.muTheta(); _sigmaTheta = hyperParams.sigmaTheta(); _dofTheta = hyperParams.dofTheta(); _muBeta = hyperParams.muBeta(); _sigmaBeta = hyperParams.sigmaBeta(); _dofBeta = hyperParams.dofBeta(); _shapeTauEpsilon = hyperParams.shapeTauEpsilon(); _rateTauEpsilon = hyperParams.rateTauEpsilon(); _aRho = hyperParams.aRho(); _bRho = hyperParams.bRho(); _atomRho = hyperParams.atomRho(); _shapeSigmaSqY = hyperParams.shapeSigmaSqY(); _scaleSigmaSqY = hyperParams.scaleSigmaSqY(); _pQuantile = hyperParams.pQuantile(); _shapeNu = hyperParams.shapeNu(); _scaleNu = hyperParams.scaleNu(); _workSqrtTau0 = hyperParams.workSqrtTau0(); _workLogDetTau0 = hyperParams.workLogDetTau0(); _workSqrtTau00 = hyperParams.workSqrtTau00(); _workLogDetTau00 = hyperParams.workLogDetTau00(); _workInverseR0 = hyperParams.workInverseR0(); _workLogDetR0 = hyperParams.workLogDetR0(); _workInverseR00 = hyperParams.workInverseR00(); _workLogDetR00 = hyperParams.workLogDetR00(); _rSlice = hyperParams.rSlice(); _truncationEps = hyperParams.truncationEps(); _shapeTauCAR = hyperParams.shapeTauCAR(); _rateTauCAR = hyperParams.rateTauCAR(); _initAlloc = hyperParams.initAlloc(); return *this; } private: // Hyper parameters for prior for alpha // prior is alpha ~ Gamma(shape,rate) double _shapeAlpha; double _rateAlpha; // Hyper parameters for prior for kappa1 // prior is kappa1 ~ InvGamma(shapeKappa1,scaleKappa1) double _shapeKappa1; double _scaleKappa1; // Hyper parameters for prior for Phi_j (discrete categorical covariates) // Prior is Phi_j ~ Dirichlet(a,a,...,a) vector<double> _aPhi; // Hyper parameters for prior for mu (for Normal covariates) // Prior is mu ~ N(mu0,inv(Tau0)) or Prior is mu ~ N(mu0,inv(Tau)/nu0) if the Normal inverse Wishart prior is chosen VectorXd _mu0; MatrixXd _Tau0; MatrixXd _Tau00; // Prior is mu_cj ~ N(mu0_j,inv(Tau0_Indep_j)) when the Independent Normal likelihood is used VectorXd _Tau0_Indep; double _nu0; // When useHyperpriorR1=FALSE, //hyper parameters for prior of Tau (for Normal covariates) // Prior is Tau ~ Wishart(R0,kappa0) (which has mean R0*kappa0). // When useHyperpriorR1=TRUE, //hyper parameters for prior for R1 (for Normal covariates) // Prior is Tau ~ Wishart(R1,kappa1) // Prior is R1 ~ Wishart(R0,kappa0) MatrixXd _R0; MatrixXd _R00; double _kappa0; double _kappa00; double _kappa1; //Prior is Tau_cj ~ Wishart(R1_Indep_j,kappa1) // Prior is R1_Indep_j ~ Wishart(R0_Indep_j,kappa0) VectorXd _R0_Indep; /// when separation prior is used VectorXd _beta_taus0; double _alpha_taus0; double _alpha_taus; // Hyper parameters for prior for theta // Prior is location and scale T distribution theta ~ t(mu,sigma,dof) // http://www.mathworks.com/help/toolbox/stats/brn2ivz-145.html double _muTheta; double _sigmaTheta; unsigned int _dofTheta; // Hyper parameters for prior for beta (for fixed effects) // Prior is location and scale T distribution theta ~ t(mu,sigma,dof) // http://www.mathworks.com/help/toolbox/stats/brn2ivz-145.html double _muBeta; double _sigmaBeta; unsigned int _dofBeta; // Hyper parameters for prior for tauEpsilon (for extra variation) // Prior is tauEpsilon ~ Gamma(shape,rate) // we use the inverse scale parameterisation so that E[tauEpsilon] = shape/rate double _shapeTauEpsilon; double _rateTauEpsilon; // Hyper parameters for prior for tauEpsilon (for variable selection) // Prior is rho ~ Beta(a,b) with a sparsity inducing atom Bernoulli(atomRho) double _aRho; double _bRho; double _atomRho; //Hyper parameter for prior for sigma_y^2 (for Normal and Quantile response model) // Prior is sigma_y^2 ~ InvGamma(shapeSigmaSqY,scaleSigmaSqY) double _shapeSigmaSqY; double _scaleSigmaSqY; //Quantile (for Quantile response model) double _pQuantile; //Hyper parameter for prior for nu, the shape parameter of the Weibull (for survival response model) // Prior is nu ~ Gamma(shapeNu,scaleNu) double _shapeNu; double _scaleNu; //Some working variables for speeding up linear algebra double _workLogDetTau0; MatrixXd _workSqrtTau0; double _workLogDetTau00; MatrixXd _workSqrtTau00; double _workLogDetR0; MatrixXd _workInverseR0; double _workLogDetR00; MatrixXd _workInverseR00; //Slice sampler variables for independent slice sampler double _rSlice; //Truncated sampler variables double _truncationEps; // Hyper parameters for prior for tauCAR (for spatial CAR term) // Prior is tauCAR ~ Gamma(shape,rate) // we use the inverse scale parameterisation so that E[tauCAR] = shape/rate double _shapeTauCAR; double _rateTauCAR; // Initial allocations vector<double> _initAlloc; }; /// \class pReMiuMParams PReMiuMModel.h "PReMiuMModel.h" /// \brief A class for PReMiuM parameters class pReMiuMParams{ public: /// \brief Default constructor pReMiuMParams(){}; /// \brief Destructor ~pReMiuMParams(){}; /// \brief Function to set the sizes of the various class members void setSizes(const unsigned int& nSubjects, const unsigned int& nCovariates, const unsigned int& nDiscreteCov, const unsigned int& nContinuousCov, const unsigned int& nFixedEffects, const unsigned int& nCategoriesY, const unsigned int& nPredictSubjects, const vector<unsigned int>& nCategories, const unsigned int& nClusInit, const string covariateType, const bool weibullFixedShape, const bool useHyperpriorR1, const bool useIndependentNormal, const bool useSeparationPrior){ unsigned int nDiscrCovs = 0; // Initially make the maximum number of clusters the bigger or // the initial number of clusters and 150. // This is only used for initial memory allocation // And will ensure that at this initial time sufficient // space is allocated to prevent future allocations unsigned int maxNClusters = 100; if(nClusInit>100){ maxNClusters=nClusInit; } _maxNClusters = maxNClusters; // Resize all the objects and set to 0 _logPsi.resize(maxNClusters); for(unsigned int c=0;c<maxNClusters;c++){ _logPsi[c]=0.0; } _v.resize(maxNClusters); _logPhi.resize(maxNClusters); _workLogPhiStar.resize(maxNClusters); _mu.resize(maxNClusters); _workMuStar.resize(maxNClusters); _Sigma_blank.resize(maxNClusters); if (useIndependentNormal) { _Tau_Indep.resize(maxNClusters); _Sigma_Indep.resize(maxNClusters); } else if (useSeparationPrior) { _SigmaR_blank.resize(maxNClusters); _SigmaS_blank.resize(maxNClusters); _TauR.resize(maxNClusters); _workSqrtTauR.resize(maxNClusters); _workLogDetTauR.resize(maxNClusters); _TauS.resize(maxNClusters); _workLogDetTauS.resize(maxNClusters); _Tau.resize(maxNClusters); _workSqrtTau.resize(maxNClusters); _workLogDetTau.resize(maxNClusters); _Sigma.resize(maxNClusters); _SigmaR.resize(maxNClusters); _SigmaS.resize(maxNClusters); }else { _Tau.resize(maxNClusters); _workSqrtTau.resize(maxNClusters); _workLogDetTau.resize(maxNClusters); _Sigma.resize(maxNClusters); } _gamma.resize(maxNClusters); for(unsigned int c=0;c<maxNClusters;c++){ if(c==0){ if (covariateType.compare("Discrete")==0) _logNullPhi.resize(nCovariates); if (covariateType.compare("Normal") == 0) { _nullMu.setZero(nCovariates); if (useIndependentNormal) { _R1_Indep.setZero(nCovariates); } if (useSeparationPrior) { _beta_taus.setZero(nCovariates); _mu00.setZero(nCovariates); } if (useHyperpriorR1) { _mu00.setZero(nCovariates); _R1.setZero(nCovariates, nCovariates); _Tau00.setZero(nCovariates, nCovariates); _Sigma00.setZero(nCovariates, nCovariates); } } if (covariateType.compare("Mixed")==0){ _logNullPhi.resize(nDiscreteCov); _nullMu.setZero(nContinuousCov); if (useIndependentNormal) { _R1_Indep.setZero(nContinuousCov); } if (useSeparationPrior) { _beta_taus.setZero(nContinuousCov); _mu00.setZero(nContinuousCov); } if (useHyperpriorR1) { _mu00.setZero(nContinuousCov); _R1.setZero(nContinuousCov, nContinuousCov); _Tau00.setZero(nContinuousCov, nContinuousCov); _Sigma00.setZero(nContinuousCov, nContinuousCov); } } } if (covariateType.compare("Discrete")==0) { _logPhi[c].resize(nCovariates); _workLogPhiStar[c].resize(nCovariates); } else if (covariateType.compare("Normal")==0) { _mu[c].setZero(nCovariates); _workMuStar[c].setZero(nCovariates); _Sigma_blank[c] = false; if (useIndependentNormal) { _Tau_Indep[c].setZero(nCovariates); _Sigma_Indep[c].setZero(nCovariates); }else if (useSeparationPrior) { _SigmaR_blank[c] = false; _SigmaS_blank[c] = false; _TauR[c].setZero(nCovariates, nCovariates); _workSqrtTauR[c].setZero(nCovariates, nCovariates); _TauS[c].setZero(nCovariates, nCovariates); _Tau[c].setZero(nCovariates, nCovariates); _workSqrtTau[c].setZero(nCovariates, nCovariates); _Sigma[c].setZero(nCovariates, nCovariates); _SigmaR[c].setZero(nCovariates, nCovariates); _SigmaS[c].setZero(nCovariates, nCovariates); } else { _Tau[c].setZero(nCovariates, nCovariates); _workSqrtTau[c].setZero(nCovariates, nCovariates); _Sigma[c].setZero(nCovariates, nCovariates); } } else if (covariateType.compare("Mixed")==0) { _logPhi[c].resize(nDiscreteCov); _workLogPhiStar[c].resize(nDiscreteCov); _mu[c].setZero(nContinuousCov); _workMuStar[c].setZero(nContinuousCov); _Sigma_blank[c] = false; if (useIndependentNormal) { _Tau_Indep[c].setZero(nContinuousCov); _Sigma_Indep[c].setZero(nContinuousCov); }else if (useSeparationPrior) { _SigmaR_blank[c] = false; _SigmaS_blank[c] = false; _TauR[c].setZero(nContinuousCov, nContinuousCov); _workSqrtTauR[c].setZero(nContinuousCov, nContinuousCov); _TauS[c].setZero(nContinuousCov, nContinuousCov); _Tau[c].setZero(nContinuousCov, nContinuousCov); _workSqrtTau[c].setZero(nContinuousCov, nContinuousCov); _Sigma[c].setZero(nContinuousCov, nContinuousCov); _SigmaR[c].setZero(nContinuousCov, nContinuousCov); _SigmaS[c].setZero(nContinuousCov, nContinuousCov); } else { _Tau[c].setZero(nContinuousCov, nContinuousCov); _workSqrtTau[c].setZero(nContinuousCov, nContinuousCov); _Sigma[c].setZero(nContinuousCov, nContinuousCov); } } _gamma[c].resize(nCovariates); if (covariateType.compare("Discrete")==0||covariateType.compare("Mixed")==0){ if (covariateType.compare("Mixed")==0){ nDiscrCovs = nDiscreteCov; } else { nDiscrCovs = nCovariates; } for(unsigned int j=0;j<nDiscrCovs;j++){ if(c==0){ _logNullPhi[j].resize(nCategories[j]); } _logPhi[c][j].resize(nCategories[j]); _workLogPhiStar[c][j].resize(nCategories[j]); for(unsigned int p=0;p<nCategories[j];p++){ // We set logPhi to 0.0 so that we can call // normal member function above when we actually // initialise (allowing workLogPXiGivenZi to be // correctly calculated) _logPhi[c][j][p]=0.0; _workLogPhiStar[c][j][p]=0.0; if(c==0){ _logNullPhi[j][p]=0.0; } } } } for(unsigned int j=0;j<nCovariates;j++){ // Everything in by default // This allows us to write general case with switches. _gamma[c][j]=1; } } _theta.resize(maxNClusters); for (unsigned int c=0;c<maxNClusters;c++){ _theta[c].resize(nCategoriesY); } _beta.resize(nFixedEffects); for (unsigned int j=0;j<nFixedEffects;j++){ _beta[j].resize(nCategoriesY); } _u.resize(nSubjects+nPredictSubjects,0.0); _lambda.resize(nSubjects); _z.resize(nSubjects+nPredictSubjects); _rho.resize(nCovariates); _omega.resize(nCovariates); _workNXInCluster.resize(maxNClusters,0); _workDiscreteX.resize(nSubjects+nPredictSubjects); _workContinuousX.resize(nSubjects+nPredictSubjects); _workLogPXiGivenZi.resize(nSubjects); _workPredictExpectedTheta.resize(nPredictSubjects); for (unsigned int i=0;i<nPredictSubjects;i++){ _workPredictExpectedTheta[i].resize(nCategoriesY); } _workEntropy.resize(nSubjects+nPredictSubjects,0); for(unsigned int i=0;i<nSubjects+nPredictSubjects;i++){ if (covariateType.compare("Discrete")==0||covariateType.compare("Normal")==0){ _workDiscreteX[i].resize(nCovariates,0); _workContinuousX[i].resize(nCovariates,0); } else { _workDiscreteX[i].resize(nDiscreteCov,0); _workContinuousX[i].resize(nContinuousCov,0); } if(i<nSubjects){ _workLogPXiGivenZi[i]=0; } } _uCAR.resize(nSubjects); if (weibullFixedShape) { _nu.resize(1); } else { _nu.resize(maxNClusters); } } /// \brief Return the number of clusters unsigned int maxNClusters() const{ return _maxNClusters; } /// \brief Set the number of clusters void maxNClusters(const unsigned int& nClus, const string covariateType, const bool useIndependentNormal, const bool useSeparationPrior){ _maxNClusters=nClus; // Check if we need to do a resize of the // number of various vectors unsigned int prevNClus = _logPsi.size(); if(nClus>prevNClus){ unsigned int nCov=nCovariates(); unsigned int nDiscrCovs=nDiscreteCovs(); unsigned int nDCovs = 0; unsigned int nContCovs=nContinuousCovs(); vector<unsigned int> nCats=nCategories(); unsigned int nCategoriesY = _theta[0].size(); _logPsi.resize(nClus); _v.resize(nClus); _theta.resize(nClus); if (_nu.size()>1) _nu.resize(nClus); for (unsigned int c=0;c<nClus;c++){ _theta[c].resize(nCategoriesY); } _workNXInCluster.resize(nClus); if (covariateType.compare("Discrete")==0){ _logPhi.resize(nClus); _workLogPhiStar.resize(nClus); } else if (covariateType.compare("Normal")==0){ _mu.resize(nClus); _workMuStar.resize(nClus); _Sigma_blank.resize(nClus); if (useIndependentNormal) { _Tau_Indep.resize(nClus); _Sigma_Indep.resize(nClus); }else if (useSeparationPrior) { _SigmaR_blank.resize(nClus); _SigmaS_blank.resize(nClus); _TauR.resize(nClus); _workSqrtTauR.resize(nClus); _workLogDetTauR.resize(nClus); _TauS.resize(nClus); _workLogDetTauS.resize(nClus); _Tau.resize(nClus); _workSqrtTau.resize(nClus); _workLogDetTau.resize(nClus); _Sigma.resize(nClus); _SigmaR.resize(nClus); _SigmaS.resize(nClus); }else { _Tau.resize(nClus); _workSqrtTau.resize(nClus); _workLogDetTau.resize(nClus); _Sigma.resize(nClus); } } else if (covariateType.compare("Mixed")==0){ _logPhi.resize(nClus); _workLogPhiStar.resize(nClus); _mu.resize(nClus); _workMuStar.resize(nClus); _Sigma_blank.resize(nClus); if (useIndependentNormal) { _Tau_Indep.resize(nClus); _Sigma_Indep.resize(nClus); } else if (useSeparationPrior) { _SigmaR_blank.resize(nClus); _SigmaS_blank.resize(nClus); _TauR.resize(nClus); _workSqrtTauR.resize(nClus); _workLogDetTauR.resize(nClus); _TauS.resize(nClus); _workLogDetTauS.resize(nClus); _Tau.resize(nClus); _workSqrtTau.resize(nClus); _workLogDetTau.resize(nClus); _Sigma.resize(nClus); _SigmaR.resize(nClus); _SigmaS.resize(nClus); }else { _Tau.resize(nClus); _workSqrtTau.resize(nClus); _workLogDetTau.resize(nClus); _Sigma.resize(nClus); } } _gamma.resize(nClus); for(unsigned int c=prevNClus;c<nClus;c++){ _workNXInCluster[c]=0; if (covariateType.compare("Discrete")==0){ _logPhi[c].resize(nCov); _workLogPhiStar[c].resize(nCov); } else if (covariateType.compare("Normal")==0){ _mu[c].setZero(nCov); _workMuStar[c].setZero(nCov); _Sigma_blank[c] = false; if (useIndependentNormal) { _Tau_Indep[c].setZero(nCov); _Sigma_Indep[c].setZero(nCov); }else if (useSeparationPrior) { _SigmaR_blank[c] = false; _SigmaS_blank[c] = false; _TauR[c].setZero(nCov, nCov); _workSqrtTauR[c].setZero(nCov, nCov); _TauS[c].setZero(nCov, nCov); _Tau[c].setZero(nCov, nCov); _workSqrtTau[c].setZero(nCov, nCov); _Sigma[c].setZero(nCov, nCov); _SigmaR[c].setZero(nCov, nCov); _SigmaS[c].setZero(nCov, nCov); } else { _Tau[c].setZero(nCov, nCov); _workSqrtTau[c].setZero(nCov, nCov); _Sigma[c].setZero(nCov, nCov); } } else if (covariateType.compare("Mixed")==0){ _logPhi[c].resize(nDiscrCovs); _workLogPhiStar[c].resize(nDiscrCovs); _mu[c].setZero(nContCovs); _workMuStar[c].setZero(nContCovs); _Sigma_blank[c] = false; if (useIndependentNormal) { _Tau_Indep[c].setZero(nContCovs); _Sigma_Indep[c].setZero(nContCovs); }else if (useSeparationPrior) { _SigmaR_blank[c] = false; _SigmaS_blank[c] = false; _TauR[c].setZero(nContCovs, nContCovs); _workSqrtTauR[c].setZero(nContCovs, nContCovs); _TauS[c].setZero(nContCovs, nContCovs); _Tau[c].setZero(nContCovs, nContCovs); _workSqrtTau[c].setZero(nContCovs, nContCovs); _Sigma[c].setZero(nContCovs, nContCovs); _SigmaR[c].setZero(nContCovs, nContCovs); _SigmaS[c].setZero(nContCovs, nContCovs); } else { _Tau[c].setZero(nContCovs, nContCovs); _workSqrtTau[c].setZero(nContCovs, nContCovs); _Sigma[c].setZero(nContCovs, nContCovs); } } _gamma[c].resize(nCov); if (covariateType.compare("Discrete")==0 || covariateType.compare("Mixed")==0){ if (covariateType.compare("Mixed")==0){ nDCovs = nDiscrCovs; } else { nDCovs = nCov; } for(unsigned int j=0;j<nDCovs;j++){ _logPhi[c][j].resize(nCats[j]); _workLogPhiStar[c][j].resize(nCats[j]); for(unsigned int p=0;p<nCats[j];p++){ // We set logPhi to 0.0 so that we can call // normal member function above when we actually // initialise (allowing workLogPXiGivenZi to be // correctly calculated) _logPhi[c][j][p]=0.0; _workLogPhiStar[c][j][p]=0.0; } // Everything in by default // This allows us to write general case with switches. _gamma[c][j]=1; } } } } } /// \brief Return the number of subjects unsigned int nSubjects() const{ return _lambda.size(); } /// \brief Return the number of covariates unsigned int nCovariates() const{ return _gamma[0].size(); } /// \brief Return the number of covariates unsigned int nDiscreteCovs() const{ return _logPhi[0].size(); } /// \brief Return the number of covariates unsigned int nContinuousCovs() const{ return _mu[0].size(); } /// \brief Return the number of fixed effects unsigned int nFixedEffects(const string& outcomeType) const{ return _beta.size(); } /// \brief Return the number of categories of outcome Y for Categorical outcome unsigned int nCategoriesY() const{ return _theta[0].size(); } /// \brief Return the number of clusters unsigned int nPredictSubjects() const{ return _z.size()-_lambda.size(); } /// \brief Return the vector of the number of categories vector<unsigned int> nCategories() const{ vector<unsigned int> output; unsigned int nCovariates = _logPhi[0].size(); for(unsigned int j=0;j<nCovariates;j++){ output.push_back(_logPhi[0][j].size()); } return output; } /// \brief Return the number of categories of covariate i unsigned int nCategories(const unsigned int& j) const{ return _logPhi[0][j].size(); } /// \brief Return the probabilities of allocation vector<double> logPsi() const{ return _logPsi; } /// \brief Return the probability of allocation to cluster c double logPsi(const unsigned int& c) const{ return _logPsi[c]; } /// \brief Set the probability of allocation to cluster c void logPsi(const unsigned int& c,const double& logPsiVal){ _logPsi[c]=logPsiVal; } /// \brief Set the vector of probability of allocations to clusters void logPsi(const vector<double>& logPsiVec){ _logPsi=logPsiVec; } /// \brief Return the stick breaking constants vector<double> v() const{ return _v; } /// \brief Return the stick breaking constant for cluster c double v(const unsigned int& c) const{ return _v[c]; } /// \brief Set the stick breaking constant for cluster c void v(const unsigned int& c,const double& vVal){ _v[c]=vVal; } /// \brief Set the stick breaking constant for cluster c void v(const vector<double>& vVec){ _v=vVec; } /// \brief Return the auxilliary variables vector<double> u() const{ return _u; } /// \brief Return the auxilliary variable for individual i double u(const unsigned int& i) const{ return _u[i]; } /// \brief Set auxilliary variable for the individual i void u(const unsigned int& i,const double& uVal){ _u[i]=uVal; } /// \brief Return the conditional covariate probabilites const vector<vector<vector<double> > >& logPhi() const{ return _logPhi; } /// \brief Return the conditional probabilities for cluster c, covariate j const vector<double>& logPhi(const unsigned int& c,const unsigned int& j) const{ return _logPhi[c][j]; } /// \brief Set the conditional probabilities for cluster c, covariate j void logPhi(const unsigned int& c,const unsigned int& j,const vector<double>& logPhiVec){ unsigned int nSbj = nSubjects(); unsigned int nCat = nCategories(j); // Update the working variables vector<double> logPhiStarNew(nCat); for(unsigned int p=0;p<nCat;p++){ logPhiStarNew[p] = log(gamma(c,j)*exp(logPhiVec[p])+(1.0-gamma(c,j))*exp(logNullPhi(j,p))); } for(unsigned int i=0;i<nSbj;i++){ if(z(i)==(int)c){ double logPhiStar; int Xij=workDiscreteX(i,j); logPhiStar = workLogPhiStar(c,j,Xij); _workLogPXiGivenZi[i]+=(logPhiStarNew[Xij]-logPhiStar); } } _workLogPhiStar[c][j]=logPhiStarNew; _logPhi[c][j]=logPhiVec; } /// \brief Return the conditional probability for cluster c, covariate j,category p double logPhi(const unsigned int& c,const unsigned int& j,const unsigned int& p) const{ return _logPhi[c][j][p]; } /// \brief Return the conditional covariate probabilites for null covariates const vector<vector<double> >& logNullPhi() const{ return _logNullPhi; } /// \brief Return the conditional probabilities for null covariate j const vector<double>& logNullPhi(const unsigned int& j) const{ return _logNullPhi[j]; } /// \brief Set the conditional probabilities for cluster c, covariate j void logNullPhi(const unsigned int& j,const vector<double>& logNullPhiVec){ unsigned int nClusters = maxNClusters(); unsigned int nSbj = nSubjects(); unsigned int nCat = nCategories(j); // Update the working variables vector<vector<double> > logPhiStarNew(nClusters); for(unsigned int c=0;c<nClusters;c++){ logPhiStarNew[c].resize(nCat); for(unsigned int p=0;p<nCat;p++){ logPhiStarNew[c][p] = log(gamma(c,j)*exp(logPhi(c,j,p))+(1.0-gamma(c,j))*exp(logNullPhiVec[p])); } } for(unsigned int i=0;i<nSbj;i++){ unsigned int c=z(i); int Xij=workDiscreteX(i,j); double logPhiStar; logPhiStar = workLogPhiStar(c,j,Xij); _workLogPXiGivenZi[i]+=(logPhiStarNew[c][Xij]-logPhiStar); } for(unsigned int c=0;c<nClusters;c++){ _workLogPhiStar[c][j]=logPhiStarNew[c]; } _logNullPhi[j]=logNullPhiVec; } /// \brief Return the conditional probability for cluster c, covariate j,category p double logNullPhi(const unsigned int& j,const unsigned int& p) const{ return _logNullPhi[j][p]; } /// \brief Return the vector of normal means mu const vector<VectorXd>& mu() const{ return _mu; } /// \brief Return the normal mean mu for cluster c const VectorXd& mu(const unsigned int& c) const{ return _mu[c]; } /// \brief Return the normal mean mu for cluster c covariate j double mu(const unsigned int& c, const unsigned int& j) const{ return _mu[c](j); } /// \brief Set the normal mean for cluster c void mu(const unsigned int& c,const VectorXd& muVec, const bool useIndependentNormal){ _mu[c]=muVec; unsigned int nSbj = nSubjects(); unsigned int nCov = nCovariates(); unsigned int nContCov = nContinuousCovs(); if (nCov!=nContCov) { nCov = nContCov; } if(Sigma_blank(c)){ // This condition should stop this being evaluated when // mu has been initialised but Sigma hasn't VectorXd xi=VectorXd::Zero(nCov); VectorXd muStar=VectorXd::Zero(nCov); for(unsigned int j=0;j<nCov;j++){ muStar(j)=gamma(c,nDiscreteCovs()+j)*muVec(j)+(1.0-gamma(c,nDiscreteCovs()+j))*nullMu(j); } _workMuStar[c] = muStar; for(unsigned int i=0;i<nSbj;i++){ if(z(i)==(int)c){ for(unsigned int j=0;j<nCov;j++){ xi(j)=workContinuousX(i,j); } if (useIndependentNormal) { _workLogPXiGivenZi[i] = 0; for (unsigned int j = 0; j < nCov; j++) { double sigma_indep_j = sqrt(1.0 / Tau_Indep(c, j)); _workLogPXiGivenZi[i] += logPdfNormal(xi(j), muStar(j), sigma_indep_j); } } else { _workLogPXiGivenZi[i] = logPdfMultivarNormal(nCov, xi, muStar, workSqrtTau(c), workLogDetTau(c)); } } } } } /// \brief Return the normal mean mu for null covariates const VectorXd& nullMu() const{ return _nullMu; } /// \brief Return the normal mean mu for null covariate j double nullMu(const unsigned int& j) const{ return _nullMu(j); } /// \brief Set the normal mean for null covariates void nullMu(const VectorXd& nullMuVec, const bool useIndependentNormal){ _nullMu=nullMuVec; unsigned int nClusters = maxNClusters(); unsigned int nSbj = nSubjects(); unsigned int nCov = nCovariates(); unsigned int nContCov = nContinuousCovs(); if (nCov!=nContCov) { nCov = nContCov; } // This condition should stop this being evaluated when // mu has been initialised but Sigma hasn't if(Sigma_blank(0)){ VectorXd xi=VectorXd::Zero(nCov); vector<VectorXd> muStar(nClusters); for(unsigned int c=0;c<nClusters;c++){ muStar[c].setZero(nCov); for(unsigned int j=0;j<nCov;j++){ muStar[c](j)=gamma(c,nDiscreteCovs()+j)*mu(c,j)+(1-gamma(c,nDiscreteCovs()+j))*nullMuVec(j); } _workMuStar[c]=muStar[c]; } for(unsigned int i=0;i<nSbj;i++){ int c=z(i); for(unsigned int j=0;j<nCov;j++){ xi(j)=workContinuousX(i,j); // Note in the continuous or global case, we just create // repeats of gamma(0,j) for each cluster } if (useIndependentNormal) { _workLogPXiGivenZi[i] = 0; for (unsigned int j = 0; j < nCov; j++) { double sigma_indep_j = sqrt(1.0 / Tau_Indep(c,j)); _workLogPXiGivenZi[i] += logPdfNormal(xi(j), muStar[c](j), sigma_indep_j); } } else { _workLogPXiGivenZi[i] = logPdfMultivarNormal(nCov, xi, muStar[c], workSqrtTau(c), workLogDetTau(c)); } } } } /// \brief Return the vector of precision matrices Tau const vector<MatrixXd>& Tau() const{ return _Tau; } /// \brief Return the precision matrix Tau for cluster c const MatrixXd& Tau(const unsigned int& c) const{ return _Tau[c]; } /// \brief Set the precision matrix Tau for cluster c void Tau(const unsigned int& c,const MatrixXd& TauMat){ _Tau[c]=TauMat; Sigma(c,TauMat.inverse()); Sigma_blank(c, true); workLogDetTau(c,log(TauMat.determinant())); LLT<MatrixXd> llt; MatrixXd sqrtTau = (llt.compute(TauMat)).matrixU(); workSqrtTau(c,sqrtTau); unsigned int nSbj = nSubjects(); unsigned int nCov = nCovariates(); unsigned int nContCov = nContinuousCovs(); if (nCov!=nContCov) { nCov = nContCov; } VectorXd muStar=workMuStar(c); for(unsigned int i=0;i<nSbj;i++){ VectorXd xi=VectorXd::Zero(nCov); if(z(i)==(int)c){ for(unsigned int j=0;j<nCov;j++){ xi(j)=workContinuousX(i,j); } _workLogPXiGivenZi[i]=logPdfMultivarNormal(nCov,xi,muStar,workSqrtTau(c),workLogDetTau(c)); } } } /// \brief Return the covariance matrix Sigma element j1,j2 for cluster c double Tau(const unsigned int& c,const unsigned int& j1,const unsigned int& j2) const{ return _Tau[c](j1,j2); } /// combine TauR and TauS using Tau=TauS*TauR*TauS if separation strategy is used void Tau(const unsigned int& c, const MatrixXd& TauS, const MatrixXd& TauR){ MatrixXd Tau_new = TauS*TauR*TauS; _Tau[c] = Tau_new; Sigma(c, Tau_new.inverse()); if (SigmaR_blank(c) && SigmaS_blank(c)) { Sigma_blank(c, true); } workLogDetTau(c, log(Tau_new.determinant())); LLT<MatrixXd> llt; MatrixXd sqrtTau = (llt.compute(Tau_new)).matrixU(); workSqrtTau(c, sqrtTau); unsigned int nSbj = nSubjects(); unsigned int nCov = nCovariates(); unsigned int nContCov = nContinuousCovs(); if (nCov != nContCov) { nCov = nContCov; } VectorXd muStar = workMuStar(c); for (unsigned int i = 0; i<nSbj; i++) { VectorXd xi = VectorXd::Zero(nCov); if (z(i) == (int)c) { for (unsigned int j = 0; j<nCov; j++) { xi(j) = workContinuousX(i, j); } _workLogPXiGivenZi[i] = logPdfMultivarNormal(nCov, xi, muStar, workSqrtTau(c), workLogDetTau(c)); } } } /// \brief Return the vector of precision matrices TauR if separation strategy is used const vector<MatrixXd>& TauR() const { return _TauR; } /// \brief Return the precision matrix TauR for cluster c if separation strategy is used const MatrixXd& TauR(const unsigned int& c) const { return _TauR[c]; } /// \brief Set the precision matrix TauR for cluster c if separation strategy is used void TauR(const unsigned int& c, const MatrixXd& TauMat) { _TauR[c] = TauMat; SigmaR(c, TauMat.inverse()); SigmaR_blank(c, true); workLogDetTauR(c, log(TauMat.determinant())); LLT<MatrixXd> llt; MatrixXd sqrtTauR = (llt.compute(TauMat)).matrixU(); workSqrtTauR(c, sqrtTauR); MatrixXd matTauS = TauS(c); Tau(c, matTauS, TauMat); } /// \brief Return the precision matrix TauR element j1,j2 for cluster c if separation strategy is used double TauR(const unsigned int& c, const unsigned int& j1, const unsigned int& j2) const { return _TauR[c](j1, j2); } /// \brief Return the vector of precision matrices TauS if separation strategy is used const vector<MatrixXd>& TauS() const { return _TauS; } /// \brief Return the precision matrix TauS for cluster c if separation strategy is used const MatrixXd& TauS(const unsigned int& c) const { return _TauS[c]; } /// \brief Set the jth element for the precision matrix TauS for cluster c if separation strategy is used void TauS(const unsigned int& c, const unsigned int& j, const double& tauj) { _TauS[c](j, j) = tauj; SigmaS_blank(c, true); MatrixXd mat = TauS(c); SigmaS(c, mat.inverse()); workLogDetTauS(c, log(mat.determinant())); MatrixXd matTauR = TauR(c); Tau(c, mat, matTauR); } /// \brief Return the precision matrix TauS element j for cluster c if separation strategy is used double TauS(const unsigned int& c, const unsigned int& j) const { return _TauS[c](j, j); } /// \brief Return the vector of precision vector Tau_Indep const vector<VectorXd>& Tau_Indep() const { return _Tau_Indep; } /// \brief Return the precision vector Tau_Indep for cluster c const VectorXd& Tau_Indep(const unsigned int& c) const { return _Tau_Indep[c]; } /// \brief Set the precision vector Tau_Indep for cluster c void Tau_Indep(const unsigned int& c, const VectorXd& TauVec) { _Tau_Indep[c] = TauVec; unsigned int nSbj = nSubjects(); unsigned int nCov = nCovariates(); unsigned int nContCov = nContinuousCovs(); if (nCov != nContCov) { nCov = nContCov; } //compute the Sigma vector for cluster c VectorXd TauVec_inv(nCov); for (unsigned int j = 0; j < nCov; j++) { TauVec_inv(j) = 1.0 / TauVec(j); } Sigma_Indep(c, TauVec_inv); Sigma_blank(c, true); VectorXd muStar = workMuStar(c); for (unsigned int i = 0; i<nSbj; i++) { VectorXd xi = VectorXd::Zero(nCov); if (z(i) == (int)c) { for (unsigned int j = 0; j<nCov; j++) { xi(j) = workContinuousX(i, j); } _workLogPXiGivenZi[i] = 0; for (unsigned int j = 0; j < nCov; j++) { double sigma_indep_j = sqrt(1.0 / Tau_Indep(c, j)); _workLogPXiGivenZi[i] += logPdfNormal(xi(j), muStar(j), sigma_indep_j); } } } } /// \brief Return the precision vector element j for cluster c double Tau_Indep(const unsigned int& c, const unsigned int& j) const { return _Tau_Indep[c](j); } /// \brief Return the scale matrix R1 for the Wishart distribution of Tau_c const MatrixXd& R1() const{ return _R1; } /// \brief Set the scale matrix R1 for the Wishart distribution of Tau_c void R1(const MatrixXd& R1Mat){ _R1=R1Mat; workLogDetR1(log(R1Mat.determinant())); workInverseR1(R1Mat.inverse()); } /// \brief Return the element j1,j2 for R1 double R1(const unsigned int& j1,const unsigned int& j2) const{ return _R1(j1,j2); } const MatrixXd& Tau00() const { return _Tau00; } void Tau00(const MatrixXd& TauMat) { _Tau00 = TauMat; Sigma00(TauMat.inverse()); workLogDetTau00(log(TauMat.determinant())); LLT<MatrixXd> llt; MatrixXd sqrtTau00 = (llt.compute(TauMat)).matrixU(); workSqrtTau00(sqrtTau00); } double Tau00(const unsigned int& j1, const unsigned int& j2) const { return _Tau00(j1, j2); } const MatrixXd& Sigma00() const { return _Sigma00; } void Sigma00(const MatrixXd& SigmaMat) { _Sigma00 = SigmaMat; } double Sigma00(const unsigned int& j1, const unsigned int& j2) const { return _Sigma00(j1, j2); } const VectorXd& mu00() const { return _mu00; } void mu00(const VectorXd& muVec) { _mu00 = muVec; } double mu00(const unsigned int& j) const { return _mu00(j); } /// \brief Return the rate vector R1 for the gamma distribution of Tau_c /// when the independent normal likelihood is used const VectorXd& R1_Indep() const{ return _R1_Indep; } /// \brief Set the rate vector R1 for the gamma distribution of Tau_c /// when the independent normal likelihood is used void R1_Indep(const VectorXd& R1Vec){ _R1_Indep = R1Vec; } /// \brief Return the element j for R1 /// when the independent normal likelihood is used double R1_Indep(const unsigned int& j) const{ return _R1_Indep(j); } //The following three functions are used when useSeparationPrior=TRUE const VectorXd& beta_taus() const { return _beta_taus; } void beta_taus(const VectorXd& R1Vec) { _beta_taus = R1Vec; } double beta_taus(const unsigned int& j) const { return _beta_taus(j); } const vector<bool>& Sigma_blank() const { return _Sigma_blank; } //\brief set whether the Sigma for cluster c is blank or not void Sigma_blank(const unsigned int& c, const bool& blank) { _Sigma_blank[c] = blank; } //\brief return the boolean value for cluster c to indicate whether the corresponding Sigma is blank bool Sigma_blank(const unsigned int& c) const { return _Sigma_blank[c]; } const vector<bool>& SigmaR_blank() const { return _SigmaR_blank; } void SigmaR_blank(const unsigned int& c, const bool& blank) { _SigmaR_blank[c] = blank; } bool SigmaR_blank(const unsigned int& c) const { return _SigmaR_blank[c]; } const vector<bool>& SigmaS_blank() const { return _SigmaS_blank; } void SigmaS_blank(const unsigned int& c, const bool& blank) { _SigmaS_blank[c] = blank; } bool SigmaS_blank(const unsigned int& c) const { return _SigmaS_blank[c]; } /// \brief Return the vector of covariance matrices Sigma const vector<MatrixXd>& Sigma() const{ return _Sigma; } /// \brief Return the covariance matrix Sigma for cluster c const MatrixXd& Sigma(const unsigned int& c) const{ return _Sigma[c]; } /// \brief Set the covariance matrix Sigma for cluster c void Sigma(const unsigned int& c,const MatrixXd& SigmaMat){ _Sigma[c]=SigmaMat; } /// \brief Return the covariance matrix Sigma element j1,j2 for cluster c double Sigma(const unsigned int& c, const unsigned int& j1, const unsigned int& j2) const { return _Sigma[c](j1, j2); } // use in the case of Separation Prior double SigmaR(const unsigned int& c,const unsigned int& j1,const unsigned int& j2) const{ return _SigmaR[c](j1,j2); } const vector<MatrixXd>& SigmaR() const { return _SigmaR; } const MatrixXd& SigmaR(const unsigned int& c) const { return _SigmaR[c]; } void SigmaR(const unsigned int& c, const MatrixXd& SigmaMat) { _SigmaR[c] = SigmaMat; } // use in the case of Separation Prior double SigmaS(const unsigned int& c, const unsigned int& j) const { return _SigmaS[c](j, j); } const vector<MatrixXd>& SigmaS() const { return _SigmaS; } const MatrixXd& SigmaS(const unsigned int& c) const { return _SigmaS[c]; } void SigmaS(const unsigned int& c, const MatrixXd& SigmaMat) { _SigmaS[c] = SigmaMat; } /// \brief Return the vector of variance vector Sigma /// when the independent normal likelihood is used const vector<VectorXd>& Sigma_Indep() const { return _Sigma_Indep; } /// \brief Return the variance vector Sigma for cluster c /// when the independent normal likelihood is used const VectorXd& Sigma_Indep(const unsigned int& c) const { return _Sigma_Indep[c]; } /// \brief Set the covariance matrix Sigma for cluster c /// when the independent normal likelihood is used void Sigma_Indep(const unsigned int& c, const VectorXd& SigmaVec) { _Sigma_Indep[c] = SigmaVec; } /// \brief Return the covariance vector Sigma element j for cluster c double Sigma_Indep(const unsigned int& c, const unsigned int& j) const { return _Sigma_Indep[c](j); } /// \brief Return the outcome probabilities vector<vector <double> > theta() const{ return _theta; } /// \brief Return the outcome probability for cluster c vector <double> theta(const unsigned int& c) const{ return _theta[c]; } /// \brief Return the outcome probability for cluster c and category k double theta(const unsigned int& c,const unsigned int& k) const{ return _theta[c][k]; } /// \brief Set the outcome probability for cluster c and category k void theta(const unsigned int& c,const unsigned int& k,const double& thetaVal){ _theta[c][k]=thetaVal; } /// \brief Return the confounder coefficients vector<vector <double> > beta() const{ return _beta; } /// \brief Return the coefficient for confounder j and category k double beta(const unsigned int& k,const unsigned int& j) const{ return _beta[k][j]; } /// \brief Set the coefficient for confounder j and category k void beta(const unsigned int& k,const unsigned int& j,const double& betaVal){ _beta[k][j]=betaVal; } /// \brief Return the hyper parameter alpha double alpha() const{ return _alpha; } /// \brief Set the hyper parameter alpha void alpha(const double& alphaVal){ _alpha=alphaVal; } /// \brief Return the hyper parameter kappa1 double kappa11() const { return _kappa11; } /// \brief Set the hyper parameter kappa1 void kappa11(const double& kappa1Val) { _kappa11 = kappa1Val; } /// \brief Return the hyper parameter dPitmanYor double dPitmanYor() const{ return _dPitmanYor; } /// \brief Set the hyper parameter dPitmanYor void dPitmanYor(const double& dPitmanYorVal){ _dPitmanYor=dPitmanYorVal; } /// \brief Return the mean y variables vector<double> lambda() const{ return _lambda; } /// \brief Return the mean y variable of the ith subject double lambda(const unsigned int& i) const{ return _lambda[i]; } /// \brief Set the ith mean y variable void lambda(const unsigned int& i,const double& lam){ _lambda[i]=lam; } /// \brief Return the hyper parameter epsilon double tauEpsilon() const{ return _tauEpsilon; } /// \brief Set the hyper parameter epsilon void tauEpsilon(const double& tauVal){ _tauEpsilon=tauVal; } /// \brief Return the allocation variables const vector<int>& z() const{ return _z; } /// \brief Return the allocation variable of the ith subject int z(const unsigned int& i) const{ return _z[i]; } /// \brief Set the ith allocation variable to cluster c void z(const unsigned int& i,const int& c,const string& covariateType, const bool useIndependentNormal){ unsigned int nCov = nCovariates(); unsigned int nDiscreteCov = nDiscreteCovs(); unsigned int nContinuousCov = nContinuousCovs(); if(i<nSubjects()){ if(covariateType.compare("Discrete")==0){ for(unsigned int j=0;j<nCov;j++){ unsigned int zi = z(i); int Xij=workDiscreteX(i,j); double logPhiStar,logPhiStarNew; logPhiStar = workLogPhiStar(zi,j,Xij); logPhiStarNew = workLogPhiStar(c,j,Xij); _workLogPXiGivenZi[i]+=(logPhiStarNew-logPhiStar); } }else if(covariateType.compare("Normal")==0){ if(Sigma_blank(0)){ VectorXd xi=VectorXd::Zero(nCov); for(unsigned int j=0;j<nCov;j++){ xi(j)=workContinuousX(i,j); } if (useIndependentNormal) { _workLogPXiGivenZi[i] = 0; VectorXd muStar = workMuStar(c); for (unsigned int j = 0; j < nCov; j++) { double sigma_indep_j = sqrt(1.0 / Tau_Indep(c, j)); _workLogPXiGivenZi[i] += logPdfNormal(xi(j),muStar(j), sigma_indep_j); } } else { _workLogPXiGivenZi[i] = logPdfMultivarNormal(nCov, xi, workMuStar(c), workSqrtTau(c), workLogDetTau(c)); } } }else if(covariateType.compare("Mixed")==0){ for(unsigned int j=0;j<nDiscreteCov;j++){ unsigned int zi = z(i); int Xij=workDiscreteX(i,j); double logPhiStar,logPhiStarNew; logPhiStar = workLogPhiStar(zi,j,Xij); logPhiStarNew = workLogPhiStar(c,j,Xij); _workLogPXiGivenZi[i]+=(logPhiStarNew-logPhiStar); } if(Sigma_blank(0)){ VectorXd xi=VectorXd::Zero(nContinuousCov); for(unsigned int j=0;j<nContinuousCov;j++){ xi(j)=workContinuousX(i,j); } if (useIndependentNormal) { _workLogPXiGivenZi[i] = 0; VectorXd muStar = workMuStar(c); for (unsigned int j = 0; j < nContinuousCov; j++) { double sigma_indep_j = sqrt(1.0 / Tau_Indep(c, j)); _workLogPXiGivenZi[i] += logPdfNormal(xi(j), muStar(j), sigma_indep_j); } } else { _workLogPXiGivenZi[i] = logPdfMultivarNormal(nCov, xi, workMuStar(c), workSqrtTau(c), workLogDetTau(c)); } } } } // This is the only original code _z[i]=c; } /// \brief Return the variable selection matrix const vector<vector<double> >& gamma() const{ return _gamma; } /// \brief Return the variable selection vector for cluster c const vector<double>& gamma(const unsigned int& c) const{ return _gamma[c]; } /// \brief Return the variable selection value for cluster c covariate j double gamma(const unsigned int& c, const unsigned int& j) const{ return _gamma[c][j]; } /// \brief Set the variable selection vector for all clusters (used for /// continuous variable selection) void gamma(const unsigned int& j,const double& gammaVal,const string& covariateType, const bool useIndependentNormal){ unsigned int nClusters = maxNClusters(); unsigned int nSbj = nSubjects(); unsigned int nCov = nCovariates(); unsigned int nDiscreteCov = nDiscreteCovs(); unsigned int nContinuousCov = nContinuousCovs(); // Need to update working vector here if(covariateType.compare("Discrete")==0){ unsigned int nCat = nCategories(j); vector<vector<double> > logPhiStarNew(nClusters); for(unsigned int c=0;c<nClusters;c++){ logPhiStarNew[c].resize(nCat); for(unsigned int p=0;p<nCat;p++){ logPhiStarNew[c][p] = log(gammaVal*exp(logPhi(c,j,p))+(1.0-gammaVal)*exp(logNullPhi(j,p))); } } for(unsigned int i=0;i<nSbj;i++){ unsigned int c=z(i); int Xij=_workDiscreteX[i][j]; double logPhiStar; logPhiStar = workLogPhiStar(c,j,Xij); _workLogPXiGivenZi[i]+=(logPhiStarNew[c][Xij]-logPhiStar); } for(unsigned int c=0;c<nClusters;c++){ _workLogPhiStar[c][j]=logPhiStarNew[c]; } }else if(covariateType.compare("Normal")==0){ if(Sigma_blank(0)){ VectorXd xi=VectorXd::Zero(nCov); vector<VectorXd> muStar(nClusters); for(unsigned int c=0;c<nClusters;c++){ muStar[c] = workMuStar(c); muStar[c](j)=gammaVal*mu(c,j)+(1-gammaVal)*nullMu(j); } for(unsigned int i=0;i<nSbj;i++){ int c=z(i); for(unsigned int jj=0;jj<nCov;jj++){ xi(jj)=workContinuousX(i,jj); } if (useIndependentNormal) { VectorXd muStarOld = workMuStar(c); double sigma_indep_j = sqrt(1.0 / Tau_Indep(c,j)); _workLogPXiGivenZi[i] += logPdfNormal(xi(j), muStar[c](j), sigma_indep_j) - logPdfNormal(xi(j), muStarOld(j), sigma_indep_j); } else { _workLogPXiGivenZi[i] = logPdfMultivarNormal(nCov, xi, muStar[c], workSqrtTau(c), workLogDetTau(c)); } } for(unsigned c=0;c<nClusters;c++){ _workMuStar[c]=muStar[c]; } } } else if (covariateType.compare("Mixed")==0){ if (j < nDiscreteCov){ unsigned int nCat = nCategories(j); vector<vector<double> > logPhiStarNew(nClusters); for(unsigned int c=0;c<nClusters;c++){ logPhiStarNew[c].resize(nCat); for(unsigned int p=0;p<nCat;p++){ logPhiStarNew[c][p] = log(gammaVal*exp(logPhi(c,j,p))+(1.0-gammaVal)*exp(logNullPhi(j,p))); } } for(unsigned int i=0;i<nSbj;i++){ unsigned int c=z(i); int Xij=_workDiscreteX[i][j]; double logPhiStar; logPhiStar = workLogPhiStar(c,j,Xij); _workLogPXiGivenZi[i]+=(logPhiStarNew[c][Xij]-logPhiStar); } for(unsigned int c=0;c<nClusters;c++){ _workLogPhiStar[c][j]=logPhiStarNew[c]; } } else { if(Sigma_blank(0)){ VectorXd xi=VectorXd::Zero(nContinuousCov); vector<VectorXd> muStar(nClusters); for(unsigned int c=0;c<nClusters;c++){ muStar[c] = workMuStar(c); muStar[c](j-nDiscreteCov)=gammaVal*mu(c,j-nDiscreteCov)+(1-gammaVal)*nullMu(j-nDiscreteCov); } for(unsigned int i=0;i<nSbj;i++){ int c=z(i); for(unsigned int jj=0;jj<nContinuousCov;jj++){ xi(jj)=workContinuousX(i,jj); } if (useIndependentNormal) { VectorXd muStarOld = workMuStar(c); double sigma_indep_j = sqrt(1.0 / Tau_Indep(c,j) ); _workLogPXiGivenZi[i] += logPdfNormal(xi(j), muStar[c](j), sigma_indep_j) - logPdfNormal(xi(j), muStarOld(j), sigma_indep_j); } else { _workLogPXiGivenZi[i] = logPdfMultivarNormal(nCov, xi, muStar[c], workSqrtTau(c), workLogDetTau(c)); } } for(unsigned c=0;c<nClusters;c++){ _workMuStar[c]=muStar[c]; } } } } for(unsigned int c=0;c<nClusters;c++){ _gamma[c][j]=gammaVal; } } /// \brief Set the variable selection vector for cluster c (used for /// binary cluster specific variable selection) void gamma(const unsigned int& c, const unsigned int& j, const double& gammaVal, const string& covariateType, const bool useIndependentNormal){ unsigned int nSbj = nSubjects(); unsigned int nCov = nCovariates(); unsigned int nDiscrCov = nDiscreteCovs(); unsigned int nContCov = nContinuousCovs(); // Need to update working vector here if(covariateType.compare("Discrete")==0){ unsigned int nCat = nCategories(j); vector<double> logPhiStarNew(nCat); for(unsigned int p=0;p<nCat;p++){ logPhiStarNew[p] = log(gammaVal*exp(logPhi(c,j,p))+(1.0-gammaVal)*exp(logNullPhi(j,p))); } for(unsigned int i=0;i<nSbj;i++){ if(z(i)==(int)c){ int Xij=workDiscreteX(i,j); double logPhiStar; logPhiStar = workLogPhiStar(c,j,Xij); _workLogPXiGivenZi[i]+=(logPhiStarNew[Xij]-logPhiStar); } } _workLogPhiStar[c][j] = logPhiStarNew; }else if(covariateType.compare("Normal")==0){ if(Sigma_blank(0)){ VectorXd xi=VectorXd::Zero(nCov); VectorXd muStarOld = workMuStar(c); VectorXd muStar = workMuStar(c); muStar(j)=gammaVal*mu(c,j)+(1-gammaVal)*nullMu(j); _workMuStar[c]=muStar; for(unsigned int i=0;i<nSbj;i++){ if(z(i)==(int)c){ for(unsigned int jj=0;jj<nCov;jj++){ xi(jj)=workContinuousX(i,jj); } if (useIndependentNormal) { double sigma_indep_j = sqrt(1.0 / Tau_Indep(c,j) ); _workLogPXiGivenZi[i] += logPdfNormal(xi(j), muStar(j), sigma_indep_j) - logPdfNormal(xi(j), muStarOld(j), sigma_indep_j); } else { _workLogPXiGivenZi[i] = logPdfMultivarNormal(nCov, xi, muStar, workSqrtTau(c), workLogDetTau(c)); } } } } }else if(covariateType.compare("Mixed")==0){ if (j<nDiscrCov){ unsigned int nCat = nCategories(j); vector<double> logPhiStarNew(nCat); for(unsigned int p=0;p<nCat;p++){ logPhiStarNew[p] = log(gammaVal*exp(logPhi(c,j,p))+(1.0-gammaVal)*exp(logNullPhi(j,p))); } for(unsigned int i=0;i<nSbj;i++){ if(z(i)==(int)c){ int Xij=workDiscreteX(i,j); double logPhiStar; logPhiStar = workLogPhiStar(c,j,Xij); _workLogPXiGivenZi[i]+=(logPhiStarNew[Xij]-logPhiStar); } } _workLogPhiStar[c][j] = logPhiStarNew; } else { if(Sigma_blank(0)){ VectorXd xi=VectorXd::Zero(nContCov); VectorXd muStarOld = workMuStar(c); VectorXd muStar = workMuStar(c); muStar(j-nDiscrCov)=gammaVal*mu(c,j-nDiscrCov)+(1-gammaVal)*nullMu(j-nDiscrCov); _workMuStar[c]=muStar; for(unsigned int i=0;i<nSbj;i++){ if(z(i)==(int)c){ for(unsigned int jj=0;jj<nContCov;jj++){ xi(jj)=workContinuousX(i,jj); } if (useIndependentNormal) { double sigma_indep_j = sqrt(1.0 / Tau_Indep(c,j) ); _workLogPXiGivenZi[i] += logPdfNormal(xi(j), muStar(j), sigma_indep_j) - logPdfNormal(xi(j), muStarOld(j), sigma_indep_j); } else { _workLogPXiGivenZi[i] = logPdfMultivarNormal(nCov, xi, muStar, workSqrtTau(c), workLogDetTau(c)); } } } } } } _gamma[c][j]=gammaVal; } /// \brief Get the variable selection rho vector - in the continuous /// case rho here is equivalent to zeta in the paper (and we copy /// this value straight to const vector<double>& rho() const{ return _rho; } /// \brief Get the variable selection rho vector for cluster c (used for /// binary cluster specific variable selection) double rho(const unsigned int& j) const{ return _rho[j]; } /// \brief Set the variable selection rho vector for cluster c (used for /// binary cluster specific variable selection) void rho(const unsigned int& j,const double& rhoVal,const string& covariateType, const string& varSelectType, const bool useIndependentNormal){ _rho[j]=rhoVal; // For continuous variable selection propagate this through to gamma if(varSelectType.compare("Continuous")==0){ gamma(j,rhoVal,covariateType, useIndependentNormal); } } /// \brief Get the variable selection rho vector for cluster c (used for /// binary cluster specific variable selection) const vector<unsigned int> omega() const{ return _omega; } /// \brief Get the variable selection rho vector for cluster c (used for /// binary cluster specific variable selection) unsigned int omega(const unsigned int& j) const{ return _omega[j]; } /// \brief Set the variable selection rho vector for cluster c (used for /// binary cluster specific variable selection) void omega(const unsigned int& j,const unsigned int& omegaVal){ _omega[j]=omegaVal; } /// \brief Return the parameter sigmaSqY double sigmaSqY() const{ return _sigmaSqY; } /// \brief Set the parameter sigmaSqY void sigmaSqY(const double& sigmaSqYVal){ _sigmaSqY=sigmaSqYVal; } /// \brief Return the vector _nu vector<double> nu() const{ return _nu; } /// \brief Return the parameter _nu for cluster c double nu(const unsigned int& c ) const{ return _nu[c]; } /// \brief Set the vector nu void nu(vector<double>& nuVal){ _nu=nuVal; } /// \brief Set the parameter nu for cluster c void nu(const unsigned int& c, double& nuVal){ _nu[c]=nuVal; } /// \brief Return the vector _uCAR vector<double> uCAR() const{ return _uCAR; } /// \brief Return the value of_uCAR for subject i double uCAR(const unsigned int& i ) const{ return _uCAR[i]; } /// \brief Set the CAR spatial random vector void uCAR(vector<double>& u){ _uCAR=u; } /// \brief Set the CAR spatial random term for subject i void uCAR(const unsigned int& i, double& u){ _uCAR[i]=u; } /// \brief Return the precision of spatial random term double TauCAR() const{ return _TauCAR; } /// \brief Set the precision for the spatial random term void TauCAR(double& t){ _TauCAR=t; } const pReMiuMHyperParams& hyperParams() const{ return _hyperParams; } pReMiuMHyperParams& hyperParams(){ return _hyperParams; } void hyperParams(const pReMiuMHyperParams& hyPar){ _hyperParams = hyPar; } const vector<unsigned int>& workNXInCluster() const{ return _workNXInCluster; } const unsigned int& workNXInCluster(unsigned int c) const{ return _workNXInCluster[c]; } void workNXInCluster(const vector<unsigned int>& nXInCluster){ for(unsigned int c=0;c<_workNXInCluster.size();c++){ if(c<nXInCluster.size()){ _workNXInCluster[c]=nXInCluster[c]; }else{ _workNXInCluster[c]=0; } } } void workNXInCluster(const unsigned int& c,const unsigned int& n){ _workNXInCluster[c]=n; } const unsigned int& workMaxZi() const{ return _workMaxZi; } void workMaxZi(const unsigned int& maxZ){ _workMaxZi=maxZ; } const double& workMinUi() const{ return _workMinUi; } void workMinUi(const double& minUi){ _workMinUi=minUi; } const vector<vector<int> >& workDiscreteX() const { return _workDiscreteX; } const vector<int>& workDiscreteX(const unsigned int& i) const{ return _workDiscreteX[i]; } int workDiscreteX(const unsigned int& i, const unsigned int& j) const { return _workDiscreteX[i][j]; } void workDiscreteX(const vector<vector<int> >& X){ _workDiscreteX=X; } void workDiscreteX(const unsigned int& i,const unsigned int& j,const int& x){ _workDiscreteX[i][j]=x; } const vector<vector<double> >& workContinuousX() const { return _workContinuousX; } double workContinuousX(const unsigned int& i, const unsigned int& j) const { return _workContinuousX[i][j]; } void workContinuousX(const vector<vector<double> >& X){ _workContinuousX=X; } void workContinuousX(const unsigned int& i,const unsigned int& j,const double& x){ _workContinuousX[i][j]=x; } /// \brief Return the conditional probabilities const vector<double>& workLogPXiGivenZi() const { return _workLogPXiGivenZi; } double workLogPXiGivenZi(const unsigned int& i) const{ return _workLogPXiGivenZi[i]; } void workLogPXiGivenZi(const unsigned int& i, const double& newVal){ _workLogPXiGivenZi[i] = newVal; } const vector<vector<vector<double> > >& workLogPhiStar() const{ return _workLogPhiStar; } double workLogPhiStar(const unsigned int& c,const unsigned int& j, const unsigned int& p) const{ return _workLogPhiStar[c][j][p]; } void workLogPhiStar(const unsigned int& c,const unsigned int& j, const unsigned int& p, const double& logPhiStar){ _workLogPhiStar[c][j][p]=logPhiStar; } const VectorXd& workMuStar(const unsigned int& c) const{ return _workMuStar[c]; } const vector<VectorXd>& workMuStar() const{ return _workMuStar; } void workMuStar(const unsigned int& c,const VectorXd& muStar){ _workMuStar[c]=muStar; } double workPredictExpectedTheta(const unsigned int& j,const unsigned int& k) const{ return _workPredictExpectedTheta[j][k]; } const vector<vector<double> >& workPredictExpectedTheta() const{ return _workPredictExpectedTheta; } void workPredictExpectedTheta(const unsigned int& j,const unsigned int& k,const double& expectedVal){ _workPredictExpectedTheta[j][k]=expectedVal; } double workEntropy(const unsigned int& i) const{ return _workEntropy[i]; } const vector<double>& workEntropy() const{ return _workEntropy; } void workEntropy(const unsigned int& i,const double& entropyVal){ _workEntropy[i]=entropyVal; } unsigned int workNClusInit() const{ return _workNClusInit; } void workNClusInit(const unsigned int& nClusInit){ _workNClusInit=nClusInit; } const vector<MatrixXd>& workSqrtTau() const{ return _workSqrtTau; } const MatrixXd& workSqrtTau(const unsigned int& c) const{ return _workSqrtTau[c]; } void workSqrtTau(const unsigned int& c, const MatrixXd& sqrtTau){ _workSqrtTau[c] = sqrtTau; } const vector<double>& workLogDetTau() const{ return _workLogDetTau; } double workLogDetTau(const unsigned int& c) const{ return _workLogDetTau[c]; } void workLogDetTau(const unsigned int& c, const double& logDetTau){ _workLogDetTau[c] = logDetTau; } const vector<MatrixXd>& workSqrtTauR() const { return _workSqrtTauR; } const MatrixXd& workSqrtTauR(const unsigned int& c) const { return _workSqrtTauR[c]; } void workSqrtTauR(const unsigned int& c, const MatrixXd& sqrtTau) { _workSqrtTauR[c] = sqrtTau; } const vector<double>& workLogDetTauR() const { return _workLogDetTauR; } double workLogDetTauR(const unsigned int& c) const { return _workLogDetTauR[c]; } void workLogDetTauR(const unsigned int& c, const double& logDetTau) { _workLogDetTauR[c] = logDetTau; } const vector<double>& workLogDetTauS() const { return _workLogDetTauS; } double workLogDetTauS(const unsigned int& c) const { return _workLogDetTauS[c]; } void workLogDetTauS(const unsigned int& c, const double& logDetTau) { _workLogDetTauS[c] = logDetTau; } const MatrixXd& workSqrtTau00() const { return _workSqrtTau00; } void workSqrtTau00(const MatrixXd& sqrtTau) { _workSqrtTau00 = sqrtTau; } double workLogDetTau00() const { return _workLogDetTau00; } void workLogDetTau00(const double& logDetTau) { _workLogDetTau00 = logDetTau; } const double& workLogDetR1() const{ return _workLogDetR1; } void workLogDetR1(const double& logDetR1){ _workLogDetR1 = logDetR1; } const MatrixXd& workInverseR1() const{ return _workInverseR1; } void workInverseR1(const MatrixXd& R1){ _workInverseR1 = R1; } void switchLabels(const unsigned int& c1,const unsigned int& c2, const string& covariateType, const string& varSelectType, const bool useIndependentNormal, const bool useSeparationPrior){ //Covariate parameters including working parameters if(covariateType.compare("Discrete")==0){ _logPhi[c1].swap(_logPhi[c2]); _workLogPhiStar[c1].swap(_workLogPhiStar[c2]); }else if(covariateType.compare("Normal")==0){ VectorXd muTmp = _mu[c1]; _mu[c1]=_mu[c2]; _mu[c2]=muTmp; VectorXd workMuStarTmp = _workMuStar[c1]; _workMuStar[c1]=_workMuStar[c2]; _workMuStar[c2]=workMuStarTmp; bool blankTmp = _Sigma_blank[c1]; _Sigma_blank[c1] = _Sigma_blank[c2]; _Sigma_blank[c2] = blankTmp; if (useIndependentNormal) { VectorXd SigmaTmp = _Sigma_Indep[c1]; _Sigma_Indep[c1] = _Sigma_Indep[c2]; _Sigma_Indep[c2] = SigmaTmp; VectorXd TauTmp = _Tau_Indep[c1]; _Tau_Indep[c1] = _Tau_Indep[c2]; _Tau_Indep[c2] = TauTmp; }else if (useSeparationPrior) { bool blankRTmp = _SigmaR_blank[c1]; _SigmaR_blank[c1] = _SigmaR_blank[c2]; _SigmaR_blank[c2] = blankRTmp; bool blankSTmp = _SigmaS_blank[c1]; _SigmaS_blank[c1] = _SigmaS_blank[c2]; _SigmaS_blank[c2] = blankSTmp; MatrixXd TauTmpR = _TauR[c1]; _TauR[c1] = _TauR[c2]; _TauR[c2] = TauTmpR; MatrixXd sqrtTauTmpR = _workSqrtTauR[c1]; _workSqrtTauR[c1] = _workSqrtTauR[c2]; _workSqrtTauR[c2] = sqrtTauTmpR; double logDetTauTmpR = _workLogDetTauR[c1]; _workLogDetTauR[c1] = _workLogDetTauR[c2]; _workLogDetTauR[c2] = logDetTauTmpR; MatrixXd TauTmpS = _TauS[c1]; _TauS[c1] = _TauS[c2]; _TauS[c2] = TauTmpS; double logDetTauTmpS = _workLogDetTauS[c1]; _workLogDetTauS[c1] = _workLogDetTauS[c2]; _workLogDetTauS[c2] = logDetTauTmpS; MatrixXd SigmaTmp = _Sigma[c1]; _Sigma[c1] = _Sigma[c2]; _Sigma[c2] = SigmaTmp; MatrixXd SigmaTmpR = _SigmaR[c1]; _SigmaR[c1] = _SigmaR[c2]; _SigmaR[c2] = SigmaTmpR; MatrixXd SigmaTmpS = _SigmaS[c1]; _SigmaS[c1] = _SigmaS[c2]; _SigmaS[c2] = SigmaTmpS; MatrixXd TauTmp = _Tau[c1]; _Tau[c1] = _Tau[c2]; _Tau[c2] = TauTmp; MatrixXd sqrtTauTmp = _workSqrtTau[c1]; _workSqrtTau[c1] = _workSqrtTau[c2]; _workSqrtTau[c2] = sqrtTauTmp; double logDetTauTmp = _workLogDetTau[c1]; _workLogDetTau[c1] = _workLogDetTau[c2]; _workLogDetTau[c2] = logDetTauTmp; }else { MatrixXd SigmaTmp = _Sigma[c1]; _Sigma[c1] = _Sigma[c2]; _Sigma[c2] = SigmaTmp; MatrixXd TauTmp = _Tau[c1]; _Tau[c1] = _Tau[c2]; _Tau[c2] = TauTmp; MatrixXd sqrtTauTmp = _workSqrtTau[c1]; _workSqrtTau[c1] = _workSqrtTau[c2]; _workSqrtTau[c2] = sqrtTauTmp; double logDetTauTmp = _workLogDetTau[c1]; _workLogDetTau[c1] = _workLogDetTau[c2]; _workLogDetTau[c2] = logDetTauTmp; } }else if(covariateType.compare("Mixed")==0){ _logPhi[c1].swap(_logPhi[c2]); _workLogPhiStar[c1].swap(_workLogPhiStar[c2]); VectorXd muTmp = _mu[c1]; _mu[c1]=_mu[c2]; _mu[c2]=muTmp; VectorXd workMuStarTmp = _workMuStar[c1]; _workMuStar[c1]=_workMuStar[c2]; _workMuStar[c2]=workMuStarTmp; bool blankTmp = _Sigma_blank[c1]; _Sigma_blank[c1] = _Sigma_blank[c2]; _Sigma_blank[c2] = blankTmp; if (useIndependentNormal) { VectorXd SigmaTmp = _Sigma_Indep[c1]; _Sigma_Indep[c1] = _Sigma_Indep[c2]; _Sigma_Indep[c2] = SigmaTmp; VectorXd TauTmp = _Tau_Indep[c1]; _Tau_Indep[c1] = _Tau_Indep[c2]; _Tau_Indep[c2] = TauTmp; } else if (useSeparationPrior) { bool blankRTmp = _SigmaR_blank[c1]; _SigmaR_blank[c1] = _SigmaR_blank[c2]; _SigmaR_blank[c2] = blankRTmp; bool blankSTmp = _SigmaS_blank[c1]; _SigmaS_blank[c1] = _SigmaS_blank[c2]; _SigmaS_blank[c2] = blankSTmp; MatrixXd TauTmpR = _TauR[c1]; _TauR[c1] = _TauR[c2]; _TauR[c2] = TauTmpR; MatrixXd sqrtTauTmpR = _workSqrtTauR[c1]; _workSqrtTauR[c1] = _workSqrtTauR[c2]; _workSqrtTauR[c2] = sqrtTauTmpR; double logDetTauTmpR = _workLogDetTauR[c1]; _workLogDetTauR[c1] = _workLogDetTauR[c2]; _workLogDetTauR[c2] = logDetTauTmpR; MatrixXd TauTmpS = _TauS[c1]; _TauS[c1] = _TauS[c2]; _TauS[c2] = TauTmpS; double logDetTauTmpS = _workLogDetTauS[c1]; _workLogDetTauS[c1] = _workLogDetTauS[c2]; _workLogDetTauS[c2] = logDetTauTmpS; MatrixXd SigmaTmp = _Sigma[c1]; _Sigma[c1] = _Sigma[c2]; _Sigma[c2] = SigmaTmp; MatrixXd SigmaTmpR = _SigmaR[c1]; _SigmaR[c1] = _SigmaR[c2]; _SigmaR[c2] = SigmaTmpR; MatrixXd SigmaTmpS = _SigmaS[c1]; _SigmaS[c1] = _SigmaS[c2]; _SigmaS[c2] = SigmaTmpS; MatrixXd TauTmp = _Tau[c1]; _Tau[c1] = _Tau[c2]; _Tau[c2] = TauTmp; MatrixXd sqrtTauTmp = _workSqrtTau[c1]; _workSqrtTau[c1] = _workSqrtTau[c2]; _workSqrtTau[c2] = sqrtTauTmp; double logDetTauTmp = _workLogDetTau[c1]; _workLogDetTau[c1] = _workLogDetTau[c2]; _workLogDetTau[c2] = logDetTauTmp; }else { MatrixXd SigmaTmp = _Sigma[c1]; _Sigma[c1] = _Sigma[c2]; _Sigma[c2] = SigmaTmp; MatrixXd TauTmp = _Tau[c1]; _Tau[c1] = _Tau[c2]; _Tau[c2] = TauTmp; MatrixXd sqrtTauTmp = _workSqrtTau[c1]; _workSqrtTau[c1] = _workSqrtTau[c2]; _workSqrtTau[c2] = sqrtTauTmp; double logDetTauTmp = _workLogDetTau[c1]; _workLogDetTau[c1] = _workLogDetTau[c2]; _workLogDetTau[c2] = logDetTauTmp; } } //Variable selection parameters if(varSelectType.compare("BinaryCluster")==0){ _gamma[c1].swap(_gamma[c2]); } //Response parameters vector<double> thetaTmp = _theta[c1]; _theta[c1]=_theta[c2]; _theta[c2]=thetaTmp; //Allocation parameters (including counts) for(unsigned int i=0;i<nSubjects()+nPredictSubjects();i++){ if(_z[i]==(int)c1){ _z[i]=c2; }else if(_z[i]==(int)c2){ _z[i]=c1; } } double workNXInClusterTmp = _workNXInCluster[c1]; _workNXInCluster[c1]=_workNXInCluster[c2]; _workNXInCluster[c2]=workNXInClusterTmp; } /// \brief Copy operator pReMiuMParams& operator=(const pReMiuMParams& params){ _maxNClusters=params.maxNClusters(); _logPsi = params.logPsi(); _u = params.u(); _v = params.v(); _logPhi = params.logPhi(); _logNullPhi = params.logNullPhi(); _mu = params.mu(); _nullMu = params.nullMu(); _Tau = params.Tau(); _TauR = params.TauR(); _TauS = params.TauS(); _Tau_Indep = params.Tau_Indep(); _R1 = params.R1(); _mu00 = params.mu00(); _Tau00 = params.Tau00(); _Sigma00 = params.Sigma00(); _R1_Indep = params.R1_Indep(); _beta_taus = params.beta_taus(); _Sigma = params.Sigma(); _SigmaR = params.SigmaR(); _SigmaS = params.SigmaS(); _Sigma_Indep = params.Sigma_Indep(); _theta = params.theta(); _beta = params.beta(); _alpha = params.alpha(); _kappa11 = params.kappa11(); _dPitmanYor = params.dPitmanYor(); _lambda = params.lambda(); _tauEpsilon = params.tauEpsilon(); _z = params.z(); _gamma = params.gamma(); _rho = params.rho(); _omega = params.omega(); _sigmaSqY = params.sigmaSqY(); _nu = params.nu(); _hyperParams = params.hyperParams(); _workNXInCluster=params.workNXInCluster(); _workMaxZi=params.workMaxZi(); _workMinUi=params.workMinUi(); _workDiscreteX=params.workDiscreteX(); _workContinuousX=params.workContinuousX(); _workLogPXiGivenZi = params.workLogPXiGivenZi(); _workLogPhiStar = params.workLogPhiStar(); _workMuStar = params.workMuStar(); _workPredictExpectedTheta = params.workPredictExpectedTheta(); _workEntropy = params.workEntropy(); _workNClusInit = params.workNClusInit(); _workLogDetTau = params.workLogDetTau(); _workLogDetTauR = params.workLogDetTauR(); _workLogDetTauS = params.workLogDetTauS(); _workLogDetTau00 = params.workLogDetTau00(); _workLogDetR1 = params.workLogDetR1(); _workInverseR1 = params.workInverseR1(); _workSqrtTau = params.workSqrtTau(); _workSqrtTauR = params.workSqrtTauR(); _workSqrtTau00 = params.workSqrtTau00(); _uCAR = params.uCAR(); _TauCAR = params.TauCAR(); _Sigma_blank = params.Sigma_blank(); _SigmaS_blank = params.SigmaS_blank(); _SigmaR_blank = params.SigmaR_blank(); return *this; } private: /// \brief The current maximum number of clusters unsigned int _maxNClusters; /// \brief Vector of probabilities of assignment to clusters vector<double> _logPsi; /// \brief Vector of constants for stick breaking generation of logPsi vector<double> _v; /// \brief Vector of auxilliary variables for slice sampler vector<double> _u; /// \brief An array containing conditional covariate probabilities vector<vector<vector<double> > > _logPhi; /// \brief A matrix containing conditional covariate probabilities /// for the "null" covariates vector<vector<double> > _logNullPhi; /// \brief A vector of Eigen dynamic vectors containing covariate means /// for the case of Normal covariates vector<VectorXd> _mu; /// \brief An Eigen dynamic vector containing covariate means /// for the case of Normal covariates for the null covariates VectorXd _nullMu; /// \brief A vector of Eigen dynamic vectors containing covariate covariance /// matrices for the case of Normal covariates vector<MatrixXd> _Sigma; /// \brief A vector of Eigen dynamic vectors containing covariate variance /// vectors for the case of Normal covariates vector<VectorXd> _Sigma_Indep; /// \brief A vector of Eigen dynamic vectors containing covariate precision /// matrices for the case of Normal covariates vector<MatrixXd> _Tau; //They are used in separation strategy vector<MatrixXd> _TauR; vector<MatrixXd> _TauS; vector<MatrixXd> _SigmaR; vector<MatrixXd> _SigmaS; /// \brief A vector of Eigen dynamic vectors containing variance precision /// vectors for the case of Normal covariates vector<VectorXd> _Tau_Indep; /// \brief A matrix of parameters for R1 where Tau ~ Wishart (R1, kappa1) MatrixXd _R1; MatrixXd _Tau00; MatrixXd _Sigma00; VectorXd _mu00; /// \brief A vector of parameters for R1 where Tau_cj~ Gamma (kappa1, R1_j,) VectorXd _R1_Indep; VectorXd _beta_taus; /// \brief A vector of outcome probabilities for each cluster vector< vector <double> > _theta; /// \brief A vector of coefficients for confounding covariates vector<vector <double> > _beta; /// \brief The hyper parameter for dirichlet model double _alpha; /// \brief The hyper parameter for base distribution of Sigma_c double _kappa11; /// \brief The discount hyper parameter for the pitman-yor process prior double _dPitmanYor; /// \brief The mean Y values (if required) vector<double> _lambda; /// \brief The precision for the extra deviation (if required) double _tauEpsilon; /// \brief A vector of allocation variables vector<int> _z; /// \brief A matrix containing the binary variable selection switches /// NOTE: in the continuous or global case, we just create /// repeats of gamma(0,j) for each cluster to make computation faster /// due to less function calls. In our notation, in the continuous case /// gamma is equal (deterministically) to rho. vector<vector<double> > _gamma; /// \brief Prior parameters for variable selection (binary and continuous) /// NOTE: in the continous case, rho is equivalent to zeta in the paper /// and we juect copy this value into gamma. vector<double> _rho; /// \brief Prior parameters for rho vector<unsigned int> _omega; /// \brief Prior variance for Y model when response is Normal and Quantile double _sigmaSqY; /// \brief Prior shape parameter for Y model when response is weibull (survival) vector<double> _nu; /// NOTE: hyper parameters /// \brief The hyper parameter object pReMiuMHyperParams _hyperParams; /// \brief Integer determining the maximum cluster label with some members /// in unsigned int _workMaxZi; /// \brief Double determining the minimum ui double _workMinUi; /// \brief A vector containing the number of subjects in each cluster vector<unsigned int> _workNXInCluster; /// \brief A matrix containing a copy of X vector<vector<int> > _workDiscreteX; /// \brief A matrix containing a copy of X vector<vector<double> > _workContinuousX; /// \brief A matrix containing P(Xi|Zi) vector<double> _workLogPXiGivenZi; /// \brief An array of phi star for variable selection vector<vector<vector<double> > > _workLogPhiStar; /// \brief An array of mu star for variable selection vector<VectorXd> _workMuStar; /// \brief A vector of expected theta values for the prediction subjects vector<vector<double> > _workPredictExpectedTheta; /// \brief A vector of entropy values for each of the subjects vector<double> _workEntropy; /// \brief The actual number of cluster the individuals are individually /// allocated to. Note this is just needed for writing the log file. unsigned int _workNClusInit; /// \brief Working vector of matrices containing matrix square root of Tau vector<MatrixXd> _workSqrtTau; /// \brief Working vector containing the log determinants of Tau vector<double> _workLogDetTau; //They are used in separation strategy vector<MatrixXd> _workSqrtTauR; vector<double> _workLogDetTauR; vector<double> _workLogDetTauS; MatrixXd _workSqrtTau00; double _workLogDetTau00; /// \brief Working double containing the log determinants of R1 double _workLogDetR1; /// \brief Working inverse of R1 MatrixXd _workInverseR1; /// \brief vector of CAR spatial random term U vector<double> _uCAR; /// \brief double for the precision of the CAR random term _uCAR double _TauCAR; //A vector to indicate whether the corresponding Sigma for each cluster is blank or not vector<bool> _Sigma_blank; vector<bool> _SigmaR_blank; vector<bool> _SigmaS_blank; }; double logPYiGivenZiWiBernoulli(const pReMiuMParams& params, const pReMiuMData& dataset, const unsigned int& nFixedEffects,const int& zi, const unsigned int& i){ double lambda; lambda=params.theta(zi,0); for(unsigned int j=0;j<nFixedEffects;j++){ lambda+=params.beta(j,0)*dataset.W(i,j); } double p=1.0/(1.0+exp(-lambda)); return logPdfBernoulli(dataset.discreteY(i),p); } double logPYiGivenZiWiBernoulliExtraVar(const pReMiuMParams& params, const pReMiuMData& dataset, const unsigned int& nFixedEffects,const int& zi, const unsigned int& i){ double lambda=params.lambda(i); double p=1.0/(1.0+exp(-lambda)); return logPdfBernoulli(dataset.discreteY(i),p); } double logPYiGivenZiWiBinomial(const pReMiuMParams& params, const pReMiuMData& dataset, const unsigned int& nFixedEffects,const int& zi, const unsigned int& i){ double lambda; lambda=params.theta(zi,0); for(unsigned int j=0;j<nFixedEffects;j++){ lambda+=params.beta(j,0)*dataset.W(i,j); } double p=1.0/(1.0+exp(-lambda)); return logPdfBinomial(dataset.discreteY(i),dataset.nTrials(i),p); } double logPYiGivenZiWiBinomialExtraVar(const pReMiuMParams& params, const pReMiuMData& dataset, const unsigned int& nFixedEffects,const int& zi, const unsigned int& i){ double lambda=params.lambda(i); double p=1.0/(1.0+exp(-lambda)); return logPdfBinomial(dataset.discreteY(i),dataset.nTrials(i),p); } double logPYiGivenZiWiPoisson(const pReMiuMParams& params, const pReMiuMData& dataset, const unsigned int& nFixedEffects,const int& zi, const unsigned int& i){ double lambda; lambda=params.theta(zi,0); for(unsigned int j=0;j<nFixedEffects;j++){ lambda+=params.beta(j,0)*dataset.W(i,j); } lambda+=dataset.logOffset(i); double mu =exp(lambda); return logPdfPoisson(dataset.discreteY(i),mu); } double logPYiGivenZiWiPoissonExtraVar(const pReMiuMParams& params, const pReMiuMData& dataset, const unsigned int& nFixedEffects,const int& zi, const unsigned int& i){ double lambda=params.lambda(i); double mu=exp(lambda); return logPdfPoisson(dataset.discreteY(i),mu); } double logPYiGivenZiWiPoissonSpatial(const pReMiuMParams& params, const pReMiuMData& dataset, const unsigned int& nFixedEffects,const int& zi, const unsigned int& i){ double lambda; lambda=params.theta(zi,0); for(unsigned int j=0;j<nFixedEffects;j++){ lambda+=params.beta(j,0)*dataset.W(i,j); } lambda+=dataset.logOffset(i); lambda+=params.uCAR(i); double mu =exp(lambda); return logPdfPoisson(dataset.discreteY(i),mu); } double logPYiGivenZiWiNormal(const pReMiuMParams& params, const pReMiuMData& dataset, const unsigned int& nFixedEffects,const int& zi, const unsigned int& i){ double mu; mu=params.theta(zi,0); for(unsigned int j=0;j<nFixedEffects;j++){ mu+=params.beta(j,0)*dataset.W(i,j); } return logPdfNormal(dataset.continuousY(i),mu,sqrt(params.sigmaSqY())); } double logPYiGivenZiWiNormalSpatial(const pReMiuMParams& params, const pReMiuMData& dataset, const unsigned int& nFixedEffects,const int& zi, const unsigned int& i){ double mu; mu=params.theta(zi,0); for(unsigned int j=0;j<nFixedEffects;j++){ mu+=params.beta(j,0)*dataset.W(i,j); } mu+=params.uCAR(i); return logPdfNormal(dataset.continuousY(i),mu,sqrt(params.sigmaSqY())); } double logPYiGivenZiWiQuantile(const pReMiuMParams& params, const pReMiuMData& dataset, const unsigned int& nFixedEffects,const int& zi, const unsigned int& i){ double mu; mu=params.theta(zi,0); for(unsigned int j=0;j<nFixedEffects;j++){ mu+=params.beta(j,0)*dataset.W(i,j); } return logPdfQuantile(dataset.continuousY(i),mu,sqrt(params.sigmaSqY()),params.hyperParams().pQuantile()); } double logPYiGivenZiWiCategorical(const pReMiuMParams& params, const pReMiuMData& dataset, const unsigned int& nFixedEffects, const int& zi, const unsigned int& i){ vector<double> lambda; lambda.resize(dataset.nCategoriesY()); double lambdaSum = 1.0; double value = 0.0; for (unsigned int k=0;k<dataset.nCategoriesY();k++){ for (unsigned int j=0;j<nFixedEffects;j++){ value+=params.beta(j,k)*dataset.W(i,j); } lambda[k] = exp(value + params.theta(zi,k)); lambdaSum += exp(value + params.theta(zi,k)); value = 0.0; } vector<double> p; p.resize(dataset.nCategoriesY()+1); p[0]=1.0/lambdaSum; for (unsigned int k=0;k<dataset.nCategoriesY();k++){ p[k+1]=lambda[k]/lambdaSum; } return logPdfMultinomialSizeOne(dataset.discreteY(i),p); } double logPYiGivenZiWiSurvival(const pReMiuMParams& params, const pReMiuMData& dataset, const unsigned int& nFixedEffects,const int& zi, const unsigned int& i){ unsigned int weibullFixedShape=params.nu().size(); double lambda = params.theta(zi,0); for(unsigned int j=0;j<nFixedEffects;j++){ lambda+=params.beta(j,0)*dataset.W(i,j); } double nu=0; if (weibullFixedShape==1) { nu=params.nu(0); } else { nu=params.nu(zi); } return logPdfWeibullCensored(dataset.continuousY(i), nu, exp(lambda), dataset.censoring(i)); } vector<double> pReMiuMLogPost(const pReMiuMParams& params, const mcmcModel<pReMiuMParams, pReMiuMOptions, pReMiuMData>& model){ const pReMiuMData& dataset = model.dataset(); const string outcomeType = model.dataset().outcomeType(); const string covariateType = model.dataset().covariateType(); const bool includeResponse = model.options().includeResponse(); const bool responseExtraVar = model.options().responseExtraVar(); const string varSelectType = model.options().varSelectType(); double fixedAlpha = model.options().fixedAlpha(); unsigned int nSubjects=dataset.nSubjects(); unsigned int maxNClusters=params.maxNClusters(); unsigned int nCovariates=dataset.nCovariates(); unsigned int nDiscreteCov=dataset.nDiscreteCovs(); unsigned int nContinuousCov=dataset.nContinuousCovs(); unsigned int nFixedEffects=dataset.nFixedEffects(); unsigned int nCategoriesY=dataset.nCategoriesY(); vector<unsigned int> nCategories = dataset.nCategories(); const pReMiuMHyperParams& hyperParams = params.hyperParams(); const bool includeCAR=model.options().includeCAR(); const bool weibullFixedShape=model.options().weibullFixedShape(); const bool useNormInvWishPrior=model.options().useNormInvWishPrior(); const bool useHyperpriorR1=model.options().useHyperpriorR1(); const bool useIndependentNormal = model.options().useIndependentNormal(); const bool useSeparationPrior = model.options().useSeparationPrior(); // (Augmented) Log Likelihood first // We want p(y,X|z,params,W) = p(y|z=c,W,params)p(X|z=c,params) double logLikelihood=0.0; // Add in contribution from X for(unsigned int i=0;i<nSubjects;i++){ //P(xi|zi,params) logLikelihood+=params.workLogPXiGivenZi(i); } // Add in contribution from Y vector<double> extraVarPriorVal(nSubjects,0.0); vector<double> extraVarPriorMean(nSubjects,0.0); if(includeResponse){ double (*logPYiGivenZiWi)(const pReMiuMParams&,const pReMiuMData&, const unsigned int&,const int&, const unsigned int&)=NULL; if(outcomeType.compare("Bernoulli")==0){ if(!responseExtraVar){ logPYiGivenZiWi = &logPYiGivenZiWiBernoulli; }else{ logPYiGivenZiWi = &logPYiGivenZiWiBernoulliExtraVar; for(unsigned int i=0;i<nSubjects;i++){ extraVarPriorVal[i]=params.lambda(i); int zi=params.z(i); extraVarPriorMean[i]=params.theta(zi,0); for(unsigned int j=0;j<nFixedEffects;j++){ extraVarPriorMean[i]+=params.beta(j,0)*dataset.W(i,j); } } } }else if(outcomeType.compare("Binomial")==0){ if(!responseExtraVar){ logPYiGivenZiWi = &logPYiGivenZiWiBinomial; }else{ logPYiGivenZiWi = &logPYiGivenZiWiBinomialExtraVar; for(unsigned int i=0;i<nSubjects;i++){ extraVarPriorVal[i]=params.lambda(i); int zi=params.z(i); extraVarPriorMean[i]=params.theta(zi,0); for(unsigned int j=0;j<nFixedEffects;j++){ extraVarPriorMean[i]+=params.beta(j,0)*dataset.W(i,j); } } } }else if(outcomeType.compare("Poisson")==0){ if(!responseExtraVar){ if (includeCAR){ logPYiGivenZiWi = &logPYiGivenZiWiPoissonSpatial; }else{ logPYiGivenZiWi = &logPYiGivenZiWiPoisson; } }else{ logPYiGivenZiWi = &logPYiGivenZiWiPoissonExtraVar; for(unsigned int i=0;i<nSubjects;i++){ extraVarPriorVal[i]=params.lambda(i); int zi=params.z(i); extraVarPriorMean[i]=params.theta(zi,0); for(unsigned int j=0;j<nFixedEffects;j++){ extraVarPriorMean[i]+=params.beta(j,0)*dataset.W(i,j); } extraVarPriorMean[i]+=dataset.logOffset(i); } } }else if(outcomeType.compare("Categorical")==0){ logPYiGivenZiWi = &logPYiGivenZiWiCategorical; }else if(outcomeType.compare("Normal")==0){ if (includeCAR){ logPYiGivenZiWi = &logPYiGivenZiWiNormalSpatial; }else{ logPYiGivenZiWi = &logPYiGivenZiWiNormal; } }else if(outcomeType.compare("Quantile")==0){ logPYiGivenZiWi = &logPYiGivenZiWiQuantile; }else if(outcomeType.compare("Survival")==0){ logPYiGivenZiWi = &logPYiGivenZiWiSurvival; } for(unsigned int i=0;i<nSubjects;i++){ int zi = params.z(i); logLikelihood+=logPYiGivenZiWi(params,dataset,nFixedEffects,zi,i); } } // Now need to add in the prior (i.e. p(z,params) in above notation) // Note we integrate out u and all parameters in Theta with no members double logPrior=0.0; // Prior for z for(unsigned int i=0;i<nSubjects;i++){ int zi = params.z(i); logPrior+=params.logPsi(zi); } // Prior for V (we only need to include these up to maxNCluster, but we do need // to include all V, whether or not a cluster is empty, as the V themselves //don't correspond to a cluster for(unsigned int c=0;c<maxNClusters;c++){ logPrior+=logPdfBeta(params.v(c),1.0-params.dPitmanYor(),params.alpha()+params.dPitmanYor()*(c+1)); } // Prior for alpha if(fixedAlpha<=-1){ logPrior+=logPdfGamma(params.alpha(),hyperParams.shapeAlpha(),hyperParams.rateAlpha()); } // Prior for cluster specific parameters for the covariates if(covariateType.compare("Discrete")==0){ // If covariate type is discrete for(unsigned int c=0;c<maxNClusters;c++){ if(params.workNXInCluster(c)>0){ for(unsigned int j=0;j<nCovariates;j++){ // We use a Dirichlet prior vector<double> dirichParams(nCategories[j]); for(unsigned int k=0;k<nCategories[j];k++){ dirichParams[k]=hyperParams.aPhi(j); } logPrior+=logPdfDirichlet(params.logPhi(c,j),dirichParams,true); } } } }else if(covariateType.compare("Normal")==0){ // If covariate type is Normal // Add in the prior for mu_c and Sigma_c for each c for(unsigned int c=0;c<maxNClusters;c++){ if(params.workNXInCluster(c)>0){ if (useNormInvWishPrior){ logPrior+=logPdfMultivarNormal(nCovariates,params.mu(c),hyperParams.mu0(),hyperParams.nu0()*params.Tau(c),nCovariates*hyperParams.nu0()+params.workLogDetTau(c)); } else if (useIndependentNormal) { VectorXd mu = params.mu(c); VectorXd mu0 = hyperParams.mu0(); VectorXd tau0 = hyperParams.Tau0_Indep(); for (unsigned int j = 0; j < nCovariates; j++) { double sigma0_j = sqrt(1.0 / tau0(j)); logPrior += logPdfNormal(mu(j), mu0(j), sigma0_j); } } else if (useHyperpriorR1) { logPrior += logPdfMultivarNormal(nCovariates, params.mu(c), params.mu00(), params.workSqrtTau00(), params.workLogDetTau00()); } else if (useSeparationPrior) { logPrior += logPdfMultivarNormal(nCovariates, params.mu(c), params.mu00(), hyperParams.workSqrtTau00(), hyperParams.workLogDetTau00()); } else{ logPrior+=logPdfMultivarNormal(nCovariates,params.mu(c),hyperParams.mu0(),hyperParams.workSqrtTau0(),hyperParams.workLogDetTau0()); } if (useIndependentNormal) { VectorXd tau = params.Tau_Indep(c); double kappa1 = hyperParams.kappa1(); VectorXd r1 = params.R1_Indep(); for (unsigned int j = 0; j < nCovariates; j++) { logPrior += logPdfGamma(tau(j), kappa1, r1(j)); } }else if (useHyperpriorR1) { logPrior += logPdfWishart(nCovariates, params.Tau(c), params.workLogDetTau(c) , params.workInverseR1() , params.workLogDetR1(), (double)params.kappa11()); } else if (useSeparationPrior){ logPrior += logPdfWishart(nCovariates, params.TauR(c), params.workLogDetTauR(c), hyperParams.workInverseR0(), hyperParams.workLogDetR0(), (double)params.kappa11()); double alpha= hyperParams.alpha_taus(); VectorXd beta = params.beta_taus(); for (unsigned int j = 0; j < nCovariates; j++) { double taus = params.TauS(c, j); logPrior += logPdfGamma(taus, alpha, beta(j)); } } else { logPrior += logPdfWishart(nCovariates, params.Tau(c), params.workLogDetTau(c), hyperParams.workInverseR0(), hyperParams.workLogDetR0(), (double)hyperParams.kappa0()); } } } }else if(covariateType.compare("Mixed")==0){ // If covariate type is discrete for(unsigned int c=0;c<maxNClusters;c++){ if(params.workNXInCluster(c)>0){ for(unsigned int j=0;j<nDiscreteCov;j++){ // We use a Dirichlet prior vector<double> dirichParams(nCategories[j]); for(unsigned int k=0;k<nCategories[j];k++){ dirichParams[k]=hyperParams.aPhi(j); } logPrior+=logPdfDirichlet(params.logPhi(c,j),dirichParams,true); } if (useNormInvWishPrior){ logPrior+=logPdfMultivarNormal(nContinuousCov,params.mu(c),hyperParams.mu0(),hyperParams.nu0()*params.Tau(c),nContinuousCov*hyperParams.nu0()+params.workLogDetTau(c)); }else if (useIndependentNormal) { VectorXd mu = params.mu(c); VectorXd mu0 = hyperParams.mu0(); VectorXd tau0 = hyperParams.Tau0_Indep(); for (unsigned int j = 0; j < nContinuousCov; j++) { double sigma0_j = sqrt(1.0 / tau0(j)); logPrior += logPdfNormal(mu(j), mu0(j), sigma0_j); } } else if (useHyperpriorR1) { logPrior += logPdfMultivarNormal(nContinuousCov, params.mu(c), params.mu00(), params.workSqrtTau00(), params.workLogDetTau00()); } else if (useSeparationPrior) { logPrior += logPdfMultivarNormal(nContinuousCov, params.mu(c), params.mu00(), hyperParams.workSqrtTau00(), hyperParams.workLogDetTau00()); } else { logPrior += logPdfMultivarNormal(nContinuousCov, params.mu(c), hyperParams.mu0(), hyperParams.workSqrtTau0(), hyperParams.workLogDetTau0()); } if (useIndependentNormal) { VectorXd tau = params.Tau_Indep(c); double kappa1 = hyperParams.kappa1(); VectorXd r1 = params.R1_Indep(); for (unsigned int j = 0; j < nContinuousCov; j++) { logPrior += logPdfGamma(tau(j), kappa1, r1(j)); } }else if (useHyperpriorR1) { logPrior+=logPdfWishart(nContinuousCov,params.Tau(c),params.workLogDetTau(c),params.workInverseR1(),params.workLogDetR1(),(double)params.kappa11()); } else if (useSeparationPrior) { logPrior += logPdfWishart(nContinuousCov, params.TauR(c), params.workLogDetTauR(c), hyperParams.workInverseR0(), hyperParams.workLogDetR0(), (double)params.kappa11()); double alpha = hyperParams.alpha_taus(); VectorXd beta = params.beta_taus(); for (unsigned int j = 0; j < nContinuousCov; j++) { double taus = params.TauS(c, j); logPrior += logPdfGamma(taus, alpha, beta(j)); } } else { logPrior+=logPdfWishart(nContinuousCov,params.Tau(c),params.workLogDetTau(c),hyperParams.workInverseR0(),hyperParams.workLogDetR0(),(double)hyperParams.kappa0()); } } } } // Prior for R1 used for the cluster specific parameter Tau_c if (covariateType.compare("Normal") == 0) { if (useHyperpriorR1) { logPrior += logPdfWishart(nCovariates, params.Tau00(), params.workLogDetTau00(), hyperParams.workInverseR00(), hyperParams.workLogDetR00(), (double)hyperParams.kappa00()); logPrior += logPdfMultivarNormal(nCovariates, params.mu00(), hyperParams.mu0(), hyperParams.workSqrtTau0(), hyperParams.workLogDetTau0()); MatrixXd workR1Inverse = params.R1().inverse(); logPrior += logPdfInverseWishart(nCovariates, workR1Inverse, params.workLogDetR1(), hyperParams.R0(), hyperParams.workLogDetR0(), (double)hyperParams.kappa0()); logPrior += logPdfInverseGamma((params.kappa11()- nCovariates), hyperParams.shapeKappa1(), hyperParams.scaleKappa1()); }else if (useSeparationPrior) { logPrior += logPdfMultivarNormal(nCovariates, params.mu00(), hyperParams.mu0(), hyperParams.workSqrtTau0(), hyperParams.workLogDetTau0()); logPrior += logPdfInverseGamma((params.kappa11()- nCovariates), hyperParams.shapeKappa1(), hyperParams.scaleKappa1()); VectorXd beta_taus = params.beta_taus(); double alpha0 = hyperParams.alpha_taus0(); VectorXd beta_taus0= hyperParams.beta_taus0(); for (unsigned int j = 0; j < nCovariates; j++) { logPrior += logPdfGamma(beta_taus(j), alpha0, beta_taus0(j)); } }else if (useIndependentNormal) { VectorXd r1 = params.R1_Indep(); double kappa0 = hyperParams.kappa0(); VectorXd r0 = hyperParams.R0_Indep(); for (unsigned int j = 0; j < nCovariates; j++) { logPrior += logPdfGamma(r1(j), kappa0, r0(j)); } } } else if (covariateType.compare("Mixed") == 0) { if (useHyperpriorR1) { logPrior += logPdfWishart(nContinuousCov, params.Tau00(), params.workLogDetTau00(), hyperParams.workInverseR00(), hyperParams.workLogDetR00(), (double)hyperParams.kappa00()); logPrior += logPdfMultivarNormal(nContinuousCov, params.mu00(), hyperParams.mu0(), hyperParams.workSqrtTau0(), hyperParams.workLogDetTau0()); MatrixXd workR1Inverse = params.R1().inverse(); logPrior += logPdfInverseWishart(nContinuousCov, workR1Inverse, params.workLogDetR1(), hyperParams.R0(), hyperParams.workLogDetR0(), (double)hyperParams.kappa0()); logPrior += logPdfInverseGamma((params.kappa11() - nContinuousCov), hyperParams.shapeKappa1(), hyperParams.scaleKappa1()); } else if (useSeparationPrior) { logPrior += logPdfMultivarNormal(nContinuousCov, params.mu00(), hyperParams.mu0(), hyperParams.workSqrtTau0(), hyperParams.workLogDetTau0()); logPrior += logPdfInverseGamma((params.kappa11() - nContinuousCov), hyperParams.shapeKappa1(), hyperParams.scaleKappa1()); VectorXd beta_taus = params.beta_taus(); double alpha0 = hyperParams.alpha_taus0(); VectorXd beta_taus0 = hyperParams.beta_taus0(); for (unsigned int j = 0; j < nContinuousCov; j++) { logPrior += logPdfGamma(beta_taus(j), alpha0, beta_taus0(j)); } }else if (useIndependentNormal) { VectorXd r1 = params.R1_Indep(); double kappa0 = hyperParams.kappa0(); VectorXd r0 = hyperParams.R0_Indep(); for (unsigned int j = 0; j < nContinuousCov; j++) { logPrior += logPdfGamma(r1(j), kappa0, r0(j)); } } } // Prior for variable selection parameters if(varSelectType.compare("None")!=0){ if(varSelectType.compare("BinaryCluster")==0){ for(unsigned int j=0;j<nCovariates;j++){ if(params.rho(j)>0){ for(unsigned int c=0;c<maxNClusters;c++){ if(params.workNXInCluster(c)>0){ logPrior+=params.gamma(c,j)*log(params.rho(j))+(1.0-params.gamma(c,j))*log(1.0-params.rho(j)); } } } } } // We can add in the prior for rho and omega logPrior+=log(hyperParams.atomRho()); for(unsigned int j=0;j<nCovariates;j++){ if(params.omega(j)==1){ logPrior+=logPdfBeta(params.rho(j),hyperParams.aRho(),hyperParams.bRho()); } } } if(includeResponse){ // Prior for theta // We use a location/scale t distribution // http://www.mathworks.com/help/toolbox/stats/brn2ivz-145.html // as per Molitor et al. 2008 (from Gelman et al. 2008) // This is different from Papathomas who uses a normal for(unsigned int c=0;c<maxNClusters;c++){ if(params.workNXInCluster(c)>0){ for (unsigned int k=0;k<nCategoriesY;k++){ logPrior+=logPdfLocationScaleT(params.theta(c,k),hyperParams.muTheta(), hyperParams.sigmaTheta(),hyperParams.dofTheta()); } } } // Prior for beta // There were no fixed effects in the Molitor paper but to be consistent with // theta we use the same distribution (based on same reasoning). // Note we should pre-process variables to standardise the fixed effects to // have 0 mean and standard dev of 0.5 for(unsigned int j=0;j<nFixedEffects;j++){ for (unsigned int k=0;k<nCategoriesY;k++){ logPrior+=logPdfLocationScaleT(params.beta(j,k),hyperParams.muBeta(), hyperParams.sigmaBeta(),hyperParams.dofBeta()); } } // Take account priors for epsilon and tauEpsilon if there is extra variation if(responseExtraVar){ double sigma = 1.0/sqrt(params.tauEpsilon()); for(unsigned int i=0;i<nSubjects;i++){ logPrior+=logPdfNormal(extraVarPriorVal[i],extraVarPriorMean[i],sigma); } logPrior+=logPdfGamma(params.tauEpsilon(),hyperParams.shapeTauEpsilon(), hyperParams.rateTauEpsilon()); } if(outcomeType.compare("Normal")==0){ double tau = 1.0/params.sigmaSqY(); logPrior+=logPdfGamma(tau,hyperParams.shapeSigmaSqY(),hyperParams.scaleSigmaSqY()); } if(outcomeType.compare("Quantile")==0){ double tau = 1.0/params.sigmaSqY(); logPrior+=logPdfGamma(tau,hyperParams.shapeSigmaSqY(),hyperParams.scaleSigmaSqY()); } if(outcomeType.compare("Survival")==0){ if (weibullFixedShape){ logPrior+=logPdfGamma(params.nu(0),hyperParams.shapeNu(),hyperParams.scaleNu()); } else { for (unsigned int c=0;c<maxNClusters;c++) { logPrior+=logPdfGamma(params.nu(c),hyperParams.shapeNu(),hyperParams.scaleNu()); } } } // Prior for TauCAR and UCAR if (includeCAR){ logPrior+=logPdfGamma(params.TauCAR(),hyperParams.shapeTauCAR(),hyperParams.rateTauCAR()); logPrior+=logPdfIntrinsicCAR(params.uCAR(), dataset.neighbours() , params.TauCAR()); } } vector<double> outVec(3); outVec[0]=logLikelihood+logPrior; outVec[1]=logLikelihood; outVec[2]=logPrior; return outVec; } // Log conditional posterior for phi (only used in continuous variable selection) double logCondPostPhicj(const pReMiuMParams& params, const mcmcModel<pReMiuMParams, pReMiuMOptions, pReMiuMData>& model, const unsigned int& c, const unsigned int& j){ const pReMiuMData& dataset = model.dataset(); unsigned int nSubjects=dataset.nSubjects(); vector<unsigned int> nCategories = dataset.nCategories(); const pReMiuMHyperParams& hyperParams = params.hyperParams(); double out=0.0; // Add in contribution from likelihood for(unsigned int i=0;i<nSubjects;i++){ //P(xi|zi,params) if(params.z(i)==(int)c){ out+=params.workLogPXiGivenZi(i); } } // Add in contribution from prior vector<double> dirichParams(nCategories[j]); for(unsigned int k=0;k<nCategories[j];k++){ dirichParams[k]=hyperParams.aPhi(j); } out+=logPdfDirichlet(params.logPhi(c,j),dirichParams,true); return out; } // Log conditional posterior for TauS (only used when useSeparationPrior=TRUE ) double logCondPostTauS(const pReMiuMParams& params, const mcmcModel<pReMiuMParams, pReMiuMOptions, pReMiuMData>& model, const unsigned int& c, const unsigned int& j) { const pReMiuMData& dataset = model.dataset(); unsigned int nSubjects = dataset.nSubjects(); const pReMiuMHyperParams& hyperParams = params.hyperParams(); double out = 0.0; // Add in contribution from likelihood for (unsigned int i = 0; i<nSubjects; i++) { //P(xi|zi,params) if (params.z(i) == (int)c) { out += params.workLogPXiGivenZi(i); } } // Add in contribution from prior double alpha_taus = hyperParams.alpha_taus(); double beta_tausj= params.beta_taus(j); out += logPdfGamma(params.TauS(c, j), alpha_taus, beta_tausj); return out; } // Log conditional posterior for rho and omega (only used in variable selection) double logCondPostRhoOmegaj(const pReMiuMParams& params, const mcmcModel<pReMiuMParams, pReMiuMOptions, pReMiuMData>& model, const unsigned int& j){ const pReMiuMData& dataset = model.dataset(); unsigned int nSubjects=dataset.nSubjects(); unsigned int maxNClusters=params.maxNClusters(); unsigned int nCovariates=dataset.nCovariates(); string varSelectType = model.options().varSelectType(); const pReMiuMHyperParams& hyperParams = params.hyperParams(); double out=0.0; // Add in contribution from likelihood (only in the case of continuous switches) if(varSelectType.compare("Continuous")==0){ for(unsigned int i=0;i<nSubjects;i++){ //P(xi|zi,params) out+=params.workLogPXiGivenZi(i); } }else{ // Add in contribution from prior if(params.omega(j)==1){ for(unsigned int c=0;c<maxNClusters;c++){ out+=params.gamma(c,j)*log(params.rho(j))+(1.0-params.gamma(c,j))*log(1.0-params.rho(j)); } }else{ for(unsigned int c=0;c<maxNClusters;c++){ if(params.gamma(c,j)>0.5){ out = -(numeric_limits<double>::max()); return out; } } } } // We can add in the prior for rho and omega // We keep the loop here because it saves evaluations in the continuous case for(unsigned int j1=0;j1<nCovariates;j1++){ out+=log(hyperParams.atomRho()); if (params.omega(j1)==1){ out+=logPdfBeta(params.rho(j1),hyperParams.aRho(),hyperParams.bRho()); } } return out; } double logCondPostThetaBeta(const pReMiuMParams& params, const mcmcModel<pReMiuMParams, pReMiuMOptions, pReMiuMData>& model){ const pReMiuMData& dataset = model.dataset(); const string outcomeType = model.dataset().outcomeType(); const bool responseExtraVar = model.options().responseExtraVar(); unsigned int nSubjects=dataset.nSubjects(); unsigned int maxNClusters=params.maxNClusters(); unsigned int nFixedEffects=dataset.nFixedEffects(); unsigned int nCategoriesY=dataset.nCategoriesY(); const pReMiuMHyperParams& hyperParams = params.hyperParams(); const bool includeCAR=model.options().includeCAR(); double out=0.0; // Add in contribution from Y vector<double> extraVarPriorVal(nSubjects,0.0); vector<double> extraVarPriorMean(nSubjects,0.0); double (*logPYiGivenZiWi)(const pReMiuMParams&,const pReMiuMData&, const unsigned int&,const int&, const unsigned int&) = NULL; if(outcomeType.compare("Bernoulli")==0){ if(!responseExtraVar){ logPYiGivenZiWi = &logPYiGivenZiWiBernoulli; }else{ logPYiGivenZiWi = &logPYiGivenZiWiBernoulliExtraVar; for(unsigned int i=0;i<nSubjects;i++){ extraVarPriorVal[i]=params.lambda(i); int zi=params.z(i); extraVarPriorMean[i]=params.theta(zi,0); for(unsigned int j=0;j<nFixedEffects;j++){ extraVarPriorMean[i]+=params.beta(j,0)*dataset.W(i,j); } } } }else if(outcomeType.compare("Binomial")==0){ if(!responseExtraVar){ logPYiGivenZiWi = &logPYiGivenZiWiBinomial; }else{ logPYiGivenZiWi = &logPYiGivenZiWiBinomialExtraVar; for(unsigned int i=0;i<nSubjects;i++){ extraVarPriorVal[i]=params.lambda(i); int zi=params.z(i); extraVarPriorMean[i]=params.theta(zi,0); for(unsigned int j=0;j<nFixedEffects;j++){ extraVarPriorMean[i]+=params.beta(j,0)*dataset.W(i,j); } } } }else if(outcomeType.compare("Poisson")==0){ if(!responseExtraVar){ if (includeCAR){ logPYiGivenZiWi = &logPYiGivenZiWiPoissonSpatial; }else{ logPYiGivenZiWi = &logPYiGivenZiWiPoisson; } }else{ logPYiGivenZiWi = &logPYiGivenZiWiPoissonExtraVar; for(unsigned int i=0;i<nSubjects;i++){ extraVarPriorVal[i]=params.lambda(i); int zi=params.z(i); extraVarPriorMean[i]=params.theta(zi,0); for(unsigned int j=0;j<nFixedEffects;j++){ extraVarPriorMean[i]+=params.beta(j,0)*dataset.W(i,j); } extraVarPriorMean[i]+=dataset.logOffset(i); } } }else if(outcomeType.compare("Categorical")==0){ logPYiGivenZiWi = &logPYiGivenZiWiCategorical; }else if(outcomeType.compare("Normal")==0){ if (includeCAR){ logPYiGivenZiWi = &logPYiGivenZiWiNormalSpatial; }else{ logPYiGivenZiWi = &logPYiGivenZiWiNormal; } }else if(outcomeType.compare("Quantile")==0){ logPYiGivenZiWi = &logPYiGivenZiWiQuantile; }else if(outcomeType.compare("Survival")==0){ logPYiGivenZiWi = &logPYiGivenZiWiSurvival; } for(unsigned int i=0;i<nSubjects;i++){ int zi = params.z(i); out+=logPYiGivenZiWi(params,dataset,nFixedEffects,zi,i); } // Prior for theta // We use a location/scale t distribution // http://www.mathworks.com/help/toolbox/stats/brn2ivz-145.html // as per Molitor et al. 2008 (from Gelman et al. 2008) // This is different from Papathomas who uses a normal for(unsigned int c=0;c<maxNClusters;c++){ for (unsigned int k=0;k<nCategoriesY;k++){ out+=logPdfLocationScaleT(params.theta(c,k),hyperParams.muTheta(), hyperParams.sigmaTheta(),hyperParams.dofTheta()); } } // Prior for beta // There were no fixed effects in the Molitor paper but to be consistent with // theta we use the same distribution (based on same reasoning). // Note we should pre-process variables to standardise the fixed effects to // have 0 mean and standard dev of 0.5 for(unsigned int j=0;j<nFixedEffects;j++){ for (unsigned int k=0;k<nCategoriesY;k++){ out+=logPdfLocationScaleT(params.beta(j,k),hyperParams.muBeta(), hyperParams.sigmaBeta(),hyperParams.dofBeta()); } } if(responseExtraVar){ for(unsigned int i=0;i<nSubjects;i++){ out+=logPdfNormal(extraVarPriorVal[i],extraVarPriorMean[i],1/sqrt(params.tauEpsilon())); } } return out; } double logCondPostLambdaiBernoulli(const pReMiuMParams& params, const mcmcModel<pReMiuMParams, pReMiuMOptions, pReMiuMData>& model, const unsigned int& i){ const pReMiuMData& dataset = model.dataset(); unsigned int nFixedEffects=dataset.nFixedEffects(); int zi = params.z(i); double meanVal = params.theta(zi,0); for(unsigned int j=0;j<nFixedEffects;j++){ meanVal+=params.beta(j,0)*dataset.W(i,j); } return logPYiGivenZiWiBernoulliExtraVar(params,dataset,nFixedEffects,zi,i) + logPdfNormal(params.lambda(i),meanVal,1.0/sqrt(params.tauEpsilon())); } double logCondPostLambdaiBinomial(const pReMiuMParams& params, const mcmcModel<pReMiuMParams, pReMiuMOptions, pReMiuMData>& model, const unsigned int& i){ const pReMiuMData& dataset = model.dataset(); unsigned int nFixedEffects=dataset.nFixedEffects(); int zi = params.z(i); double meanVal = params.theta(zi,0); for(unsigned int j=0;j<nFixedEffects;j++){ meanVal+=params.beta(j,0)*dataset.W(i,j); } return logPYiGivenZiWiBinomialExtraVar(params,dataset,nFixedEffects,zi,i) + logPdfNormal(params.lambda(i),meanVal,1.0/sqrt(params.tauEpsilon())); } double logCondPostLambdaiPoisson(const pReMiuMParams& params, const mcmcModel<pReMiuMParams, pReMiuMOptions, pReMiuMData>& model, const unsigned int& i){ const pReMiuMData& dataset = model.dataset(); unsigned int nFixedEffects=dataset.nFixedEffects(); int zi = params.z(i); double meanVal = params.theta(zi,0); for(unsigned int j=0;j<nFixedEffects;j++){ meanVal+=params.beta(j,0)*dataset.W(i,j); } meanVal+=dataset.logOffset(i); return logPYiGivenZiWiPoissonExtraVar(params,dataset,nFixedEffects,zi,i) + logPdfNormal(params.lambda(i),meanVal,1.0/sqrt(params.tauEpsilon())); } // Evaluation log of conditional density of U_i given U_{-i} and Y for adaptive rejection void logUiPostPoissonSpatial(const pReMiuMParams& params, const mcmcModel<pReMiuMParams,pReMiuMOptions,pReMiuMData>& model, const unsigned int& iSub, const double& x, double* Pt_y1, double* Pt_y2){ const pReMiuMData& dataset=model.dataset(); unsigned int nFixedEffects=dataset.nFixedEffects(); double y1; double y2; int Yi=dataset.discreteY(iSub); int zi=params.z(iSub); double meanVal=params.theta(zi,0); for(unsigned int j=0;j<nFixedEffects;j++){ meanVal+=params.beta(j,0)*dataset.W(iSub,j); } int nNeighi=dataset.nNeighbours(iSub); // mean of Ui is mean of Uj where j are the neighbours of i double meanUi=0.0; for (int j = 0; j<nNeighi; j++){ unsigned int nj = dataset.neighbours(iSub,j); double ucarj = params.uCAR(nj-1); meanUi+=ucarj; } meanUi/=nNeighi; y1=Yi*x-exp(dataset.logOffset(iSub)+meanVal+x)-0.5*params.TauCAR()*nNeighi*(x-meanUi)*(x-meanUi); // derivative of y1 y2=Yi-exp(dataset.logOffset(iSub)+meanVal+x)-params.TauCAR()*nNeighi*(x-meanUi); *Pt_y1=y1; *Pt_y2=y2; } // Evaluation log of conditional density of \nu (shape parameter of Weibull for Survival response) // given \gamma for adaptive rejection sampling void logNuPostSurvival(const pReMiuMParams& params, const mcmcModel<pReMiuMParams,pReMiuMOptions,pReMiuMData>& model, const unsigned int& cluster, const double& x, double* Pt_y1, double* Pt_y2){ const pReMiuMData& dataset=model.dataset(); const pReMiuMHyperParams& hyperParams = params.hyperParams(); unsigned int nFixedEffects=dataset.nFixedEffects(); unsigned int nSubjects=dataset.nSubjects(); const vector<unsigned int> censoring = dataset.censoring(); vector<double> y = dataset.continuousY(); const bool weibullFixedShape=model.options().weibullFixedShape(); double y1; double y2; // compute d double dCensored = 0; if (weibullFixedShape){ for (unsigned int i=0;i<nSubjects;i++){ dCensored += censoring[i]; } } else { for (unsigned int i=0;i<nSubjects;i++){ int zi=params.z(i); if (zi==(int)cluster) dCensored += censoring[i]; } } // sum of yi^nu double yNu = 0; double yNulogy = 0; for (unsigned int i=0;i<nSubjects;i++){ int zi=params.z(i); if (weibullFixedShape){ double lambda = params.theta(zi,0); for(unsigned int j=0;j<nFixedEffects;j++){ lambda+=params.beta(j,0)*dataset.W(i,j); } yNulogy += pow(y[i],x) * log(y[i]) * exp(lambda); yNu += pow(y[i],x) * exp(lambda); } else { if (zi==(int)cluster) { double lambda = params.theta(zi,0); for(unsigned int j=0;j<nFixedEffects;j++){ lambda+=params.beta(j,0)*dataset.W(i,j); } yNulogy += pow(y[i],x) * log(y[i]) * exp(lambda); yNu += pow(y[i],x) * exp(lambda); } } } // sum of di*log yi double dlogY = 0; for (unsigned int i=0;i<nSubjects;i++){ if (weibullFixedShape){ dlogY += log(y[i]) * censoring[i]; } else { int zi=params.z(i); if (zi==(int)cluster) dlogY += log(y[i]) * censoring[i]; } } y1=dCensored * log(x) - yNu + x * dlogY + (hyperParams.shapeNu()-1) * log(x) - hyperParams.scaleNu() * x; // derivative of y1 y2=dCensored / x - yNulogy + dlogY + (hyperParams.shapeNu()-1) / x - hyperParams.scaleNu(); *Pt_y1=y1; *Pt_y2=y2; } //void EvalHXHPrimaXPoissonSpatial(const pReMiuMParams& params, // const mcmcModel<pReMiuMParams,pReMiuMOptions,pReMiuMData>& model, // const unsigned int& iSub, // const double& x, // double* Pt_y1, double* Pt_y2){ // // const pReMiuMData& dataset=model.dataset(); // unsigned int nFixedEffects=dataset.nFixedEffects(); // // double y1; // double y2; // y1=-0.5*x*x; // y2=-x; // *Pt_y1=y1; // *Pt_y2=y2; //} #endif /* DIPBACMODEL_H_ */
[ "akhilakollasrinu424jf@gmail.com" ]
akhilakollasrinu424jf@gmail.com
02fba24eeac0425f22f66fb4a7960086bbd617b3
9a66d8339de7cf8debcd79b2d6bc4b669245087e
/王玥蕴/第3次作业-2017310340-王玥蕴-金实/6-22.cpp
1792a369ceb8f91ef8ebb3a12712b9b262c70224
[]
no_license
jinrongsyb17/homework-space
391183e268f1a09e586a18e4cbe2735b59173074
f0c8fe0c17c6fb08c55d967899d9b26a1782b0e3
refs/heads/master
2020-03-28T14:40:12.876141
2019-01-02T04:57:27
2019-01-02T04:57:27
148,510,153
9
18
null
2018-09-18T11:05:38
2018-09-12T16:33:38
C++
GB18030
C++
false
false
448
cpp
#include<iostream> #include<string> using namespace std; string reverse(string&s) { if (s.length() > 1) { string sub = s.substr(1, s.length() - 2); return s.substr(s.length() - 1, 1) + reverse(sub) + s.substr(0, 1); } else return s; } int main() { string s; cout << "输入一个字符串:"; cin >> s; cout << "原字符串为:" << s << endl; cout << "倒序反转后为:" << reverse(s) << endl; return 0; }
[ "noreply@github.com" ]
jinrongsyb17.noreply@github.com
257461c6936fe93e3da5cb7aa82879e3c96a512b
83f9051a64a747b28bdbd3cb60f711dd8dc0cfbe
/poro/source/poro/desktop/platform_desktop.cpp
d7f90abdd6e147edec791870ba11d7c566d9b5aa
[ "Zlib" ]
permissive
gummikana/qr_test
0311608fe82acd7d4879a44f4111e30bc8840d0f
9143353e59238a7767b02d18c446f2e47172a6b5
refs/heads/master
2021-01-20T08:49:01.625142
2015-09-08T15:15:36
2015-09-08T15:15:36
39,264,257
0
0
null
null
null
null
UTF-8
C++
false
false
12,160
cpp
/*************************************************************************** * * Copyright (c) 2010 - 2012 Petri Purho, Dennis Belfrage * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. * ***************************************************************************/ #include "platform_desktop.h" #include <ctime> #include "../libraries.h" #include "../external/poro_windows.h" #include "../mouse.h" #include "../keyboard.h" #include "../touch.h" #include "../event_recorder.h" #include "event_recorder_impl.h" #include "event_playback_impl.h" #include "graphics_opengl.h" #include "soundplayer_sdl.h" #include "joystick_impl.h" #include "mouse_impl.h" namespace { #ifdef PORO_PLAT_WINDOWS double cpu_frequence = 0.0; __int64 counter_start_time = 0; void StartCounter() { LARGE_INTEGER li; if(!QueryPerformanceFrequency(&li)) std::cout << "QueryPerformanceFrequency failed" << std::endl; cpu_frequence = double(li.QuadPart); QueryPerformanceCounter(&li); counter_start_time = li.QuadPart; } double GetPreciseTime() { LARGE_INTEGER li; QueryPerformanceCounter(&li); return ( double(li.QuadPart-counter_start_time)/cpu_frequence ); } #else void StartCounter() { } #define GetPreciseTime() double(SDL_GetTicks() * 0.001 ) #endif } // end of anonymous time namespace poro { const int PORO_WINDOWS_JOYSTICK_COUNT = 4; //----------------------------------------------------------------------------- PlatformDesktop::PlatformDesktop() : mGraphics( NULL ), mFrameCount( 0 ), mFrameRate( 0 ), mOneFrameShouldLast( 1.f / 60.f ), mFixedTimeStep( true ), mWidth( 0 ), mHeight( 0 ), mEventRecorder( NULL ), mMouse( NULL ), mKeyboard( NULL ), mTouch( NULL ), mJoysticks(), mSoundPlayer( NULL ), mRunning( 0 ), mMousePos(), mSleepingMode( PORO_NEVER_SLEEP ), mPrintFramerate( false ), mRandomSeed( 1234567 ) { StartCounter(); } PlatformDesktop::~PlatformDesktop() { } //----------------------------------------------------------------------------- void PlatformDesktop::Init( IApplication* application, int w, int h, bool fullscreen, std::string title ) { IPlatform::Init( application, w, h, fullscreen, title ); mRandomSeed = (int)time(NULL); mRunning = true; mFrameCount = 1; mFrameRate = -1; mWidth = w; mHeight = h; mApplication = application; mGraphics = new GraphicsOpenGL; mGraphics->Init(w, h, fullscreen, title); mSoundPlayer = new SoundPlayerSDL; mSoundPlayer->Init(); mMouse = new MouseImpl; mKeyboard = new Keyboard; mTouch = new Touch; mJoysticks.resize( PORO_WINDOWS_JOYSTICK_COUNT ); for( int i = 0; i < PORO_WINDOWS_JOYSTICK_COUNT; ++i ) { mJoysticks[ i ] = new JoystickImpl( i ); } mEventRecorder = new EventRecorder( mKeyboard, mMouse, mTouch ); // mEventRecorder = new EventRecorderImpl( mKeyboard, mMouse, mTouch ); // mEventRecorder->SetFilename( ); SDL_EnableUNICODE(1); } //----------------------------------------------------------------------------- void PlatformDesktop::Destroy() { delete mGraphics; mGraphics = NULL; delete mSoundPlayer; mSoundPlayer = NULL; delete mMouse; mMouse = NULL; delete mKeyboard; mKeyboard = NULL; delete mTouch; mTouch = NULL; for( std::size_t i = 0; i < mJoysticks.size(); ++i ) delete mJoysticks[ i ]; delete mEventRecorder; mEventRecorder = NULL; mJoysticks.clear(); } //----------------------------------------------------------------------------- void PlatformDesktop::StartMainLoop() { mRunning = true; // just render the screen black before initializing the application if( mGraphics && true ) { mGraphics->BeginRendering(); mGraphics->EndRendering(); } if( mApplication ) mApplication->Init(); types::Double32 mFrameCountLastTime = 0; int mFrameRateUpdateCounter = 0; types::Double32 mProcessorRate = 0; while( mRunning ) { const types::Double32 time_before = GetUpTime(); SingleLoop(); if( mApplication && mApplication->IsDead() == true ) mRunning = false; const types::Double32 time_after = GetUpTime(); const types::Double32 elapsed_time = ( time_after - time_before ); if( elapsed_time < mOneFrameShouldLast ) Sleep( mOneFrameShouldLast - elapsed_time ); while( ( GetUpTime() - time_before ) < mOneFrameShouldLast ) { Sleep( 0 ); } // frame-rate check mProcessorRate += ( elapsed_time / mOneFrameShouldLast ); mFrameCount++; mFrameRateUpdateCounter++; mLastFrameExecutionTime = time_after - time_before; if( ( GetUpTime() - mFrameCountLastTime ) >= 1.0 ) { mFrameCountLastTime = GetUpTime(); mFrameRate = mFrameRateUpdateCounter; mFrameRateUpdateCounter = 0; if( mPrintFramerate ) std::cout << "Fps: " << mFrameRate << " (CPU): " << ( mProcessorRate / (types::Double32)mFrameRate ) * 100.f << "%" << std::endl; mProcessorRate = 0; } } if( mApplication ) mApplication->Exit(); } //----------------------------------------------------------------------------- void PlatformDesktop::SingleLoop() { if( mEventRecorder ) mEventRecorder->StartOfFrame( GetTime() ); HandleEvents(); poro_assert( GetApplication() ); poro_assert( mGraphics ); types::Double32 dt = mOneFrameShouldLast; if( mFixedTimeStep == false ) { static types::Double32 last_time_update_called = 0; dt = (types::Double32)( GetUpTime() - last_time_update_called ); last_time_update_called = GetUpTime(); } GetApplication()->Update( (types::Float32)(dt) ); mGraphics->BeginRendering(); GetApplication()->Draw(mGraphics); mGraphics->EndRendering(); if( mEventRecorder ) mEventRecorder->EndOfFrame( GetTime() ); } //----------------------------------------------------------------------------- void PlatformDesktop::Sleep( types::Double32 seconds ) { if( mSleepingMode == PORO_NEVER_SLEEP ) { return; } else if( mSleepingMode == PORO_USE_SLEEP_0 ) { SDL_Delay( 0 ); } else if( mSleepingMode == PORO_MAXIMIZE_SLEEP ) { SDL_Delay( (Uint32)( seconds * 1000.0 ) ); } } //----------------------------------------------------------------------------- void PlatformDesktop::HandleEvents() { // Reset mouse state mMouse->OnFrameStart(); mKeyboard->OnFrameStart(); // -- event recorder might fire or simulate events of the SDL_EventPoll poro_assert( mEventRecorder ); if( mEventRecorder ) mEventRecorder->DoPlaybacksForFrame(); //---------- for( std::size_t i = 0; i < mJoysticks.size(); ++i ) { HandleJoystickImpl( mJoysticks[ i ] ); } //--------- // Handle events SDL_Event event; while( SDL_PollEvent( &event ) ) { switch( event.type ) { case SDL_KEYDOWN: { mEventRecorder->FireKeyDownEvent( static_cast< int >( event.key.keysym.sym ), static_cast< types::charset >( event.key.keysym.unicode ) ); } break; case SDL_KEYUP: { mEventRecorder->FireKeyUpEvent( static_cast< int >( event.key.keysym.sym ), static_cast< types::charset >( event.key.keysym.unicode ) ); } break; case SDL_QUIT: mRunning = 0; break; case SDL_MOUSEBUTTONDOWN: if( event.button.button == SDL_BUTTON_LEFT ) { mEventRecorder->FireMouseDownEvent( mMousePos, Mouse::MOUSE_BUTTON_LEFT ); mEventRecorder->FireTouchDownEvent( mMousePos, 0 ); } else if( event.button.button == SDL_BUTTON_RIGHT ) { mEventRecorder->FireMouseDownEvent( mMousePos, Mouse::MOUSE_BUTTON_RIGHT ); } else if( event.button.button == SDL_BUTTON_MIDDLE ) { mEventRecorder->FireMouseDownEvent( mMousePos, Mouse::MOUSE_BUTTON_MIDDLE ); } else if( event.button.button == SDL_BUTTON_WHEELUP ) { mEventRecorder->FireMouseDownEvent( mMousePos, Mouse::MOUSE_BUTTON_WHEEL_UP ); } else if( event.button.button == SDL_BUTTON_WHEELDOWN ) { mEventRecorder->FireMouseDownEvent( mMousePos, Mouse::MOUSE_BUTTON_WHEEL_DOWN ); } break; case SDL_MOUSEBUTTONUP: if( event.button.button == SDL_BUTTON_LEFT ) { mEventRecorder->FireMouseUpEvent( mMousePos, Mouse::MOUSE_BUTTON_LEFT ); mEventRecorder->FireTouchUpEvent( mMousePos, 0 ); } else if( event.button.button == SDL_BUTTON_RIGHT ) { mEventRecorder->FireMouseUpEvent( mMousePos, Mouse::MOUSE_BUTTON_RIGHT ); } else if( event.button.button == SDL_BUTTON_MIDDLE ) { mEventRecorder->FireMouseUpEvent( mMousePos, Mouse::MOUSE_BUTTON_MIDDLE ); } break; case SDL_MOUSEMOTION: { mMousePos = mGraphics->ConvertToInternalPos( event.motion.x, event.motion.y ); mEventRecorder->FireMouseMoveEvent( mMousePos ); if( mTouch && mTouch->IsTouchIdDown( 0 ) ) mEventRecorder->FireTouchMoveEvent( mMousePos, 0 ); } break; } } } //----------------------------------------------------------------------------- types::Double32 PlatformDesktop::GetUpTime() { return GetPreciseTime(); } void PlatformDesktop::SetWindowSize( int width, int height ) { mWidth = width; mHeight = height; mGraphics->SetWindowSize( width, height ); } //----------------------------------------------------------------------------- Mouse* PlatformDesktop::GetMouse() { return mMouse; } Joystick* PlatformDesktop::GetJoystick( int n ) { poro_assert( n >= 0 && n < (int)mJoysticks.size() ); poro_assert( mJoysticks[ n ] ); return mJoysticks[ n ]; } //----------------------------------------------------------------------------- IGraphics* PlatformDesktop::GetGraphics() { return mGraphics; } ISoundPlayer* PlatformDesktop::GetSoundPlayer() { return mSoundPlayer; } //----------------------------------------------------------------------------- void PlatformDesktop::SetEventRecording( bool record_events ) { if( record_events ) { if( mEventRecorder == NULL || mEventRecorder->IsRecording() == false ) { delete mEventRecorder; mEventRecorder = new EventRecorderImpl( mKeyboard, mMouse, mTouch ); mRandomSeed = mEventRecorder->GetRandomSeed(); } } else { if( mEventRecorder && mEventRecorder->IsRecording() ) { delete mEventRecorder; mEventRecorder = NULL; mEventRecorder = new EventRecorder( mKeyboard, mMouse, mTouch ); } } } bool PlatformDesktop::GetEventRecording() const { if( mEventRecorder == NULL ) return false; return mEventRecorder->IsRecording(); } void PlatformDesktop::DoEventPlayback( const std::string& filename ) { delete mEventRecorder; EventPlaybackImpl* temp = new EventPlaybackImpl( mKeyboard, mMouse, mTouch ); temp->LoadFromFile( filename ); mEventRecorder = temp; mRandomSeed = mEventRecorder->GetRandomSeed(); } bool PlatformDesktop::IsBreakpointFrame() { if( mEventRecorder == NULL ) return false; if( mEventRecorder->IsPlaybacking() == false ) return false; return ( mEventRecorder->GetFrameLength() > 20 ); } //----------------------------------------------------------------------------- int PlatformDesktop::GetRandomSeed() { int result = mRandomSeed; // use a simple randomizer to randomize the random seed // random func from https://code.google.com/p/nvidia-mesh-tools/source/browse/trunk/src/nvmath/Random.h unsigned int t = ((unsigned int)(mRandomSeed)) * 1103515245 + 12345; mRandomSeed = (int)t; return result; } //----------------------------------------------------------------------------- } // end o namespace poro
[ "petri.purho@gmail.com" ]
petri.purho@gmail.com
f910257047c69527dd5c4fc4ee8aa57b54ae1bc0
ced23fd21573b7be8689005cdd56ed829c336bd3
/extlibs/sqrat/include/sqrat/sqratVM.h
48a909300135453b047fa0d2c1518345d12a5291
[]
no_license
zackthehuman/asobiba
847db04f1f758902cc7c915cd5857972947cf376
541457d657016e7bb4396f16cd19350faa8af581
refs/heads/master
2021-01-10T19:41:22.961116
2013-09-25T04:10:10
2013-09-25T04:10:10
9,310,171
1
0
null
null
null
null
UTF-8
C++
false
false
6,145
h
// wrapper for the Squirrel VM under Sqrat // // Copyright (c) 2011 Alston Chen // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source // distribution. // // #if !defined(_SCRAT_VM_H_) #define _SCRAT_VM_H_ #include <squirrel.h> #include <sqrat.h> #include <map> #include <iostream> #include <stdarg.h> #include <sqstdio.h> #include <sqstdblob.h> #include <sqstdmath.h> #include <sqstdsystem.h> #include <sqstdstring.h> namespace Sqrat { class SqratVM { private: static std::map<HSQUIRRELVM, SqratVM*> ms_sqratVMs; static void s_addVM(HSQUIRRELVM vm, SqratVM* sqratvm); static void s_deleteVM(HSQUIRRELVM vm); static SqratVM* s_getVM(HSQUIRRELVM vm); HSQUIRRELVM m_vm; Sqrat::RootTable* m_rootTable; Sqrat::Script* m_script; Sqrat::string m_lastErrorMsg; private: static void printFunc(HSQUIRRELVM v, const SQChar *s, ...); static SQInteger runtimeErrorHandler(HSQUIRRELVM v); static void compilerErrorHandler(HSQUIRRELVM v, const SQChar* desc, const SQChar* source, SQInteger line, SQInteger column); public: enum ERROR_STATE { NO_ERROR, COMPILE_ERROR, RUNTIME_ERROR }; SqratVM(int initialStackSize = 1024); ~SqratVM(); HSQUIRRELVM getVM() { return m_vm; } Sqrat::RootTable& getRootTable() { return *m_rootTable; } Sqrat::Script& getScript() { return *m_script; } Sqrat::string getLastErrorMsg() { return m_lastErrorMsg; } void setLastErrorMsg(const Sqrat::string& str) { m_lastErrorMsg = str; } void setPrintFunc(SQPRINTFUNCTION printFunc, SQPRINTFUNCTION errFunc); void setErrorHandler(SQFUNCTION runErr, SQCOMPILERERROR comErr); ERROR_STATE doString(const Sqrat::string& str); ERROR_STATE doFile(const Sqrat::string& file); }; #ifdef SQUNICODE #define scvprintf vwprintf #else #define scvprintf vprintf #endif std::map<HSQUIRRELVM, SqratVM*> SqratVM::ms_sqratVMs; void SqratVM::s_addVM(HSQUIRRELVM vm, SqratVM* sqratvm) { //TODO: use mutex to lock ms_sqratVMs ms_sqratVMs.insert(std::make_pair(vm, sqratvm)); } void SqratVM::s_deleteVM(HSQUIRRELVM vm) { //TODO: use mutex to lock ms_sqratVMs ms_sqratVMs.erase(vm); } SqratVM* SqratVM::s_getVM(HSQUIRRELVM vm) { //TODO: use mutex to lock ms_sqratVMs return ms_sqratVMs[vm]; } void SqratVM::printFunc(HSQUIRRELVM v, const SQChar *s, ...) { va_list vl; va_start(vl, s); scvprintf(s, vl); va_end(vl); } SQInteger SqratVM::runtimeErrorHandler(HSQUIRRELVM v) { const SQChar *sErr = 0; if(sq_gettop(v) >= 1) { Sqrat::string& errStr = s_getVM(v)->m_lastErrorMsg; if(SQ_SUCCEEDED(sq_getstring(v, 2, &sErr))) { //scprintf(_SC("RuntimeError: %s\n"), sErr); //errStr = _SC("RuntimeError: ") + sErr; errStr = sErr; } else { //scprintf(_SC("An Unknown RuntimeError Occured.\n")); errStr = _SC("An Unknown RuntimeError Occured."); } } return 0; } void SqratVM::compilerErrorHandler(HSQUIRRELVM v, const SQChar* desc, const SQChar* source, SQInteger line, SQInteger column) { //scprintf(_SC("%s(%d:%d): %s\n"), source, line, column, desc); SQChar buf[512]; scsprintf(buf, _SC("%s(%d:%d): %s"), source, line, column, desc); s_getVM(v)->m_lastErrorMsg = buf; } SqratVM::SqratVM(int initialStackSize /* = 1024 */) : m_vm(sq_open(initialStackSize)) , m_rootTable(new Sqrat::RootTable(m_vm)) , m_script(new Sqrat::Script(m_vm)) , m_lastErrorMsg() { s_addVM(m_vm, this); //register std libs sq_pushroottable(m_vm); sqstd_register_iolib(m_vm); sqstd_register_bloblib(m_vm); sqstd_register_mathlib(m_vm); sqstd_register_systemlib(m_vm); sqstd_register_stringlib(m_vm); sq_pop(m_vm, 1); setPrintFunc(printFunc, printFunc); setErrorHandler(runtimeErrorHandler, compilerErrorHandler); } SqratVM::~SqratVM() { s_deleteVM(m_vm); delete m_script; delete m_rootTable; sq_close(m_vm); } void SqratVM::setPrintFunc(SQPRINTFUNCTION printFunc, SQPRINTFUNCTION errFunc) { sq_setprintfunc(m_vm, printFunc, errFunc); } void SqratVM::setErrorHandler(SQFUNCTION runErr, SQCOMPILERERROR comErr) { sq_newclosure(m_vm, runErr, 0); sq_seterrorhandler(m_vm); sq_setcompilererrorhandler(m_vm, comErr); } SqratVM::ERROR_STATE SqratVM::doString(const Sqrat::string& str) { Sqrat::string msg; m_lastErrorMsg.clear(); if(!m_script->CompileString(str, msg)) { if(m_lastErrorMsg.empty()) { m_lastErrorMsg = msg; } return COMPILE_ERROR; } if(!m_script->Run(msg)) { if(m_lastErrorMsg.empty()) { m_lastErrorMsg = msg; } return RUNTIME_ERROR; } return NO_ERROR; } SqratVM::ERROR_STATE SqratVM::doFile(const Sqrat::string& file) { Sqrat::string msg; m_lastErrorMsg.clear(); if(!m_script->CompileFile(file, msg)) { if(m_lastErrorMsg.empty()) { m_lastErrorMsg = msg; } return COMPILE_ERROR; } if(!m_script->Run(msg)) { if(m_lastErrorMsg.empty()) { m_lastErrorMsg = msg; } return RUNTIME_ERROR; } return NO_ERROR; } } #endif
[ "zack@zackthehuman.com" ]
zack@zackthehuman.com
a1388963371dbcca4e63814d13565708a69d2553
a74146b9020fe1a5fe5ba4c29064206aabdcb0f0
/term2/task3/salesman/graph.cpp
7fc6ce322303ca07b0902a33457fe9eb8486c2aa
[]
no_license
sungulnara2000/term2
246383387e9cf6b6fe01bf53e94f58779d3e4470
60905e81edfbe07a46870fb7d301082711e2efef
refs/heads/master
2022-01-05T15:43:04.738202
2019-05-18T12:00:45
2019-05-18T12:00:45
172,383,024
0
0
null
null
null
null
UTF-8
C++
false
false
1,565
cpp
// // Created by gulnara on 25.04.19. // #include "graph.h" using std::numeric_limits; MatrixGraph::MatrixGraph(int vertexCount) : verticesCount(vertexCount), weightMatrix(vertexCount, vector<float>(vertexCount, std::numeric_limits<int>::max())) { for (int i = 0; i < weightMatrix.size(); ++i) { weightMatrix[i][i] = 0; } } void MatrixGraph::addEdge(int from, int to, float weight) { Edge edge(from, to, weight); Edge backEdge(to, from, weight); weightMatrix[from][to] = weight; weightMatrix[to][from] = weight; } void MatrixGraph::clear() { weightMatrix.clear(); verticesCount = 0; } int MatrixGraph::getVerticesCount() { return verticesCount; } void MatrixGraph::getAllEdges(vector<Edge> &edges) { edges.clear(); for (int j = 0; j < verticesCount; ++j) { for (int i = j + 1; i < verticesCount; ++i) { if (weightMatrix[j][i] != 0 && weightMatrix[j][i] != std::numeric_limits<int>::max()) { edges.push_back(Edge(j, i, weightMatrix[j][i])); } } } } void MatrixGraph::getNextEdges(int vertex, vector<Edge> &edges) { for (int i = 0; i < weightMatrix[vertex].size(); ++i) { if (weightMatrix[vertex][i] != 0 && weightMatrix[vertex][i] != std::numeric_limits<int>::max()) { edges.push_back(Edge(vertex, i, weightMatrix[vertex][i])); } } } void MatrixGraph::getNextVertices(int vertex, vector<float> &vertices) { vertices.clear(); vertices = weightMatrix[vertex]; }
[ "sungulnara2000@mail.ru" ]
sungulnara2000@mail.ru
38ed8a0d3b624dd7afd6b9d9ca7856827fbdd8b9
a31a8fbea9538fbd7650e253faf295fcc22cb303
/Week_4/files_and_streams/rw_file/main.cpp
4d4c4ea5df083616253742f7041d8995883d4b01
[]
no_license
GAlekseyV/White-belt
a6a8b0f7f5397ba5d448059b3fa189dfea170b36
8bc25ae648841979c5e8d4bd00337e13952cbfd1
refs/heads/master
2022-05-14T06:57:22.867182
2022-04-10T11:32:20
2022-04-10T11:32:20
220,627,795
1
0
null
2022-04-10T08:56:04
2019-11-09T10:45:05
C++
UTF-8
C++
false
false
619
cpp
/* * Cчитайте все содержимое файла input.txt, но на этот раз выведите его в файл output.txt. * Точно так же гарантируется, что содержимое файла input.txt заканчивается переводом строки. */ #include <iostream> #include <fstream> #include <string> using namespace std; int main() { string line; ifstream input("input.txt"); ofstream output("output.txt"); if(input.is_open()){ while(getline(input, line)){ output << line << endl; } } return 0; }
[ "galekseyv@gmail.com" ]
galekseyv@gmail.com
acb435a027d37ea0c4bbfd41bf044801457598cd
ea34252a9daa13d015d68494a6a5d18cd60263ec
/include/ircd/m/event/fetch.h
34ee93ec4c0bc3916794fbcc35ac29ddffd8f07e
[ "BSD-3-Clause", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
TurBoss/construct
711cec9bf6dcebbf51f5dda2697d46b558ed87fd
beda5abc2ab884562253324eeeeca7f8789c1891
refs/heads/master
2020-04-12T05:50:51.098932
2018-12-17T20:47:39
2018-12-17T21:18:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,848
h
// Matrix Construct // // Copyright (C) Matrix Construct Developers, Authors & Contributors // Copyright (C) 2016-2018 Jason Volk <jason@zemos.net> // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice is present in all copies. The // full license for this software is available in the LICENSE file. #pragma once #define HAVE_IRCD_M_EVENT_FETCH_H struct ircd::m::event::fetch :event { struct opts; using keys = event::keys; static const opts default_opts; std::array<db::cell, event::size()> cell; db::row row; bool valid; public: fetch(const idx &, std::nothrow_t, const opts *const & = nullptr); fetch(const idx &, const opts *const & = nullptr); fetch(const id &, std::nothrow_t, const opts *const & = nullptr); fetch(const id &, const opts *const & = nullptr); fetch(const opts *const & = nullptr); static bool event_id(const idx &, std::nothrow_t, const id::closure &); static void event_id(const idx &, const id::closure &); friend bool index(const id &, std::nothrow_t, const closure_idx &); friend idx index(const id &, std::nothrow_t); friend idx index(const id &); friend idx index(const event &, std::nothrow_t); friend idx index(const event &); friend bool seek(fetch &, const idx &, std::nothrow_t); friend void seek(fetch &, const idx &); friend bool seek(fetch &, const id &, std::nothrow_t); friend void seek(fetch &, const id &); using view_closure = std::function<void (const string_view &)>; friend bool get(std::nothrow_t, const idx &, const string_view &key, const view_closure &); friend bool get(std::nothrow_t, const id &, const string_view &key, const view_closure &); friend void get(const idx &, const string_view &key, const view_closure &); friend void get(const id &, const string_view &key, const view_closure &); friend const_buffer get(std::nothrow_t, const idx &, const string_view &key, const mutable_buffer &out); friend const_buffer get(std::nothrow_t, const id &, const string_view &key, const mutable_buffer &out); friend const_buffer get(const idx &, const string_view &key, const mutable_buffer &out); friend const_buffer get(const id &, const string_view &key, const mutable_buffer &out); friend void prefetch(const idx &, const string_view &key); friend void prefetch(const idx &, const opts & = default_opts); friend void prefetch(const id &, const string_view &key); friend void prefetch(const id &, const opts & = default_opts); }; struct ircd::m::event::fetch::opts { event::keys keys; db::gopts gopts; opts(const event::keys &, const db::gopts & = {}); opts(const event::keys::selection &, const db::gopts & = {}); opts(const db::gopts &, const event::keys::selection & = {}); opts() = default; };
[ "jason@zemos.net" ]
jason@zemos.net
7ad47c0326234e0c8be60a0e0aca88207774e194
c5aa6545861110fb22033df79c73fe5c72a9ff7d
/cuentaPersonas_Listo_para_autocontenido/cuentaPersonas_Listo_para_autocontenido.ino
e72197307ac285cab4592e009acfbdae4083835c
[]
no_license
fnahuelp/cuentaPersonas-AutoContenido-Joaquin-
4295efe1e26d508a615ff8027caaee4852ee1fa0
6d5968d21dc1b5a111c929a43edd1871935a7460
refs/heads/master
2022-08-02T07:56:39.403537
2020-05-22T19:20:57
2020-05-22T19:20:57
266,216,981
0
0
null
2020-05-22T22:09:51
2020-05-22T22:09:51
null
UTF-8
C++
false
false
8,703
ino
#include <ESP8266WiFi.h> #include <InfluxDb.h> #include <DNSServer.h> #include <ESP8266WebServer.h> #include <WiFiManager.h> #include <EEPROM.h> #define INTDELAY 30 #define RDELAY 100 #define APNAME "Configurar_Sensores" #define APPASS "ESP2866" #define DISPOSITIVO "d1" //Nombre del dispositivo #define SENSOR_OBSTRUCCION "reflectivo" char influx_host [128]; const unsigned short influx_port = 8086; char influx_db [32]; char influx_user [32]; char influx_pass [32]; const byte pinExt = D5; const byte pinInt = D7; volatile bool intExt = false; volatile bool intInt = false; bool exterior = 0; bool interior = 0; int loopCount = 0; int dtimeExt = 0; int dtimeInt = 0; int Trigger_der = 0; int Echo_der = 2; int Trigger_izq = 5; int Echo_izq = 4; int detectado = 1; int derecho = 0; int derecho_max = 0; int derecho_dist_disparo = 0; int izquierdo = 0;; int izquierdo_max = 0; int izquierdo_dist_disparo = 0; int tiempo = 0; int izqInt = 1; int derInt = 1; int izquierdo_duracion,izquierdo_distancia; int derecho_duracion, derecho_distancia; int inactivo = 0; int cuenta = 0; String pulsadores = ""; bool newData = false; Influxdb* influx; void SaveDataCallback () { newData = true; } void pinIntExt() { intExt = true; } void pinIntInt() { intInt = true; } void ResetState () { Serial.print("Reset"); intExt = false; intInt = false; exterior = false; interior = false; loopCount = 0; } void SendInflux (int c) { Serial.print("Mandando... "); InfluxData row("ingreso"); row.addValue("valor", c); influx->write(row); Serial.print("Enviado: "); Serial.println(c); } inline void SendReset (int c) { SendInflux(c); ResetState(); } bool IntStateInt () { if (intInt) { intInt = false; if (dtimeInt == 0) { dtimeInt = INTDELAY; return true; } } return false; } bool IntStateExt () { if (intExt) { intExt = false; if (dtimeExt == 0) { dtimeExt = INTDELAY; return true; } } return false; } void setup() { EEPROM.begin(512); pinMode(Trigger_der, OUTPUT); pinMode(Echo_der, INPUT); pinMode(Trigger_izq, OUTPUT); pinMode(Echo_der, INPUT); Serial.begin(115200); WiFiManager wifiManager; WiFiManagerParameter param_host("influx_host", "influx host", "", 128); WiFiManagerParameter param_db("influx_db", "influx database", "", 32); WiFiManagerParameter param_user("influx_user", "influx user", "", 32); WiFiManagerParameter param_pass("influx_pass", "influx pass", "", 32); wifiManager.addParameter(&param_host); wifiManager.addParameter(&param_db); wifiManager.addParameter(&param_user); wifiManager.addParameter(&param_pass); wifiManager.setSaveConfigCallback(SaveDataCallback); wifiManager.autoConnect(APNAME, APPASS); Serial.print("Connected! IP address: "); Serial.println(WiFi.localIP()); if (newData){ strcpy (influx_host, param_host.getValue()); strcpy (influx_db, param_db.getValue()); strcpy (influx_user, param_user.getValue()); strcpy (influx_pass, param_pass.getValue()); savestr (128, influx_host, 128); savestr (256, influx_db, 32); savestr (288, influx_user, 32); savestr (320, influx_pass, 32); } else { char* temp; temp = loadstr(128, 128); strcpy (influx_host, temp); free(temp); temp = loadstr(256, 32); strcpy (influx_db, temp); free(temp); temp = loadstr(288, 32); strcpy (influx_user, temp); free(temp); temp = loadstr(320, 32); strcpy (influx_pass, temp); free(temp); } influx = new Influxdb (influx_host, influx_port); influx->setDbAuth(influx_db, influx_user, influx_pass); pinMode(pinExt, INPUT_PULLUP); pinMode(pinInt, INPUT_PULLUP); attachInterrupt(digitalPinToInterrupt(pinExt), pinIntExt, RISING); attachInterrupt(digitalPinToInterrupt(pinInt), pinIntInt, RISING); for (int i=0;i<=50;i++) { digitalWrite (Trigger_izq, LOW); delayMicroseconds(2); digitalWrite (Trigger_izq, HIGH); delayMicroseconds (10); digitalWrite (Trigger_izq, LOW); derecho_duracion = pulseIn (Echo_der, HIGH); derecho_distancia = (derecho_duracion/2) / 29.1; if (derecho_distancia > derecho_max || derecho_distancia < 3000) { derecho_max=derecho_distancia; } digitalWrite (Trigger_izq, LOW); delayMicroseconds(2); digitalWrite (Trigger_izq, HIGH); delayMicroseconds (10); digitalWrite (Trigger_izq, LOW); izquierdo_duracion = pulseIn (Echo_izq, HIGH); izquierdo_distancia = (izquierdo_duracion/2) / 29.1; if (izquierdo_distancia > izquierdo_max || izquierdo_distancia < 3000) { izquierdo_max=izquierdo_distancia; } Serial.print("Actual:");Serial.print(izquierdo_distancia);Serial.print(",");Serial.print(derecho_distancia);Serial.println("."); delay(100); } derecho_dist_disparo = derecho_max*0.8; izquierdo_dist_disparo = izquierdo_max*0.8; attachInterrupt(digitalPinToInterrupt(Echo_izq), echo_int_fall, FALLING); //Se vincula la funcion a la subida de señal del pin de interrupcion. attachInterrupt(digitalPinToInterrupt(Echo_der), echo_2_int_fall, FALLING); //Se vincula la funcion a la subida de señal del pin de interrupcion. Serial.print("Fin de configuracion. Distancia de disparo: "); Serial.print(izquierdo_dist_disparo); Serial.print(" y "); Serial.println(derecho_dist_disparo); Serial.println(); Serial.println("Configurando conexion a base de datos..."); } void influx_send_entra_persona(){ //Se conto una persona. InfluxData measurement ("Personas"); measurement.addTag("device", DISPOSITIVO); measurement.addTag("sensor", SENSOR_OBSTRUCCION); measurement.addTag("accion", "entrar"); measurement.addValue("value", 1); // write it into db influx->write(measurement); } void influx_send_sale_persona(){ //Se conto una persona. InfluxData measurement ("Personas"); measurement.addTag("device", DISPOSITIVO); measurement.addTag("sensor", SENSOR_OBSTRUCCION); measurement.addTag("accion", "salir"); measurement.addValue("value", -1); // write it into db influx->write(measurement); } void echo_int_fall(){ izquierdo_duracion=micros() - tiempo; //izqInt=0; } void echo_2_int_fall(){ derecho_duracion=micros() - tiempo; //derInt=0; } void loop(){ digitalWrite (Trigger_izq, HIGH); delayMicroseconds(2); digitalWrite (Trigger_izq, LOW); tiempo=micros(); delayMicroseconds(20); izquierdo_distancia = (izquierdo_duracion/2) / 29.1; derecho_distancia = (derecho_duracion/2) / 29.1; delay(10); if ((izquierdo_distancia < izquierdo_dist_disparo) || (izquierdo_distancia > 3000)) { // Se esta a menos de cierta distancia activa izquierdo. izquierdo = HIGH; } else { izquierdo = LOW; } if ((derecho_distancia < derecho_dist_disparo) || (derecho_distancia > 3000)) { // Se esta a menos de cierta distancia activa derecho. derecho = HIGH; } else { derecho = LOW; } //////////////////////////////////////////////////////////////// if (izquierdo == HIGH && derecho == LOW && pulsadores == "") { pulsadores="entrando"; inactivo=0; } if (izquierdo == LOW && derecho == HIGH && pulsadores == "") { pulsadores="saliendo"; inactivo=0; } if (izquierdo == HIGH && derecho == HIGH && pulsadores == "entrando") { pulsadores="entrando_medio"; //inactivo=0; } if (izquierdo == LOW && derecho == HIGH && pulsadores == "entrando_medio") { pulsadores="casi_entro"; //inactivo=0; } if (izquierdo == HIGH && derecho == HIGH && pulsadores == "saliendo") { pulsadores="saliendo_medio"; //inactivo=0; } if (izquierdo == HIGH && derecho == LOW && pulsadores == "saliendo_medio") { pulsadores="casi_salio"; //inactivo=0; } if (izquierdo == LOW && derecho == LOW && pulsadores == "casi_entro") { inactivo=0; pulsadores=""; cuenta=cuenta+1; Serial.print("Cuenta uno mas: "); Serial.println(cuenta); //Aca tendria que haber un delay para no contar demas, pero como enviar a influx tarda al menos un segundo, eso será el delay influx_send_entra_persona(); } if (izquierdo == LOW && derecho == LOW && pulsadores == "casi_salio") { inactivo=0; pulsadores=""; cuenta=cuenta-1; Serial.print("Cuenta uno menos: "); Serial.println(cuenta); //Aca tendria que haber un delay para no contar demas, pero como enviar a influx tarda al menos un segundo, eso será el delay influx_send_sale_persona(); } /////////////////////////////////////////////// inactivo++; if (inactivo > 150){ inactivo=0; pulsadores=""; } }
[ "joaquin.kpo.99@gmail.com" ]
joaquin.kpo.99@gmail.com
dcdcf09c821a7bb93281dc5814eff676ae2a3ec8
043226adf84531a160bb816f0926382f3e3f4a5c
/Lesson3/S00_enumclass.cc
d3c6d153a484433491a0ebd52d399f69f737a64a
[]
no_license
Akhil-Dalwadi/CPP
14ddba738bc39e771523a5d498be712d034db592
1f8030a39b6e7d9ed3038aee91d16be33c1af971
refs/heads/master
2022-02-16T10:56:40.302269
2018-10-19T16:40:23
2018-10-19T16:40:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
939
cc
// enum class: scoped enum // static_cast may be used to obtain the numeric value of the enumerator // Khuyến khích sử dụng enum class thay cho enum void Print_color(int color); enum Web_color { red = 0xFF0000, green = 0x00FF00, blue = 0x0000FF }; enum Product_info { Red = 0, Purple = 1, Blue = 2 }; Web_color webby = Web_color::blue; // Clearly at least one of these calls is buggy. Print_color(webby); Print_color(Product_info::Blue); // Instead use an enum class: void Print_color(int color); enum class Web_color { red = 0xFF0000, green = 0x00FF00, blue = 0x0000FF }; enum class Product_info { red = 0, purple = 1, blue = 2 }; Web_color webby = Web_color::blue; Print_color(webby); // Error: cannot convert Web_color to int. Print_color(Product_info::Red); // Error: cannot convert Product_info to int. int main () { int i = static_cast<int>(Product_info::Red); Product_info color = static_cast<Product_info>(1); }
[ "nguyen_bn@hotmail.com" ]
nguyen_bn@hotmail.com
b748af415cb3db3f0295401182355814e8537237
8cedb5e222372768ffc1c354b5a0414e0e0ffd41
/Implementation Files/Aarow.cpp
971992585e681ba5e4ecc4a4c0e652ca91678a61
[]
no_license
TuckerDane/2016_OSU_ComputerScience_II_Final_Project
f323bbc04dd0d70e75d17ffc1919a9bd462af99d
2225b0496ed3d4a41ff020a33c337f85bee2416e
refs/heads/master
2021-09-21T21:50:43.409056
2018-08-31T22:52:54
2018-08-31T22:52:54
101,434,320
1
0
null
null
null
null
UTF-8
C++
false
false
2,523
cpp
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Name: Tucker Dane Walker // // Date: 09 December 2016 // // Description: The Aarow Class // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include "Aarow.h" /*************************************************************************************************** ** default constructor for Aarow ***************************************************************************************************/ Aarow::Aarow() : Object(':', "Silver", 3, 3, "Aarow") { this->weight = 2; } /*************************************************************************************************** ** constructor for Aarow initializing rowPos and colPos ***************************************************************************************************/ Aarow::Aarow(int row, int col) : Object(':', "Generic", row, col, "Aarow") { weight = 2; } /*************************************************************************************************** ** deconstructor for Aarow ***************************************************************************************************/ Aarow::~Aarow() { } /*************************************************************************************************** ** sets its position ***************************************************************************************************/ void Aarow::setPosition(int row, int col) { this->setRowPos(row); this->setColPos(col); } /*************************************************************************************************** ** returns the weight of the object ***************************************************************************************************/ int Aarow::getWeight() { return weight; } /*************************************************************************************************** ** returns the name of the Object ***************************************************************************************************/ string Aarow::getName() { return name; } /*************************************************************************************************** ** returns the weight of the object ***************************************************************************************************/ void Aarow::setWeight(int w) { weight = w; }
[ "noreply@github.com" ]
TuckerDane.noreply@github.com
d31ecefcc8989797e2adc8d1256562a281df4c03
99ba2f9970f6045f5c5ab3a9499e404fb4010192
/并查集.cpp
6118c3c07d4520100e975aa4fdeb5a90e91cc363
[]
no_license
YichuanSun/template
f745eec87b15b260236b8222a37d8589fbe31b40
5b23bb494f0877a8f6d7b494a26a4eaf602b3953
refs/heads/master
2020-03-28T07:16:47.025613
2019-07-30T10:33:01
2019-07-30T10:33:01
147,891,695
1
0
null
null
null
null
GB18030
C++
false
false
1,682
cpp
//并查集,直接用日本人书上的代码也行 //设数组parent存放集合,parent[i]=j意为i的根节点为j //规定根节点处的元素值为负,它的相反数为该集合节点个数 #include <bits/stdc++.h> #define MAX_E 1005 #define N 1005 using namespace std; int parent[N]; void UFset(); //并查集初始化函数 int Find(int x); //查找函数 void Union(int R1,int R2); //将R1和R2所在集合合并 bool same(int a,int b); //判断a和b是否在同一个集合中 int main() { return 0; } //初始化 void UFset() { for (int i=0;i<n;i++) parent[i]=-1; } //查找并返回节点x所属集合的根节点 int Find(int x) { int s; for (s=x;parent[s]>=0;s=parent[s]); //不停循环直至找到集合的根节点s while (s!=x) { //路径压缩,将路径上的所有节点的根节点全都设为s int tmp=parent[x]; parent[x]=s; x=tmp; } return s; } // R1和R2是两个元素,属于两个不同的集合,现在合并这两个集合 void Union(int R1,int R2) { int r1=Find(R1),r2=Find(R2); //r1是R1的根节点,r2是R2的根节点 int tmp=parent[r1]+parent[r2]; //-tmp是合并后的集合的节点数 if (parent[r1]>parent[r2]) { //由于是负的,如果r1集合元素少于r2集合元素 parent[r1]=r2; //将r1合并到r2中 parent[r2]=tmp; //新集合元素为-tmp } else { //与上同理 parent[r2]=r1; parent[r1]=tmp; } } bool same(int a,int b) { if (Find(a)==Find(b)) return true; return false; }
[ "30886176+YichuanSun@users.noreply.github.com" ]
30886176+YichuanSun@users.noreply.github.com
a0a139167cdc9b1b906be0198d575701a6a57237
1f3dd4320acfafb283266491edfb6d571b6f0e50
/src/rpc/RpcContentWrapper.h
b8f0a206e9c3676168b322c88fcb4d9fb24cc482
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
erikmuttersbach/libhdfs3
d193c6b787b33f2339a8ff73ab4356ef835ca5d3
9a60d79812d6dee72455f61bff57a93c3c7d56f5
refs/heads/apache-rpc-9
2020-12-25T22:58:48.860681
2019-11-05T00:53:35
2019-11-05T00:53:35
27,222,933
42
25
Apache-2.0
2019-11-05T00:53:36
2014-11-27T11:42:59
C++
UTF-8
C++
false
false
1,807
h
/******************************************************************** * Copyright (c) 2013 - 2014, Pivotal Inc. * All rights reserved. * * Author: Zhanwei Wang ********************************************************************/ /******************************************************************** * 2014 - * open source under Apache License Version 2.0 ********************************************************************/ /** * 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. */ #ifndef _HDFS_LIBHDFS3_RPC_RPCCONTENTWRAPPER_H_ #define _HDFS_LIBHDFS3_RPC_RPCCONTENTWRAPPER_H_ #include <google/protobuf/message.h> #include "WriteBuffer.h" namespace Hdfs { namespace Internal { class RpcContentWrapper { public: RpcContentWrapper(::google::protobuf::Message * header, ::google::protobuf::Message * msg); int getLength(); void writeTo(WriteBuffer & buffer); public: ::google::protobuf::Message * header; ::google::protobuf::Message * msg; }; } } #endif /* _HDFS_LIBHDFS3_RPC_RPCCONTENTWRAPPER_H_ */
[ "zwang@gopivotal.com" ]
zwang@gopivotal.com
b29464a65c5569abd93a2d6a7a898c64ebbe812c
59b3f266dc5d06b7d70b84a005fe993c84d23592
/Ch 11.4/main.cpp
f7da4d615d2e89d644d6d4445b70ae953ae9cb7e
[]
no_license
ChrisAlexman27/Assignments
b77597ed6adbd64693f159dbeec7d1bd0502862e
9250d9c34ad2504a8b085dd8998789ffd6155b88
refs/heads/master
2021-07-16T18:39:09.905111
2017-10-21T07:11:18
2017-10-21T07:11:18
107,757,294
0
0
null
null
null
null
UTF-8
C++
false
false
9,094
cpp
//Christopher Alexman CSC 17A Chapter 11, P. 652, #04 // /******************************************************************************* * * STORE WEATHER DATA INTO AN STRUCTURE * _____________________________________________________________________________ * This function uses a structure to store weather data into an array of 12 * structures. It asks the user to enter data for each month and stores it in * each structure of the array. The input validation is that temp values are * between -100 and +140. Then it displays the average monthly rainfall, total * rainfall for the year, and the highest/lowest temperatures for the year. * * Computation is based on the formula: * * _____________________________________________________________________________ * INPUT * * * OUTPUT * * ******************************************************************************/ #include <iostream> #include <string> #include <iomanip> #include <cstdlib> using namespace std; struct Data { string month; //the name of the month float ttlRain; //total amount of rainfall float highTmp; //highest temperature float lowTmp; //lowest temperature float avgTemp; //average monthly temperature }; struct YrInfo { float totlPre; //total precipitate in a year float avgPpt; //average precipitate in a year float highPre; //highest amount of rainfall float lowPre; //lowest amount of rainfall string highMon; //month with highest precipitate string lowMon; //month with lowest precipitate float avgTYr; //average yearly temperature float hgstTem; //highest temperature of the year float lwstTem; //lowest temperature in the year }; void getData(Data [], const int); void avgTemp(Data [], YrInfo &, const int); void calcPer(Data[], YrInfo &, const int); void getPer(Data[], YrInfo &, const int); void disData(const Data [], const YrInfo &, const int); int main() { //create a constant for the size of the array const int MONTHS = 12; //create an array of structures, initialize the members to the month names Data mnthNms[MONTHS] = { { "JANUARY" }, { "FEBRUARY" }, { "MARCH" }, { "APRIL" }, { "MAY" }, { "JUNE" }, { "JULY" }, { "AUGUST" }, { "SEPTEMBER" }, { "OCTOBER" }, { "NOVEMBER" }, { "DECEMBER" } }; //definition of a structure variable, initialize all values to 0 //it is a holder structure YrInfo holder = { 0.0, 0.0, 0.0, 0.0, "\0", "\0", 0.0, 0.0, 0.0, }; //call the functions getData(mnthNms, MONTHS); avgTemp(mnthNms, holder, MONTHS); calcPer(mnthNms, holder, MONTHS); getPer(mnthNms, holder, MONTHS); disData(mnthNms, holder, MONTHS); return 0; } //****************************************************************************** // Definition of function getData // This function uses a for loop to get all of the various values for each of // the 12 months. It uses input validation to make sure the values are not // negative or outside the bounds. It receives a structure array and the // number of months as arguments. //****************************************************************************** void getData(Data mnthNms[], const int MONTHS) { //use a for loop to get the data for each month, one at a time for (int count = 0; count < MONTHS; count++) { cout << "Enter data for " << mnthNms[count].month; cout << "\n----------------------------"; cout << "\n\nAmount of rainfall" << ": "; cin >> mnthNms[count].ttlRain; //input validation, will not accept negative values while (mnthNms[count].ttlRain < 0) { cout << "ERROR. No negative values."; cout << "\n\nAmount of rainfall" << ": "; cin >> mnthNms[count].ttlRain; } cout << "Highest temperature" << ": "; cin >> mnthNms[count].highTmp; //input validation, temperature cannot be outside these values while (mnthNms[count].highTmp < -100 || mnthNms[count].highTmp > 140) { cout << "ERROR. Temperatures cannot be above +140F or below -100F "; cout << "Highest temperature" << ": "; cin >> mnthNms[count].highTmp; } cout << "Lowest temperature" << ": "; cin >> mnthNms[count].lowTmp; while (mnthNms[count].lowTmp < -100 || mnthNms[count].lowTmp > 140) { cout << "ERROR. Temperatures cannot be above +140F or below -100F "; cout << "Lowest temperature" << ": "; cin >> mnthNms[count].lowTmp; } cout << endl << endl; } } //****************************************************************************** // Definition of function avgTemp // This function uses a for loop to step through all of the values given for // the year and sums them up with the holder variable. //****************************************************************************** void avgTemp(Data mnthNms[], YrInfo &holder, const int MONTHS) { for (int index = 0; index < MONTHS; index++) { mnthNms[index].avgTemp = (mnthNms[index].highTmp + mnthNms[index].lowTmp) / 2; holder.avgTYr += mnthNms[index].lowTmp + mnthNms[index].highTmp; } holder.avgTYr /= 24; } //****************************************************************************** // Definition of function calcPer // This function uses an array of structures and the holder reference variable // in order to calculate the precipitate amounts. //****************************************************************************** void calcPer(Data mnthNms[], YrInfo &holder, const int MONTHS) { for (int index = 0; index < MONTHS; index++) { holder.totlPre += mnthNms[index].ttlRain; holder.avgPpt = holder.totlPre / 12; } } //****************************************************************************** // Definition of function getPer // This function uses an array of structures and the holder reference variable // to figure out which months have the lowest and highest rainfall values. //****************************************************************************** void getPer(Data mnthNms[], YrInfo &holder, const int MONTHS) { holder.highPre = mnthNms[0].ttlRain; holder.lowPre = mnthNms[0].ttlRain; for (int index = 0; index < MONTHS; index++) { if (mnthNms[index].ttlRain <= holder.lowPre) { holder.lowPre = mnthNms[index].ttlRain; holder.lowMon = mnthNms[index].month; } if (mnthNms[index].ttlRain >= holder.highPre) { holder.highPre = mnthNms[index].ttlRain; holder.highMon = mnthNms[index].month; } } } //****************************************************************************** // Definition of function disData // This function displays and formats all of the data using an array of // structures and the holder reference variable. //****************************************************************************** void disData(const Data metData[], const YrInfo &holder, const int MONTHS) { cout << setw(9) << left << "MONTH NAME"; cout << setw(19) << right << "Rainfall Amount"; cout << setw(20) << right << "Highest Temp"; cout << setw(20) << right << "Lowest Temp"; cout << setw(20) << right << "Average Temp" << "\n"; //format for the rest of the output cout << fixed << showpoint << setprecision(2); for (int count = 0; count < MONTHS; count++) { cout << setw(9) << left; cout << metData[count].month; cout << setw(20) << right << metData[count].ttlRain; cout << setw(20) << right << metData[count].highTmp; cout << setw(20) << right << metData[count].lowTmp; cout << setw(20) << right << metData[count].avgTemp; cout << endl; } cout << endl << endl; cout << "Total rainfall: "; cout << holder.totlPre << " mm"; cout << "\nAverage rainfall: "; cout << holder.avgPpt << " mm"; cout << "\n\nMonth with highest rainfall: "; cout << holder.highMon; cout << "\nHighest recorded rainfall: "; cout << holder.highPre << " mm"; cout << "\n\nMonth with lowest rainfall: "; cout << holder.lowMon; cout << "\nLowest recorded rainfall: "; cout << holder.lowPre << " mm" << "\n"; cout << "\nAverage of all monthly average temperatures: "; cout << holder.avgTYr << " F"; }
[ "noreply@github.com" ]
ChrisAlexman27.noreply@github.com
e90a27aee4335180a62ebd20ac373c6d6a092f5f
0b79cf40da1c8ef55fabc70e0e2534d7dfe21a1a
/Src/mainwindow.h
a0bccb84aee50637091e24955cafd10f4ab81199
[]
no_license
DaLinYYY/MyQtWork
c141db0cbb8b0c77bc8e0b6c703fe1edf6a3a8d4
60f8ba1f4149d5b91edca6ee8d889cab02c657c3
refs/heads/master
2022-12-26T07:10:23.712309
2020-09-25T08:18:24
2020-09-25T08:18:24
297,289,295
0
0
null
null
null
null
UTF-8
C++
false
false
1,802
h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include "mytimer.h" #include "chartview.h" #include <QMainWindow> #include "recvthread.h" #include <QTimer> #include <QtSerialPort/QSerialPort> #include <QtSerialPort/QSerialPortInfo> #include <QtCharts/QChart> #include <QtCharts/QDateTimeAxis> #include <QtCharts/QChartView> #include <QtCharts/QLineSeries> #include <QtCharts/QValueAxis> QT_CHARTS_USE_NAMESPACE #define UPDATE_SHOW_TIME 10 #define COM_REFRESH_TIME 100 QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE enum PORT_CHANGE_STATUS{ NOT_CHANGE, ADD_ITEM, MINUS_ITEM, ADD_TIEM_ALL, MINUS_TIEM_ALL }; typedef struct{ QStringList ComName; QStringList Description; QStringList Manufacturer; int PortChangeStatus; }mPortList; class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); private: void initUi(); void initSlot(); void initChartUi(); mPortList* CheckPortListDif(mPortList *newList, mPortList *oldList); void wheelEvent(QWheelEvent *event); private: Ui::MainWindow *ui; QSerialPort *mySerialPort; QSerialPortInfo *mySerialInfo; QTimer *timer; QTimer *timerShow; mPortList *newPortStringList; mPortList *oldPortStringList; bool btnOpenIsOpen; bool btnSendIsSend; recvthread * myrecvThread; recvthread * mysendThread; unsigned int recvBytes; unsigned int sendBytes; quint16 count; // ChartView *chartView; ChartView *chartView; QChart *m_chart; QValueAxis *m_axisX; QValueAxis *m_axisY; QLineSeries *m_series,*series; private slots: void on_btnOpen_clicked(); void updateComShow(); void updateData(); }; #endif // MAINWINDOW_H
[ "dalinyy@163.com" ]
dalinyy@163.com
62a0d0bc860c815de91a8d642f7aeb2a77e0a551
820489b64b7c787643a1e803db968c9b0a7b2e8f
/EstructuraDeDatos/Actividad04-PilaYCola/model/dto/Pila.h
f97f2d061f5849a7b14c8050981be959e6f482ae
[]
no_license
Norzuiso/University
2ad452cd4fd85ee8062b56fe6bb7f0da8fa10427
3616aa385c9534e736cb5c3633983346adb3fb09
refs/heads/main
2023-08-01T06:04:34.047520
2021-09-17T02:45:09
2021-09-17T02:45:09
360,977,796
0
0
null
2021-05-22T21:29:06
2021-04-23T18:48:57
C
UTF-8
C++
false
false
1,122
h
// // Created by josue on 9/5/2021. // #ifndef ACTIVIDAD04_PILAYCOLA_PILA_H #define ACTIVIDAD04_PILAYCOLA_PILA_H #include "../../logic/utils/Utils.h" template<class T, int size = 1024> class Pila { private: T data[size]; int top; private: Pila(); bool isEmpty(); bool isFull(); void push(T value); T pop(); T getTop(); }; template<class T, int size> Pila<T, size>::Pila() { top = -1; } template<class T, int size> bool Pila<T, size>::isEmpty() { return top == -1; } template<class T, int size> bool Pila<T, size>::isFull() { return top == size - 1; } template<class T, int size> void Pila<T, size>::push(T value) { Utils::isTrueThrowException(isEmpty(), "Desbordamiento de datos"); data[++top] = value; } template<class T, int size> T Pila<T, size>::pop() { Utils::isTrueThrowException(isEmpty(), "La pila se encuentra vacia "); return data[top--]; } template<class T, int size> T Pila<T, size>::getTop() { Utils::isTrueThrowException(isEmpty(), "La pila se encuentra vacia "); return data[top]; } #endif //ACTIVIDAD04_PILAYCOLA_PILA_H
[ "josueaguilarjnai@gmail.com" ]
josueaguilarjnai@gmail.com
ad15bb99845600e0f1a99531aaf530f03d7107a0
49874e38e315b06cc6880bacb5d0fef20380629e
/src/qt/splashscreen.cpp
0b45263d327884035ea99c8889ebb68c72ab5c89
[ "MIT" ]
permissive
viduedo/danscoin
91b38e0cfaa282a9a2ce1d7250d3a2f7a6c690ae
1860cf5586851ff6a676e7dacf60396bf2e04da1
refs/heads/master
2020-03-11T12:55:35.193088
2018-04-18T22:29:46
2018-04-18T22:29:46
129,997,720
0
0
null
null
null
null
UTF-8
C++
false
false
2,254
cpp
// Copyright (c) 2011-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "splashscreen.h" #include "clientversion.h" #include "util.h" #include <QPainter> #undef loop /* ugh, remove this when the #define loop is gone from util.h */ #include <QApplication> SplashScreen::SplashScreen(const QPixmap &pixmap, Qt::WindowFlags f) : QSplashScreen(pixmap, f) { // set reference point, paddings int paddingLeftCol2 = 230; int paddingTopCol2 = 376; int line1 = 0; int line2 = 13; int line3 = 26; int line4 = 39; float fontFactor = 1.0; // define text to place QString titleText = QString(QApplication::applicationName()).replace(QString("-testnet"), QString(""), Qt::CaseSensitive); // cut of testnet, place it as single object further down QString versionText = QString("Version %1 ").arg(QString::fromStdString(FormatFullVersion())); QString copyrightText1 = QChar(0xA9)+QString(" 2009-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Bitcoin developers")); QString copyrightText2 = QChar(0xA9)+QString(" 2011-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Litecoin developers")); QString copyrightText3 = QChar(0xA9)+QString(" %1 ").arg(2018) + QString(tr("The Dan$coin developers")); QString font = "Arial"; // load the bitmap for writing some text over it QPixmap newPixmap; if(GetBoolArg("-testnet")) { newPixmap = QPixmap(":/images/splash_testnet"); } else { newPixmap = QPixmap(":/images/splash"); } QPainter pixPaint(&newPixmap); pixPaint.setPen(QColor(70,70,70)); pixPaint.setFont(QFont(font, 9*fontFactor)); pixPaint.drawText(paddingLeftCol2,paddingTopCol2+line4,versionText); // draw copyright stuff pixPaint.setFont(QFont(font, 9*fontFactor)); pixPaint.drawText(paddingLeftCol2,paddingTopCol2+line1,copyrightText1); pixPaint.drawText(paddingLeftCol2,paddingTopCol2+line2,copyrightText2); pixPaint.drawText(paddingLeftCol2,paddingTopCol2+line3,copyrightText3); pixPaint.end(); this->setPixmap(newPixmap); }
[ "daniel.viduedo@gmail.com" ]
daniel.viduedo@gmail.com
a2e7a7c812c6a24d453dee4b6166facd7558c9c9
783279f7d64424fd4535a819cc19be335a3ce196
/codeforces/735Div2/D.cpp
297552134d313de281f2b9f7537b39323b056120
[]
no_license
rish-singhal/CompetitiveProgramming
2bfa88e086c084c9d68624f176ee3cbcb20b8577
5ed290ea7e28b81e38679f8c0e99c9c3f80da231
refs/heads/master
2023-07-02T18:59:11.817298
2021-08-10T04:15:52
2021-08-10T04:15:52
248,025,974
2
0
null
null
null
null
UTF-8
C++
false
false
922
cpp
#include<bits/stdc++.h> using namespace std; typedef long long LL; typedef vector<int> vi; typedef vector<vi> vii; #define fi first #define se second #define pb push_back #define forn(i,n) for(int i=0;i<(n);i++) #define for1(i,n) for(int i=1;i<=n;i++) #define forr(i,n) for(int i=n;i>=0;i--) #define all(x) x.begin(), x.end() #define sz(x) ((int)x.size()) const int MAXN = 1e5 +5; void fio(){ ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); } int main(){ fio(); int t; cin >> t; while(t--) { int n; cin >> n; if(n == 1) { cout << "a" << endl; continue; } string ans; if((n % 2) == 0) { forn(i, (n/2)) { ans += "a"; } ans += "b"; forn(i, ((n/2) - 1)) { ans += "a"; } } else { n--; forn(i, (n/2)) { ans += "a"; } ans += "bc"; forn(i, ((n/2) - 1)) { ans += "a"; } } cout << ans << endl; } return 0; }
[ "zzxy334@gmail.com" ]
zzxy334@gmail.com
1b6ef365058920a28a30b50b749ddfcef3447da3
8c3c4f9fbd5682097c1e8b8f2bff77dabd3745de
/2131Z - CtrlZV4 - PROS/include/Custom/Intake.hpp
3661bcebacd2a66d02ff2310c351bfc71605e6d6
[]
no_license
Go-Line-Track-Yourself/Z-Team-Repository
d010cf347eff1696ff2d11ffabb91aeb0b18ef80
5a0532df7d14a887435308f01f880f0ef41ce36b
refs/heads/master
2020-04-01T03:13:54.965322
2019-04-22T15:14:42
2019-04-22T15:14:42
152,814,629
0
0
null
null
null
null
UTF-8
C++
false
false
569
hpp
#ifndef INTAKE_HPP #define INTAKE_HPP namespace Intake{ bool AutoIntakeEnabled; bool AutoIntakeTaskEnabled; bool AutoIntakeOff; bool AutoFlip; bool IntakeEnabledBtnPressed; bool IntakeEnabledInverted; //SetMotors void SetIntakerPower(int power); void SetTFeederPower(int power); //User void IntakeVoid(); void AutoIntakeCont(); //Autonomous void AutonIntk(bool ON, bool In); void AutonBelt(bool ON, bool In); void Auto_Intake(); int Auto_Intaking(); } #endif /* end of include guard: INTAKE.HPP */
[ "legocreator75@gmail.com" ]
legocreator75@gmail.com
02435f651927b469e0b26a884897909186dc5257
a03a00fec769762293702a70ede77393230857e0
/120-Stacks of Flapjacks/120.cpp
00c71d081e018ec4f2f5b5e5223647818d1e4a2f
[]
no_license
chiaminchuang/UVA
75eb1f44ae463e6755405161f5eac19e6ea0e9f9
574dc1970fbcc7b3f893ad9fd48bb0abe8bb34fd
refs/heads/master
2021-09-05T13:16:32.286561
2018-01-28T02:06:29
2018-01-28T02:06:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
863
cpp
#include <iostream> #include <string> #include <sstream> #include <vector> #include <algorithm> using namespace std; void flip(vector<int>&, int, int); int main(){ string str; while (getline(cin, str)) { stringstream ss(str); vector<int> stack; int jack, i = 0; while (ss >> jack) stack.push_back(jack); for (int i = 0; i < stack.size(); ++i) cout << stack[i] << " "; cout << endl; while (!is_sorted(stack.begin(), stack.end())) { int n = max_element(stack.begin(), stack.end() - i) - stack.begin(); flip(stack, n, i++); } cout << 0 << endl; } return 0; } void flip(vector<int> &stack, int n, int i) { if (n != 0) { reverse(stack.begin(), stack.begin() + n + 1); cout << stack.size() - n << " "; } reverse(stack.begin(), stack.end() - i); cout << i + 1 << " "; }
[ "noreply@github.com" ]
chiaminchuang.noreply@github.com
8f726411c9d2d908f741b4a319192de3d433c347
c21c8cba94f4f73aa23de98e555ef77bcab494f0
/HackerEarth/pair count.cpp
bd534025e1c6f439317d2102d10355254fa6ae34
[]
no_license
hoatd/Ds-Algos-
fc3ed0c8c1b285fb558f53eeeaea2632e0ed03ae
1e74995433685f32ce75a036cd82460605024c49
refs/heads/master
2023-03-19T05:48:42.595330
2019-04-29T06:20:43
2019-04-29T06:20:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,451
cpp
#include<bits/stdc++.h> #define ff first #define ss second #define mp make_pair #define ll long long #define max3(a,b,c) max(a, max(b,c)) #define max4(a,b,c,d) max(a, max(b, max(c,d))) #define pb push_back #define si(x) scanf("%d",&x) #define slli(x) scanf("%lld",&x) #define pi(x) printf("%d",x) #define sp() putchar(' ') #define nl() putchar('\n') #define fck std::ios::sync_with_stdio(false); #define mx5 100010 #define mx6 1000010 #define mod 1000000007 using namespace std; #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> #include <ext/pb_ds/detail/standard_policies.hpp> #define ordered_set tree<int,null_type,less<int>,rb_tree_tag,tree_order_statistics_node_update> using namespace __gnu_pbds; ll arr[mx5]; int main() { fck; ll t,n,k,m,pi,tij,ko; cin>>t; while(t--) { cin>>n>>k>>m; for(int i=0;i<n;i++){ cin>>arr[i]; } ll ans=LLONG_MAX,tmp; int index; for(int i=0; i<n; i++) { tmp=0LL; ll p=arr[i]; for(int j=0;j<p;j++) { cin>>tij; tmp += tij; } tmp += ( k*arr[i] + m*(arr[i]-1) ); //cout<<tmp<<endl; if(ans > tmp){ ans = tmp; index = i+1; } } cout<<index<<" "<<ans<<endl; } return 0; }
[ "noreply@github.com" ]
hoatd.noreply@github.com
cba4e74bba00d0093c2fab1f92fd0d5a56dd2a55
b9023bd137b0cba5895717ab79ee53d40b813c0c
/BarRevenueSimulation/main.cpp
e103802556a80600f6073b21ae38f27fcdf1bdbf
[]
no_license
dinobertoli/CSCI61-Data-Structrures-and-Algorithms
64fdeec3ec3ffac3dcd918ed4f70220dd1797456
13fdfe1994b05748914b55032206e64167388bd3
refs/heads/master
2021-06-21T21:27:22.825243
2021-02-07T06:41:55
2021-02-07T06:41:55
181,377,414
0
0
null
null
null
null
UTF-8
C++
false
false
856
cpp
#include <iostream> #include "arriveEvent.h" /* *Discrete Event-Driven Simulation *Project 2 *Dino Bertoli *6/1/19 * *simulates profit of softwareGurusBar with given input for seats * */ int main( ) { srand(time(0)); ofstream file; file.open ("output.txt"); // load priority queue with initial arrive Events then run simulation unsigned int t = 0; // load 4 hours (240 minutes) of arrive Events while (t < 240) { // new group every 2-5 minutes t += randBetween(2,5); // group size ranges from 1 to 5 unsigned int randomSize = randBetween(1,5); theSimulation.scheduleEvent(new arriveEvent(t, randomSize)); } // then run simulation and print profits theSimulation.run( ); cout << "Total profits " << theBar.profit << endl; file << "Total profits " << theBar.profit << endl; return 0; file.close(); }
[ "noreply@github.com" ]
dinobertoli.noreply@github.com
5b9f6c039910b0d31fbce605f81d81c360d3e417
a9d2c5b679a7f565e2de9105c610c26d54073d56
/ResourceAssignment.h
727528e0a02365df59e2af778103df11d272c274
[]
no_license
mt1ger/SimEON
e9fa8a3c656e5f968eb074090b4ea33cb9d06840
93b24438c07b23d378d9b6f0c22a6550ff070439
refs/heads/master
2021-09-05T20:16:11.458277
2018-01-30T20:43:55
2018-01-30T20:43:55
108,190,901
0
0
null
null
null
null
UTF-8
C++
false
false
772
h
#ifndef _RESOURCEASSIGNMENT_H #define _RESOURCEASSIGNMENT_H #include "Event.h" #include "EventQueue.h" #include "RoutingTable.h" class ResourceAssignment { public: ResourceAssignment (Network * net, EventQueue * eq) {network = net; eventQueue = eq;} ~ResourceAssignment () {} vector< vector<int> > SourceAvailableSections; void handle_requests (CircuitRequest * circuitRequest); void handle_releases (CircuitRelease * circuitRelease); void check_availability_source (unsigned int predecessor, unsigned int successor, CircuitRequest * circuitRequest); void check_availability_link (unsigned int predecessor, unsigned int successor, int i, bool * AvailableFlag, int * TempLocation); private: Network * network; EventQueue * eventQueue; }; #endif
[ "Yue_Wang@student.uml.edu" ]
Yue_Wang@student.uml.edu
28d0745995f9c717cd61561d9f10f76ecd467ff2
fdfb3b2257a91fc0c142189c568f1181b6baff82
/ethercat_generic_plugins/ethercat_generic_cia402_drive/test/test_generic_ec_cia402_drive.hpp
ad123ff9866253d9c564ab8adec45e2b41902fe2
[ "Apache-2.0" ]
permissive
ICube-Robotics/ethercat_driver_ros2
0ca3362b5d63a56df430d752b79913da3ac7b559
3ccdb0dd7aa747fb0173390769876bbb4b9587ee
refs/heads/main
2023-08-10T12:13:48.823357
2023-07-28T07:41:39
2023-07-28T07:41:39
491,930,126
86
22
Apache-2.0
2023-07-25T12:56:05
2022-05-13T14:30:53
C++
UTF-8
C++
false
false
1,803
hpp
// Copyright 2023 ICUBE Laboratory, University of Strasbourg // // 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 TEST_GENERIC_EC_CIA402_DRIVE_HPP_ #define TEST_GENERIC_EC_CIA402_DRIVE_HPP_ #include <memory> #include <string> #include <vector> #include <unordered_map> #include "gmock/gmock.h" #include "ethercat_generic_plugins/generic_ec_cia402_drive.hpp" // subclassing and friending so we can access member variables class FriendEcCiA402Drive : public ethercat_generic_plugins::EcCiA402Drive { FRIEND_TEST(EcCiA402DriveTest, SlaveSetupDriveFromConfig); FRIEND_TEST(EcCiA402DriveTest, SlaveSetupPdoChannels); FRIEND_TEST(EcCiA402DriveTest, SlaveSetupSyncs); FRIEND_TEST(EcCiA402DriveTest, SlaveSetupDomains); FRIEND_TEST(EcCiA402DriveTest, EcReadTPDOToStateInterface); FRIEND_TEST(EcCiA402DriveTest, EcWriteRPDOFromCommandInterface); FRIEND_TEST(EcCiA402DriveTest, EcWriteRPDODefaultValue); // FRIEND_TEST(EcCiA402DriveTest, FaultReset); FRIEND_TEST(EcCiA402DriveTest, SwitchModeOfOperation); FRIEND_TEST(EcCiA402DriveTest, EcWriteDefaultTargetPosition); }; class EcCiA402DriveTest : public ::testing::Test { public: void SetUp(); void TearDown(); protected: std::unique_ptr<FriendEcCiA402Drive> plugin_; }; #endif // TEST_GENERIC_EC_CIA402_DRIVE_HPP_
[ "noreply@github.com" ]
ICube-Robotics.noreply@github.com
45599517c4f36f474c198f8033ffc2715ae493ee
ddec21c31c705046a27b1fa155eee83ac7f198a6
/project-assignment-1/code-problem/3.Labyrinth-CPP/Labyrinth-CPP/Cursor.cpp
9178ce939411173e0baf5fb127a739390e5cf2de
[ "MIT", "CC-BY-3.0" ]
permissive
Lilleengen/INF3121-Project-assignments-spring-2016
7381865b545d01df6c3920743c2717b905471633
bd44bf16c4e321fc379fc77ea14e7677b4b171f2
refs/heads/master
2021-01-01T04:55:32.384373
2016-05-11T09:59:19
2016-05-11T09:59:19
58,267,817
0
0
null
null
null
null
UTF-8
C++
false
false
990
cpp
#include "Cursor.h" #include <iostream> Cursor::Cursor( const Position & position ) : position( position ), movements( 0 ) { } bool Cursor::move( const Direction & direction, Playfield & playfield ) { this->movements ++; Position newPosition( this->position ); switch ( direction ) { case IMoveable::DIRECTION_LEFT: newPosition.x --; break; case IMoveable::DIRECTION_UP: newPosition.y --; break; case IMoveable::DIRECTION_RIGHT: newPosition.x ++; break; case IMoveable::DIRECTION_DOWN: newPosition.y ++; break; default: std::cerr << "Invalid direction!" << std::endl; } Cell * cell = playfield.getCell( newPosition ); bool successfulMove = cell->canGo(); if( successfulMove ) { this->position = newPosition; } return successfulMove; } Position Cursor::getPosition( void ) const { return this->position; } int Cursor::getMovements( void ) { return this->movements; }
[ "mail@ithenrik.com" ]
mail@ithenrik.com
500e3ea3f9e78d440d2430c49c613b59aff2e159
1c7cb3154854a0d5f628c4285aa209affd8d2fc9
/chaos-ns-3/ns-3.27/src/core/model/simulator.cc
d2e08d0ec1a0b095a1cef98ec49772affa2ab05f
[ "GPL-2.0-only", "LicenseRef-scancode-free-unknown", "MIT" ]
permissive
ErikNatanael/royal-chaos
fac8e5891044490cd2e61b7367f284d99951d0d1
a8e763d3720cc3e158e98143cabce8106d8de2aa
refs/heads/master
2022-07-16T12:21:31.494237
2020-05-12T12:50:08
2020-05-12T12:50:08
263,333,134
0
0
MIT
2020-05-12T12:42:08
2020-05-12T12:42:08
null
UTF-8
C++
false
false
10,249
cc
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2005,2006 INRIA * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * 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 * * Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr> */ #include "ns3/core-config.h" #include "simulator.h" #include "simulator-impl.h" #include "scheduler.h" #include "map-scheduler.h" #include "event-impl.h" #include "des-metrics.h" #include "ptr.h" #include "string.h" #include "object-factory.h" #include "global-value.h" #include "assert.h" #include "log.h" #include <cmath> #include <fstream> #include <list> #include <vector> #include <iostream> #include <iomanip> /** * \file * \ingroup simulator * ns3::Simulator implementation, as well as implementation pointer, * global scheduler implementation, and default ns3::NodePrinter * and ns3::TimePrinter. */ namespace ns3 { // Note: Logging in this file is largely avoided due to the // number of calls that are made to these functions and the possibility // of causing recursions leading to stack overflow NS_LOG_COMPONENT_DEFINE ("Simulator"); /** * \ingroup simulator * The specific simulator implementation to use. * * Must be derived from SimulatorImpl. */ static GlobalValue g_simTypeImpl = GlobalValue ("SimulatorImplementationType", "The object class to use as the simulator implementation", StringValue ("ns3::DefaultSimulatorImpl"), MakeStringChecker ()); /** * \ingroup scheduler * The specific event scheduler implementation to use. * * Must be derived from Scheduler. */ static GlobalValue g_schedTypeImpl = GlobalValue ("SchedulerType", "The object class to use as the scheduler implementation", TypeIdValue (MapScheduler::GetTypeId ()), MakeTypeIdChecker ()); /** * \ingroup logging * Default TimePrinter implementation. * * \param [in,out] os The output stream to print the time on. */ static void TimePrinter (std::ostream &os) { std::ios_base::fmtflags ff = os.flags (); // Save stream flags std::streamsize oldPrecision = os.precision (); if (Time::GetResolution () == Time::NS) { os << std::fixed << std::setprecision (9) << Simulator::Now ().As (Time::S); } else if (Time::GetResolution () == Time::PS) { os << std::fixed << std::setprecision (12) << Simulator::Now ().As (Time::S); } else if (Time::GetResolution () == Time::FS) { os << std::fixed << std::setprecision (15) << Simulator::Now ().As (Time::S); } else if (Time::GetResolution () == Time::US) { os << std::fixed << std::setprecision (6) << Simulator::Now ().As (Time::S); } else { // default C++ precision of 5 os << std::fixed << std::setprecision (5) << Simulator::Now ().As (Time::S); } os << std::setprecision (oldPrecision); os.flags (ff); // Restore stream flags } /** * \ingroup logging * Default node id printer implementation. * * \param [in,out] os The output stream to print the node id on. */ static void NodePrinter (std::ostream &os) { if (Simulator::GetContext () == Simulator::NO_CONTEXT) { os << "-1"; } else { os << Simulator::GetContext (); } } /** * \ingroup simulator * \brief Get the static SimulatorImpl instance. * \return The SimulatorImpl instance pointer. */ static SimulatorImpl **PeekImpl (void) { static SimulatorImpl *impl = 0; return &impl; } /** * \ingroup simulator * \brief Get the SimulatorImpl singleton. * \return The singleton pointer. * \see Simulator::GetImplementation() */ static SimulatorImpl * GetImpl (void) { SimulatorImpl **pimpl = PeekImpl (); /* Please, don't include any calls to logging macros in this function * or pay the price, that is, stack explosions. */ if (*pimpl == 0) { { ObjectFactory factory; StringValue s; g_simTypeImpl.GetValue (s); factory.SetTypeId (s.Get ()); *pimpl = GetPointer (factory.Create<SimulatorImpl> ()); } { ObjectFactory factory; StringValue s; g_schedTypeImpl.GetValue (s); factory.SetTypeId (s.Get ()); (*pimpl)->SetScheduler (factory); } // // Note: we call LogSetTimePrinter _after_ creating the implementation // object because the act of creation can trigger calls to the logging // framework which would call the TimePrinter function which would call // Simulator::Now which would call Simulator::GetImpl, and, thus, get us // in an infinite recursion until the stack explodes. // LogSetTimePrinter (&TimePrinter); LogSetNodePrinter (&NodePrinter); } return *pimpl; } void Simulator::Destroy (void) { NS_LOG_FUNCTION_NOARGS (); SimulatorImpl **pimpl = PeekImpl (); if (*pimpl == 0) { return; } /* Note: we have to call LogSetTimePrinter (0) below because if we do not do * this, and restart a simulation after this call to Destroy, (which is * legal), Simulator::GetImpl will trigger again an infinite recursion until * the stack explodes. */ LogSetTimePrinter (0); LogSetNodePrinter (0); (*pimpl)->Destroy (); (*pimpl)->Unref (); *pimpl = 0; } void Simulator::SetScheduler (ObjectFactory schedulerFactory) { NS_LOG_FUNCTION (schedulerFactory); GetImpl ()->SetScheduler (schedulerFactory); } bool Simulator::IsFinished (void) { NS_LOG_FUNCTION_NOARGS (); return GetImpl ()->IsFinished (); } void Simulator::Run (void) { NS_LOG_FUNCTION_NOARGS (); Time::ClearMarkedTimes (); GetImpl ()->Run (); } void Simulator::Stop (void) { NS_LOG_FUNCTION_NOARGS (); NS_LOG_LOGIC ("stop"); GetImpl ()->Stop (); } void Simulator::Stop (Time const &delay) { NS_LOG_FUNCTION (delay); GetImpl ()->Stop (delay); } Time Simulator::Now (void) { /* Please, don't include any calls to logging macros in this function * or pay the price, that is, stack explosions. */ return GetImpl ()->Now (); } Time Simulator::GetDelayLeft (const EventId &id) { NS_LOG_FUNCTION (&id); return GetImpl ()->GetDelayLeft (id); } EventId Simulator::Schedule (Time const &delay, const Ptr<EventImpl> &event) { return DoSchedule (delay, GetPointer (event)); } EventId Simulator::ScheduleNow (const Ptr<EventImpl> &ev) { return DoScheduleNow (GetPointer (ev)); } void Simulator::ScheduleWithContext (uint32_t context, const Time &delay, EventImpl *impl) { #ifdef ENABLE_DES_METRICS DesMetrics::Get ()->TraceWithContext (context, Now (), delay); #endif return GetImpl ()->ScheduleWithContext (context, delay, impl); } EventId Simulator::ScheduleDestroy (const Ptr<EventImpl> &ev) { return DoScheduleDestroy (GetPointer (ev)); } EventId Simulator::DoSchedule (Time const &time, EventImpl *impl) { #ifdef ENABLE_DES_METRICS DesMetrics::Get ()->Trace (Now (), time); #endif return GetImpl ()->Schedule (time, impl); } EventId Simulator::DoScheduleNow (EventImpl *impl) { #ifdef ENABLE_DES_METRICS DesMetrics::Get ()->Trace (Now (), Time (0)); #endif return GetImpl ()->ScheduleNow (impl); } EventId Simulator::DoScheduleDestroy (EventImpl *impl) { return GetImpl ()->ScheduleDestroy (impl); } EventId Simulator::Schedule (Time const &delay, void (*f)(void)) { return DoSchedule (delay, MakeEvent (f)); } void Simulator::ScheduleWithContext (uint32_t context, Time const &delay, void (*f)(void)) { return ScheduleWithContext (context, delay, MakeEvent (f)); } EventId Simulator::ScheduleNow (void (*f)(void)) { return DoScheduleNow (MakeEvent (f)); } EventId Simulator::ScheduleDestroy (void (*f)(void)) { return DoScheduleDestroy (MakeEvent (f)); } void Simulator::Remove (const EventId &id) { if (*PeekImpl () == 0) { return; } return GetImpl ()->Remove (id); } void Simulator::Cancel (const EventId &id) { if (*PeekImpl () == 0) { return; } return GetImpl ()->Cancel (id); } bool Simulator::IsExpired (const EventId &id) { if (*PeekImpl () == 0) { return true; } return GetImpl ()->IsExpired (id); } Time Now (void) { return Time (Simulator::Now ()); } Time Simulator::GetMaximumSimulationTime (void) { NS_LOG_FUNCTION_NOARGS (); return GetImpl ()->GetMaximumSimulationTime (); } uint32_t Simulator::GetContext (void) { return GetImpl ()->GetContext (); } uint32_t Simulator::GetSystemId (void) { NS_LOG_FUNCTION_NOARGS (); if (*PeekImpl () != 0) { return GetImpl ()->GetSystemId (); } else { return 0; } } void Simulator::SetImplementation (Ptr<SimulatorImpl> impl) { NS_LOG_FUNCTION (impl); if (*PeekImpl () != 0) { NS_FATAL_ERROR ("It is not possible to set the implementation after calling any Simulator:: function. Call Simulator::SetImplementation earlier or after Simulator::Destroy."); } *PeekImpl () = GetPointer (impl); // Set the default scheduler ObjectFactory factory; StringValue s; g_schedTypeImpl.GetValue (s); factory.SetTypeId (s.Get ()); impl->SetScheduler (factory); // // Note: we call LogSetTimePrinter _after_ creating the implementation // object because the act of creation can trigger calls to the logging // framework which would call the TimePrinter function which would call // Simulator::Now which would call Simulator::GetImpl, and, thus, get us // in an infinite recursion until the stack explodes. // LogSetTimePrinter (&TimePrinter); LogSetNodePrinter (&NodePrinter); } Ptr<SimulatorImpl> Simulator::GetImplementation (void) { NS_LOG_FUNCTION_NOARGS (); return GetImpl (); } } // namespace ns3
[ "zhanglong3030@qq.com" ]
zhanglong3030@qq.com
ef606ea70c3c0d729a30369eca3f053f3e401b31
07cdc852789922612460a6145144955b6d76c504
/MapEditCreate.h
fecbcb1841e975e127fc1b5c1f1d769cd814c9c3
[]
no_license
WooLyung/Lightcuit
9379b8d2c3f412c0e71e853b6cf5116b53f5e704
37455456318d8dfaf350a2bb5fe61a87f3315b78
refs/heads/master
2020-08-29T00:08:57.369134
2019-12-24T01:11:33
2019-12-24T01:11:33
217,859,728
1
0
null
null
null
null
UTF-8
C++
false
false
652
h
#pragma once #include "Object.h" #include "Transform.h" #include "SpriteRenderer.h" #include "CommandList.h" #include "MapEditorScene.h" class MapEditorScene; class MapEditCreate : public Object { private: enum StageState { appear, wait, disappear, wait2 }; Transform* transform; SpriteRenderer* spriteRenderer; MapEditorScene* scene; StageState state = appear; // animations float animTime = 0; CommandList* appearAnim; CommandList* disappearAnim; public: MapEditCreate(MapEditorScene*); ~MapEditCreate(); Transform* GetTransform(); SpriteRenderer* GetSpriteRenderer(); void OnStart(); void OnUpdate(); void Disappear(); };
[ "vlfkdydtk@naver.com" ]
vlfkdydtk@naver.com
60f3d216d3e1b79ca0dc173b142ec927e8f88062
4434910c965bf51c945e95f590422198d24d303a
/Linked List/109. convert-sorted-list-to-binary-search-tree.cpp
0a28dfd073e9e39426860803758104f46259ccad
[]
no_license
utkarsh914/LeetCode
7ca325e130a0b420603e7899562f7a463a765748
93d4c2a62e553f13ecc6f3506e91a597bf901ceb
refs/heads/main
2023-08-14T20:30:49.174023
2021-09-17T13:12:23
2021-09-17T13:12:23
338,639,989
6
3
null
null
null
null
UTF-8
C++
false
false
1,845
cpp
// https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: TreeNode* sortedListToBST(ListNode* head, ListNode* last = NULL) { if (!head or head==last) return NULL; ListNode *slow = head, *fast = head; while (fast && fast!=last && fast->next && fast->next!=last) { slow = slow->next; fast = fast->next->next; } TreeNode* ans = new TreeNode(slow->val); ans->left = sortedListToBST(head, slow); ans->right = sortedListToBST(slow->next, last); return ans; } }; class Solution { ListNode* getMid(ListNode* head) { if (!head) return NULL; ListNode *slow=head, *fast=head; ListNode* prev = new ListNode(0, head); while (fast && fast->next) { prev = slow; slow = slow->next; fast = fast->next->next; } prev->next = NULL; // disconnect left part from this list return slow; } public: TreeNode* sortedListToBST(ListNode* head) { if (!head) return NULL; if (!head->next) return new TreeNode(head->val); ListNode* mid = getMid(head); TreeNode* root = new TreeNode(mid->val); root->left = sortedListToBST(head); root->right = sortedListToBST(mid->next); return root; } };
[ "utiwari914@gmail.com" ]
utiwari914@gmail.com
b13217d5331c7f7c9bdee0768201eab4ca3080a3
a2d7e5f99f68ff2a845850fbb2a4982459d28022
/arena2d-sim/engine/zLogfile.hpp
6955f66a9a7ae62fa1271cd4aea4b6be4f3ccb9a
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
linhdoan8/arena2D
c10bcd9154530717eb2526bd8f085b3b2c66fb4e
290ec59bb1962c9caac99ead76c57607ed8cfdc4
refs/heads/master
2022-12-03T08:18:55.448239
2020-08-17T07:38:40
2020-08-17T07:38:40
289,931,780
1
0
MIT
2020-08-24T13:11:32
2020-08-24T13:11:31
null
UTF-8
C++
false
false
1,952
hpp
//Created on: 16th Jan 2017 //Author: Cornelius Marx #ifndef ZER0_LOGFILE_H #define ZER0_LOGFILE_H #include <stdio.h> #include <string.h> #include <stdarg.h> #include "zSingleton.hpp" #define Z_LOG zLogfile::get() // makro for logging something (info, error, warning) #define INFO_F(X, ...) zLogfile::get()->printfMode(zLogfile::LOG_INFO, true, X, __VA_ARGS__) #define WARNING_F(X, ...) zLogfile::get()->printfMode(zLogfile::LOG_WARNING, true, X, __VA_ARGS__) #define ERROR_F(X, ...) zLogfile::get()->printfMode(zLogfile::LOG_ERROR, true, X, __VA_ARGS__) #define INFO(X) zLogfile::get()->printfMode(zLogfile::LOG_INFO, true, X) #define WARNING(X) zLogfile::get()->printfMode(zLogfile::LOG_WARNING, true, X) #define ERROR(X) zLogfile::get()->printfMode(zLogfile::LOG_ERROR, true, X) #define Z_LOG_HEAD_CHARACTER '#' #define Z_LOG_DEFAULT_FILE_NAME "log.txt" class zLogfile : public zTSingleton<zLogfile> { public: // logging modes enum Mode{LOG_INFO, LOG_WARNING, LOG_ERROR}; //constructor zLogfile(); //destructor ~zLogfile(); //initializer // @logfile_path where to store the logfile (NULL for no output file) void createLog(bool std_print, const char * logfile_path); //write-out functions // close Log void closeLog(); // printf with given mode #ifndef WIN32 __attribute__((format(printf, 4, 5))) #endif void printfMode(enum Mode mode, bool new_line, const char * fmt, ...); void printfMode(enum Mode mode, bool new_line, const char * fmt, va_list args); // printing to all streams that were registerd (std_print/file_print) void printFormatted(const char * fmt, va_list args); #ifndef WIN32 __attribute__((format(printf, 2, 3))) #endif void printFormatted(const char * fmt, ...); // writing out given number of linebreaks to all registered streams void writeLines(int num); private: FILE * _logfile; bool _std_print; //shall the output be written to console? (std) }; #endif
[ "marxc9@outlook.de" ]
marxc9@outlook.de
e40ecf36000d24f43bddb96e42f4d89e51f6361b
2c8c9841bbd2917cbd0f89c51edbb4400f1430e4
/BearGame/base/Clock.h
9165f5bd07de9b5108409a41ef286877fb6a21ce
[]
no_license
IBM9100/BearGame
1df62db066c3e5f812f261a71cc201e07ac769d6
41370e8dc63e6f5479ae4931057ec45e7fce255d
refs/heads/master
2022-12-14T05:33:12.212964
2020-09-05T05:53:52
2020-09-05T05:53:52
291,615,600
0
0
null
2020-09-03T13:13:48
2020-08-31T04:37:40
C
UTF-8
C++
false
false
356
h
#ifndef BEARGAME_BASE_CLOCK_H #define BEARGAME_BASE_CLOCK_H #include <cstdint> #include <sys/time.h> #include "base/Singleton.h" namespace BearGame { class Clock : public Singleton<Clock> { public: void Update(); int64_t Now(); struct timeval NowTv(); public: int64_t Tick() { return m_tick; } private: int64_t m_tick; }; } #endif
[ "yu2erer@gmail.com" ]
yu2erer@gmail.com
3634584dee2c8a8170cc9eab568248857461284b
15247681c3cd7969ecea2349ba18667df9c9fbee
/epoch1/cuda/ee_mumu/src/read_slha.cc
281062f9afab2f81e0401e57e05b9b9c1fea28fe
[]
no_license
TaranSinghania/madgraph4gpu-1
4f181eb75a3e0e342e4860400edb12ce044fa64b
6baa276dc2c974f207f67cbaa93b9ee49acc9c36
refs/heads/master
2023-02-15T04:35:02.978445
2020-12-16T17:32:24
2020-12-17T09:34:46
289,874,630
1
0
null
2020-08-24T08:44:40
2020-08-24T08:44:40
null
UTF-8
C++
false
false
4,023
cc
#include <algorithm> #include <iostream> #include <fstream> #include "read_slha.h" void SLHABlock::set_entry(std::vector<int> indices, double value) { if (_entries.size() == 0) _indices = indices.size(); else if(indices.size() != _indices) throw "Wrong number of indices in set_entry"; _entries[indices] = value; } double SLHABlock::get_entry(std::vector<int> indices, double def_val) { if (_entries.find(indices) == _entries.end()){ std::cout << "Warning: No such entry in " << _name << ", using default value " << def_val << std::endl; return def_val; } return _entries[indices]; } void SLHAReader::read_slha_file(std::string file_name, bool verbose) { std::ifstream param_card; param_card.open(file_name.c_str(), std::ifstream::in); if(!param_card.good()) throw "Error while opening param card"; if(verbose) std::cout << "Opened slha file " << file_name << " for reading" << std::endl; char buf[200]; std::string line; std::string block(""); while(param_card.good()){ param_card.getline(buf, 200); line = buf; // Change to lowercase transform(line.begin(), line.end(), line.begin(), (int(*)(int)) tolower); if(line != "" && line[0] != '#'){ if(block != ""){ // Look for double index blocks double dindex1, dindex2; double value; std::stringstream linestr2(line); if (linestr2 >> dindex1 >> dindex2 >> value && dindex1 == int(dindex1) and dindex2 == int(dindex2)) { std::vector<int> indices; indices.push_back(int(dindex1)); indices.push_back(int(dindex2)); set_block_entry(block, indices, value); // Done with this line, read next continue; } std::stringstream linestr1(line); // Look for single index blocks if(linestr1 >> dindex1 >> value && dindex1 == int(dindex1)) { std::vector<int> indices; indices.push_back(int(dindex1)); set_block_entry(block, indices, value); // Done with this line, read next continue; } } // Look for block if(line.find("block ") != line.npos){ line = line.substr(6); // Get rid of spaces between block and block name while (line[0] == ' ') line = line.substr(1); // Now find end of block name int space_pos = line.find(' '); if(space_pos != ((int) line.npos)) line = line.substr(0, space_pos); block = line; continue; } // Look for decay if(line.find("decay ") == 0){ line = line.substr(6); block = ""; std::stringstream linestr(line); int pdg_code; double value; if(linestr >> pdg_code >> value) set_block_entry("decay", pdg_code, value); else std::cout << "Warning: Wrong format for decay block " << line << std::endl; continue; } } } if (_blocks.size() == 0) throw "No information read from SLHA card"; param_card.close(); } double SLHAReader::get_block_entry(std::string block_name, std::vector<int> indices, double def_val) { if (_blocks.find(block_name) == _blocks.end()){ std::cout << "No such block " << block_name << ", using default value " << def_val << std::endl; return def_val; } return _blocks[block_name].get_entry(indices); } double SLHAReader::get_block_entry(std::string block_name, int index, double def_val) { std::vector<int> indices; indices.push_back(index); return get_block_entry(block_name, indices, def_val); } void SLHAReader::set_block_entry(std::string block_name, std::vector<int> indices, double value) { if (_blocks.find(block_name) == _blocks.end()){ SLHABlock block(block_name); _blocks[block_name] = block; } _blocks[block_name].set_entry(indices, value); /* cout << "Set block " << block_name << " entry "; for (int i=0;i < indices.size();i++) cout << indices[i] << " "; cout << "to " << _blocks[block_name].get_entry(indices) << endl;*/ } void SLHAReader::set_block_entry(std::string block_name, int index, double value) { std::vector<int> indices; indices.push_back(index); set_block_entry(block_name, indices, value); }
[ "andrea.valassi@cern.ch" ]
andrea.valassi@cern.ch
8f79eec53847ab94774624be2553f2f8ca2c59ec
19194c2f2c07ab3537f994acfbf6b34ea9b55ae7
/android-28/android/app/backup/BackupManager.def.hpp
64c8d8178f35a9435e07e0a05a13f1fbd3e027b7
[ "GPL-3.0-only" ]
permissive
YJBeetle/QtAndroidAPI
e372609e9db0f96602da31b8417c9f5972315cae
ace3f0ea2678967393b5eb8e4edba7fa2ca6a50c
refs/heads/Qt6
2023-08-05T03:14:11.842336
2023-07-24T08:35:31
2023-07-24T08:35:31
249,539,770
19
4
Apache-2.0
2022-03-14T12:15:32
2020-03-23T20:42:54
C++
UTF-8
C++
false
false
765
hpp
#pragma once #include "../../../JObject.hpp" namespace android::app::backup { class RestoreObserver; } namespace android::content { class Context; } class JString; namespace android::app::backup { class BackupManager : public JObject { public: // Fields // QJniObject forward template<typename ...Ts> explicit BackupManager(const char *className, const char *sig, Ts...agv) : JObject(className, sig, std::forward<Ts>(agv)...) {} BackupManager(QJniObject obj) : JObject(obj) {} // Constructors BackupManager(android::content::Context arg0); // Methods static void dataChanged(JString arg0); void dataChanged() const; jint requestRestore(android::app::backup::RestoreObserver arg0) const; }; } // namespace android::app::backup
[ "yjbeetle@gmail.com" ]
yjbeetle@gmail.com
15b6f7be15a60fbac5bb6f08ae1c549312c2dd04
4fb009d90ec61501c8b4c15a9ca7f480045f7c94
/Pacman/Pacman/packman.cpp
cc923e46067b087516dc558ef8c3e483f9262a04
[]
no_license
Bariskas/ProjectDeveloping
250fcc4c9b22734ee2461e8b1679de354e3c83ba
6f41e73c2996ff0e19732ea7f383a5ff441d9ba6
refs/heads/master
2021-05-04T06:15:14.616975
2016-11-26T01:13:20
2016-11-26T01:13:20
71,046,244
0
0
null
null
null
null
UTF-8
C++
false
false
1,936
cpp
#include "Packman.h" void initializePackman(Packman& packman) { packman.direction = Direction::NONE; packman.shape.setRadius(20); packman.shape.setFillColor(sf::Color::Green); packman.shape.setPosition(100, 0); } bool handlePackmanKeyPress(const sf::Event::KeyEvent &event, Packman &packman) { bool handled = true; switch (event.code) { case sf::Keyboard::Up: packman.direction = Direction::UP; break; case sf::Keyboard::Down: packman.direction = Direction::DOWN; break; case sf::Keyboard::Left: packman.direction = Direction::LEFT; break; case sf::Keyboard::Right: packman.direction = Direction::RIGHT; break; default: handled = false; break; } return handled; } bool handlePackmanKeyRelease(const sf::Event::KeyEvent &event, Packman &packman) { bool handled = true; switch (event.code) { case sf::Keyboard::Up: if (packman.direction == Direction::UP) { packman.direction = Direction::NONE; } break; case sf::Keyboard::Down: if (packman.direction == Direction::DOWN) { packman.direction = Direction::NONE; } break; case sf::Keyboard::Left: if (packman.direction == Direction::LEFT) { packman.direction = Direction::NONE; } break; case sf::Keyboard::Right: if (packman.direction == Direction::RIGHT) { packman.direction = Direction::NONE; } break; default: handled = false; break; } return handled; } void updatePackman(Packman &packman, float elapsedTime) { const float PACKMAN_SPEED = 20.f; // pixels per second. const float step = PACKMAN_SPEED * elapsedTime; sf::Vector2f position = packman.shape.getPosition(); switch (packman.direction) { case Direction::UP: position.y -= step; break; case Direction::DOWN: position.y += step; break; case Direction::LEFT: position.x -= step; break; case Direction::RIGHT: position.x += step; break; case Direction::NONE: break; } packman.shape.setPosition(position); }
[ "Bariskas@gmail.com" ]
Bariskas@gmail.com
5ea688b363508a32eb6ddf6c5d78428365e52661
da13b72e19a2fa45808e5e49442fba1b66396ebe
/Template/数学/多项式.cpp
fc0b4fc0720f6979d12bb47e57eaca547ece3ec5
[]
no_license
WangJunqiao/Algorithm
82c0a1c1d76ded16d1f8d53e0fce39861ad87227
f35e67f5bb5801d6c59c6286fa57ba6a11a9f42d
refs/heads/master
2021-01-17T11:04:00.913369
2016-03-04T14:35:21
2016-03-04T14:35:21
18,668,251
0
0
null
null
null
null
GB18030
C++
false
false
1,558
cpp
//多项式展开,用于母函数展开**** template<typename T> //系数的数据类型T struct Polynomial { map <int, T> mp; //x的幂, 系数 //************************** Polynomial() { mp.clear(); } void add(T c, int p) { //加 c * x^p mp[p] += c; } void get_c(int p) { return mp[p]; } void zero() { //清0 mp.clear(); } //复杂度O(n*n*logn) Polynomial<T> operator*(const Polynomial &p) const { Polynomial<T> ret; for (typename map<int, T>::const_iterator it1 = mp.begin(); it1 != mp.end(); ++it1) { for (typename map<int, T>::const_iterator it2 = p.mp.begin(); it2 != p.mp.end(); ++it2) { ret.mp[it1->first + it2->first] += it1->second * it2->second; } } return ret; } //复杂度O(n*logn) Polynomial<T> operator+(const Polynomial<T> &p) const { Polynomial<T> ret = *this; for (typename map<int, T>::const_iterator it = p.mp.begin(); it != p.mp.end(); ++it) { ret.mp[it->first] += it->second; } return ret; } void print() const { typename map<int, T>::const_iterator it1 = mp.end(); bool first = true; do { --it1; if (!first) putchar('+'); if (it1->second != 1) cout << it1->second; if (it1->first != 1)printf("x^%d", it1->first); else putchar('x'); first = false; } while (it1 != mp.begin()); cout << endl; } };
[ "774367334@qq.com" ]
774367334@qq.com
56127c819ef7e7a7b4f3b98a477b0892e8df47a0
fefbffe56cc5dd6d9256337d44d65386ceae4292
/include/xthreejs/math/xsphere_autogen.hpp
b07a5ec7c62e1a2cca4a4cc30ae2362e3036fd78
[]
no_license
yssource/xthreejs
e405a706a0e35131e679af9fbeb2e18e403e2b24
cd8ab8929b0019f495d9f1566461306e9e3d8310
refs/heads/master
2020-05-18T10:07:08.534561
2018-06-20T05:49:35
2018-06-20T05:49:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,665
hpp
#ifndef XTHREE_SPHERE_HPP #define XTHREE_SPHERE_HPP #include "xtl/xoptional.hpp" #include "xwidgets/xeither.hpp" #include "xwidgets/xwidget.hpp" #include "../base/xenums.hpp" #include "../base/xthree_types.hpp" #include "../base/xthree.hpp" #include "../base/xrender.hpp" namespace xthree { // // sphere declaration // template<class D> class xsphere : public xthree_widget<D> { public: using base_type = xthree_widget<D>; using derived_type = D; void serialize_state(xeus::xjson&, xeus::buffer_sequence&) const; void apply_patch(const xeus::xjson&, const xeus::buffer_sequence&); XPROPERTY(vector3, derived_type, center, vector3({0,0,0})); XPROPERTY(double, derived_type, radius, 0); std::shared_ptr<xw::xmaterialize<xpreview>> pre = nullptr; protected: xsphere(); using base_type::base_type; private: void set_defaults(); }; using sphere = xw::xmaterialize<xsphere>; using sphere_generator = xw::xgenerator<xsphere>; // // sphere implementation // template <class D> inline void xsphere<D>::serialize_state(xeus::xjson& state, xeus::buffer_sequence& buffers) const { base_type::serialize_state(state, buffers); xw::set_patch_from_property(center, state, buffers); xw::set_patch_from_property(radius, state, buffers); } template <class D> inline void xsphere<D>::apply_patch(const xeus::xjson& patch, const xeus::buffer_sequence& buffers) { base_type::apply_patch(patch, buffers); xw::set_property_from_patch(center, patch, buffers); xw::set_property_from_patch(radius, patch, buffers); } template <class D> inline xsphere<D>::xsphere() : base_type() { set_defaults(); } template <class D> inline void xsphere<D>::set_defaults() { this->_model_name() = "SphereModel"; this->_view_name() = ""; } } xeus::xjson mime_bundle_repr(xw::xmaterialize<xthree::xsphere>& widget); /********************* * precompiled types * *********************/ #ifdef XTHREEJS_PRECOMPILED #ifndef _WIN32 extern template class xw::xmaterialize<xthree::xsphere>; extern template xw::xmaterialize<xthree::xsphere>::xmaterialize(); extern template class xw::xtransport<xw::xmaterialize<xthree::xsphere>>; extern template class xw::xgenerator<xthree::xsphere>; extern template xw::xgenerator<xthree::xsphere>::xgenerator(); extern template class xw::xtransport<xw::xgenerator<xthree::xsphere>>; #endif #endif #endif
[ "loic.gouarin@gmail.com" ]
loic.gouarin@gmail.com
6947e0c27458b9cceee2cd52238cf9b106610100
70927ebfa40ae0b6ce5d19cb5256cfb880de4f07
/Pods/geos/Sources/geos/src/planargraph/DirectedEdgeStar.cpp
5342bd5091e864dc1b3b0f77ed4f1d595e54b704
[ "LGPL-2.0-or-later", "LGPL-2.1-only", "GPL-2.0-only", "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
baato/BaatoSwift
44af06fe3a1af26fe8540376cdc82a93e498fdbc
87cb476affbdf24f4b902bb498970051d0382a9c
refs/heads/master
2023-03-28T07:50:10.326223
2020-12-09T09:58:48
2020-12-09T09:58:48
294,601,067
0
0
MIT
2020-12-08T08:09:04
2020-09-11T05:17:37
Swift
UTF-8
C++
false
false
3,886
cpp
/********************************************************************** * * GEOS - Geometry Engine Open Source * http://geos.osgeo.org * * Copyright (C) 2001-2002 Vivid Solutions Inc. * Copyright (C) 2005 Refractions Research Inc. * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * **********************************************************************/ #include <geos/planargraph/DirectedEdgeStar.h> #include <geos/planargraph/DirectedEdge.h> #include <vector> #include <algorithm> using namespace std; using namespace geos::geom; namespace geos { namespace planargraph { /* * Adds a new member to this DirectedEdgeStar. */ void DirectedEdgeStar::add(DirectedEdge* de) { outEdges.push_back(de); sorted = false; } /* * Drops a member of this DirectedEdgeStar. */ void DirectedEdgeStar::remove(DirectedEdge* de) { for(unsigned int i = 0; i < outEdges.size(); ++i) { if(outEdges[i] == de) { outEdges.erase(outEdges.begin() + i); --i; } } } vector<DirectedEdge*>::iterator DirectedEdgeStar::begin() { sortEdges(); return outEdges.begin(); } vector<DirectedEdge*>::iterator DirectedEdgeStar::end() { sortEdges(); return outEdges.end(); } vector<DirectedEdge*>::const_iterator DirectedEdgeStar::begin() const { sortEdges(); return outEdges.begin(); } vector<DirectedEdge*>::const_iterator DirectedEdgeStar::end() const { sortEdges(); return outEdges.end(); } /* * Returns the coordinate for the node at wich this star is based */ Coordinate& DirectedEdgeStar::getCoordinate() const { if(outEdges.empty()) { return Coordinate::getNull(); } DirectedEdge* e = outEdges[0]; return e->getCoordinate(); } /* * Returns the DirectedEdges, in ascending order by angle with * the positive x-axis. */ vector<DirectedEdge*>& DirectedEdgeStar::getEdges() { sortEdges(); return outEdges; } bool pdeLessThan(DirectedEdge* first, DirectedEdge* second) { if(first->compareTo(second) < 0) { return true; } else { return false; } } /*private*/ void DirectedEdgeStar::sortEdges() const { if(!sorted) { sort(outEdges.begin(), outEdges.end(), pdeLessThan); sorted = true; } } /* * Returns the zero-based index of the given Edge, after sorting in * ascending order by angle with the positive x-axis. */ int DirectedEdgeStar::getIndex(const Edge* edge) { sortEdges(); for(unsigned int i = 0; i < outEdges.size(); ++i) { DirectedEdge* de = outEdges[i]; if(de->getEdge() == edge) { return i; } } return -1; } /* * Returns the zero-based index of the given DirectedEdge, after sorting * in ascending order by angle with the positive x-axis. */ int DirectedEdgeStar::getIndex(const DirectedEdge* dirEdge) { sortEdges(); for(unsigned int i = 0; i < outEdges.size(); ++i) { DirectedEdge* de = outEdges[i]; if(de == dirEdge) { return i; } } return -1; } /* * Returns the remainder when i is divided by the number of edges in this * DirectedEdgeStar. */ int DirectedEdgeStar::getIndex(int i) const { int modi = i % (int)outEdges.size(); //I don't think modi can be 0 (assuming i is positive) [Jon Aquino 10/28/2003] if(modi < 0) { modi += (int)outEdges.size(); } return modi; } /* * Returns the DirectedEdge on the left-hand side of the given * DirectedEdge (which must be a member of this DirectedEdgeStar). */ DirectedEdge* DirectedEdgeStar::getNextEdge(DirectedEdge* dirEdge) { int i = getIndex(dirEdge); return outEdges[getIndex(i + 1)]; } } // namespace planargraph } // namespace geos
[ "bhawak.pokhrel@gmail.com" ]
bhawak.pokhrel@gmail.com
56c51bd8e7bcf241f3cb53f74d1cca05e7fdb015
673cda4a27c99b1f036d456a7db43bd18219f4af
/src/change_detector2.cpp
d05e7761d39f137219c6d5124a761bed43f81e9d
[]
no_license
HiroIshida/image_collision_detection
4f2b50e41e39ba897e16b9da22506acb9847c0c2
7efd691cdb579360826f2f03d026802eee236915
refs/heads/master
2020-07-03T21:13:19.944878
2019-08-29T13:54:00
2019-08-29T13:54:00
202,051,256
0
0
null
null
null
null
UTF-8
C++
false
false
3,543
cpp
#include <ros/ros.h> #include "std_msgs/String.h" #include "sensor_msgs/Image.h" #include "std_msgs/Int64.h" #include "std_msgs/Float64.h" #include "std_srvs/Empty.h" #include <sstream> #include <string> #include <cv_bridge/cv_bridge.h> #include <sensor_msgs/image_encodings.h> #include "image_dif.hpp" #include <boost/function.hpp> #include <active_visual_perception/CostService.h> //from active_visual_perception.srv import * // as for use callback function of class member functions... // https://answers.ros.org/question/108551/using-subscribercallback-function-inside-of-a-class-c/ class ChangeDetector { ros::NodeHandle nh; ros::Publisher pub_cost, pub_cost_max, pub_image; ros::Subscriber sub_image; ros::ServiceServer service_init, service_cost; double cost, cost_max; double t_pre; cv::Mat img_pre; bool isInit; public: ChangeDetector(); private: void init_common(); void callback(const sensor_msgs::Image& msg); bool req_handler_init(std_srvs::Empty::Request& req, std_srvs::Empty::Response& res);//deprecated bool req_handler_cost(active_visual_perception::CostService::Request& req, active_visual_perception::CostService::Response& res); }; ChangeDetector::ChangeDetector(){ pub_cost = nh.advertise<std_msgs::Int64>("/cost", 1); pub_cost_max = nh.advertise<std_msgs::Int64>("/cost_max", 1); pub_image = nh.advertise<sensor_msgs::Image>("/debug_image", 1); sub_image = nh.subscribe("/kinect_head/rgb/image_raw", 1, &ChangeDetector::callback, this); service_init = nh.advertiseService("change_detector_init", &ChangeDetector::req_handler_init, this); service_cost = nh.advertiseService("current_cost", &ChangeDetector::req_handler_cost, this); init_common(); } void ChangeDetector::init_common() { isInit = true; cost = -1; cost_max = -1; t_pre = ros::Time::now().toSec(); } bool ChangeDetector::req_handler_init(std_srvs::Empty::Request& req, std_srvs::Empty::Response& res)//deprecated { ROS_INFO("received; initialize change detector"); init_common(); return true; } bool ChangeDetector::req_handler_cost(active_visual_perception::CostService::Request& req, active_visual_perception::CostService::Response& res) { ROS_INFO("received; return costs"); auto msg_cost = std_msgs::Float64(); auto msg_cost_max = std_msgs::Float64(); msg_cost.data = cost; msg_cost_max.data = cost_max; res.cost = msg_cost; res.cost_max = msg_cost_max; return true; } void ChangeDetector::callback(const sensor_msgs::Image& msg) { cv_bridge::CvImageConstPtr cv_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8); auto predicate = gen_hsi_filter(0.0, 1.0, 0.3, 1.0, 0.5, 0.88); auto img_received = convert_bf(cv_ptr->image, predicate); if(isInit){ img_pre = img_received; isInit = false; }else{ double t_now = ros::Time::now().toSec(); t_pre = t_now; auto img_diff = diff_image(img_received, img_pre); sensor_msgs::ImagePtr msg_debug = cv_bridge::CvImage(std_msgs::Header(), "bgr8", img_diff).toImageMsg(); cost = (float)compute_cost(img_received, img_pre); if (cost > cost_max){ cost_max = cost; } std_msgs::Int64 msg_cost, msg_cost_max; msg_cost.data = cost; msg_cost_max.data = cost_max; pub_image.publish(msg_debug); pub_cost.publish(msg_cost); pub_cost_max.publish(msg_cost_max); img_pre = img_received; } } int main(int argc, char **argv) { ros::init(argc, argv, "change_detector"); ChangeDetector cb; ros::spin(); return 0; }
[ "spitfire.docomo@gmail.com" ]
spitfire.docomo@gmail.com
ca506cb0fa0875067afd93fa6e97656d7ac2b58d
c8d3a372f9cd46732caa5ef983f12d3b9b667961
/componente/componente.cpp
b7b6dde36fc45fa1b036c5b25d9d3f4dbd3f9ef4
[]
no_license
Momofil31/ASD_2019-2020
7db1329a42dcf0dc895fc18c46bb5f1cafbdfee5
c0a62336ab01a1cb92681c1d444a32c65d69525b
refs/heads/master
2020-09-13T22:02:40.897397
2020-03-27T20:34:37
2020-03-27T20:34:37
222,916,168
1
0
null
null
null
null
UTF-8
C++
false
false
4,294
cpp
#include <algorithm> #include <fstream> #include <iostream> #include <stack> #include <vector> using namespace std; struct nodo { vector<int> vic; }; int N, M; vector<int> componentiFortConnesse(vector<nodo> &); void compConnDFS(vector<nodo> &, int, int, vector<int> &); vector<int> componentiConnesse(vector<nodo> &, stack<int> &); void topSort(vector<nodo> &, stack<int> &); void topSortDFS(vector<nodo> &, int &, vector<bool> &, stack<int> &); void stampaGrafo(vector<nodo> &); int main() { ifstream in("input.txt"); ofstream out("output.txt"); in >> N >> M; vector<nodo> grafo(N); vector<int> vettoreCompFortConnesse; int dimMaxCompConn; int numCompConnesse; // Prendo grafo da input for (int j = 0; j < M; j++) { int from, to; in >> from >> to; grafo[from].vic.push_back(to); } // Stampo grafo cout << "-- STAMPO GRAFO --" << endl; stampaGrafo(grafo); // calcolo componenti fortemente connesse vettoreCompFortConnesse = componentiFortConnesse(grafo); // stampo componenti fortemente connesse for (int i = 0; i < N; i++) { cout << vettoreCompFortConnesse[i] << " "; } cout << endl; // conto componenti connesse (massimo valore nel vettore) numCompConnesse = *max_element(vettoreCompFortConnesse.begin(), vettoreCompFortConnesse.end()); cout << "Il numero di componenti connesse è: " << numCompConnesse << endl; // Calcolo dimensione della più grande componente fortemente connessa vector<int> dimComponenti(numCompConnesse, 0); for (auto i : vettoreCompFortConnesse) { dimComponenti[i - 1]++; // i-1 perchè i vettori partono da zero ! } dimMaxCompConn = *max_element(dimComponenti.begin(), dimComponenti.end()); cout << "La dimensionne della più grande componente fort. conn. è: " << dimMaxCompConn << endl; out << dimMaxCompConn << endl; return 0; } // Calcolo delle componenti fortemente connesse vector<int> componentiFortConnesse(vector<nodo> &grafo) { stack<int> permutazNodiGrafo; vector<nodo> grafoTrasposto(grafo.size()); // Ordinamento topologico del grafo topSort(grafo, permutazNodiGrafo); // Calcolo grafo trasposto for (int u = 0; u < N; u++) { for (int v : grafo[u].vic) { grafoTrasposto[v].vic.push_back(u); } } // Stampo grafo trasposto cout << "-- STAMPO GRAFO TRASPOSTO --" << endl; stampaGrafo(grafoTrasposto); return componentiConnesse(grafoTrasposto, permutazNodiGrafo); } // Funzioni per il calcolo delle componenti connesse vector<int> componentiConnesse(vector<nodo> &G, stack<int> &S) { vector<int> id(N, 0); // vettore id che identifica la componente connessa a // cui appartiene il nodo in posizione u int conta = 0; while (!S.empty()) { int u = S.top(); S.pop(); if (id[u] == 0) { cout << "u = " << u << " e id[u] = " << id[u] << endl; conta++; compConnDFS(G, conta, u, id); } } return id; } void compConnDFS(vector<nodo> &G, int conta, int u, vector<int> &id) { id[u] = conta; for (auto v : G[u].vic) { cout << "-- v = " << v << " e id[u] = " << id[v] << endl; if (id[v] == 0) compConnDFS(G, conta, v, id); } } // Funzioni per il calcolo dell'ordinamento topologico (TopSort) void topSort(vector<nodo> &G, stack<int> &S) { vector<bool> visitato(N, false); for (int u = 0; u < N; u++) { if (!visitato[u]) { if (!visitato[u]) { topSortDFS(G, u, visitato, S); } } } } void topSortDFS(vector<nodo> &G, int &u, vector<bool> &visitato, stack<int> &S) { visitato[u] = true; for (auto v : G[u].vic) { if (!visitato[v]) { topSortDFS(G, v, visitato, S); } } S.push(u); cout << "Push sullo stack del nodo: " << u << endl; } // UTILITY void stampaGrafo(vector<nodo> &G) { for (int i = 0; i < G.size(); i++) { cout << "Nodo " << i << " ha " << G[i].vic.size() << " vicini" << endl; for (int v : G[i].vic) { cout << " " << v << endl; } } }
[ "filippomomesso@gmail.com" ]
filippomomesso@gmail.com
00e82709d6ca894b59342d7a83f85d5832e5324a
dfd0425f038466d200fc32e8ae0f4a72a32ab0bc
/engine/render/include/render/render_passes/particle_system_render_pass.h
ab5625ca821792ac1c04aa61e44a81402aea818b
[]
no_license
suVrik/KWA
4a0e51e1ffa99650a8a09630e44a54ea8067b8da
416d39a5a2355a59f115d44b3ed4032798edc197
refs/heads/master
2023-08-11T15:07:24.438061
2021-09-10T20:31:40
2021-09-20T05:23:34
375,077,587
6
0
null
2021-09-20T05:27:44
2021-06-08T16:34:40
C++
UTF-8
C++
false
false
1,139
h
#pragma once #include "render/render_passes/base_render_pass.h" namespace kw { class CameraManager; class Scene; struct ParticleSystemRenderPassDescriptor { Scene* scene; CameraManager* camera_manager; MemoryResource* transient_memory_resource; }; class ParticleSystemRenderPass : public BaseRenderPass { public: explicit ParticleSystemRenderPass(const ParticleSystemRenderPassDescriptor& descriptor); void get_color_attachment_descriptors(Vector<AttachmentDescriptor>& attachment_descriptors) override; void get_depth_stencil_attachment_descriptors(Vector<AttachmentDescriptor>& attachment_descriptors) override; void get_render_pass_descriptors(Vector<RenderPassDescriptor>& render_pass_descriptors) override; void create_graphics_pipelines(FrameGraph& frame_graph) override; void destroy_graphics_pipelines(FrameGraph& frame_graph) override; // Must be placed between acquire and present frame graph's tasks. Task* create_task(); private: class Task; Scene& m_scene; CameraManager& m_camera_manager; MemoryResource& m_transient_memory_resource; }; } // namespace kw
[ "suvri4@gmail.com" ]
suvri4@gmail.com
75ff98f1bf4442c5e4c6dadfdca38afd7aede2d3
b0e6305c81cf3e799a4ce56f02ef69b616d38647
/Source/ThirdParty/tracy/client/TracyCallstack.hpp
6a8539258f3c17337ce5441db850ed8a28604789
[ "BSD-3-Clause", "MIT", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-warranty-disclaimer", "Zlib", "LicenseRef-scancode-khronos", "BSL-1.0", "BSD-2-Clause" ]
permissive
JSandusky/rbfx
9331074ea11b2fad48bd68e23416f70dbcd0fb3d
36fcc929f19dccddda666c5a378105a1229e31fe
refs/heads/master
2022-11-26T15:38:55.475680
2020-01-25T14:04:34
2020-01-25T14:04:54
236,247,918
0
1
MIT
2020-01-26T00:14:37
2020-01-26T00:14:37
null
UTF-8
C++
false
false
2,424
hpp
#ifndef __TRACYCALLSTACK_HPP__ #define __TRACYCALLSTACK_HPP__ #include "TracyCallstack.h" #if TRACY_HAS_CALLSTACK == 1 extern "C" { typedef unsigned long (__stdcall *t_RtlWalkFrameChain)( void**, unsigned long, unsigned long ); extern t_RtlWalkFrameChain RtlWalkFrameChain; } #elif TRACY_HAS_CALLSTACK == 2 || TRACY_HAS_CALLSTACK == 5 # include <unwind.h> #elif TRACY_HAS_CALLSTACK >= 3 # include <execinfo.h> #endif #ifdef TRACY_HAS_CALLSTACK #include <assert.h> #include <stdint.h> #include "../common/TracyAlloc.hpp" #include "../common/TracyForceInline.hpp" namespace tracy { struct CallstackEntry { const char* name; const char* file; uint32_t line; }; struct CallstackEntryData { const CallstackEntry* data; uint8_t size; }; const char* DecodeCallstackPtrFast( uint64_t ptr ); CallstackEntryData DecodeCallstackPtr( uint64_t ptr ); void InitCallstack(); #if TRACY_HAS_CALLSTACK == 1 static tracy_force_inline void* Callstack( int depth ) { assert( depth >= 1 && depth < 63 ); auto trace = (uintptr_t*)tracy_malloc( ( 1 + depth ) * sizeof( uintptr_t ) ); const auto num = RtlWalkFrameChain( (void**)( trace + 1 ), depth, 0 ); *trace = num; return trace; } #elif TRACY_HAS_CALLSTACK == 2 || TRACY_HAS_CALLSTACK == 5 struct BacktraceState { void** current; void** end; }; static _Unwind_Reason_Code tracy_unwind_callback( struct _Unwind_Context* ctx, void* arg ) { auto state = (BacktraceState*)arg; uintptr_t pc = _Unwind_GetIP( ctx ); if( pc ) { if( state->current == state->end ) return _URC_END_OF_STACK; *state->current++ = (void*)pc; } return _URC_NO_REASON; } static tracy_force_inline void* Callstack( int depth ) { assert( depth >= 1 && depth < 63 ); auto trace = (uintptr_t*)tracy_malloc( ( 1 + depth ) * sizeof( uintptr_t ) ); BacktraceState state = { (void**)(trace+1), (void**)(trace+1+depth) }; _Unwind_Backtrace( tracy_unwind_callback, &state ); *trace = (uintptr_t*)state.current - trace + 1; return trace; } #elif TRACY_HAS_CALLSTACK == 3 || TRACY_HAS_CALLSTACK == 4 static tracy_force_inline void* Callstack( int depth ) { assert( depth >= 1 ); auto trace = (uintptr_t*)tracy_malloc( ( 1 + depth ) * sizeof( uintptr_t ) ); const auto num = backtrace( (void**)(trace+1), depth ); *trace = num; return trace; } #endif } #endif #endif
[ "rokups@zoho.com" ]
rokups@zoho.com
fe4abc66681ff440c3ec372867f5a8a25c56e489
bc2043edf8c4a3c1b2c33826eea4f13e90051ba5
/src/BulletPool.cpp
8aae297c4b2a4945f04faa9d8f0df31301e69480
[]
no_license
RuiGeng101277255/GAME2005_Assignment3
9b536d41a1225137476f0fc8c80a3546b10517bc
49f57de65e9d8e3b1ee8c631042c21c9f1a0fb3b
refs/heads/main
2023-01-15T22:30:28.397965
2020-11-27T18:39:34
2020-11-27T18:39:34
314,070,225
0
0
null
null
null
null
UTF-8
C++
false
false
1,834
cpp
#include "BulletPool.h" #include <iostream> #include "Util.h" #include "CollisionManager.h" BulletPool::BulletPool() { for (int i = 0; i < PoolSize; i++) { bullet[i] = new Bullet(); } } BulletPool::~BulletPool() = default; void BulletPool::draw() { for (int a = 0; a < PoolSize; a++) { bullet[a]->draw(); } } void BulletPool::update() { for (int b = 0; b < PoolSize; b++) { bullet[b]->update(); } } void BulletPool::clean() { for (int c = 0; c < PoolSize; c++) { bullet[c]->clean(); } } void BulletPool::spawnBullet(int num) { if ((num > 0) && (num <= 10)) { for (int j = 0; j < PoolSize; j++) { if (!bullet[j]->inUse) { bullet[j]->inUse = true; num--; } } num = 0; } } void BulletPool::setBulletGrav(glm::vec2 grav) { for (int m = 0; m < PoolSize; m++) { bullet[m]->Gravity = grav; } } void BulletPool::checkCollisionWith(GameObject* obj) { m_pReference = obj; for (int h = 0; h < PoolSize; h++) { if (CollisionManager::squaredRadiusCheck(obj, bullet[h])) { bullet[h]->Collided = true; } } } std::string BulletPool::getBulletInUse(int n) { if (n < PoolSize) { return ("In use: " + std::to_string(bullet[n]->inUse)); } } std::string BulletPool::getBulletPos(int n) { if (n < PoolSize) { return ("Pos(m) x: " + std::to_string(bullet[n]->getTransform()->position.x) + " y: " + std::to_string(bullet[n]->getTransform()->position.y)); } } std::string BulletPool::getBulletVel(int n) { if (n < PoolSize) { return ("Vel(m/s) x: " + std::to_string(bullet[n]->getRigidBody()->velocity.x) + " y: " + std::to_string(bullet[n]->getRigidBody()->velocity.y)); } } std::string BulletPool::getBulletAcc(int n) { if (n < PoolSize) { return ("Grav(m/s^2) x: " + std::to_string(bullet[n]->Gravity.x) + " y: " + std::to_string(bullet[n]->Gravity.y)); } }
[ "ruichen.gengli@georgebrown.ca" ]
ruichen.gengli@georgebrown.ca
8770020a2e4f4bdf50f643e32a38036762f341fa
49b86bb41a4b65f4b63e9b9b79327fb635103065
/src/DAGraphB.h
7283881c0db20887ba5d5ad15e06d95014c0719e
[ "MIT" ]
permissive
georgedeath/TAsK
f5f15f90e08ee9b51e4da60002e81a70f0518ec4
14c4abb3b3f9918accd59e9987e9403bd8a0470c
refs/heads/master
2020-09-20T06:50:10.886648
2020-08-06T10:30:37
2020-08-06T10:30:37
224,403,889
0
0
MIT
2019-11-27T10:22:22
2019-11-27T10:22:21
null
UTF-8
C++
false
false
1,412
h
#ifndef DAGRAPH_B #define DAGRAPH_B #include "DAGraph.h" class Path; /** \brief This class implements origin-based algorithm B. \details For details see \cite Dial_2006. */ class DAGraphB : public DAGraph { public: /** @param useMultiStep true if multiple Newton steps must be applied, false otherwise. @param dirTol tolerance of the direction of descent. */ DAGraphB(StarNetwork *net, ODMatrix *mat, FPType zeroFlow, FPType dirTol, int originIndex, bool useMultiStep); ~DAGraphB(); bool moveFlow(); protected: /** Implements Newton flow step. See DAGraphBWithStep for other step size implementations. */ virtual FPType calcFlowStep(Path* minPath, Path* maxPath) const; int nbIter; private: static bool useMultiStep_; static FPType dirTol_; /** Perform a flow move: flow is moved from longest path to shortest path that belong to the bush and start at \b origin and finish at node \b index. It is assumed that \b minPath and \b maxPath do not have common links. */ bool performFlowMove(int index, int origin); /** Adds flow \b dFlow to \b link, updates corresponding origin flow and recalculates travel time of \b link. */ void addFlow(StarLink *link, FPType dFlow); /** For debugging. */ void printMinPathOFlows(int index) const; /** For debugging. */ void printMaxPathOFlows(int index) const; }; #endif
[ "peredereeva@gmail.com" ]
peredereeva@gmail.com
bd34beaf8488bbac4d65902bed87b14be39267b0
211dc4d24f6c06cb1d3b67f9106517d6ab1a2159
/ABC/089/March.cpp
6c7ef6dcf34c123621ad6e72a7f87b966842648c
[]
no_license
oonota/atcoder
afe565f89fa646a1d0d4c30aeff51a9cf8150343
e7a6e0220583ad91e3fbb40257eb94d9f2b85565
refs/heads/master
2021-04-15T03:41:17.775133
2018-12-21T12:24:03
2018-12-21T12:24:03
126,293,973
0
0
null
null
null
null
UTF-8
C++
false
false
806
cpp
#include<bits/stdc++.h> #define print(x) std::cout << x << std::endl using namespace std; typedef vector<int> VI; typedef vector<string> VS; //container util #define SORT(c) sort((c).begin(),(c).end()) //repetition #define FOR(i,a,b) for(int i=(a);i<(b);++i) #define REP(i,n) FOR(i,0,n) int main(){ string s; int N; long long m, a, r, c, h; long long D[5]; int P[10] = {0, 0, 0, 0, 0, 0, 1, 1, 1, 2}; int Q[10] = {1, 1, 1, 2, 2, 3, 2, 2, 3, 3}; int R[10] = {2, 3, 4, 3, 4, 4, 3, 4, 4, 4}; m = a = r = c = h = 0; cin >> N; REP(i,N){ cin >> s; if(s[0] == 'M') m++; if(s[0] == 'A') a++; if(s[0] == 'R') r++; if(s[0] == 'C') c++; if(s[0] == 'H') h++; } D[0] = m,D[1]=a,D[2]=r,D[3]=c,D[4]=h; long long res=0; REP(i,10){ res+=D[P[i]]*D[Q[i]]*D[R[i]]; } print(res); }
[ "taotaotao0310@gmail.com" ]
taotaotao0310@gmail.com
6e04e4417a67aba05efcbd444c4d832e0f150c73
52f64708ba7560f5d16eef95b057a993ab73c787
/Codeforces/1000/F.cpp
5499d2d40cf6580f6e20f0395fe3ba2c221cbf5c
[]
no_license
ckpiyanon/submission
1c5709755afeba8b5087fa29b12f9c2c931c4b68
7b3f546e3c1e10787a24f567c9f2ec1366bbaf5a
refs/heads/master
2022-10-28T18:42:34.937505
2020-06-15T22:00:19
2020-06-15T22:00:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,370
cpp
#include <bits/stdc++.h> #define pii pair<int, int> #define x first #define y second using namespace std; const int N = 1<<19, INF = 1e9; int n, m, A[N], ans[N]; pii pos[N], t[N<<1]; vector<pii> que[N]; void update(int x, int v, int v2, int p = 1, int l = 1, int r = n) { if(l == r) { t[p] = pii(v, v2); return; } int m = (l + r) >> 1; if(x <= m) update(x, v, v2, p<<1, l, m); else update(x, v, v2, p<<1|1, m+1, r); t[p] = t[p<<1].x < t[p<<1|1].x ? t[p<<1] : t[p<<1|1]; } pii query(int x, int y, int p = 1, int l = 1, int r = n) { if(x > r || l > y) return pii(INF, 0); if(x <= l && r <= y) return t[p]; int m = (l + r) >> 1; pii a = query(x, y, p<<1, l, m), b = query(x, y, p<<1|1, m+1, r); return a.x < b.x ? a : b; } int main() { scanf("%d", &n); for(int i = 1; i <= n; ++i) scanf("%d", A+i); scanf("%d", &m); for(int i = 1, a, b; i <= m; ++i) { scanf("%d %d", &a, &b); que[b].emplace_back(a, i); } for(int i = 1; i <= n; ++i) { if(pos[A[i]].y) update(pos[A[i]].y, INF, 0); pos[A[i]].x = pos[A[i]].y; pos[A[i]].y = i; update(i, pos[A[i]].x, A[i]); for(auto x : que[i]) { pii z = query(x.x, i); if(z.x < x.x) ans[x.y] = z.y; } } for(int i = 1; i <= m; ++i) printf("%d\n", ans[i]); }
[ "30414878+win11905@users.noreply.github.com" ]
30414878+win11905@users.noreply.github.com
ae8ee015c23144389b48d394fe828ff5f088e262
6d401de5ec5e1c326ae7d27c12dbaf6c9ef54d50
/source/152.cpp
843aaad2c4e6eb95dd498a30990cff139f36b9b3
[]
no_license
wangtss/leetcodePractice
8a0f038937b5cda2ca3aaf97d7eae0f60e28287f
e0e7d8bba24d344fdd4a313b142140dd30f07fe9
refs/heads/master
2021-09-06T01:16:58.867438
2018-02-01T08:11:08
2018-02-01T08:11:08
104,712,341
0
0
null
null
null
null
UTF-8
C++
false
false
536
cpp
int maxProduct(vector<int>& nums) { if (nums.empty()) return 0; int len = nums.size(), global; vector<int> local_min(len, 0), local_max(len, 0); local_min[0] = local_max[0] = global = nums[0]; for (int index = 1; index < len; ++index) { local_max[index] = max(max(local_max[index - 1] * nums[index], nums[index]), nums[index] * local_min[index - 1]); local_min[index] = min(min(local_min[index - 1] * nums[index], nums[index]), nums[index] * local_max[index - 1]); global = max(global, local_max[index]); } return global; }
[ "wangtstim@gmail.com" ]
wangtstim@gmail.com
833946bc0a2c0e86582793016ec940845092269b
a2e1afcba56037065070eb9e0fa44996f85083ee
/inc/zprimecrosssection.h
50571ef3ed707061372a62e5b767e1740c08c223
[]
no_license
markrosslonergan/forlorn-extremity
42accbeb3b06cd1838dbf366a47df7f1fd26c06d
d2f4e1c847e595a6f04d55086e9abadc6359b6b4
refs/heads/master
2021-01-20T18:14:52.218668
2017-09-26T14:49:09
2017-09-26T14:49:09
90,910,257
0
1
null
2017-08-28T18:32:36
2017-05-10T21:33:05
Jupyter Notebook
UTF-8
C++
false
false
26,377
h
#include <gsl/gsl_integration.h> #include <algorithm> #include <math.h> #include <gsl/gsl_rng.h> #include <string> #include <sstream> #include <iomanip> #define FLUX_CUTOFF 10.0 #define POSNU 0 #define POSNUBAR 1 #define NEGNU 2 #define NEGNUBAR 3 #define MP 0.13957018 #define MMu 0.1056583715 #define Me 0.0005109989 #define MKao 0.493677 #define PI 3.14159 #define Mw 80.385 #define MZ 91.1876 #define Gf 1.16637e-5 #define Mnuc 1 /********************************************************************** * * * Flux Temp * * * **********************************************************************/ double fluxPosNuMu (double En){ std::vector<double > list = {4.544e-11,1.7132e-10,2.224e-10,2.67e-10,3.316e-10,3.64e-10,3.892e-10,4.09e-10,4.322e-10,4.482e-10,4.558e-10,4.584e-10,4.55e-10,4.506e-10,4.428e-10,4.312e-10,4.156e-10,3.984e-10,3.788e-10,3.578e-10,3.354e-10,3.116e-10,2.878e-10,2.636e-10,2.386e-10,2.138e-10,1.9006e-10,1.6712e-10,1.4556e-10,1.2584e-10,1.0792e-10,9.202e-11,7.804e-11,6.57e-11,5.52e-11,4.624e-11,3.864e-11,3.232e-11,2.71e-11,2.276e-11,1.9178e-11,1.63e-11,1.3856e-11,1.1874e-11,1.0294e-11,8.956e-12,7.87e-12,7.e-12,6.3e-12,5.734e-12,5.23e-12,4.818e-12,4.546e-12,4.22e-12,3.99e-12,3.84e-12,3.63e-12,3.452e-12,3.33e-12,3.202e-12,3.108e-12,2.986e-12,2.884e-12,2.824e-12,2.726e-12,2.646e-12,2.53e-12,2.434e-12,2.366e-12,2.28e-12,2.204e-12,2.12e-12,2.028e-12,1.94e-12,1.868e-12,1.8002e-12,1.7282e-12,1.638e-12,1.5734e-12,1.4928e-12,1.4292e-12,1.3624e-12,1.2998e-12,1.237e-12,1.1716e-12,1.1228e-12,1.064e-12,1.0032e-12,9.53e-13,9.122e-13,8.562e-13,8.174e-13,7.682e-13,7.264e-13,6.864e-13,6.526e-13,6.032e-13,5.714e-13,5.378e-13,5.058e-13,4.744e-13,4.454e-13,4.206e-13,3.914e-13,3.668e-13,3.46e-13,3.23e-13,3.026e-13,2.812e-13,2.606e-13,2.428e-13,2.258e-13,2.094e-13,1.9138e-13,1.774e-13,1.6296e-13,1.4858e-13,1.353e-13,1.2194e-13,1.0984e-13,9.954e-14,8.89e-14,7.934e-14,6.984e-14,6.074e-14,5.19e-14,4.45e-14,3.708e-14,3.074e-14,2.44e-14,1.956e-14,1.5684e-14,1.2396e-14,9.572e-15,6.668e-15,3.942e-15,1.8782e-15,5.476e-16,1.213e-16,8.27e-17,3.866e-17,1.9776e-17,8.988e-19,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.}; double ans = 0; if(En <= 10.0 && En >=0){ ans = list[floor(En/0.05)]; } return ans; } double fluxPosNuMuBar (double En){ std::vector<double > list ={5.12e-11,1.1342e-10,6.6e-11,4.056e-11,3.246e-11,2.79e-11,2.602e-11,2.498e-11,2.342e-11,2.108e-11,1.916e-11,1.739e-11,1.6196e-11,1.4868e-11,1.382e-11,1.2628e-11,1.181e-11,1.1008e-11,1.0158e-11,9.416e-12,8.694e-12,8.042e-12,7.406e-12,6.886e-12,6.346e-12,5.744e-12,5.194e-12,4.674e-12,4.202e-12,3.806e-12,3.436e-12,3.014e-12,2.682e-12,2.346e-12,2.106e-12,1.8482e-12,1.6376e-12,1.423e-12,1.2698e-12,1.1094e-12,9.598e-13,8.142e-13,7.184e-13,6.164e-13,5.276e-13,4.496e-13,3.756e-13,3.246e-13,2.782e-13,2.324e-13,2.02e-13,1.7382e-13,1.4764e-13,1.1998e-13,1.0008e-13,8.408e-14,7.142e-14,6.094e-14,5.194e-14,4.276e-14,3.912e-14,3.168e-14,2.454e-14,2.042e-14,1.6712e-14,1.5554e-14,1.3624e-14,1.4772e-14,1.2256e-14,1.2502e-14,1.1038e-14,7.872e-15,8.282e-15,6.79e-15,6.004e-15,5.004e-15,4.546e-15,4.598e-15,2.858e-15,3.148e-15,2.436e-15,2.56e-15,3.224e-15,1.7208e-15,1.854e-15,1.0742e-15,1.099e-15,8.552e-16,7.386e-16,1.3184e-15,1.2522e-15,4.532e-16,7.848e-16,1.0072e-15,6.102e-16,1.597e-15,3.26e-15,3.574e-15,1.1458e-15,1.2766e-16,1.0514e-16,1.0444e-16,8.738e-17,6.372e-17,7.83e-17,4.394e-17,3.38e-17,2.354e-17,1.9926e-17,1.8394e-17,1.358e-17,1.139e-17,1.0468e-17,6.418e-18,5.618e-18,5.4e-18,3.248e-18,2.766e-18,2.384e-18,1.8048e-18,1.8884e-18,1.0152e-18,1.278e-18,9.39e-19,5.468e-19,7.88e-19,4.134e-19,4.654e-19,4.588e-19,2.77e-19,3.864e-20,1.6598e-19,1.1708e-19,3.686e-20,0.,3.566e-20,8.98e-20,8.41e-20,0.,0.,0.,0.,0.,2.422e-20,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.}; double ans = 0; if(En <= 10.0 && En >=0){ ans = list[floor(En/0.05)]; } return ans; } double fluxNegNuMu (double En){ std::vector<double > list = {4.596e-11,1.1806e-10,7.452e-11,4.676e-11,5.14e-11,3.594e-11,3.552e-11,3.71e-11,3.668e-11,3.54e-11,3.402e-11,3.236e-11,3.11e-11,2.986e-11,2.85e-11,2.714e-11,2.604e-11,2.472e-11,2.384e-11,2.282e-11,2.174e-11,2.088e-11,1.9934e-11,1.887e-11,1.7652e-11,1.664e-11,1.5472e-11,1.436e-11,1.3218e-11,1.2106e-11,1.1066e-11,1.0116e-11,9.154e-12,8.268e-12,7.45e-12,6.672e-12,6.006e-12,5.326e-12,4.75e-12,4.252e-12,3.772e-12,3.338e-12,2.972e-12,2.62e-12,2.342e-12,2.06e-12,1.8558e-12,1.6398e-12,1.4706e-12,1.3154e-12,1.166e-12,1.0636e-12,9.644e-13,8.634e-13,7.994e-13,7.238e-13,6.75e-13,6.1e-13,5.852e-13,5.41e-13,5.318e-13,5.004e-13,4.782e-13,4.594e-13,4.382e-13,4.236e-13,4.104e-13,3.89e-13,3.772e-13,3.656e-13,3.518e-13,3.276e-13,3.138e-13,3.02e-13,2.942e-13,2.77e-13,2.698e-13,2.602e-13,2.526e-13,2.38e-13,2.344e-13,2.176e-13,2.126e-13,2.024e-13,1.909e-13,1.8716e-13,1.7328e-13,1.6778e-13,1.59e-13,1.5006e-13,1.4584e-13,1.4388e-13,1.3602e-13,1.2604e-13,1.1878e-13,1.1336e-13,1.0544e-13,1.0198e-13,9.62e-14,9.242e-14,8.728e-14,8.078e-14,7.682e-14,7.092e-14,6.776e-14,6.402e-14,5.928e-14,5.606e-14,5.302e-14,5.042e-14,4.678e-14,4.322e-14,4.024e-14,3.756e-14,3.558e-14,3.254e-14,3.04e-14,2.838e-14,2.57e-14,2.414e-14,2.18e-14,1.971e-14,1.827e-14,1.617e-14,1.4652e-14,1.313e-14,1.0906e-14,9.296e-15,7.814e-15,6.368e-15,5.026e-15,4.09e-15,3.34e-15,2.564e-15,1.882e-15,1.0478e-15,4.794e-16,1.3788e-16,1.3246e-17,4.494e-18,2.564e-18,1.5318e-18,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.}; double ans = 0; if(En <= 10.0 && En >=0){ ans = list[floor(En/0.05)]; } return ans; } double fluxNegNuMuBar (double En){ std::vector<double > list = {4.314e-11,1.568e-10,1.9462e-10,2.282e-10,2.638e-10,2.876e-10,2.954e-10,2.958e-10,3.e-10,2.97e-10,2.894e-10,2.812e-10,2.69e-10,2.574e-10,2.442e-10,2.304e-10,2.15e-10,1.996e-10,1.8354e-10,1.6822e-10,1.5316e-10,1.3814e-10,1.236e-10,1.101e-10,9.754e-11,8.538e-11,7.372e-11,6.302e-11,5.356e-11,4.524e-11,3.796e-11,3.16e-11,2.622e-11,2.166e-11,1.7834e-11,1.457e-11,1.1882e-11,9.668e-12,7.874e-12,6.36e-12,5.154e-12,4.132e-12,3.33e-12,2.692e-12,2.162e-12,1.7674e-12,1.4272e-12,1.1414e-12,9.24e-13,7.556e-13,6.056e-13,4.824e-13,3.954e-13,3.276e-13,2.646e-13,2.076e-13,1.7414e-13,1.3962e-13,1.2156e-13,1.0222e-13,7.838e-14,6.656e-14,5.722e-14,4.764e-14,4.59e-14,4.538e-14,3.656e-14,3.226e-14,3.074e-14,2.75e-14,2.494e-14,2.088e-14,1.9064e-14,1.6296e-14,1.497e-14,1.5674e-14,1.2404e-14,1.3228e-14,1.099e-14,1.0264e-14,9.8e-15,9.968e-15,8.958e-15,4.812e-15,4.392e-15,3.946e-15,3.524e-15,2.678e-15,2.512e-15,1.9338e-15,1.5092e-15,1.196e-15,1.2582e-15,9.48e-16,7.162e-16,6.578e-16,5.616e-16,5.412e-16,4.878e-16,2.954e-16,2.48e-16,2.07e-16,1.8002e-16,1.374e-16,1.715e-16,8.784e-17,9.472e-17,6.076e-17,4.826e-17,4.144e-17,4.122e-17,2.226e-17,1.8512e-17,1.3066e-17,1.6158e-17,1.3324e-17,6.95e-18,7.616e-18,6.99e-18,5.042e-18,3.934e-18,2.528e-18,1.3784e-18,1.4774e-18,6.934e-19,2.052e-18,3.206e-19,3.24e-19,2.26e-19,2.79e-19,4.228e-20,7.886e-20,3.776e-20,1.3424e-19,1.1888e-19,0.,2.872e-20,0.,0.,0.,0.,0.,0.,2.872e-20,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.}; double ans = 0; if(En <= 10.0 && En >=0){ ans = list[floor(En/0.05)]; } return ans; } double flux(double En, int selector){ double ans = 0; switch (selector){ case POSNU: ans = fluxPosNuMu(En); break; case POSNUBAR: ans = fluxPosNuMuBar(En); break; case NEGNU: ans = fluxNegNuMu(En); break; case NEGNUBAR: ans = fluxNegNuMuBar(En); break; } return ans; } double fluxPosNuMuNormed (double En){ return fluxPosNuMu(En)/5.19358e-10; } double fluxPosNuMuBarNormed (double En){ return fluxPosNuMuBar(En)/3.26002e-11; } double fluxNegNuMuNormed (double En){ return fluxNegNuMu(En)/5.42276e-11; } double fluxNegNuMuBarNormed (double En){ return fluxNegNuMuBar(En)/2.9282e-10; } double fluxNormed(double En, int selector){ double ans = 0; switch (selector){ case POSNU: ans = fluxPosNuMuNormed(En); break; case POSNUBAR: ans = fluxPosNuMuBarNormed(En); break; case NEGNU: ans = fluxNegNuMuNormed(En); break; case NEGNUBAR: ans = fluxNegNuMuBarNormed(En); break; } return ans; } double fluxTempOldOBSOLETE(double En) { double result =0; if (0<=En && En <= 12.55){ double kflux = 1000/50.0; result = kflux*(4.427824623217513e-14*pow(En,7)-9.971799853312788e-13*pow(En,6) + 9.231207886825193e-12*pow(En,5) - 4.493562336824403e-11*pow(En,4) + 1.2126620243628683e-10*pow(En,3) - 1.7206489225632898e-10*pow(En,2)+ 1.0055899381298395e-10*En - 5.096969325003961e-13); } return result; } double fluxTemp(double En){ double result = 0 ; double kflux = 1000/50.0; double heavi = 1.0; if(En > 4){ heavi = 0.0; } double ktop=(1.51364530023684e-9*pow(En,2.5608335856419675)); double kbot= (pow(0.04173905329386966 + pow(En,1.942453984231271),3.7059504555184652)*(3986.923260185046/pow(En,4.646872292396358) + 0.14401684718576835*pow(En,2.5608335856419675))); double ptop=(5.479159036783009e-7*pow(En,0.29615835741178265)); double pbot=(pow(1.7304776909979156 + pow(En,1.215969360903414),11.5953242599689)* (0.05068826655476809*pow(En,0.29615835741178265) + 33176.287610674655/pow(1.7304776909979156 + En,11.5953242599689))); result = kflux*(ktop/kbot+heavi*ptop/pbot); return result; } double fluxTempNormed (double En) { return fluxTemp(En)/4.698e-10; } /********************************************************************** * * * KINEMATICS * * * **********************************************************************/ double mandelT (double Es, double Ev, double mN) { return 2*mN*(Es-Ev); } double mandelS (double Ev, double mV, double mN) { return mN*mN+mV*mV+2*mN*Ev; } double LABcos (double Es, double Ms, double Ev, double Mv, double Mn){ double top = (2*Es*Ev+2*Es*Mn-2*Ev*Mn-Ms*Ms-Mv*Mv); double bot = 2*sqrt(Es*Es-Ms*Ms)*sqrt(Ev*Ev-Mv*Mv); return top/bot; } double LABesMin (double Ev, double ms, double mv, double mn){ double b1 = (Ev+mn)*(2*Ev*mn+ms*ms+mv*mv); double b2= (Ev-mv)*(Ev+mv)*(2*Ev*mn + 2*mn*ms - ms*ms + mv*mv)*(2*Ev*mn -ms*(2*mn + ms) + mv*mv); double b3= 2*(2*Ev*mn+mn*mn+mv*mv); return (b1-sqrt(b2))/b3; } double LABesMax (double Ev, double ms, double mv, double mn){ double b1 = (Ev+mn)*(2*Ev*mn+ms*ms+mv*mv); double b2= (Ev-mv)*(Ev+mv)*(2*Ev*mn + 2*mn*ms - ms*ms + mv*mv)*(2*Ev*mn -ms*(2*mn + ms) + mv*mv); double b3= 2*(2*Ev*mn+mn*mn+mv*mv); return (b1+sqrt(b2))/b3; } double mandelTmin (double ms, double Ev, double mv, double mn) { return mandelT(LABesMax(Ev,ms,mv,mn), Ev, mn); } double mandelTmax (double ms, double Ev, double mv, double mn) { return mandelT(LABesMin(Ev,ms,mv,mn), Ev, mn); } double LABevMin(double ms, double mv, double mn){ return -(ms*ms+mv*mv-2*mn*ms)/(2*mn-2*ms); } /********************************************************************** * * * Form Factor Cross Section * * * **********************************************************************/ double CSffactor (double Qs, double Ev, double mz, double ms, double X, double U) { //My Differentia CSection. double s2th= 0.23149; double ans = 0; double gp = 1; double MA = 1.39; double gA = 1.2671; double MV = 0.84; double Ds = 0.08; double muN = -1.91304273; double muP = 2.792847351; double t3 = -1; double tau = Qs/(4*Mnuc*Mnuc); double W = 4*Mnuc*Ev-Qs-ms*ms; //Sachs form factors double GD = 1/((1+Qs/(MV*MV))*(1+Qs/(MV*MV))); double GEn = 0; double GEp = GD; double GMn = muN*GD; double GMp = muP*GD; //Dirac and Pauly FormFac double F1EMN = (GEn+tau*GMn)/(1+tau); double F2EMN = (GMn-GEn)/(1+tau); double F1EMP = (GEp+tau*GMp)/(1+tau); double F2EMP = (GMp-GEp)/(1+tau); // according to 1007:4730 appendix isoscalar constsitant with 0 double F1S =0; double F2S = 0; //write weak through dirac and pauli form fac double F1Z = (0.5-s2th)*(F1EMP-F1EMN)*t3-s2th*(F1EMP+F1EMN)-0.5*F1S; double F2Z = (0.5-s2th)*(F2EMP-F2EMN)*t3-s2th*(F2EMP+F2EMN)-0.5*F2S; double FA = gA/((1+Qs/(MA*MA))*(1+Qs/(MA*MA))); double FAS = Ds/((1+Qs/(MA*MA))*(1+Qs/(MA*MA))); double FAZ = t3*0.5*FA-0.5*FAS; double FPZ = 2*Mnuc*Mnuc*FAZ/(MP*MP+Qs); //Write A,B,C in terms of all nucelon, dirac, pauli and axial weak double A = (ms*ms+Qs)/(Mnuc*Mnuc)*((FAZ*FAZ*(1+tau)+(F1Z*F1Z-tau*F2Z*F2Z)*(1-tau)+4*tau*F1Z*F2Z)); double B = 4*tau*FAZ*(F1Z+F2Z); double C = 0.25*(FAZ*FAZ+F1Z*F1Z+tau*F2Z*F2Z); ans = Gf*Gf*MZ*MZ*MZ*MZ*U*U*X*X*Mnuc*Mnuc*Mnuc*Mnuc*(A+B*W/(Mnuc*Mnuc)+C*W*W/(Mnuc*Mnuc*Mnuc*Mnuc))/(8*PI*Ev*Ev*(mz*mz+Qs)*(mz*mz+Qs)); return ans; } double CSProton(double t, double Ev, double mz, double ms, double X, double U) { //My Differentia CSection. double Qs = -t; double mN=1; double ee = sqrt(4*3.14148/137.0); double gX=1.0; double MV = 0.84; double cw = 80.385/91.1876; //Sachs form factors double GD = 1/((1+Qs/(MV*MV))*(1+Qs/(MV*MV))); double GE = GD; //0.938272; double muN = 2.792847351; // -1.91304273 //0.939565; double GM = muN*GD; double tau = Qs/(4*mN*mN); //Dirac and Pauly FormFac double F1 = (GE+tau*GM)/(1+tau); double F2 = (GM-GE)/(1+tau); double A = 8*F1*F1*(8*Ev*Ev/(t-ms*ms)+4*Ev/mN+t/(mN*mN)+2); double B = 4*F2*F2*(-4*Ev*Ev*t/(mN*mN*(t-ms*ms))-2*Ev*t/(mN*mN*mN)+(ms*ms+t)/(mN*mN)+ ms*ms*t/(4*mN*mN*mN)); double C = 8*F1*F2*(ms*ms +2*t)/(mN*mN); double Anew = 8*F1*F1*(8*Ev*Ev/(ms*ms-t)-4*Ev/mN-t/(mN*mN)+2); double Bnew = 4*t*F2*F2/(mN*mN)*(-4*Ev*Ev/(ms*ms-t)+2*Ev/mN-ms*ms/(4*mN*mN)+1); double Cnew = 8*F1*F2*(4*Ev*ms*ms/(mN*(ms*ms-t))-ms*ms/(mN*mN)); double ans = pow(ee*gX*cw*U*X,2)*(t-ms*ms)/(32*3.14159*Ev*Ev*pow(mz*mz-t,2))*(A+B+C); double ansnew = pow(ee*gX*cw*U*X,2)*(ms*ms-t)/(256*3.14159*Ev*Ev*pow(mz*mz-t,2))*(Anew+Bnew+Cnew); return ansnew; } double CSNeutron(double t, double Ev, double mz, double ms, double X, double U) { //My Differentia CSection. double Qs = -t; double mN=1; double ee = sqrt(4*3.14148/137.0); double gX=1.0; double MV = 0.84; double cw = 80.385/91.1876; //Sachs form factors double GD = 1/((1+Qs/(MV*MV))*(1+Qs/(MV*MV))); double GE = 0; //0.938272; double muN = -1.91304273; //0.939565; double GM = muN*GD; double tau = Qs/(4*mN*mN); //Dirac and Pauly FormFac double F1 = (GE+tau*GM)/(1+tau); double F2 = (GM-GE)/(1+tau); double A = 8*F1*F1*(8*Ev*Ev/(t-ms*ms)+4*Ev/mN+t/(mN*mN)+2); double B = 4*F2*F2*(-4*Ev*Ev*t/(mN*mN*(t-ms*ms))-2*Ev*t/(mN*mN*mN)+(ms*ms+t)/(mN*mN)+ ms*ms*t/(4*mN*mN*mN)); double C = 8*F1*F2*(ms*ms +2*t)/(mN*mN); double Anew = 8*F1*F1*(8*Ev*Ev/(ms*ms-t)-4*Ev/mN-t/(mN*mN)+2); double Bnew = 4*t*F2*F2/(mN*mN)*(-4*Ev*Ev/(ms*ms-t)+2*Ev/mN-ms*ms/(4*mN*mN)+1); double Cnew = 8*F1*F2*(4*Ev*ms*ms/(mN*(ms*ms-t))-ms*ms/(mN*mN)); double ansnew = pow(ee*gX*cw*U*X,2)*(ms*ms-t)/(256*3.14159*Ev*Ev*pow(mz*mz-t,2))*(Anew+Bnew+Cnew); double ans = pow(ee*gX*cw*U*X,2)*(t-ms*ms)/(32*3.14159*Ev*Ev*pow(mz*mz-t,2))*(A+B+C); return ansnew; } double CSCarbon(double t, double Ev, double mz, double ms, double X, double U) { return 6*CSNeutron(t,Ev,mz,ms,X,U)+6*CSProton(t,Ev,mz,ms,X,U); } struct TcsParams { double Ev; double mz; double ms; double X; double U;}; double csToBeInt (double tvar, void * p) { struct TcsParams * params = (struct TcsParams *)p; return CSffactor(-tvar, params->Ev, params->mz, params->ms,params->X, params->U); } double totalCS (double Evin, double Mz, double Ms, double X, double U) { double ans = 0; // Function to integrate the diff cs from its Max and Min Mandel T bounds for any given Neutrino Energy if(Evin >= LABevMin(Ms,0.0,Mnuc)){ double tint1 = mandelTmax(Ms,Evin,0.0,Mnuc); double tint2 = mandelTmin(Ms,Evin,0.0,Mnuc); gsl_integration_workspace * w = gsl_integration_workspace_alloc (1000); struct TcsParams params = {Evin, Mz, Ms,X,U}; double result,error; gsl_function F; F.function = &csToBeInt; F.params = &params; //std::cout<<std::setprecision(12)<<" Evin: "<<Evin<<" ms: "<<Ms<<" mz: "<<Mz<<" Evin2: "<<params.Ev<<" ms: "<<params.ms<<" mz: "<<params.mz<<std::endl; gsl_integration_qags (&F,tint1, tint2 ,0, 1e-4, 1000, w, &result, &error); gsl_integration_workspace_free (w); ans = result; } return ans; } double csToBeIntProton (double tvar, void * p) { struct TcsParams * params = (struct TcsParams *)p; return CSProton(tvar, params->Ev, params->mz, params->ms,params->X, params->U); } double csToBeIntNeutron (double tvar, void * p) { struct TcsParams * params = (struct TcsParams *)p; return CSNeutron(tvar, params->Ev, params->mz, params->ms,params->X, params->U); } double totalCSProton (double Evin, double Mz, double Ms, double X, double U) { double ans = 0; // Function to integrate the diff cs from its Max and Min Mandel T bounds for any given Neutrino Energy if(Evin >= LABevMin(Ms,0.0,Mnuc)){ double tint1 = mandelTmax(Ms,Evin,0.0,Mnuc); double tint2 = mandelTmin(Ms,Evin,0.0,Mnuc); gsl_integration_workspace * w = gsl_integration_workspace_alloc (1000); struct TcsParams params = {Evin, Mz, Ms,X,U}; double result,error; gsl_function F; F.function = &csToBeIntProton; F.params = &params; //std::cout<<std::setprecision(12)<<" Evin: "<<Evin<<" ms: "<<Ms<<" mz: "<<Mz<<" Evin2: "<<params.Ev<<" ms: "<<params.ms<<" mz: "<<params.mz<<std::endl; gsl_integration_qags (&F,tint1, tint2 ,0, 1e-4, 1000, w, &result, &error); gsl_integration_workspace_free (w); ans = result; } return ans; } double totalCSNeutron (double Evin, double Mz, double Ms, double X, double U) { double ans = 0; // Function to integrate the diff cs from its Max and Min Mandel T bounds for any given Neutrino Energy if(Evin >= LABevMin(Ms,0.0,Mnuc)){ double tint1 = mandelTmax(Ms,Evin,0.0,Mnuc); double tint2 = mandelTmin(Ms,Evin,0.0,Mnuc); gsl_integration_workspace * w = gsl_integration_workspace_alloc (1000); struct TcsParams params = {Evin, Mz, Ms,X,U}; double result,error; gsl_function F; F.function = &csToBeIntNeutron; F.params = &params; //std::cout<<std::setprecision(12)<<" Evin: "<<Evin<<" ms: "<<Ms<<" mz: "<<Mz<<" Evin2: "<<params.Ev<<" ms: "<<params.ms<<" mz: "<<params.mz<<std::endl; gsl_integration_qags (&F,tint1, tint2 ,0, 1e-4, 1000, w, &result, &error); gsl_integration_workspace_free (w); ans = result; } return ans; } std::vector<double > MaxTotalCs(double Mz, double Ms, double X, double U){ // Very Simple 1-D raster scan to find maximum Total CS and its corresponding Ev double emax = 0; double csmax = 0; double tempCS = 0; for( double ei = LABevMin(Ms,0.0,Mnuc); ei<=FLUX_CUTOFF ;ei=ei+0.0001){ tempCS = 6*totalCSProton(ei, Mz, Ms, X, U)+6*totalCSNeutron(ei,Mz,Ms,X,U); if(tempCS > csmax){ csmax = tempCS; emax = ei; } } std::vector<double > ans = {emax,csmax}; return ans; } std::vector<double > MaxDiffCs(double Mz, double Ms, double X, double U){ // Very Simple 1-D raster scan to find maximum Diff CS and its corresponding Ev. Making assumption that for each Ev, the max will be at the tmin or tmax (to within 20%) double emax = 0; double csmax = 0; double tempCS = 0; double tmint = 0; double tmaxt = 0; for( double ei = LABevMin(Ms,0.0,Mnuc); ei<=FLUX_CUTOFF;ei=ei+0.01){ tmaxt = mandelTmax(Ms,ei,0.0,Mnuc); tmint = mandelTmin(Ms,ei,0.0,Mnuc); tempCS = std::max(CSCarbon(tmaxt, ei, Mz,Ms, 1,1) ,CSCarbon(tmint, ei, Mz,Ms, 1,1) ); if(tempCS >= csmax){ csmax = tempCS; emax = ei; } } std::vector<double > ans = {emax,1.2*csmax}; return ans; } /********************************************************************** * * * Events! * * * **********************************************************************/ /*double totalevents (double X, double U, double mz, double ms) { double result=0; double binw = 0.01; double POT = 6.46e20; double ATOMS = 3.5e31*pow(5/6.1,3); double GEV2cm = pow(1e9*5.068e4,-2); double eE = 0.9; double eC = 0.75; double lowBound = LABevMin(ms,0.0,Mnuc); for(double en = lowBound; en <=FLUX_CUTOFF; en=en+binw){ // std::cout<<result<<std::endl; result = result +12*binw*GEV2cm*eC*eE*totalCS(en,mz,ms,X,U)*fluxTemp(en)*POT*ATOMS; } return result; } */ double POT(int selector){ double ans = 1; switch (selector){ case POSNU: ans = 6.46e20; break; case POSNUBAR: ans= 6.46e20; break; case NEGNU: ans = 11.27e20; break; case NEGNUBAR: ans= 11.27e20; break; } return ans; } double CSmodifier(int selector){ double ans = 1; switch (selector){ case POSNU: ans = 1.0; break; case POSNUBAR: ans= 1.0;//was 0.33 break; case NEGNU: ans = 1.0; break; case NEGNUBAR: ans= 1.0;//was 0.33 break; } return ans; } double totalevents2 (double X, double U, double mz, double ms, int selector) { double result=0; double binw = 0.01; double ATOMS = 3.5e31*pow(5/6.1,3); double GEV2cm = pow(1e9*5.068e4,-2); double eE = 0.9; double eC = 0.75; double lowBound = LABevMin(ms,0.0,Mnuc); for(double en = lowBound; en <=FLUX_CUTOFF; en=en+binw){ // std::cout<<result<<std::endl; result = result +CSmodifier(selector)*binw*GEV2cm*eC*eE*(6*totalCSNeutron(en,mz,ms,X,U)+6*totalCSProton(en,mz,ms,X,U))*flux(en,selector)*POT(selector)*ATOMS; } return result; } /********************************************************************** * * * Subsequent Decay t body * * * **********************************************************************/ double RFegamma(double ms, double mgam, double m5){ return (ms*ms+mgam*mgam-m5*m5)/(2*ms); } double egamma(double es, double ms, double mgam, double m5, gsl_rng * r){ double gamma = es/ms; double beta = sqrt(1-pow(gamma,-2)); double RFcosth = 2*gsl_rng_uniform(r)-1; double result = gamma*RFegamma(ms, mgam, m5)+gamma*beta*sqrt(pow(RFegamma(ms, mgam,m5),2)-mgam*mgam)*RFcosth; return result; } /********************************************************************** * * * MC calc * * * **********************************************************************/ double SampleNuFlux(double ms, gsl_rng * r, int selector){ double Evin=0; double mc2 = 0; Evin = (FLUX_CUTOFF-LABevMin(ms,0.0,Mnuc))*gsl_rng_uniform(r)+LABevMin(ms,0.0,Mnuc); mc2 = gsl_rng_uniform(r); //howmanyrngs++; while(mc2 > fluxNormed(Evin,selector)){ Evin = (FLUX_CUTOFF-LABevMin(ms,0.0,Mnuc))*gsl_rng_uniform(r)+LABevMin(ms,0.0,Mnuc); mc2 = gsl_rng_uniform(r); //howmanyrngs++; } return Evin; } std::vector<double > MCkin (double mz, double ms, gsl_rng * r, double CSmax, int selector){ double howmanyrngs=2; //Currently Broken double Evin = SampleNuFlux(ms,r,selector); double tmax= mandelTmax(ms,Evin,0.0,Mnuc); double tmin = mandelTmin(ms,Evin,0.0,Mnuc); double tout = (tmax-tmin)*gsl_rng_uniform(r)+tmin; double func = CSCarbon(tout, Evin, mz, ms, 1.0, 1.0); double mc = CSmax*gsl_rng_uniform(r); // Loop until an event is sampled from the distributions while(mc > func){ Evin = SampleNuFlux(ms, r, selector); tmax= mandelTmax(ms,Evin,0.0,Mnuc); tmin = mandelTmin(ms,Evin,0.0,Mnuc); tout = (tmax-tmin)*gsl_rng_uniform(r)+tmin; func = CSCarbon(tout, Evin, mz, ms, 1.0, 1.0);///totcs; mc = CSmax*gsl_rng_uniform(r); //howmanyrngs++; } // Calculate end observables for this event double Esout = (2*Evin*Mnuc + tout)/(2*Mnuc); double costh = LABcos(Esout, ms, Evin, 0.0 , Mnuc); double Edecay = egamma(Esout, ms, 0.0, 0, r); std::vector<double > event = {Evin,tout,Esout,costh,Edecay,Esout/ms, howmanyrngs}; return event; } int MCmassrun( double mz, double ms, int numEvents, gsl_rng * r,int selector) { // Takes an input pair of Ms and Mz, along with a initilised random number generator, and a number of events to generate. std::vector<double > event ; std::stringstream str; str.str( std::string() ); str.clear(); std::stringstream str2; str2.str( std::string() ); str2.clear(); std::ofstream myfile; std::ofstream myfileHist; //What I want to name the files, str << std::fixed<<std::setprecision(3) << "MC_"<<ms<<"_"<<mz<< ".dat"; str2 << std::fixed<<std::setprecision(3) << "HIST_"<<ms<<"_"<<mz<< ".dat"; myfile.open (str.str().c_str()); //Send as a standard C-style string myfileHist.open (str2.str().c_str()); //Send as a standard C-style string myfileHist<<"########## Ms | Mz | Total Num Sterile | MC points ##########"<<std::endl; myfileHist<<ms<<"\t"<<mz<<"\t"<<totalevents2(1,1,mz,ms, selector)<<"\t"<<numEvents<<std::endl; //Maximum Total CS for normalisation sampling. std::vector<double > CSmax = MaxDiffCs(mz,ms,1,1); for(int j=0; j<numEvents; j++){ event = MCkin(mz,ms,r,CSmax[1],selector); //Get Event //for(int i=0; i<event.size();i++){ //Print events to fil // Ev tout Esout Costh Edecay Esout/ms how many rngs // myfile<<std::fixed<<std::setprecision(6)<<event[0]<<"\t"<<event[1]<<"\t"<<event[2]<<"\t"<<event[3]<<"\t"<<event[4]<<"\t"<<event[5]<<std::endl; myfile<<std::fixed<<std::setprecision(6)<<event[2]<<"\t"<<event[3]<<std::endl; //} } myfile.close(); return 0; }
[ "mark.ross-lonergan@durham.ac.uk" ]
mark.ross-lonergan@durham.ac.uk
6976cdac16325fcdc6ac5c7b5c03a65cfc532b13
17b22f7e6b831cfc2e27b37181ed4d8aae693a61
/Frameworks/XEScene.framework/Headers/XSkin.h
5d257da67a8d4dcf8b8cc53a4152c1aee58a5ba1
[]
no_license
cosmos33/MMXEScene
af3409c0d21bd2d56b5845b705564151d612d436
067373218035cead3b761831189c97ca2a024447
refs/heads/master
2020-05-07T13:00:45.392787
2019-06-16T13:41:32
2019-06-16T13:41:32
180,528,299
0
0
null
null
null
null
UTF-8
C++
false
false
5,194
h
/****************************************************************************** @File XSkin.h @Version 1.0 @Created 2017, 4, 14 @Description @HISTORY: ******************************************************************************/ #ifndef _X_SKIN_H_ #define _X_SKIN_H_ #include "XMemBase.h" #include "XString.h" #include "XArray.h" #include "XRefCount.h" #include "XHashTable.h" #include "XCustomGeometry.h" class XSkin; class XSkinData; class XXMLExtendTool; class IXMaterialInstance; class XSkinBlendShapeTarget; class IXSkinUpatedListener : public XMemBase { public: virtual void Update(XSkin* pUpdatedSkin) = 0; }; class XSkin : public XMemBase, public XRefCount { friend class XModelInstance; friend class XModelManager; friend class XHashTable<XString, XSkin*>; public: struct XMeshInfo { XString strName; xint32 nRawMeshIndex; IXMaterialInstance* pMaterialIns; // cloth info xbool bCloth; XString strClothName; XString strClothMaterialName; // 用于自动匹配,模型导出时设置,之后不修改 XMeshInfo() { nRawMeshIndex = -1; pMaterialIns = NULL; bCloth = xfalse; strClothName = ""; } }; public: void Release(); const xchar* GetSkinDatXFile() const; xint32 GetRenderMeshRawIndex(const xchar* szMeshName, xint32 nLODIndex = 0) const; const xchar* GetSkeletonFile() const; const xchar* GetSkinFile() const; xint32 GetLODNum() const { return m_aMeshInfos.Num(); } xint32 GetRawMeshNum(xint32 nLODIndex = 0) const; const xchar* GetRawMeshName(xint32 nRawMeshIndex, xint32 nLODIndex = 0) const; const IXMaterialInstance* GetRawMeshMtlIns(const xchar* szMeshName, xint32 nLODIndex = 0) const; IXMaterialInstance* GetRawMeshMtlIns(const xchar* szMeshName, xint32 nLODIndex = 0); void SetRawMeshMtlIns(const xchar* szMeshName, const xchar* szMtlIns, xint32 nLODIndex = 0); /* 设置rawmesh对应的材质 @notice SetRawMeshMtlIns中未设置skin,morph宏,是错误的逻辑,此处为了防止影响外部调用;此处另加设置材质的函数。 */ void SetRawMeshMtlInsApplyMacros(const xchar* szMeshName, const xchar* szMtlIns, xint32 nLODIndex = 0); xint32 GetRenderMeshNum(xint32 nLODIndex = 0) const; const xchar* GetRenderMeshName(xint32 nRenderMeshIndex, xint32 nLODIndex = 0) const; const XSkinData* GetSkinData() const { return m_pSkinData; } XSkinData* GetSkinData(){ return m_pSkinData; } void SetSkinData(const xchar* szSkinDatXFile); xbool HasBlendShapeTargets() const { return GetBlendShapeTargetNum() > 0; } xint32 GetBlendShapeTargetNum() const { return m_apBlendShapeTargets.Num(); } XSkinBlendShapeTarget* GetBlendShapeTarget(xint32 nIndex) { return m_apBlendShapeTargets[nIndex]; } const XSkinBlendShapeTarget* GetBlendShapeTarget(xint32 nIndex) const { return m_apBlendShapeTargets[nIndex]; } xbool HasBlendShapeTarget(xint32 nRenderMeshIndex) const; void SetSkeletonFile(const xchar* szSkeletonFile); void Save(xbool bRecursive = xfalse) const; void AddSkinUpdatedListener(IXSkinUpatedListener* pListener); void RemoveSkinUpdatedListener(IXSkinUpatedListener* pListener); xint32 GetCorrespondingRenderMeshStartIndex(const xchar* szRawMeshName, xint32 nLODIndex = 0) const; xint32 GetCorrespondingRenderMeshNum(const xchar* szRawMeshName, xint32 nLODIndex = 0) const; xint32 GetFaceNum() const; xbool IsCloth(const xchar* szMeshName); const xchar* GetClothName(const xchar* szMeshName); void SetClothName(const xchar* szMeshName, const xchar* szClothName); const xchar* GetClothMaterialName(const xchar* szMeshName); /* * 添加XSkinBlendShapeTarget * @notice 一般XSkinBlendShapeTarget信息由文件读取,此函数只用于特殊情况 */ xbool AddBlendShapeTarget(XSkinBlendShapeTarget *pBlendShape); private: XSkin(); ~XSkin(); void ResponseUpdated(); const IXMaterialInstance* GetRenderMeshMtlIns(xint32 nMeshIndex, xint32 nLODIndex = 0) const; IXMaterialInstance* GetRenderMeshMtlIns(xint32 nMeshIndex, xint32 nLODIndex = 0); XString m_strSkinFile; XString m_strSkeletonFile; XArray<XString> m_astrBShpTargetFiles; XArray<XArray<XMeshInfo> > m_aMeshInfos; XSkinData* m_pSkinData; XArray<XSkinBlendShapeTarget*> m_apBlendShapeTargets; XArray<IXSkinUpatedListener*> m_aSkinUpdatedListeners; }; #endif
[ "sun.fei@immomo.com" ]
sun.fei@immomo.com
e94a2bfe0233b9ad839ba6675b81e3f8deddf75a
f9fe33be8d046538593398282231b379449213f5
/Solutions/3.10/List.h
e967515566ab60bff8f48d51b31fa6ce9ac1af7f
[]
no_license
liuxinbo1984/cplus-in-action
d777a09523439d66fd2cd941694370724b77b163
1087742fdf6528bc7e810db351492034b24c4dbb
refs/heads/master
2021-04-23T21:20:55.827607
2020-03-25T16:32:10
2020-03-25T16:32:10
250,007,524
0
0
null
null
null
null
UTF-8
C++
false
false
511
h
#if !defined (LIST_H) #define LIST_H // (c) Bartosz Milewski 2000 class Link { public: Link (Link* pNext, int id) : _pNext (pNext), _id (id) {} Link * Next () const { return _pNext; } int Id () const { return _id; } private: int _id; Link * _pNext; }; class List { public: List (): _pHead (0) {} ~List (); void Add ( int id ); Link const * GetHead () const { return _pHead; } bool IsEmpty () const { return _pHead == 0; } private: Link* _pHead; }; #endif
[ "liuxinbo.1984@163.com" ]
liuxinbo.1984@163.com
6a881bfab647dc854fe8e44950c601c253ca05e3
73787a734b04586db054d9a71d3870bb6ac6e49a
/第四章/4.4-贪心/D-Repair the Wall/2021.3.6.cpp
0bdc449a0c33f0f199ebd902a4e722338d50364d
[]
no_license
nanashi100/Codeup_Coding
4d83950ce5c284e20c8ec9f2b4584b9bf409f713
5bee75db7b1dea3a8531579b310cc5bb55b80c6e
refs/heads/main
2023-03-27T16:58:36.690377
2021-03-27T02:05:10
2021-03-27T02:05:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
630
cpp
#include<cstdio> #include<vector> #include<algorithm> #include<iostream> using namespace std; bool cmp(int a, int b){ return a > b; } int main(){ int L, N; while ( scanf("%d %d", &L, &N) != EOF ) { int block; vector<int> blocks; for (int i = 0; i < N; i++) { scanf("%d", &block); blocks.push_back(block); } sort(blocks.begin(), blocks.end(), cmp); int total = 0, count = 0; for (int i = 0; i < blocks.size(); i++) { total += blocks[i]; count++; if ( total >= L ) break; } if ( total >= L ) printf("%d\n", count); else printf("impossible\n"); } system("pause"); return 0; }
[ "chenjian19990211@163.com" ]
chenjian19990211@163.com
2421df18dac183de71f78381c2b9f9ce124fc017
5926ff763a5055c535462b5a3479946ce77aa0a9
/Answersheet/356PoorTradeAdvisor.cpp
a8011fa9730ec5f72cc741413315b96a9f9f14b5
[]
no_license
wuzijian4/CS3391_Answer
765886b237415ae1c6abe22ea0ee83ac50f4c649
8ccb57501e00ed7e55da21f4fb6dc2083eb47069
refs/heads/master
2022-08-03T08:47:03.012167
2020-05-28T05:50:04
2020-05-28T05:50:04
267,270,885
0
0
null
null
null
null
UTF-8
C++
false
false
1,499
cpp
#include <iostream> #include <stdlib.h> #include <memory.h> using namespace std; int n, m; int parent[510]; struct edge { int from; int to; int ppa; }; int cmp(const void* a, const void* b) { edge* x = (edge*)a; edge* y = (edge*)b; return y->ppa - x->ppa; //decresing order } int find(int e) { if (parent[e] < 0) return e; else return parent[e] = find(parent[e]); } void UnionSet(int e1, int e2) { parent[e1] += parent[e2]; parent[e2] = e1; } void Union(int e1, int e2) { int root1 = find(e1); int root2 = find(e2); if (root1 == root2) return; if (parent[root1] < parent[root2]) UnionSet(root1, root2); else UnionSet(root2, root1); return; } int main() { do { cin >> n >> m; if (n == 0 && m == 0) break; edge *edges = new edge[m + 1]; edge *Maxedges = new edge[m + 1]; for (int i = 0; i < m; i++) cin >> edges[i].from >> edges[i].to >> edges[i].ppa; qsort(edges, m, sizeof(edge), cmp); int k = 0; for (int i = 0; i < m; i++) { if (edges[i].ppa != edges[0].ppa) break; else Maxedges[k++] = edges[i]; } memset(parent, -1, sizeof(parent)); for (int i = 0; i < k; i++) { Union(Maxedges[i].from, Maxedges[i].to); } int min = parent[0]; for (int i = 1; i <= n; i++) { if (min > parent[i]) min = parent[i]; } cout << abs(min) << endl; delete(edges); delete(Maxedges); } while (true); return 0; }
[ "noreply@github.com" ]
wuzijian4.noreply@github.com
e53b0504a788bbd5192ab4caa1b503a379ef7f41
04251e142abab46720229970dab4f7060456d361
/lib/rosetta/source/src/protocols/rbsegment_relax/OptimizeThreading.cc
d609a0d539c8c4a1dec37d8b3986a5205a356f63
[]
no_license
sailfish009/binding_affinity_calculator
216257449a627d196709f9743ca58d8764043f12
7af9ce221519e373aa823dadc2005de7a377670d
refs/heads/master
2022-12-29T11:15:45.164881
2020-10-22T09:35:32
2020-10-22T09:35:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
21,640
cc
// -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*- // vi: set ts=2 noet: // // (c) Copyright Rosetta Commons Member Institutions. // (c) This file is part of the Rosetta software suite and is made available under license. // (c) The Rosetta software is developed by the contributing members of the Rosetta Commons. // (c) For more information, see http://www.rosettacommons.org. Questions about this can be // (c) addressed to University of Washington CoMotion, email: license@uw.edu. /// @file /// @brief protocols for folding into density /// @details /// @author Frank DiMaio #include <protocols/rbsegment_relax/OptimizeThreading.hh> #include <protocols/rbsegment_relax/OptimizeThreadingCreator.hh> #include <protocols/loops/loops_main.hh> #include <protocols/simple_moves/FragmentMover.hh> #include <core/scoring/ScoreFunction.hh> #include <core/scoring/ScoreFunctionFactory.hh> #include <core/pose/Pose.hh> #include <core/pose/symmetry/util.hh> #include <core/conformation/Residue.hh> #include <core/conformation/symmetry/util.hh> #include <core/pose/PDBInfo.hh> #include <core/io/Remarks.hh> #include <protocols/moves/MonteCarlo.hh> #include <core/fragment/picking_old/vall/util.hh> #include <core/fragment/IndependentBBTorsionSRFD.hh> #include <core/fragment/FragSet.hh> #include <core/fragment/FrameIterator.hh> #include <core/fragment/FragmentIO.hh> #include <core/fragment/ConstantLengthFragSet.hh> #include <core/fragment/Frame.hh> #include <core/fragment/FragData.hh> #include <core/fragment/util.hh> #include <core/scoring/rms_util.hh> #include <core/import_pose/import_pose.hh> #include <protocols/rbsegment_relax/util.hh> #include <protocols/rbsegment_relax/RBSegmentMover.hh> #include <protocols/rbsegment_relax/RBSegment.hh> #include <protocols/hybridization/util.hh> #include <protocols/loops/util.hh> #include <protocols/moves/DsspMover.hh> #include <core/scoring/dssp/Dssp.hh> #include <protocols/symmetry/SetupNCSMover.hh> #include <basic/datacache/DataMap.hh> #include <protocols/rosetta_scripts/util.hh> #include <utility/tag/Tag.hh> #include <numeric/random/random.hh> #include <basic/options/option.hh> #include <basic/Tracer.hh> #include <core/pose/datacache/CacheableDataType.hh> #include <basic/datacache/BasicDataCache.hh> // XSD XRW Includes #include <utility/tag/XMLSchemaGeneration.hh> #include <protocols/moves/mover_schemas.hh> namespace protocols { namespace rbsegment_relax { static basic::Tracer TR( "protocols.rbsegment_relax.OptimizeThreading" ); using namespace protocols; using namespace core; ////////////////// ////////////////// /// creator ////////////////// ////////////////// /// mover void OptimizeThreadingMover::apply( core::pose::Pose & pose ) { using namespace rbsegment_relax; core::Size nres = hybridization::get_num_residues_nonvirt( pose ); while ( !pose.residue_type(nres).is_protein() ) --nres; // see if the pose has NCS symmetry::NCSResMappingOP ncs; if ( pose.data().has( core::pose::datacache::CacheableDataType::NCS_RESIDUE_MAPPING ) ) { ncs = ( utility::pointer::static_pointer_cast< symmetry::NCSResMapping > ( pose.data().get_ptr( core::pose::datacache::CacheableDataType::NCS_RESIDUE_MAPPING ) )); } // get sses & choose cutpoints protocols::loops::Loops SSEs; if ( core::pose::symmetry::is_symmetric( pose ) ) { core::pose::Pose pose_asu; core::pose::symmetry::extract_asymmetric_unit(pose, pose_asu); core::scoring::dssp::Dssp dssp_obj( pose_asu ); dssp_obj.insert_ss_into_pose( pose_asu ); SSEs = protocols::loops::extract_secondary_structure_chunks( pose_asu, "HE", 3, 6, 3, 3, 4); } else { core::scoring::dssp::Dssp dssp_obj( pose ); dssp_obj.insert_ss_into_pose( pose ); SSEs = protocols::loops::extract_secondary_structure_chunks( pose, "HE", 3, 6, 3, 3, 4); } SSEs.sequential_order(); // penalize insertions/deletions in the middle of SSEs utility::vector1< bool > sse_core(nres,false); for ( int j=1; j<=(int)SSEs.num_loop(); ++j ) { int jstart=SSEs[j].start(), jstop=SSEs[j].stop(); for ( int k=jstart+4; k<=jstop-4; ++k ) { sse_core[ k ] = true; } } utility::vector1< RBResidueRange > segments; core::Size prevcut = 1; for ( int j=2; j<=(int)SSEs.num_loop(); ++j ) { core::Size j0stop = SSEs[j-1].stop(); core::Size j1start = SSEs[j].start(); char chain0 = pose.pdb_info()->chain(j0stop); char chain1 = pose.pdb_info()->chain(j1start); if ( chains_.size()>0 && std::find(chains_.begin(), chains_.end(), chain0) == chains_.end() ) continue; if ( chains_.size()>0 && std::find(chains_.begin(), chains_.end(), chain1) == chains_.end() ) continue; // see if there is a cut between the two and use that instead bool found_cuts = false; for ( auto k=(int)j0stop; k<(int)j1start; ++k ) { if ( pose.fold_tree().is_cutpoint( k ) ) { segments.push_back( RBResidueRange( prevcut, k ) ); TR << "Add segment: " << prevcut << " , " << k << std::endl; prevcut = k+1; found_cuts=true; } } if ( !found_cuts ) { core::Size cutpoint = numeric::random::random_range(j0stop,j1start-1); segments.push_back( RBResidueRange( prevcut, cutpoint-1 ) ); TR << "Add segment: " << prevcut << " , " << cutpoint-1 << std::endl; prevcut = cutpoint; } } segments.push_back( RBResidueRange( prevcut, nres ) ); TR << "Add segment: " << prevcut << " , " << nres << std::endl; // combine segments core::Size nsegments=segments.size(); for ( int i=1; i<=(int)nsegments; ++i ) { for ( int j=i+1; j<=(int)nsegments; ++j ) { bool crosses_cut = false; for ( int k=i; k<j && !crosses_cut; ++k ) { crosses_cut = pose.fold_tree().is_cutpoint( segments[k].end() ); } if ( !crosses_cut ) { segments.push_back( RBResidueRange( segments[i].start(), segments[j].end() ) ); TR << "Add segment: " << segments[i].start() << " , " << segments[j].end() << std::endl; } } } // mc loop SequenceShiftMover sshift( pose, RBSegment(), max_shift_ ); sshift.set_extra_penalty( sse_core ); core::Real best_score=1e30, acc_score=1e30; loops::LoopsOP best_loops( new loops::Loops() ); core::pose::Pose best_pose=pose, acc_pose; utility::vector1< int > offsets( nres, 0 ); if ( greedy_ ) { /// /// greedy /// core::Size steps_eff = nsteps_; //std::ceil( nsteps_ / (2.0*max_shift_*segments.size())); TR << "Greedy search for " << steps_eff << " steps" << std::endl; for ( int i=1; i<=(int)steps_eff; ++i ) { acc_pose = pose; core::Real score_cst = (*scorefxn_)(pose); core::Real score_aln = sshift.score(); best_score = score_cst + weight_*score_aln; int bestSeg=1, bestK=0; for ( core::Size seg_i = 1; seg_i<=segments.size(); ++seg_i ) { utility::vector1 < RBResidueRange > ncs_segments ( 1, segments[seg_i] ); if ( ncs ) { for ( core::uint j = 1; j <= ncs->ngroups(); ++j ) { core::Size remap_start = ncs->get_equiv( j, segments[seg_i].start() ); core::Size remap_stop = ncs->get_equiv( j, segments[seg_i].end() ); for ( core::uint k = segments[seg_i].start(); k <= segments[seg_i].end() && remap_start == 0; ++k ) { remap_start = ncs->get_equiv( j,k ); } if ( remap_start==0 ) continue; // undefined for ( core::uint k = segments[seg_i].end(); k >= segments[seg_i].start() && remap_stop == 0; --k ) { remap_stop = ncs->get_equiv( j,k ); } //TR.Debug << "NCS: Add segment: " << remap_start << " , " << remap_stop << std::endl; ncs_segments.push_back( RBResidueRange(remap_start, remap_stop) ); } } sshift.set_segment( RBSegment(ncs_segments) ); int k_start = -1*(int)max_shift_; for ( int k=k_start; k<=(int)max_shift_; ++k ) { pose = acc_pose; if ( k!=0 ) { sshift.apply( pose, k ); score_cst = (*scorefxn_)(pose); score_aln = sshift.score(); // boltzmann core::Real score = score_cst + weight_*score_aln; if ( score < best_score ) { TR << "New best! Step " << i << "." << seg_i << "[" << segments[seg_i].start() << "-" << segments[seg_i].end() << "]." << k << " score = " << score_cst << " + " << weight_ << " * " << score_aln << " = " << score << std::endl; best_score = score; bestK=k; bestSeg=seg_i; } } } } // apply best shift we found { utility::vector1 < RBResidueRange > ncs_segments ( 1, segments[bestSeg] ); if ( ncs ) { for ( core::uint j=1; j <= ncs->ngroups(); ++j ) { core::Size remap_start = ncs->get_equiv( j, segments[bestSeg].start() ), remap_stop = ncs->get_equiv( j, segments[bestSeg].end() ); for ( core::uint k = segments[bestSeg].start(); k <= segments[bestSeg].end() && remap_start == 0; ++k ) { remap_start = ncs->get_equiv( j, k ); } if ( remap_start==0 ) continue; for ( core::uint k = segments[bestSeg].end(); k >= segments[bestSeg].start() && remap_stop == 0; --k ) { remap_stop = ncs->get_equiv( j, k ); } ncs_segments.push_back( RBResidueRange(remap_start,remap_stop) ); } } if ( bestK==0 ) break; // no move accepted last cycle pose = acc_pose; sshift.set_segment( RBSegment(ncs_segments) ); sshift.apply( pose, bestK ); sshift.trigger_accept(); } } best_loops = sshift.get_residues_to_rebuild(); *loops_ = *best_loops; } else { /// /// non-greedy /// for ( int i=1; i<=(int)nsteps_; ++i ) { // random segment core::Size seg_i = numeric::random::random_range(1, segments.size() ); if ( i>1 ) { // apply movement & score pose utility::vector1 < RBResidueRange > ncs_segments ( 1, segments[seg_i] ); if ( ncs ) { for ( core::uint j = 1; j <= ncs->ngroups(); ++j ) { core::Size remap_start = ncs->get_equiv( j, segments[seg_i].start() ); core::Size remap_stop = ncs->get_equiv( j, segments[seg_i].end() ); for ( core::uint k = segments[seg_i].start(); k <= segments[seg_i].end() && remap_start == 0; ++k ) { remap_start = ncs->get_equiv( j,k ); } if ( remap_start==0 ) continue; // undefined for ( core::uint k = segments[seg_i].end(); k >= segments[seg_i].start() && remap_stop == 0; --k ) { remap_stop = ncs->get_equiv( j,k ); } //TR.Debug << "NCS: Add segment: " << remap_start << " , " << remap_stop << std::endl; ncs_segments.push_back( RBResidueRange(remap_start,remap_stop) ); } } sshift.set_segment( RBSegment(ncs_segments) ); sshift.apply( pose ); } core::Real score_cst = (*scorefxn_)(pose); core::Real score_aln = sshift.score(); if ( native_ ) { score_cst = core::scoring::CA_rmsd( pose, *native_ ); } // boltzmann core::Real score = score_cst + weight_*score_aln; core::Real boltz_factor = ( acc_score - score ) / temperature_; core::Real probability = std::exp( std::min (40.0, std::max(-40.0,boltz_factor)) ); if ( probability < 1 ) { if ( numeric::random::uniform() >= probability ) { // reject pose = acc_pose; } else { // accept, not new best acc_pose = pose; acc_score = score; sshift.trigger_accept(); if ( !recover_low_ ) best_loops = sshift.get_residues_to_rebuild(); TR << "Accept! Step " << i << " score = " << score_cst << " + " << weight_ << " * " << score_aln << " = " << score << std::endl; } } else { // new best acc_pose = pose; acc_score = score; sshift.trigger_accept(); if ( score < best_score ) { TR << "New best! Step " << i << " score = " << score_cst << " + " << weight_ << " * " << score_aln << " = " << score << std::endl; best_pose = pose; best_loops = sshift.get_residues_to_rebuild(); best_score = score; } else { TR << "Accept! Step " << i << " score = " << score_cst << " + " << weight_ << " * " << score_aln << " = " << score << std::endl; if ( !recover_low_ ) best_loops = sshift.get_residues_to_rebuild(); } } *loops_ = *best_loops; } if ( recover_low_ ) { pose = best_pose; } } TR << "Building:" << std::endl; TR << *loops_ << std::endl; rebuild_unaligned( pose ); } void OptimizeThreadingMover::rebuild_unaligned(core::pose::Pose &pose) { if ( loops_->size() != 0 && rebuild_cycles_!=0 ) { // see if the pose has NCS symmetry::NCSResMappingOP ncs; if ( pose.data().has( core::pose::datacache::CacheableDataType::NCS_RESIDUE_MAPPING ) ) { ncs = ( utility::pointer::static_pointer_cast< symmetry::NCSResMapping > ( pose.data().get_ptr( core::pose::datacache::CacheableDataType::NCS_RESIDUE_MAPPING ) )); } core::kinematics::FoldTree f_in=pose.fold_tree(), f_new; // set foldtree + variants for ( auto it=loops_->v_begin(), it_end=loops_->v_end(); it!=it_end; ++it ) { // if loop crosses a cut maintain that cut bool crosses_cut=false; core::Size i = 0; for ( i=it->start(); i<=it->stop() && !crosses_cut; ++i ) { crosses_cut |= f_in.is_cutpoint(i); } if ( crosses_cut ) { it->set_cut(i-1); //? } else { it->set_cut( it->midpoint() ); // be deterministic so ncs copies match up } // to do? what if we cross two cuts? } protocols::loops::fold_tree_from_loops( pose, *loops_, f_new); std::cerr << f_new << std::endl; pose.fold_tree( f_new ); protocols::loops::add_cutpoint_variants( pose ); // set movemap core::kinematics::MoveMapOP mm_loop( new core::kinematics::MoveMap() ); for ( auto const & it : *loops_ ) { for ( core::Size i=it.start(); i<=it.stop(); ++i ) { mm_loop->set_bb(i, true); mm_loop->set_chi(i, true); } } // extend + idealize loops protocols::loops::set_extended_torsions_and_idealize_loops( pose, *loops_ ); // pick 3mers only in unaligned regions std::string tgt_seq = pose.sequence(); core::fragment::FragSetOP frags3( new core::fragment::ConstantLengthFragSet( 3 ) ); for ( auto const & it : *loops_ ) { for ( core::Size i=it.start(); i+2<=it.stop(); ++i ) { core::fragment::FrameOP frame( new core::fragment::Frame( i, 3 ) ); frame->add_fragment( core::fragment::picking_old::vall::pick_fragments_by_ss_plus_aa( "DDD", tgt_seq.substr( i-1, 3 ), 25, true, core::fragment::IndependentBBTorsionSRFD() ) ); frags3->add( frame ); } } core::fragment::FragSetOP frags1( new core::fragment::ConstantLengthFragSet( 1 ) ); core::fragment::chop_fragments( *frags3, *frags1 ); // make a vector of fragments for random access (why does FragSet not have this?!?) utility::vector1< core::fragment::FrameOP > frames1, frames3; for ( core::fragment::FrameIterator it = frags1->nonconst_begin(); it != frags1->nonconst_end(); ++it ) frames1.push_back( *it ); for ( core::fragment::FrameIterator it = frags3->nonconst_begin(); it != frags3->nonconst_end(); ++it ) frames3.push_back( *it ); // setup MC core::Size nouterCyc=4, ninnerCyc=rebuild_cycles_; for ( core::Size i=1; i<=nouterCyc; ++i ) { if ( i==nouterCyc-1 ) scorefxn_sampling_->set_weight( core::scoring::linear_chainbreak, 0.5 ); if ( i==nouterCyc ) scorefxn_sampling_->set_weight( core::scoring::linear_chainbreak, 2.0 ); (*scorefxn_sampling_)(pose); protocols::moves::MonteCarloOP mc( new protocols::moves::MonteCarlo( pose, *scorefxn_sampling_, 2.0 ) ); for ( core::Size n=1; n<=ninnerCyc; ++n ) { utility::vector1< core::fragment::FrameOP > & working_frames = (n%2)?frames3:frames1; //frag3mover->apply( pose ); int frame_idx = numeric::random::random_range(1,working_frames.size()); core::fragment::FrameOP frame_i = working_frames[frame_idx]; int frag_idx = numeric::random::random_range(1,frame_i->nr_frags()); core::fragment::FragDataCOP to_insert = frame_i->fragment_ptr(frag_idx); to_insert->apply( pose, *frame_i ); // now apply to ncs copies if ( ncs ) { for ( core::uint j = 1; j <= ncs->ngroups(); ++j ) { bool all_are_mapped = true; for ( core::Size k=frame_i->start(); k<=frame_i->stop() && all_are_mapped; ++k ) { all_are_mapped &= (ncs->get_equiv( j,k )!=0 && loops_->is_loop_residue(ncs->get_equiv( j,k )) ); } if ( !all_are_mapped ) continue; core::Size remap_start = ncs->get_equiv( j, frame_i->start() ); core::Size remap_stop = ncs->get_equiv( j, frame_i->stop() ); if ( remap_stop-remap_start != frame_i->stop()-frame_i->start() ) continue; to_insert->apply( pose, remap_start, remap_stop ); } } (*scorefxn_sampling_)(pose); if ( mc->boltzmann( pose , (n%2)?"frag3":"frag1" ) ) { ; //std::ostringstream oss; //oss << "out" << i << "_" << n << ".pdb"; //pose.dump_pdb( oss.str() ); //std::cerr << "out " << i << "_" << n << ": " << frame_i->start() << std::endl; //for (int j=1; j<=ncs->ngroups(); ++j ) { // bool all_are_mapped = true; // for ( core::Size k=frame_i->start(); k<=frame_i->stop() && all_are_mapped; ++k ) all_are_mapped &= (ncs->get_equiv( j,k )!=0); // if (!all_are_mapped) continue; // core::Size remap_start = ncs->get_equiv( j, frame_i->start() ); // std::cerr << " ---> " << remap_start << std::endl; //} } } mc->show_scores(); mc->show_counters(); if ( recover_low_ ) mc->recover_low( pose ); } // restore input ft protocols::loops::remove_cutpoint_variants( pose ); pose.fold_tree( f_in ); } } void OptimizeThreadingMover::parse_my_tag( utility::tag::TagCOP tag, basic::datacache::DataMap & data ) { if ( tag->hasOption( "scorefxn" ) ) { std::string const scorefxn_name( tag->getOption<std::string>( "scorefxn" ) ); scorefxn_ = (data.get< core::scoring::ScoreFunction * >( "scorefxns", scorefxn_name ))->clone(); } if ( tag->hasOption( "scorefxn_sampling" ) ) { std::string const scorefxn_name( tag->getOption<std::string>( "scorefxn_sampling" ) ); scorefxn_sampling_ = (data.get< core::scoring::ScoreFunction * >( "scorefxns", scorefxn_name ))->clone(); } if ( tag->hasOption( "native" ) ) { std::string ref_model_pdb = tag->getOption<std::string>( "native" ); native_ = utility::pointer::make_shared< core::pose::Pose >(); core::import_pose::pose_from_file( *native_, ref_model_pdb , core::import_pose::PDB_file); } if ( tag->hasOption( "chains" ) ) { std::string chain_str = tag->getOption<std::string>( "chains" ); utility::vector1< std::string > chns = utility::string_split(chain_str, ','); for ( int i=1; i<=(int)chns.size(); ++i ) chains_.push_back( chns[i][0] ); } nsteps_ = tag->getOption<core::Size>( "nsteps", 5000 ); step_penalty_ = tag->getOption<bool>( "step_penalty", false ); recover_low_ = tag->getOption<bool>( "recover_low", true ); greedy_ = tag->getOption<bool>( "greedy", false ); rebuild_cycles_ = tag->getOption<core::Size>( "rebuild_cycles", 200 ); weight_ = tag->getOption<core::Real>( "weight", 0.1 ); temperature_ = tag->getOption<core::Real>( "temperature", 2.0 ); max_shift_ = tag->getOption<core::Size>( "max_shift", 4 ); // different nstep default for greedy if ( greedy_ && !tag->hasOption("nsteps") ) nsteps_=2; // add loopsOP to the DataMap if ( tag->hasOption( "loops_out" ) ) { std::string looptag = tag->getOption<std::string>( "loops_out" ); data.add( "loops", looptag, loops_ ); } } std::string OptimizeThreadingMover::get_name() const { return mover_name(); } std::string OptimizeThreadingMover::mover_name() { return "OptimizeThreading"; } void OptimizeThreadingMover::provide_xml_schema( utility::tag::XMLSchemaDefinition & xsd ) { using namespace utility::tag; AttributeList attlist; attlist + XMLSchemaAttribute( "scorefxn", xs_string, "Scorefunction to use for threading" ) + XMLSchemaAttribute( "scorefxn_sampling", xs_string, "Scorefunction to use for Monte Carlo sampling" ) + XMLSchemaAttribute( "native", xs_string, "Path to PDB file containing native pose" ) + XMLSchemaAttribute( "chains", xsct_chain_cslist, "Specify chains within the pose to use for threading" ) + XMLSchemaAttribute::attribute_w_default( "nsteps", xsct_non_negative_integer, "Number of monte carlo steps", "5000" ) + XMLSchemaAttribute::attribute_w_default( "step_penalty", xsct_rosetta_bool, "This attribute is never actually used", "false" ) + XMLSchemaAttribute::attribute_w_default( "recover_low", xsct_rosetta_bool, "Recover the lowest energy structure", "true" ) + XMLSchemaAttribute::attribute_w_default( "greedy", xsct_rosetta_bool, "Perform a greedy alignment", "false" ) + XMLSchemaAttribute::attribute_w_default( "rebuild_cycles", xsct_non_negative_integer, "Number of loop modeling cycles", "200" ) + XMLSchemaAttribute::attribute_w_default( "weight", xsct_real, "Weight for the sequence shift mover's score", "0.1" ) + XMLSchemaAttribute::attribute_w_default( "temperature", xsct_real, "Temperature for the Metropolis criterion", "2.0" ) + XMLSchemaAttribute::attribute_w_default( "max_shift", xsct_non_negative_integer, "Maximum number of residues to shift sequence", "4" ) + XMLSchemaAttribute( "loops_out", xs_string, "Add the LoopsOP to the datamap with this name" ); protocols::moves::xsd_type_definition_w_attributes( xsd, mover_name(), "Optimize threading of a sequence onto a pose", attlist ); } std::string OptimizeThreadingMoverCreator::keyname() const { return OptimizeThreadingMover::mover_name(); } protocols::moves::MoverOP OptimizeThreadingMoverCreator::create_mover() const { return utility::pointer::make_shared< OptimizeThreadingMover >(); } void OptimizeThreadingMoverCreator::provide_xml_schema( utility::tag::XMLSchemaDefinition & xsd ) const { OptimizeThreadingMover::provide_xml_schema( xsd ); } } }
[ "lzhangbk@connect.ust.hk" ]
lzhangbk@connect.ust.hk
003971c94184f6469a5f61c505c692db20ef2862
d582847aa1b4d7529ca57a9b9d27019ae50e89f2
/Bases/Seno con taylor.cpp
3805f49daab1b4c7b721363d07abaf9966d6b3c9
[]
no_license
srdelsalto/Proyecto-Final-2
2f9f4f19d1a9d86d137affc5be923ebd446f465d
43767e9f4584ad73fd72337460f3bfd9784f5436
refs/heads/master
2021-09-04T18:00:07.404966
2018-01-20T22:19:39
2018-01-20T22:19:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,201
cpp
#include <stdio.h> #include <stdlib.h> #include <conio.h> #include <math.h> double factorial (int a) { int i; double fac; fac=1; for (i=a;i>0;i--) { fac=fac*i; } return fac; //dentro de la funcion no llamar a nada igual que la funcion } double potencia (double base, double exponente) { double resultado = 1; for (int i = 0; i < exponente ; i++){ resultado *= base; } return (resultado); } int main() { int k,n=0; double x,sinx=0.0,seno; double pro,den,pot; k = 84; /*printf ("introduce el valor de k: "); scanf ("%d",&k);*/ printf ("\nintroduce el valor del angulo en radianes: "); scanf ("%lf",&x); while (n<=k) { // esta es una prueba con la formula toda junta, sin casting //seno =((pow (-1,n))/factorial(2*n+1))*(pow(x,2*n+1)); pot=potencia(-1,n); den=factorial(2*n+1); pro=potencia(x,2*n+1); seno= (pot/den)*pro; sinx= sinx + seno; //printf("\nEl elemento n=%d es %lf y la suma va siendo %lf",n,seno,sinx); n++; } printf ("\nEl valor del seno es: %lf\n\n",sinx); system ("pause"); }
[ "32906638+Santy5442@users.noreply.github.com" ]
32906638+Santy5442@users.noreply.github.com
9f8491572e176380ed9ccba60cdff905bdd42f5c
a2ad0bfa5bcd3fce61a4055b1ef98926225747b1
/ElementsOfProgrammingInterview/chapter12_Search/cyclicallySortedArr.cc
e808617f7f98610d4541450e26626874a8d6357e
[]
no_license
ldcm3/Tech-Interview-Studies
7e077a3006eaaf443c4f3d94c50321792ec96171
ba64fad928c3baef56a43ecc3ec85706db9d8aba
refs/heads/master
2021-01-13T02:51:40.204583
2017-07-06T12:36:41
2017-07-06T12:36:41
77,131,514
0
1
null
null
null
null
UTF-8
C++
false
false
669
cc
/* Find the position of the smallest element in a cyclically sorted array, assuming all elements are distinct. {378,478,550,631,103,203,220,234,279,368} should return 4 */ #include<iostream> #include<vector> using namespace std; int findCilPos(const vector<int>& A) { int left = 0; int right = A.size() - 1; int mid; while(left < right) // all elements are distinct { mid = left + ((right - left)/2); if (A[mid] > A[right]) left = mid + 1; else // A[mid] < A[right] right = mid ; } return left; } int main() { return 0; }
[ "lucasdacruzmendes@hotmail.com" ]
lucasdacruzmendes@hotmail.com
fb8a61b7333739a903fece57f75b4746228a890f
66b8c3a5ec8696dcefd796a188c94a2ede7e290e
/Bitcoin.ino
9e858f3ff30e80d1da6f293eb4f8828bd1287d0f
[]
no_license
AndresJ551/Arduino-Bitcoin-Display
e011c3a05d090505647abe26e2ecd4f0ba8dac44
2546aff581c0ceda56fc22eed05b54f18b25de71
refs/heads/master
2020-05-25T19:50:17.438905
2017-03-14T14:58:39
2017-03-14T14:58:39
84,961,291
0
0
null
null
null
null
UTF-8
C++
false
false
1,572
ino
/* SevSeg Counter Example Copyright 2016 Dean Reading 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. This example demonstrates a very simple use of the SevSeg library with a 4 digit display. It displays a counter that counts up, showing deci-seconds. */ #include "SevSeg.h" SevSeg sevseg; bool stringComplete = false; String inputString = ""; void setup() { Serial.begin(9600); byte numDigits = 4; byte digitPins[] = {9,10,11,12}; byte segmentPins[] = {2,3,4,5,6,7,8,1}; bool resistorsOnSegments = false; byte hardwareConfig = COMMON_ANODE; sevseg.begin(hardwareConfig, numDigits, digitPins, segmentPins, resistorsOnSegments); } void loop() { sevseg.refreshDisplay(); } void serialEvent() { while (Serial.available()) { char inChar = (char)Serial.read(); inputString += inChar; if (inChar == ' ') { // Detect end of data with a ' ' character. stringComplete = true; } } if(stringComplete){ Serial.println(inputString); sevseg.setNumber(inputString.toInt(), 1); inputString = ""; stringComplete = false; } }
[ "AndresJ551@gmail.com" ]
AndresJ551@gmail.com
c3f4300fc233d72827052381b03e4f7218f6e644
fbe68d84e97262d6d26dd65c704a7b50af2b3943
/third_party/retdec-3.2/include/retdec/fileformat/types/resource_table/resource.h
0bcf83fa30c6cc110c8994f1e5b70eb629a5c249
[ "MIT", "GPL-1.0-or-later", "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "OpenSSL", "WTFPL", "LGPL-2.1-only", "LicenseRef-scancode-openssl", "LicenseRef-scancode-ssleay-windows", "LGPL-2.0-or-later", "JSON", "Zlib", "NCSA", "LicenseRef-scancode-proprietary-license", "GPL-2.0-only", "LicenseRef-scancode-patent-disclaimer", "LGPL-2.0-only", "LicenseRef-scancode-public-domain" ]
permissive
thalium/icebox
c4e6573f2b4f0973b6c7bb0bf068fe9e795fdcfb
6f78952d58da52ea4f0e55b2ab297f28e80c1160
refs/heads/master
2022-08-14T00:19:36.984579
2022-02-22T13:10:31
2022-02-22T13:10:31
190,019,914
585
109
MIT
2022-01-13T20:58:15
2019-06-03T14:18:12
C++
UTF-8
C++
false
false
3,503
h
/** * @file include/retdec/fileformat/types/resource_table/resource.h * @brief Class for one resource. * @copyright (c) 2017 Avast Software, licensed under the MIT license */ #ifndef RETDEC_FILEFORMAT_TYPES_RESOURCE_TABLE_RESOURCE_H #define RETDEC_FILEFORMAT_TYPES_RESOURCE_TABLE_RESOURCE_H #include <string> #include <vector> #include <llvm/ADT/StringRef.h> namespace retdec { namespace fileformat { class FileFormat; /** * One resource */ class Resource { private: std::string crc32; ///< CRC32 of resource content std::string md5; ///< MD5 of resource content std::string sha256; ///< SHA256 of resource content std::string name; ///< resource name std::string type; ///< resource type std::string language; ///< resource language llvm::StringRef bytes; ///< reference to resource data std::size_t offset; ///< offset in file std::size_t size; ///< size in file std::size_t nameId; ///< resource name identifier std::size_t typeId; ///< resource type identifier std::size_t languageId; ///< resource language identifier std::size_t sublanguageId; ///< resource sublanguage identifier bool nameIdIsValid; ///< @c true if name ID is valid bool typeIdIsValid; ///< @c true if type ID is valid bool languageIdIsValid; ///< @c true if language ID is valid bool sublanguageIdIsValid; ///< @c true if sublanguage ID is valid bool loaded; ///< @c true if content of resource was successfully loaded from input file public: Resource(); ~Resource(); /// @name Getters /// @{ std::string getCrc32() const; std::string getMd5() const; std::string getSha256() const; std::string getName() const; std::string getType() const; std::string getLanguage() const; const llvm::StringRef getBytes(std::size_t sOffset = 0, std::size_t sSize = 0) const; std::size_t getOffset() const; std::size_t getSizeInFile() const; std::size_t getLoadedSize() const; bool getNameId(std::size_t &rId) const; bool getTypeId(std::size_t &rId) const; bool getLanguageId(std::size_t &rId) const; bool getSublanguageId(std::size_t &rId) const; /// @} /// @name Getters of resource content /// @{ bool getBits(std::string &sResult) const; bool getBytes(std::vector<unsigned char> &sResult, std::size_t sOffset = 0, std::size_t sSize = 0) const; bool getString(std::string &sResult, std::size_t sOffset = 0, std::size_t sSize = 0) const; bool getHexBytes(std::string &sResult) const; /// @} /// @name Setters /// @{ void setName(std::string rName); void setType(std::string rType); void setLanguage(std::string rLan); void setOffset(std::size_t rOffset); void setSizeInFile(std::size_t rSize); void setNameId(std::size_t rId); void setTypeId(std::size_t rId); void setLanguageId(std::size_t rId); void setSublanguageId(std::size_t rId); /// @} /// @name Other methods /// @{ void invalidateNameId(); void invalidateTypeId(); void invalidateLanguageId(); void invalidateSublanguageId(); void load(const FileFormat *rOwner); bool hasCrc32() const; bool hasMd5() const; bool hasSha256() const; bool hasEmptyName() const; bool hasEmptyType() const; bool hasEmptyLanguage() const; /// @} }; } // namespace fileformat } // namespace retdec #endif
[ "benoit.amiaux@gmail.com" ]
benoit.amiaux@gmail.com
84c92d4e181f3c857efbd6a82241bac9b46723bd
9c88295f001a92201ff9db33b253b6ea5300c41d
/src/Rational.cpp
b6a88da9ab54c2cb179d2b3c073a1520c292049e
[]
no_license
ANAbdrahmanov/Dyab-lib
a20b7cc3e4c587f7867a2e38e98f9bebac5704ff
2aa0cb4942331d5427e37330e364d050889e2e47
refs/heads/master
2020-04-03T03:02:47.819722
2019-11-25T14:31:47
2019-11-25T14:31:47
154,975,112
0
0
null
null
null
null
UTF-8
C++
false
false
2,137
cpp
#include <iostream> #include "Rational.h" int Euclid(int A, int B){ while (B) { A %= B; swap (A, B); } return A; } Rational operator/(int a, Rational b){ return Rational(a*b.getZNT(), b.getCHS()); } Rational operator*(int a, Rational b){ return Rational(a*b.getCHS(), b.getZNT()); } Rational operator+(int a, Rational b){ return Rational(a*b.getZNT() + b.getCHS(), b.getZNT()); } Rational operator-(int a, Rational b){ return Rational(a*b.getZNT() - b.getCHS(), b.getZNT()); } ostream& operator<<(ostream& c, Rational a){ c<<a.getCHS(); if(a.getZNT() != 1) c<<'/'<<a.getZNT(); return c; } istream& operator>>(istream& c, Rational& a){ int ch; int zn; c>>ch>>zn; a = Rational(ch,zn); return c; } Rational::Rational(int C){ chs = C; znt = 1; } Rational::Rational(int C, int Z){ if(Z < 0){ Z=-Z; C=-C; } int nod = Euclid(C<0?-C:C, Z); if(nod == 1){ chs = C; znt = Z; } else{ chs = C/nod; znt = Z/nod; } } Rational Rational::operator+(Rational b){ return Rational(chs*b.znt + b.chs*znt, znt*b.znt);; } Rational Rational::operator-(Rational b){ return Rational(chs*b.znt - b.chs*znt, znt*b.znt); } Rational Rational::operator*(Rational b){ return Rational(chs*b.chs, znt*b.znt); } Rational Rational::operator/(Rational b){ return Rational(chs*b.znt, znt*b.chs); } bool Rational::operator<(Rational b){ return chs*b.znt < znt*b.chs; } bool Rational::operator>(Rational b){ return chs*b.znt > znt*b.chs; } bool Rational::operator<=(Rational b){ return chs*b.znt <= znt*b.chs; } bool Rational::operator>=(Rational b){ return chs*b.znt >= znt*b.chs; } bool Rational::operator==(Rational b){ return chs*b.znt == znt*b.chs; } bool Rational::operator!=(Rational b){ return chs*b.znt != znt*b.chs; } Rational& Rational::operator+=(Rational b){ return *this=*this+b; } Rational& Rational::operator-=(Rational b){ return *this=*this-b; } Rational& Rational::operator*=(Rational b){ return *this=*this*b; } Rational& Rational::operator/=(Rational b){ return *this=*this/b; }
[ "big.daddy5674@gmail.com" ]
big.daddy5674@gmail.com
ce0ec2b4ce2d8f8773f2292c3893eed312295645
a2bdc65e6f303b81a1beecfeb346cb862c8a8534
/main.cpp
ab59e9d711fd0754e795c74d494d90980aa3e3ca
[]
no_license
zoz25/calculatriceHP
aca7a79cec78fc22cf11b091c8114a4bc330e72b
cb6c6e5452c585e5f6e59847e4cde6ca9463a798
refs/heads/master
2020-06-16T14:35:02.309158
2016-12-14T15:13:15
2016-12-14T15:13:15
75,015,473
0
0
null
null
null
null
ISO-8859-2
C++
false
false
414
cpp
#include "calculatrice.h" int main(int argc, char** argv) { Calculatrice calcul = new Calculatrice(); Calculatrice.ajouterOperande(10); Calculatrice.ajouterOperande(117); Calculatrice.ajouterOperande(32.4); Calculatrice.ajouterOperation("+"); //va faire 32.4+117 et va supprimer les deux opérandes de la pile et ajouter le resultat, le nouveau x est le resultat de l'opération return EXIT_SUCCESS; }
[ "elkhabirayoub@gmail.com" ]
elkhabirayoub@gmail.com
90cf3a23bf79a809c01f6379d5dfdd9360a64ae1
e9da7781e7859e2e20f8fa980a945f67960a228a
/CIS170_IntroToC++/Week1/Week1LAB1B/Week1LAB1B/main.cpp
47460ee5ceabc06ea48a93cc88b5898ca62bb126
[]
no_license
reneet327/C_class_samples
8fd41c12679c6192581cf194807f8666bf95f066
4171385c21fdc3b5d7bd33734c12207f6076255d
refs/heads/master
2021-08-31T15:24:39.397235
2017-12-21T21:49:07
2017-12-21T21:49:07
115,050,108
0
0
null
null
null
null
UTF-8
C++
false
false
782
cpp
// --------------------------------------------------------------- // Programming Assignment: LAB1B // Developer: Renee Thomas // Date Written: 1/9/14 // Purpose: Ticket Calculation Program // --------------------------------------------------------------- // add libraries #include <iostream> using namespace std; // add main function void main() { //initialize variables as integers int childTkts, adultTkts, totalTkts; // add values to all the variables childTkts = 3; adultTkts = 2; // Calculate total tickets by adding childTkts and adultTkts totalTkts = childTkts + adultTkts; // output the total number of tickets to the console cout << totalTkts << endl; //add cin.ignore(2); to stop the console widow from closing cin.ignore(2); }
[ "reneet327@gmail.com" ]
reneet327@gmail.com
5727750047332f12794c3dbf11a55c3f37457c4d
0e41db6f4da32470aa80c55191b5cbe517ab1dc5
/11712406-project3/source/type.cpp
1f62784f1cffa6bbfc148eb4a5da007f956ff223
[]
no_license
wudiiv11/CS323-SPLCompiler
7f965f3271d899bca6a33db7d8cd7f3ebf842e7b
259691a22dabc9235bc11b9b48285a8d3774702d
refs/heads/master
2023-01-30T00:18:52.344373
2020-12-15T15:41:31
2020-12-15T15:41:31
302,395,342
0
0
null
null
null
null
UTF-8
C++
false
false
3,882
cpp
#include "../include/type.h" Type::Type() {} Type::Type(string* primitive) { category = T_PRIMITIVE; this->primitive = primitive; } Type::Type(Array* array) { category = T_ARRAY; this->array = array; } Type::Type(Struct* structure) { category = T_STRUCTURE; this->structure = structure; } Type::Type(Function* func) { category = T_FUNCTION; this->funcion = func; } int Type::size() { if (_size == 0) { switch (this->category) { case T_STRUCTURE: for (auto i : *this->structure->fields) { _size += i->type->size(); } break; case T_ARRAY: _size = this->array->base->size() * this->array->length; break; default: _size = 4; break; } } return _size; } Array::Array() {} Array::Array(Type* base, int length) { this->base = base; this->length = length; } Field::Field() {} Field::Field(string name, Type* type) { this->name = name; this->type = type; } Struct::Struct(string name, vector<Field*>* fields) { this->name = name; this->fields = fields; } int Struct::offset_of(string field) { int offset = 0; for (auto i : *fields) { if (i->name == field) { return offset; } offset += i->type->size(); } return -1; } Type* Struct::type_of(string name) { for (auto s : *fields) { if (s->name == name) { return s->type; } } return nullptr; } Function::Function() {} Function::Function(string name, Type* ret, vector<Field*>* args) { this->name = name; this->ret = ret; this->args = args; } Expr::Expr() { is_pointer = 0; t = nullptr; } string Record::to_string() { switch (category) { case R_INT: return args[0] + " := #" + args[1]; case R_ID: return args[0] + " := " + args[1]; case R_ASSIGN: return args[0] + " := " + args[1]; case R_OFFSET: return args[0] + " := " + args[1] + " + #" + args[2]; case R_PLUS: return args[0] + " := " + args[1] + " + " + args[2]; case R_MINUS: return args[0] + " := " + args[1] + " - " + args[2]; case R_MUL: return args[0] + " := " + args[1] + " * " + args[2]; case R_DIV: return args[0] + " := " + args[1] + " / " + args[2]; case R_LT: return "IF " + args[0] + " < " + args[1] + " GOTO " + args[2]; case R_LE: return "IF " + args[0] + " <= " + args[1] + " GOTO " + args[2]; case R_GT: return "IF " + args[0] + " > " + args[1] + " GOTO " + args[2]; case R_GE: return "IF " + args[0] + " >= " + args[1] + " GOTO " + args[2]; case R_NE: return "IF " + args[0] + " != " + args[1] + " GOTO " + args[2]; case R_EQ: return "IF " + args[0] + " == " + args[1] + " GOTO " + args[2]; case R_GOTO: return "GOTO " + args[0]; case R_LABEL: return "LABEL " + args[0] + " :"; case R_RETURN: return "RETURN " + args[0]; case R_FUNCTION: return "FUNCTION " + args[0] + " :"; case R_PARAM: return "PARAM " + args[0]; case R_READ: return "READ " + args[0]; case R_WRITE: return "WRITE " + args[0]; case R_CALL: return args[0] + " := CALL " + args[1]; case R_ARG: return "ARG " + args[0]; case R_DEC: return "DEC " + args[0] + " " + args[1]; default: return "error"; } } Record::Record(CATEGORY c, vector<string> args) { this->category = c; this->args = args; } Record::Record(CATEGORY c, int num, ...) { this->category = c; va_list list; va_start(list, num); for (int i = 0; i < num; ++i) { string* p = va_arg(list, string*); args.push_back(*p); } va_end(list); }
[ "xingxing6124@gmail.com" ]
xingxing6124@gmail.com
8743df230eb8ce9a787443b456f43f84ba003c85
4ec6bc3779261b73164a73c361de26cb0a724676
/include/NumCpp/Linalg/svd.hpp
182c1b0fd6897f3f2be38100b794880a144ef345
[ "MIT" ]
permissive
kontramind/NumCpp
3efc6673e0cc69b3fcb93f8b7c801abc6d9419cf
eba08fc5b97b338bc1ca9d1f9e2d3d76c2431cd1
refs/heads/master
2020-12-26T19:32:05.328636
2020-04-12T11:26:35
2020-04-12T11:26:35
237,615,461
0
0
MIT
2020-02-01T12:59:35
2020-02-01T12:59:35
null
UTF-8
C++
false
false
2,588
hpp
/// @file /// @author David Pilger <dpilger26@gmail.com> /// [GitHub Repository](https://github.com/dpilger26/NumCpp) /// @version 1.3 /// /// @section License /// Copyright 2020 David Pilger /// /// 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. /// /// @section Description /// matrix svd /// #pragma once #include "NumCpp/Linalg/svd/SVDClass.hpp" #include "NumCpp/Functions/diagflat.hpp" #include "NumCpp/NdArray.hpp" #include <utility> namespace nc { namespace linalg { //============================================================================ // Method Description: /// matrix svd /// /// NumPy Reference: https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.svd.html#numpy.linalg.svd /// /// @param inArray: NdArray to be SVDed /// @param outU: NdArray output U /// @param outS: NdArray output S /// @param outVt: NdArray output V transpose /// template<typename dtype> void svd(const NdArray<dtype>& inArray, NdArray<double>& outU, NdArray<double>& outS, NdArray<double>& outVt) noexcept { SVD svdSolver(inArray.template astype<double>()); outU = std::move(svdSolver.u()); NdArray<double> vt = svdSolver.v().transpose(); outVt = std::move(vt); NdArray<double> s = diagflat(svdSolver.s(), 0); outS = std::move(s); } } }
[ "dpilger26@gmail.com" ]
dpilger26@gmail.com
12f33a063b280a93331c4f8c13aedd21b1ea72f3
f3af5c4cbf6b24cec4142d8cfa7c452ddbccb0de
/CS482/Application.h
8d504a25e0d352d5eadd5a0ba1fa1327b0afdb10
[]
no_license
Suckzoo/CS482
5d2c08d6e27884bd971ea1f051fe90c5de3ad6f1
2e1d417080babdb4257ab6e91e80c42c2cabe8df
refs/heads/master
2021-01-22T02:59:16.763409
2014-10-07T05:15:14
2014-10-07T05:15:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
694
h
#pragma once #include "Window.h" #include "Renderer.h" #include <GL/glfw3.h> #include "World.h" #include "Program.h" //#include "ViewRenderer.h" //#include "SimulationRenderer.h" class Application { protected: int m_fCursorx, m_fCursory; std::list<Room*> m_pWorld; std::shared_ptr<Window> m_pWindow; std::map<std::string, Program*> m_pPrograms; //btCollisionWorld::ClosestRayResultCallback *PerformRayTest(double x, double y); public: Application(); ~Application(); void Initialize(); void Run(); void DispatchKeyEvent(int key, int scancode, int action, int mods); void DispatchMouseEvent(int button, int action, int mods); void DispatchCursorEvent(int xoffset, int yoffset); };
[ "seokju.hong@kaist.ac.kr" ]
seokju.hong@kaist.ac.kr
9008e1c91ab84c87caea7f8131c99e2b105c1bb7
4b43259b236d6d8596c3af5886e9b09502b97f3f
/manasaAndStones.cpp
ca90bb06a81d408c3d21f87c4f9d5b27cc2d7636
[]
no_license
karanbhatia116/Solutions-to-Coding-Problems
0ed8bf58db1df08d8ba3f68d431ad4a584782ccf
68c150fed3e62d7ea9bf5c3c666e5e5ded72caa1
refs/heads/master
2021-07-03T22:40:27.373938
2020-10-30T06:12:15
2020-10-30T06:12:15
194,615,610
1
2
null
2020-10-30T06:12:16
2019-07-01T06:47:50
C++
UTF-8
C++
false
false
575
cpp
#include<iostream> using namespace std; int* SumAndAppend(int a[],int x,int o,int b,int n,int y) { if(y<=n) { int i,j; for(j=x;j<y+1;j++) { for(i=x-y;i<x;i++) { a[j] = a[i] + o; a[j+1] = a[i] + b; } } x = x + y + 1; y++; SumAndAppend(a,x,o,b,n,y);} else return a; } int main() { int n,o,b,i; cin>>n>>o>>b; int a[n*n +n] = {0}; int *p; p = SumAndAppend(a,0,o,b,n,1); for(i=0;i<(n+1)*n;i++) cout<<*(p + i)<<" "; }
[ "noreply@github.com" ]
karanbhatia116.noreply@github.com
9b964d9601193a21399a74dbbfa436a8a93ebf04
2fb7188adb6f52023485d8a775e4ecbf96331b81
/AutoEncoder/DrawTracker.cxx
60a838e28b5395926ac80d52b8611770558a893d
[]
no_license
amassiro/dEdxCalibration
f5c580247041b4477a118772bbda9b924ae1103a
837eb440711983ddd0a283ec0cf3582c4a454d24
refs/heads/master
2020-03-24T03:31:45.099672
2019-11-08T13:09:40
2019-11-08T13:09:40
142,422,991
0
0
null
null
null
null
UTF-8
C++
false
false
3,272
cxx
TH1F * ConvertOverflow(TH1F *h) { // This function paint the histogram h with an extra bin for overflows UInt_t nx = h->GetNbinsX()+1; Double_t *xbins= new Double_t[nx+1]; for (UInt_t i=0;i<nx;i++) xbins[i]=h->GetBinLowEdge(i+1); xbins[nx]=xbins[nx-1]+h->GetBinWidth(nx); char *tempName= new char[strlen(h->GetName())+10]; sprintf(tempName,"%swtOverFlow",h->GetName()); // Book a temporary histogram having ab extra bin for overflows TH1F *htmp = new TH1F(tempName, h->GetTitle(), nx, xbins); //---- style htmp->SetLineColor(h->GetLineColor()); htmp->SetLineWidth(h->GetLineWidth()); htmp->SetLineStyle(h->GetLineStyle()); // Reset the axis labels htmp->SetXTitle(h->GetXaxis()->GetTitle()); htmp->SetYTitle(h->GetYaxis()->GetTitle()); // Fill the new hitogram including the extra bin for overflows for (UInt_t i=1; i<=nx; i++) htmp->SetBinContent(i, h->GetBinContent(i)); // Fill the underflows htmp->SetBinContent(0, h->GetBinContent(0)); // Restore the number of entries htmp->SetEntries(h->GetEntries()); // FillStyle and color htmp->SetFillStyle(h->GetFillStyle()); htmp->SetFillColor(h->GetFillColor()); return htmp; } void setupHisto(TH1F* histo, int icolor, std::string var) { Color_t* color = new Color_t [200]; color[0] = kAzure; //kRed ; color[1] = kAzure + 10 ; color[2] = kYellow + 2 ; color[3] = kGreen ; color[4] = kGreen + 4 ; color[5] = kBlue ; color[6] = kCyan ; color[7] = kPink + 1 ; color[8] = kBlack ; color[9] = kYellow + 4 ; color[10]= kRed ; for (int i=0; i<30; i++) { color[i+11] = kBlue + i; } histo->SetLineWidth(2); histo->SetLineColor(color[icolor]); histo->SetMarkerColor(color[icolor]); histo->SetMarkerSize(1); histo->SetMarkerStyle(20+icolor); histo->GetXaxis()->SetTitle(var.c_str()); } void Normalize(TH1F* histo) { float integral = histo->Integral(); if (integral != 0) { histo->Scale(1./integral); } } void DrawTracker( std::string var = "ciao", int NBIN = 1000, float MIN = 0, float MAX = 1000, std::string cut = "1") { TFile* inputFile_bkg = new TFile ("Data/../calibration/11Feb2019/tree_filtered_mc_DYJetsM50_HT100to200.root", "READ"); TTree* inputTree_bkg = (TTree*) ((TTree*) inputFile_bkg -> Get ("tree")); TFile* inputFile_data = new TFile ("Data/../calibration/11Feb2019/tree_filtered_data_SingleMuon_Run2017E_31Mar2018.root", "READ"); TTree* inputTree_data = (TTree*) ((TTree*) inputFile_data -> Get ("tree")); TString name; TString toDraw; TString weight; weight = Form ("%s", cut.c_str()); TH1F* h_bkg = new TH1F("h_bkg","DY",NBIN,MIN,MAX); TH1F* h_data = new TH1F("h_data","data",NBIN,MIN,MAX); toDraw = Form ("%s >> h_bkg",var.c_str()); inputTree_bkg->Draw(toDraw.Data(),weight.Data(),"goff"); toDraw = Form ("%s >> h_data",var.c_str()); inputTree_data->Draw(toDraw.Data(),weight.Data(),"goff"); h_bkg = ConvertOverflow(h_bkg); h_data = ConvertOverflow(h_data); setupHisto(h_bkg, 10, var); setupHisto(h_data, 0, var); Normalize(h_bkg); Normalize(h_data); TCanvas* cc = new TCanvas ("cc", "", 800, 600); h_bkg->Draw(""); h_data->Draw("same"); cc->BuildLegend(); }
[ "massironi.andrea@gmail.com" ]
massironi.andrea@gmail.com
2223f3131b46e5c573e3d7843c2498fac7767ed6
3e691e8defd8b2a15ccac8006b1ab996e0e8b232
/Contrib/STLib/packages/numerical/random/poisson/PoissonGeneratorInversionRatioOfUniformsWinrand.h
b4e323549b71250bfbdbc5c6f2ff437fe8b07ada
[]
no_license
cpbotha/vtktudoss
16063bcd5d61bbbc81efbd2205f07ed0c3161eb1
d519f47c1c6e98501c5829b0c7d08355143ccb57
refs/heads/master
2021-09-03T21:57:39.924068
2017-11-14T11:17:50
2017-11-14T11:17:50
103,945,005
1
0
null
2017-11-14T11:17:51
2017-09-18T13:49:18
C++
UTF-8
C++
false
false
4,830
h
// -*- C++ -*- /*! \file numerical/random/poisson/PoissonGeneratorInversionRatioOfUniformsWinrand.h \brief Poisson deviates using WinRand implementation of inversion/ratio of uniforms. */ #if !defined(__numerical_PoissonGeneratorInversionRatioOfUniformsWinrand_h__) #define __numerical_PoissonGeneratorInversionRatioOfUniformsWinrand_h__ #include "../uniform/ContinuousUniformGenerator.h" #include <cmath> #include <cstddef> // If we are debugging the whole numerical package. #if defined(DEBUG_numerical) && !defined(DEBUG_PoissonGeneratorInversionRatioOfUniformsWinrand) #define DEBUG_PoissonGeneratorInversionRatioOfUniformsWinrand #endif BEGIN_NAMESPACE_NUMERICAL //! Poisson deviates using WinRand implementation of inversion/ratio of uniforms. /*! This functor computes Poisson deviates using the <a href="http://www.stat.tugraz.at/stadl/random.html">WinRand</a> implementation of inversion/ratio of uniforms. Modifications: - Changed <code>double</code> to <code>Number</code> - Use my own uniform random deviate generator. \image html random/poisson/same/sameInversionRatioOfUniformsWinrandSmallArgument.jpg "Execution times for the same means." \image latex random/poisson/same/sameInversionRatioOfUniformsWinrandSmallArgument.pdf "Execution times for the same means." width=0.5\textwidth \image html random/poisson/same/sameInversionRatioOfUniformsWinrandLargeArgument.jpg "Execution times for the same means." \image latex random/poisson/same/sameInversionRatioOfUniformsWinrandLargeArgument.pdf "Execution times for the same means." width=0.5\textwidth \image html random/poisson/different/differentInversionRatioOfUniformsWinrandSmallArgument.jpg "Execution times for different means." \image latex random/poisson/different/differentInversionRatioOfUniformsWinrandSmallArgument.pdf "Execution times for different means." width=0.5\textwidth \image html random/poisson/different/differentInversionRatioOfUniformsWinrandLargeArgument.jpg "Execution times for different means." \image latex random/poisson/different/differentInversionRatioOfUniformsWinrandLargeArgument.pdf "Execution times for different means." width=0.5\textwidth \image html random/poisson/distribution/distributionInversionRatioOfUniformsWinrandSmallArgument.jpg "Execution times for a distribution of means." \image latex random/poisson/distribution/distributionInversionRatioOfUniformsWinrandSmallArgument.pdf "Execution times for a distribution of means." width=0.5\textwidth \image html random/poisson/distribution/distributionInversionRatioOfUniformsWinrandLargeArgument.jpg "Execution times for a distribution of means." \image latex random/poisson/distribution/distributionInversionRatioOfUniformsWinrandLargeArgument.pdf "Execution times for a distribution of means." width=0.5\textwidth */ template<class _Uniform = DISCRETE_UNIFORM_GENERATOR_DEFAULT, typename _Result = std::size_t> class PoissonGeneratorInversionRatioOfUniformsWinrand { public: //! The number type. typedef _Result Number; //! The argument type. typedef Number argument_type; //! The result type. typedef _Result result_type; //! The discrete uniform generator. typedef _Uniform DiscreteUniformGenerator; // // Member data. // private: //! The discrete uniform generator. DiscreteUniformGenerator* _discreteUniformGenerator; // // Not implemented. // private: //! Default constructor not implemented. PoissonGeneratorInversionRatioOfUniformsWinrand(); public: //! Construct using the uniform generator. explicit PoissonGeneratorInversionRatioOfUniformsWinrand (DiscreteUniformGenerator* generator) : _discreteUniformGenerator(generator) {} //! Copy constructor. PoissonGeneratorInversionRatioOfUniformsWinrand (const PoissonGeneratorInversionRatioOfUniformsWinrand& other) : _discreteUniformGenerator(other._discreteUniformGenerator) {} //! Assignment operator. PoissonGeneratorInversionRatioOfUniformsWinrand& operator=(const PoissonGeneratorInversionRatioOfUniformsWinrand& other) { if (this != &other) { _discreteUniformGenerator = other._discreteUniformGenerator; } return *this; } //! Destructor. ~PoissonGeneratorInversionRatioOfUniformsWinrand() {} //! Seed the uniform random number generator. void seed(const typename DiscreteUniformGenerator::result_type seedValue) { _discreteUniformGenerator->seed(seedValue); } //! Return a Poisson deviate with the specifed mean. result_type operator()(argument_type mean); }; END_NAMESPACE_NUMERICAL #define __numerical_random_PoissonGeneratorInversionRatioOfUniformsWinrand_ipp__ #include "PoissonGeneratorInversionRatioOfUniformsWinrand.ipp" #undef __numerical_random_PoissonGeneratorInversionRatioOfUniformsWinrand_ipp__ #endif
[ "cpbotha@vxlabs.com" ]
cpbotha@vxlabs.com
8c3c93a3cea52cd5ae24b25bcee07171816f6824
77f78708f87096ee87d9b8a18ce0ff76bec84712
/Cpp_Version/RayTracingInOneWeekend/RayTracingInOneWeekend/hitable_list.h
46711012f6c28eaffc5bda86299ca4a9b3d6f4ab
[]
no_license
Arctic-0/RayTracingInOneWeekend
32fc309e7c50c2d3efa927431d8a780d67e42bd0
7b94a6d29d75c3254336c1425699f1c028d37a1e
refs/heads/master
2023-07-16T08:53:56.027341
2021-09-03T15:24:30
2021-09-03T15:24:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
703
h
#pragma once #ifndef HITABLELISTH #define HITABLELISTH #include "hitable.h" class hitable_list : public hitable { public: hitable_list() {} hitable_list(hitable **l, int n) { list = l; list_size = n; } virtual bool hit(const ray& r, float tmin, float tmax, hit_record& rec) const; hitable **list; int list_size; }; bool hitable_list::hit(const ray& r, float t_min, float t_max, hit_record& rec) const { hit_record temp_rec; bool hit_anything = false; double closest_so_far = t_max; for (int i = 0; i < list_size; i++) { if (list[i]->hit(r, t_min, closest_so_far, temp_rec)) { hit_anything = true; closest_so_far = temp_rec.t; rec = temp_rec; } } return hit_anything; } #endif
[ "406943342@qq.com" ]
406943342@qq.com
5cdb6ad93389b2bcabb308651cb13a28356765ec
3c6727a2ec316c0c9bd0f9368171f4f37af3c4e7
/half_bridge/dc_motor_shield/DC-Motor-Control-TLE94112EL/src/TLE94112.cpp
a42b00b51300b9aec45e8218cd024d1871ebc769
[ "BSD-3-Clause" ]
permissive
ventilator/arduino
d0ad705553adfaf5f1b05463d6e137b416675a28
cbd6fedd2e86c6ce4ecdd19b9db6d70dd9bd14da
refs/heads/master
2021-01-10T02:11:13.732168
2018-07-05T13:49:48
2018-07-05T13:49:48
49,771,373
0
0
null
null
null
null
UTF-8
C++
false
false
5,679
cpp
/* * Arduino library to control Infineon's DC Motor Control Shield with TLE94112 * * The shield contains twelve independent halfbridges, * so it can drive up to 6 indipendent (+5 cascaded) bidirectional DC motor(s). * Each halfbridge provides a high-Voltage (nominal 5.5-18 V) tristate output, * which is also capable of PWM with 3 different frequencies. * * Have a look at the datasheet for more information. */ /*! \file TLE94112.cpp * \brief This file defines functions and predefined instances from TLE94112.h */ #include "TLE94112.h" #include "./util/tle94112_conf.h" //SPI address commands #define TLE94112_CMD_WRITE 0x80; #define TLE94112_CMD_CLEAR 0x80; //standard pin assignment #define TLE94112_PIN_CS1 10 #define TLE94112_PIN_CS2 9 #define TLE94112_PIN_EN 8 #define TLE94112_CS_RISETIME 2 #define TLE94112_STATUS_INV_MASK (Tle94112::TLE_POWER_ON_RESET) //predefined instances Tle94112 tle94112(&SPI, TLE94112_PIN_CS1, TLE94112_PIN_EN); Tle94112 tle94112_2(&SPI, TLE94112_PIN_CS2, TLE94112_PIN_EN); Tle94112::Tle94112(void) { Tle94112(&SPI, TLE94112_PIN_CS1, TLE94112_PIN_EN); } Tle94112::Tle94112(SPIClass *bus, uint8_t cs, uint8_t en) { mEnabled = FALSE; mBus = bus; mCsPin = cs; mEnPin = en; } void Tle94112::begin(void) { mEnabled = TRUE; mBus->begin(); mBus->setBitOrder(LSBFIRST); mBus->setClockDivider(SPI_CLOCK_DIV16); mBus->setDataMode(SPI_MODE1); pinMode(mEnPin, OUTPUT); pinMode(mCsPin, OUTPUT); digitalWrite(mCsPin, HIGH); digitalWrite(mEnPin, HIGH); init(); } void Tle94112::end(void) { mEnabled = FALSE; digitalWrite(mCsPin, HIGH); digitalWrite(mEnPin, LOW); } void Tle94112::configHB(HalfBridge hb, HBState state, PWMChannel pwm) { configHB(hb, state, pwm, 0); } void Tle94112::configHB(HalfBridge hb, HBState state, PWMChannel pwm, uint8_t activeFW) { if(mEnabled == TRUE) { configHB(static_cast<uint8_t>(hb), static_cast<uint8_t>(state), static_cast<uint8_t>(pwm), activeFW ); } } void Tle94112::configHB(uint8_t hb, uint8_t state, uint8_t pwm, uint8_t activeFW) { uint8_t reg = mHalfBridges[hb].stateReg; uint8_t mask = mHalfBridges[hb].stateMask; uint8_t shift = mHalfBridges[hb].stateShift; writeReg(reg, mask, shift, state); reg = mHalfBridges[hb].pwmReg; mask = mHalfBridges[hb].pwmMask; shift = mHalfBridges[hb].pwmShift; writeReg(reg, mask, shift, pwm); reg = mHalfBridges[hb].fwReg; mask = mHalfBridges[hb].fwMask; shift = mHalfBridges[hb].fwShift; writeReg(reg, mask, shift, pwm); } void Tle94112::configPWM(PWMChannel pwm, PWMFreq freq, uint8_t dutyCycle) { if(mEnabled == TRUE) { configPWM(static_cast<uint8_t>(pwm), static_cast<uint8_t>(freq), dutyCycle ); } } void Tle94112::configPWM(uint8_t pwm, uint8_t freq, uint8_t dutyCycle) { uint8_t reg = mPwmChannels[pwm].freqReg; uint8_t mask = mPwmChannels[pwm].freqMask; uint8_t shift = mPwmChannels[pwm].freqShift; writeReg(reg, mask, shift, freq); reg = mPwmChannels[pwm].dcReg; mask = mPwmChannels[pwm].dcMask; shift = mPwmChannels[pwm].dcShift; writeReg(reg, mask, shift, dutyCycle); } uint8_t Tle94112::getSysDiagnosis() { uint8_t ret = readStatusReg(SYS_DIAG1); return ret^TLE94112_STATUS_INV_MASK; } uint8_t Tle94112::getSysDiagnosis(DiagFlag mask) { return getSysDiagnosis(static_cast<uint8_t>(mask)); } uint8_t Tle94112::getSysDiagnosis(uint8_t mask) { uint8_t ret = readStatusReg(SYS_DIAG1, mask, 0); return ret^(TLE94112_STATUS_INV_MASK&mask); } uint8_t Tle94112::getHBOverCurrent(HalfBridge hb) { return getHBOverCurrent(static_cast<uint8_t>(hb)); } uint8_t Tle94112::getHBOverCurrent(uint8_t hb) { uint8_t reg = mHalfBridges[hb].ocReg; uint8_t mask = mHalfBridges[hb].ocMask; uint8_t shift = mHalfBridges[hb].ocShift; return readStatusReg(reg, mask, shift); } uint8_t Tle94112::getHBOpenLoad(HalfBridge hb) { return getHBOpenLoad(static_cast<uint8_t>(hb)); } uint8_t Tle94112::getHBOpenLoad(uint8_t hb) { uint8_t reg = mHalfBridges[hb].olReg; uint8_t mask = mHalfBridges[hb].olMask; uint8_t shift = mHalfBridges[hb].olShift; return readStatusReg(reg, mask, shift); } void Tle94112::clearErrors() { clearStatusReg(SYS_DIAG1); clearStatusReg(OP_ERROR_1_STAT); clearStatusReg(OP_ERROR_2_STAT); clearStatusReg(OP_ERROR_3_STAT); clearStatusReg(OP_ERROR_4_STAT); clearStatusReg(OP_ERROR_5_STAT); clearStatusReg(OP_ERROR_6_STAT); } void Tle94112::writeReg(uint8_t reg, uint8_t mask, uint8_t shift, uint8_t data) { uint8_t address = mCtrlRegAddresses[reg]; uint8_t toWrite = mCtrlRegData[reg] & (~mask); toWrite |= (data << shift) & mask; mCtrlRegData[reg] = toWrite; address = address | TLE94112_CMD_WRITE; digitalWrite(mCsPin, LOW); uint8_t byte0 = mBus->transfer(address); uint8_t byte1 = mBus->transfer(toWrite); digitalWrite(mCsPin, HIGH); delay(TLE94112_CS_RISETIME); } uint8_t Tle94112::readStatusReg(uint8_t reg) { //read the whole register return readStatusReg(reg, 0xFF, 0); } uint8_t Tle94112::readStatusReg(uint8_t reg, uint8_t mask, uint8_t shift) { uint8_t address = mStatusRegAddresses[reg]; digitalWrite(mCsPin, LOW); uint8_t byte0 = SPI.transfer(address); uint8_t received = SPI.transfer(0xFF); //send dummy byte while receiving digitalWrite(mCsPin, HIGH); delay(TLE94112_CS_RISETIME); received = (received & mask) >> shift; return received; } void Tle94112::clearStatusReg(uint8_t reg) { uint8_t address = mStatusRegAddresses[reg]; address = address | TLE94112_CMD_CLEAR; digitalWrite(mCsPin, LOW); uint8_t byte0 = mBus->transfer(address); uint8_t byte1 = mBus->transfer(0); //clear register by writing 0x00 digitalWrite(mCsPin, HIGH); delay(TLE94112_CS_RISETIME); }
[ "gruenewald.clemens@gmail.com" ]
gruenewald.clemens@gmail.com
88ce2d81a56f43a5f2f048202284b0a079546863
a8461f71fa5dea2da62570c375a743d51fb10c64
/AF_2.0/lattice.cpp
d4d672f48cb48ac8a0e810230c8b13e6930c722a
[]
no_license
JoshFreemont/AF
25528c3025031fadc243009b6277b9d84d0d784e
0f33cabb264373a8e9b05df880b0b50c8d372c2c
refs/heads/master
2020-12-24T13:35:51.677932
2014-09-13T12:48:57
2014-09-13T12:48:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,312
cpp
// // lattice.cpp // AF_2.0 // // Created by josh freemont on 29/08/2014. // Copyright (c) 2014 com.example. All rights reserved. // #include "lattice.h" #include <ctime> //Constructor //Initialises SinoAtrial Period, Grid Size. Reserve capacity for coordinate data. //Set lattice1D new pointer to instances of cell class. lattice2D::lattice2D(int SAP_INIT, const int SIZE_INIT) { SAP = SAP_INIT; SIZE = SIZE_INIT; //vector of pairs: vector<pair<xcoord,ycoord> > newExCoords.reserve(SIZE*SIZE); oldExCoords.reserve(SIZE*SIZE); lattice1D = new cell[SIZE_INIT*SIZE_INIT]; } //InitCells //Initializes/Reinitializes all cells: sets parameter values to default, callibrates cell positional relationships. //Sets defect/vertical connection locations dependent on the model type. bool lattice2D::initCells(int RP, double defectDensity, double epsilon, std::string defectType, double vertDensity, double eta, std::string vertType, MTRand_open& rand) { //Initialize/Re-Initialize. for (int i = 0; i<SIZE*SIZE; i++) { lattice1D[i].init(RP);//set individual values. lattice1D[i].setCellRelations(lattice1D, SIZE, i);//calibrate cell position and link to neighbours } //Set Defect Locations if(defectType == "static")//static defects. { double measuredDensity = 0.0; int defectCount = 0; int index = 0; //verify measured density never greater than required density. while (measuredDensity < defectDensity) { //case epsilon = 0.0 - epsilon set to 0.0 above, so break. if(epsilon == 0.0) break; //case epsilon != 0.0 - (rnd select && unique select). if(rand() < defectDensity && lattice1D[index].getEpsilon() != epsilon) { lattice1D[index].setEpsilon(epsilon); defectCount++;//increment defect count measuredDensity = defectCount/(double)(SIZE*SIZE);//recalculate measured density } index = (index+1)%(SIZE*SIZE);//increment index, periodic with total length of lattice1D } } else if(defectType == "dynamic")//dynamic defects { for(int i = 0; i<SIZE*SIZE; i++){lattice1D[i].setEpsilon(epsilon*defectDensity);} } else return false; //if unknown defect type. //Set Vert Locations if(vertType == "static")//static verts { double measuredDensity = 0.0; int vertCount = 0; int index = 0; //verify that measured density is never greater than required density. while (measuredDensity < vertDensity) { //case eta = 0.0 - eta set to 0.0 above, so break. if(eta == 0.0) break;// //case eta != 0.0 - (rnd select && unique select) if(rand() < vertDensity && lattice1D[index].getEtaN() != eta) { //determine north index with continuous BCs. int index_N = (index + (SIZE*SIZE) - SIZE)%(SIZE*SIZE); //set north connection on current cell == south connection on north cell. lattice1D[index].setEtaN(eta); lattice1D[index_N].setEtaS(eta); vertCount++;//increment vert count measuredDensity = vertCount/(double)(SIZE*SIZE);//recalculate measured density. } index = (index+1)%(SIZE*SIZE); } } else if(vertType == "dynamic")//dynamic verts { for(int i = 0; i<SIZE*SIZE; i++){lattice1D[i].setEtaN(eta); lattice1D[i].setEtaS(eta);} } else return false;//unknown vert type return true;//successful initiation } //Iterate //Method carries out one step iteration: takes old excited cell excites neighbours probabilistically. //Stores new excited coordinates. void lattice2D::iterate(int frame, MTRand_open &rand) { //iterate through oldExCoords to calculate newExCoords. for(auto coords = oldExCoords.begin(); coords != oldExCoords.end(); coords++) { //find previously excited cell and calculate subsequent excitation of neighbours. int index1D = coords->first + SIZE*coords->second;//find 1d index. std::vector<int> exctdNeighbrs = lattice1D[index1D].exciteAll(frame, rand);//return excited coords //iterate through exctdNeighbours and add to newExCoords. for(auto neighbrs = exctdNeighbrs.begin(); neighbrs != exctdNeighbrs.end(); neighbrs++) { newExCoords.push_back(index1Dto2D(*neighbrs, SIZE)); } } } //Pacemaker //Periodically excites the Westmost cells, still according to the rules of excitation. void lattice2D::pacemaker(int frame, MTRand_open& rand) { if(frame%SAP==0) { for (int j = 0; j<SIZE*SIZE; j+=SIZE) { if(lattice1D[j].excite(frame, rand)) { newExCoords.push_back(std::make_pair(0, (int)j/SIZE)); lattice1D[j].setExBy(&lattice1D[j]); } } } } //Update //Updates excited coordinate memory. void lattice2D::update() { oldExCoords.clear(); oldExCoords = newExCoords; newExCoords.clear(); } //getExcitedCoords //Returns coordinates of currently excited cells. std::vector<int> lattice2D::getExcitedCoords() { std::vector<int> coords; coords.reserve(SIZE*SIZE); for(auto it = newExCoords.begin(); it !=newExCoords.end(); it++) { coords.push_back(it->first); coords.push_back(it->second); } return coords; } //DetectRtrs //do not care about rotor identification, only detection. //for each excited cell site get chain of excited cells which may form a rotor std::vector<int> lattice2D::detectRtrs(int maxLength, int maxX, int maxY) { //declare rotors pixel data. std::vector<int> rotors; rotors.reserve(SIZE*SIZE); for(auto coord = newExCoords.begin(); coord != newExCoords.end(); coord++) { //declare local variables. int exCoord1D = index2Dto1D(*coord, SIZE); int minRepeatLength = 1; //declare temp chain vector std::vector<int> chain; chain.reserve(maxLength);//reserve max rotor length chain = lattice1D[exCoord1D].getExChainCoords(maxLength, minRepeatLength, maxX, maxY);//fill chain with coords. //check excited chain is physical if(!chain.size()) continue;//if chain length==0: skip to next coords. //look for repeats. for(int i = minRepeatLength; i < chain.size(); i++) { if(chain[i-1] == exCoord1D)//if a loop is formed { chain.erase(chain.begin()+i, chain.end());//erase elements beyond the repeat. for(auto it = chain.begin(); it != chain.end(); it++) { //return vector in format {x1, y1, ... xN, yN}. rotors.push_back(index1Dto2D(*it, SIZE).first); rotors.push_back(index1Dto2D(*it, SIZE).second); } } } } return rotors; } //DetectSimpleReEntry //Assume "simple" re-entry- ie. only one lane behaves defectively st. all vertical connections are excited from flanking lanes. //Check for respective intervals between North/South vertical connections, then check for re-entry condition to a defect. //function returns a 2d vector, indexed [i][j], with a count of how many re-entry circuits each cell is a member. std::vector<std::vector<int> > lattice2D::detectSimpleReEntry(int minLength) { std::vector<int> reEntry1D (SIZE*SIZE, 0);//1d vector for re-entry structure count (indexed by 1d cell coord) int vertN = -1, vertS = -1; for(int i = 0; i < SIZE*SIZE; i++)//iterate over 1d lattice { //check for north vertical if(lattice1D[i].getEtaN() != 0.0) { //check if is first vert in row if(vertN == -1) { vertN = i; continue; }//set vertN and go to next vert. //check interval between vert i and vertN. if(i - vertN > minLength)//if interval is large enough for re-entry check for defects. { int reEntryCount = 0;//reEntryCount counts how many re-entry circuits are detected for(int j = vertN; j < i; j++)//iterate from vertN forwards obeying reEntry length condition { //if defect exists obeying condition for re-entry: add to reEntry count if((j < i - minLength) && lattice1D[j].getEpsilon() != 0.0){reEntryCount ++;} reEntry1D[j] += reEntryCount;//add count to 1d re-entry vector. } reEntryCount = 0;//reset reEntryCount and iterate backwards obeying reentry length condition for(int j = i; j > vertN; j--)//iterate from vertN backwards checking defect. { //if defect exists obeying condition for re-entry: add to reEntry count if((j > vertN + minLength) && lattice1D[j].getEpsilon() != 0.0){reEntryCount ++;} reEntry1D[j] += reEntryCount;//add count to 1d re-entry vector. } } vertN = i;//reassign vertN } //check south vertical if(lattice1D[i].getEtaS() != 0.0) { //check if first vert in row if(vertS == -1){vertS = i; continue;} //check interval between vert i and vertS if(i - vertS > minLength)//if interval is large enough for re-entry. { int reEntryCount = 0; for(int j = vertS; j <= i; j++)//iterate from vertS forwards checking defects { //if defect exists obeying condition for re-entry: add to reEntry count if((j < i - minLength) && lattice1D[j].getEpsilon() != 0.0){reEntryCount ++;} reEntry1D[j] += reEntryCount;//add count to 1d re-entry vector. } reEntryCount = 0; for(int j = i; j >= vertS; j--)//iterate from i backwards checking defect. { //if elligible defect exists add to reEntry count if((j > vertS + minLength) && lattice1D[j].getEpsilon() != 0.0){reEntryCount ++;} reEntry1D[j] += reEntryCount;//add count to 1d re-entry vector. } } vertS = i;//reassign vertS } //reassign vertS and vertN to default if at end of row if((i+1)%SIZE == 0) { vertN = -1;//if at end of row: reset vertN=-1 for start of next row. vertS = -1;//if at end of row: reset vertS=-1 for start of next row. } } //Return reEntry count vector in 2D. std::vector<std::vector<int> > reEntry2D (SIZE, std::vector<int>(SIZE,0)); for(int i=0; i<SIZE; i++)//iterate through columns { for(int j=0; j<SIZE; j++)//iterate through rows { reEntry2D[i][j] = reEntry1D[i+SIZE*j];//add data from 1D to 2D vector. } } return reEntry2D;//return 2D vector. }
[ "giosh@hotmail.co.uk" ]
giosh@hotmail.co.uk
b4d4d60e856f94fe581fd70a64dad7144f5c2190
8ec4ef59d30685452f569aa7932b7bea7792d7fa
/Source/ShooterMulti/Public/MenuInterface.h
715bff12b6b292b907a363a07941f9b386fafe2f
[]
no_license
DavidKirkpatrick95/UE4-Multiplayer-Shooter
a575b11b10c6ac0cfa66d261411e43a245c6247c
9f8546c25f497442241994f65e9b3bc202f43397
refs/heads/master
2023-03-02T23:55:52.968758
2020-11-29T19:24:43
2020-11-29T19:24:43
308,693,016
0
0
null
null
null
null
UTF-8
C++
false
false
714
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "UObject/Interface.h" #include "MenuInterface.generated.h" // This class does not need to be modified. UINTERFACE(MinimalAPI) class UMenuInterface : public UInterface { GENERATED_BODY() }; /** * */ class SHOOTERMULTI_API IMenuInterface { GENERATED_BODY() // Add interface functions to this class. This is the class that will be inherited to implement this interface. public: virtual void Host() = 0; //pure virtual function to be implemented by Main Menu virtual void Join(const FString& Address) = 0; virtual void LoadMainMenu() = 0; virtual void QuitGame() = 0; };
[ "david.kirkpatrick83@gmail.com" ]
david.kirkpatrick83@gmail.com
cd635e4d625bb3686f72b20d8bdda13b29db5b44
4d1d1c1b84cb9f02fb8677f9fb2dae9244ff82e6
/add_on/scripthandle/scripthandle.cpp
c636637305904324d7f8d3bab4d93e5239d32d8e
[]
no_license
simongeilfus/angelscriptsdk
c6ea619750695bf9c99bb0072fed63d11a458d35
c892cabbd10a809d064d8601490495518c0cbf6d
refs/heads/master
2020-12-31T02:43:08.010577
2014-12-14T02:01:40
2014-12-14T02:01:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,279
cpp
#include "scripthandle.h" #include <new> #include <assert.h> #include <string.h> BEGIN_AS_NAMESPACE static void Construct(CScriptHandle *self) { new(self) CScriptHandle(); } static void Construct(CScriptHandle *self, const CScriptHandle &o) { new(self) CScriptHandle(o); } // This one is not static because it needs to be friend with the CScriptHandle class void Construct(CScriptHandle *self, void *ref, int typeId) { new(self) CScriptHandle(ref, typeId); } static void Destruct(CScriptHandle *self) { self->~CScriptHandle(); } CScriptHandle::CScriptHandle() { m_ref = 0; m_type = 0; } CScriptHandle::CScriptHandle(const CScriptHandle &other) { m_ref = other.m_ref; m_type = other.m_type; AddRefHandle(); } CScriptHandle::CScriptHandle(void *ref, asIObjectType *type) { m_ref = ref; m_type = type; AddRefHandle(); } // This constructor shouldn't be called from the application // directly as it requires an active script context CScriptHandle::CScriptHandle(void *ref, int typeId) { m_ref = 0; m_type = 0; Assign(ref, typeId); } CScriptHandle::~CScriptHandle() { ReleaseHandle(); } void CScriptHandle::ReleaseHandle() { if( m_ref && m_type ) { asIScriptEngine *engine = m_type->GetEngine(); engine->ReleaseScriptObject(m_ref, m_type); engine->Release(); m_ref = 0; m_type = 0; } } void CScriptHandle::AddRefHandle() { if( m_ref && m_type ) { asIScriptEngine *engine = m_type->GetEngine(); engine->AddRefScriptObject(m_ref, m_type); // Hold on to the engine so it isn't destroyed while // a reference to a script object is still held engine->AddRef(); } } CScriptHandle &CScriptHandle::operator =(const CScriptHandle &other) { Set(other.m_ref, other.m_type); return *this; } void CScriptHandle::Set(void *ref, asIObjectType *type) { if( m_ref == ref ) return; ReleaseHandle(); m_ref = ref; m_type = type; AddRefHandle(); } asIObjectType *CScriptHandle::GetType() const { return m_type; } int CScriptHandle::GetTypeId() const { if( m_type == 0 ) return 0; if( m_type->GetFlags() & asOBJ_SCRIPT_FUNCTION ) { asIScriptFunction *func = reinterpret_cast<asIScriptFunction*>(m_ref); return func->GetTypeId() | asTYPEID_OBJHANDLE; } return m_type->GetTypeId() | asTYPEID_OBJHANDLE; } // This method shouldn't be called from the application // directly as it requires an active script context CScriptHandle &CScriptHandle::Assign(void *ref, int typeId) { // When receiving a null handle we just clear our memory if( typeId == 0 ) { Set(0, 0); return *this; } // Dereference received handles to get the object if( typeId & asTYPEID_OBJHANDLE ) { // Store the actual reference ref = *(void**)ref; typeId &= ~asTYPEID_OBJHANDLE; } // Get the object type asIScriptContext *ctx = asGetActiveContext(); asIScriptEngine *engine = ctx->GetEngine(); asIObjectType *type = engine->GetObjectTypeById(typeId); // If the argument is another CScriptHandle, we should copy the content instead if( type && strcmp(type->GetName(), "ref") == 0 ) { CScriptHandle *r = (CScriptHandle*)ref; ref = r->m_ref; type = r->m_type; } Set(ref, type); return *this; } bool CScriptHandle::operator==(const CScriptHandle &o) const { if( m_ref == o.m_ref && m_type == o.m_type ) return true; // TODO: If type is not the same, we should attempt to do a dynamic cast, // which may change the pointer for application registered classes return false; } bool CScriptHandle::operator!=(const CScriptHandle &o) const { return !(*this == o); } bool CScriptHandle::Equals(void *ref, int typeId) const { // Null handles are received as reference to a null handle if( typeId == 0 ) ref = 0; // Dereference handles to get the object if( typeId & asTYPEID_OBJHANDLE ) { // Compare the actual reference ref = *(void**)ref; typeId &= ~asTYPEID_OBJHANDLE; } // TODO: If typeId is not the same, we should attempt to do a dynamic cast, // which may change the pointer for application registered classes if( ref == m_ref ) return true; return false; } // AngelScript: used as '@obj = cast<obj>(ref);' void CScriptHandle::Cast(void **outRef, int typeId) { // If we hold a null handle, then just return null if( m_type == 0 ) { *outRef = 0; return; } // It is expected that the outRef is always a handle assert( typeId & asTYPEID_OBJHANDLE ); // Compare the type id of the actual object typeId &= ~asTYPEID_OBJHANDLE; asIScriptEngine *engine = m_type->GetEngine(); asIObjectType *type = engine->GetObjectTypeById(typeId); *outRef = 0; if( type == m_type ) { // If the requested type is a script function it is // necessary to check if the functions are compatible too if( m_type->GetFlags() & asOBJ_SCRIPT_FUNCTION ) { asIScriptFunction *func = reinterpret_cast<asIScriptFunction*>(m_ref); if( !func->IsCompatibleWithTypeId(typeId) ) return; } // Must increase the ref count as we're returning a new reference to the object engine->AddRefScriptObject(m_ref, m_type); *outRef = m_ref; } else { // RefCastObject will increment the refCount of the returned object if successful engine->RefCastObject(m_ref, m_type, type, outRef); } } void RegisterScriptHandle_Native(asIScriptEngine *engine) { int r; #if AS_CAN_USE_CPP11 // With C++11 it is possible to use asGetTypeTraits to automatically determine the flags that represent the C++ class r = engine->RegisterObjectType("ref", sizeof(CScriptHandle), asOBJ_VALUE | asOBJ_ASHANDLE | asGetTypeTraits<CScriptHandle>()); assert( r >= 0 ); #else r = engine->RegisterObjectType("ref", sizeof(CScriptHandle), asOBJ_VALUE | asOBJ_ASHANDLE | asOBJ_APP_CLASS_CDAK); assert( r >= 0 ); #endif r = engine->RegisterObjectBehaviour("ref", asBEHAVE_CONSTRUCT, "void f()", asFUNCTIONPR(Construct, (CScriptHandle *), void), asCALL_CDECL_OBJFIRST); assert( r >= 0 ); r = engine->RegisterObjectBehaviour("ref", asBEHAVE_CONSTRUCT, "void f(const ref &in)", asFUNCTIONPR(Construct, (CScriptHandle *, const CScriptHandle &), void), asCALL_CDECL_OBJFIRST); assert( r >= 0 ); r = engine->RegisterObjectBehaviour("ref", asBEHAVE_CONSTRUCT, "void f(const ?&in)", asFUNCTIONPR(Construct, (CScriptHandle *, void *, int), void), asCALL_CDECL_OBJFIRST); assert( r >= 0 ); r = engine->RegisterObjectBehaviour("ref", asBEHAVE_DESTRUCT, "void f()", asFUNCTIONPR(Destruct, (CScriptHandle *), void), asCALL_CDECL_OBJFIRST); assert( r >= 0 ); r = engine->RegisterObjectBehaviour("ref", asBEHAVE_REF_CAST, "void f(?&out)", asMETHODPR(CScriptHandle, Cast, (void **, int), void), asCALL_THISCALL); assert( r >= 0 ); r = engine->RegisterObjectMethod("ref", "ref &opHndlAssign(const ref &in)", asMETHOD(CScriptHandle, operator=), asCALL_THISCALL); assert( r >= 0 ); r = engine->RegisterObjectMethod("ref", "ref &opHndlAssign(const ?&in)", asMETHOD(CScriptHandle, Assign), asCALL_THISCALL); assert( r >= 0 ); r = engine->RegisterObjectMethod("ref", "bool opEquals(const ref &in) const", asMETHODPR(CScriptHandle, operator==, (const CScriptHandle &) const, bool), asCALL_THISCALL); assert( r >= 0 ); r = engine->RegisterObjectMethod("ref", "bool opEquals(const ?&in) const", asMETHODPR(CScriptHandle, Equals, (void*, int) const, bool), asCALL_THISCALL); assert( r >= 0 ); } void CScriptHandle_Construct_Generic(asIScriptGeneric *gen) { CScriptHandle *self = reinterpret_cast<CScriptHandle*>(gen->GetObject()); new(self) CScriptHandle(); } void CScriptHandle_ConstructCopy_Generic(asIScriptGeneric *gen) { CScriptHandle *other = reinterpret_cast<CScriptHandle*>(gen->GetArgAddress(0)); CScriptHandle *self = reinterpret_cast<CScriptHandle*>(gen->GetObject()); new(self) CScriptHandle(*other); } void CScriptHandle_ConstructVar_Generic(asIScriptGeneric *gen) { void *ref = gen->GetArgAddress(0); int typeId = gen->GetArgTypeId(0); CScriptHandle *self = reinterpret_cast<CScriptHandle*>(gen->GetObject()); Construct(self, ref, typeId); } void CScriptHandle_Destruct_Generic(asIScriptGeneric *gen) { CScriptHandle *self = reinterpret_cast<CScriptHandle*>(gen->GetObject()); self->~CScriptHandle(); } void CScriptHandle_Cast_Generic(asIScriptGeneric *gen) { void **ref = reinterpret_cast<void**>(gen->GetArgAddress(0)); int typeId = gen->GetArgTypeId(0); CScriptHandle *self = reinterpret_cast<CScriptHandle*>(gen->GetObject()); self->Cast(ref, typeId); } void CScriptHandle_Assign_Generic(asIScriptGeneric *gen) { CScriptHandle *other = reinterpret_cast<CScriptHandle*>(gen->GetArgAddress(0)); CScriptHandle *self = reinterpret_cast<CScriptHandle*>(gen->GetObject()); *self = *other; gen->SetReturnAddress(self); } void CScriptHandle_AssignVar_Generic(asIScriptGeneric *gen) { void *ref = gen->GetArgAddress(0); int typeId = gen->GetArgTypeId(0); CScriptHandle *self = reinterpret_cast<CScriptHandle*>(gen->GetObject()); self->Assign(ref, typeId); gen->SetReturnAddress(self); } void CScriptHandle_Equals_Generic(asIScriptGeneric *gen) { CScriptHandle *other = reinterpret_cast<CScriptHandle*>(gen->GetArgAddress(0)); CScriptHandle *self = reinterpret_cast<CScriptHandle*>(gen->GetObject()); gen->SetReturnByte(*self == *other); } void CScriptHandle_EqualsVar_Generic(asIScriptGeneric *gen) { void *ref = gen->GetArgAddress(0); int typeId = gen->GetArgTypeId(0); CScriptHandle *self = reinterpret_cast<CScriptHandle*>(gen->GetObject()); gen->SetReturnByte(self->Equals(ref, typeId)); } void RegisterScriptHandle_Generic(asIScriptEngine *engine) { int r; r = engine->RegisterObjectType("ref", sizeof(CScriptHandle), asOBJ_VALUE | asOBJ_ASHANDLE | asOBJ_APP_CLASS_CDAK); assert( r >= 0 ); r = engine->RegisterObjectBehaviour("ref", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(CScriptHandle_Construct_Generic), asCALL_GENERIC); assert( r >= 0 ); r = engine->RegisterObjectBehaviour("ref", asBEHAVE_CONSTRUCT, "void f(const ref &in)", asFUNCTION(CScriptHandle_ConstructCopy_Generic), asCALL_GENERIC); assert( r >= 0 ); r = engine->RegisterObjectBehaviour("ref", asBEHAVE_CONSTRUCT, "void f(const ?&in)", asFUNCTION(CScriptHandle_ConstructVar_Generic), asCALL_GENERIC); assert( r >= 0 ); r = engine->RegisterObjectBehaviour("ref", asBEHAVE_DESTRUCT, "void f()", asFUNCTION(CScriptHandle_Destruct_Generic), asCALL_GENERIC); assert( r >= 0 ); r = engine->RegisterObjectBehaviour("ref", asBEHAVE_REF_CAST, "void f(?&out)", asFUNCTION(CScriptHandle_Cast_Generic), asCALL_GENERIC); assert( r >= 0 ); r = engine->RegisterObjectMethod("ref", "ref &opAssign(const ref &in)", asFUNCTION(CScriptHandle_Assign_Generic), asCALL_GENERIC); assert( r >= 0 ); r = engine->RegisterObjectMethod("ref", "ref &opAssign(const ?&in)", asFUNCTION(CScriptHandle_AssignVar_Generic), asCALL_GENERIC); assert( r >= 0 ); r = engine->RegisterObjectMethod("ref", "bool opEquals(const ref &in) const", asFUNCTION(CScriptHandle_Equals_Generic), asCALL_GENERIC); assert( r >= 0 ); r = engine->RegisterObjectMethod("ref", "bool opEquals(const ?&in) const", asFUNCTION(CScriptHandle_EqualsVar_Generic), asCALL_GENERIC); assert( r >= 0 ); } void RegisterScriptHandle(asIScriptEngine *engine) { if( strstr(asGetLibraryOptions(), "AS_MAX_PORTABILITY") ) RegisterScriptHandle_Generic(engine); else RegisterScriptHandle_Native(engine); } END_AS_NAMESPACE
[ "angelcode@404ce1b2-830e-0410-a2e2-b09542c77caf" ]
angelcode@404ce1b2-830e-0410-a2e2-b09542c77caf
25c591326571d617020ac864b6257e808e561e93
519a52653ba485b4ec3e8044e39014ece7822d5c
/oop/04-inheritance/01.cpp
d666d8ec83e24076c0821e9897536036b7c64dc2
[]
no_license
ACMatUC/cpp-language-review
3713c05f0ee68211e7e366e35e773086c33fde47
0c2f93da187c011c7b54c9296adab5c66a72775e
refs/heads/master
2021-01-19T06:23:51.977128
2017-02-22T22:54:27
2017-02-22T22:54:27
79,752,524
1
0
null
null
null
null
UTF-8
C++
false
false
1,193
cpp
#include <iostream> #include <string> using namespace std; class Person { private: string name, address, ssn; public: Person(string inName, string inAddress, string inSSN) : name(inName), address(inAddress), ssn(inSSN) { /* More logic here if necessary */ } string getName() { return this->name; } string getAddress() { return this->address; } string getSSN() { return ssn; // `this->` is not necessary } }; class Student: public Person { private: string mNumber; public: Student(string inName, string inAddress, string inSSN, string inMNumber) : Person(inName, inAddress, inSSN), mNumber(inMNumber) { /* Again, more logic if we needed */ } string getMNumber() { return this->mNumber; } }; /** * Access modifier, why does getName() work on student? * Theoretical memory layout of a "Student" */ int main() { Person alice("alice", "215 Street Here" , "XXX-XX-XXXX"); cout << alice.getName() << endl; cout << alice.getAddress() << endl; cout << alice.getSSN() << endl; Student sam("sam", "215 Street Here", "XXX-XX", "M02995953"); cout << sam.getName() << endl; cout << sam.getMNumber() << endl; return 0; }
[ "domfarolino@gmail.com" ]
domfarolino@gmail.com
803d2173c032835f8071f8e9b2dd51f8d71dd353
3e5ae9b260b16fcc86bb0669c1bd4e56912b5433
/VCB600ENU1/MSDN_VCB/SAMPLES/VC98/SDK/NETDS/ADSI/SAMPPROV/CENUMSCH.CPP
ca418eb86dad4b519cced8fa637ecf128245266f
[]
no_license
briancpark/deitel-cpp
e8612c7011c9d9d748290419ae2708d2f3f11543
90cdae5661718e65ab945bcf45fe6adff30c1e10
refs/heads/main
2023-06-14T14:07:05.497253
2021-07-05T01:46:04
2021-07-05T01:46:04
382,984,213
0
0
null
null
null
null
UTF-8
C++
false
false
8,843
cpp
/*++ Copyright (c) 1996 Microsoft Corporation Module Name: CEnumSch.cpp Abstract: Sample Provider Enum Schema functionality Author: Environment: User mode Revision History : --*/ #include "adssmp.h" #pragma hdrstop //+--------------------------------------------------------------------------- // // Function: CSampleDSSchemaEnum::Create // // Synopsis: // // Arguments: [pCollection] // [ppEnumVariant] // // Returns: HRESULT // // Modifies: // // History: 01-30-95 yihsins Created. // //---------------------------------------------------------------------------- HRESULT CSampleDSSchemaEnum::Create( CSampleDSSchemaEnum FAR* FAR* ppenumvariant, BSTR bstrSampleDSTreeName, BSTR bstrADsPath, BSTR bstrName, VARIANT var ) { HRESULT hr = S_OK; CSampleDSSchemaEnum FAR* penumvariant = NULL; *ppenumvariant = NULL; penumvariant = new CSampleDSSchemaEnum(); if (!penumvariant) { hr = E_OUTOFMEMORY; BAIL_ON_FAILURE(hr); } hr = ProvAllocString( bstrSampleDSTreeName, &penumvariant->_bstrSampleDSTreeName); BAIL_ON_FAILURE(hr); hr = ProvAllocString( bstrADsPath, &penumvariant->_bstrADsPath); BAIL_ON_FAILURE(hr); hr = ProvAllocString( bstrName, &penumvariant->_bstrName); BAIL_ON_FAILURE(hr); hr = ObjectTypeList::CreateObjectTypeList( var, &penumvariant->_pObjList ); BAIL_ON_FAILURE(hr); *ppenumvariant = penumvariant; RRETURN(hr); error: delete penumvariant; RRETURN(hr); } CSampleDSSchemaEnum::CSampleDSSchemaEnum() : _bstrADsPath( NULL ), _bstrName( NULL ), _bstrSampleDSTreeName( NULL ), _pObjList( NULL ) { _lpClassDefs = NULL; _dwClassCurrent = 0; _dwClassReturned = 0; _lpAttrDefs = NULL; _dwAttrCurrent = 0; _dwAttrReturned = 0; } CSampleDSSchemaEnum::~CSampleDSSchemaEnum() { ProvFreeString( _bstrName ); ProvFreeString( _bstrADsPath ); ProvFreeString( _bstrSampleDSTreeName ); if ( _pObjList != NULL ) { delete _pObjList; _pObjList = NULL; } } //+--------------------------------------------------------------------------- // // Function: CSampleDSSchemaEnum::Next // // Synopsis: Returns cElements number of requested NetOle objects in the // array supplied in pvar. // // Arguments: [cElements] -- The number of elements requested by client // [pvar] -- ptr to array of VARIANTs to for return objects // [pcElementFetched] -- if non-NULL, then number of elements // -- actually returned is placed here // // Returns: HRESULT -- S_OK if number of elements requested are returned // -- S_FALSE if number of elements is < requested // // Modifies: // // History: 11-3-95 yihsins Created. // //---------------------------------------------------------------------------- STDMETHODIMP CSampleDSSchemaEnum::Next( ULONG cElements, VARIANT FAR* pvar, ULONG FAR* pcElementFetched ) { ULONG cElementFetched = 0; HRESULT hr = S_OK; hr = EnumObjects( cElements, pvar, &cElementFetched ); if ( pcElementFetched ) *pcElementFetched = cElementFetched; RRETURN(hr); } HRESULT CSampleDSSchemaEnum::EnumObjects( DWORD ObjectType, ULONG cElements, VARIANT FAR * pvar, ULONG FAR * pcElementFetched ) { switch (ObjectType) { case SampleDS_CLASS_ID: RRETURN (EnumClasses(cElements, pvar, pcElementFetched)); case SampleDS_PROPERTY_ID: RRETURN (EnumProperties(cElements, pvar, pcElementFetched)); default: RRETURN(S_FALSE); } } HRESULT CSampleDSSchemaEnum::EnumObjects( ULONG cElements, VARIANT FAR* pvar, ULONG FAR* pcElementFetched ) { DWORD i; ULONG cRequested = 0; ULONG cFetchedByPath = 0; ULONG cTotalFetched = 0; VARIANT FAR* pPathvar = pvar; HRESULT hr; DWORD ObjectType; for (i = 0; i < cElements; i++) VariantInit(&pvar[i]); cRequested = cElements; while ( SUCCEEDED( _pObjList->GetCurrentObject(&ObjectType)) && ((hr = EnumObjects( ObjectType, cRequested, pPathvar, &cFetchedByPath)) == S_FALSE ) ) { pPathvar += cFetchedByPath; cRequested -= cFetchedByPath; cTotalFetched += cFetchedByPath; cFetchedByPath = 0; if ( FAILED(_pObjList->Next()) ) { if ( pcElementFetched ) *pcElementFetched = cTotalFetched; RRETURN(S_FALSE); } } if ( pcElementFetched ) *pcElementFetched = cTotalFetched + cFetchedByPath; RRETURN(hr); } HRESULT CSampleDSSchemaEnum::EnumClasses( ULONG cElements, VARIANT FAR* pvar, ULONG FAR* pcElementFetched ) { HRESULT hr = S_OK; DWORD i = 0; IDispatch *pDispatch = NULL; while ( i < cElements ) { hr = GetClassObject(&pDispatch); if ( hr == S_FALSE ) break; VariantInit( &pvar[i] ); pvar[i].vt = VT_DISPATCH; pvar[i].pdispVal = pDispatch; (*pcElementFetched)++; i++; } RRETURN(hr); } HRESULT CSampleDSSchemaEnum::GetClassObject( IDispatch ** ppDispatch ) { HRESULT hr = S_OK; LPSampleDS_CLASS_DEF lpCurrentObject = NULL; if (!_lpClassDefs) { _dwClassCurrent = 0; hr = SampleDSGetClassDefinition(&_lpClassDefs, &_dwClassReturned); BAIL_ON_FAILURE(hr); } if (_dwClassCurrent == _dwClassReturned) { goto error; } if (_dwClassCurrent < _dwClassReturned) { // // Now send back the current object // lpCurrentObject = _lpClassDefs + _dwClassCurrent; hr = CSampleDSClass::CreateClass( _bstrADsPath, lpCurrentObject->lpClassName, lpCurrentObject, ADS_OBJECT_BOUND, IID_IDispatch, (void **)ppDispatch ); BAIL_ON_FAILURE(hr); _dwClassCurrent++; RRETURN(S_OK); } error: if (_lpClassDefs) { SampleDSFreeClassDefinition(_lpClassDefs, _dwClassReturned); } *ppDispatch = NULL; RRETURN(S_FALSE); } HRESULT CSampleDSSchemaEnum::EnumProperties( ULONG cElements, VARIANT FAR* pvar, ULONG FAR* pcElementFetched ) { HRESULT hr = S_OK; DWORD i = 0; IDispatch *pDispatch = NULL; while ( i < cElements ) { hr = GetPropertyObject(&pDispatch); if ( hr == S_FALSE ) break; VariantInit( &pvar[i] ); pvar[i].vt = VT_DISPATCH; pvar[i].pdispVal = pDispatch; (*pcElementFetched)++; i++; } RRETURN(hr); } HRESULT CSampleDSSchemaEnum::GetPropertyObject( IDispatch ** ppDispatch ) { HRESULT hr = S_OK; LPSampleDS_ATTR_DEF lpCurrentObject = NULL; if (!_lpAttrDefs) { _dwAttrCurrent = 0; hr = SampleDSGetPropertyDefinition(&_lpAttrDefs, &_dwAttrReturned); BAIL_ON_FAILURE(hr); } if (_dwAttrCurrent == _dwAttrReturned) { goto error; } if (_dwAttrCurrent < _dwAttrReturned) { lpCurrentObject = _lpAttrDefs + _dwAttrCurrent; hr = CSampleDSProperty::CreateProperty( _bstrADsPath, lpCurrentObject->lpAttributeName, lpCurrentObject, ADS_OBJECT_BOUND, IID_IDispatch, (void **)ppDispatch ); BAIL_ON_FAILURE(hr); _dwAttrCurrent++; RRETURN(S_OK); } error: if (_lpAttrDefs) SampleDSFreePropertyDefinition(_lpAttrDefs, _dwAttrReturned); *ppDispatch = NULL; RRETURN(S_FALSE); }
[ "briancpark@berkeley.edu" ]
briancpark@berkeley.edu
44808233301cd22e3ddf1d95bd01fea0c89a64e8
b1fca7a6b38cfdabe16eb9280bd13338035c0352
/test/constructor/pre_error.cpp
4bbbac10494f783fb2c8e7577bd13a7c6611c04e
[ "BSL-1.0" ]
permissive
danieljames/contract
14f6d8d74fd77f4474488e74b19984d4ff42c5ac
2a7205e98a1acbcc583b105036b68bf1d1c70953
refs/heads/master
2021-09-03T19:26:00.170791
2017-09-20T04:26:06
2017-09-20T04:26:06
104,771,261
0
0
null
2017-09-25T15:56:56
2017-09-25T15:56:56
null
UTF-8
C++
false
false
644
cpp
// Copyright (C) 2008-2017 Lorenzo Caminiti // Distributed under the Boost Software License, Version 1.0 (see accompanying // file LICENSE_1_0.txt or a copy at http://www.boost.org/LICENSE_1_0.txt). // See: http://www.boost.org/doc/libs/release/libs/contract/doc/html/index.html // Test constructor cannot use `.precondition(...)`. #include <boost/contract/constructor.hpp> #include <boost/contract/check.hpp> struct a { a() { boost::contract::check c = boost::contract::constructor(this) .precondition([] {}) // Error (must use constructor_precondition). ; } }; int main() { a aa; return 0; }
[ "lorcaminiti@gmail.com" ]
lorcaminiti@gmail.com
3e88292de4dc1afcbeb6393b39a41361f1ece4c6
becd5ee93440020322e3ad99926cebc0e71d786d
/src/common/expression/RelationalExpression.cpp
4b60d0d2434be7a38351b3d8c6d328a4ea391320
[ "Apache-2.0" ]
permissive
heyanlong/nebula
aa94f589a2d77d0cb6e40dcced1f5ee0a8e6a79c
07ccfde198c978b8c86b7091773e3238bfcdf454
refs/heads/master
2023-09-04T13:49:18.522506
2021-11-03T15:16:03
2021-11-03T15:16:03
424,433,008
1
0
null
null
null
null
UTF-8
C++
false
false
8,286
cpp
/* Copyright (c) 2020 vesoft inc. All rights reserved. * * This source code is licensed under Apache 2.0 License. */ #include "common/expression/RelationalExpression.h" #include "common/datatypes/List.h" #include "common/datatypes/Map.h" #include "common/datatypes/Set.h" #include "common/expression/ExprVisitor.h" namespace nebula { const Value& RelationalExpression::eval(ExpressionContext& ctx) { auto& lhs = lhs_->eval(ctx); auto& rhs = rhs_->eval(ctx); switch (kind_) { case Kind::kRelEQ: result_ = lhs.equal(rhs); break; case Kind::kRelNE: result_ = !lhs.equal(rhs); break; case Kind::kRelLT: result_ = lhs.lessThan(rhs); break; case Kind::kRelLE: result_ = lhs.lessThan(rhs) || lhs.equal(rhs); break; case Kind::kRelGT: result_ = !lhs.lessThan(rhs) && !lhs.equal(rhs); break; case Kind::kRelGE: result_ = !lhs.lessThan(rhs) || lhs.equal(rhs); break; case Kind::kRelREG: { if (lhs.isBadNull() || rhs.isBadNull()) { result_ = Value::kNullBadType; } else if ((!lhs.isNull() && !lhs.isStr()) || (!rhs.isNull() && !rhs.isStr())) { result_ = Value::kNullBadType; } else if (lhs.isStr() && rhs.isStr()) { try { const auto& r = ctx.getRegex(rhs.getStr()); result_ = std::regex_match(lhs.getStr(), r); } catch (const std::exception& ex) { LOG(ERROR) << "Regex match error: " << ex.what(); result_ = Value::kNullBadType; } } else { result_ = Value::kNullValue; } break; } case Kind::kRelIn: { if (rhs.isNull() && !rhs.isBadNull()) { result_ = Value::kNullValue; } else if (rhs.isList()) { auto& list = rhs.getList(); result_ = list.contains(lhs); if (UNLIKELY(result_.isBool() && !result_.getBool() && list.contains(Value::kNullValue))) { result_ = Value::kNullValue; } } else if (rhs.isSet()) { auto& set = rhs.getSet(); result_ = set.contains(lhs); if (UNLIKELY(result_.isBool() && !result_.getBool() && set.contains(Value::kNullValue))) { result_ = Value::kNullValue; } } else if (rhs.isMap()) { auto& map = rhs.getMap(); result_ = map.contains(lhs); if (UNLIKELY(result_.isBool() && !result_.getBool() && map.contains(Value::kNullValue))) { result_ = Value::kNullValue; } } else { result_ = Value(NullType::BAD_TYPE); } if (UNLIKELY(!result_.isBadNull() && lhs.isNull())) { result_ = Value::kNullValue; } break; } case Kind::kRelNotIn: { if (rhs.isNull() && !rhs.isBadNull()) { result_ = Value::kNullValue; } else if (rhs.isList()) { auto& list = rhs.getList(); result_ = !list.contains(lhs); if (UNLIKELY(result_.isBool() && result_.getBool() && list.contains(Value::kNullValue))) { result_ = Value::kNullValue; } } else if (rhs.isSet()) { auto& set = rhs.getSet(); result_ = !set.contains(lhs); if (UNLIKELY(result_.isBool() && result_.getBool() && set.contains(Value::kNullValue))) { result_ = Value::kNullValue; } } else if (rhs.isMap()) { auto& map = rhs.getMap(); result_ = !map.contains(lhs); if (UNLIKELY(result_.isBool() && result_.getBool() && map.contains(Value::kNullValue))) { result_ = Value::kNullValue; } } else { result_ = Value(NullType::BAD_TYPE); } if (UNLIKELY(!result_.isBadNull() && lhs.isNull())) { result_ = Value::kNullValue; } break; } case Kind::kContains: { if (lhs.isBadNull() || rhs.isBadNull()) { result_ = Value::kNullBadType; } else if ((!lhs.isNull() && !lhs.isStr()) || (!rhs.isNull() && !rhs.isStr())) { result_ = Value::kNullBadType; } else if (lhs.isStr() && rhs.isStr()) { result_ = lhs.getStr().size() >= rhs.getStr().size() && lhs.getStr().find(rhs.getStr()) != std::string::npos; } else { result_ = Value::kNullValue; } break; } case Kind::kNotContains: { if (lhs.isBadNull() || rhs.isBadNull()) { result_ = Value::kNullBadType; } else if ((!lhs.isNull() && !lhs.isStr()) || (!rhs.isNull() && !rhs.isStr())) { result_ = Value::kNullBadType; } else if (lhs.isStr() && rhs.isStr()) { result_ = !(lhs.getStr().size() >= rhs.getStr().size() && lhs.getStr().find(rhs.getStr()) != std::string::npos); } else { result_ = Value::kNullValue; } break; } case Kind::kStartsWith: { if (lhs.isBadNull() || rhs.isBadNull()) { result_ = Value::kNullBadType; } else if ((!lhs.isNull() && !lhs.isStr()) || (!rhs.isNull() && !rhs.isStr())) { result_ = Value::kNullBadType; } else if (lhs.isStr() && rhs.isStr()) { result_ = lhs.getStr().size() >= rhs.getStr().size() && lhs.getStr().find(rhs.getStr()) == 0; } else { result_ = Value::kNullValue; } break; } case Kind::kNotStartsWith: { if (lhs.isBadNull() || rhs.isBadNull()) { result_ = Value::kNullBadType; } else if ((!lhs.isNull() && !lhs.isStr()) || (!rhs.isNull() && !rhs.isStr())) { result_ = Value::kNullBadType; } else if (lhs.isStr() && rhs.isStr()) { result_ = !(lhs.getStr().size() >= rhs.getStr().size() && lhs.getStr().find(rhs.getStr()) == 0); } else { result_ = Value::kNullValue; } break; } case Kind::kEndsWith: { if (lhs.isBadNull() || rhs.isBadNull()) { result_ = Value::kNullBadType; } else if ((!lhs.isNull() && !lhs.isStr()) || (!rhs.isNull() && !rhs.isStr())) { result_ = Value::kNullBadType; } else if (lhs.isStr() && rhs.isStr()) { result_ = lhs.getStr().size() >= rhs.getStr().size() && lhs.getStr().compare( lhs.getStr().size() - rhs.getStr().size(), rhs.getStr().size(), rhs.getStr()) == 0; } else { result_ = Value::kNullValue; } break; } case Kind::kNotEndsWith: { if (lhs.isBadNull() || rhs.isBadNull()) { result_ = Value::kNullBadType; } else if ((!lhs.isNull() && !lhs.isStr()) || (!rhs.isNull() && !rhs.isStr())) { result_ = Value::kNullBadType; } else if (lhs.isStr() && rhs.isStr()) { result_ = !(lhs.getStr().size() >= rhs.getStr().size() && lhs.getStr().compare(lhs.getStr().size() - rhs.getStr().size(), rhs.getStr().size(), rhs.getStr()) == 0); } else { result_ = Value::kNullValue; } break; } default: LOG(FATAL) << "Unknown type: " << kind_; } return result_; } std::string RelationalExpression::toString() const { std::string op; switch (kind_) { case Kind::kRelLT: op = "<"; break; case Kind::kRelLE: op = "<="; break; case Kind::kRelGT: op = ">"; break; case Kind::kRelGE: op = ">="; break; case Kind::kRelEQ: op = "=="; break; case Kind::kRelNE: op = "!="; break; case Kind::kRelREG: op = "=~"; break; case Kind::kRelIn: op = " IN "; break; case Kind::kRelNotIn: op = " NOT IN "; break; case Kind::kContains: op = " CONTAINS "; break; case Kind::kNotContains: op = " NOT CONTAINS "; break; case Kind::kStartsWith: op = " STARTS WITH "; break; case Kind::kNotStartsWith: op = " NOT STARTS WITH "; break; case Kind::kEndsWith: op = " ENDS WITH "; break; case Kind::kNotEndsWith: op = " NOT ENDS WITH "; break; default: op = " illegal symbol "; } std::stringstream out; out << "(" << lhs_->toString() << op << rhs_->toString() << ")"; return out.str(); } void RelationalExpression::accept(ExprVisitor* visitor) { visitor->visit(this); } } // namespace nebula
[ "noreply@github.com" ]
heyanlong.noreply@github.com
04c017e2c2b8048b5e1e6868359bd025f8f6a184
cd8d38b5db8430b66b6aa8e917b2f2869c526d68
/Onyx/lib/fakes.cpp
8abc6978f0ab41a75b25374d840941c5821b163d
[]
no_license
jwatte/robotcode
48005310a8672287b4c70dee1339272e9d55a710
a95c78dfa63cb5b231a832c52e5aaea83c2d9a61
refs/heads/master
2016-09-06T12:24:06.913757
2013-08-18T03:12:23
2013-08-18T03:12:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,376
cpp
#include "fakes.h" #include <iostream> #include <stdexcept> Fakenet::Fakenet() { stepCnt_ = 0; wasLocked_ = false; wasUnlocked_ = false; locked_ = false; timeout_ = 0; } void Fakenet::step() { ++stepCnt_; } bool Fakenet::receive(size_t &size, void const *&packet) { if (!toReceive_.size()) { return false; } size = toReceive_.front().first; packet = toReceive_.front().second; toReceive_.pop_front(); return true; } void Fakenet::broadcast(size_t size, void const *packet) { iovec iov[1]; iov[0].iov_base = const_cast<void *>(packet); iov[0].iov_len = size; vsend(false, 1, iov); } void Fakenet::respond(size_t size, void const *packet) { iovec iov[1]; iov[0].iov_base = const_cast<void *>(packet); iov[0].iov_len = size; vsend(true, 1, iov); } void Fakenet::vsend(bool response, size_t cnt, iovec const *vecs) { std::vector<char> sent; while (cnt > 0) { sent.insert(sent.end(), (char const *)vecs->iov_base, (char const *)vecs->iov_base + vecs->iov_len); ++vecs; --cnt; } wereSent_.push_back(std::pair<bool, std::vector<char>>(response, sent)); } void Fakenet::lock_address(double timeout) { locked_ = true; wasLocked_ = true; timeout_ = timeout; } void Fakenet::unlock_address() { wasUnlocked_ = true; locked_ = false; } bool Fakenet::is_locked() { return locked_; } bool Fakenet::check_clear_overflow() { return false; } void Fakenet::check_clear_loss(int &lost, int &got) { lost = 1; got = 3; } void Fakestatus::message(std::string const &str) { messages_.push_back(Message(1, false, str)); } void Fakestatus::error(std::string const &str) { messages_.push_back(Message(1, true, str)); } size_t Fakestatus::n_messages() { return 0; } bool Fakestatus::get_message(Message &om) { return false; } int Fakesockets::recvfrom(void *buf, size_t sz, sockaddr_in &addr) { if (toReceive_.size() > 0) { rec r = toReceive_.front(); toReceive_.pop_front(); if (r.ret < 0) { return r.ret; } if (r.data.size() > 0) { memcpy(buf, &r.data[0], std::min(sz, r.data.size())); } r.addr = addr; return std::min(sz, r.data.size()); } return -1; } int Fakesockets::sendto(void const *buf, size_t sz, sockaddr_in const &addr) { wasSent_.push_back(rec()); wasSent_.back().ret = sz; wasSent_.back().addr = addr; wasSent_.back().data.insert(wasSent_.back().data.end(), (char const *)buf, (char const *)buf + sz); return sz; } boost::shared_ptr<ISocket> Fakesockets::connect(sockaddr_in const &addr) { // todo: maybe I should require pre-configuring addresses we connect to Fakesocket *sock = new Fakesocket(); sock->addr_ = addr; sock->owner_ = this; sock->connected_ = true; sockets_.push_back(sock); return boost::shared_ptr<ISocket>(sock); } Fakesocket::~Fakesocket() { owner_->sockets_.erase(std::find(owner_->sockets_.begin(), owner_->sockets_.end(), this)); } bool Fakesocket::step() { return connected_; } size_t Fakesocket::peek(void *buf, size_t maxSize) { if (!toRecv_.size()) { return 0; } if (maxSize > toRecv_.front().size()) { maxSize = toRecv_.front().size(); } if (maxSize) { memcpy(buf, &toRecv_.front()[0], maxSize); } return maxSize; } void Fakesocket::recvd(size_t maxSize) { if (!toRecv_.size()) { if (maxSize > 0) { throw std::runtime_error("bad call to recvd()"); } return; } if (maxSize > toRecv_.front().size()) { throw std::runtime_error("bad call to recvd()"); } if (toRecv_.front().size() == maxSize) { toRecv_.pop_front(); } else { toRecv_.front().erase(toRecv_.front().begin(), toRecv_.front().begin() +maxSize); } } size_t Fakesocket::send(void const *buf, size_t size) { sent_.push_back(std::vector<char>()); sent_.back().resize(size); if (size) { memcpy(&sent_.back()[0], buf, size); } return size; } Faketime::Faketime() { timeSlept_ = 0; time_ = 1; dTime_ = 0.008; } double Faketime::now() { time_ += dTime_; return time_; } void Faketime::sleep(double dt) { timeSlept_ += dt; time_ += dt; }
[ "jwatte@gmail.com" ]
jwatte@gmail.com
a541d352747efc5639b0d568fd71febeb12872e6
26b78f3fd4668de73bfa289163fe6522f67f6f60
/dg/src/analysis/ReachingDefinitions/Srg/MarkerSRGBuilderFS.h
4d5f6e48738b49ed6c7c484b92ce0c1a014de968
[ "MIT" ]
permissive
zytMatrix/binFICS
8aa522d1454f38c27f90288929c5c3ecc799952e
cd630a3d95f8b4eaba2563c78a75fe051db9fed6
refs/heads/master
2023-06-03T09:16:08.037042
2021-06-22T09:20:14
2021-06-22T09:20:14
371,326,263
1
0
null
null
null
null
UTF-8
C++
false
false
5,757
h
#ifndef _DG_MARKERSRGBUILDERFS_H #define _DG_MARKERSRGBUILDERFS_H #include <memory> #include <vector> #include <unordered_set> #include <unordered_map> #include <map> #include "analysis/BFS.h" #include "analysis/ReachingDefinitions/Srg/SparseRDGraphBuilder.h" #include "analysis/ReachingDefinitions/Srg/IntervalMap.h" namespace dg { namespace analysis { namespace rd { namespace srg { class MarkerSRGBuilderFS : public SparseRDGraphBuilder { /* see using-s in SparseRDGraphBuilder for reference... */ // offset in variable using OffsetT = uint64_t; using Intervals = std::vector<detail::Interval>; // for each variable { for each block { for each offset in variable { remember definition } } } using DefMapT = std::unordered_map<NodeT *, std::unordered_map<BlockT *, detail::IntervalMap<NodeT *>>>; /* the resulting graph - stored in class for convenience, moved away on return */ SparseRDGraph srg; /* phi nodes added during the process */ std::vector<std::unique_ptr<NodeT>> phi_nodes; /* work structures for strong defs */ DefMapT current_def; DefMapT last_def; /* work structures for weak defs */ DefMapT current_weak_def; DefMapT last_weak_def; /** * Remember strong definition @assignment of a @var in @block. * Side-effect: kill current overlapping strong definitions and current overlapping weak definitions. */ void writeVariableStrong(const DefSite& var, NodeT *assignment, BlockT *block); /** * Remember weak definition @assignment of @var in @block. * Does not affect other definitions. */ void writeVariableWeak(const DefSite& var, NodeT *assignment, BlockT *block); /** * Recursively looks up definition of @var in @block starting in @start. @start is supplied to prevent infinite recursion with weak updates. * @covered is set of intervals where strong update has already been found. * Returns a phi node that joins previous definitions. * The phi node is owned by the @phi_nodes vector. */ NodeT *readVariableRecursive(const DefSite& var, BlockT *block, BlockT *start, const Intervals& covered); /* * If the interval has unknown offset or length, it is changed to contain everything. * Optional parameter @size makes it possible to concretize to variable size, in case the size is known. */ detail::Interval concretize(detail::Interval interval, uint64_t size = Offset::UNKNOWN) const { if (size == 0) { size = Offset::UNKNOWN; } if (interval.isUnknown()) { return detail::Interval{ 0, size }; } return interval; } std::vector<NodeT *> readVariable(const DefSite& var, BlockT *read, BlockT *start) { Intervals empty_vector; return readVariable(var, read, start, empty_vector); } /** * Lookup all definitions of @var in @read starting from @start. */ std::vector<NodeT *> readVariable(const DefSite& var, BlockT *read, BlockT *start, const Intervals& covered); void addPhiOperands(const DefSite& var, NodeT *phi, BlockT *block, BlockT *start, const Intervals& covered); /** * Insert a def->use edge into the resulting SparseRDGraph. * @from is a definition * @to is a use */ void insertSrgEdge(NodeT *from, NodeT *to, const DefSite& var) { srg[from].push_back(std::make_pair(var, to)); } void performLvn(BlockT *block) { for (NodeT *node : block->getNodes()) { for (const DefSite& def : node->defs) { if (node->isOverwritten(def) && !def.offset.isUnknown()) { detail::Interval interval = concretize(detail::Interval{def.offset, def.len}, def.target->getSize()); last_def[def.target][block].killOverlapping(interval); last_weak_def[def.target][block].killOverlapping(interval); last_def[def.target][block].add(std::move(interval), node); } else { last_weak_def[def.target][block].add(concretize(detail::Interval{def.offset, def.len}, def.target->getSize()), node); } } } } void performGvn(BlockT *block) { for (NodeT *node : block->getNodes()) { for (const DefSite& use : node->getUses()) { std::vector<NodeT *> assignments = readVariable(use, block, block); // add edge from last definition to here for (NodeT *assignment : assignments) { insertSrgEdge(assignment, node, use); } } for (const DefSite& def : node->defs) { if (node->isOverwritten(def) && !def.offset.isUnknown()) { writeVariableStrong(def, node, block); } else { writeVariableWeak(def, node, block); } } } } public: std::pair<SparseRDGraph, std::vector<std::unique_ptr<NodeT>>> build(NodeT *root) override { current_def.clear(); BBlockBFS<NodeT> bfs(BFS_BB_CFG | BFS_INTERPROCEDURAL); AssignmentFinder af; af.populateUnknownMemory(root); std::vector<BlockT *> cfg; BlockT *block = root->getBBlock(); bfs.run(block, [&](BlockT *block, void*){ cfg.push_back(block); }, nullptr); for (BlockT *BB : cfg) { performLvn(BB); } for (BlockT *BB : cfg) { performGvn(BB); } return std::make_pair<SparseRDGraph, std::vector<std::unique_ptr<NodeT>>>(std::move(srg), std::move(phi_nodes)); } }; } } } } #endif /* _DG_MARKERSRGBUILDERFS_H */
[ "919902609@qq.com" ]
919902609@qq.com
5eee5d77b8728c72746b4e45bd6ccd834cf43cf5
45b4fdd740f367b4cbce2071b565f3640cc99d9c
/OFTest1/src/game/leveldesc/level.cpp
ffeeca10de422d28b2f6054dd5235843c85ca57e
[]
no_license
paarm/of_playground
7bd928de0a3f3b0235f83f5f187abba96486e137
272f0c6db4ae4cd30e8ae05eb71e6f924c35a38c
refs/heads/master
2021-01-19T10:17:53.373873
2017-04-10T19:46:02
2017-04-10T19:46:02
87,850,680
0
0
null
null
null
null
UTF-8
C++
false
false
1,979
cpp
#include "level.h" void Level::clearLevel() { mLevelName=""; mObjectDescMap.clear(); mLayerList.clear(); mTextureManager.reset(); mLevelObjectNameNbPool=0; } void Level::setLevelName(const string &rLevelName) { mLevelName=rLevelName; } string& Level::getLevelName() { return mLevelName; } ObjectDesc& Level::getOrAddObjectDesc(const string& rId) { ObjectDesc &rObjectDescExist=getObjectDescByName(rId); if (!rObjectDescExist.isValid() && !rId.empty()) { return mObjectDescMap.emplace(rId, rId).first->second; //auto y=x.first; //return y->second; } return rObjectDescExist; } bool Level::isObjectDescAvailable(const string &rId) { bool rv=false; if (mObjectDescMap.find(rId)!=mObjectDescMap.end()) { rv=true; } return rv; } ObjectDesc& Level::getObjectDescByName(const string &rId) { auto it=mObjectDescMap.find(rId); if (it!=mObjectDescMap.end()) { return it->second; } return mEmptyObjectDesc; } void Level::setAssetPath(const string &rAssetPath) { mAssetPath=rAssetPath; } string &Level::getAssetPath() { return mAssetPath; } Layer& Level::getOrAddLayer(const string &rLayerName) { Layer &existLayer=getLayerByName(rLayerName); if (!rLayerName.empty() && !existLayer.isValid()) { mLayerList.emplace_back(rLayerName); return mLayerList.back(); } return existLayer; } Layer& Level::getLayerByName(const string &rLayerName) { auto foundIterator=find_if(mLayerList.begin(), mLayerList.end(), [&rLayerName] (Layer& r) { //cout <<"Lambda Layer Name: " << r.getLayerName() << "Name: "<< rLayerName <<endl; return rLayerName==r.getLayerName(); }); if (foundIterator!=mLayerList.end()) { return *foundIterator; } return mEmptyLayer; } int Level::getLayerCount() { return mLayerList.size(); } Layer& Level::getLayerFromIndex(int rIndex) { if (rIndex>=0 && rIndex<(int)mLayerList.size()) { return mLayerList[rIndex]; } return mEmptyLayer; } int Level::getNextLevelObjectNameNb() { return mLevelObjectNameNbPool++; }
[ "martin.paar@gmail.com" ]
martin.paar@gmail.com
07fcfe267a1db18ba13bfe44a7e7ebce60e44277
1f45bf1127ff868bf4d22753a65047d874c2ffb1
/src/thirdPartyLibs/apache-log4cxx-win32-0.10.0/apache-log4cxx-0.10.0/src/main/cpp/outputstreamwriter.cpp
8440c44a252c7c25d613a2be7410aea15e5b6d2c
[ "Apache-2.0" ]
permissive
smartdevice475/sdl_core_v3.6_wince
50207a89fa2bfe0487409e4ad3babae52e477b54
5fff3bd40f83517f89428895b3dbe069b0f2f262
refs/heads/master
2021-01-18T09:34:08.202701
2016-08-10T01:57:23
2016-08-10T01:57:23
55,580,033
2
0
null
2016-04-06T06:05:08
2016-04-06T06:05:08
null
UTF-8
C++
false
false
2,467
cpp
/* * 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. */ #ifdef OS_WINCE #include <stdlib.h> #endif #include <log4cxx/logstring.h> #include <log4cxx/helpers/outputstreamwriter.h> #include <log4cxx/helpers/exception.h> #include <log4cxx/helpers/charsetencoder.h> #include <log4cxx/helpers/bytebuffer.h> #include <log4cxx/helpers/stringhelper.h> using namespace log4cxx; using namespace log4cxx::helpers; IMPLEMENT_LOG4CXX_OBJECT(OutputStreamWriter) OutputStreamWriter::OutputStreamWriter(OutputStreamPtr& out1) : out(out1), enc(CharsetEncoder::getDefaultEncoder()) { if (out1 == 0) { throw NullPointerException(LOG4CXX_STR("out parameter may not be null.")); } } OutputStreamWriter::OutputStreamWriter(OutputStreamPtr& out1, CharsetEncoderPtr &enc1) : out(out1), enc(enc1) { if (out1 == 0) { throw NullPointerException(LOG4CXX_STR("out parameter may not be null.")); } if (enc1 == 0) { throw NullPointerException(LOG4CXX_STR("enc parameter may not be null.")); } } OutputStreamWriter::~OutputStreamWriter() { } void OutputStreamWriter::close(Pool& p) { out->close(p); } void OutputStreamWriter::flush(Pool& p) { out->flush(p); } void OutputStreamWriter::write(const LogString& str, Pool& p) { if (str.length() > 0) { enum { BUFSIZE = 1024 }; char rawbuf[BUFSIZE]; ByteBuffer buf(rawbuf, (size_t) BUFSIZE); enc->reset(); LogString::const_iterator iter = str.begin(); while(iter != str.end()) { CharsetEncoder::encode(enc, str, iter, buf); buf.flip(); out->write(buf, p); buf.clear(); } CharsetEncoder::encode(enc, str, iter, buf); enc->flush(buf); buf.flip(); out->write(buf, p); } }
[ "luwanjia@beyondsoft.com" ]
luwanjia@beyondsoft.com