blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
de5bbe8f6f4fff5cbd6a07511faf4204f0e5c858
5e4cd5a93fd2458979aa3c2dcc1cc62623c74fce
/Defs.h
ae8fb9a1ad03f1b7ee17cec00bb0cd8e77c945cf
[]
no_license
MichaelZhao21/CSCE1040-UNT-Project4
02ad94bb1b8aa31bed24cbae62485db7e639ad79
c5c4085096fe800bf3dd1a67a78cebaa7730d110
refs/heads/master
2022-04-17T22:20:15.311463
2020-04-18T22:17:38
2020-04-18T22:17:38
254,800,118
0
0
null
null
null
null
UTF-8
C++
false
false
311
h
#ifndef DEFS_H #define DEFS_H #include <string> #include <vector> #include <unordered_map> #include <iostream> #include <iomanip> #include <limits> #include <fstream> #include <cmath> #include <regex> #include <cassert> using namespace std; typedef vector<string> vs; typedef vector<int> vi; #endif //DEFS_H
[ "michaelzhao314@gmail.com" ]
michaelzhao314@gmail.com
ca16c0536ae1bf60bc6b904de7f377d4b9906cc2
1dbf007249acad6038d2aaa1751cbde7e7842c53
/gaussdbfornosql/src/v3/model/NoSqlModiflyEpsQuotasRequestBody.cpp
2fde09aa2814ae9ae58ade75e6c66e8fe4e14f45
[]
permissive
huaweicloud/huaweicloud-sdk-cpp-v3
24fc8d93c922598376bdb7d009e12378dff5dd20
71674f4afbb0cd5950f880ec516cfabcde71afe4
refs/heads/master
2023-08-04T19:37:47.187698
2023-08-03T08:25:43
2023-08-03T08:25:43
324,328,641
11
10
Apache-2.0
2021-06-24T07:25:26
2020-12-25T09:11:43
C++
UTF-8
C++
false
false
1,620
cpp
#include "huaweicloud/gaussdbfornosql/v3/model/NoSqlModiflyEpsQuotasRequestBody.h" namespace HuaweiCloud { namespace Sdk { namespace Gaussdbfornosql { namespace V3 { namespace Model { NoSqlModiflyEpsQuotasRequestBody::NoSqlModiflyEpsQuotasRequestBody() { quotasIsSet_ = false; } NoSqlModiflyEpsQuotasRequestBody::~NoSqlModiflyEpsQuotasRequestBody() = default; void NoSqlModiflyEpsQuotasRequestBody::validate() { } web::json::value NoSqlModiflyEpsQuotasRequestBody::toJson() const { web::json::value val = web::json::value::object(); if(quotasIsSet_) { val[utility::conversions::to_string_t("quotas")] = ModelBase::toJson(quotas_); } return val; } bool NoSqlModiflyEpsQuotasRequestBody::fromJson(const web::json::value& val) { bool ok = true; if(val.has_field(utility::conversions::to_string_t("quotas"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("quotas")); if(!fieldValue.is_null()) { std::vector<NoSqlRequestEpsQuota> refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setQuotas(refVal); } } return ok; } std::vector<NoSqlRequestEpsQuota>& NoSqlModiflyEpsQuotasRequestBody::getQuotas() { return quotas_; } void NoSqlModiflyEpsQuotasRequestBody::setQuotas(const std::vector<NoSqlRequestEpsQuota>& value) { quotas_ = value; quotasIsSet_ = true; } bool NoSqlModiflyEpsQuotasRequestBody::quotasIsSet() const { return quotasIsSet_; } void NoSqlModiflyEpsQuotasRequestBody::unsetquotas() { quotasIsSet_ = false; } } } } } }
[ "hwcloudsdk@huawei.com" ]
hwcloudsdk@huawei.com
9110d98534923d789537c83e84c41741052afc52
290b4c7ca63a975b38e55018cc38bd2766e14639
/ORC_app/jni-build/jni/genfiles/tensorflow/core/framework/step_stats.pb.h
429248f68c0a447bc991dfcf1b81222df44e6883
[ "MIT" ]
permissive
luoabd/EMNIST-ORC
1233c373abcc3ed237c2ec86491b29c0b9223894
8c2d633a9b4d5214e908550812f6a2489ba9eb72
refs/heads/master
2022-12-27T14:03:55.046933
2020-01-16T15:20:04
2020-01-16T15:20:04
234,325,497
0
1
MIT
2022-12-11T13:32:42
2020-01-16T13:25:23
C++
UTF-8
C++
false
true
43,549
h
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: tensorflow/core/framework/step_stats.proto #ifndef PROTOBUF_tensorflow_2fcore_2fframework_2fstep_5fstats_2eproto__INCLUDED #define PROTOBUF_tensorflow_2fcore_2fframework_2fstep_5fstats_2eproto__INCLUDED #include <string> #include <google/protobuf/stubs/common.h> #if GOOGLE_PROTOBUF_VERSION < 3000000 #error This file was generated by a newer version of protoc which is #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif #if 3000000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif #include <google/protobuf/arena.h> #include <google/protobuf/arenastring.h> #include <google/protobuf/generated_message_util.h> #include <google/protobuf/metadata.h> #include <google/protobuf/message.h> #include <google/protobuf/repeated_field.h> #include <google/protobuf/extension_set.h> #include <google/protobuf/unknown_field_set.h> #include "tensorflow/core/framework/allocation_description.pb.h" #include "tensorflow/core/framework/tensor_description.pb.h" // @@protoc_insertion_point(includes) namespace tensorflow { // Internal implementation detail -- do not call these. void protobuf_AddDesc_tensorflow_2fcore_2fframework_2fstep_5fstats_2eproto(); void protobuf_AssignDesc_tensorflow_2fcore_2fframework_2fstep_5fstats_2eproto(); void protobuf_ShutdownFile_tensorflow_2fcore_2fframework_2fstep_5fstats_2eproto(); class AllocatorMemoryUsed; class DeviceStepStats; class NodeExecStats; class NodeOutput; class StepStats; // =================================================================== class AllocatorMemoryUsed : public ::google::protobuf::Message { public: AllocatorMemoryUsed(); virtual ~AllocatorMemoryUsed(); AllocatorMemoryUsed(const AllocatorMemoryUsed& from); inline AllocatorMemoryUsed& operator=(const AllocatorMemoryUsed& from) { CopyFrom(from); return *this; } static const ::google::protobuf::Descriptor* descriptor(); static const AllocatorMemoryUsed& default_instance(); void Swap(AllocatorMemoryUsed* other); // implements Message ---------------------------------------------- inline AllocatorMemoryUsed* New() const { return New(NULL); } AllocatorMemoryUsed* New(::google::protobuf::Arena* arena) const; void CopyFrom(const ::google::protobuf::Message& from); void MergeFrom(const ::google::protobuf::Message& from); void CopyFrom(const AllocatorMemoryUsed& from); void MergeFrom(const AllocatorMemoryUsed& from); void Clear(); bool IsInitialized() const; int ByteSize() const; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input); void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const; ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; int GetCachedSize() const { return _cached_size_; } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const; void InternalSwap(AllocatorMemoryUsed* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { return _internal_metadata_.arena(); } inline void* MaybeArenaPtr() const { return _internal_metadata_.raw_arena_ptr(); } public: ::google::protobuf::Metadata GetMetadata() const; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // optional string allocator_name = 1; void clear_allocator_name(); static const int kAllocatorNameFieldNumber = 1; const ::std::string& allocator_name() const; void set_allocator_name(const ::std::string& value); void set_allocator_name(const char* value); void set_allocator_name(const char* value, size_t size); ::std::string* mutable_allocator_name(); ::std::string* release_allocator_name(); void set_allocated_allocator_name(::std::string* allocator_name); // optional int64 total_bytes = 2; void clear_total_bytes(); static const int kTotalBytesFieldNumber = 2; ::google::protobuf::int64 total_bytes() const; void set_total_bytes(::google::protobuf::int64 value); // optional int64 peak_bytes = 3; void clear_peak_bytes(); static const int kPeakBytesFieldNumber = 3; ::google::protobuf::int64 peak_bytes() const; void set_peak_bytes(::google::protobuf::int64 value); // @@protoc_insertion_point(class_scope:tensorflow.AllocatorMemoryUsed) private: ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; bool _is_default_instance_; ::google::protobuf::internal::ArenaStringPtr allocator_name_; ::google::protobuf::int64 total_bytes_; ::google::protobuf::int64 peak_bytes_; mutable int _cached_size_; friend void protobuf_AddDesc_tensorflow_2fcore_2fframework_2fstep_5fstats_2eproto(); friend void protobuf_AssignDesc_tensorflow_2fcore_2fframework_2fstep_5fstats_2eproto(); friend void protobuf_ShutdownFile_tensorflow_2fcore_2fframework_2fstep_5fstats_2eproto(); void InitAsDefaultInstance(); static AllocatorMemoryUsed* default_instance_; }; // ------------------------------------------------------------------- class NodeOutput : public ::google::protobuf::Message { public: NodeOutput(); virtual ~NodeOutput(); NodeOutput(const NodeOutput& from); inline NodeOutput& operator=(const NodeOutput& from) { CopyFrom(from); return *this; } static const ::google::protobuf::Descriptor* descriptor(); static const NodeOutput& default_instance(); void Swap(NodeOutput* other); // implements Message ---------------------------------------------- inline NodeOutput* New() const { return New(NULL); } NodeOutput* New(::google::protobuf::Arena* arena) const; void CopyFrom(const ::google::protobuf::Message& from); void MergeFrom(const ::google::protobuf::Message& from); void CopyFrom(const NodeOutput& from); void MergeFrom(const NodeOutput& from); void Clear(); bool IsInitialized() const; int ByteSize() const; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input); void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const; ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; int GetCachedSize() const { return _cached_size_; } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const; void InternalSwap(NodeOutput* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { return _internal_metadata_.arena(); } inline void* MaybeArenaPtr() const { return _internal_metadata_.raw_arena_ptr(); } public: ::google::protobuf::Metadata GetMetadata() const; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // optional int32 slot = 1; void clear_slot(); static const int kSlotFieldNumber = 1; ::google::protobuf::int32 slot() const; void set_slot(::google::protobuf::int32 value); // optional .tensorflow.TensorDescription tensor_description = 3; bool has_tensor_description() const; void clear_tensor_description(); static const int kTensorDescriptionFieldNumber = 3; const ::tensorflow::TensorDescription& tensor_description() const; ::tensorflow::TensorDescription* mutable_tensor_description(); ::tensorflow::TensorDescription* release_tensor_description(); void set_allocated_tensor_description(::tensorflow::TensorDescription* tensor_description); // @@protoc_insertion_point(class_scope:tensorflow.NodeOutput) private: ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; bool _is_default_instance_; ::tensorflow::TensorDescription* tensor_description_; ::google::protobuf::int32 slot_; mutable int _cached_size_; friend void protobuf_AddDesc_tensorflow_2fcore_2fframework_2fstep_5fstats_2eproto(); friend void protobuf_AssignDesc_tensorflow_2fcore_2fframework_2fstep_5fstats_2eproto(); friend void protobuf_ShutdownFile_tensorflow_2fcore_2fframework_2fstep_5fstats_2eproto(); void InitAsDefaultInstance(); static NodeOutput* default_instance_; }; // ------------------------------------------------------------------- class NodeExecStats : public ::google::protobuf::Message { public: NodeExecStats(); virtual ~NodeExecStats(); NodeExecStats(const NodeExecStats& from); inline NodeExecStats& operator=(const NodeExecStats& from) { CopyFrom(from); return *this; } static const ::google::protobuf::Descriptor* descriptor(); static const NodeExecStats& default_instance(); void Swap(NodeExecStats* other); // implements Message ---------------------------------------------- inline NodeExecStats* New() const { return New(NULL); } NodeExecStats* New(::google::protobuf::Arena* arena) const; void CopyFrom(const ::google::protobuf::Message& from); void MergeFrom(const ::google::protobuf::Message& from); void CopyFrom(const NodeExecStats& from); void MergeFrom(const NodeExecStats& from); void Clear(); bool IsInitialized() const; int ByteSize() const; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input); void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const; ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; int GetCachedSize() const { return _cached_size_; } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const; void InternalSwap(NodeExecStats* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { return _internal_metadata_.arena(); } inline void* MaybeArenaPtr() const { return _internal_metadata_.raw_arena_ptr(); } public: ::google::protobuf::Metadata GetMetadata() const; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // optional string node_name = 1; void clear_node_name(); static const int kNodeNameFieldNumber = 1; const ::std::string& node_name() const; void set_node_name(const ::std::string& value); void set_node_name(const char* value); void set_node_name(const char* value, size_t size); ::std::string* mutable_node_name(); ::std::string* release_node_name(); void set_allocated_node_name(::std::string* node_name); // optional int64 all_start_micros = 2; void clear_all_start_micros(); static const int kAllStartMicrosFieldNumber = 2; ::google::protobuf::int64 all_start_micros() const; void set_all_start_micros(::google::protobuf::int64 value); // optional int64 op_start_rel_micros = 3; void clear_op_start_rel_micros(); static const int kOpStartRelMicrosFieldNumber = 3; ::google::protobuf::int64 op_start_rel_micros() const; void set_op_start_rel_micros(::google::protobuf::int64 value); // optional int64 op_end_rel_micros = 4; void clear_op_end_rel_micros(); static const int kOpEndRelMicrosFieldNumber = 4; ::google::protobuf::int64 op_end_rel_micros() const; void set_op_end_rel_micros(::google::protobuf::int64 value); // optional int64 all_end_rel_micros = 5; void clear_all_end_rel_micros(); static const int kAllEndRelMicrosFieldNumber = 5; ::google::protobuf::int64 all_end_rel_micros() const; void set_all_end_rel_micros(::google::protobuf::int64 value); // repeated .tensorflow.AllocatorMemoryUsed memory = 6; int memory_size() const; void clear_memory(); static const int kMemoryFieldNumber = 6; const ::tensorflow::AllocatorMemoryUsed& memory(int index) const; ::tensorflow::AllocatorMemoryUsed* mutable_memory(int index); ::tensorflow::AllocatorMemoryUsed* add_memory(); ::google::protobuf::RepeatedPtrField< ::tensorflow::AllocatorMemoryUsed >* mutable_memory(); const ::google::protobuf::RepeatedPtrField< ::tensorflow::AllocatorMemoryUsed >& memory() const; // repeated .tensorflow.NodeOutput output = 7; int output_size() const; void clear_output(); static const int kOutputFieldNumber = 7; const ::tensorflow::NodeOutput& output(int index) const; ::tensorflow::NodeOutput* mutable_output(int index); ::tensorflow::NodeOutput* add_output(); ::google::protobuf::RepeatedPtrField< ::tensorflow::NodeOutput >* mutable_output(); const ::google::protobuf::RepeatedPtrField< ::tensorflow::NodeOutput >& output() const; // optional string timeline_label = 8; void clear_timeline_label(); static const int kTimelineLabelFieldNumber = 8; const ::std::string& timeline_label() const; void set_timeline_label(const ::std::string& value); void set_timeline_label(const char* value); void set_timeline_label(const char* value, size_t size); ::std::string* mutable_timeline_label(); ::std::string* release_timeline_label(); void set_allocated_timeline_label(::std::string* timeline_label); // optional int64 scheduled_micros = 9; void clear_scheduled_micros(); static const int kScheduledMicrosFieldNumber = 9; ::google::protobuf::int64 scheduled_micros() const; void set_scheduled_micros(::google::protobuf::int64 value); // optional uint32 thread_id = 10; void clear_thread_id(); static const int kThreadIdFieldNumber = 10; ::google::protobuf::uint32 thread_id() const; void set_thread_id(::google::protobuf::uint32 value); // repeated .tensorflow.AllocationDescription referenced_tensor = 11; int referenced_tensor_size() const; void clear_referenced_tensor(); static const int kReferencedTensorFieldNumber = 11; const ::tensorflow::AllocationDescription& referenced_tensor(int index) const; ::tensorflow::AllocationDescription* mutable_referenced_tensor(int index); ::tensorflow::AllocationDescription* add_referenced_tensor(); ::google::protobuf::RepeatedPtrField< ::tensorflow::AllocationDescription >* mutable_referenced_tensor(); const ::google::protobuf::RepeatedPtrField< ::tensorflow::AllocationDescription >& referenced_tensor() const; // @@protoc_insertion_point(class_scope:tensorflow.NodeExecStats) private: ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; bool _is_default_instance_; ::google::protobuf::internal::ArenaStringPtr node_name_; ::google::protobuf::int64 all_start_micros_; ::google::protobuf::int64 op_start_rel_micros_; ::google::protobuf::int64 op_end_rel_micros_; ::google::protobuf::int64 all_end_rel_micros_; ::google::protobuf::RepeatedPtrField< ::tensorflow::AllocatorMemoryUsed > memory_; ::google::protobuf::RepeatedPtrField< ::tensorflow::NodeOutput > output_; ::google::protobuf::internal::ArenaStringPtr timeline_label_; ::google::protobuf::int64 scheduled_micros_; ::google::protobuf::RepeatedPtrField< ::tensorflow::AllocationDescription > referenced_tensor_; ::google::protobuf::uint32 thread_id_; mutable int _cached_size_; friend void protobuf_AddDesc_tensorflow_2fcore_2fframework_2fstep_5fstats_2eproto(); friend void protobuf_AssignDesc_tensorflow_2fcore_2fframework_2fstep_5fstats_2eproto(); friend void protobuf_ShutdownFile_tensorflow_2fcore_2fframework_2fstep_5fstats_2eproto(); void InitAsDefaultInstance(); static NodeExecStats* default_instance_; }; // ------------------------------------------------------------------- class DeviceStepStats : public ::google::protobuf::Message { public: DeviceStepStats(); virtual ~DeviceStepStats(); DeviceStepStats(const DeviceStepStats& from); inline DeviceStepStats& operator=(const DeviceStepStats& from) { CopyFrom(from); return *this; } static const ::google::protobuf::Descriptor* descriptor(); static const DeviceStepStats& default_instance(); void Swap(DeviceStepStats* other); // implements Message ---------------------------------------------- inline DeviceStepStats* New() const { return New(NULL); } DeviceStepStats* New(::google::protobuf::Arena* arena) const; void CopyFrom(const ::google::protobuf::Message& from); void MergeFrom(const ::google::protobuf::Message& from); void CopyFrom(const DeviceStepStats& from); void MergeFrom(const DeviceStepStats& from); void Clear(); bool IsInitialized() const; int ByteSize() const; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input); void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const; ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; int GetCachedSize() const { return _cached_size_; } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const; void InternalSwap(DeviceStepStats* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { return _internal_metadata_.arena(); } inline void* MaybeArenaPtr() const { return _internal_metadata_.raw_arena_ptr(); } public: ::google::protobuf::Metadata GetMetadata() const; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // optional string device = 1; void clear_device(); static const int kDeviceFieldNumber = 1; const ::std::string& device() const; void set_device(const ::std::string& value); void set_device(const char* value); void set_device(const char* value, size_t size); ::std::string* mutable_device(); ::std::string* release_device(); void set_allocated_device(::std::string* device); // repeated .tensorflow.NodeExecStats node_stats = 2; int node_stats_size() const; void clear_node_stats(); static const int kNodeStatsFieldNumber = 2; const ::tensorflow::NodeExecStats& node_stats(int index) const; ::tensorflow::NodeExecStats* mutable_node_stats(int index); ::tensorflow::NodeExecStats* add_node_stats(); ::google::protobuf::RepeatedPtrField< ::tensorflow::NodeExecStats >* mutable_node_stats(); const ::google::protobuf::RepeatedPtrField< ::tensorflow::NodeExecStats >& node_stats() const; // @@protoc_insertion_point(class_scope:tensorflow.DeviceStepStats) private: ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; bool _is_default_instance_; ::google::protobuf::internal::ArenaStringPtr device_; ::google::protobuf::RepeatedPtrField< ::tensorflow::NodeExecStats > node_stats_; mutable int _cached_size_; friend void protobuf_AddDesc_tensorflow_2fcore_2fframework_2fstep_5fstats_2eproto(); friend void protobuf_AssignDesc_tensorflow_2fcore_2fframework_2fstep_5fstats_2eproto(); friend void protobuf_ShutdownFile_tensorflow_2fcore_2fframework_2fstep_5fstats_2eproto(); void InitAsDefaultInstance(); static DeviceStepStats* default_instance_; }; // ------------------------------------------------------------------- class StepStats : public ::google::protobuf::Message { public: StepStats(); virtual ~StepStats(); StepStats(const StepStats& from); inline StepStats& operator=(const StepStats& from) { CopyFrom(from); return *this; } static const ::google::protobuf::Descriptor* descriptor(); static const StepStats& default_instance(); void Swap(StepStats* other); // implements Message ---------------------------------------------- inline StepStats* New() const { return New(NULL); } StepStats* New(::google::protobuf::Arena* arena) const; void CopyFrom(const ::google::protobuf::Message& from); void MergeFrom(const ::google::protobuf::Message& from); void CopyFrom(const StepStats& from); void MergeFrom(const StepStats& from); void Clear(); bool IsInitialized() const; int ByteSize() const; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input); void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const; ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; int GetCachedSize() const { return _cached_size_; } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const; void InternalSwap(StepStats* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { return _internal_metadata_.arena(); } inline void* MaybeArenaPtr() const { return _internal_metadata_.raw_arena_ptr(); } public: ::google::protobuf::Metadata GetMetadata() const; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // repeated .tensorflow.DeviceStepStats dev_stats = 1; int dev_stats_size() const; void clear_dev_stats(); static const int kDevStatsFieldNumber = 1; const ::tensorflow::DeviceStepStats& dev_stats(int index) const; ::tensorflow::DeviceStepStats* mutable_dev_stats(int index); ::tensorflow::DeviceStepStats* add_dev_stats(); ::google::protobuf::RepeatedPtrField< ::tensorflow::DeviceStepStats >* mutable_dev_stats(); const ::google::protobuf::RepeatedPtrField< ::tensorflow::DeviceStepStats >& dev_stats() const; // @@protoc_insertion_point(class_scope:tensorflow.StepStats) private: ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; bool _is_default_instance_; ::google::protobuf::RepeatedPtrField< ::tensorflow::DeviceStepStats > dev_stats_; mutable int _cached_size_; friend void protobuf_AddDesc_tensorflow_2fcore_2fframework_2fstep_5fstats_2eproto(); friend void protobuf_AssignDesc_tensorflow_2fcore_2fframework_2fstep_5fstats_2eproto(); friend void protobuf_ShutdownFile_tensorflow_2fcore_2fframework_2fstep_5fstats_2eproto(); void InitAsDefaultInstance(); static StepStats* default_instance_; }; // =================================================================== // =================================================================== #if !PROTOBUF_INLINE_NOT_IN_HEADERS // AllocatorMemoryUsed // optional string allocator_name = 1; inline void AllocatorMemoryUsed::clear_allocator_name() { allocator_name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& AllocatorMemoryUsed::allocator_name() const { // @@protoc_insertion_point(field_get:tensorflow.AllocatorMemoryUsed.allocator_name) return allocator_name_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void AllocatorMemoryUsed::set_allocator_name(const ::std::string& value) { allocator_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:tensorflow.AllocatorMemoryUsed.allocator_name) } inline void AllocatorMemoryUsed::set_allocator_name(const char* value) { allocator_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:tensorflow.AllocatorMemoryUsed.allocator_name) } inline void AllocatorMemoryUsed::set_allocator_name(const char* value, size_t size) { allocator_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:tensorflow.AllocatorMemoryUsed.allocator_name) } inline ::std::string* AllocatorMemoryUsed::mutable_allocator_name() { // @@protoc_insertion_point(field_mutable:tensorflow.AllocatorMemoryUsed.allocator_name) return allocator_name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* AllocatorMemoryUsed::release_allocator_name() { return allocator_name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void AllocatorMemoryUsed::set_allocated_allocator_name(::std::string* allocator_name) { if (allocator_name != NULL) { } else { } allocator_name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), allocator_name); // @@protoc_insertion_point(field_set_allocated:tensorflow.AllocatorMemoryUsed.allocator_name) } // optional int64 total_bytes = 2; inline void AllocatorMemoryUsed::clear_total_bytes() { total_bytes_ = GOOGLE_LONGLONG(0); } inline ::google::protobuf::int64 AllocatorMemoryUsed::total_bytes() const { // @@protoc_insertion_point(field_get:tensorflow.AllocatorMemoryUsed.total_bytes) return total_bytes_; } inline void AllocatorMemoryUsed::set_total_bytes(::google::protobuf::int64 value) { total_bytes_ = value; // @@protoc_insertion_point(field_set:tensorflow.AllocatorMemoryUsed.total_bytes) } // optional int64 peak_bytes = 3; inline void AllocatorMemoryUsed::clear_peak_bytes() { peak_bytes_ = GOOGLE_LONGLONG(0); } inline ::google::protobuf::int64 AllocatorMemoryUsed::peak_bytes() const { // @@protoc_insertion_point(field_get:tensorflow.AllocatorMemoryUsed.peak_bytes) return peak_bytes_; } inline void AllocatorMemoryUsed::set_peak_bytes(::google::protobuf::int64 value) { peak_bytes_ = value; // @@protoc_insertion_point(field_set:tensorflow.AllocatorMemoryUsed.peak_bytes) } // ------------------------------------------------------------------- // NodeOutput // optional int32 slot = 1; inline void NodeOutput::clear_slot() { slot_ = 0; } inline ::google::protobuf::int32 NodeOutput::slot() const { // @@protoc_insertion_point(field_get:tensorflow.NodeOutput.slot) return slot_; } inline void NodeOutput::set_slot(::google::protobuf::int32 value) { slot_ = value; // @@protoc_insertion_point(field_set:tensorflow.NodeOutput.slot) } // optional .tensorflow.TensorDescription tensor_description = 3; inline bool NodeOutput::has_tensor_description() const { return !_is_default_instance_ && tensor_description_ != NULL; } inline void NodeOutput::clear_tensor_description() { if (GetArenaNoVirtual() == NULL && tensor_description_ != NULL) delete tensor_description_; tensor_description_ = NULL; } inline const ::tensorflow::TensorDescription& NodeOutput::tensor_description() const { // @@protoc_insertion_point(field_get:tensorflow.NodeOutput.tensor_description) return tensor_description_ != NULL ? *tensor_description_ : *default_instance_->tensor_description_; } inline ::tensorflow::TensorDescription* NodeOutput::mutable_tensor_description() { if (tensor_description_ == NULL) { tensor_description_ = new ::tensorflow::TensorDescription; } // @@protoc_insertion_point(field_mutable:tensorflow.NodeOutput.tensor_description) return tensor_description_; } inline ::tensorflow::TensorDescription* NodeOutput::release_tensor_description() { ::tensorflow::TensorDescription* temp = tensor_description_; tensor_description_ = NULL; return temp; } inline void NodeOutput::set_allocated_tensor_description(::tensorflow::TensorDescription* tensor_description) { delete tensor_description_; tensor_description_ = tensor_description; if (tensor_description) { } else { } // @@protoc_insertion_point(field_set_allocated:tensorflow.NodeOutput.tensor_description) } // ------------------------------------------------------------------- // NodeExecStats // optional string node_name = 1; inline void NodeExecStats::clear_node_name() { node_name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& NodeExecStats::node_name() const { // @@protoc_insertion_point(field_get:tensorflow.NodeExecStats.node_name) return node_name_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void NodeExecStats::set_node_name(const ::std::string& value) { node_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:tensorflow.NodeExecStats.node_name) } inline void NodeExecStats::set_node_name(const char* value) { node_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:tensorflow.NodeExecStats.node_name) } inline void NodeExecStats::set_node_name(const char* value, size_t size) { node_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:tensorflow.NodeExecStats.node_name) } inline ::std::string* NodeExecStats::mutable_node_name() { // @@protoc_insertion_point(field_mutable:tensorflow.NodeExecStats.node_name) return node_name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* NodeExecStats::release_node_name() { return node_name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void NodeExecStats::set_allocated_node_name(::std::string* node_name) { if (node_name != NULL) { } else { } node_name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), node_name); // @@protoc_insertion_point(field_set_allocated:tensorflow.NodeExecStats.node_name) } // optional int64 all_start_micros = 2; inline void NodeExecStats::clear_all_start_micros() { all_start_micros_ = GOOGLE_LONGLONG(0); } inline ::google::protobuf::int64 NodeExecStats::all_start_micros() const { // @@protoc_insertion_point(field_get:tensorflow.NodeExecStats.all_start_micros) return all_start_micros_; } inline void NodeExecStats::set_all_start_micros(::google::protobuf::int64 value) { all_start_micros_ = value; // @@protoc_insertion_point(field_set:tensorflow.NodeExecStats.all_start_micros) } // optional int64 op_start_rel_micros = 3; inline void NodeExecStats::clear_op_start_rel_micros() { op_start_rel_micros_ = GOOGLE_LONGLONG(0); } inline ::google::protobuf::int64 NodeExecStats::op_start_rel_micros() const { // @@protoc_insertion_point(field_get:tensorflow.NodeExecStats.op_start_rel_micros) return op_start_rel_micros_; } inline void NodeExecStats::set_op_start_rel_micros(::google::protobuf::int64 value) { op_start_rel_micros_ = value; // @@protoc_insertion_point(field_set:tensorflow.NodeExecStats.op_start_rel_micros) } // optional int64 op_end_rel_micros = 4; inline void NodeExecStats::clear_op_end_rel_micros() { op_end_rel_micros_ = GOOGLE_LONGLONG(0); } inline ::google::protobuf::int64 NodeExecStats::op_end_rel_micros() const { // @@protoc_insertion_point(field_get:tensorflow.NodeExecStats.op_end_rel_micros) return op_end_rel_micros_; } inline void NodeExecStats::set_op_end_rel_micros(::google::protobuf::int64 value) { op_end_rel_micros_ = value; // @@protoc_insertion_point(field_set:tensorflow.NodeExecStats.op_end_rel_micros) } // optional int64 all_end_rel_micros = 5; inline void NodeExecStats::clear_all_end_rel_micros() { all_end_rel_micros_ = GOOGLE_LONGLONG(0); } inline ::google::protobuf::int64 NodeExecStats::all_end_rel_micros() const { // @@protoc_insertion_point(field_get:tensorflow.NodeExecStats.all_end_rel_micros) return all_end_rel_micros_; } inline void NodeExecStats::set_all_end_rel_micros(::google::protobuf::int64 value) { all_end_rel_micros_ = value; // @@protoc_insertion_point(field_set:tensorflow.NodeExecStats.all_end_rel_micros) } // repeated .tensorflow.AllocatorMemoryUsed memory = 6; inline int NodeExecStats::memory_size() const { return memory_.size(); } inline void NodeExecStats::clear_memory() { memory_.Clear(); } inline const ::tensorflow::AllocatorMemoryUsed& NodeExecStats::memory(int index) const { // @@protoc_insertion_point(field_get:tensorflow.NodeExecStats.memory) return memory_.Get(index); } inline ::tensorflow::AllocatorMemoryUsed* NodeExecStats::mutable_memory(int index) { // @@protoc_insertion_point(field_mutable:tensorflow.NodeExecStats.memory) return memory_.Mutable(index); } inline ::tensorflow::AllocatorMemoryUsed* NodeExecStats::add_memory() { // @@protoc_insertion_point(field_add:tensorflow.NodeExecStats.memory) return memory_.Add(); } inline ::google::protobuf::RepeatedPtrField< ::tensorflow::AllocatorMemoryUsed >* NodeExecStats::mutable_memory() { // @@protoc_insertion_point(field_mutable_list:tensorflow.NodeExecStats.memory) return &memory_; } inline const ::google::protobuf::RepeatedPtrField< ::tensorflow::AllocatorMemoryUsed >& NodeExecStats::memory() const { // @@protoc_insertion_point(field_list:tensorflow.NodeExecStats.memory) return memory_; } // repeated .tensorflow.NodeOutput output = 7; inline int NodeExecStats::output_size() const { return output_.size(); } inline void NodeExecStats::clear_output() { output_.Clear(); } inline const ::tensorflow::NodeOutput& NodeExecStats::output(int index) const { // @@protoc_insertion_point(field_get:tensorflow.NodeExecStats.output) return output_.Get(index); } inline ::tensorflow::NodeOutput* NodeExecStats::mutable_output(int index) { // @@protoc_insertion_point(field_mutable:tensorflow.NodeExecStats.output) return output_.Mutable(index); } inline ::tensorflow::NodeOutput* NodeExecStats::add_output() { // @@protoc_insertion_point(field_add:tensorflow.NodeExecStats.output) return output_.Add(); } inline ::google::protobuf::RepeatedPtrField< ::tensorflow::NodeOutput >* NodeExecStats::mutable_output() { // @@protoc_insertion_point(field_mutable_list:tensorflow.NodeExecStats.output) return &output_; } inline const ::google::protobuf::RepeatedPtrField< ::tensorflow::NodeOutput >& NodeExecStats::output() const { // @@protoc_insertion_point(field_list:tensorflow.NodeExecStats.output) return output_; } // optional string timeline_label = 8; inline void NodeExecStats::clear_timeline_label() { timeline_label_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& NodeExecStats::timeline_label() const { // @@protoc_insertion_point(field_get:tensorflow.NodeExecStats.timeline_label) return timeline_label_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void NodeExecStats::set_timeline_label(const ::std::string& value) { timeline_label_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:tensorflow.NodeExecStats.timeline_label) } inline void NodeExecStats::set_timeline_label(const char* value) { timeline_label_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:tensorflow.NodeExecStats.timeline_label) } inline void NodeExecStats::set_timeline_label(const char* value, size_t size) { timeline_label_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:tensorflow.NodeExecStats.timeline_label) } inline ::std::string* NodeExecStats::mutable_timeline_label() { // @@protoc_insertion_point(field_mutable:tensorflow.NodeExecStats.timeline_label) return timeline_label_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* NodeExecStats::release_timeline_label() { return timeline_label_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void NodeExecStats::set_allocated_timeline_label(::std::string* timeline_label) { if (timeline_label != NULL) { } else { } timeline_label_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), timeline_label); // @@protoc_insertion_point(field_set_allocated:tensorflow.NodeExecStats.timeline_label) } // optional int64 scheduled_micros = 9; inline void NodeExecStats::clear_scheduled_micros() { scheduled_micros_ = GOOGLE_LONGLONG(0); } inline ::google::protobuf::int64 NodeExecStats::scheduled_micros() const { // @@protoc_insertion_point(field_get:tensorflow.NodeExecStats.scheduled_micros) return scheduled_micros_; } inline void NodeExecStats::set_scheduled_micros(::google::protobuf::int64 value) { scheduled_micros_ = value; // @@protoc_insertion_point(field_set:tensorflow.NodeExecStats.scheduled_micros) } // optional uint32 thread_id = 10; inline void NodeExecStats::clear_thread_id() { thread_id_ = 0u; } inline ::google::protobuf::uint32 NodeExecStats::thread_id() const { // @@protoc_insertion_point(field_get:tensorflow.NodeExecStats.thread_id) return thread_id_; } inline void NodeExecStats::set_thread_id(::google::protobuf::uint32 value) { thread_id_ = value; // @@protoc_insertion_point(field_set:tensorflow.NodeExecStats.thread_id) } // repeated .tensorflow.AllocationDescription referenced_tensor = 11; inline int NodeExecStats::referenced_tensor_size() const { return referenced_tensor_.size(); } inline void NodeExecStats::clear_referenced_tensor() { referenced_tensor_.Clear(); } inline const ::tensorflow::AllocationDescription& NodeExecStats::referenced_tensor(int index) const { // @@protoc_insertion_point(field_get:tensorflow.NodeExecStats.referenced_tensor) return referenced_tensor_.Get(index); } inline ::tensorflow::AllocationDescription* NodeExecStats::mutable_referenced_tensor(int index) { // @@protoc_insertion_point(field_mutable:tensorflow.NodeExecStats.referenced_tensor) return referenced_tensor_.Mutable(index); } inline ::tensorflow::AllocationDescription* NodeExecStats::add_referenced_tensor() { // @@protoc_insertion_point(field_add:tensorflow.NodeExecStats.referenced_tensor) return referenced_tensor_.Add(); } inline ::google::protobuf::RepeatedPtrField< ::tensorflow::AllocationDescription >* NodeExecStats::mutable_referenced_tensor() { // @@protoc_insertion_point(field_mutable_list:tensorflow.NodeExecStats.referenced_tensor) return &referenced_tensor_; } inline const ::google::protobuf::RepeatedPtrField< ::tensorflow::AllocationDescription >& NodeExecStats::referenced_tensor() const { // @@protoc_insertion_point(field_list:tensorflow.NodeExecStats.referenced_tensor) return referenced_tensor_; } // ------------------------------------------------------------------- // DeviceStepStats // optional string device = 1; inline void DeviceStepStats::clear_device() { device_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline const ::std::string& DeviceStepStats::device() const { // @@protoc_insertion_point(field_get:tensorflow.DeviceStepStats.device) return device_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void DeviceStepStats::set_device(const ::std::string& value) { device_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:tensorflow.DeviceStepStats.device) } inline void DeviceStepStats::set_device(const char* value) { device_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:tensorflow.DeviceStepStats.device) } inline void DeviceStepStats::set_device(const char* value, size_t size) { device_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:tensorflow.DeviceStepStats.device) } inline ::std::string* DeviceStepStats::mutable_device() { // @@protoc_insertion_point(field_mutable:tensorflow.DeviceStepStats.device) return device_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* DeviceStepStats::release_device() { return device_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void DeviceStepStats::set_allocated_device(::std::string* device) { if (device != NULL) { } else { } device_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), device); // @@protoc_insertion_point(field_set_allocated:tensorflow.DeviceStepStats.device) } // repeated .tensorflow.NodeExecStats node_stats = 2; inline int DeviceStepStats::node_stats_size() const { return node_stats_.size(); } inline void DeviceStepStats::clear_node_stats() { node_stats_.Clear(); } inline const ::tensorflow::NodeExecStats& DeviceStepStats::node_stats(int index) const { // @@protoc_insertion_point(field_get:tensorflow.DeviceStepStats.node_stats) return node_stats_.Get(index); } inline ::tensorflow::NodeExecStats* DeviceStepStats::mutable_node_stats(int index) { // @@protoc_insertion_point(field_mutable:tensorflow.DeviceStepStats.node_stats) return node_stats_.Mutable(index); } inline ::tensorflow::NodeExecStats* DeviceStepStats::add_node_stats() { // @@protoc_insertion_point(field_add:tensorflow.DeviceStepStats.node_stats) return node_stats_.Add(); } inline ::google::protobuf::RepeatedPtrField< ::tensorflow::NodeExecStats >* DeviceStepStats::mutable_node_stats() { // @@protoc_insertion_point(field_mutable_list:tensorflow.DeviceStepStats.node_stats) return &node_stats_; } inline const ::google::protobuf::RepeatedPtrField< ::tensorflow::NodeExecStats >& DeviceStepStats::node_stats() const { // @@protoc_insertion_point(field_list:tensorflow.DeviceStepStats.node_stats) return node_stats_; } // ------------------------------------------------------------------- // StepStats // repeated .tensorflow.DeviceStepStats dev_stats = 1; inline int StepStats::dev_stats_size() const { return dev_stats_.size(); } inline void StepStats::clear_dev_stats() { dev_stats_.Clear(); } inline const ::tensorflow::DeviceStepStats& StepStats::dev_stats(int index) const { // @@protoc_insertion_point(field_get:tensorflow.StepStats.dev_stats) return dev_stats_.Get(index); } inline ::tensorflow::DeviceStepStats* StepStats::mutable_dev_stats(int index) { // @@protoc_insertion_point(field_mutable:tensorflow.StepStats.dev_stats) return dev_stats_.Mutable(index); } inline ::tensorflow::DeviceStepStats* StepStats::add_dev_stats() { // @@protoc_insertion_point(field_add:tensorflow.StepStats.dev_stats) return dev_stats_.Add(); } inline ::google::protobuf::RepeatedPtrField< ::tensorflow::DeviceStepStats >* StepStats::mutable_dev_stats() { // @@protoc_insertion_point(field_mutable_list:tensorflow.StepStats.dev_stats) return &dev_stats_; } inline const ::google::protobuf::RepeatedPtrField< ::tensorflow::DeviceStepStats >& StepStats::dev_stats() const { // @@protoc_insertion_point(field_list:tensorflow.StepStats.dev_stats) return dev_stats_; } #endif // !PROTOBUF_INLINE_NOT_IN_HEADERS // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // @@protoc_insertion_point(namespace_scope) } // namespace tensorflow // @@protoc_insertion_point(global_scope) #endif // PROTOBUF_tensorflow_2fcore_2fframework_2fstep_5fstats_2eproto__INCLUDED
[ "abdellah.lahnaoui@gmail.com" ]
abdellah.lahnaoui@gmail.com
335ea278a382252b0c08847ba3d6c1e455a418be
29a1989e08f9fc2b7f9bbf663b04a1fc6442735a
/Dynamic Programming/2579.cpp
e176efe7ce9d1f9bfe2f0b1cdb977d16d3c93746
[]
no_license
giantim/algorithm_practice
310a6130dca72a211e1624fea09af69a20a44bda
009132a428c9ed7291078fe2d777e9e95b0bbc49
refs/heads/master
2021-06-17T13:50:31.510429
2021-04-10T01:48:34
2021-04-10T01:48:34
193,831,710
0
0
null
null
null
null
UTF-8
C++
false
false
531
cpp
#include <iostream> using namespace std; int stair[300]; int total[300]; int main() { int T, i; int count = 1; cin >> T; for (i = 0; i < T; i++) cin >> stair[i]; total[0] = stair[0]; total[1] = stair[0] + stair[1]; total[2] = stair[0] > stair[1] ? stair[0] + stair[2] : stair[1] + stair[2]; for (i = 3; i <= T - 1; i++) { if (total[i - 3] + stair[i - 1] > total[i - 2]) total[i] = total[i - 3] + stair[i - 1] + stair[i]; else total[i] = total[i - 2] + stair[i]; } cout << total[T - 1] << endl; return 0; }
[ "giantim132@gmail.com" ]
giantim132@gmail.com
831192606f54d11201fabb246e8a3822acb9f3cf
8daeb0c11937793c99aed8daed6e5794361656d7
/adventofcode/day1/bin/day1.cpp
a0dd0e187a96c2bb58a375076e77cc7f0fc5cd72
[ "MIT" ]
permissive
terotests/Ranger
8c35f4d444070454765c2c8f691af0b09bd8bf19
1ed644d3014cf1c27198701f9539d83447204d64
refs/heads/master
2020-05-22T17:19:01.357080
2018-11-10T14:05:06
2018-11-10T14:05:06
84,709,069
8
0
null
null
null
null
UTF-8
C++
false
false
5,787
cpp
#include <memory> #include "variant.hpp" #include <string> #include <vector> #include <sstream> #include <iterator> #include <functional> #include <iostream> // define classes here to avoid compiler errors class day_one; class operatorsOf; typedef mpark::variant<std::shared_ptr<day_one>, int, std::string, bool, double> r_union_Any; std::vector<std::string> r_str_split(std::string data, std::string token) { std::vector<std::string> output; size_t pos = std::string::npos; if(token.length() == 0) { for(std::string::iterator it = data.begin(); it != data.end(); ++it) { output.push_back( std::string( it, it + 1) ); } return output; } do { pos = data.find(token); output.push_back(data.substr(0, pos)); if (std::string::npos != pos) data = data.substr(pos + token.size()); } while (std::string::npos != pos); return output; } template <class T> class r_optional_primitive { public: bool has_value; T value; r_optional_primitive<T> & operator=(const r_optional_primitive<T> & rhs) { has_value = rhs.has_value; value = rhs.value; return *this; } r_optional_primitive<T> & operator=(const T a_value) { has_value = true; value = a_value; return *this; } }; r_optional_primitive<int> cpp_str_to_int(std::string s) { r_optional_primitive<int> result; try { result.value = std::stoi(s); result.has_value = true; } catch (...) { } return result; } // header definitions class day_one : public std::enable_shared_from_this<day_one> { public : /* class constructor */ day_one( ); /* static methods */ static void main(); }; class operatorsOf : public std::enable_shared_from_this<operatorsOf> { public : /* class constructor */ operatorsOf( ); /* static methods */ static std::vector<int> map_2( std::vector<std::string> __self , std::function<int(std::string, int)> cb ); static int reduce_3( std::vector<int> __self , std::function<int(int, int, int)> cb , int initialValue ); }; int __g_argc; char **__g_argv; day_one::day_one( ) { } int main(int argc, char* argv[]) { __g_argc = argc; __g_argv = argv; std::string data = std::string("428122498997587283996116951397957933569136949848379417125362532269869461185743113733992331379856446362482129646556286611543756564275715359874924898113424472782974789464348626278532936228881786273586278886575828239366794429223317476722337424399239986153675275924113322561873814364451339186918813451685263192891627186769818128715595715444565444581514677521874935942913547121751851631373316122491471564697731298951989511917272684335463436218283261962158671266625299188764589814518793576375629163896349665312991285776595142146261792244475721782941364787968924537841698538288459355159783985638187254653851864874544584878999193242641611859756728634623853475638478923744471563845635468173824196684361934269459459124269196811512927442662761563824323621758785866391424778683599179447845595931928589255935953295111937431266815352781399967295389339626178664148415561175386725992469782888757942558362117938629369129439717427474416851628121191639355646394276451847131182652486561415942815818785884559193483878139351841633366398788657844396925423217662517356486193821341454889283266691224778723833397914224396722559593959125317175899594685524852419495793389481831354787287452367145661829287518771631939314683137722493531318181315216342994141683484111969476952946378314883421677952397588613562958741328987734565492378977396431481215983656814486518865642645612413945129485464979535991675776338786758997128124651311153182816188924935186361813797251997643992686294724699281969473142721116432968216434977684138184481963845141486793996476793954226225885432422654394439882842163295458549755137247614338991879966665925466545111899714943716571113326479432925939227996799951279485722836754457737668191845914566732285928453781818792236447816127492445993945894435692799839217467253986218213131249786833333936332257795191937942688668182629489191693154184177398186462481316834678733713614889439352976144726162214648922159719979143735815478633912633185334529484779322818611438194522292278787653763328944421516569181178517915745625295158611636365253948455727653672922299582352766484"); std::vector<int> values = operatorsOf::map_2((r_str_split( data, std::string(""))), [&](std::string item, int index) mutable { return /*unwrap int*/(cpp_str_to_int(item)).value; }); std::function<int(std::vector<int>, int)> random_ch = [&](std::vector<int> list, int index) mutable { if ( index >= ((int)(list.size())) ) { return list.at(0); } return list.at(index); }; std::cout << std::to_string(operatorsOf::reduce_3(values, [&](int left, int right, int index) mutable { return ((right == random_ch(values, (index + 1))) ? (left + right) : left); }, 0)) << std::endl; return 0; } operatorsOf::operatorsOf( ) { } std::vector<int> operatorsOf::map_2( std::vector<std::string> __self , std::function<int(std::string, int)> cb ) { /** unused: int __len = (int)(__self.size()) **/ ; std::vector<int> res; for ( int i = 0; i != (int)(__self.size()); i++) { std::string it = __self.at(i); res.push_back( cb(it, i) ); } return res; } int operatorsOf::reduce_3( std::vector<int> __self , std::function<int(int, int, int)> cb , int initialValue ) { int len_1 = (int)(__self.size()); int res_1 = initialValue; if ( len_1 >= 1 ) { for ( int i_1 = 0; i_1 != (int)(__self.size()); i_1++) { int it_1 = __self.at(i_1); res_1 = cb(res_1, it_1, i_1); } } return res_1; }
[ "tero@DESKTOP-OVRCN99.localdomain" ]
tero@DESKTOP-OVRCN99.localdomain
a979bdfb738c751e295735a7da056c6d64989831
3b52957226a012ec352f3f73192fd77828ad501c
/LightOJ/1072 - Calm Down.cpp
3a4f916f02c5076e1935742548c446212f6433dd
[]
no_license
jishnusaha/Competetive-Programming
8912aa92962d4c72712de44449f6e9ac8f34fbbf
5535ee9d67a37def87541639f488e328ba579a97
refs/heads/master
2021-06-30T00:18:26.959910
2020-12-21T18:18:37
2020-12-21T18:18:37
204,193,372
0
0
null
null
null
null
UTF-8
C++
false
false
333
cpp
#include<iostream> #include<iomanip> #include<math.h> #define pi 2.0*acos(0.0) using namespace std ; int main () { int t , i ; cin>>t ; for (i=1 ; i<=t ; i++) { double x , n , R ,r ; cin >> R >> n; x=sin(pi / n); r=(x * R) / (1 + x) ; cout << setprecision(10) << "Case " << i << ": " << r <<endl ; } return 0 ; }
[ "jishnusaha89@gmail.com" ]
jishnusaha89@gmail.com
746abf35b90193d7734776a56859e3ec22bc882a
6d7f2381b8f1c5c0e0d96156ae36cac12be3017b
/atcoder/abc069/B/main.cpp
0f47689b157bdd68367bdbb2d5c2bd452c83eed3
[ "Unlicense" ]
permissive
Johniel/contests
708ccf944d6aeb0ef0404eec47e8ff7819ea00f0
15d465b08cac56e394509bcf8f24764e3dc6ca7d
refs/heads/master
2023-09-04T07:32:49.822786
2023-09-02T13:44:28
2023-09-02T13:44:50
48,701,889
0
0
null
2019-10-25T09:21:20
2015-12-28T16:38:38
C++
UTF-8
C++
false
false
1,061
cpp
#include <bits/stdc++.h> #define each(i, c) for (auto& i : c) #define unless(cond) if (!(cond)) using namespace std; typedef long long int lli; typedef unsigned long long ull; typedef complex<double> point; template<typename P, typename Q> ostream& operator << (ostream& os, pair<P, Q> p) { os << "(" << p.first << "," << p.second << ")"; return os; } template<typename P, typename Q> istream& operator >> (istream& is, pair<P, Q>& p) { is >> p.first >> p.second; return is; } template<typename T> ostream& operator << (ostream& os, vector<T> v) { os << "("; each (i, v) os << i << ","; os << ")"; return os; } template<typename T> istream& operator >> (istream& is, vector<T>& v) { each (i, v) is >> i; return is; } template<typename T> inline T setmax(T& a, T b) { return a = std::max(a, b); } template<typename T> inline T setmin(T& a, T b) { return a = std::min(a, b); } int main(int argc, char *argv[]) { ios_base::sync_with_stdio(0); cin.tie(0); string s; cin >> s; cout << s.front() << s.size() - 2 << s.back() << endl; return 0; }
[ "motohazu@mercari.com" ]
motohazu@mercari.com
75d9768fddf982b7f8057f06170831dd2cf689c9
4dbb45758447dcfa13c0be21e4749d62588aab70
/iOS/Classes/Native/UnityEngine_UI_U3CModuleU3E86524790.h
2ab8d1ad4e6ccca06e51e7561f9b5ccaf730fcf1
[ "MIT" ]
permissive
mopsicus/unity-share-plugin-ios-android
6dd6ccd2fa05c73f0bf5e480a6f2baecb7e7a710
3ee99aef36034a1e4d7b156172953f9b4dfa696f
refs/heads/master
2020-12-25T14:38:03.861759
2016-07-19T10:06:04
2016-07-19T10:06:04
63,676,983
12
0
null
null
null
null
UTF-8
C++
false
false
423
h
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // <Module> struct U3CModuleU3E_t86524795 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif
[ "lii@rstgames.com" ]
lii@rstgames.com
f3a90e0b57f26aa7759f9156e09fd0d8a7de70a1
282f567373766261ef56e3b8824b58e107584f94
/OJ/OpenJudge/1.9 编程基础之顺序查找/1.9-03.cpp
19fa6a1257b0a6caf1a3a71057de4ab2ce84efbd
[]
no_license
yhzhm/Practice
27aff56652122d64d7879f15aa41e2550240bb06
9114447ed3346614a7c633f51917069da6aa17f7
refs/heads/master
2022-10-19T01:15:10.517149
2022-09-29T09:04:38
2022-09-29T09:04:38
121,328,943
0
0
null
null
null
null
UTF-8
C++
false
false
243
cpp
#include<bits/stdc++.h> using namespace std; int main() { int max = 0, n1, n2, d = 0; for (int i = 1; i <= 7; ++i) { cin >> n1 >> n2; if (n1 + n2 > 8 && max < n1 + n2) { max = n1 + n2; d = i; } } cout << d << endl; return 0; }
[ "yhzhm@qq.com" ]
yhzhm@qq.com
502089f4ff2b370a347b2fa248e3346ecbbd5aa5
8085f16eaf5133bebb45aeeabb9b172ae3db4176
/hiho1078/hiho1078/main.cpp
fff020082cf41d5016a4a01378dedf28b34d353e
[]
no_license
EyciaZhou/acm
ff0dd40971424f338369eca8507e8c339497f946
50121929dc658be717b8fa6076ec28dea915ce97
refs/heads/master
2020-05-01T08:57:48.118961
2015-06-09T06:48:53
2015-06-09T06:48:53
35,026,832
0
0
null
null
null
null
UTF-8
C++
false
false
265
cpp
// // main.cpp // hiho1078 // // Created by eycia on 12/5/15. // Copyright (c) 2015年 eycia. All rights reserved. // #include <iostream> int main(int argc, const char * argv[]) { // insert code here... std::cout << "Hello, World!\n"; return 0; }
[ "zhou.eycia@gmail.com" ]
zhou.eycia@gmail.com
6ecbe3ff54af3362fcaa325fe007634a00a91a99
d75f121aa96edbfcfd4cdb09ec09a9affdf0c625
/11th Assignment/Sungjuk.cpp
994bcb91abb1db4df1127e1cde996233fb3f4b63
[]
no_license
XIOZ119/Object_oriented_programming
cc9047dc17e15584318ef9be170af664d2991003
c329e14c5585b5c78b198507eeaa710ca0895560
refs/heads/master
2023-06-03T00:03:00.628945
2021-06-23T08:25:01
2021-06-23T08:25:01
379,532,818
0
0
null
null
null
null
UHC
C++
false
false
984
cpp
#include "Student.h" #include <algorithm> #include <iostream> using namespace std; inline void InputValue(int& ref) { cin >> ref; } inline void InputValue(string& ref) { getline(cin, ref); if (ref.empty()) getline(cin, ref); } inline void PrintMenu() { cout << "=========메뉴=========" << endl; cout << "1. 학생 정보 입력" << endl; cout << "2. 학생 정보 보기" << endl; cout << "3. 학생 정보 삭제" << endl; cout << "4. 프로그램 종료" << endl << endl; cout << "원하는 기능을 입력하세요 : "; } int main() { int select_menu = 0; Students St; while (true) { PrintMenu(); InputValue(select_menu); cout << "\n"; if (select_menu == 1) { St.InputData(St); } else if (select_menu == 2) { cout.width(25); cout << "학생 정보 보기\n"; St.PrintData(St); } else if (select_menu == 3) { St.DeleteData(St); } else if (select_menu == 4) { cout << "-------------------------"; break; } } }
[ "tjwns53@naver.com" ]
tjwns53@naver.com
4fd3e3872fd51e7f2740b52d0c599a7d8c1ba1a9
5a68ff9e58ebdc209e3b462f45d3e885bcfa48fd
/Submarine/test.cpp
6d99ed676a77864d48ca2370afbe9fe76b6af41e
[]
no_license
MishaLivshitz/submarines
cc43b1df12627d98108b7bf3c034186df68de621
b5beadd960b9edecae1f2b29ea7bc42676a02ef4
refs/heads/master
2020-07-31T13:41:12.756969
2019-10-07T07:17:29
2019-10-07T07:17:29
164,846,170
0
0
null
null
null
null
UTF-8
C++
false
false
321
cpp
#include "mu_test.h" #include "Submarine.h" UNIT(submarine_test) const size_t size = 5; Submarine s(size); while (!s.isDead()) { ASSERT_THAT(!s.isDead()); s.setHit(); } ASSERT_THAT(s.isDead()); END_UNIT TEST_SUITE(Test of submarine unit) TEST(submarine_test) END_SUITE
[ "michaellivshitz91@gmail.com" ]
michaellivshitz91@gmail.com
dd83a2311e6c80dbe7ab37f038691a9783146f84
c287f063100e0ddb29bcf27e9f901b914cca0f2e
/thirdparty/v8/src/src/spaces.cc
6c03daa75aea0d862a72908807cf1e24e96c57c6
[ "bzip2-1.0.6", "BSD-3-Clause", "MIT" ]
permissive
imzcy/JavaScriptExecutable
803c55db0adce8b32fcbe0db81531d248a9420d0
723a13f433aafad84faa609f62955ce826063c66
refs/heads/master
2022-11-05T01:37:49.036607
2016-10-26T17:13:10
2016-10-26T17:13:10
20,448,619
3
1
MIT
2022-10-24T23:26:37
2014-06-03T15:37:09
C++
UTF-8
C++
false
false
104,014
cc
// Copyright 2011 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "v8.h" #include "macro-assembler.h" #include "mark-compact.h" #include "msan.h" #include "platform.h" namespace v8 { namespace internal { // ---------------------------------------------------------------------------- // HeapObjectIterator HeapObjectIterator::HeapObjectIterator(PagedSpace* space) { // You can't actually iterate over the anchor page. It is not a real page, // just an anchor for the double linked page list. Initialize as if we have // reached the end of the anchor page, then the first iteration will move on // to the first page. Initialize(space, NULL, NULL, kAllPagesInSpace, NULL); } HeapObjectIterator::HeapObjectIterator(PagedSpace* space, HeapObjectCallback size_func) { // You can't actually iterate over the anchor page. It is not a real page, // just an anchor for the double linked page list. Initialize the current // address and end as NULL, then the first iteration will move on // to the first page. Initialize(space, NULL, NULL, kAllPagesInSpace, size_func); } HeapObjectIterator::HeapObjectIterator(Page* page, HeapObjectCallback size_func) { Space* owner = page->owner(); ASSERT(owner == page->heap()->old_pointer_space() || owner == page->heap()->old_data_space() || owner == page->heap()->map_space() || owner == page->heap()->cell_space() || owner == page->heap()->property_cell_space() || owner == page->heap()->code_space()); Initialize(reinterpret_cast<PagedSpace*>(owner), page->area_start(), page->area_end(), kOnePageOnly, size_func); ASSERT(page->WasSweptPrecisely()); } void HeapObjectIterator::Initialize(PagedSpace* space, Address cur, Address end, HeapObjectIterator::PageMode mode, HeapObjectCallback size_f) { // Check that we actually can iterate this space. ASSERT(!space->was_swept_conservatively()); space_ = space; cur_addr_ = cur; cur_end_ = end; page_mode_ = mode; size_func_ = size_f; } // We have hit the end of the page and should advance to the next block of // objects. This happens at the end of the page. bool HeapObjectIterator::AdvanceToNextPage() { ASSERT(cur_addr_ == cur_end_); if (page_mode_ == kOnePageOnly) return false; Page* cur_page; if (cur_addr_ == NULL) { cur_page = space_->anchor(); } else { cur_page = Page::FromAddress(cur_addr_ - 1); ASSERT(cur_addr_ == cur_page->area_end()); } cur_page = cur_page->next_page(); if (cur_page == space_->anchor()) return false; cur_addr_ = cur_page->area_start(); cur_end_ = cur_page->area_end(); ASSERT(cur_page->WasSweptPrecisely()); return true; } // ----------------------------------------------------------------------------- // CodeRange CodeRange::CodeRange(Isolate* isolate) : isolate_(isolate), code_range_(NULL), free_list_(0), allocation_list_(0), current_allocation_block_index_(0) { } bool CodeRange::SetUp(const size_t requested) { ASSERT(code_range_ == NULL); code_range_ = new VirtualMemory(requested); CHECK(code_range_ != NULL); if (!code_range_->IsReserved()) { delete code_range_; code_range_ = NULL; return false; } // We are sure that we have mapped a block of requested addresses. ASSERT(code_range_->size() == requested); LOG(isolate_, NewEvent("CodeRange", code_range_->address(), requested)); Address base = reinterpret_cast<Address>(code_range_->address()); Address aligned_base = RoundUp(reinterpret_cast<Address>(code_range_->address()), MemoryChunk::kAlignment); size_t size = code_range_->size() - (aligned_base - base); allocation_list_.Add(FreeBlock(aligned_base, size)); current_allocation_block_index_ = 0; return true; } int CodeRange::CompareFreeBlockAddress(const FreeBlock* left, const FreeBlock* right) { // The entire point of CodeRange is that the difference between two // addresses in the range can be represented as a signed 32-bit int, // so the cast is semantically correct. return static_cast<int>(left->start - right->start); } void CodeRange::GetNextAllocationBlock(size_t requested) { for (current_allocation_block_index_++; current_allocation_block_index_ < allocation_list_.length(); current_allocation_block_index_++) { if (requested <= allocation_list_[current_allocation_block_index_].size) { return; // Found a large enough allocation block. } } // Sort and merge the free blocks on the free list and the allocation list. free_list_.AddAll(allocation_list_); allocation_list_.Clear(); free_list_.Sort(&CompareFreeBlockAddress); for (int i = 0; i < free_list_.length();) { FreeBlock merged = free_list_[i]; i++; // Add adjacent free blocks to the current merged block. while (i < free_list_.length() && free_list_[i].start == merged.start + merged.size) { merged.size += free_list_[i].size; i++; } if (merged.size > 0) { allocation_list_.Add(merged); } } free_list_.Clear(); for (current_allocation_block_index_ = 0; current_allocation_block_index_ < allocation_list_.length(); current_allocation_block_index_++) { if (requested <= allocation_list_[current_allocation_block_index_].size) { return; // Found a large enough allocation block. } } // Code range is full or too fragmented. V8::FatalProcessOutOfMemory("CodeRange::GetNextAllocationBlock"); } Address CodeRange::AllocateRawMemory(const size_t requested_size, const size_t commit_size, size_t* allocated) { ASSERT(commit_size <= requested_size); ASSERT(current_allocation_block_index_ < allocation_list_.length()); if (requested_size > allocation_list_[current_allocation_block_index_].size) { // Find an allocation block large enough. This function call may // call V8::FatalProcessOutOfMemory if it cannot find a large enough block. GetNextAllocationBlock(requested_size); } // Commit the requested memory at the start of the current allocation block. size_t aligned_requested = RoundUp(requested_size, MemoryChunk::kAlignment); FreeBlock current = allocation_list_[current_allocation_block_index_]; if (aligned_requested >= (current.size - Page::kPageSize)) { // Don't leave a small free block, useless for a large object or chunk. *allocated = current.size; } else { *allocated = aligned_requested; } ASSERT(*allocated <= current.size); ASSERT(IsAddressAligned(current.start, MemoryChunk::kAlignment)); if (!isolate_->memory_allocator()->CommitExecutableMemory(code_range_, current.start, commit_size, *allocated)) { *allocated = 0; return NULL; } allocation_list_[current_allocation_block_index_].start += *allocated; allocation_list_[current_allocation_block_index_].size -= *allocated; if (*allocated == current.size) { GetNextAllocationBlock(0); // This block is used up, get the next one. } return current.start; } bool CodeRange::CommitRawMemory(Address start, size_t length) { return isolate_->memory_allocator()->CommitMemory(start, length, EXECUTABLE); } bool CodeRange::UncommitRawMemory(Address start, size_t length) { return code_range_->Uncommit(start, length); } void CodeRange::FreeRawMemory(Address address, size_t length) { ASSERT(IsAddressAligned(address, MemoryChunk::kAlignment)); free_list_.Add(FreeBlock(address, length)); code_range_->Uncommit(address, length); } void CodeRange::TearDown() { delete code_range_; // Frees all memory in the virtual memory range. code_range_ = NULL; free_list_.Free(); allocation_list_.Free(); } // ----------------------------------------------------------------------------- // MemoryAllocator // MemoryAllocator::MemoryAllocator(Isolate* isolate) : isolate_(isolate), capacity_(0), capacity_executable_(0), size_(0), size_executable_(0), lowest_ever_allocated_(reinterpret_cast<void*>(-1)), highest_ever_allocated_(reinterpret_cast<void*>(0)) { } bool MemoryAllocator::SetUp(intptr_t capacity, intptr_t capacity_executable) { capacity_ = RoundUp(capacity, Page::kPageSize); capacity_executable_ = RoundUp(capacity_executable, Page::kPageSize); ASSERT_GE(capacity_, capacity_executable_); size_ = 0; size_executable_ = 0; return true; } void MemoryAllocator::TearDown() { // Check that spaces were torn down before MemoryAllocator. ASSERT(size_ == 0); // TODO(gc) this will be true again when we fix FreeMemory. // ASSERT(size_executable_ == 0); capacity_ = 0; capacity_executable_ = 0; } bool MemoryAllocator::CommitMemory(Address base, size_t size, Executability executable) { if (!VirtualMemory::CommitRegion(base, size, executable == EXECUTABLE)) { return false; } UpdateAllocatedSpaceLimits(base, base + size); return true; } void MemoryAllocator::FreeMemory(VirtualMemory* reservation, Executability executable) { // TODO(gc) make code_range part of memory allocator? ASSERT(reservation->IsReserved()); size_t size = reservation->size(); ASSERT(size_ >= size); size_ -= size; isolate_->counters()->memory_allocated()->Decrement(static_cast<int>(size)); if (executable == EXECUTABLE) { ASSERT(size_executable_ >= size); size_executable_ -= size; } // Code which is part of the code-range does not have its own VirtualMemory. ASSERT(!isolate_->code_range()->contains( static_cast<Address>(reservation->address()))); ASSERT(executable == NOT_EXECUTABLE || !isolate_->code_range()->exists()); reservation->Release(); } void MemoryAllocator::FreeMemory(Address base, size_t size, Executability executable) { // TODO(gc) make code_range part of memory allocator? ASSERT(size_ >= size); size_ -= size; isolate_->counters()->memory_allocated()->Decrement(static_cast<int>(size)); if (executable == EXECUTABLE) { ASSERT(size_executable_ >= size); size_executable_ -= size; } if (isolate_->code_range()->contains(static_cast<Address>(base))) { ASSERT(executable == EXECUTABLE); isolate_->code_range()->FreeRawMemory(base, size); } else { ASSERT(executable == NOT_EXECUTABLE || !isolate_->code_range()->exists()); bool result = VirtualMemory::ReleaseRegion(base, size); USE(result); ASSERT(result); } } Address MemoryAllocator::ReserveAlignedMemory(size_t size, size_t alignment, VirtualMemory* controller) { VirtualMemory reservation(size, alignment); if (!reservation.IsReserved()) return NULL; size_ += reservation.size(); Address base = RoundUp(static_cast<Address>(reservation.address()), alignment); controller->TakeControl(&reservation); return base; } Address MemoryAllocator::AllocateAlignedMemory(size_t reserve_size, size_t commit_size, size_t alignment, Executability executable, VirtualMemory* controller) { ASSERT(commit_size <= reserve_size); VirtualMemory reservation; Address base = ReserveAlignedMemory(reserve_size, alignment, &reservation); if (base == NULL) return NULL; if (executable == EXECUTABLE) { if (!CommitExecutableMemory(&reservation, base, commit_size, reserve_size)) { base = NULL; } } else { if (reservation.Commit(base, commit_size, false)) { UpdateAllocatedSpaceLimits(base, base + commit_size); } else { base = NULL; } } if (base == NULL) { // Failed to commit the body. Release the mapping and any partially // commited regions inside it. reservation.Release(); return NULL; } controller->TakeControl(&reservation); return base; } void Page::InitializeAsAnchor(PagedSpace* owner) { set_owner(owner); set_prev_page(this); set_next_page(this); } NewSpacePage* NewSpacePage::Initialize(Heap* heap, Address start, SemiSpace* semi_space) { Address area_start = start + NewSpacePage::kObjectStartOffset; Address area_end = start + Page::kPageSize; MemoryChunk* chunk = MemoryChunk::Initialize(heap, start, Page::kPageSize, area_start, area_end, NOT_EXECUTABLE, semi_space); chunk->set_next_chunk(NULL); chunk->set_prev_chunk(NULL); chunk->initialize_scan_on_scavenge(true); bool in_to_space = (semi_space->id() != kFromSpace); chunk->SetFlag(in_to_space ? MemoryChunk::IN_TO_SPACE : MemoryChunk::IN_FROM_SPACE); ASSERT(!chunk->IsFlagSet(in_to_space ? MemoryChunk::IN_FROM_SPACE : MemoryChunk::IN_TO_SPACE)); NewSpacePage* page = static_cast<NewSpacePage*>(chunk); heap->incremental_marking()->SetNewSpacePageFlags(page); return page; } void NewSpacePage::InitializeAsAnchor(SemiSpace* semi_space) { set_owner(semi_space); set_next_chunk(this); set_prev_chunk(this); // Flags marks this invalid page as not being in new-space. // All real new-space pages will be in new-space. SetFlags(0, ~0); } MemoryChunk* MemoryChunk::Initialize(Heap* heap, Address base, size_t size, Address area_start, Address area_end, Executability executable, Space* owner) { MemoryChunk* chunk = FromAddress(base); ASSERT(base == chunk->address()); chunk->heap_ = heap; chunk->size_ = size; chunk->area_start_ = area_start; chunk->area_end_ = area_end; chunk->flags_ = 0; chunk->set_owner(owner); chunk->InitializeReservedMemory(); chunk->slots_buffer_ = NULL; chunk->skip_list_ = NULL; chunk->write_barrier_counter_ = kWriteBarrierCounterGranularity; chunk->progress_bar_ = 0; chunk->high_water_mark_ = static_cast<int>(area_start - base); chunk->set_parallel_sweeping(PARALLEL_SWEEPING_DONE); chunk->available_in_small_free_list_ = 0; chunk->available_in_medium_free_list_ = 0; chunk->available_in_large_free_list_ = 0; chunk->available_in_huge_free_list_ = 0; chunk->non_available_small_blocks_ = 0; chunk->ResetLiveBytes(); Bitmap::Clear(chunk); chunk->initialize_scan_on_scavenge(false); chunk->SetFlag(WAS_SWEPT_PRECISELY); ASSERT(OFFSET_OF(MemoryChunk, flags_) == kFlagsOffset); ASSERT(OFFSET_OF(MemoryChunk, live_byte_count_) == kLiveBytesOffset); if (executable == EXECUTABLE) { chunk->SetFlag(IS_EXECUTABLE); } if (owner == heap->old_data_space()) { chunk->SetFlag(CONTAINS_ONLY_DATA); } return chunk; } // Commit MemoryChunk area to the requested size. bool MemoryChunk::CommitArea(size_t requested) { size_t guard_size = IsFlagSet(IS_EXECUTABLE) ? MemoryAllocator::CodePageGuardSize() : 0; size_t header_size = area_start() - address() - guard_size; size_t commit_size = RoundUp(header_size + requested, OS::CommitPageSize()); size_t committed_size = RoundUp(header_size + (area_end() - area_start()), OS::CommitPageSize()); if (commit_size > committed_size) { // Commit size should be less or equal than the reserved size. ASSERT(commit_size <= size() - 2 * guard_size); // Append the committed area. Address start = address() + committed_size + guard_size; size_t length = commit_size - committed_size; if (reservation_.IsReserved()) { Executability executable = IsFlagSet(IS_EXECUTABLE) ? EXECUTABLE : NOT_EXECUTABLE; if (!heap()->isolate()->memory_allocator()->CommitMemory( start, length, executable)) { return false; } } else { CodeRange* code_range = heap_->isolate()->code_range(); ASSERT(code_range->exists() && IsFlagSet(IS_EXECUTABLE)); if (!code_range->CommitRawMemory(start, length)) return false; } if (Heap::ShouldZapGarbage()) { heap_->isolate()->memory_allocator()->ZapBlock(start, length); } } else if (commit_size < committed_size) { ASSERT(commit_size > 0); // Shrink the committed area. size_t length = committed_size - commit_size; Address start = address() + committed_size + guard_size - length; if (reservation_.IsReserved()) { if (!reservation_.Uncommit(start, length)) return false; } else { CodeRange* code_range = heap_->isolate()->code_range(); ASSERT(code_range->exists() && IsFlagSet(IS_EXECUTABLE)); if (!code_range->UncommitRawMemory(start, length)) return false; } } area_end_ = area_start_ + requested; return true; } void MemoryChunk::InsertAfter(MemoryChunk* other) { MemoryChunk* other_next = other->next_chunk(); set_next_chunk(other_next); set_prev_chunk(other); other_next->set_prev_chunk(this); other->set_next_chunk(this); } void MemoryChunk::Unlink() { if (!InNewSpace() && IsFlagSet(SCAN_ON_SCAVENGE)) { heap_->decrement_scan_on_scavenge_pages(); ClearFlag(SCAN_ON_SCAVENGE); } MemoryChunk* next_element = next_chunk(); MemoryChunk* prev_element = prev_chunk(); next_element->set_prev_chunk(prev_element); prev_element->set_next_chunk(next_element); set_prev_chunk(NULL); set_next_chunk(NULL); } MemoryChunk* MemoryAllocator::AllocateChunk(intptr_t reserve_area_size, intptr_t commit_area_size, Executability executable, Space* owner) { ASSERT(commit_area_size <= reserve_area_size); size_t chunk_size; Heap* heap = isolate_->heap(); Address base = NULL; VirtualMemory reservation; Address area_start = NULL; Address area_end = NULL; // // MemoryChunk layout: // // Executable // +----------------------------+<- base aligned with MemoryChunk::kAlignment // | Header | // +----------------------------+<- base + CodePageGuardStartOffset // | Guard | // +----------------------------+<- area_start_ // | Area | // +----------------------------+<- area_end_ (area_start + commit_area_size) // | Committed but not used | // +----------------------------+<- aligned at OS page boundary // | Reserved but not committed | // +----------------------------+<- aligned at OS page boundary // | Guard | // +----------------------------+<- base + chunk_size // // Non-executable // +----------------------------+<- base aligned with MemoryChunk::kAlignment // | Header | // +----------------------------+<- area_start_ (base + kObjectStartOffset) // | Area | // +----------------------------+<- area_end_ (area_start + commit_area_size) // | Committed but not used | // +----------------------------+<- aligned at OS page boundary // | Reserved but not committed | // +----------------------------+<- base + chunk_size // if (executable == EXECUTABLE) { chunk_size = RoundUp(CodePageAreaStartOffset() + reserve_area_size, OS::CommitPageSize()) + CodePageGuardSize(); // Check executable memory limit. if (size_executable_ + chunk_size > capacity_executable_) { LOG(isolate_, StringEvent("MemoryAllocator::AllocateRawMemory", "V8 Executable Allocation capacity exceeded")); return NULL; } // Size of header (not executable) plus area (executable). size_t commit_size = RoundUp(CodePageGuardStartOffset() + commit_area_size, OS::CommitPageSize()); // Allocate executable memory either from code range or from the // OS. if (isolate_->code_range()->exists()) { base = isolate_->code_range()->AllocateRawMemory(chunk_size, commit_size, &chunk_size); ASSERT(IsAligned(reinterpret_cast<intptr_t>(base), MemoryChunk::kAlignment)); if (base == NULL) return NULL; size_ += chunk_size; // Update executable memory size. size_executable_ += chunk_size; } else { base = AllocateAlignedMemory(chunk_size, commit_size, MemoryChunk::kAlignment, executable, &reservation); if (base == NULL) return NULL; // Update executable memory size. size_executable_ += reservation.size(); } if (Heap::ShouldZapGarbage()) { ZapBlock(base, CodePageGuardStartOffset()); ZapBlock(base + CodePageAreaStartOffset(), commit_area_size); } area_start = base + CodePageAreaStartOffset(); area_end = area_start + commit_area_size; } else { chunk_size = RoundUp(MemoryChunk::kObjectStartOffset + reserve_area_size, OS::CommitPageSize()); size_t commit_size = RoundUp(MemoryChunk::kObjectStartOffset + commit_area_size, OS::CommitPageSize()); base = AllocateAlignedMemory(chunk_size, commit_size, MemoryChunk::kAlignment, executable, &reservation); if (base == NULL) return NULL; if (Heap::ShouldZapGarbage()) { ZapBlock(base, Page::kObjectStartOffset + commit_area_size); } area_start = base + Page::kObjectStartOffset; area_end = area_start + commit_area_size; } // Use chunk_size for statistics and callbacks because we assume that they // treat reserved but not-yet committed memory regions of chunks as allocated. isolate_->counters()->memory_allocated()-> Increment(static_cast<int>(chunk_size)); LOG(isolate_, NewEvent("MemoryChunk", base, chunk_size)); if (owner != NULL) { ObjectSpace space = static_cast<ObjectSpace>(1 << owner->identity()); PerformAllocationCallback(space, kAllocationActionAllocate, chunk_size); } MemoryChunk* result = MemoryChunk::Initialize(heap, base, chunk_size, area_start, area_end, executable, owner); result->set_reserved_memory(&reservation); MSAN_MEMORY_IS_INITIALIZED(base, chunk_size); return result; } void Page::ResetFreeListStatistics() { non_available_small_blocks_ = 0; available_in_small_free_list_ = 0; available_in_medium_free_list_ = 0; available_in_large_free_list_ = 0; available_in_huge_free_list_ = 0; } Page* MemoryAllocator::AllocatePage(intptr_t size, PagedSpace* owner, Executability executable) { MemoryChunk* chunk = AllocateChunk(size, size, executable, owner); if (chunk == NULL) return NULL; return Page::Initialize(isolate_->heap(), chunk, executable, owner); } LargePage* MemoryAllocator::AllocateLargePage(intptr_t object_size, Space* owner, Executability executable) { MemoryChunk* chunk = AllocateChunk(object_size, object_size, executable, owner); if (chunk == NULL) return NULL; return LargePage::Initialize(isolate_->heap(), chunk); } void MemoryAllocator::Free(MemoryChunk* chunk) { LOG(isolate_, DeleteEvent("MemoryChunk", chunk)); if (chunk->owner() != NULL) { ObjectSpace space = static_cast<ObjectSpace>(1 << chunk->owner()->identity()); PerformAllocationCallback(space, kAllocationActionFree, chunk->size()); } isolate_->heap()->RememberUnmappedPage( reinterpret_cast<Address>(chunk), chunk->IsEvacuationCandidate()); delete chunk->slots_buffer(); delete chunk->skip_list(); VirtualMemory* reservation = chunk->reserved_memory(); if (reservation->IsReserved()) { FreeMemory(reservation, chunk->executable()); } else { FreeMemory(chunk->address(), chunk->size(), chunk->executable()); } } bool MemoryAllocator::CommitBlock(Address start, size_t size, Executability executable) { if (!CommitMemory(start, size, executable)) return false; if (Heap::ShouldZapGarbage()) { ZapBlock(start, size); } isolate_->counters()->memory_allocated()->Increment(static_cast<int>(size)); return true; } bool MemoryAllocator::UncommitBlock(Address start, size_t size) { if (!VirtualMemory::UncommitRegion(start, size)) return false; isolate_->counters()->memory_allocated()->Decrement(static_cast<int>(size)); return true; } void MemoryAllocator::ZapBlock(Address start, size_t size) { for (size_t s = 0; s + kPointerSize <= size; s += kPointerSize) { Memory::Address_at(start + s) = kZapValue; } } void MemoryAllocator::PerformAllocationCallback(ObjectSpace space, AllocationAction action, size_t size) { for (int i = 0; i < memory_allocation_callbacks_.length(); ++i) { MemoryAllocationCallbackRegistration registration = memory_allocation_callbacks_[i]; if ((registration.space & space) == space && (registration.action & action) == action) registration.callback(space, action, static_cast<int>(size)); } } bool MemoryAllocator::MemoryAllocationCallbackRegistered( MemoryAllocationCallback callback) { for (int i = 0; i < memory_allocation_callbacks_.length(); ++i) { if (memory_allocation_callbacks_[i].callback == callback) return true; } return false; } void MemoryAllocator::AddMemoryAllocationCallback( MemoryAllocationCallback callback, ObjectSpace space, AllocationAction action) { ASSERT(callback != NULL); MemoryAllocationCallbackRegistration registration(callback, space, action); ASSERT(!MemoryAllocator::MemoryAllocationCallbackRegistered(callback)); return memory_allocation_callbacks_.Add(registration); } void MemoryAllocator::RemoveMemoryAllocationCallback( MemoryAllocationCallback callback) { ASSERT(callback != NULL); for (int i = 0; i < memory_allocation_callbacks_.length(); ++i) { if (memory_allocation_callbacks_[i].callback == callback) { memory_allocation_callbacks_.Remove(i); return; } } UNREACHABLE(); } #ifdef DEBUG void MemoryAllocator::ReportStatistics() { float pct = static_cast<float>(capacity_ - size_) / capacity_; PrintF(" capacity: %" V8_PTR_PREFIX "d" ", used: %" V8_PTR_PREFIX "d" ", available: %%%d\n\n", capacity_, size_, static_cast<int>(pct*100)); } #endif int MemoryAllocator::CodePageGuardStartOffset() { // We are guarding code pages: the first OS page after the header // will be protected as non-writable. return RoundUp(Page::kObjectStartOffset, OS::CommitPageSize()); } int MemoryAllocator::CodePageGuardSize() { return static_cast<int>(OS::CommitPageSize()); } int MemoryAllocator::CodePageAreaStartOffset() { // We are guarding code pages: the first OS page after the header // will be protected as non-writable. return CodePageGuardStartOffset() + CodePageGuardSize(); } int MemoryAllocator::CodePageAreaEndOffset() { // We are guarding code pages: the last OS page will be protected as // non-writable. return Page::kPageSize - static_cast<int>(OS::CommitPageSize()); } bool MemoryAllocator::CommitExecutableMemory(VirtualMemory* vm, Address start, size_t commit_size, size_t reserved_size) { // Commit page header (not executable). if (!vm->Commit(start, CodePageGuardStartOffset(), false)) { return false; } // Create guard page after the header. if (!vm->Guard(start + CodePageGuardStartOffset())) { return false; } // Commit page body (executable). if (!vm->Commit(start + CodePageAreaStartOffset(), commit_size - CodePageGuardStartOffset(), true)) { return false; } // Create guard page before the end. if (!vm->Guard(start + reserved_size - CodePageGuardSize())) { return false; } UpdateAllocatedSpaceLimits(start, start + CodePageAreaStartOffset() + commit_size - CodePageGuardStartOffset()); return true; } // ----------------------------------------------------------------------------- // MemoryChunk implementation void MemoryChunk::IncrementLiveBytesFromMutator(Address address, int by) { MemoryChunk* chunk = MemoryChunk::FromAddress(address); if (!chunk->InNewSpace() && !static_cast<Page*>(chunk)->WasSwept()) { static_cast<PagedSpace*>(chunk->owner())->IncrementUnsweptFreeBytes(-by); } chunk->IncrementLiveBytes(by); } // ----------------------------------------------------------------------------- // PagedSpace implementation PagedSpace::PagedSpace(Heap* heap, intptr_t max_capacity, AllocationSpace id, Executability executable) : Space(heap, id, executable), free_list_(this), was_swept_conservatively_(false), first_unswept_page_(Page::FromAddress(NULL)), unswept_free_bytes_(0) { if (id == CODE_SPACE) { area_size_ = heap->isolate()->memory_allocator()-> CodePageAreaSize(); } else { area_size_ = Page::kPageSize - Page::kObjectStartOffset; } max_capacity_ = (RoundDown(max_capacity, Page::kPageSize) / Page::kPageSize) * AreaSize(); accounting_stats_.Clear(); allocation_info_.set_top(NULL); allocation_info_.set_limit(NULL); anchor_.InitializeAsAnchor(this); } bool PagedSpace::SetUp() { return true; } bool PagedSpace::HasBeenSetUp() { return true; } void PagedSpace::TearDown() { PageIterator iterator(this); while (iterator.has_next()) { heap()->isolate()->memory_allocator()->Free(iterator.next()); } anchor_.set_next_page(&anchor_); anchor_.set_prev_page(&anchor_); accounting_stats_.Clear(); } size_t PagedSpace::CommittedPhysicalMemory() { if (!VirtualMemory::HasLazyCommits()) return CommittedMemory(); MemoryChunk::UpdateHighWaterMark(allocation_info_.top()); size_t size = 0; PageIterator it(this); while (it.has_next()) { size += it.next()->CommittedPhysicalMemory(); } return size; } MaybeObject* PagedSpace::FindObject(Address addr) { // Note: this function can only be called on precisely swept spaces. ASSERT(!heap()->mark_compact_collector()->in_use()); if (!Contains(addr)) return Failure::Exception(); Page* p = Page::FromAddress(addr); HeapObjectIterator it(p, NULL); for (HeapObject* obj = it.Next(); obj != NULL; obj = it.Next()) { Address cur = obj->address(); Address next = cur + obj->Size(); if ((cur <= addr) && (addr < next)) return obj; } UNREACHABLE(); return Failure::Exception(); } bool PagedSpace::CanExpand() { ASSERT(max_capacity_ % AreaSize() == 0); if (Capacity() == max_capacity_) return false; ASSERT(Capacity() < max_capacity_); // Are we going to exceed capacity for this space? if ((Capacity() + Page::kPageSize) > max_capacity_) return false; return true; } bool PagedSpace::Expand() { if (!CanExpand()) return false; intptr_t size = AreaSize(); if (anchor_.next_page() == &anchor_) { size = SizeOfFirstPage(); } Page* p = heap()->isolate()->memory_allocator()->AllocatePage( size, this, executable()); if (p == NULL) return false; ASSERT(Capacity() <= max_capacity_); p->InsertAfter(anchor_.prev_page()); return true; } intptr_t PagedSpace::SizeOfFirstPage() { int size = 0; switch (identity()) { case OLD_POINTER_SPACE: size = 72 * kPointerSize * KB; break; case OLD_DATA_SPACE: size = 192 * KB; break; case MAP_SPACE: size = 16 * kPointerSize * KB; break; case CELL_SPACE: size = 16 * kPointerSize * KB; break; case PROPERTY_CELL_SPACE: size = 8 * kPointerSize * KB; break; case CODE_SPACE: if (heap()->isolate()->code_range()->exists()) { // When code range exists, code pages are allocated in a special way // (from the reserved code range). That part of the code is not yet // upgraded to handle small pages. size = AreaSize(); } else { size = 480 * KB; } break; default: UNREACHABLE(); } return Min(size, AreaSize()); } int PagedSpace::CountTotalPages() { PageIterator it(this); int count = 0; while (it.has_next()) { it.next(); count++; } return count; } void PagedSpace::ObtainFreeListStatistics(Page* page, SizeStats* sizes) { sizes->huge_size_ = page->available_in_huge_free_list(); sizes->small_size_ = page->available_in_small_free_list(); sizes->medium_size_ = page->available_in_medium_free_list(); sizes->large_size_ = page->available_in_large_free_list(); } void PagedSpace::ResetFreeListStatistics() { PageIterator page_iterator(this); while (page_iterator.has_next()) { Page* page = page_iterator.next(); page->ResetFreeListStatistics(); } } void PagedSpace::IncreaseCapacity(int size) { accounting_stats_.ExpandSpace(size); } void PagedSpace::ReleasePage(Page* page, bool unlink) { ASSERT(page->LiveBytes() == 0); ASSERT(AreaSize() == page->area_size()); // Adjust list of unswept pages if the page is the head of the list. if (first_unswept_page_ == page) { first_unswept_page_ = page->next_page(); if (first_unswept_page_ == anchor()) { first_unswept_page_ = Page::FromAddress(NULL); } } if (page->WasSwept()) { intptr_t size = free_list_.EvictFreeListItems(page); accounting_stats_.AllocateBytes(size); ASSERT_EQ(AreaSize(), static_cast<int>(size)); } else { DecreaseUnsweptFreeBytes(page); } // TODO(hpayer): This check is just used for debugging purpose and // should be removed or turned into an assert after investigating the // crash in concurrent sweeping. CHECK(!free_list_.ContainsPageFreeListItems(page)); if (Page::FromAllocationTop(allocation_info_.top()) == page) { allocation_info_.set_top(NULL); allocation_info_.set_limit(NULL); } if (unlink) { page->Unlink(); } if (page->IsFlagSet(MemoryChunk::CONTAINS_ONLY_DATA)) { heap()->isolate()->memory_allocator()->Free(page); } else { heap()->QueueMemoryChunkForFree(page); } ASSERT(Capacity() > 0); accounting_stats_.ShrinkSpace(AreaSize()); } #ifdef DEBUG void PagedSpace::Print() { } #endif #ifdef VERIFY_HEAP void PagedSpace::Verify(ObjectVisitor* visitor) { // We can only iterate over the pages if they were swept precisely. if (was_swept_conservatively_) return; bool allocation_pointer_found_in_space = (allocation_info_.top() == allocation_info_.limit()); PageIterator page_iterator(this); while (page_iterator.has_next()) { Page* page = page_iterator.next(); CHECK(page->owner() == this); if (page == Page::FromAllocationTop(allocation_info_.top())) { allocation_pointer_found_in_space = true; } CHECK(page->WasSweptPrecisely()); HeapObjectIterator it(page, NULL); Address end_of_previous_object = page->area_start(); Address top = page->area_end(); int black_size = 0; for (HeapObject* object = it.Next(); object != NULL; object = it.Next()) { CHECK(end_of_previous_object <= object->address()); // The first word should be a map, and we expect all map pointers to // be in map space. Map* map = object->map(); CHECK(map->IsMap()); CHECK(heap()->map_space()->Contains(map)); // Perform space-specific object verification. VerifyObject(object); // The object itself should look OK. object->Verify(); // All the interior pointers should be contained in the heap. int size = object->Size(); object->IterateBody(map->instance_type(), size, visitor); if (Marking::IsBlack(Marking::MarkBitFrom(object))) { black_size += size; } CHECK(object->address() + size <= top); end_of_previous_object = object->address() + size; } CHECK_LE(black_size, page->LiveBytes()); } CHECK(allocation_pointer_found_in_space); } #endif // VERIFY_HEAP // ----------------------------------------------------------------------------- // NewSpace implementation bool NewSpace::SetUp(int reserved_semispace_capacity, int maximum_semispace_capacity) { // Set up new space based on the preallocated memory block defined by // start and size. The provided space is divided into two semi-spaces. // To support fast containment testing in the new space, the size of // this chunk must be a power of two and it must be aligned to its size. int initial_semispace_capacity = heap()->InitialSemiSpaceSize(); size_t size = 2 * reserved_semispace_capacity; Address base = heap()->isolate()->memory_allocator()->ReserveAlignedMemory( size, size, &reservation_); if (base == NULL) return false; chunk_base_ = base; chunk_size_ = static_cast<uintptr_t>(size); LOG(heap()->isolate(), NewEvent("InitialChunk", chunk_base_, chunk_size_)); ASSERT(initial_semispace_capacity <= maximum_semispace_capacity); ASSERT(IsPowerOf2(maximum_semispace_capacity)); // Allocate and set up the histogram arrays if necessary. allocated_histogram_ = NewArray<HistogramInfo>(LAST_TYPE + 1); promoted_histogram_ = NewArray<HistogramInfo>(LAST_TYPE + 1); #define SET_NAME(name) allocated_histogram_[name].set_name(#name); \ promoted_histogram_[name].set_name(#name); INSTANCE_TYPE_LIST(SET_NAME) #undef SET_NAME ASSERT(reserved_semispace_capacity == heap()->ReservedSemiSpaceSize()); ASSERT(static_cast<intptr_t>(chunk_size_) >= 2 * heap()->ReservedSemiSpaceSize()); ASSERT(IsAddressAligned(chunk_base_, 2 * reserved_semispace_capacity, 0)); to_space_.SetUp(chunk_base_, initial_semispace_capacity, maximum_semispace_capacity); from_space_.SetUp(chunk_base_ + reserved_semispace_capacity, initial_semispace_capacity, maximum_semispace_capacity); if (!to_space_.Commit()) { return false; } ASSERT(!from_space_.is_committed()); // No need to use memory yet. start_ = chunk_base_; address_mask_ = ~(2 * reserved_semispace_capacity - 1); object_mask_ = address_mask_ | kHeapObjectTagMask; object_expected_ = reinterpret_cast<uintptr_t>(start_) | kHeapObjectTag; ResetAllocationInfo(); return true; } void NewSpace::TearDown() { if (allocated_histogram_) { DeleteArray(allocated_histogram_); allocated_histogram_ = NULL; } if (promoted_histogram_) { DeleteArray(promoted_histogram_); promoted_histogram_ = NULL; } start_ = NULL; allocation_info_.set_top(NULL); allocation_info_.set_limit(NULL); to_space_.TearDown(); from_space_.TearDown(); LOG(heap()->isolate(), DeleteEvent("InitialChunk", chunk_base_)); ASSERT(reservation_.IsReserved()); heap()->isolate()->memory_allocator()->FreeMemory(&reservation_, NOT_EXECUTABLE); chunk_base_ = NULL; chunk_size_ = 0; } void NewSpace::Flip() { SemiSpace::Swap(&from_space_, &to_space_); } void NewSpace::Grow() { // Double the semispace size but only up to maximum capacity. ASSERT(Capacity() < MaximumCapacity()); int new_capacity = Min(MaximumCapacity(), 2 * static_cast<int>(Capacity())); if (to_space_.GrowTo(new_capacity)) { // Only grow from space if we managed to grow to-space. if (!from_space_.GrowTo(new_capacity)) { // If we managed to grow to-space but couldn't grow from-space, // attempt to shrink to-space. if (!to_space_.ShrinkTo(from_space_.Capacity())) { // We are in an inconsistent state because we could not // commit/uncommit memory from new space. V8::FatalProcessOutOfMemory("Failed to grow new space."); } } } ASSERT_SEMISPACE_ALLOCATION_INFO(allocation_info_, to_space_); } void NewSpace::Shrink() { int new_capacity = Max(InitialCapacity(), 2 * SizeAsInt()); int rounded_new_capacity = RoundUp(new_capacity, Page::kPageSize); if (rounded_new_capacity < Capacity() && to_space_.ShrinkTo(rounded_new_capacity)) { // Only shrink from-space if we managed to shrink to-space. from_space_.Reset(); if (!from_space_.ShrinkTo(rounded_new_capacity)) { // If we managed to shrink to-space but couldn't shrink from // space, attempt to grow to-space again. if (!to_space_.GrowTo(from_space_.Capacity())) { // We are in an inconsistent state because we could not // commit/uncommit memory from new space. V8::FatalProcessOutOfMemory("Failed to shrink new space."); } } } ASSERT_SEMISPACE_ALLOCATION_INFO(allocation_info_, to_space_); } void NewSpace::UpdateAllocationInfo() { MemoryChunk::UpdateHighWaterMark(allocation_info_.top()); allocation_info_.set_top(to_space_.page_low()); allocation_info_.set_limit(to_space_.page_high()); UpdateInlineAllocationLimit(0); ASSERT_SEMISPACE_ALLOCATION_INFO(allocation_info_, to_space_); } void NewSpace::ResetAllocationInfo() { to_space_.Reset(); UpdateAllocationInfo(); pages_used_ = 0; // Clear all mark-bits in the to-space. NewSpacePageIterator it(&to_space_); while (it.has_next()) { Bitmap::Clear(it.next()); } } void NewSpace::UpdateInlineAllocationLimit(int size_in_bytes) { if (heap()->inline_allocation_disabled()) { // Lowest limit when linear allocation was disabled. Address high = to_space_.page_high(); Address new_top = allocation_info_.top() + size_in_bytes; allocation_info_.set_limit(Min(new_top, high)); } else if (inline_allocation_limit_step() == 0) { // Normal limit is the end of the current page. allocation_info_.set_limit(to_space_.page_high()); } else { // Lower limit during incremental marking. Address high = to_space_.page_high(); Address new_top = allocation_info_.top() + size_in_bytes; Address new_limit = new_top + inline_allocation_limit_step_; allocation_info_.set_limit(Min(new_limit, high)); } ASSERT_SEMISPACE_ALLOCATION_INFO(allocation_info_, to_space_); } bool NewSpace::AddFreshPage() { Address top = allocation_info_.top(); if (NewSpacePage::IsAtStart(top)) { // The current page is already empty. Don't try to make another. // We should only get here if someone asks to allocate more // than what can be stored in a single page. // TODO(gc): Change the limit on new-space allocation to prevent this // from happening (all such allocations should go directly to LOSpace). return false; } if (!to_space_.AdvancePage()) { // Failed to get a new page in to-space. return false; } // Clear remainder of current page. Address limit = NewSpacePage::FromLimit(top)->area_end(); if (heap()->gc_state() == Heap::SCAVENGE) { heap()->promotion_queue()->SetNewLimit(limit); heap()->promotion_queue()->ActivateGuardIfOnTheSamePage(); } int remaining_in_page = static_cast<int>(limit - top); heap()->CreateFillerObjectAt(top, remaining_in_page); pages_used_++; UpdateAllocationInfo(); return true; } MaybeObject* NewSpace::SlowAllocateRaw(int size_in_bytes) { Address old_top = allocation_info_.top(); Address high = to_space_.page_high(); if (allocation_info_.limit() < high) { // Either the limit has been lowered because linear allocation was disabled // or because incremental marking wants to get a chance to do a step. Set // the new limit accordingly. Address new_top = old_top + size_in_bytes; int bytes_allocated = static_cast<int>(new_top - top_on_previous_step_); heap()->incremental_marking()->Step( bytes_allocated, IncrementalMarking::GC_VIA_STACK_GUARD); UpdateInlineAllocationLimit(size_in_bytes); top_on_previous_step_ = new_top; return AllocateRaw(size_in_bytes); } else if (AddFreshPage()) { // Switched to new page. Try allocating again. int bytes_allocated = static_cast<int>(old_top - top_on_previous_step_); heap()->incremental_marking()->Step( bytes_allocated, IncrementalMarking::GC_VIA_STACK_GUARD); top_on_previous_step_ = to_space_.page_low(); return AllocateRaw(size_in_bytes); } else { return Failure::RetryAfterGC(); } } #ifdef VERIFY_HEAP // We do not use the SemiSpaceIterator because verification doesn't assume // that it works (it depends on the invariants we are checking). void NewSpace::Verify() { // The allocation pointer should be in the space or at the very end. ASSERT_SEMISPACE_ALLOCATION_INFO(allocation_info_, to_space_); // There should be objects packed in from the low address up to the // allocation pointer. Address current = to_space_.first_page()->area_start(); CHECK_EQ(current, to_space_.space_start()); while (current != top()) { if (!NewSpacePage::IsAtEnd(current)) { // The allocation pointer should not be in the middle of an object. CHECK(!NewSpacePage::FromLimit(current)->ContainsLimit(top()) || current < top()); HeapObject* object = HeapObject::FromAddress(current); // The first word should be a map, and we expect all map pointers to // be in map space. Map* map = object->map(); CHECK(map->IsMap()); CHECK(heap()->map_space()->Contains(map)); // The object should not be code or a map. CHECK(!object->IsMap()); CHECK(!object->IsCode()); // The object itself should look OK. object->Verify(); // All the interior pointers should be contained in the heap. VerifyPointersVisitor visitor; int size = object->Size(); object->IterateBody(map->instance_type(), size, &visitor); current += size; } else { // At end of page, switch to next page. NewSpacePage* page = NewSpacePage::FromLimit(current)->next_page(); // Next page should be valid. CHECK(!page->is_anchor()); current = page->area_start(); } } // Check semi-spaces. CHECK_EQ(from_space_.id(), kFromSpace); CHECK_EQ(to_space_.id(), kToSpace); from_space_.Verify(); to_space_.Verify(); } #endif // ----------------------------------------------------------------------------- // SemiSpace implementation void SemiSpace::SetUp(Address start, int initial_capacity, int maximum_capacity) { // Creates a space in the young generation. The constructor does not // allocate memory from the OS. A SemiSpace is given a contiguous chunk of // memory of size 'capacity' when set up, and does not grow or shrink // otherwise. In the mark-compact collector, the memory region of the from // space is used as the marking stack. It requires contiguous memory // addresses. ASSERT(maximum_capacity >= Page::kPageSize); initial_capacity_ = RoundDown(initial_capacity, Page::kPageSize); capacity_ = initial_capacity; maximum_capacity_ = RoundDown(maximum_capacity, Page::kPageSize); maximum_committed_ = 0; committed_ = false; start_ = start; address_mask_ = ~(maximum_capacity - 1); object_mask_ = address_mask_ | kHeapObjectTagMask; object_expected_ = reinterpret_cast<uintptr_t>(start) | kHeapObjectTag; age_mark_ = start_; } void SemiSpace::TearDown() { start_ = NULL; capacity_ = 0; } bool SemiSpace::Commit() { ASSERT(!is_committed()); int pages = capacity_ / Page::kPageSize; if (!heap()->isolate()->memory_allocator()->CommitBlock(start_, capacity_, executable())) { return false; } NewSpacePage* current = anchor(); for (int i = 0; i < pages; i++) { NewSpacePage* new_page = NewSpacePage::Initialize(heap(), start_ + i * Page::kPageSize, this); new_page->InsertAfter(current); current = new_page; } SetCapacity(capacity_); committed_ = true; Reset(); return true; } bool SemiSpace::Uncommit() { ASSERT(is_committed()); Address start = start_ + maximum_capacity_ - capacity_; if (!heap()->isolate()->memory_allocator()->UncommitBlock(start, capacity_)) { return false; } anchor()->set_next_page(anchor()); anchor()->set_prev_page(anchor()); committed_ = false; return true; } size_t SemiSpace::CommittedPhysicalMemory() { if (!is_committed()) return 0; size_t size = 0; NewSpacePageIterator it(this); while (it.has_next()) { size += it.next()->CommittedPhysicalMemory(); } return size; } bool SemiSpace::GrowTo(int new_capacity) { if (!is_committed()) { if (!Commit()) return false; } ASSERT((new_capacity & Page::kPageAlignmentMask) == 0); ASSERT(new_capacity <= maximum_capacity_); ASSERT(new_capacity > capacity_); int pages_before = capacity_ / Page::kPageSize; int pages_after = new_capacity / Page::kPageSize; size_t delta = new_capacity - capacity_; ASSERT(IsAligned(delta, OS::AllocateAlignment())); if (!heap()->isolate()->memory_allocator()->CommitBlock( start_ + capacity_, delta, executable())) { return false; } SetCapacity(new_capacity); NewSpacePage* last_page = anchor()->prev_page(); ASSERT(last_page != anchor()); for (int i = pages_before; i < pages_after; i++) { Address page_address = start_ + i * Page::kPageSize; NewSpacePage* new_page = NewSpacePage::Initialize(heap(), page_address, this); new_page->InsertAfter(last_page); Bitmap::Clear(new_page); // Duplicate the flags that was set on the old page. new_page->SetFlags(last_page->GetFlags(), NewSpacePage::kCopyOnFlipFlagsMask); last_page = new_page; } return true; } bool SemiSpace::ShrinkTo(int new_capacity) { ASSERT((new_capacity & Page::kPageAlignmentMask) == 0); ASSERT(new_capacity >= initial_capacity_); ASSERT(new_capacity < capacity_); if (is_committed()) { size_t delta = capacity_ - new_capacity; ASSERT(IsAligned(delta, OS::AllocateAlignment())); MemoryAllocator* allocator = heap()->isolate()->memory_allocator(); if (!allocator->UncommitBlock(start_ + new_capacity, delta)) { return false; } int pages_after = new_capacity / Page::kPageSize; NewSpacePage* new_last_page = NewSpacePage::FromAddress(start_ + (pages_after - 1) * Page::kPageSize); new_last_page->set_next_page(anchor()); anchor()->set_prev_page(new_last_page); ASSERT((current_page_ >= first_page()) && (current_page_ <= new_last_page)); } SetCapacity(new_capacity); return true; } void SemiSpace::FlipPages(intptr_t flags, intptr_t mask) { anchor_.set_owner(this); // Fixup back-pointers to anchor. Address of anchor changes // when we swap. anchor_.prev_page()->set_next_page(&anchor_); anchor_.next_page()->set_prev_page(&anchor_); bool becomes_to_space = (id_ == kFromSpace); id_ = becomes_to_space ? kToSpace : kFromSpace; NewSpacePage* page = anchor_.next_page(); while (page != &anchor_) { page->set_owner(this); page->SetFlags(flags, mask); if (becomes_to_space) { page->ClearFlag(MemoryChunk::IN_FROM_SPACE); page->SetFlag(MemoryChunk::IN_TO_SPACE); page->ClearFlag(MemoryChunk::NEW_SPACE_BELOW_AGE_MARK); page->ResetLiveBytes(); } else { page->SetFlag(MemoryChunk::IN_FROM_SPACE); page->ClearFlag(MemoryChunk::IN_TO_SPACE); } ASSERT(page->IsFlagSet(MemoryChunk::SCAN_ON_SCAVENGE)); ASSERT(page->IsFlagSet(MemoryChunk::IN_TO_SPACE) || page->IsFlagSet(MemoryChunk::IN_FROM_SPACE)); page = page->next_page(); } } void SemiSpace::Reset() { ASSERT(anchor_.next_page() != &anchor_); current_page_ = anchor_.next_page(); } void SemiSpace::Swap(SemiSpace* from, SemiSpace* to) { // We won't be swapping semispaces without data in them. ASSERT(from->anchor_.next_page() != &from->anchor_); ASSERT(to->anchor_.next_page() != &to->anchor_); // Swap bits. SemiSpace tmp = *from; *from = *to; *to = tmp; // Fixup back-pointers to the page list anchor now that its address // has changed. // Swap to/from-space bits on pages. // Copy GC flags from old active space (from-space) to new (to-space). intptr_t flags = from->current_page()->GetFlags(); to->FlipPages(flags, NewSpacePage::kCopyOnFlipFlagsMask); from->FlipPages(0, 0); } void SemiSpace::SetCapacity(int new_capacity) { capacity_ = new_capacity; if (capacity_ > maximum_committed_) { maximum_committed_ = capacity_; } } void SemiSpace::set_age_mark(Address mark) { ASSERT(NewSpacePage::FromLimit(mark)->semi_space() == this); age_mark_ = mark; // Mark all pages up to the one containing mark. NewSpacePageIterator it(space_start(), mark); while (it.has_next()) { it.next()->SetFlag(MemoryChunk::NEW_SPACE_BELOW_AGE_MARK); } } #ifdef DEBUG void SemiSpace::Print() { } #endif #ifdef VERIFY_HEAP void SemiSpace::Verify() { bool is_from_space = (id_ == kFromSpace); NewSpacePage* page = anchor_.next_page(); CHECK(anchor_.semi_space() == this); while (page != &anchor_) { CHECK(page->semi_space() == this); CHECK(page->InNewSpace()); CHECK(page->IsFlagSet(is_from_space ? MemoryChunk::IN_FROM_SPACE : MemoryChunk::IN_TO_SPACE)); CHECK(!page->IsFlagSet(is_from_space ? MemoryChunk::IN_TO_SPACE : MemoryChunk::IN_FROM_SPACE)); CHECK(page->IsFlagSet(MemoryChunk::POINTERS_TO_HERE_ARE_INTERESTING)); if (!is_from_space) { // The pointers-from-here-are-interesting flag isn't updated dynamically // on from-space pages, so it might be out of sync with the marking state. if (page->heap()->incremental_marking()->IsMarking()) { CHECK(page->IsFlagSet(MemoryChunk::POINTERS_FROM_HERE_ARE_INTERESTING)); } else { CHECK(!page->IsFlagSet( MemoryChunk::POINTERS_FROM_HERE_ARE_INTERESTING)); } // TODO(gc): Check that the live_bytes_count_ field matches the // black marking on the page (if we make it match in new-space). } CHECK(page->IsFlagSet(MemoryChunk::SCAN_ON_SCAVENGE)); CHECK(page->prev_page()->next_page() == page); page = page->next_page(); } } #endif #ifdef DEBUG void SemiSpace::AssertValidRange(Address start, Address end) { // Addresses belong to same semi-space NewSpacePage* page = NewSpacePage::FromLimit(start); NewSpacePage* end_page = NewSpacePage::FromLimit(end); SemiSpace* space = page->semi_space(); CHECK_EQ(space, end_page->semi_space()); // Start address is before end address, either on same page, // or end address is on a later page in the linked list of // semi-space pages. if (page == end_page) { CHECK(start <= end); } else { while (page != end_page) { page = page->next_page(); CHECK_NE(page, space->anchor()); } } } #endif // ----------------------------------------------------------------------------- // SemiSpaceIterator implementation. SemiSpaceIterator::SemiSpaceIterator(NewSpace* space) { Initialize(space->bottom(), space->top(), NULL); } SemiSpaceIterator::SemiSpaceIterator(NewSpace* space, HeapObjectCallback size_func) { Initialize(space->bottom(), space->top(), size_func); } SemiSpaceIterator::SemiSpaceIterator(NewSpace* space, Address start) { Initialize(start, space->top(), NULL); } SemiSpaceIterator::SemiSpaceIterator(Address from, Address to) { Initialize(from, to, NULL); } void SemiSpaceIterator::Initialize(Address start, Address end, HeapObjectCallback size_func) { SemiSpace::AssertValidRange(start, end); current_ = start; limit_ = end; size_func_ = size_func; } #ifdef DEBUG // heap_histograms is shared, always clear it before using it. static void ClearHistograms(Isolate* isolate) { // We reset the name each time, though it hasn't changed. #define DEF_TYPE_NAME(name) isolate->heap_histograms()[name].set_name(#name); INSTANCE_TYPE_LIST(DEF_TYPE_NAME) #undef DEF_TYPE_NAME #define CLEAR_HISTOGRAM(name) isolate->heap_histograms()[name].clear(); INSTANCE_TYPE_LIST(CLEAR_HISTOGRAM) #undef CLEAR_HISTOGRAM isolate->js_spill_information()->Clear(); } static void ClearCodeKindStatistics(int* code_kind_statistics) { for (int i = 0; i < Code::NUMBER_OF_KINDS; i++) { code_kind_statistics[i] = 0; } } static void ReportCodeKindStatistics(int* code_kind_statistics) { PrintF("\n Code kind histograms: \n"); for (int i = 0; i < Code::NUMBER_OF_KINDS; i++) { if (code_kind_statistics[i] > 0) { PrintF(" %-20s: %10d bytes\n", Code::Kind2String(static_cast<Code::Kind>(i)), code_kind_statistics[i]); } } PrintF("\n"); } static int CollectHistogramInfo(HeapObject* obj) { Isolate* isolate = obj->GetIsolate(); InstanceType type = obj->map()->instance_type(); ASSERT(0 <= type && type <= LAST_TYPE); ASSERT(isolate->heap_histograms()[type].name() != NULL); isolate->heap_histograms()[type].increment_number(1); isolate->heap_histograms()[type].increment_bytes(obj->Size()); if (FLAG_collect_heap_spill_statistics && obj->IsJSObject()) { JSObject::cast(obj)->IncrementSpillStatistics( isolate->js_spill_information()); } return obj->Size(); } static void ReportHistogram(Isolate* isolate, bool print_spill) { PrintF("\n Object Histogram:\n"); for (int i = 0; i <= LAST_TYPE; i++) { if (isolate->heap_histograms()[i].number() > 0) { PrintF(" %-34s%10d (%10d bytes)\n", isolate->heap_histograms()[i].name(), isolate->heap_histograms()[i].number(), isolate->heap_histograms()[i].bytes()); } } PrintF("\n"); // Summarize string types. int string_number = 0; int string_bytes = 0; #define INCREMENT(type, size, name, camel_name) \ string_number += isolate->heap_histograms()[type].number(); \ string_bytes += isolate->heap_histograms()[type].bytes(); STRING_TYPE_LIST(INCREMENT) #undef INCREMENT if (string_number > 0) { PrintF(" %-34s%10d (%10d bytes)\n\n", "STRING_TYPE", string_number, string_bytes); } if (FLAG_collect_heap_spill_statistics && print_spill) { isolate->js_spill_information()->Print(); } } #endif // DEBUG // Support for statistics gathering for --heap-stats and --log-gc. void NewSpace::ClearHistograms() { for (int i = 0; i <= LAST_TYPE; i++) { allocated_histogram_[i].clear(); promoted_histogram_[i].clear(); } } // Because the copying collector does not touch garbage objects, we iterate // the new space before a collection to get a histogram of allocated objects. // This only happens when --log-gc flag is set. void NewSpace::CollectStatistics() { ClearHistograms(); SemiSpaceIterator it(this); for (HeapObject* obj = it.Next(); obj != NULL; obj = it.Next()) RecordAllocation(obj); } static void DoReportStatistics(Isolate* isolate, HistogramInfo* info, const char* description) { LOG(isolate, HeapSampleBeginEvent("NewSpace", description)); // Lump all the string types together. int string_number = 0; int string_bytes = 0; #define INCREMENT(type, size, name, camel_name) \ string_number += info[type].number(); \ string_bytes += info[type].bytes(); STRING_TYPE_LIST(INCREMENT) #undef INCREMENT if (string_number > 0) { LOG(isolate, HeapSampleItemEvent("STRING_TYPE", string_number, string_bytes)); } // Then do the other types. for (int i = FIRST_NONSTRING_TYPE; i <= LAST_TYPE; ++i) { if (info[i].number() > 0) { LOG(isolate, HeapSampleItemEvent(info[i].name(), info[i].number(), info[i].bytes())); } } LOG(isolate, HeapSampleEndEvent("NewSpace", description)); } void NewSpace::ReportStatistics() { #ifdef DEBUG if (FLAG_heap_stats) { float pct = static_cast<float>(Available()) / Capacity(); PrintF(" capacity: %" V8_PTR_PREFIX "d" ", available: %" V8_PTR_PREFIX "d, %%%d\n", Capacity(), Available(), static_cast<int>(pct*100)); PrintF("\n Object Histogram:\n"); for (int i = 0; i <= LAST_TYPE; i++) { if (allocated_histogram_[i].number() > 0) { PrintF(" %-34s%10d (%10d bytes)\n", allocated_histogram_[i].name(), allocated_histogram_[i].number(), allocated_histogram_[i].bytes()); } } PrintF("\n"); } #endif // DEBUG if (FLAG_log_gc) { Isolate* isolate = heap()->isolate(); DoReportStatistics(isolate, allocated_histogram_, "allocated"); DoReportStatistics(isolate, promoted_histogram_, "promoted"); } } void NewSpace::RecordAllocation(HeapObject* obj) { InstanceType type = obj->map()->instance_type(); ASSERT(0 <= type && type <= LAST_TYPE); allocated_histogram_[type].increment_number(1); allocated_histogram_[type].increment_bytes(obj->Size()); } void NewSpace::RecordPromotion(HeapObject* obj) { InstanceType type = obj->map()->instance_type(); ASSERT(0 <= type && type <= LAST_TYPE); promoted_histogram_[type].increment_number(1); promoted_histogram_[type].increment_bytes(obj->Size()); } size_t NewSpace::CommittedPhysicalMemory() { if (!VirtualMemory::HasLazyCommits()) return CommittedMemory(); MemoryChunk::UpdateHighWaterMark(allocation_info_.top()); size_t size = to_space_.CommittedPhysicalMemory(); if (from_space_.is_committed()) { size += from_space_.CommittedPhysicalMemory(); } return size; } // ----------------------------------------------------------------------------- // Free lists for old object spaces implementation void FreeListNode::set_size(Heap* heap, int size_in_bytes) { ASSERT(size_in_bytes > 0); ASSERT(IsAligned(size_in_bytes, kPointerSize)); // We write a map and possibly size information to the block. If the block // is big enough to be a FreeSpace with at least one extra word (the next // pointer), we set its map to be the free space map and its size to an // appropriate array length for the desired size from HeapObject::Size(). // If the block is too small (eg, one or two words), to hold both a size // field and a next pointer, we give it a filler map that gives it the // correct size. if (size_in_bytes > FreeSpace::kHeaderSize) { set_map_no_write_barrier(heap->raw_unchecked_free_space_map()); // Can't use FreeSpace::cast because it fails during deserialization. FreeSpace* this_as_free_space = reinterpret_cast<FreeSpace*>(this); this_as_free_space->set_size(size_in_bytes); } else if (size_in_bytes == kPointerSize) { set_map_no_write_barrier(heap->raw_unchecked_one_pointer_filler_map()); } else if (size_in_bytes == 2 * kPointerSize) { set_map_no_write_barrier(heap->raw_unchecked_two_pointer_filler_map()); } else { UNREACHABLE(); } // We would like to ASSERT(Size() == size_in_bytes) but this would fail during // deserialization because the free space map is not done yet. } FreeListNode* FreeListNode::next() { ASSERT(IsFreeListNode(this)); if (map() == GetHeap()->raw_unchecked_free_space_map()) { ASSERT(map() == NULL || Size() >= kNextOffset + kPointerSize); return reinterpret_cast<FreeListNode*>( Memory::Address_at(address() + kNextOffset)); } else { return reinterpret_cast<FreeListNode*>( Memory::Address_at(address() + kPointerSize)); } } FreeListNode** FreeListNode::next_address() { ASSERT(IsFreeListNode(this)); if (map() == GetHeap()->raw_unchecked_free_space_map()) { ASSERT(Size() >= kNextOffset + kPointerSize); return reinterpret_cast<FreeListNode**>(address() + kNextOffset); } else { return reinterpret_cast<FreeListNode**>(address() + kPointerSize); } } void FreeListNode::set_next(FreeListNode* next) { ASSERT(IsFreeListNode(this)); // While we are booting the VM the free space map will actually be null. So // we have to make sure that we don't try to use it for anything at that // stage. if (map() == GetHeap()->raw_unchecked_free_space_map()) { ASSERT(map() == NULL || Size() >= kNextOffset + kPointerSize); Memory::Address_at(address() + kNextOffset) = reinterpret_cast<Address>(next); } else { Memory::Address_at(address() + kPointerSize) = reinterpret_cast<Address>(next); } } intptr_t FreeListCategory::Concatenate(FreeListCategory* category) { intptr_t free_bytes = 0; if (category->top() != NULL) { // This is safe (not going to deadlock) since Concatenate operations // are never performed on the same free lists at the same time in // reverse order. LockGuard<Mutex> target_lock_guard(mutex()); LockGuard<Mutex> source_lock_guard(category->mutex()); ASSERT(category->end_ != NULL); free_bytes = category->available(); if (end_ == NULL) { end_ = category->end(); } else { category->end()->set_next(top()); } set_top(category->top()); NoBarrier_Store(&top_, category->top_); available_ += category->available(); category->Reset(); } return free_bytes; } void FreeListCategory::Reset() { set_top(NULL); set_end(NULL); set_available(0); } intptr_t FreeListCategory::EvictFreeListItemsInList(Page* p) { int sum = 0; FreeListNode* t = top(); FreeListNode** n = &t; while (*n != NULL) { if (Page::FromAddress((*n)->address()) == p) { FreeSpace* free_space = reinterpret_cast<FreeSpace*>(*n); sum += free_space->Size(); *n = (*n)->next(); } else { n = (*n)->next_address(); } } set_top(t); if (top() == NULL) { set_end(NULL); } available_ -= sum; return sum; } bool FreeListCategory::ContainsPageFreeListItemsInList(Page* p) { FreeListNode* node = top(); while (node != NULL) { if (Page::FromAddress(node->address()) == p) return true; node = node->next(); } return false; } FreeListNode* FreeListCategory::PickNodeFromList(int *node_size) { FreeListNode* node = top(); if (node == NULL) return NULL; while (node != NULL && Page::FromAddress(node->address())->IsEvacuationCandidate()) { available_ -= reinterpret_cast<FreeSpace*>(node)->Size(); node = node->next(); } if (node != NULL) { set_top(node->next()); *node_size = reinterpret_cast<FreeSpace*>(node)->Size(); available_ -= *node_size; } else { set_top(NULL); } if (top() == NULL) { set_end(NULL); } return node; } FreeListNode* FreeListCategory::PickNodeFromList(int size_in_bytes, int *node_size) { FreeListNode* node = PickNodeFromList(node_size); if (node != NULL && *node_size < size_in_bytes) { Free(node, *node_size); *node_size = 0; return NULL; } return node; } void FreeListCategory::Free(FreeListNode* node, int size_in_bytes) { node->set_next(top()); set_top(node); if (end_ == NULL) { end_ = node; } available_ += size_in_bytes; } void FreeListCategory::RepairFreeList(Heap* heap) { FreeListNode* n = top(); while (n != NULL) { Map** map_location = reinterpret_cast<Map**>(n->address()); if (*map_location == NULL) { *map_location = heap->free_space_map(); } else { ASSERT(*map_location == heap->free_space_map()); } n = n->next(); } } FreeList::FreeList(PagedSpace* owner) : owner_(owner), heap_(owner->heap()) { Reset(); } intptr_t FreeList::Concatenate(FreeList* free_list) { intptr_t free_bytes = 0; free_bytes += small_list_.Concatenate(free_list->small_list()); free_bytes += medium_list_.Concatenate(free_list->medium_list()); free_bytes += large_list_.Concatenate(free_list->large_list()); free_bytes += huge_list_.Concatenate(free_list->huge_list()); return free_bytes; } void FreeList::Reset() { small_list_.Reset(); medium_list_.Reset(); large_list_.Reset(); huge_list_.Reset(); } int FreeList::Free(Address start, int size_in_bytes) { if (size_in_bytes == 0) return 0; FreeListNode* node = FreeListNode::FromAddress(start); node->set_size(heap_, size_in_bytes); Page* page = Page::FromAddress(start); // Early return to drop too-small blocks on the floor. if (size_in_bytes < kSmallListMin) { page->add_non_available_small_blocks(size_in_bytes); return size_in_bytes; } // Insert other blocks at the head of a free list of the appropriate // magnitude. if (size_in_bytes <= kSmallListMax) { small_list_.Free(node, size_in_bytes); page->add_available_in_small_free_list(size_in_bytes); } else if (size_in_bytes <= kMediumListMax) { medium_list_.Free(node, size_in_bytes); page->add_available_in_medium_free_list(size_in_bytes); } else if (size_in_bytes <= kLargeListMax) { large_list_.Free(node, size_in_bytes); page->add_available_in_large_free_list(size_in_bytes); } else { huge_list_.Free(node, size_in_bytes); page->add_available_in_huge_free_list(size_in_bytes); } ASSERT(IsVeryLong() || available() == SumFreeLists()); return 0; } FreeListNode* FreeList::FindNodeFor(int size_in_bytes, int* node_size) { FreeListNode* node = NULL; Page* page = NULL; if (size_in_bytes <= kSmallAllocationMax) { node = small_list_.PickNodeFromList(node_size); if (node != NULL) { ASSERT(size_in_bytes <= *node_size); page = Page::FromAddress(node->address()); page->add_available_in_small_free_list(-(*node_size)); ASSERT(IsVeryLong() || available() == SumFreeLists()); return node; } } if (size_in_bytes <= kMediumAllocationMax) { node = medium_list_.PickNodeFromList(node_size); if (node != NULL) { ASSERT(size_in_bytes <= *node_size); page = Page::FromAddress(node->address()); page->add_available_in_medium_free_list(-(*node_size)); ASSERT(IsVeryLong() || available() == SumFreeLists()); return node; } } if (size_in_bytes <= kLargeAllocationMax) { node = large_list_.PickNodeFromList(node_size); if (node != NULL) { ASSERT(size_in_bytes <= *node_size); page = Page::FromAddress(node->address()); page->add_available_in_large_free_list(-(*node_size)); ASSERT(IsVeryLong() || available() == SumFreeLists()); return node; } } int huge_list_available = huge_list_.available(); FreeListNode* top_node = huge_list_.top(); for (FreeListNode** cur = &top_node; *cur != NULL; cur = (*cur)->next_address()) { FreeListNode* cur_node = *cur; while (cur_node != NULL && Page::FromAddress(cur_node->address())->IsEvacuationCandidate()) { int size = reinterpret_cast<FreeSpace*>(cur_node)->Size(); huge_list_available -= size; page = Page::FromAddress(cur_node->address()); page->add_available_in_huge_free_list(-size); cur_node = cur_node->next(); } *cur = cur_node; if (cur_node == NULL) { huge_list_.set_end(NULL); break; } ASSERT((*cur)->map() == heap_->raw_unchecked_free_space_map()); FreeSpace* cur_as_free_space = reinterpret_cast<FreeSpace*>(*cur); int size = cur_as_free_space->Size(); if (size >= size_in_bytes) { // Large enough node found. Unlink it from the list. node = *cur; *cur = node->next(); *node_size = size; huge_list_available -= size; page = Page::FromAddress(node->address()); page->add_available_in_huge_free_list(-size); break; } } huge_list_.set_top(top_node); if (huge_list_.top() == NULL) { huge_list_.set_end(NULL); } huge_list_.set_available(huge_list_available); if (node != NULL) { ASSERT(IsVeryLong() || available() == SumFreeLists()); return node; } if (size_in_bytes <= kSmallListMax) { node = small_list_.PickNodeFromList(size_in_bytes, node_size); if (node != NULL) { ASSERT(size_in_bytes <= *node_size); page = Page::FromAddress(node->address()); page->add_available_in_small_free_list(-(*node_size)); } } else if (size_in_bytes <= kMediumListMax) { node = medium_list_.PickNodeFromList(size_in_bytes, node_size); if (node != NULL) { ASSERT(size_in_bytes <= *node_size); page = Page::FromAddress(node->address()); page->add_available_in_medium_free_list(-(*node_size)); } } else if (size_in_bytes <= kLargeListMax) { node = large_list_.PickNodeFromList(size_in_bytes, node_size); if (node != NULL) { ASSERT(size_in_bytes <= *node_size); page = Page::FromAddress(node->address()); page->add_available_in_large_free_list(-(*node_size)); } } ASSERT(IsVeryLong() || available() == SumFreeLists()); return node; } // Allocation on the old space free list. If it succeeds then a new linear // allocation space has been set up with the top and limit of the space. If // the allocation fails then NULL is returned, and the caller can perform a GC // or allocate a new page before retrying. HeapObject* FreeList::Allocate(int size_in_bytes) { ASSERT(0 < size_in_bytes); ASSERT(size_in_bytes <= kMaxBlockSize); ASSERT(IsAligned(size_in_bytes, kPointerSize)); // Don't free list allocate if there is linear space available. ASSERT(owner_->limit() - owner_->top() < size_in_bytes); int old_linear_size = static_cast<int>(owner_->limit() - owner_->top()); // Mark the old linear allocation area with a free space map so it can be // skipped when scanning the heap. This also puts it back in the free list // if it is big enough. owner_->Free(owner_->top(), old_linear_size); owner_->heap()->incremental_marking()->OldSpaceStep( size_in_bytes - old_linear_size); int new_node_size = 0; FreeListNode* new_node = FindNodeFor(size_in_bytes, &new_node_size); if (new_node == NULL) { owner_->SetTopAndLimit(NULL, NULL); return NULL; } int bytes_left = new_node_size - size_in_bytes; ASSERT(bytes_left >= 0); #ifdef DEBUG for (int i = 0; i < size_in_bytes / kPointerSize; i++) { reinterpret_cast<Object**>(new_node->address())[i] = Smi::FromInt(kCodeZapValue); } #endif // The old-space-step might have finished sweeping and restarted marking. // Verify that it did not turn the page of the new node into an evacuation // candidate. ASSERT(!MarkCompactCollector::IsOnEvacuationCandidate(new_node)); const int kThreshold = IncrementalMarking::kAllocatedThreshold; // Memory in the linear allocation area is counted as allocated. We may free // a little of this again immediately - see below. owner_->Allocate(new_node_size); if (owner_->heap()->inline_allocation_disabled()) { // Keep the linear allocation area empty if requested to do so, just // return area back to the free list instead. owner_->Free(new_node->address() + size_in_bytes, bytes_left); ASSERT(owner_->top() == NULL && owner_->limit() == NULL); } else if (bytes_left > kThreshold && owner_->heap()->incremental_marking()->IsMarkingIncomplete() && FLAG_incremental_marking_steps) { int linear_size = owner_->RoundSizeDownToObjectAlignment(kThreshold); // We don't want to give too large linear areas to the allocator while // incremental marking is going on, because we won't check again whether // we want to do another increment until the linear area is used up. owner_->Free(new_node->address() + size_in_bytes + linear_size, new_node_size - size_in_bytes - linear_size); owner_->SetTopAndLimit(new_node->address() + size_in_bytes, new_node->address() + size_in_bytes + linear_size); } else if (bytes_left > 0) { // Normally we give the rest of the node to the allocator as its new // linear allocation area. owner_->SetTopAndLimit(new_node->address() + size_in_bytes, new_node->address() + new_node_size); } else { // TODO(gc) Try not freeing linear allocation region when bytes_left // are zero. owner_->SetTopAndLimit(NULL, NULL); } return new_node; } intptr_t FreeList::EvictFreeListItems(Page* p) { intptr_t sum = huge_list_.EvictFreeListItemsInList(p); p->set_available_in_huge_free_list(0); if (sum < p->area_size()) { sum += small_list_.EvictFreeListItemsInList(p) + medium_list_.EvictFreeListItemsInList(p) + large_list_.EvictFreeListItemsInList(p); p->set_available_in_small_free_list(0); p->set_available_in_medium_free_list(0); p->set_available_in_large_free_list(0); } return sum; } bool FreeList::ContainsPageFreeListItems(Page* p) { return huge_list_.EvictFreeListItemsInList(p) || small_list_.EvictFreeListItemsInList(p) || medium_list_.EvictFreeListItemsInList(p) || large_list_.EvictFreeListItemsInList(p); } void FreeList::RepairLists(Heap* heap) { small_list_.RepairFreeList(heap); medium_list_.RepairFreeList(heap); large_list_.RepairFreeList(heap); huge_list_.RepairFreeList(heap); } #ifdef DEBUG intptr_t FreeListCategory::SumFreeList() { intptr_t sum = 0; FreeListNode* cur = top(); while (cur != NULL) { ASSERT(cur->map() == cur->GetHeap()->raw_unchecked_free_space_map()); FreeSpace* cur_as_free_space = reinterpret_cast<FreeSpace*>(cur); sum += cur_as_free_space->Size(); cur = cur->next(); } return sum; } static const int kVeryLongFreeList = 500; int FreeListCategory::FreeListLength() { int length = 0; FreeListNode* cur = top(); while (cur != NULL) { length++; cur = cur->next(); if (length == kVeryLongFreeList) return length; } return length; } bool FreeList::IsVeryLong() { if (small_list_.FreeListLength() == kVeryLongFreeList) return true; if (medium_list_.FreeListLength() == kVeryLongFreeList) return true; if (large_list_.FreeListLength() == kVeryLongFreeList) return true; if (huge_list_.FreeListLength() == kVeryLongFreeList) return true; return false; } // This can take a very long time because it is linear in the number of entries // on the free list, so it should not be called if FreeListLength returns // kVeryLongFreeList. intptr_t FreeList::SumFreeLists() { intptr_t sum = small_list_.SumFreeList(); sum += medium_list_.SumFreeList(); sum += large_list_.SumFreeList(); sum += huge_list_.SumFreeList(); return sum; } #endif // ----------------------------------------------------------------------------- // OldSpace implementation void PagedSpace::PrepareForMarkCompact() { // We don't have a linear allocation area while sweeping. It will be restored // on the first allocation after the sweep. EmptyAllocationInfo(); // Stop lazy sweeping and clear marking bits for unswept pages. if (first_unswept_page_ != NULL) { Page* p = first_unswept_page_; do { // Do not use ShouldBeSweptLazily predicate here. // New evacuation candidates were selected but they still have // to be swept before collection starts. if (!p->WasSwept()) { Bitmap::Clear(p); if (FLAG_gc_verbose) { PrintF("Sweeping 0x%" V8PRIxPTR " lazily abandoned.\n", reinterpret_cast<intptr_t>(p)); } } p = p->next_page(); } while (p != anchor()); } first_unswept_page_ = Page::FromAddress(NULL); unswept_free_bytes_ = 0; // Clear the free list before a full GC---it will be rebuilt afterward. free_list_.Reset(); } intptr_t PagedSpace::SizeOfObjects() { ASSERT(!heap()->IsSweepingComplete() || (unswept_free_bytes_ == 0)); return Size() - unswept_free_bytes_ - (limit() - top()); } // After we have booted, we have created a map which represents free space // on the heap. If there was already a free list then the elements on it // were created with the wrong FreeSpaceMap (normally NULL), so we need to // fix them. void PagedSpace::RepairFreeListsAfterBoot() { free_list_.RepairLists(heap()); } bool PagedSpace::AdvanceSweeper(intptr_t bytes_to_sweep) { if (IsLazySweepingComplete()) return true; intptr_t freed_bytes = 0; Page* p = first_unswept_page_; do { Page* next_page = p->next_page(); if (ShouldBeSweptLazily(p)) { if (FLAG_gc_verbose) { PrintF("Sweeping 0x%" V8PRIxPTR " lazily advanced.\n", reinterpret_cast<intptr_t>(p)); } DecreaseUnsweptFreeBytes(p); freed_bytes += MarkCompactCollector:: SweepConservatively<MarkCompactCollector::SWEEP_SEQUENTIALLY>( this, NULL, p); } p = next_page; } while (p != anchor() && freed_bytes < bytes_to_sweep); if (p == anchor()) { first_unswept_page_ = Page::FromAddress(NULL); } else { first_unswept_page_ = p; } heap()->FreeQueuedChunks(); return IsLazySweepingComplete(); } void PagedSpace::EvictEvacuationCandidatesFromFreeLists() { if (allocation_info_.top() >= allocation_info_.limit()) return; if (Page::FromAllocationTop(allocation_info_.top())-> IsEvacuationCandidate()) { // Create filler object to keep page iterable if it was iterable. int remaining = static_cast<int>(allocation_info_.limit() - allocation_info_.top()); heap()->CreateFillerObjectAt(allocation_info_.top(), remaining); allocation_info_.set_top(NULL); allocation_info_.set_limit(NULL); } } bool PagedSpace::EnsureSweeperProgress(intptr_t size_in_bytes) { MarkCompactCollector* collector = heap()->mark_compact_collector(); if (collector->AreSweeperThreadsActivated()) { if (collector->IsConcurrentSweepingInProgress()) { if (collector->RefillFreeLists(this) < size_in_bytes) { if (!collector->sequential_sweeping()) { collector->WaitUntilSweepingCompleted(); return true; } } return false; } return true; } else { return AdvanceSweeper(size_in_bytes); } } HeapObject* PagedSpace::SlowAllocateRaw(int size_in_bytes) { // Allocation in this space has failed. // If there are unswept pages advance lazy sweeper a bounded number of times // until we find a size_in_bytes contiguous piece of memory const int kMaxSweepingTries = 5; bool sweeping_complete = false; for (int i = 0; i < kMaxSweepingTries && !sweeping_complete; i++) { sweeping_complete = EnsureSweeperProgress(size_in_bytes); // Retry the free list allocation. HeapObject* object = free_list_.Allocate(size_in_bytes); if (object != NULL) return object; } // Free list allocation failed and there is no next page. Fail if we have // hit the old generation size limit that should cause a garbage // collection. if (!heap()->always_allocate() && heap()->OldGenerationAllocationLimitReached()) { return NULL; } // Try to expand the space and allocate in the new next page. if (Expand()) { ASSERT(CountTotalPages() > 1 || size_in_bytes <= free_list_.available()); return free_list_.Allocate(size_in_bytes); } // Last ditch, sweep all the remaining pages to try to find space. This may // cause a pause. if (!IsLazySweepingComplete()) { EnsureSweeperProgress(kMaxInt); // Retry the free list allocation. HeapObject* object = free_list_.Allocate(size_in_bytes); if (object != NULL) return object; } // Finally, fail. return NULL; } #ifdef DEBUG void PagedSpace::ReportCodeStatistics(Isolate* isolate) { CommentStatistic* comments_statistics = isolate->paged_space_comments_statistics(); ReportCodeKindStatistics(isolate->code_kind_statistics()); PrintF("Code comment statistics (\" [ comment-txt : size/ " "count (average)\"):\n"); for (int i = 0; i <= CommentStatistic::kMaxComments; i++) { const CommentStatistic& cs = comments_statistics[i]; if (cs.size > 0) { PrintF(" %-30s: %10d/%6d (%d)\n", cs.comment, cs.size, cs.count, cs.size/cs.count); } } PrintF("\n"); } void PagedSpace::ResetCodeStatistics(Isolate* isolate) { CommentStatistic* comments_statistics = isolate->paged_space_comments_statistics(); ClearCodeKindStatistics(isolate->code_kind_statistics()); for (int i = 0; i < CommentStatistic::kMaxComments; i++) { comments_statistics[i].Clear(); } comments_statistics[CommentStatistic::kMaxComments].comment = "Unknown"; comments_statistics[CommentStatistic::kMaxComments].size = 0; comments_statistics[CommentStatistic::kMaxComments].count = 0; } // Adds comment to 'comment_statistics' table. Performance OK as long as // 'kMaxComments' is small static void EnterComment(Isolate* isolate, const char* comment, int delta) { CommentStatistic* comments_statistics = isolate->paged_space_comments_statistics(); // Do not count empty comments if (delta <= 0) return; CommentStatistic* cs = &comments_statistics[CommentStatistic::kMaxComments]; // Search for a free or matching entry in 'comments_statistics': 'cs' // points to result. for (int i = 0; i < CommentStatistic::kMaxComments; i++) { if (comments_statistics[i].comment == NULL) { cs = &comments_statistics[i]; cs->comment = comment; break; } else if (strcmp(comments_statistics[i].comment, comment) == 0) { cs = &comments_statistics[i]; break; } } // Update entry for 'comment' cs->size += delta; cs->count += 1; } // Call for each nested comment start (start marked with '[ xxx', end marked // with ']'. RelocIterator 'it' must point to a comment reloc info. static void CollectCommentStatistics(Isolate* isolate, RelocIterator* it) { ASSERT(!it->done()); ASSERT(it->rinfo()->rmode() == RelocInfo::COMMENT); const char* tmp = reinterpret_cast<const char*>(it->rinfo()->data()); if (tmp[0] != '[') { // Not a nested comment; skip return; } // Search for end of nested comment or a new nested comment const char* const comment_txt = reinterpret_cast<const char*>(it->rinfo()->data()); const byte* prev_pc = it->rinfo()->pc(); int flat_delta = 0; it->next(); while (true) { // All nested comments must be terminated properly, and therefore exit // from loop. ASSERT(!it->done()); if (it->rinfo()->rmode() == RelocInfo::COMMENT) { const char* const txt = reinterpret_cast<const char*>(it->rinfo()->data()); flat_delta += static_cast<int>(it->rinfo()->pc() - prev_pc); if (txt[0] == ']') break; // End of nested comment // A new comment CollectCommentStatistics(isolate, it); // Skip code that was covered with previous comment prev_pc = it->rinfo()->pc(); } it->next(); } EnterComment(isolate, comment_txt, flat_delta); } // Collects code size statistics: // - by code kind // - by code comment void PagedSpace::CollectCodeStatistics() { Isolate* isolate = heap()->isolate(); HeapObjectIterator obj_it(this); for (HeapObject* obj = obj_it.Next(); obj != NULL; obj = obj_it.Next()) { if (obj->IsCode()) { Code* code = Code::cast(obj); isolate->code_kind_statistics()[code->kind()] += code->Size(); RelocIterator it(code); int delta = 0; const byte* prev_pc = code->instruction_start(); while (!it.done()) { if (it.rinfo()->rmode() == RelocInfo::COMMENT) { delta += static_cast<int>(it.rinfo()->pc() - prev_pc); CollectCommentStatistics(isolate, &it); prev_pc = it.rinfo()->pc(); } it.next(); } ASSERT(code->instruction_start() <= prev_pc && prev_pc <= code->instruction_end()); delta += static_cast<int>(code->instruction_end() - prev_pc); EnterComment(isolate, "NoComment", delta); } } } void PagedSpace::ReportStatistics() { int pct = static_cast<int>(Available() * 100 / Capacity()); PrintF(" capacity: %" V8_PTR_PREFIX "d" ", waste: %" V8_PTR_PREFIX "d" ", available: %" V8_PTR_PREFIX "d, %%%d\n", Capacity(), Waste(), Available(), pct); if (was_swept_conservatively_) return; ClearHistograms(heap()->isolate()); HeapObjectIterator obj_it(this); for (HeapObject* obj = obj_it.Next(); obj != NULL; obj = obj_it.Next()) CollectHistogramInfo(obj); ReportHistogram(heap()->isolate(), true); } #endif // ----------------------------------------------------------------------------- // MapSpace implementation // TODO(mvstanton): this is weird...the compiler can't make a vtable unless // there is at least one non-inlined virtual function. I would prefer to hide // the VerifyObject definition behind VERIFY_HEAP. void MapSpace::VerifyObject(HeapObject* object) { CHECK(object->IsMap()); } // ----------------------------------------------------------------------------- // CellSpace and PropertyCellSpace implementation // TODO(mvstanton): this is weird...the compiler can't make a vtable unless // there is at least one non-inlined virtual function. I would prefer to hide // the VerifyObject definition behind VERIFY_HEAP. void CellSpace::VerifyObject(HeapObject* object) { CHECK(object->IsCell()); } void PropertyCellSpace::VerifyObject(HeapObject* object) { CHECK(object->IsPropertyCell()); } // ----------------------------------------------------------------------------- // LargeObjectIterator LargeObjectIterator::LargeObjectIterator(LargeObjectSpace* space) { current_ = space->first_page_; size_func_ = NULL; } LargeObjectIterator::LargeObjectIterator(LargeObjectSpace* space, HeapObjectCallback size_func) { current_ = space->first_page_; size_func_ = size_func; } HeapObject* LargeObjectIterator::Next() { if (current_ == NULL) return NULL; HeapObject* object = current_->GetObject(); current_ = current_->next_page(); return object; } // ----------------------------------------------------------------------------- // LargeObjectSpace static bool ComparePointers(void* key1, void* key2) { return key1 == key2; } LargeObjectSpace::LargeObjectSpace(Heap* heap, intptr_t max_capacity, AllocationSpace id) : Space(heap, id, NOT_EXECUTABLE), // Managed on a per-allocation basis max_capacity_(max_capacity), first_page_(NULL), size_(0), page_count_(0), objects_size_(0), chunk_map_(ComparePointers, 1024) {} bool LargeObjectSpace::SetUp() { first_page_ = NULL; size_ = 0; maximum_committed_ = 0; page_count_ = 0; objects_size_ = 0; chunk_map_.Clear(); return true; } void LargeObjectSpace::TearDown() { while (first_page_ != NULL) { LargePage* page = first_page_; first_page_ = first_page_->next_page(); LOG(heap()->isolate(), DeleteEvent("LargeObjectChunk", page->address())); ObjectSpace space = static_cast<ObjectSpace>(1 << identity()); heap()->isolate()->memory_allocator()->PerformAllocationCallback( space, kAllocationActionFree, page->size()); heap()->isolate()->memory_allocator()->Free(page); } SetUp(); } MaybeObject* LargeObjectSpace::AllocateRaw(int object_size, Executability executable) { // Check if we want to force a GC before growing the old space further. // If so, fail the allocation. if (!heap()->always_allocate() && heap()->OldGenerationAllocationLimitReached()) { return Failure::RetryAfterGC(identity()); } if (Size() + object_size > max_capacity_) { return Failure::RetryAfterGC(identity()); } LargePage* page = heap()->isolate()->memory_allocator()-> AllocateLargePage(object_size, this, executable); if (page == NULL) return Failure::RetryAfterGC(identity()); ASSERT(page->area_size() >= object_size); size_ += static_cast<int>(page->size()); objects_size_ += object_size; page_count_++; page->set_next_page(first_page_); first_page_ = page; if (size_ > maximum_committed_) { maximum_committed_ = size_; } // Register all MemoryChunk::kAlignment-aligned chunks covered by // this large page in the chunk map. uintptr_t base = reinterpret_cast<uintptr_t>(page) / MemoryChunk::kAlignment; uintptr_t limit = base + (page->size() - 1) / MemoryChunk::kAlignment; for (uintptr_t key = base; key <= limit; key++) { HashMap::Entry* entry = chunk_map_.Lookup(reinterpret_cast<void*>(key), static_cast<uint32_t>(key), true); ASSERT(entry != NULL); entry->value = page; } HeapObject* object = page->GetObject(); if (Heap::ShouldZapGarbage()) { // Make the object consistent so the heap can be verified in OldSpaceStep. // We only need to do this in debug builds or if verify_heap is on. reinterpret_cast<Object**>(object->address())[0] = heap()->fixed_array_map(); reinterpret_cast<Object**>(object->address())[1] = Smi::FromInt(0); } heap()->incremental_marking()->OldSpaceStep(object_size); return object; } size_t LargeObjectSpace::CommittedPhysicalMemory() { if (!VirtualMemory::HasLazyCommits()) return CommittedMemory(); size_t size = 0; LargePage* current = first_page_; while (current != NULL) { size += current->CommittedPhysicalMemory(); current = current->next_page(); } return size; } // GC support MaybeObject* LargeObjectSpace::FindObject(Address a) { LargePage* page = FindPage(a); if (page != NULL) { return page->GetObject(); } return Failure::Exception(); } LargePage* LargeObjectSpace::FindPage(Address a) { uintptr_t key = reinterpret_cast<uintptr_t>(a) / MemoryChunk::kAlignment; HashMap::Entry* e = chunk_map_.Lookup(reinterpret_cast<void*>(key), static_cast<uint32_t>(key), false); if (e != NULL) { ASSERT(e->value != NULL); LargePage* page = reinterpret_cast<LargePage*>(e->value); ASSERT(page->is_valid()); if (page->Contains(a)) { return page; } } return NULL; } void LargeObjectSpace::FreeUnmarkedObjects() { LargePage* previous = NULL; LargePage* current = first_page_; while (current != NULL) { HeapObject* object = current->GetObject(); // Can this large page contain pointers to non-trivial objects. No other // pointer object is this big. bool is_pointer_object = object->IsFixedArray(); MarkBit mark_bit = Marking::MarkBitFrom(object); if (mark_bit.Get()) { mark_bit.Clear(); Page::FromAddress(object->address())->ResetProgressBar(); Page::FromAddress(object->address())->ResetLiveBytes(); previous = current; current = current->next_page(); } else { LargePage* page = current; // Cut the chunk out from the chunk list. current = current->next_page(); if (previous == NULL) { first_page_ = current; } else { previous->set_next_page(current); } // Free the chunk. heap()->mark_compact_collector()->ReportDeleteIfNeeded( object, heap()->isolate()); size_ -= static_cast<int>(page->size()); objects_size_ -= object->Size(); page_count_--; // Remove entries belonging to this page. // Use variable alignment to help pass length check (<= 80 characters) // of single line in tools/presubmit.py. const intptr_t alignment = MemoryChunk::kAlignment; uintptr_t base = reinterpret_cast<uintptr_t>(page)/alignment; uintptr_t limit = base + (page->size()-1)/alignment; for (uintptr_t key = base; key <= limit; key++) { chunk_map_.Remove(reinterpret_cast<void*>(key), static_cast<uint32_t>(key)); } if (is_pointer_object) { heap()->QueueMemoryChunkForFree(page); } else { heap()->isolate()->memory_allocator()->Free(page); } } } heap()->FreeQueuedChunks(); } bool LargeObjectSpace::Contains(HeapObject* object) { Address address = object->address(); MemoryChunk* chunk = MemoryChunk::FromAddress(address); bool owned = (chunk->owner() == this); SLOW_ASSERT(!owned || !FindObject(address)->IsFailure()); return owned; } #ifdef VERIFY_HEAP // We do not assume that the large object iterator works, because it depends // on the invariants we are checking during verification. void LargeObjectSpace::Verify() { for (LargePage* chunk = first_page_; chunk != NULL; chunk = chunk->next_page()) { // Each chunk contains an object that starts at the large object page's // object area start. HeapObject* object = chunk->GetObject(); Page* page = Page::FromAddress(object->address()); CHECK(object->address() == page->area_start()); // The first word should be a map, and we expect all map pointers to be // in map space. Map* map = object->map(); CHECK(map->IsMap()); CHECK(heap()->map_space()->Contains(map)); // We have only code, sequential strings, external strings // (sequential strings that have been morphed into external // strings), fixed arrays, and byte arrays in large object space. CHECK(object->IsCode() || object->IsSeqString() || object->IsExternalString() || object->IsFixedArray() || object->IsFixedDoubleArray() || object->IsByteArray()); // The object itself should look OK. object->Verify(); // Byte arrays and strings don't have interior pointers. if (object->IsCode()) { VerifyPointersVisitor code_visitor; object->IterateBody(map->instance_type(), object->Size(), &code_visitor); } else if (object->IsFixedArray()) { FixedArray* array = FixedArray::cast(object); for (int j = 0; j < array->length(); j++) { Object* element = array->get(j); if (element->IsHeapObject()) { HeapObject* element_object = HeapObject::cast(element); CHECK(heap()->Contains(element_object)); CHECK(element_object->map()->IsMap()); } } } } } #endif #ifdef DEBUG void LargeObjectSpace::Print() { LargeObjectIterator it(this); for (HeapObject* obj = it.Next(); obj != NULL; obj = it.Next()) { obj->Print(); } } void LargeObjectSpace::ReportStatistics() { PrintF(" size: %" V8_PTR_PREFIX "d\n", size_); int num_objects = 0; ClearHistograms(heap()->isolate()); LargeObjectIterator it(this); for (HeapObject* obj = it.Next(); obj != NULL; obj = it.Next()) { num_objects++; CollectHistogramInfo(obj); } PrintF(" number of objects %d, " "size of objects %" V8_PTR_PREFIX "d\n", num_objects, objects_size_); if (num_objects > 0) ReportHistogram(heap()->isolate(), false); } void LargeObjectSpace::CollectCodeStatistics() { Isolate* isolate = heap()->isolate(); LargeObjectIterator obj_it(this); for (HeapObject* obj = obj_it.Next(); obj != NULL; obj = obj_it.Next()) { if (obj->IsCode()) { Code* code = Code::cast(obj); isolate->code_kind_statistics()[code->kind()] += code->Size(); } } } void Page::Print() { // Make a best-effort to print the objects in the page. PrintF("Page@%p in %s\n", this->address(), AllocationSpaceName(this->owner()->identity())); printf(" --------------------------------------\n"); HeapObjectIterator objects(this, heap()->GcSafeSizeOfOldObjectFunction()); unsigned mark_size = 0; for (HeapObject* object = objects.Next(); object != NULL; object = objects.Next()) { bool is_marked = Marking::MarkBitFrom(object).Get(); PrintF(" %c ", (is_marked ? '!' : ' ')); // Indent a little. if (is_marked) { mark_size += heap()->GcSafeSizeOfOldObjectFunction()(object); } object->ShortPrint(); PrintF("\n"); } printf(" --------------------------------------\n"); printf(" Marked: %x, LiveCount: %x\n", mark_size, LiveBytes()); } #endif // DEBUG } } // namespace v8::internal
[ "zcy920225@gmail.com" ]
zcy920225@gmail.com
d1d5584484d4509e3a6093c41513ad351773c5fe
88f47d1e5d1adc0617d04055eaa08181c6f23777
/tests/gtest-binary-search-tree-tests.cpp
7e175501d61dcde6f5edfe80e6cb3878c58d9bc6
[ "BSD-3-Clause" ]
permissive
syedhali/data-structures-practice
de04bf5a232c8b8f899702c42a44b42a1e375de2
66e916fe177d87794eb3638757594b6741e2e5b2
refs/heads/master
2021-01-11T21:30:28.741478
2017-01-20T20:27:19
2017-01-20T20:27:19
78,794,388
1
1
null
2017-01-20T20:27:19
2017-01-12T22:54:16
C++
UTF-8
C++
false
false
4,276
cpp
// // Created by Syed Haris Ali on 1/18/17. // #include <gtest/gtest.h> #include "Tree/BinarySearchTree.h" using namespace ds::tree::binary; class BinarySearchTreeTest : public ::testing::Test { protected: Node<int> *mRootWithChildren; SearchTree *mTree; BinarySearchTreeTest() { populateChildren(); mTree = new SearchTree(); mTree->setRoot(mRootWithChildren); } ~BinarySearchTreeTest() { if (mTree != nullptr) { delete mTree; } if (mRootWithChildren != nullptr) { delete mRootWithChildren; } } void populateChildren() { Node<int> *node1 = new Node<int>(1); Node<int> *node0 = new Node<int>(0); Node<int> *node3 = new Node<int>(3); Node<int> *node2 = new Node<int>(2); Node<int> *node8 = new Node<int>(8); Node<int> *node5 = new Node<int>(5); Node<int> *node10 = new Node<int>(10); node1->setLeftChild(node0); node1->setRightChild(node3); node3->setLeftChild(node2); node3->setRightChild(node8); node8->setLeftChild(node5); node8->setRightChild(node10); mRootWithChildren = node1; } }; TEST_F(BinarySearchTreeTest, Insertion) { Node<int> *head = mTree->insert(new Node<int>(4)); ASSERT_TRUE(head != nullptr); ASSERT_EQ(head->getData(), 1); } TEST_F(BinarySearchTreeTest, Lookup) { Node<int> *node = mTree->lookup(5); ASSERT_TRUE(node != nullptr); ASSERT_EQ(node->getData(), 5); } TEST_F(BinarySearchTreeTest, LookupDoesNotExist) { Node<int> *node = mTree->lookup(1111); ASSERT_FALSE(node != nullptr); } TEST_F(BinarySearchTreeTest, Minimum) { int min = mTree->minimumValue(); ASSERT_TRUE(min != MINIMUM_VALUE_NOT_FOUND); ASSERT_EQ(min, 0); } TEST_F(BinarySearchTreeTest, Minimum2) { mTree->insert(new Node<int>(-1)); int min = mTree->minimumValue(); ASSERT_TRUE(min != MINIMUM_VALUE_NOT_FOUND); ASSERT_EQ(min, -1); } TEST_F(BinarySearchTreeTest, MinimumNotFound) { mTree->setRoot(nullptr); int min = mTree->minimumValue(); ASSERT_TRUE(min == MINIMUM_VALUE_NOT_FOUND); } TEST_F(BinarySearchTreeTest, MaximumDepth) { int maxDepth = mTree->maximumDepth(); ASSERT_EQ(maxDepth, 3); } TEST_F(BinarySearchTreeTest, NodesInRange) { std::vector<Node<int> *> nodes = mTree->nodesInRange(2, 10); ASSERT_EQ(nodes.size(), 5); } TEST_F(BinarySearchTreeTest, NodesInRangeEdgeCase) { std::vector<Node<int> *> nodes = mTree->nodesInRange(0, 0); ASSERT_EQ(nodes.size(), 1); } TEST_F(BinarySearchTreeTest, NodesInRangeEdgeCase2) { std::vector<Node<int> *> nodes = mTree->nodesInRange(13, 20); ASSERT_EQ(nodes.size(), 0); } TEST_F(BinarySearchTreeTest, IsBinaryTreeSearchTree) { bool isSearchTree = SearchTree::isBinarySearchTree(mRootWithChildren); ASSERT_TRUE(isSearchTree); } TEST_F(BinarySearchTreeTest, IsBinaryTreeSearchTree2) { bool isSearchTree = SearchTree::isBinarySearchTree(nullptr); ASSERT_TRUE(isSearchTree); } TEST_F(BinarySearchTreeTest, IsBinaryTreeSearchTree3) { Node<int> *root = new Node<int>(5); bool isSearchTree = SearchTree::isBinarySearchTree(root); ASSERT_TRUE(isSearchTree); } TEST_F(BinarySearchTreeTest, IsNotBinaryTreeSearchTree) { Node<int> *root = new Node<int>(5); Node<int> *left = new Node<int>(8); Node<int> *right = new Node<int>(10); root->setLeftChild(left); root->setRightChild(right); bool isSearchTree = SearchTree::isBinarySearchTree(root); ASSERT_FALSE(isSearchTree); } TEST_F(BinarySearchTreeTest, IsNotBinaryTreeSearchTree2) { Node<int> *root = new Node<int>(5); Node<int> *left = new Node<int>(2); Node<int> *right = new Node<int>(4); root->setLeftChild(left); root->setRightChild(right); bool isSearchTree = SearchTree::isBinarySearchTree(root); ASSERT_FALSE(isSearchTree); } TEST_F(BinarySearchTreeTest, IsNotBinaryTreeSearchTree3) { Node<int> *root = new Node<int>(5); Node<int> *left = new Node<int>(5); Node<int> *right = new Node<int>(5); root->setLeftChild(left); root->setRightChild(right); bool isSearchTree = SearchTree::isBinarySearchTree(root); ASSERT_FALSE(isSearchTree); }
[ "syedhali07@gmail.com" ]
syedhali07@gmail.com
ada312d917a4ba55acc5240220719bf1ff3fee2c
ee54e7bdf79b7ce264f0bc22d1fd78177010bf75
/cpp_tutor/函数重载.cpp
512874b833549e0be44936d68dee3a278796e5cc
[]
no_license
luningcowboy/AlgorithmPractice
985effad2d286bc09d515c73d4884f7ee48cb435
1d2cd40fe2f85edab87939feab05525134d89538
refs/heads/master
2021-09-28T01:21:19.939324
2018-11-13T05:09:42
2018-11-13T05:09:42
115,409,232
0
0
null
null
null
null
UTF-8
C++
false
false
243
cpp
#include<iostream> using namespace std; void print(const char* myString){ cout<<myString<<endl; } void print(int myInt){ cout<<myInt<<endl; } int main(int argc, char const *argv[]) { print("hello"); print(10); return 0; }
[ "luning@tuyougame.com" ]
luning@tuyougame.com
35369011c16164054dfb2be004c3b46df224da84
9be4b9a1b91b1acba724c2d5215104e352bbc93e
/node_modules/grunt-sass/node_modules/node-sass/libsass/sass_values.cpp
ac6b3afbb9fa03810e1e02423ad4b3f97c472490
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
railsgirlswgtn/intro-talk-may-2015
a824a33b2c92dd9f44bed5215584196c7208ac9d
c2ba0be6d47cb4b57a1d429491aa114f750a18a2
refs/heads/master
2020-12-30T09:26:17.110159
2015-05-15T05:10:53
2015-05-15T05:10:53
35,654,578
0
0
null
null
null
null
UTF-8
C++
false
false
2,897
cpp
#include "stdlib.h" #include "string.h" #include "sass_values.h" extern "C" { union Sass_Value make_sass_boolean(int val) { return new_sass_c_boolean(val); } union Sass_Value make_sass_number(double val) { return new_sass_c_number(val); } union Sass_Value make_sass_percentage(double val) { return new_sass_c_percentage(val); } union Sass_Value make_sass_dimension(double val, const char* unit) { return new_sass_c_dimension(val, unit); } union Sass_Value make_sass_color(double r, double g, double b, double a) { return new_sass_c_color(r, g, b, a); } union Sass_Value make_sass_string(const char* val) { return new_sass_c_string(val); } union Sass_Value make_sass_list(size_t len, enum Sass_Separator sep) { return new_sass_c_list(len, sep); } union Sass_Value make_sass_error(const char* msg) { return new_sass_c_error(msg); } } union Sass_Value new_sass_c_boolean(int val) { union Sass_Value v; v.boolean.tag = SASS_BOOLEAN; v.boolean.value = val; return v; } union Sass_Value new_sass_c_number(double val) { union Sass_Value v; v.number.tag = SASS_NUMBER; v.number.value = val; return v; } union Sass_Value new_sass_c_percentage(double val) { union Sass_Value v; v.percentage.tag = SASS_PERCENTAGE; v.percentage.value = val; return v; } union Sass_Value new_sass_c_dimension(double val, const char* unit) { union Sass_Value v; v.dimension.tag = SASS_DIMENSION; v.dimension.value = val; char* copy = (char*) malloc(sizeof(char)*(strlen(unit)+1)); strcpy(copy, unit); v.dimension.unit = copy; return v; } union Sass_Value new_sass_c_color(double r, double g, double b, double a) { union Sass_Value v; v.color.tag = SASS_COLOR; v.color.r = r; v.color.g = g; v.color.b = b; v.color.a = a; return v; } union Sass_Value new_sass_c_string(const char* val) { union Sass_Value v; v.string.tag = SASS_STRING; char* copy = (char*) malloc(sizeof(char)*(strlen(val)+1)); strcpy(copy, val); v.string.value = copy; return v; } union Sass_Value new_sass_c_list(size_t len, enum Sass_Separator sep) { union Sass_Value v; v.list.tag = SASS_LIST; v.list.separator = sep; v.list.values = (union Sass_Value*) malloc(sizeof(union Sass_Value)*len); return v; } union Sass_Value new_sass_c_error(const char* msg) { union Sass_Value v; v.error.tag = SASS_ERROR; char* copy = (char*) malloc(sizeof(char)*(strlen(msg)+1)); strcpy(copy, msg); v.error.message = copy; return v; } void free_sass_value(union Sass_Value v) { switch (v.unknown.tag) { case SASS_STRING: { free(v.string.value); v.string.value = NULL; } break; case SASS_LIST: { size_t i; for (i = 0; i < v.list.length; ++i) free_sass_value(v.list.values[i]); free(v.list.values); v.list.values = NULL; v.list.length = 0; } break; case SASS_ERROR: { free(v.error.message); v.error.message = NULL; } break; default: break; } }
[ "merrin.macleod@gmail.com" ]
merrin.macleod@gmail.com
a6570385adf9e60c2e751976b4bad64a17f23ba1
e68065baff69ae084c727c1482169006e6a51ae6
/StatTools/interface/DataCardCreatorHTT_2D.h
a2db3a0ee380bc04c3e4ae01553bf46c19e85b69
[]
no_license
isobelojalvo/PUAnalysis-1
f0d6ed502bd518c64ee0f1e4b0745a6e5edd524b
ab635a1c313ae4ff280e9eb4039733cc6ec53412
refs/heads/cmssw10_2_14_2018
2020-06-20T18:43:37.086594
2019-10-14T22:31:22
2019-10-14T22:31:22
197,211,373
0
0
null
2019-07-26T16:22:28
2019-07-16T14:37:11
C++
UTF-8
C++
false
false
96,962
h
/* Thanks to Laura Dodd: https://github.com/lmdodd/StatTools/blob/master/interface/DataCardCreatorHTT2D.h couldn't merge commit but needed this code! Modifer: Sam Higginbotham Nov 19th, 2018 */ #include "TCanvas.h" #include "TROOT.h" #include "TFile.h" #include "TTree.h" #include "TChain.h" #include "TH1.h" #include "TH2.h" #include "TF1.h" #include "PhysicsTools/FWLite/interface/CommandLineParser.h" #include <math.h> #include <boost/algorithm/string.hpp> #include "HiggsAnalysis/CombinedLimit/interface/th1fmorph.h" #include <TEfficiency.h> #include <TMath.h> #include <iostream> #include <string> #include <boost/lexical_cast.hpp> //#include "FineBins.h" struct BkgOutput { float DATA; float W, dW; float QCD, dQCD; float ZLFT, dZLFT; float ZJFT, dZJFT; float TOP, dTOP; float VV, dVV; float EWKZ, dEWKZ; float ZTT, dZTT; BkgOutput(){}; BkgOutput(float i) { // This assumes that a-d are all of the same type and all in order std::fill(&DATA, &dZTT+1, i); } }; class DataCardCreatorHTT2D { public: DataCardCreatorHTT2D(optutl::CommandLineParser parser) { channel_ = parser.stringValue("channel"); shifts_ = parser.stringVector("shifts"); energy_ = parser.stringValue("energy"); samesign_ = parser.doubleValue("samesign"); std::string name_=channel_; if (channel_=="eleTau") filelabel_="et"; if (channel_=="muTau") filelabel_="mt"; //create the name you need to add to the histograms //in the root file for(unsigned int i=0;i<shifts_.size();++i) { std::string shiftL = shifts_.at(i); shiftL.resize(1); boost::to_lower(shiftL); std::cout<<"shiftL: "<<shiftL<<std::endl; std::string chan = "mt"; if(channel_=="eleTau") chan = "et"; if (shifts_[i]=="Jet") shiftsPostFix_.push_back("CMS_scale_"+shiftL+"_"+energy_); else shiftsPostFix_.push_back("CMS_scale_"+shiftL+"_"+chan+"_"+energy_); } //read input files zttFile_ = parser.stringValue("zttFile"); zllFile_ = parser.stringValue("zllFile"); wFile_ = parser.stringValue("wFile"); vvFile_ = parser.stringValue("vvFile"); ewkFile_ = parser.stringValue("ewkFile"); topFile_ = parser.stringValue("topFile"); qcdFile_ = parser.stringValue("qcdFile"); dataFile_ = parser.stringValue("dataFile"); //read control and signal regions preSelection_ = parser.stringValue("preselection"); signalSelection_ = parser.stringValue("signalselection"); wSelection_ = parser.stringValue("wselection"); relaxedSelection_ = parser.stringValue("relaxedSelection"); trigSelection_ = parser.stringValue("trigSelection"); trigSelectionData_ = parser.stringValue("trigSelectionData"); blinding_ = parser.stringValue("blinding"); charge_ = parser.stringValue("charge"); if (samesign_) charge_="abs(charge)==2"; ZTT_genTauSel_ = "gen_match_2==5"; //Zttyield ZLFT_genLSel_ = "gen_match_2<5"; ZJFT_genLReject_ = "gen_match_2==6"; ZLL_genLLSel_ = "(gen_match_2<5||gen_match_2==6)"; //Zttyield // if(samesign_>0) osSignalSelection_ = signalSelection_+"&&abs(charge)==2"; else osSignalSelection_ = signalSelection_+"&&charge==0"; ssSignalSelection_ = signalSelection_+"&&abs(charge)==2"; if(samesign_>0) osWSelection_ = wSelection_+"&&abs(charge)==2"; else osWSelection_ = wSelection_+"&&charge==0"; ssWSelection_ = wSelection_+"&&abs(charge)==2"; verbose_ = parser.integerValue("verbose"); //read systematic uncertainties luminosity_ = parser.doubleValue("luminosity"); luminosityErr_ = parser.doubleValue("luminosityErr"); muID_ = parser.doubleValue("muID"); muIDErr_ = parser.doubleValue("muIDErr"); bID_ = parser.doubleValue("bID"); bIDErr_ = parser.doubleValue("bIDErr"); bMisID_ = parser.doubleValue("bMisID"); bMisIDErr_ = parser.doubleValue("bMisIDErr"); eleID_ = parser.doubleValue("eleID"); eleIDErr_ = parser.doubleValue("eleIDErr"); tauID_ = parser.doubleValue("tauID"); tauIDHigh_ = parser.doubleValue("tauIDHigh"); tauIDErr_ = parser.doubleValue("tauIDErr"); zttScale_ = parser.doubleValue("zttScale"); zttScaleErr_ = parser.doubleValue("zttScaleErr"); //read the basic varibale you will put in the histogram variable_ = parser.stringValue("variable"); variableUnroll_ = parser.stringValue("variableUnroll"); //read the event weight for MC and embedded weight_ = parser.stringValue("weight"); Zweight_ = parser.stringValue("Zweight"); ZUnrollweight_ = parser.stringValue("ZUnrollweight"); TTweight_ = parser.stringValue("TTweight"); embWeight_ = parser.stringValue("embWeight"); ggHWeight_ = parser.stringValue("ggHWeight"); //define the histogram binning bins_ = parser.integerValue("bins"); max_ = parser.doubleValue("max"); min_ = parser.doubleValue("min"); //Define background uncertainty Errors topErr_ = parser.doubleValue("topErr"); qcdErr_ = parser.doubleValue("qcdErr"); vvErr_ = parser.doubleValue("vvErr"); zlftErr_ = parser.doubleValue("zlftErr"); zlftFactor_ = parser.stringValue("zlftFactor"); zjftErr_ = parser.doubleValue("zjftErr"); wFactorErr_ = parser.doubleValue("wFactorErr"); qcdFactor_ = parser.doubleValue("qcdFactor"); qcdFactorErr_ = parser.doubleValue("qcdFactorErr"); bFactorZ_ = parser.doubleValue("bFactorZ"); bFactorZErr_ = parser.doubleValue("bFactorZErr"); bFactorW_ = parser.doubleValue("bFactorW"); bFactorWErr_ = parser.doubleValue("bFactorWErr"); dir_ = parser.stringValue("dir"); scaleUp_ = parser.doubleValue("scaleUp"); fout_ = new TFile(parser.stringValue("outputfile").c_str(),"RECREATE"); } void makeHiggsShape(std::string preselection, std::string categoryselection, std::string prefix) { std::pair<float,float> tmp; float legCorr=1.0; if(muID_!=0&&eleID_!=0) {legCorr*=muID_*eleID_;} if(muID_!=0&&eleID_==0) {legCorr*=muID_*tauID_;} if(muID_==0&&eleID_!=0) {legCorr*=eleID_*tauID_;} std::cout<<"Make Higgs Shape"<<std::endl; tmp= createHistogramAndShifts(dir_+"ggH120.root","ggH120","("+preselection+"&&"+categoryselection+"&&"+trigSelection_+"&&"+osSignalSelection_+")",weight_,luminosity_*legCorr*52.22*0.0698,prefix); tmp= createHistogramAndShifts(dir_+"ggH120.root","ggH120_CMS_scale_gg_13TeVUp","("+preselection+"&&"+categoryselection+"&&"+trigSelection_+"&&"+osSignalSelection_+")",weight_+"*"+ggHWeight_,luminosity_*legCorr*52.22*0.0698,prefix); tmp= createHistogramAndShifts(dir_+"ggH120.root","ggH120_CMS_scale_gg_13TeVDown","("+preselection+"&&"+categoryselection+"&&"+trigSelection_+"&&"+osSignalSelection_+")",weight_+"*(2-"+ggHWeight_+")",luminosity_*legCorr*52.22*0.0698,prefix); tmp= createHistogramAndShifts(dir_+"ggH125.root","ggH125","("+preselection+"&&"+categoryselection+"&&"+trigSelection_+"&&"+osSignalSelection_+")",weight_,luminosity_*legCorr*48.58*0.0627,prefix); tmp= createHistogramAndShifts(dir_+"ggH125.root","ggH125_CMS_scale_gg_13TeVUp","("+preselection+"&&"+categoryselection+"&&"+trigSelection_+"&&"+osSignalSelection_+")",weight_+"*"+ggHWeight_,luminosity_*legCorr*48.58*0.0627,prefix); tmp= createHistogramAndShifts(dir_+"ggH125.root","ggH125_CMS_scale_gg_13TeVDown","("+preselection+"&&"+categoryselection+"&&"+trigSelection_+"&&"+osSignalSelection_+")",weight_+"*(2-"+ggHWeight_+")",luminosity_*legCorr*48.58*0.0627,prefix); tmp= createHistogramAndShifts(dir_+"ggH130.root","ggH130","("+preselection+"&&"+categoryselection+"&&"+trigSelection_+"&&"+osSignalSelection_+")",weight_,luminosity_*legCorr*45.31*0.0541,prefix); tmp= createHistogramAndShifts(dir_+"ggH130.root","ggH130_CMS_scale_gg_13TeVUp","("+preselection+"&&"+categoryselection+"&&"+trigSelection_+"&&"+osSignalSelection_+")",weight_+"*"+ggHWeight_,luminosity_*legCorr*45.31*0.0541,prefix); tmp= createHistogramAndShifts(dir_+"ggH130.root","ggH130_CMS_scale_gg_13TeVDown","("+preselection+"&&"+categoryselection+"&&"+trigSelection_+"&&"+osSignalSelection_+")",weight_+"*(2-"+ggHWeight_+")",luminosity_*legCorr*45.31*0.0541,prefix); tmp= createHistogramAndShifts(dir_+"vbfH120.root","qqH120","("+preselection+"&&"+categoryselection+"&&"+trigSelection_+"&&"+osSignalSelection_+")",weight_,luminosity_*legCorr*3.935*0.0698,prefix); tmp= createHistogramAndShifts(dir_+"vbfH125.root","qqH125","("+preselection+"&&"+categoryselection+"&&"+trigSelection_+"&&"+osSignalSelection_+")",weight_,luminosity_*legCorr*3.782*0.0627,prefix); tmp= createHistogramAndShifts(dir_+"vbfH130.root","qqH130","("+preselection+"&&"+categoryselection+"&&"+trigSelection_+"&&"+osSignalSelection_+")",weight_,luminosity_*legCorr*3.637*0.0541,prefix); tmp= createHistogramAndShifts(dir_+"ZH120.root","ZH120","("+preselection+"&&"+categoryselection+"&&"+trigSelection_+"&&"+osSignalSelection_+")",weight_,luminosity_*legCorr*0.994*0.0698,prefix); tmp= createHistogramAndShifts(dir_+"ZH125.root","ZH125","("+preselection+"&&"+categoryselection+"&&"+trigSelection_+"&&"+osSignalSelection_+")",weight_,luminosity_*legCorr*0.884*0.0627,prefix); tmp= createHistogramAndShifts(dir_+"ZH130.root","ZH130","("+preselection+"&&"+categoryselection+"&&"+trigSelection_+"&&"+osSignalSelection_+")",weight_,luminosity_*legCorr*0.790*0.0541,prefix); tmp= createHistogramAndShifts(dir_+"WpH120.root","WH120","("+preselection+"&&"+categoryselection+"&&"+trigSelection_+"&&"+osSignalSelection_+")",weight_,luminosity_*legCorr*0.9558*0.0698,prefix); tmp= createHistogramAndShifts(dir_+"WpH125.root","WH125","("+preselection+"&&"+categoryselection+"&&"+trigSelection_+"&&"+osSignalSelection_+")",weight_,luminosity_*legCorr*0.840*0.0627,prefix); tmp= createHistogramAndShifts(dir_+"WpH130.root","WH130","("+preselection+"&&"+categoryselection+"&&"+trigSelection_+"&&"+osSignalSelection_+")",weight_,luminosity_*legCorr*0.7414*0.0541,prefix); tmp= createHistogramAndShifts(dir_+"WmH120.root","WmH120","("+preselection+"&&"+categoryselection+"&&"+trigSelection_+"&&"+osSignalSelection_+")",weight_,luminosity_*legCorr*0.6092*0.0698,prefix); tmp= createHistogramAndShifts(dir_+"WmH125.root","WmH125","("+preselection+"&&"+categoryselection+"&&"+trigSelection_+"&&"+osSignalSelection_+")",weight_,luminosity_*legCorr*0.5328*0.0627,prefix); tmp= createHistogramAndShifts(dir_+"WmH130.root","WmH130","("+preselection+"&&"+categoryselection+"&&"+trigSelection_+"&&"+osSignalSelection_+")",weight_,luminosity_*legCorr*0.4676*0.0541,prefix); std::cout<<"Made Higgs Shape"<<std::endl; addHistogram(filelabel_+prefix,"WH120","WmH120"); addHistogram(filelabel_+prefix,"WH125","WmH125"); addHistogram(filelabel_+prefix,"WH130","WmH130"); std::cout<<"Added WH samples"<<std::endl; } /*-------------Create Histograms------------------*/ /* * Run the full extrapolation in the Btag category * Needed: BtagSF, categorySelection * */ BkgOutput runFullExtrapBtag(std::string relaxedSelection, std::string wSel, std::string preSelection, std::string categorySelection_, std::string prefix, std::string zShape, float topExtrap, float zExtrap, float zExtrapErr, std::string bTagSF) { std::cout<<"======================"<<std::endl; std::cout<<"Run Full Extrapolation"<<std::endl; std::cout<<"categorySelection: "<<categorySelection_<<std::endl; //TODO: Fix this category seleciton business, should be more elegant std::string categorySelection = categorySelection_; std::string dummySelection_ = osSignalSelection_; weight_ = weight_+"*"+bTagSF; BkgOutput output; float leg1Corr=1.0; if(muID_!=0) leg1Corr*=muID_; if(eleID_!=0) leg1Corr*=eleID_; printf("Tau ID Scale Factor is %.3f \n",tauID_); std::cout<<"Select DATA"<<std::endl; //old funciton std::pair<float,float> dataY = createHistogramAndShifts(dataFile_,"data_obs","("+preSelection+"&&"+trigSelectionData_+"&&"+osSignalSelection_+"&&"+categorySelection+")",scaleUp_,prefix); //addHistogram(filelabel_+prefix,"data_obs","data_obsB") output.DATA = dataY.first; std::cout<<" DATA Yield: "<< output.DATA<<std::endl; std::cout<<" DATA Selection: "<<preSelection<<"&&"<<trigSelectionData_<<"&&"<<osSignalSelection_<<"&&"<<categorySelection<<std::endl; std::cout<<"Create DiBoson"<<std::endl; //Create Diboson std::pair<float,float> vvYield = createHistogramAndShifts(vvFile_,"VV","("+preSelection+"&&"+trigSelection_+"&&"+osSignalSelection_+"&&"+categorySelection+")",weight_,luminosity_*leg1Corr*tauID_,prefix); std::pair<float,float> vvJYield = createHistogramAndShifts(vvFile_,"VVJ","("+preSelection+"&&"+trigSelection_+"&&"+osSignalSelection_+"&&"+categorySelection+"&&gen_match_2!=5)",weight_,luminosity_*leg1Corr,prefix); std::pair<float,float> vvTYield = createHistogramAndShifts(vvFile_,"VVT","("+preSelection+"&&"+trigSelection_+"&&"+osSignalSelection_+"&&"+categorySelection+"&&gen_match_2==5)",weight_,luminosity_*leg1Corr*tauID_,prefix); std::cout<<" VV before error inflation: "<<vvYield.first<<std::endl; std::pair<float,float> vvInflYield = inflateError(vvYield,vvErr_); printf(" Diboson events in signal region = %f + %f \n",vvInflYield.first,vvInflYield.second); std::cout<<" VV after error inflation: "<<vvInflYield.first<<std::endl; output.VV = vvInflYield.first; output.dVV = vvInflYield.second; std::cout<<"Create EWKZ"<<std::endl; //Create Diboson std::pair<float,float> ewkYield = createHistogramAndShifts(ewkFile_,"EWKZ","("+preSelection+"&&"+trigSelection_+"&&"+osSignalSelection_+"&&"+categorySelection+")",weight_,luminosity_*leg1Corr*tauID_,prefix); printf(" EWKZ events before inflation = %f + %f \n",ewkYield.first,ewkYield.second); std::pair<float,float> ewkInflYield = inflateError(ewkYield,vvErr_); printf(" EWKZ events in signal region = %f + %f \n",ewkInflYield.first,ewkInflYield.second); output.EWKZ = ewkInflYield.first; output.dEWKZ = ewkInflYield.second; //Create ZL and ZJ std::cout<<"Create ZLFT"<<std::endl; //ZL Yield std::pair<float,float> zlftYield = createHistogramAndShifts(zllFile_,"ZLTmp","("+preSelection+"&&"+trigSelection_+"&&"+osSignalSelection_+"&&"+categorySelection+"&&"+ZLFT_genLSel_+")",weight_+"*"+Zweight_+"*"+zlftFactor_+"*"+ZUnrollweight_,luminosity_*leg1Corr*zttScale_,prefix); std::pair<float,float> zlftShape = createHistogramAndShifts(zllFile_,"ZL","("+preSelection+"&&"+trigSelection_+"&&"+osSignalSelection_+"&&"+categorySelection+"&&"+ZLFT_genLSel_+")",weight_+"*"+Zweight_+"*"+zlftFactor_+"*"+ZUnrollweight_,luminosity_*leg1Corr*zttScale_,prefix); std::pair<float,float> zlftShapeUp = createHistogramAndShifts(zllFile_,"ZL_CMS_htt_dyShape_13TeVUp","("+preSelection+"&&"+trigSelection_+"&&"+osSignalSelection_+"&&"+categorySelection+"&&"+ZLFT_genLSel_+")",weight_+"*"+Zweight_+"*"+Zweight_+"*"+zlftFactor_+"*"+ZUnrollweight_,luminosity_*leg1Corr*zttScale_,prefix); std::pair<float,float> zlftShapeDown = createHistogramAndShifts(zllFile_,"ZL_CMS_htt_dyShape_13TeVDown","("+preSelection+"&&"+trigSelection_+"&&"+osSignalSelection_+"&&"+categorySelection+"&&"+ZLFT_genLSel_+")",weight_+"*"+zlftFactor_+"*"+ZUnrollweight_,luminosity_*leg1Corr*zttScale_,prefix); if (prefix=="_vbf"){ std::pair<float,float> zlftZMShapeUp = createHistogramAndShifts(zllFile_,"ZL_CMS_htt_zmumuShape_VBF_13TeVUp","("+preSelection+"&&"+trigSelection_+"&&"+osSignalSelection_+"&&"+categorySelection+"&&"+ZLFT_genLSel_+")",weight_+"*"+Zweight_+"*"+zlftFactor_+"*"+ZUnrollweight_+"*"+ZUnrollweight_,luminosity_*leg1Corr*zttScale_,prefix); std::pair<float,float> zlftZMShapeDown = createHistogramAndShifts(zllFile_,"ZL_CMS_htt_zmumuShape_VBF_13TeVDown","("+preSelection+"&&"+trigSelection_+"&&"+osSignalSelection_+"&&"+categorySelection+"&&"+ZLFT_genLSel_+")",weight_+"*"+Zweight_+"*"+zlftFactor_,luminosity_*leg1Corr*zttScale_,prefix); } std::pair<float,float> zlftInflYield = inflateError(zlftYield,zlftErr_); printf(" Z (l->tau) in signal region = %f + %f \n",zlftInflYield.first,zlftInflYield.second); std::cout<<"renormalize"<<std::endl; renormalizeHistogram(filelabel_+prefix,"ZL",zlftInflYield.first); output.ZLFT = zlftInflYield.first; output.dZLFT = zlftInflYield.second; std::cout<<"create histogram shifted"<<std::endl; if(shifts_.size()>0&&channel_=="eleTau"){ std::pair<float,float> zlShiftUp = createHistogramShifted(zllFile_,"ZL_CMS_htt_ZLShape_et_13TeVUp","("+preSelection+"&&"+trigSelection_+"&&"+osSignalSelection_+"&&"+categorySelection+"&&abs(pdg2)==11&&"+ZLFT_genLSel_+")*"+weight_+"*"+Zweight_+"*"+zlftFactor_+"*"+ZUnrollweight_,"TauUp",luminosity_*leg1Corr*zttScale_*zExtrap,prefix); std::pair<float,float> zlShiftDown = createHistogramShifted(zllFile_,"ZL_CMS_htt_ZLShape_et_13TeVDown","("+preSelection+"&&"+trigSelection_+"&&"+osSignalSelection_+"&&"+categorySelection+"&&abs(pdg2)==11&&"+ZLFT_genLSel_+")*"+weight_+"*"+Zweight_+"*"+zlftFactor_+"*"+ZUnrollweight_,"TauDown",luminosity_*leg1Corr*zttScale_*zExtrap,prefix); } else if(shifts_.size()>0&&channel_=="muTau"){ std::pair<float,float> zlShiftUp = createHistogramShifted(zllFile_,"ZL_CMS_htt_ZLShape_mt_13TeVUp","("+preSelection+"&&"+trigSelection_+"&&"+osSignalSelection_+"&&"+categorySelection+"&&abs(pdg2)==13&&"+ZLFT_genLSel_+")*"+weight_+"*"+Zweight_+"*"+zlftFactor_+"*"+ZUnrollweight_,"TauUp",luminosity_*leg1Corr*zttScale_*zExtrap,prefix); std::pair<float,float> zlShiftDown = createHistogramShifted(zllFile_,"ZL_CMS_htt_ZLShape_mt_13TeVDown","("+preSelection+"&&"+trigSelection_+"&&"+osSignalSelection_+"&&"+categorySelection+"&&abs(pdg2)==13&&"+ZLFT_genLSel_+")*"+weight_+"*"+Zweight_+"*"+zlftFactor_+"*"+ZUnrollweight_,"TauDown",luminosity_*leg1Corr*zttScale_*zExtrap,prefix); } std::cout<<"Create ZJFT"<<std::endl; //ZJ Yield std::pair<float,float> zjftYield = createHistogramAndShifts(zllFile_,"ZJTmp","("+preSelection+"&&"+trigSelection_+"&&"+osSignalSelection_+"&&"+categorySelection+"&&"+ZJFT_genLReject_+")",weight_+"*"+Zweight_+"*"+ZUnrollweight_,luminosity_*leg1Corr*zttScale_,prefix); //ZJ Shape std::pair<float,float> zjftShape = createHistogramAndShifts(zllFile_,"ZJ","("+preSelection+"&&"+trigSelection_+"&&"+osSignalSelection_+"&&"+categorySelection+"&&"+ZJFT_genLReject_+")",weight_+"*"+Zweight_+"*"+ZUnrollweight_,luminosity_*leg1Corr*zttScale_,prefix); std::pair<float,float> zjftShapeUp = createHistogramAndShifts(zllFile_,"ZJ_CMS_htt_dyShape_13TeVUp","("+preSelection+"&&"+trigSelection_+"&&"+osSignalSelection_+"&&"+categorySelection+"&&"+ZJFT_genLReject_+")",weight_+"*"+Zweight_+"*"+Zweight_+"*"+ZUnrollweight_,luminosity_*leg1Corr*zttScale_,prefix); std::pair<float,float> zjftShapeDown = createHistogramAndShifts(zllFile_,"ZJ_CMS_htt_dyShape_13TeVDown","("+preSelection+"&&"+trigSelection_+"&&"+osSignalSelection_+"&&"+categorySelection+"&&"+ZJFT_genLReject_+")",weight_+"*"+ZUnrollweight_,luminosity_*leg1Corr*zttScale_,prefix); std::pair<float,float> zjftFTShapeUp = createHistogramAndShifts(zllFile_,"ZJ_CMS_htt_jetToTauFake_13TeVUp","("+preSelection+"&&"+trigSelection_+"&&"+osSignalSelection_+"&&"+categorySelection+"&&"+ZJFT_genLReject_+")",weight_+"*"+Zweight_+"*"+ZUnrollweight_+"*fakeTauEffiUp",luminosity_*leg1Corr*zttScale_,prefix); std::pair<float,float> zjftFTShapeDown = createHistogramAndShifts(zllFile_,"ZJ_CMS_htt_jetToTauFake_13TeVDown","("+preSelection+"&&"+trigSelection_+"&&"+osSignalSelection_+"&&"+categorySelection+"&&"+ZJFT_genLReject_+")",weight_+"*"+Zweight_+"*"+ZUnrollweight_+"*fakeTauEffiDown",luminosity_*leg1Corr*zttScale_,prefix); // if (prefix=="_vbf"){ std::pair<float,float> zjftZMShapeUp = createHistogramAndShifts(zttFile_,"ZJ_CMS_htt_zmumuShape_VBF_13TeVUp","("+preSelection+"&&"+trigSelection_+"&&"+osSignalSelection_+"&&"+categorySelection+"&&"+ZJFT_genLReject_+")",weight_+"*"+Zweight_+"*"+ZUnrollweight_+"*"+ZUnrollweight_,luminosity_*leg1Corr*zttScale_,prefix); std::pair<float,float> zjftZMShapeDown = createHistogramAndShifts(zttFile_,"ZJ_CMS_htt_zmumuShape_VBF_13TeVDown","("+preSelection+"&&"+trigSelection_+"&&"+osSignalSelection_+"&&"+categorySelection+"&&"+ZJFT_genLReject_+")",weight_+"*"+Zweight_,luminosity_*leg1Corr*zttScale_,prefix); } std::pair<float,float> zjftInflYield = inflateError(zjftYield,zjftErr_); printf(" Z (j->tau) in signal region = %f + %f \n",zjftInflYield.first,zjftInflYield.second); renormalizeHistogram(filelabel_+prefix,"ZJ",zjftInflYield.first); renormalizeHistogram(filelabel_+prefix,"ZJ_CMS_htt_jetToTauFake_13TeVUp",zjftInflYield.first); renormalizeHistogram(filelabel_+prefix,"ZJ_CMS_htt_jetToTauFake_13TeVDown",zjftInflYield.first); output.ZJFT = zjftInflYield.first; output.dZJFT = zjftInflYield.second; std::cout<<"Create ZTT"<<std::endl; //TODO: Check me, previous Btag ZTT shape correction had a special normalization method if(!runZTT(preSelection, prefix, zShape, topExtrap, output, categorySelection)){ std::cout<<"Error Creating Ztt"<<std::endl; return output; } std::cout<<"Create TOP"<<std::endl; //Create ttbar //Last argument is a dummy argument if(!runTOP(preSelection, prefix, zShape, topExtrap, output, categorySelection, relaxedSelection)){ std::cout<<"Error Creating TOP"<<std::endl; return output; } std::cout<<"Create W"<<std::endl; //Create W if(!runW(preSelection, prefix, zShape, topExtrap, output, categorySelection, relaxedSelection, wSel)){ std::cout<<"Error Creating W"<<std::endl; return output; } std::cout<<"Create QCD"<<std::endl; //Create QCD if(!runQCD(preSelection, prefix, zShape, topExtrap, output, categorySelection, relaxedSelection)){ std::cout<<"Error Creating QCD"<<std::endl; return output; } //FixNegativeBins(filelabel_+prefix,"QCD",false); //FixNegativeBinsMC(filelabel_+prefix,"W",false); //FixNegativeBinsMC(filelabel_+prefix,"TOP",false); //FixNegativeBinsMC(filelabel_+prefix,"VV",false); //FixNegativeBinsMC(filelabel_+prefix,"ZL",false); //FixNegativeBinsMC(channel_+prefix,"ZJ",false); //FixNegativeBinsMC(channel_+prefix,"ZTT",false); //FixNegativeBinsMC(channel_+prefix,"EWKZ",false); std::cout<<std::endl; std::cout<<"=============Data Yields============="<<std::endl; std::cout<<"DATA: "<< output.DATA<<std::endl; std::cout<<std::endl; std::cout<<std::endl; std::cout<<"BKGD Yields "<<std::endl; std::cout<<"QCD: "<< output.QCD<<std::endl; std::cout<<"W: "<< output.W<<std::endl; std::cout<<"TOP: "<< output.TOP<<std::endl; std::cout<<"VV: "<< output.VV<<std::endl; std::cout<<"EWKZ: "<< output.EWKZ<<std::endl; std::cout<<"ZLFT: "<< output.ZLFT<<std::endl; std::cout<<"ZJFT: "<< output.ZJFT<<std::endl; std::cout<<"ZTT: "<< output.ZTT<<std::endl; float background = output.QCD + output.W + output.TOP + output.VV + output.ZLFT + output.ZJFT + output.ZTT; float backgroundErr = sqrt( pow(output.dQCD,2) + pow(output.dW,2) + pow(output.dTOP,2) + pow(output.dVV,2) + pow(output.dZLFT,2) + pow(output.dZJFT,2) + pow(output.dZTT,2)); printf("BACKGROUND=%f +-%f \n",background,backgroundErr); ///LATEX->Here since we want it for the note add all errors , even those that will go separate in the datacard //printf("LATEX ------------------------------------\n"); //printf("Total & %.2f & %.2f & %.2f & %.2f \\\\ \n", dataYield.first, dataYieldSdb.first, dataSSYield.first, dataSSYieldSdb.first); //printf("Di-Boson & %.2f $\\pm$ %.2f & %.2f $\\pm$ %.2f & - & - \\\\ \n", vvInflYield.first, quadrature(vvInflYield.first,vvInflYield.second,muIDErr_,eleIDErr_,zttScaleErr_,tauIDErr_), vvInflYieldSdb.first, quadrature(vvInflYieldSdb.first,vvInflYieldSdb.second,muIDErr_,eleIDErr_,tauIDErr_)); //printf("$t\\bar{t}$ & %.2f $\\pm$ %.2f & %.2f $\\pm$ %.2f & - & - \\\\ \n", topInflYield.first,quadrature(topInflYield.first,topInflYield.second,muIDErr_,eleIDErr_,tauIDErr_), topInflYieldSdb.first, quadrature(topInflYieldSdb.first,topInflYield.second,muIDErr_,eleIDErr_,tauIDErr_)); //printf("$Z^{l+jet}$ & %.2f $\\pm$ %.2f & - & %.2f $\\pm$ %.2f & - \\\\ \n", zjftInflYield.first, quadrature(zjftInflYield.first,zjftInflYield.second,muIDErr_,eleIDErr_,zttScaleErr_), zjftInflSSYield.first,quadrature(zjftInflSSYield.first,zjftInflSSYield.second,muIDErr_,eleIDErr_,zttScaleErr_)); //printf("$Z^{ll}$ & %.2f $\\pm$ %.2f & - & %.2f $\\pm$ %.2f & - \\\\ \n", zlftInflYield.first, quadrature(zlftInflYield.first,zlftInflYield.second,muIDErr_,eleIDErr_,zttScaleErr_),zlftInflSSYield.first,quadrature(zlftInflSSYield.first,zlftInflSSYield.second,muIDErr_,eleIDErr_,zttScaleErr_)); //printf("$W+jets$ & %.2f $\\pm$ %.2f & %.2f $\\pm$ %.2f & %.2f $\\pm$ %.2f & %.2f $\\pm$ %.2f \\\\ \n", osWLow.first, osWLow.second, osWHigh.first, osWHigh.second, ssWLow.first, ssWLow.second, dataSSYieldSdb.first, dataSSYieldSdb.second); //printf("QCD & %.2f $\\pm$ %.2f & - & %.2f $\\pm$ %.2f & - \\\\ \n", osQCD.first, osQCD.second, ssQCD.first, ssQCD.second); //printf("$Z\\rightarrow\\tau\\tau$ & %.2f $\\pm$ %.2f & - & - & - \\\\ \n", zttYield.first,quadrature(zttYield.first,zttYield.second,muIDErr_,eleIDErr_,zttScaleErr_,tauIDErr_)); float fullBackgroundErr = sqrt(pow(quadrature(output.VV,output.dVV,muIDErr_,eleIDErr_,zttScaleErr_,tauIDErr_),2) +pow(quadrature(output.TOP,output.dTOP,muIDErr_,eleIDErr_,tauIDErr_),2) +pow(quadrature(output.ZJFT,output.dZJFT,muIDErr_,eleIDErr_,zttScaleErr_),2) +pow(quadrature(output.ZLFT,output.dZLFT,muIDErr_,eleIDErr_,zttScaleErr_),2) +pow(output.dQCD,2) +pow(output.dW,2) +pow(quadrature(output.ZTT,output.dZTT,muIDErr_,eleIDErr_,zttScaleErr_,tauIDErr_),2)); printf("Total Background & %.2f $\\pm$ %.2f & - & - & - \\\\ \n",background,sqrt(pow(quadrature(output.VV, output.dVV, muIDErr_,eleIDErr_,zttScaleErr_,tauIDErr_),2) +pow(quadrature(output.TOP, output.dTOP, muIDErr_,eleIDErr_,tauIDErr_),2) +pow(quadrature(output.ZJFT, output.dZJFT, muIDErr_,eleIDErr_,zttScaleErr_),2) +pow(quadrature(output.ZLFT, output.dZLFT, muIDErr_,eleIDErr_,zttScaleErr_),2) +pow(output.dQCD,2) +pow(output.dW,2) +pow(quadrature(output.ZTT,output.dZTT,muIDErr_,eleIDErr_,zttScaleErr_,tauIDErr_),2))); //create a histogram with the error for plotting reasons and only TH1F *err = new TH1F("BKGErr","",1,0,1); err->SetBinContent(1,fullBackgroundErr/background); fout_->cd((filelabel_+prefix).c_str()); err->Write(); return output; } /* * For Inclusive take the Ztt normalization directly from MC (zttFile_) * For a category the Ztt normalization is as follows, * ZttCategoryYield = ZttMCInclusiveYield * (ZttEmbedded_Category) / *Ztt( */ bool runZTT(std::string preSelection,std::string prefix,std::string zShape, float topExtrap, BkgOutput &output, std::string categorySelection = "pt_1>-100", std::string relaxedSelection = "pt_1>-100"){ float leg1Corr=1.0; if(muID_!=0) leg1Corr*=muID_; if(eleID_!=0) leg1Corr*=eleID_; std::pair<float,float> ztt = createHistogramAndShifts(zttFile_,"ZTT","("+preSelection+"&&"+trigSelection_+"&&"+osSignalSelection_+"&&"+categorySelection+"&&"+ZTT_genTauSel_+")",weight_+"*"+Zweight_+"*"+ZUnrollweight_,luminosity_*zttScale_*leg1Corr*tauID_,prefix); std::pair<float,float> zttDyUp = createHistogramAndShifts(zttFile_,"ZTT_CMS_htt_dyShape_13TeVUp","("+preSelection+"&&"+trigSelection_+"&&"+osSignalSelection_+"&&"+categorySelection+"&&"+ZTT_genTauSel_+")",weight_+"*"+Zweight_+"*"+Zweight_+"*"+ZUnrollweight_,luminosity_*zttScale_*leg1Corr*tauID_,prefix); std::pair<float,float> zttDyDown = createHistogramAndShifts(zttFile_,"ZTT_CMS_htt_dyShape_13TeVDown","("+preSelection+"&&"+trigSelection_+"&&"+osSignalSelection_+"&&"+categorySelection+"&&"+ZTT_genTauSel_+")",weight_,luminosity_*zttScale_*leg1Corr*tauID_,prefix); if (prefix=="_vbf"){ std::pair<float,float> zttZMShapeUp = createHistogramAndShifts(zttFile_,"ZTT_CMS_htt_zmumuShape_VBF_13TeVUp","("+preSelection+"&&"+trigSelection_+"&&"+osSignalSelection_+"&&"+categorySelection+"&&"+ZTT_genTauSel_+")",weight_+"*"+Zweight_+"*"+ZUnrollweight_+"*"+ZUnrollweight_,luminosity_*leg1Corr*zttScale_,prefix); std::pair<float,float> zttZMShapeDown = createHistogramAndShifts(zttFile_,"ZTT_CMS_htt_zmumuShape_VBF_13TeVDown","("+preSelection+"&&"+trigSelection_+"&&"+osSignalSelection_+"&&"+categorySelection+"&&"+ZTT_genTauSel_+")",weight_+"*"+Zweight_,luminosity_*leg1Corr*zttScale_,prefix); } std::cout<<" ZTT Selection: "<<preSelection<<"&&"<<trigSelection_<<"&&"<<osSignalSelection_<<"&&"<<categorySelection<<std::endl; output.ZTT = ztt.first; output.dZTT = ztt.second; printf(" Selection ZTT events in signal region = %f + %f \n",ztt.first,ztt.second); return true; } bool runTOP( std::string preSelection, std::string prefix, std::string zShape, float topExtrap, BkgOutput &output, std::string categorySelection, std::string relaxedSelection ) { std::string genTauSel_="gen_match_2==5"; std::string genTauRej_="gen_match_2!=5"; float leg1Corr=1.0; if(muID_!=0) leg1Corr*=muID_; if(eleID_!=0) leg1Corr*=eleID_; std::pair<float,float> topShape = createHistogramAndShifts(topFile_,"TT","("+preSelection+"&&"+trigSelection_+"&&"+osSignalSelection_+"&&"+categorySelection+")",weight_+"*"+TTweight_, luminosity_*leg1Corr*tauID_*topExtrap, prefix); std::pair<float,float> topShapeUp = createHistogramAndShifts(topFile_,"TT_CMS_htt_ttbarShape_13TeVUp","("+preSelection+"&&"+trigSelection_+"&&"+osSignalSelection_+"&&"+categorySelection+")",weight_+"*"+TTweight_+"*"+TTweight_, luminosity_*leg1Corr*tauID_*topExtrap, prefix); std::pair<float,float> topShapeDown = createHistogramAndShifts(topFile_,"TT_CMS_htt_ttbarShape_13TeVDown","("+preSelection+"&&"+trigSelection_+"&&"+osSignalSelection_+"&&"+categorySelection+")",weight_, luminosity_*leg1Corr*tauID_*topExtrap, prefix); std::pair<float,float> topJShape = createHistogramAndShifts(topFile_,"TTJ","("+preSelection+"&&"+trigSelection_+"&&"+osSignalSelection_+"&&"+categorySelection+"&&"+genTauRej_+")",weight_+"*"+TTweight_, luminosity_*leg1Corr*topExtrap, prefix); std::pair<float,float> topJShapeUp = createHistogramAndShifts(topFile_,"TTJ_CMS_htt_ttbarShape_13TeVUp","("+preSelection+"&&"+trigSelection_+"&&"+osSignalSelection_+"&&"+categorySelection+"&&"+genTauRej_+")",weight_+"*"+TTweight_+"*"+TTweight_, luminosity_*leg1Corr*topExtrap, prefix); std::pair<float,float> topJShapeDown = createHistogramAndShifts(topFile_,"TTJ_CMS_htt_ttbarShape_13TeVDown","("+preSelection+"&&"+trigSelection_+"&&"+osSignalSelection_+"&&"+categorySelection+"&&"+genTauRej_+")",weight_, luminosity_*leg1Corr*topExtrap, prefix); std::pair<float,float> topJFTShapeUp = createHistogramAndShifts(topFile_,"TTJ_CMS_htt_jetToTauFake_13TeVUp","("+preSelection+"&&"+trigSelection_+"&&"+osSignalSelection_+"&&"+categorySelection+"&&"+genTauRej_+")",weight_+"*"+TTweight_+"*fakeTauEffiUp", luminosity_*leg1Corr*topExtrap, prefix); std::pair<float,float> topJFTShapeDown = createHistogramAndShifts(topFile_,"TTJ_CMS_htt_jetToTauFake_13TeVDown","("+preSelection+"&&"+trigSelection_+"&&"+osSignalSelection_+"&&"+categorySelection+"&&"+genTauRej_+")",weight_+"*"+TTweight_+"*fakeTauEffiDown", luminosity_*leg1Corr*topExtrap, prefix); renormalizeHistogram(filelabel_+prefix,"TTJ_CMS_htt_jetToTauFake_13TeVUp",topJShape.first); renormalizeHistogram(filelabel_+prefix,"TTJ_CMS_htt_jetToTauFake_13TeVDown",topJShape.first); std::pair<float,float> topTShape = createHistogramAndShifts(topFile_,"TTT","("+preSelection+"&&"+trigSelection_+"&&"+osSignalSelection_+"&&"+categorySelection+"&&"+genTauSel_+")",weight_+"*"+TTweight_, luminosity_*leg1Corr*tauID_*topExtrap, prefix); std::pair<float,float> topTShapeUp = createHistogramAndShifts(topFile_,"TTT_CMS_htt_ttbarShape_13TeVUp","("+preSelection+"&&"+trigSelection_+"&&"+osSignalSelection_+"&&"+categorySelection+"&&"+genTauSel_+")",weight_+"*"+TTweight_+"*"+TTweight_, luminosity_*leg1Corr*tauID_*topExtrap, prefix); std::pair<float,float> topTShapeDown = createHistogramAndShifts(topFile_,"TTT_CMS_htt_ttbarShape_13TeVDown","("+preSelection+"&&"+trigSelection_+"&&"+osSignalSelection_+"&&"+categorySelection+"&&"+genTauSel_+")",weight_, luminosity_*leg1Corr*tauID_*topExtrap, prefix); std::pair<float,float> topYield = createHistogramAndShifts(topFile_,"TTYield","("+preSelection+"&&"+trigSelection_+"&&"+osSignalSelection_+"&&"+categorySelection+")",weight_+"*"+TTweight_, luminosity_*leg1Corr*tauID_*topExtrap, prefix); std::pair<float,float> topInflYield = inflateError(topYield,topErr_); output.TOP = topInflYield.first; output.dTOP = topInflYield.second; //Subtract the ztt ttbar overlap of 1.5% from the ttbar yield //not used for 2014 MSSM //output.TOP = output.TOP-(output.ZTT*0.015); //only for renormalizeHistogram(filelabel_+prefix,"TT",output.TOP); printf(" TTbar events in signal region = %f + %f \n",topInflYield.first,topInflYield.second); return true;} bool runQCD(std::string preSelection, std::string prefix, std::string zShape, float topExtrap, BkgOutput &output, std::string categorySelection, std::string relaxedSelection) { float leg1Corr=1.0; if(muID_!=0) leg1Corr*=muID_; if(eleID_!=0) leg1Corr*=eleID_; std::string chan = "mt"; if(channel_ == "eleTau") chan = "et"; std::pair<float,float> dataQCDShape = createHistogramAndShiftsQCD(dataFile_,"QCD","("+relaxedSelection+"&&"+trigSelectionData_+"&&"+ssSignalSelection_+"&&"+categorySelection+")",scaleUp_,prefix); std::pair<float,float> dataQCDShapeUp = createHistogramAndShifts(dataFile_,"QCD_WSFUncert_"+chan+prefix+"_13TeVUp","("+relaxedSelection+"&&"+trigSelectionData_+"&&"+ssSignalSelection_+"&&"+categorySelection+")",scaleUp_,prefix); std::pair<float,float> dataQCDShapeDown = createHistogramAndShifts(dataFile_,"QCD_WSFUncert_"+chan+prefix+"_13TeVDown","("+relaxedSelection+"&&"+trigSelectionData_+"&&"+ssSignalSelection_+"&&"+categorySelection+")",scaleUp_,prefix); printf(" Data events in SS Signal QCDShape sideband region = %f + %f \n",dataQCDShape.first,dataQCDShape.second); std::pair<float,float> ZQCDShape = createHistogramAndShifts(zttFile_,"ZQCD","("+relaxedSelection+"&&"+trigSelection_+"&&"+ssSignalSelection_+"&&"+categorySelection+")",weight_+"*"+Zweight_+"*"+ZUnrollweight_,luminosity_,prefix); printf(" Z events in SS Signal QCDShape sideband region = %f + %f \n",ZQCDShape.first,ZQCDShape.second); std::pair<float,float> TopQCDShape = createHistogramAndShifts(topFile_,"TopQCD","("+relaxedSelection+"&&"+trigSelection_+"&&"+ssSignalSelection_+"&&"+categorySelection+")",weight_+"*"+TTweight_,luminosity_,prefix); printf(" TOP events in SS Signal QCDShape sideband region = %f + %f \n",TopQCDShape.first,TopQCDShape.second); std::pair<float,float> VVQCDShape = createHistogramAndShifts(vvFile_,"VVQCD","("+relaxedSelection+"&&"+trigSelection_+"&&"+ssSignalSelection_+"&&"+categorySelection+")",weight_,luminosity_,prefix); printf(" VV events in SS Signal QCDShape sideband region = %f + %f \n",VVQCDShape.first,VVQCDShape.second); std::pair<float,float> WQCDLowShape = createHistogramAndShifts(wFile_,"WQCD","("+relaxedSelection+"&&"+trigSelection_+"&&"+ssSignalSelection_+"&&"+categorySelection+")",weight_,luminosity_*leg1Corr*wFactorQCD_,prefix); std::pair<float,float> WQCDLowShapeUp = createHistogramAndShifts(wFile_,"WQCDUp","("+relaxedSelection+"&&"+trigSelection_+"&&"+ssSignalSelection_+"&&"+categorySelection+")",weight_,luminosity_*leg1Corr*(wFactorQCD_+wFactorErr_),prefix); std::pair<float,float> WQCDLowShapeDown = createHistogramAndShifts(wFile_,"WQCDDown","("+relaxedSelection+"&&"+trigSelection_+"&&"+ssSignalSelection_+"&&"+categorySelection+")",weight_,luminosity_*leg1Corr*(wFactorQCD_-wFactorErr_),prefix); //CHECKME add scaling to W printf(" W events in SS Signal QCDShape sideband region = %f*%f =%f + %f \n",WQCDLowShape.first/wFactorQCD_,wFactorQCD_,WQCDLowShape.first,WQCDLowShape.second); std::cout<<"QCD Selections= "<<"("<<relaxedSelection<<"&&"<<trigSelectionData_<<"&&"<<ssSignalSelection_<<")"<<std::endl; std::pair<float,float> dataQCD = createHistogramAndShifts(dataFile_,"QCDYield","("+preSelection+"&&"+trigSelectionData_+"&&"+ssSignalSelection_+"&&"+categorySelection+")",scaleUp_,prefix); std::pair<float,float> dataQCDUp = createHistogramAndShifts(dataFile_,"QCDYieldUp","("+preSelection+"&&"+trigSelectionData_+"&&"+ssSignalSelection_+"&&"+categorySelection+")",scaleUp_,prefix); std::pair<float,float> dataQCDDown = createHistogramAndShifts(dataFile_,"QCDYieldDown","("+preSelection+"&&"+trigSelectionData_+"&&"+ssSignalSelection_+"&&"+categorySelection+")",scaleUp_,prefix); printf(" Data events in SS Signal QCD sideband region = %f + %f \n",dataQCD.first,dataQCD.second); std::pair<float,float> ZQCD = createHistogramAndShifts(zttFile_,"ZQCDYield","("+preSelection+"&&"+trigSelection_+"&&"+ssSignalSelection_+"&&"+categorySelection+")",weight_+"*"+Zweight_+"*"+ZUnrollweight_,luminosity_,prefix); printf(" Z events in SS Signal QCD sideband region = %f + %f \n",ZQCD.first,ZQCD.second); std::pair<float,float> TopQCD = createHistogramAndShifts(topFile_,"TopQCDYield","("+preSelection+"&&"+trigSelection_+"&&"+ssSignalSelection_+"&&"+categorySelection+")",weight_+"*"+TTweight_,luminosity_,prefix); printf(" TOP events in SS Signal QCD sideband region = %f + %f \n",TopQCD.first,TopQCD.second); std::pair<float,float> VVQCD = createHistogramAndShifts(vvFile_,"VVQCDYield","("+preSelection+"&&"+trigSelection_+"&&"+ssSignalSelection_+"&&"+categorySelection+")",weight_,luminosity_,prefix); printf(" VV events in SS Signal QCD sideband region = %f + %f \n",VVQCD.first,VVQCD.second); //CHECK std::pair<float,float> ssWLow = createHistogramAndShifts(wFile_,"WQCDYield","("+preSelection+"&&"+trigSelection_+"&&"+ssSignalSelection_+"&&"+categorySelection+")",weight_,luminosity_*leg1Corr,prefix); std::pair<float,float> ssWLowUp = createHistogramAndShifts(wFile_,"WQCDYieldUp","("+preSelection+"&&"+trigSelection_+"&&"+ssSignalSelection_+"&&"+categorySelection+")",weight_,luminosity_*leg1Corr*(1+wFactorErr_),prefix); std::pair<float,float> ssWLowDown = createHistogramAndShifts(wFile_,"WQCDYieldDown","("+preSelection+"&&"+trigSelection_+"&&"+ssSignalSelection_+"&&"+categorySelection+")",weight_,luminosity_*leg1Corr*(1-wFactorErr_),prefix); printf(" (MonteCarlo) W events in SS region = %f + %f \n",ssWLow.first,ssWLow.second); /* * DATADRIVEN W FOUND */ subtractHistogramShifts(filelabel_+prefix,"QCD","ZQCD"); subtractHistogramShifts(filelabel_+prefix,"QCD","VVQCD"); subtractHistogramShifts(filelabel_+prefix,"QCD","TopQCD"); subtractHistogramShifts(filelabel_+prefix,"QCD","WQCD"); //Now subtracting off bkgd shapes from data ss shape //iWSF subtractHistogram(filelabel_+prefix,"QCD_WSFUncert_"+chan+prefix+"_13TeVUp","ZQCD"); subtractHistogram(filelabel_+prefix,"QCD_WSFUncert_"+chan+prefix+"_13TeVUp","VVQCD"); subtractHistogram(filelabel_+prefix,"QCD_WSFUncert_"+chan+prefix+"_13TeVUp","TopQCD"); subtractHistogram(filelabel_+prefix,"QCD_WSFUncert_"+chan+prefix+"_13TeVUp","WQCDUp"); subtractHistogram(filelabel_+prefix,"QCD_WSFUncert_"+chan+prefix+"_13TeVDown","ZQCD"); subtractHistogram(filelabel_+prefix,"QCD_WSFUncert_"+chan+prefix+"_13TeVDown","VVQCD"); subtractHistogram(filelabel_+prefix,"QCD_WSFUncert_"+chan+prefix+"_13TeVDown","TopQCD"); subtractHistogram(filelabel_+prefix,"QCD_WSFUncert_"+chan+prefix+"_13TeVDown","WQCDDown"); std::pair<float,float> ssQCD = std::make_pair(TMath::Nint(dataQCD.first -ssWLow.first -TopQCD.first -VVQCD.first -ZQCD.first), sqrt(dataQCD.second*dataQCD.second +ssWLow.second*ssWLow.second +TopQCD.second*TopQCD.second +VVQCD.second*VVQCD.second +ZQCD.second*ZQCD.second)); std::pair<float,float> ssQCDUp = std::make_pair(TMath::Nint(dataQCD.first -ssWLowUp.first -TopQCD.first -VVQCD.first -ZQCD.first), sqrt(dataQCD.second*dataQCD.second +ssWLowUp.second*ssWLowUp.second +TopQCD.second*TopQCD.second +VVQCD.second*VVQCD.second +ZQCD.second*ZQCD.second)); std::pair<float,float> ssQCDDown = std::make_pair(TMath::Nint(dataQCD.first -ssWLowDown.first -TopQCD.first -VVQCD.first -ZQCD.first), sqrt(dataQCD.second*dataQCD.second +ssWLowDown.second*ssWLowDown.second +TopQCD.second*TopQCD.second +VVQCD.second*VVQCD.second +ZQCD.second*ZQCD.second)); if(ssQCD.first<0) { ssQCD.first=0.0000001; ssQCD.second=1.2; ssQCDUp.first=0.0000001; ssQCDUp.second=1.2; ssQCDDown.first=0.0000001; ssQCDDown.second=1.2; } printf("SS QCD in core =%f -%f -%f -%f -%f= %f +- %f \n", dataQCD.first, ssWLow.first, TopQCD.first, ZQCD.first, VVQCD.first, ssQCD.first, ssQCD.second); printf("5. Extrapolate SS QCD -> OS QCD \n"); std::pair<float,float> osQCD = std::make_pair(ssQCD.first*qcdFactor_, sqrt(ssQCD.second*ssQCD.second*qcdFactor_*qcdFactor_ +qcdFactorErr_*qcdFactorErr_*ssQCD.first*ssQCD.first)); std::pair<float,float> osQCDUp = std::make_pair(ssQCDUp.first*qcdFactor_, sqrt(ssQCDUp.second*ssQCDUp.second*qcdFactor_*qcdFactor_ +qcdFactorErr_*qcdFactorErr_*ssQCDUp.first*ssQCDUp.first)); std::pair<float,float> osQCDDown = std::make_pair(ssQCDDown.first*qcdFactor_, sqrt(ssQCDDown.second*ssQCDDown.second*qcdFactor_*qcdFactor_ +qcdFactorErr_*qcdFactorErr_*ssQCDDown.first*ssQCDDown.first)); //Now Renormalize renormalizeHistogram(filelabel_+prefix,"QCD",osQCD.first); renormalizeHistogram(filelabel_+prefix,"QCD_CMS_scale_j_13TeVUp",osQCD.first); renormalizeHistogram(filelabel_+prefix,"QCD_CMS_scale_j_13TeVDown",osQCD.first); renormalizeHistogram(filelabel_+prefix,"QCD_CMS_scale_t_"+chan+"_13TeVUp",osQCD.first); renormalizeHistogram(filelabel_+prefix,"QCD_CMS_scale_t_"+chan+"_13TeVDown",osQCD.first); //renormalizeHistogram(filelabel_+prefix,"QCD_WSFUncert_"+chan+prefix+"_13TeVUp",osQCDUp.first); //renormalizeHistogram(filelabel_+prefix,"QCD_WSFUncert_"+chan+prefix+"_13TeVDown",osQCDDown.first); renormalizeHistogram(filelabel_+prefix,"QCD_WSFUncert_"+chan+prefix+"_13TeVUp",osQCD.first); renormalizeHistogram(filelabel_+prefix,"QCD_WSFUncert_"+chan+prefix+"_13TeVDown",osQCD.first); printf("OS QCD in core =%f *%f = %f +- %f \n",ssQCD.first,qcdFactor_,osQCD.first,osQCD.second); output.QCD = osQCD.first; output.dQCD = osQCD.second; if(shifts_.size()>0){ qcdSyst(filelabel_, prefix, "QCD", 1.0, qcdFactorErr_); } return true; } bool runW(std::string preSelection,std::string prefix,std::string zShape, float topExtrap, BkgOutput &output, std::string categorySelection, std::string relaxedSelection, std::string wSel) { std::string chan = "mt"; if(channel_ == "eleTau") chan = "et"; float leg1Corr=1.0; if(muID_!=0) leg1Corr*=muID_; if(eleID_!=0) leg1Corr*=eleID_; //tempt yield std::pair<float,float> wYield = createHistogramAndShifts(wFile_,"WMC","("+preSelection+"&&"+trigSelection_+"&&"+osSignalSelection_+"&&"+categorySelection+")",weight_,luminosity_*leg1Corr,prefix); std::pair<float,float> wShape = createHistogramAndShifts(wFile_,"W","("+relaxedSelection+"&&"+trigSelection_+"&&"+osSignalSelection_+"&&"+categorySelection+")",weight_,luminosity_*leg1Corr,prefix); std::pair<float,float> wShapeFTUp = createHistogramAndShifts(wFile_,"W_CMS_htt_jetToTauFake_13TeVUp","("+relaxedSelection+"&&"+trigSelection_+"&&"+osSignalSelection_+"&&"+categorySelection+")",weight_+"*fakeTauEffiUp",luminosity_*leg1Corr,prefix); std::pair<float,float> wShapeFTDown = createHistogramAndShifts(wFile_,"W_CMS_htt_jetToTauFake_13TeVDown","("+relaxedSelection+"&&"+trigSelection_+"&&"+osSignalSelection_+"&&"+categorySelection+")",weight_+"*fakeTauEffiDown",luminosity_*leg1Corr,prefix); //std::pair<float,float> wShapeFTUp = createHistogramAndShifts(wFile_,"W_CMS_htt_jetToTauFake_13TeVUp","("+relaxedSelection+"&&"+trigSelection_+"&&"+osSignalSelection_+"&&"+categorySelection+")",weight_+"*fakeTauEffiUp",luminosity_*leg1Corr,prefix,false); //std::pair<float,float> wShapeFTDown = createHistogramAndShifts(wFile_,"W_CMS_htt_jetToTauFake_13TeVDown","("+relaxedSelection+"&&"+trigSelection_+"&&"+osSignalSelection_+"&&"+categorySelection+")",weight_+"*fakeTauEffiDown",luminosity_*leg1Corr,prefix,false); /* * SUBTRACT MC IN HIGH OS SDB */ //First get data in Sideband //old std::pair<float,float> dataYSdb = createHistogramAndShifts(dataFile_,"data_obs_sdb","("+preSelection+"&&"+trigSelectionData_+"&&"+categorySelection+"&&"+osWSelection_+")",scaleUp_,prefix); //std::pair<float,float> dataYieldSdb = createHistogramAndShifts(dataFile_,"data_obs_sdb","("+preSelection+"&&"+trigSelectionData_+"&&"+categorySelection+"&&"+osWSelection_+")",scaleUp_,prefix); std::pair<float,float> dataYieldSdb = convertToPoisson(dataYSdb); //then get ttbar in sideband std::pair<float,float> topYieldSdb = createHistogramAndShifts(topFile_,"TT_SDB","("+preSelection+"&&"+trigSelection_+"&&"+categorySelection+"&&"+osWSelection_+")",weight_,luminosity_*leg1Corr*tauID_*topExtrap,prefix); std::pair<float,float> topInflYieldSdb = inflateError(topYieldSdb,topErr_); printf("TTbar events in sideband region = %f + %f \n",topYieldSdb.first,topInflYieldSdb.second); //Next get Diboson in sideband std::pair<float,float> vvYieldSdb = createHistogramAndShifts(vvFile_,"VV_SDB","("+preSelection+"&&"+trigSelection_+"&&"+categorySelection+"&&"+osWSelection_+")",weight_,luminosity_*leg1Corr*tauID_,prefix); std::pair<float,float> vvInflYieldSdb = inflateError(vvYieldSdb,vvErr_); printf("Diboson events in sideband region = %f + %f \n",vvYieldSdb.first,vvInflYieldSdb.second); //next get Z in sideband std::pair<float,float> zSDB = createHistogramAndShifts(zttFile_,"Z_SDB","("+preSelection+"&&"+trigSelection_+"&&"+categorySelection+"&&"+osWSelection_+")",weight_+"*"+Zweight_+"*"+ZUnrollweight_,luminosity_*zttScale_*leg1Corr*tauID_,prefix); printf("Z events in sideband region = %f + %f \n",zSDB.first,zSDB.second); /* * also want to subtract QCD * NOW GET QCD IN HIGH MT SS SDB */ //NEXT GET SS QCD //next get QCD in sideband //old function std::pair<float,float> dataYSdbSS = createHistogramAndShifts(dataFile_,"QCD_SS_HMT_SDB","("+preSelection+"&&"+trigSelectionData_+"&&"+categorySelection+"&&"+ssWSelection_+")",scaleUp_,prefix); //then get ttbar in sideband // std::pair<float,float> topYieldSdbSS = createHistogramAndShifts(topFile_,"TT_SS_HMT_SDB","("+preSelection+"&&"+trigSelection_+"&&"+categorySelection+"&&"+ssWSelection_+")",weight_,luminosity_*leg1Corr*tauID_*topExtrap,prefix); std::pair<float,float> topInflYieldSdbSS = inflateError(topYieldSdbSS,topErr_); //Next get Diboson in sideband std::pair<float,float> vvYieldSdbSS = createHistogramAndShifts(vvFile_,"VV_SS_HMT_SDB","("+preSelection+"&&"+trigSelection_+"&&"+categorySelection+"&&"+ssWSelection_+")",weight_,luminosity_*leg1Corr*tauID_,prefix); std::pair<float,float> vvInflYieldSdbSS = inflateError(vvYieldSdbSS,vvErr_); //next get Z in sideband std::pair<float,float> zSdbSS = createHistogramAndShifts(zttFile_,"Z_SS_HMT_SDB","("+preSelection+"&&"+trigSelection_+"&&"+categorySelection+"&&"+ssWSelection_+")",weight_+"*"+Zweight_+"*"+ZUnrollweight_,luminosity_*zttScale_*leg1Corr*tauID_,prefix); printf("Z events in sideband region = %f + %f \n",zSDB.first,zSDB.second); std::pair<float,float> wSdbSS = createHistogramAndShifts(wFile_,"W_SS_HMT_SDB","("+preSelection+"&&"+trigSelection_+"&&"+categorySelection+"&&"+ssWSelection_+")",weight_,luminosity_*zttScale_*leg1Corr*tauID_,prefix); subtractHistogram(filelabel_+prefix,"QCD_SS_HMT_SDB","TT_SS_HMT_SDB"); subtractHistogram(filelabel_+prefix,"QCD_SS_HMT_SDB","VV_SS_HMT_SDB"); subtractHistogram(filelabel_+prefix,"QCD_SS_HMT_SDB","Z_SS_HMT_SDB"); subtractHistogram(filelabel_+prefix,"QCD_SS_HMT_SDB","W_SS_HMT_SDB"); std::pair<float,float> ssQCDhigh = std::make_pair(TMath::Nint(dataYSdbSS.first -wSdbSS.first -topYieldSdbSS.first -vvYieldSdbSS.first -zSdbSS.first), sqrt(dataYSdbSS.second*dataYSdbSS.second +wSdbSS.second*wSdbSS.second +topYieldSdbSS.second*topYieldSdbSS.second +vvYieldSdbSS.second*vvYieldSdbSS.second +zSdbSS.second*zSdbSS.second)); if(ssQCDhigh.first<0) { ssQCDhigh.first=0.0000001; ssQCDhigh.second=1.8; } printf("5. Extrapolate SS QCD -> OS QCD \n"); std::pair<float,float> osQCDhigh = std::make_pair(ssQCDhigh.first*qcdFactor_, sqrt(ssQCDhigh.second*ssQCDhigh.second*qcdFactor_*qcdFactor_ +qcdFactorErr_*qcdFactorErr_*ssQCDhigh.first*ssQCDhigh.first)); renormalizeHistogram(filelabel_+prefix,"QCD_SS_HMT_SDB",osQCDhigh.first); printf("SS QCD in wJets =%f *%f = %f +- %f \n",ssQCDhigh.first,qcdFactor_,osQCDhigh.first,osQCDhigh.second); /* * NOW ACTUALLY SUBRACT THE BACKGORUNDS FROM THE W YIELD */ //Run OS+LS + MT method printf("1. Subtract TTbar and diboson from sideband"); std::pair<float,float> osWHigh = std::make_pair(TMath::Nint(dataYieldSdb.first -topInflYieldSdb.first -vvInflYieldSdb.first -zSDB.first -osQCDhigh.first), sqrt(dataYieldSdb.second*dataYieldSdb.second +topInflYieldSdb.second*topInflYieldSdb.second +vvInflYieldSdb.second*vvInflYieldSdb.second +osQCDhigh.second*osQCDhigh.second +zSDB.second*zSDB.second)); std::pair<float,float> osWHighUp = std::make_pair(TMath::Nint(dataYieldSdb.first -topInflYieldSdb.first -vvInflYieldSdb.first -zSDB.first -osQCDhigh.first*(1+qcdFactorErr_)), sqrt(dataYieldSdb.second*dataYieldSdb.second +topInflYieldSdb.second*topInflYieldSdb.second +vvInflYieldSdb.second*vvInflYieldSdb.second +osQCDhigh.second*osQCDhigh.second +zSDB.second*zSDB.second)); std::pair<float,float> osWHighDown = std::make_pair(TMath::Nint(dataYieldSdb.first -topInflYieldSdb.first -vvInflYieldSdb.first -zSDB.first -osQCDhigh.first*(1-qcdFactorErr_)), sqrt(dataYieldSdb.second*dataYieldSdb.second +topInflYieldSdb.second*topInflYieldSdb.second +vvInflYieldSdb.second*vvInflYieldSdb.second +osQCDhigh.second*osQCDhigh.second +zSDB.second*zSDB.second)); printf("OS W in high mt sideband =%f -%f -%f -%f -(dd)%f = %f +- %f \n",dataYieldSdb.first,topInflYieldSdb.first,vvInflYieldSdb.first,zSDB.first,osQCDhigh.first,osWHigh.first,osWHigh.second); /* * NOW EXTRAPOLATE TO LOW MT */ std::pair<float,float> wFactor = extractWFactor(wFile_,preSelection+"&&"+trigSelection_+"&&"+categorySelection,prefix,osWSelection_,osSignalSelection_); //std::pair<float,float> wFactor = extractWFactor(wFile_,preSelection,prefix,osWSelection_,osSignalSelection_); printf("W extrapolation factor as measured in corrected MC = %f +- %f\n",wFactor.first,wFactor.second); //std::pair<float,float> wFactorUp = extractWFactor(wFile_,preSelection+"&&"+trigSelection_+"&&charge==0&&"+categorySelection+"",prefix,"WWeightUp"); //std::pair<float,float> wFactorDown = extractWFactor(wFile_,preSelection+"&&"+trigSelection_+"&&charge==0&&"+categorySelection+"",prefix,"WWeightDown"); // printf("2. Extrapolate W in the low MT region\n"); std::pair<float,float> osWLow = std::make_pair(osWHigh.first*wFactor.first, sqrt(osWHigh.first*osWHigh.first*wFactor.second*wFactor.second+osWHigh.second*osWHigh.second*wFactor.first*wFactor.first)); printf("OS W Full Estimation =%f *%f = %f +- %f \n",osWHigh.first,wFactor.first,osWLow.first,osWLow.second); std::pair<float,float> osWLowUp = std::make_pair(osWHighUp.first*wFactor.first, sqrt(osWHighUp.first*osWHighUp.first*wFactor.second*wFactor.second+osWHighUp.second*osWHighUp.second*wFactor.first*wFactor.first)); std::pair<float,float> osWLowDown = std::make_pair(osWHighDown.first*wFactor.first, sqrt(osWHighDown.first*osWHighDown.first*wFactor.second*wFactor.second+osWHighDown.second*osWHighDown.second*wFactor.first*wFactor.first)); if (osWLow.first<0.0000001) osWLow.first=0.0000001; if(shifts_.size()>0){ WSyst(filelabel_, prefix, "W", 1.0, wFactorErr_); } renormalizeHistogram(filelabel_+prefix,"W",osWLow.first); renormalizeHistogram(filelabel_+prefix,"W_CMS_htt_jetToTauFake_13TeVUp",osWLow.first); renormalizeHistogram(filelabel_+prefix,"W_CMS_htt_jetToTauFake_13TeVDown",osWLow.first); renameHist(filelabel_+prefix,"W_QCDSFUncert_"+chan+prefix+"_13TeVUp","W"); renameHist(filelabel_+prefix,"W_QCDSFUncert_"+chan+prefix+"_13TeVDown","W"); renormalizeHistogram(filelabel_+prefix,"W_QCDSFUncert_"+chan+prefix+"_13TeVUp",osWLowUp.first); renormalizeHistogram(filelabel_+prefix,"W_QCDSFUncert_"+chan+prefix+"_13TeVDown",osWLowDown.first); printf("OS W Straight MC Estimation = %f +- %f \n", wYield.first, wYield.second); wFactorQCD_ = osWLow.first/wYield.first; printf("OS W Datadriven/Straight MC Estimation = %f \n", wFactorQCD_); //use wFactorError instead!!! wFactorStatErr_ = (osWLow.first+osWLow.second)/wYield.first; printf("OS W Straight MC -> Full Sideband Estimation = %f +- (stat)%f +- full %f \n",osWLow.first, wFactorStatErr_,wFactorErr_*osWLow.first); output.W = osWLow.first; output.dW = osWLow.second; return true; } //-------------Helper Functions------------------ void addHistogramZTT(std::string folder, std::string histo1, std::string histo2) { std::cout<<"In AddHistogramZTT"<<std::endl; addHistogram(folder,histo1,histo2); for(unsigned int i=0;i<shifts_.size();++i) { TH2F * h1 =(TH2F*) fout_->Get((folder+"/"+histo1+"_"+shiftsPostFix_[i]+"Up").c_str()); if(h1!=0) { addHistogram(folder,(histo1+"_"+shiftsPostFix_[i]+"Up").c_str(),histo2); } else { printf("Shift not found = %s\n",(folder+"/"+histo1+"_"+shiftsPostFix_[i]+"Up").c_str()); } TH2F * h2 =(TH2F*) fout_->Get((folder+"/"+histo1+"_"+shiftsPostFix_[i]+"Down").c_str()); if(h2!=0) { addHistogram(folder,(histo1+"_"+shiftsPostFix_[i]+"Down").c_str(),histo2); } else { printf("Shift not found = %s\n",(folder+"/"+histo1+"_"+shiftsPostFix_[i]+"Down").c_str()); } }//end for }//end addHistogram ZTT //old no weight variable // std::pair<float,float> createHistogramAndShifts(std::string file,std::string name, std::string cut,float scaleFactor = 1, std::string postfix = "",bool normUC = true, bool keys=false,bool ShapeUncertainty=true) { TFile *f = new TFile(file.c_str()); if(f==0) printf("Not file Found\n"); //get the nominal tree first TTree *t= (TTree*)f->Get((channel_+"EventTree/eventTree").c_str()); if(t==0) printf("Not Tree Found in file %s\n",file.c_str()); std::pair<float,float> yield; if(!keys) yield =makeHistogram(t,filelabel_+postfix,name,cut,scaleFactor); //now the shifts std::pair<float,float> tmpYield; for(unsigned int i=0;i<shifts_.size();++i) { TTree *ts= (TTree*)f->Get((channel_+"EventTree"+shifts_[i]+"Up/eventTree").c_str()); if(ts!=0) { if(!keys) tmpYield = makeHistogram(ts,filelabel_+postfix,name+"_"+shiftsPostFix_[i]+"Up",cut,scaleFactor); if(!normUC) scaleHistogram(filelabel_+postfix,name+"_"+shiftsPostFix_[i]+"Up",yield.first/tmpYield.first); } TTree *td= (TTree*)f->Get((channel_+"EventTree"+shifts_[i]+"Down/eventTree").c_str()); if(td!=0) { if(!keys) tmpYield = makeHistogram(td,filelabel_+postfix,name+"_"+shiftsPostFix_[i]+"Down",cut,scaleFactor); if(!normUC) scaleHistogram(filelabel_+postfix,name+"_"+shiftsPostFix_[i]+"Down",yield.first/tmpYield.first); } } f->Close(); return yield; } std::pair<float,float> createHistogramAndShifts(std::string file,std::string name, std::string cut,std::string tmpWeight, float scaleFactor = 1, std::string postfix = "",bool normUC = true, bool keys=false,bool ShapeUncertainty=true) { TFile *f = new TFile(file.c_str()); if(f==0) printf("Not file Found\n"); //get the nominal tree first TTree *t= (TTree*)f->Get((channel_+"EventTree/eventTree").c_str()); if(t==0) printf("Not Tree Found in file %s\n",file.c_str()); std::pair<float,float> yield; std::string tmpCut = cut+"*"+tmpWeight; if(!keys) yield =makeHistogram(t,filelabel_+postfix,name,tmpCut,scaleFactor); //now the shifts std::pair<float,float> tmpYield; for(unsigned int i=0;i<shifts_.size();++i) { if (shifts_[i]=="Tau"){ tmpCut=cut+"*"+tmpWeight+"*(gen_match_2==5)"; } else { tmpCut = cut+"*"+tmpWeight; } TTree *ts= (TTree*)f->Get((channel_+"EventTree"+shifts_[i]+"Up/eventTree").c_str()); if(ts!=0) { if(!keys) tmpYield = makeHistogram(ts,filelabel_+postfix,name+"_"+shiftsPostFix_[i]+"Up",tmpCut,scaleFactor); if(!normUC) scaleHistogram(filelabel_+postfix,name+"_"+shiftsPostFix_[i]+"Up",yield.first/tmpYield.first); } TTree *td= (TTree*)f->Get((channel_+"EventTree"+shifts_[i]+"Down/eventTree").c_str()); if(td!=0) { if(!keys) tmpYield = makeHistogram(td,filelabel_+postfix,name+"_"+shiftsPostFix_[i]+"Down",tmpCut,scaleFactor); if(!normUC) scaleHistogram(filelabel_+postfix,name+"_"+shiftsPostFix_[i]+"Down",yield.first/tmpYield.first); } } f->Close(); return yield; } std::pair<float,float> createHistogramAndShiftsQCD(std::string file,std::string name, std::string cut,float scaleFactor = 1, std::string postfix = "",bool normUC = true, bool keys=false,bool ShapeUncertainty=true) { TFile *f = new TFile(file.c_str()); if(f==0) printf("Not file Found\n"); //get the nominal tree first TTree *t= (TTree*)f->Get((channel_+"EventTree/eventTree").c_str()); if(t==0) printf("Not Tree Found in file %s\n",file.c_str()); std::pair<float,float> yield; if(!keys) yield =makeHistogram(t,filelabel_+postfix,name,cut,scaleFactor); //now the shifts std::pair<float,float> tmpYield; for(unsigned int i=0;i<shifts_.size();++i) { tmpYield = makeHistogram(t,filelabel_+postfix,name+"_"+shiftsPostFix_[i]+"Up",cut,scaleFactor); tmpYield = makeHistogram(t,filelabel_+postfix,name+"_"+shiftsPostFix_[i]+"Down",cut,scaleFactor); } f->Close(); return yield; } std::pair<float,float> createHistogramAndShiftsFinal(std::string file,std::string name, std::string cut, std::string tmpWeight, float scaleFactor = 1, std::string postfix = "",bool normUC = true, bool keys=false,bool ShapeUncertainty=true) { TFile *f = new TFile(file.c_str()); if(f==0) printf("Not file Found\n"); //get the nominal tree first TTree *t= (TTree*)f->Get((channel_+"EventTreeFinal/eventTree").c_str()); if(t==0) printf("Not Tree Found in file %s\n",file.c_str()); std::pair<float,float> yield; std::string tmpCut =cut+"*"+tmpWeight; if(!keys) yield =makeHistogram(t,filelabel_+postfix,name,tmpCut,scaleFactor); //now the shifts std::pair<float,float> tmpYield; for(unsigned int i=0;i<shifts_.size();++i) { if (shifts_[i]=="Tau"){ tmpCut=cut+"*"+tmpWeight+"*gen_match_2==5"; } TTree *ts= (TTree*)f->Get((channel_+"EventTreeFinal"+shifts_[i]+"Up/eventTree").c_str()); if(ts!=0) { if(!keys) tmpYield = makeHistogram(ts,filelabel_+postfix,name+"_"+shiftsPostFix_[i]+"Up",tmpCut,scaleFactor); if(!normUC) scaleHistogram(filelabel_+postfix,name+"_"+shiftsPostFix_[i]+"Up",yield.first/tmpYield.first); } TTree *td= (TTree*)f->Get((channel_+"EventTreeFinal"+shifts_[i]+"Down/eventTree").c_str()); if(td!=0) { if(!keys) tmpYield = makeHistogram(td,filelabel_+postfix,name+"_"+shiftsPostFix_[i]+"Down",tmpCut,scaleFactor); if(!normUC) scaleHistogram(filelabel_+postfix,name+"_"+shiftsPostFix_[i]+"Down",yield.first/tmpYield.first); } } //if (!(name=="data_obs"||name=="data_obs_ss"||name=="data_obs_sdb"||name=="data_obs_ss_sdb")) //FixNegativeBinsMC(filelabel_+postfix,name,false); f->Close(); return yield; } void setBinning2D(const std::vector<double>& binning, const std::vector<double>& binningUnroll) { binning_ = binning; binningUnroll_ = binningUnroll; } void setBinning(const std::vector<double>& binning) { binning_ = binning; } std::pair<float,float> inflateError(std::pair<float,float> input,float error, float error2 =0.0, float error3 = 0.0 ) { float value = input.first; float err = sqrt(input.second*input.second+(input.first*error)*(input.first*error)+(input.first*error2)*(input.first*error2)+(input.first*error3)*(input.first*error3)); if(err>value) { err=0.99*value; printf("Found error above value -> Setting error to value\n"); } return std::make_pair(value,err); } void renormalizeHistogram(std::string folder, std::string histo, float yield) { TH2F * h =(TH2F*) fout_->Get((folder+"/"+histo).c_str()); double scaleFactor = yield/h->Integral(); h->Scale(scaleFactor); fout_->cd(folder.c_str()); h->Write(h->GetName(),TObject::kOverwrite); for(unsigned int i=0;i<shifts_.size();++i) { TH2F * hh =(TH2F*) fout_->Get((folder+"/"+histo+"_"+shiftsPostFix_[i]+"Up").c_str()); if(hh!=0) { hh->Scale(scaleFactor); fout_->cd(folder.c_str()); hh->Write(hh->GetName(),TObject::kOverwrite); } else { printf("Shift not found = %s\n",(folder+"/"+histo+"_"+shiftsPostFix_[i]+"Up").c_str()); } TH2F * hhh =(TH2F*) fout_->Get((folder+"/"+histo+"_"+shiftsPostFix_[i]+"Down").c_str()); if(hhh!=0) { hhh->Scale(scaleFactor); fout_->cd(folder.c_str()); hhh->Write(hhh->GetName(),TObject::kOverwrite); } else { printf("Shift not found\n"); } } } float quadrature(float value, float error, float e0 = 0.0, float e1 = 0.0 ,float e2 = 0.0, float e3 = 0.0 ,float e4 = 0.0, float e5 = 0.0 ){ float returnValue = sqrt(error*error+(e0*e0+e1*e1+e2*e2+e3*e3+e4*e4+e5*e5)*value*value); return returnValue; } std::pair<float,float> makeHistogram(TTree* tree,std::string folder,std::string name,std::string cut,float scaleFactor = 1.) { if(fout_->Get(folder.c_str())==0) fout_->mkdir(folder.c_str()); TH2F *h=0; TString variableOld_=variable_; if((name=="data_obs"||name=="data_obs_ss"||name=="data_obs_sdb"||name=="data_obs_ss_sdb"||name=="QCD")&&variable_=="pt2ES"){ variable_="pt_2"; } //binning_ binningX //binning_ binningY //double xbins[4]={0,70,130,400}; //double ybins[4]={0,50,100,400}; //TH2F *h = new TH2F("oldrebin",old->GetTitle(),nx,xbins,ny,ybins); if(binning_.size()==0) h=new TH2F(name.c_str(),name.c_str(),bins_,min_,max_,bins_,min_,max_); else h=new TH2F(name.c_str(),name.c_str(),binning_.size()-1,&binning_[0],binningUnroll_.size()-1,&binningUnroll_[0]); h->Sumw2(); tree->Draw((variableUnroll_+":"+variable_+">>"+name).c_str(),cut.c_str()); //tree->Draw((variable_+":"+variableUnroll_+">>"+name).c_str(),cut.c_str()); h->Scale(scaleFactor); variable_=variableOld_;// if(verbose_>0) std::cout<< " " <<name<<": "<<h->Integral()<<std::endl; // printf("Created Histogram %s with entries=%f\n",name.c_str(),h->Integral()); fout_->cd(folder.c_str()); Double_t error=0.0; //LD float yield = h->IntegralAndError(1,h->GetNbinsX(),error,""); //float yield = h->IntegralAndError(0,h->GetNbinsX()+1,error,""); if(yield == 0){ h->SetBinContent(1,1,0.00001); } h->Write(h->GetName(),TObject::kOverwrite); return std::make_pair(yield,error); } void close() { fout_->Close(); } std::pair<float,float> createHistogramShifted(std::string file,std::string name, std::string cut,std::string shift,float scaleFactor = 1, std::string postfix = "") { TFile *f = new TFile(file.c_str()); if(f==0) printf("Not file Found\n"); //get the nominal tree first TTree *t= (TTree*)f->Get((channel_+"EventTree/eventTree").c_str()); TTree *ts= (TTree*)f->Get((channel_+"EventTree"+shift+"/eventTree").c_str()); if(t==0||ts==0) printf("Not Tree Found in file %s\n",file.c_str()); std::pair<float,float> yieldNorm; std::pair<float,float> yield; yieldNorm =makeHistogram(t,filelabel_+postfix,name,cut,scaleFactor); yield =makeHistogram(ts,filelabel_+postfix,name,cut,scaleFactor); scaleHistogram(filelabel_+postfix, name, yieldNorm.first/yield.first); //yield =makeHistogramShifted(t,filelabel_+postfix,name,cut,"1.0",scaleFactor); f->Close(); return yield; } std::pair<float,float> makeHistogramShifted(TTree* tree,std::string folder,std::string name,std::string cut, std::string shift,float scaleFactor = 1.) { if(fout_->Get(folder.c_str())==0) fout_->mkdir(folder.c_str()); TH2F *h=0; TString variableOld_=variable_; if((name=="data_obs"||name=="data_obs_ss"||name=="data_obs_sdb"||name=="data_obs_ss_sdb"||name=="QCD")&&variable_=="pt2ES"){ variable_="pt_2"; } //binning_ binningX //binning_ binningY //double xbins[4]={0,70,130,400}; //double ybins[4]={0,50,100,400}; //TH2F *h = new TH2F("oldrebin",old->GetTitle(),nx,xbins,ny,ybins); if(binning_.size()==0) h=new TH2F(name.c_str(),name.c_str(),bins_,min_,max_,bins_,min_,max_); else h=new TH2F(name.c_str(),name.c_str(),binning_.size()-1,&binning_[0],binningUnroll_.size()-1,&binningUnroll_[0]); h->Sumw2(); tree->Draw((variableUnroll_+":"+variable_+"*"+shift+">>"+name).c_str(),cut.c_str()); //tree->Draw((variable_+"*"+shift+":"+variableUnroll_+">>"+name).c_str(),cut.c_str()); h->Scale(scaleFactor); variable_=variableOld_;// printf("Created Histogram %s with entries=%f\n",name.c_str(),h->Integral()); fout_->cd(folder.c_str()); Double_t error=0.0; float yield = h->IntegralAndError(1,h->GetNbinsX(),error,""); if(yield == 0){ h->SetBinContent(1,0.00001); } h->Write(h->GetName(),TObject::kOverwrite); return std::make_pair(yield,error); } void scaleHistogram(std::string folder, std::string histo, float scaleFactor) { TH2F * h =(TH2F*) fout_->Get((folder+"/"+histo).c_str()); h->Scale(scaleFactor); fout_->cd(folder.c_str()); h->Write(h->GetName(),TObject::kOverwrite); fout_->cd(); for(unsigned int i=0;i<shifts_.size();++i) { TH2F * hh =(TH2F*) fout_->Get((folder+"/"+histo+"_"+shiftsPostFix_[i]+"Up").c_str()); if(hh!=0) { hh->Scale(scaleFactor); fout_->cd(folder.c_str()); hh->Write(hh->GetName(),TObject::kOverwrite); fout_->cd(); } TH2F * hhh =(TH2F*) fout_->Get((folder+"/"+histo+"_"+shiftsPostFix_[i]+"Down").c_str()); if(hhh!=0) { hhh->Scale(scaleFactor); fout_->cd(folder.c_str()); hhh->Write(hhh->GetName(),TObject::kOverwrite); fout_->cd(); } } } std::pair<float,float> extractRFactor(std::string file,std::string preselection,std::string postfix) { TFile *f = new TFile (file.c_str()); TTree *t = (TTree*)f->Get((channel_+"EventTree/eventTree").c_str()); std::pair<float,float> ss; std::pair<float,float> os; ss = makeHistogram(t,filelabel_+postfix,"W_SS",("("+preselection+"&&charge!=0)*"+weight_).c_str()); os = makeHistogram(t,filelabel_+postfix,"W_OS",("("+preselection+"&&charge==0)*"+weight_).c_str()); std::cout<<"W Rfactor Selection: ("<<preselection+"&&(charge requirement) )*"<<weight_<<std::endl; std::cout<<"W + Jets SS: "<< ss.first<<" OS: "<< os.first<<std::endl; float factor = os.first/ss.first; float factorerrStat = sqrt(os.second*os.second + ss.second*ss.second); //float factorerrSyst = factor*wFactorErr_; //float factorErr = sqrt(factorerrStat*factorerrStat+factorerrSyst*factorerrSyst); float factorErr = factorerrStat; if(ss.first==0.){ factor=0.; factorErr=0.; } return std::make_pair(factor,factorErr); } std::pair<float,float> extractWFactor(std::string file,std::string preselection,std::string postfix, std::string Wweight = "1") { TFile *f = new TFile (file.c_str()); TTree *t = (TTree*)f->Get((channel_+"EventTree/eventTree").c_str()); std::pair<float,float> high; std::pair<float,float> low; high = makeHistogram(t,filelabel_+postfix,"W_High",("("+preselection+"&&"+wSelection_+")*"+weight_+"*"+Wweight).c_str()); low = makeHistogram(t,filelabel_+postfix,"W_Low",("("+preselection+"&&"+signalSelection_+")*"+weight_+"*"+Wweight).c_str()); std::cout<<"W + Jets High: "<< high.first<<" Low: "<< low.first<<std::endl; float factor = low.first/high.first; float factorerrStat = sqrt(low.second*low.second + high.second*high.second); float factorerrSyst = factor*wFactorErr_; float factorErr = sqrt(factorerrStat*factorerrStat+factorerrSyst*factorerrSyst); if(high.first==0.){ factor=0.; factorErr=0.; } return std::make_pair(factor,factorErr); } std::pair<float,float> extractWFactorFinal(std::string file,std::string preselection,std::string postfix, std::string Wweight = "1") { TFile *f = new TFile (file.c_str()); TTree *t = (TTree*)f->Get((channel_+"EventTreeFinal/eventTree").c_str()); std::pair<float,float> high; std::pair<float,float> low; high = makeHistogram(t,filelabel_+postfix,"W_High",("("+preselection+"&&"+wSelection_+")*"+weight_+"*"+Wweight).c_str()); low = makeHistogram(t,filelabel_+postfix,"W_Low",("("+preselection+"&&"+signalSelection_+")*"+weight_+"*"+Wweight).c_str()); std::cout<<"W + Jets High: "<< high.first<<" Low: "<< low.first<<std::endl; float factor = low.first/high.first; float factorerrStat = sqrt(low.second*low.second + high.second*high.second); float factorerrSyst = factor*wFactorErr_; float factorErr = sqrt(factorerrStat*factorerrStat+factorerrSyst*factorerrSyst); if(high.first==0.){ factor=0.; factorErr=0.; } return std::make_pair(factor,factorErr); } std::pair<float,float> extractWFactor(std::string file, std::string preselection, std::string postfix, std::string wSel, std::string sigSel) { TFile *f = new TFile (file.c_str()); TTree *t = (TTree*)f->Get((channel_+"EventTree/eventTree").c_str()); //TTree *t = (TTree*)f->Get((channel_+"EventTreeFinal/eventTree").c_str()); std::pair<float,float> high; std::pair<float,float> low; high = makeHistogram(t,filelabel_+postfix,"W_High",("("+preselection+"&&"+wSel+")*"+weight_).c_str(),luminosity_); low = makeHistogram(t,filelabel_+postfix,"W_Low",("("+preselection+"&&"+sigSel+")*"+weight_).c_str(),luminosity_); std::cout<<" Cuts in extract WFactor "<<" OS W Mt>80: "<<high.first<<" OS W Mt Low: "<<low.first<<std::endl; std::cout<<" Extract WFactor Second"<<" OS W Mt>80: "<<high.second<<" OS W Mt Low: "<<low.second<<std::endl; float factor = low.first/high.first; float factorerrStat = sqrt(low.second*low.second + high.second*high.second); float factorerrSyst = factor*wFactorErr_; float factorErr = sqrt(factorerrStat*factorerrStat+factorerrSyst*factorerrSyst); std::cout<<" WFactor Stat Error "<<" factor: "<<factor<<" StatError: "<<factorerrStat<<std::endl; std::cout<<" WFactor Syst Error "<<" factor*wFactorErr_: "<<factor<<"*"<<wFactorErr_<<" = "<<factorerrSyst<<std::endl; std::cout<<" WFactor Error "<<" factorError = sqrt(Syst Error^2+Stat Error^2)= "<<factorErr<<std::endl; if(high.first==0.){ factor=0.; factorErr=0.; } return std::make_pair(factor,factorErr); } void mergeHistogram(std::string folder, std::string histo1, std::string histo2, std::string newName) { TH2F * h1 =(TH2F*) fout_->Get((folder+"/"+histo1).c_str()); TH2F * h2 =(TH2F*) fout_->Get((folder+"/"+histo2).c_str()); TH2F *hNew =(TH2F*) h1->Clone(TString(newName)); hNew->Add(h2,1.); for(int i=1;i<h1->GetNbinsX();++i){ if(h1->GetBinContent(i)<0){ h1->SetBinContent(i,0.00001); h1->SetBinError(i,1.0); } } fout_->cd(folder.c_str()); hNew->Write(TString(newName),TObject::kOverwrite); } std::pair<float,float> convertToPoisson(std::pair<float,float> measurement) { float yield = measurement.first; float CLHi = TMath::ChisquareQuantile(1-0.32/2,2*yield+2)/2.; float CLLo = TMath::ChisquareQuantile(0.32/2,2*yield)/2.; printf("Yield =%f Lo=%f Hi=%f\n",measurement.first,CLLo,CLHi); return std::make_pair(measurement.first,(CLHi-CLLo)/2.); } void subtractHistogramShifts(std::string folder, std::string histo1, std::string histo2) { TH2F * h1 =(TH2F*) fout_->Get((folder+"/"+histo1).c_str()); TH2F * h2 =(TH2F*) fout_->Get((folder+"/"+histo2).c_str()); h1->Add(h2,-1.); for(int i=1;i<h1->GetNbinsX();++i){ for(int j=1;j<h1->GetNbinsX();++j){ if(h1->GetBinContent(i,j)<0){ h1->SetBinContent(i,j,0.00001); h1->SetBinError(i,j,1.2); } } } for(unsigned int i=0;i<shifts_.size();++i) { TH2F * hhu1 =(TH2F*) fout_->Get((folder+"/"+histo1+"_"+shiftsPostFix_[i]+"Up").c_str()); TH2F * hhu2 =(TH2F*) fout_->Get((folder+"/"+histo2+"_"+shiftsPostFix_[i]+"Up").c_str()); TH2F * hhd1=(TH2F*) fout_->Get((folder+"/"+histo1+"_"+shiftsPostFix_[i]+"Down").c_str()); TH2F * hhd2 =(TH2F*) fout_->Get((folder+"/"+histo2+"_"+shiftsPostFix_[i]+"Down").c_str()); hhu1->Add(hhu2,-1.); hhd1->Add(hhd2,-1.); fout_->cd(folder.c_str()); hhu1->Write(hhu1->GetName(),TObject::kOverwrite); hhd1->Write(hhd1->GetName(),TObject::kOverwrite); } fout_->cd(folder.c_str()); h1->Write(h1->GetName(),TObject::kOverwrite); } void subtractHistogram(std::string folder, std::string histo1, std::string histo2) { TH2F * h1 =(TH2F*) fout_->Get((folder+"/"+histo1).c_str()); TH2F * h2 =(TH2F*) fout_->Get((folder+"/"+histo2).c_str()); h1->Add(h2,-1.); for(int i=1;i<h1->GetNbinsX();++i){ for(int j=1;j<h1->GetNbinsX();++j){ if(h1->GetBinContent(i,j)<0){ h1->SetBinContent(i,j,0.00001); h1->SetBinError(i,j,1.2); } } } fout_->cd(folder.c_str()); h1->Write(h1->GetName(),TObject::kOverwrite); } void addHistogram(std::string folder, std::string histo1, std::string histo2) { TH2F * h1 =(TH2F*) fout_->Get((folder+"/"+histo1).c_str()); TH2F * h2 =(TH2F*) fout_->Get((folder+"/"+histo2).c_str()); h1->Add(h2,1.); fout_->cd(folder.c_str()); h1->Write(h1->GetName(),TObject::kOverwrite); } void renameHist(std::string folder, std::string name ,std::string histo1)///folder, new name, old name { TH2F * h1 =(TH2F*) fout_->Get((folder+"/"+histo1).c_str()); TH2F * h2 = (TH2F*) h1->Clone(TString(name)); h2->Write(h2->GetName(),TObject::kOverwrite); } void FixNegativeBins(std::string folder, std::string histo, bool verbose=false) { TH2F * hist =(TH2F*) fout_->Get((folder+"/"+histo).c_str()); unsigned bins = hist->GetNbinsX(); unsigned binsy = hist->GetNbinsY(); for (unsigned i = 1; i <= bins; ++i) { for (unsigned j = 1; j <= binsy; ++j) { if (hist->GetBinContent(i,j) < 0.000001){ hist->SetBinContent(i,j,0.000001); if(verbose) std::cout<<"Bin "<< i << " is negative or zero, setting to 1E6"<<std::endl; } } } hist->Write(hist->GetName(),TObject::kOverwrite); } void FixNegativeBinsMC(std::string folder, std::string histo, bool verbose=false){ FixNegativeBins(folder, histo, verbose); for(unsigned int i=0;i<shifts_.size();++i) { TH2F * hh =(TH2F*) fout_->Get((folder+"/"+histo+"_"+shiftsPostFix_[i]+"Up").c_str()); if(hh!=0) { FixNegativeBins(folder, (histo+"_"+shiftsPostFix_[i]+"Up").c_str(), verbose); } TH2F * hhh =(TH2F*) fout_->Get((folder+"/"+histo+"_"+shiftsPostFix_[i]+"Down").c_str()); if(hhh!=0) { FixNegativeBins(folder, (histo+"_"+shiftsPostFix_[i]+"Down").c_str(), verbose); } } } void FixEmptyBins(std::string folder, std::string histo, bool is_qcd, bool verbose=false) { TH2F * hist =(TH2F*) fout_->Get((folder+"/"+histo).c_str()); unsigned bins = hist->GetNbinsX(); unsigned first_populated = 0; unsigned last_populated = 0; for (unsigned i = 1; i <= bins; ++i) { if (hist->GetBinContent(i) > 0. && first_populated == 0) first_populated = i; if (hist->GetBinContent(bins-(i-1)) > 0. && last_populated == 0) last_populated = bins-(i-1); } if (last_populated <= first_populated) { if (verbose) std::cout << "Cannot correct this distribution!" << std::endl; return; } if (verbose) std::cout << "First populated bin: " << first_populated << std::endl; if (verbose) std::cout << "Last populated bin: " << last_populated << std::endl; double av_weight = ( hist->Integral() / double(hist->GetEntries())); if (!is_qcd) { if (verbose) std::cout << "Integral: " << hist->Integral() << std::endl; if (verbose) std::cout << "Entries: " << hist->GetEntries() << std::endl; if (verbose) std::cout << "Av. Weight: " << av_weight << std::endl; } for (unsigned i = first_populated+1; i < last_populated; ++i) { if (hist->GetBinContent(i) == 0.) { if (verbose) std::cout << "Bin " << i << " is empty!" << std::endl; if (is_qcd) { hist->SetBinError(i, 1.0); } else { if (verbose) std::cout << "Set weight to 1.0 * av_weight = " << (1.0 * av_weight) << std::endl; hist->SetBinError(i, av_weight); } } } hist->Write(hist->GetName(),TObject::kOverwrite); } bool WSyst(std::string channel, std::string prefix, std::string histo1, float corr, float unc) { std::string chan = "mt"; if(channel_ == "eleTau") chan = "et"; TH2F * h1 =(TH2F*) fout_->Get((channel+prefix+"/"+histo1).c_str()); TH2F * h2 = (TH2F*)h1->Clone(TString(histo1+std::string("_WSFUncert_"+chan+prefix+"_"+energy_+"Up"))); TH2F * h3 = (TH2F*)h1->Clone(TString(histo1+std::string("_WSFUncert_"+chan+prefix+"_"+energy_+"Down"))); std::cout << "Channel label is " << chan << std::endl; float y; float cUp = corr+unc; float cDown = corr-unc; //printf("Creating QCD Shape Systematic \n"); float scale = h1->Integral(); for(int i=1;i<h1->GetNbinsX();++i){ for(int j=1;j<h1->GetNbinsY();++j){ y = h1->GetBinContent(i,j); h2->SetBinContent(i,j,y*cUp); h3->SetBinContent(i,j,y*cDown); } } //h1->Scale(scale/h1->Integral()); //h2->Scale(scale/h2->Integral()); //h3->Scale(scale/h3->Integral()); h1->Write(h1->GetName(),TObject::kOverwrite); h2->Write(h2->GetName(),TObject::kOverwrite); h3->Write(h3->GetName(),TObject::kOverwrite); return true; } bool qcdSyst(std::string channel, std::string prefix, std::string histo1, float corr, float unc) { std::string chan = "mt"; if(channel_ == "eleTau") chan = "et"; TH2F * h1 =(TH2F*) fout_->Get((channel+prefix+"/"+histo1).c_str()); TH2F * h2 = (TH2F*)h1->Clone(TString(histo1+std::string("_QCDSFUncert_"+chan+prefix+"_"+energy_+"Up"))); TH2F * h3 = (TH2F*)h1->Clone(TString(histo1+std::string("_QCDSFUncert_"+chan+prefix+"_"+energy_+"Down"))); std::cout << "Channel label is " << chan << std::endl; float x,y; float cUp = corr+unc; float cDown = corr-unc; //printf("Creating QCD Shape Systematic \n"); float scale = h1->Integral(); for(int i=1;i<h1->GetNbinsX();++i){ for(int j=1;j<h1->GetNbinsY();++j){ y = h1->GetBinContent(i,j); h1->SetBinContent(i,j,y*corr); h2->SetBinContent(i,j,y*cUp); h3->SetBinContent(i,j,y*cDown); } } //h1->Scale(scale/h1->Integral()); //h2->Scale(scale/h2->Integral()); //h3->Scale(scale/h3->Integral()); h1->Write(h1->GetName(),TObject::kOverwrite); h2->Write(h2->GetName(),TObject::kOverwrite); h3->Write(h3->GetName(),TObject::kOverwrite); return true; } private: std::string channel_; std::string filelabel_; std::vector<std::string> shifts_; std::vector<std::string> shiftsPostFix_; std::string energy_; int samesign_; //files TFile *fout_; int verbose_; std::string zttFile_; std::string zllFile_; std::string wFile_; std::string vvFile_; std::string ewkFile_; std::string topFile_; std::string qcdFile_; std::string dataFile_; /////////////////////// //selections of regions std::string preSelection_; std::string osSignalSelection_; std::string ssSignalSelection_; std::string signalSelection_; std::string osWSelection_; std::string ssWSelection_; std::string wSelection_; std::string qcdSelection_; std::string relaxedSelection_; std::string trigSelection_; std::string trigSelectionData_; std::string blinding_; std::string charge_; std::string ZLL_genLLSel_; std::string ZTT_genTauSel_; std::string ZJFT_genLReject_; std::string ZLFT_genLSel_; std::string genTSel_; std::string dataSelection_; //Luminosity and efficiency corrections float luminosity_; float luminosityErr_; float muID_ ; float muIDErr_; float eleID_ ; float eleIDErr_; float tauID_ ; float tauIDHigh_; float tauIDErr_; float zttScale_; float zttScaleErr_; float scaleUp_; //histogram options std::string variable_; std::string variableUnroll_; int bins_; float min_; float max_; std::vector<double> binning_; std::vector<double> binningUnroll_; std::string weight_; std::string Zweight_; std::string ZUnrollweight_; std::string TTweight_; std::string embWeight_; std::string ggHWeight_; std::string zlftFactor_; //external parameters float topErr_; float qcdErr_;//tmp float vvErr_; float zlftErr_; float zjftErr_; float wFactorQCD_; float wFactorStatErr_; float wFactorErr_; float qcdFactor_; float qcdFactorErr_; float bFactorZ_; float bFactorZErr_; float bFactorW_; float bFactorWErr_; float vbfFactorZ_; float vbfFactorZErr_; float vbfFactorW_; float vbfFactorWErr_; float boostFactorZ_; float boostFactorZErr_; float boostFactorW_; float boostFactorWErr_; float vhFactorZ_; float vhFactorZErr_; float vhFactorW_; float vhFactorWErr_; float bID_; float bIDErr_; float bMisID_; float bMisIDErr_; std::vector<std::string> mssmMasses_; std::vector<std::string> smMasses_; std::vector<std::string> smMassesDC_; std::vector<float> mssmBBFraction_; std::vector<float> smSigma_; std::vector<float> vbfSigma_; std::vector<float> vhSigma_; std::string dir_; };
[ "samhiggie72@gmail.com" ]
samhiggie72@gmail.com
6d8bb39532f0803b54167ccae958847e1497ff75
b9d9b29c2a180399393c6ab298b9e5bfba17831e
/Top Interview Questions/328-Odd Even Linked List.cpp
6ec9578d0304ad11d5d1b5df7c710322f61ebab1
[]
no_license
qqwangxiaow/leetcode-fast-and-elegant
08b7c6120b82f7ee3b5a99b84e7ba0f0eb38a477
f5081a9e1d893b9d936d9486cf6141b5b35684e1
refs/heads/master
2022-02-11T00:36:22.911461
2022-01-02T05:14:20
2022-01-02T05:14:20
199,302,384
0
0
null
null
null
null
UTF-8
C++
false
false
512
cpp
/* while(cur2&&cur2->next) key! */ class Solution { public: ListNode* oddEvenList(ListNode* head) { if(!head||!head->next||!head->next->next) return head; ListNode *head1=head,*head2=head->next; ListNode *cur=head1,*cur2=head2; while(cur2&&cur2->next) { cur->next=cur->next->next; cur2->next=cur2->next->next; cur=cur->next; cur2=cur2->next; } cur->next=head2; return head1; } };
[ "ywwangxiaow@qq.com" ]
ywwangxiaow@qq.com
bf16887834fe216f410788fc2d0afec11bf14ea2
a6703732232f45dadcadb352f0c3f5cf7a805e7c
/target.cpp
fe18a5363c33996f703c6614ba45bbd045b2c3a2
[]
no_license
rrrrrerw/sokoban_game
7c98ffe27e43552a2498f776aa9dcdb217f0b1d7
bddd1dae4fd4a7d310da640f7b33db2cf2347dd6
refs/heads/master
2022-04-12T21:06:20.723281
2020-03-29T03:02:35
2020-03-29T03:02:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
203
cpp
#include "target.h" target::target() { this->pixel = 64; this->x_origin = 0; this->y_origin = 0; } void target::set_origin(int x, int y) { this->x_origin = x; this->y_origin = y; }
[ "lucky020372@gmail.com" ]
lucky020372@gmail.com
d20cf3d471ed01faa086529a179397e49c9b7be9
0c3a00a110988e96e669fdf9295a5add6152837d
/Source/wali/include/wali/witness/Witness.hpp
67e50a17dbb3f4740fc86921b0af42ec9bb8bc49
[ "MIT" ]
permissive
pdschubert/WALi-OpenNWA
0e360ac04326aa9cd20155b311898e1b6ff99d07
57c26420fb25bbb4bba8a6de3641fef0eb9967e0
refs/heads/master
2022-08-27T07:32:07.005480
2022-08-18T13:54:50
2022-08-18T13:54:50
148,313,943
1
5
NOASSERTION
2020-02-20T12:06:30
2018-09-11T12:30:20
C++
UTF-8
C++
false
false
3,813
hpp
#ifndef wali_WITNESS_GUARD #define wali_WITNESS_GUARD 1 /*! * @author Nicholas Kidd */ #include "wali/Common.hpp" #include "wali/Markable.hpp" #include "wali/ref_ptr.hpp" #include "wali/SemElem.hpp" #include "wali/witness/Visitable.hpp" namespace wali { class Visitor; namespace witness { class Witness; struct witness_t : public wali::ref_ptr< Witness > { typedef wali::ref_ptr< Witness > Parent; witness_t(); witness_t( sem_elem_t ); witness_t( Witness* ); witness_t& operator=( sem_elem_t se ); witness_t& operator=( Witness* alpha ); Witness* getWitness( sem_elem_t se ); }; /** * @class Witness */ class Witness : public SemElem, public Markable, public Visitable { public: static int COUNT; public: Witness( sem_elem_t se ); virtual ~Witness(); /*! * Test if the Witness has user weight ZERO */ bool isZero(); /*! * Test if the Witness has user weight ONE */ bool isOne(); /*! * Returns a new Witness whose user_se is a sem_elem_t ONE * element of the user's weight domain. * * @see SemElem * @see sem_elem_t */ virtual sem_elem_t one() const; /*! * Returns a new Witness whose user_se is a sem_elem_t ZERO * element of the user's weight domain. * * @see SemElem * @see sem_elem_t */ virtual sem_elem_t zero() const; /*! * Extend the user supplied weight and create a new WitnessExtend. * * @see WitnessExtend */ virtual sem_elem_t extend( SemElem * se ); /*! * Combines the user's weight and creates a WitnessCombine * if parameter "se" is not already a WitnessCombine. * * @see SemElem * @see sem_elem_t * @see WitnessCombine */ virtual sem_elem_t combine( SemElem * se ); /*! * Test for equality of user supplied weight. The Witness is * simply along for the ride. */ virtual bool equal( SemElem * se ) const; virtual bool equal( sem_elem_t se ) const { return equal(se.get_ptr()); } //! Print the Witness to the parameter o. virtual std::ostream& print( std::ostream& o ) const; /*! * Accept method allows for different behaviors to be applied to * the Witness DAG. * * @see Visitor */ virtual void accept( Visitor& v, bool visitOnce=false ); //! Pretty print in a DAG like structure to the ostream virtual std::ostream& prettyPrint( std::ostream& o, size_t depth ) const; //! Prints " |" to parameter o for each level of depth std::ostream& formatDepth( std::ostream& o, size_t depth ) const; /*! * Returns protected sem_elem_t se member variable that is the * user supplied weight or from a computation involving the * user defined semiring. * * @see sem_elem_t */ sem_elem_t weight() { return user_se; } //! Reset all marks (recursively) virtual void reset_marks() const; // @return length, taking the shorter of any combine branches virtual unsigned long getMinimumLength() const; protected: sem_elem_t user_se; //!< The user SemElem value bool isEmpty; //!< True if type == Witness. Cheap reflection. unsigned long min_length; private: Witness( sem_elem_t se, bool ie ); }; // class Witness } // namespace witness } // namespace wali #endif // wali_WITNESS_GUARD
[ "linusjun@mail.upb.de" ]
linusjun@mail.upb.de
704b4b36a6a3a06861ee4e77c40d0513f0b4c338
f34d62dbcc664385823c0f273c3e6aef66037f58
/SimpleManager/RoleManagerItem.h
dbd259cd8b82c0b6c7178d2789d922433b6bec65
[]
no_license
MetalPizzaCat/SimpleManager
4a1455555aaf6cb8b83fe08ddb007b1fb88d848a
fb42350ce9061e2c7c5e97cc0f7e3424f6af7748
refs/heads/master
2023-03-12T23:10:34.635008
2021-02-26T12:14:04
2021-02-26T12:14:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
479
h
#pragma once #include <QWidget> #include "ui_RoleManagerItem.h" #include "Info.h" #include <QSqlDatabase> class RoleManagerItem : public QWidget { Q_OBJECT public: RoleManagerItem(ManagerInfo::SUserInfo currentUserInfo, QSqlDatabase dataBase, QWidget *parent = Q_NULLPTR); ~RoleManagerItem(); private: void GenerateList(); Ui::RoleManagerItem ui; QWidget* scrollWidget; QVBoxLayout* scrollBox; ManagerInfo::SUserInfo CurrentUserInfo; QSqlDatabase DataBase; };
[ "catguy228@gmail.com" ]
catguy228@gmail.com
56cac07d3f808598c1e1a2d7354bd594586e84fb
10ee620f5e4473e11fb821d5944a6b06bf4ca493
/UPPayAppDemo1/inc/BrCtlSampleAppContainer.h
43f3da2633cd1714296830d0ceaeb30ad898f630
[]
no_license
zhonghualee/TestSymbian
a4bc7401964da9a47ea4f80c68386e834613eb24
014ef7ef759a3dca419daf787eca2e5b8b8e4d6b
refs/heads/master
2016-09-05T11:28:51.442611
2012-08-06T07:31:02
2012-08-06T07:31:02
5,311,232
0
1
null
null
null
null
MacCentralEurope
C++
false
false
8,795
h
/* * Copyright (c) 2005-2006 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of the License "Symbian Foundation License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.symbianfoundation.org/legal/sfl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: Declares container control for Browser Control Sample application. * */ #ifndef BRCTLSAMPLEAPPCONTAINER_H #define BRCTLSAMPLEAPPCONTAINER_H // INCLUDES #include <coecntrl.h> #include "BrCtlInterface.h" #include "WebClientEngine.h" // FORWARD DECLARATIONS class CBrCtlSampleAppSpecialLoadObserver; class CBrCtlSampleAppLayoutObserver; class CBrCtlSampleAppSoftkeysObserver; class CBrCtlSampleAppLoadEventObserver; class CBrCtlSampleAppCommandObserver; class CBrCtlSampleAppLinkResolver; class CBrCtlSampleAppStateChangeObserver; class CBrCtlSampleAppDialogsProvider; class CBrCtlSampleAppWidgetHandler; class CBrowserContentView; class MWebClientObserver; class CUPPayAppDemo1AppView; // CLASS DECLARATION /** * CBrCtlSampleAppContainer class. * This is the container control class. */ class CBrCtlSampleAppContainer : public CCoeControl, public MWebClientObserver, MCoeControlObserver, MBrCtlDataLoadSupplier { public: // Constructors and destructor /** * EPOC default constructor. * @param aRect Frame rectangle for container. */ void ConstructL(CUPPayAppDemo1AppView* aContainer, const TRect& aRect); /** * Two-phased constructor. */ static CBrCtlSampleAppContainer* NewL(const TRect& aRect); /** * Destructor. */ ~CBrCtlSampleAppContainer(); public: // New functions /** * Pass a command to the Browser Control * @since 2.8 * @param aCommand The command that the Browser Control should process * @return void */ void HandleCommandL(TInt aCommand); /** * Dynamically initialises a menu pane. The Uikon framework calls this * function, if it is implemented in a menuís observer, immediately before * the menu pane is activated. * @since 2.8 * @param aResourceId Resource ID identifying the menu pane to initialise * @param aMenuPane The in-memory representation of the menu pane. * @return void */ void DynInitMenuPaneL(TInt aResourceId, CEikMenuPane* aMenuPane); /** * Handles key events * @since 2.8 * @param aKeyEvent The key event that occurred. * @param aType The window server event type that is being handled * @return TKeyResponse Value indicates whether or not the key event was consumed by the control. The default implementation simply returns EKeyWasNotConsumed. */ TKeyResponse HandleKeyEventL(const TKeyEvent& aKeyEvent,TEventCode aType); /** * Accessor method for iText * @since 2.8 * @param void * @return TDesc& The descriptor of the text */ inline const TDesC& Text() const {return iText;} /** * Setter method for iText * @since 2.8 * @param aText The descriptor for the text you wish to display * @return void */ void SetText( const TDesC& aText ); /** * Setter method for iPoint * @since 2.8 * @param aPoint The point at which you want to display the text * @return void */ void SetPoint( const TPoint& aPoint ); /** * Accessor method iBrCtlInterface * @since 2.8 * @param void * @return CBrCtlInterface* A pointer to the browser control interface as a convenience to the observers */ inline CBrCtlInterface* BrCtlInterface() const {return iBrCtlInterface;} void ProcessIcon(); /** * Check if this is an GetBitmapData test * @param void * @return */ TBool isIconTest(); void setIconTest(); void BasicBrowserControlL(); void SpecialLoadRequestsL(); /** * From MWebClientObserver (see WebClientEngine.h) */ void ClientEvent( const TDesC& aEventDescription ); void ClientHeaderReceived( const TDesC& aHeaderData ); void ClientBodyReceived( const TDesC8& aBodyData ); // const TDesC& CreateOrders(const TDesC& sum, const TDesC& SPId, const TDesC& SPName, int UserId); CUPPayAppDemo1AppView* GetView() {return iAppView;}; void NotifyUser(const TDesC& aData); private: // Functions from base classes /** * From CoeControl,SizeChanged. */ void SizeChanged(); /** * From CoeControl,CountComponentControls. */ TInt CountComponentControls() const; /** * From CCoeControl,ComponentControl. */ CCoeControl* ComponentControl(TInt aIndex) const; /** * From CCoeControl,Draw. */ void Draw(const TRect& aRect) const; /** * Handle key events. */ TKeyResponse OfferKeyEventL(const TKeyEvent& aKeyEvent,TEventCode aType); /** * From MBrCtlDataLoadSupplier, Cancel an on-going load */ void CancelLoad(); /** * Create a Basic Browser Control that does not have observers with scrolling * and HTTP framework capabilities */ void CreateBasicBrowserControlL(); /** * Create Browser Control with observers with the given capabilities */ void CreateBrowserControlWithObserversL(TUint aCapabilities); /** * Read the file. */ HBufC8* ReadFileLC(const TDesC& aFileName); /** * Handles an event from an observed control. */ void HandleControlEventL(CCoeControl* aControl,TCoeEvent aEventType); /** * The following methods are used to demonstrate the functionality of * the browser control API */ // void BasicBrowserControlL(); void BrowserControlWithObserversL(); void BrowserControlPostWithObserversL(); void LoadingContentWithFileHandleL(); void LoadingContentWithBufferL(); void IncrementalLoadingL(); // void SpecialLoadRequestsL(); void CustomizedDialogsL(); void CustomizedSoftKeysL(); void ResolvingEmbeddedLinksL(); void CustomizedScrollBarsL(); void HandleStateChangedL(); void ChangeSizeExtentsL(); void PageInfoL(); void ContentSizeImageCountL(); void GetBitmapDataL(); void CommandObserverL(); void WidgetHandlerL(); void LoadurlL(); private: //data // Pointer to the browser control interface CBrCtlInterface* iBrCtlInterface; // Desired capabilities of the browser control TUint iBrCtlCapabilities; // Command Base TInt iCommandBase; // Special Load Observer CBrCtlSampleAppSpecialLoadObserver* iBrCtlSampleAppSpecialLoadObserver; // Layout Observer CBrCtlSampleAppLayoutObserver* iBrCtlSampleAppLayoutObserver; // Softkeys Observer CBrCtlSampleAppSoftkeysObserver* iBrCtlSampleAppSoftkeysObserver; // Load Event Observer CBrCtlSampleAppLoadEventObserver* iBrCtlSampleAppLoadEventObserver; // Command Observer CBrCtlSampleAppCommandObserver* iBrCtlSampleAppCommandObserver; // Link Resolver CBrCtlSampleAppLinkResolver* iBrCtlSampleAppLinkResolver; // State Change Observer CBrCtlSampleAppStateChangeObserver* iBrCtlSampleAppStateChangeObserver; // // Dialogs Provider // CBrCtlSampleAppDialogsProvider* iBrCtlSampleAppDialogsProvider; // //Widget Handler // CBrCtlSampleAppWidgetHandler* iBrCtlSampleAppWidgetHandler; // // Informs whether or not CancelLoad has been called TBool iCancelInitDataLoad; // Abstract font interface CFont* iFont; // Text to display to the screen if desired TPtrC iText; // Point at which to display text TPoint iPoint; //icon: favicon or thumbnail CGulIcon* icon; TBool iconFlag; TRect iRect; TBool iRectChanged; CUPPayAppDemo1AppView* iAppView; }; #endif // End of File
[ "zhonghua.lee@gmail.com" ]
zhonghua.lee@gmail.com
b7799b124336aa3cee9e3ab585b6afcc2e705c63
aa238e9d4f0b7ff0e86469b88bd877fde3f2c37f
/be/src/http/http_status.h
44779a2d65acfc2120c10bfc80ae484c93f1835a
[ "Apache-2.0", "BSD-3-Clause", "dtoa", "bzip2-1.0.6", "BSL-1.0", "PSF-2.0" ]
permissive
tengxunshigou/palo
42474a5bcb3933443830c0ea6a1c56dd8f608c45
fb64a1a8e8ed612cd95d1ea0c67bf70804a1d2da
refs/heads/master
2021-01-16T21:13:50.190451
2017-08-11T14:09:07
2017-08-11T14:09:07
100,223,889
1
0
null
2017-08-14T03:18:55
2017-08-14T03:18:55
null
UTF-8
C++
false
false
2,201
h
// Copyright (c) 2017, Baidu.com, Inc. All Rights Reserved // 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 BDG_PALO_BE_SRC_COMMON_UTIL_HTTP_STATUS_H #define BDG_PALO_BE_SRC_COMMON_UTIL_HTTP_STATUS_H #include <string> namespace palo { enum HttpStatus { CONTINUE = 100, SWITCHING_PROTOCOLS = 101, OK = 200, CREATED = 201, ACCEPTED = 202, NON_AUTHORITATIVE_INFORMATION = 203, NO_CONTENT = 204, RESET_CONTENT = 205, PARTIAL_CONTENT = 206, MULTIPLE_CHOICES = 300, MOVED_PERMANENTLY = 301, FOUND = 302, SEE_OTHER = 303, NOT_MODIFIED = 304, USE_PROXY = 305, TEMPORARY_REDIRECT = 307, BAD_REQUEST = 400, UNAUTHORIZED = 401, PAYMENT_REQUIRED = 402, FORBIDDEN = 403, NOT_FOUND = 404, METHOD_NOT_ALLOWED = 405, NOT_ACCEPTABLE = 406, PROXY_AUTHENTICATION = 407, REQUEST_TIMEOUT = 408, CONFLICT = 409, GONE = 410, LENGTH_REQUIRED = 411, PRECONDITION_FAILED = 412, REQUEST_ENTITY_TOO_LARGE = 413, REQUEST_URI_TOO_LONG = 414, UNSUPPORTED_MEDIA_TYPE = 415, REQUESTED_RANGE_NOT_SATISFIED = 416, EXPECTATION_FAILED = 417, INTERNAL_SERVER_ERROR = 500, NOT_IMPLEMENTED = 501, BAD_GATEWAY = 502, SERVICE_UNAVAILABLE = 503, GATEWAY_TIMEOUT = 504, HTTP_VERSION_NOT_SUPPORTED = 505 }; std::string to_code(const HttpStatus& status); std::string defalut_reason(const HttpStatus& status); } #endif
[ "lichaoyong121@qq.com" ]
lichaoyong121@qq.com
259880e592a6f7194dc69f7b054227460ebc06c3
1c83aef38de4e27f54d4664886a431b4fd2caea3
/Engine/Rendering/VertexArray.h
38946e75f40796b05d442f3f7b9e32d28a95b6ee
[]
no_license
quinsmpang/StormBrewerEngine
7a84494debe415c9216586ccfb7d1faf5e0e016f
73f0f3874874909fdf97977737133f5996668410
refs/heads/master
2021-06-21T05:42:34.051588
2017-08-09T08:51:42
2017-08-09T08:51:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
807
h
#pragma once #include "Engine/EngineCommon.h" #include "Engine/Rendering/VertexDefinition.h" #include "Engine/Rendering/ShaderProgram.h" #include "Engine/Rendering/VertexBuffer.h" #ifndef _WEB class ENGINE_EXPORT VertexArray { public: VertexArray(); VertexArray(const VertexArray & rhs) = delete; VertexArray(VertexArray && rhs) noexcept; ~VertexArray(); VertexArray & operator = (VertexArray & rhs) = delete; VertexArray & operator = (VertexArray && rhs) noexcept; void Move(VertexArray && rhs) noexcept; void Destroy(); void CreateDefaultBinding(const ShaderProgram & program, const VertexBuffer & buffer); int GetLoadError() const { return m_LoadError; } void Bind() const; void Unbind() const; private: unsigned int m_VertexArrayName; int m_LoadError; }; #endif
[ "nick.weihs@gmail.com" ]
nick.weihs@gmail.com
4d8a7d81f657c9d3e964834e42b018354bb4fd3e
9b8591c5f2a54cc74c73a30472f97909e35f2ecf
/codegen/QtCharts/QVPieModelMapperSlots.h
80cdd51380059a564216b25016c1cb346d4f1f83
[ "MIT" ]
permissive
tnsr1/Qt5xHb
d3a9396a6ad5047010acd5d8459688e6e07e49c2
04b6bd5d8fb08903621003fa5e9b61b831c36fb3
refs/heads/master
2021-05-17T11:15:52.567808
2020-03-26T06:52:17
2020-03-26T06:52:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
477
h
%% %% Qt5xHb - Bindings libraries for Harbour/xHarbour and Qt Framework 5 %% %% Copyright (C) 2020 Marcos Antonio Gambeta <marcosgambeta AT outlook DOT com> %% $project=Qt5xHb $module=QtCharts $header $includes=5,7,0 using namespace QtCharts; $beginSlotsClass $signal=5,7,0|firstRowChanged() $signal=5,7,0|labelsColumnChanged() $signal=5,7,0|modelReplaced() $signal=5,7,0|rowCountChanged() $signal=5,7,0|seriesReplaced() $signal=5,7,0|valuesColumnChanged() $endSlotsClass
[ "5998677+marcosgambeta@users.noreply.github.com" ]
5998677+marcosgambeta@users.noreply.github.com
73fe1961d66789e1c2691cd2a400574424ccd116
af886cff5033e866c2208f2d179b88ff74d33794
/PCSamples/Graphics/VideoTexturePC12/DeviceResources.h
21b2cc7e8f72d53b4a1eca235b98d4a9eb947700
[]
permissive
tunip3/Xbox-ATG-Samples
c1d1d6c0b9f93c453733a1dada074b357bd6577a
27e30925a46ae5777703361409b8395fed0394d3
refs/heads/master
2020-04-14T08:37:00.614182
2018-12-14T02:38:01
2018-12-14T02:38:01
163,739,353
3
0
MIT
2019-01-01T13:38:37
2019-01-01T13:38:37
null
UTF-8
C++
false
false
6,572
h
// // DeviceResources.h - A wrapper for the Direct3D 12 device and swapchain // #pragma once namespace DX { // Provides an interface for an application that owns DeviceResources to be notified of the device being lost or created. interface IDeviceNotify { virtual void OnDeviceLost() = 0; virtual void OnDeviceRestored() = 0; }; // Controls all the DirectX device resources. class DeviceResources { public: static const unsigned int c_AllowTearing = 0x1; static const unsigned int c_EnableHDR = 0x2; DeviceResources(DXGI_FORMAT backBufferFormat = DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT depthBufferFormat = DXGI_FORMAT_D32_FLOAT, UINT backBufferCount = 2, D3D_FEATURE_LEVEL minFeatureLevel = D3D_FEATURE_LEVEL_11_0, unsigned int flags = 0) noexcept(false); ~DeviceResources(); void CreateDeviceResources(); void CreateWindowSizeDependentResources(); void SetWindow(HWND window, int width, int height); bool WindowSizeChanged(int width, int height); void HandleDeviceLost(); void RegisterDeviceNotify(IDeviceNotify* deviceNotify) { m_deviceNotify = deviceNotify; } void Prepare(D3D12_RESOURCE_STATES beforeState = D3D12_RESOURCE_STATE_PRESENT); void Present(D3D12_RESOURCE_STATES beforeState = D3D12_RESOURCE_STATE_RENDER_TARGET); void WaitForGpu() noexcept; // Device Accessors. RECT GetOutputSize() const { return m_outputSize; } // Direct3D Accessors. ID3D12Device* GetD3DDevice() const { return m_d3dDevice.Get(); } IDXGISwapChain3* GetSwapChain() const { return m_swapChain.Get(); } IDXGIFactory4* GetDXGIFactory() const { return m_dxgiFactory.Get(); } D3D_FEATURE_LEVEL GetDeviceFeatureLevel() const { return m_d3dFeatureLevel; } ID3D12Resource* GetRenderTarget() const { return m_renderTargets[m_backBufferIndex].Get(); } ID3D12Resource* GetDepthStencil() const { return m_depthStencil.Get(); } ID3D12CommandQueue* GetCommandQueue() const { return m_commandQueue.Get(); } ID3D12CommandAllocator* GetCommandAllocator() const { return m_commandAllocators[m_backBufferIndex].Get(); } ID3D12GraphicsCommandList* GetCommandList() const { return m_commandList.Get(); } DXGI_FORMAT GetBackBufferFormat() const { return m_backBufferFormat; } DXGI_FORMAT GetDepthBufferFormat() const { return m_depthBufferFormat; } D3D12_VIEWPORT GetScreenViewport() const { return m_screenViewport; } D3D12_RECT GetScissorRect() const { return m_scissorRect; } UINT GetCurrentFrameIndex() const { return m_backBufferIndex; } UINT GetBackBufferCount() const { return m_backBufferCount; } DXGI_COLOR_SPACE_TYPE GetColorSpace() const { return m_colorSpace; } unsigned int GetDeviceOptions() const { return m_options; } CD3DX12_CPU_DESCRIPTOR_HANDLE GetRenderTargetView() const { return CD3DX12_CPU_DESCRIPTOR_HANDLE(m_rtvDescriptorHeap->GetCPUDescriptorHandleForHeapStart(), m_backBufferIndex, m_rtvDescriptorSize); } CD3DX12_CPU_DESCRIPTOR_HANDLE GetDepthStencilView() const { return CD3DX12_CPU_DESCRIPTOR_HANDLE(m_dsvDescriptorHeap->GetCPUDescriptorHandleForHeapStart()); } private: void MoveToNextFrame(); void GetAdapter(IDXGIAdapter1** ppAdapter); void UpdateColorSpace(); static const size_t MAX_BACK_BUFFER_COUNT = 3; UINT m_backBufferIndex; // Direct3D objects. Microsoft::WRL::ComPtr<ID3D12Device> m_d3dDevice; Microsoft::WRL::ComPtr<ID3D12CommandQueue> m_commandQueue; Microsoft::WRL::ComPtr<ID3D12GraphicsCommandList> m_commandList; Microsoft::WRL::ComPtr<ID3D12CommandAllocator> m_commandAllocators[MAX_BACK_BUFFER_COUNT]; // Swap chain objects. Microsoft::WRL::ComPtr<IDXGIFactory4> m_dxgiFactory; Microsoft::WRL::ComPtr<IDXGISwapChain3> m_swapChain; Microsoft::WRL::ComPtr<ID3D12Resource> m_renderTargets[MAX_BACK_BUFFER_COUNT]; Microsoft::WRL::ComPtr<ID3D12Resource> m_depthStencil; // Presentation fence objects. Microsoft::WRL::ComPtr<ID3D12Fence> m_fence; UINT64 m_fenceValues[MAX_BACK_BUFFER_COUNT]; Microsoft::WRL::Wrappers::Event m_fenceEvent; // Direct3D rendering objects. Microsoft::WRL::ComPtr<ID3D12DescriptorHeap> m_rtvDescriptorHeap; Microsoft::WRL::ComPtr<ID3D12DescriptorHeap> m_dsvDescriptorHeap; UINT m_rtvDescriptorSize; D3D12_VIEWPORT m_screenViewport; D3D12_RECT m_scissorRect; // Direct3D properties. DXGI_FORMAT m_backBufferFormat; DXGI_FORMAT m_depthBufferFormat; UINT m_backBufferCount; D3D_FEATURE_LEVEL m_d3dMinFeatureLevel; // Cached device properties. HWND m_window; D3D_FEATURE_LEVEL m_d3dFeatureLevel; DWORD m_dxgiFactoryFlags; RECT m_outputSize; // HDR Support DXGI_COLOR_SPACE_TYPE m_colorSpace; // DeviceResources options (see flags above) unsigned int m_options; // The IDeviceNotify can be held directly as it owns the DeviceResources. IDeviceNotify* m_deviceNotify; }; }
[ "chuckw@windows.microsoft.com" ]
chuckw@windows.microsoft.com
2465ef4b26b60aa47797c16e5d5c9ee85b13433f
2442e2798dd379a5adeebfa392728720e6d14015
/Promise.h
67e5dcc1248b893f5d793fb22eb154563c688879
[]
no_license
Amoniy/cpp-second-year-hometasks
38e9c5c54ff0c02106c99c84cedb63d266fcc2d6
03a3615edcdd8221d0fc944eacdffb61c0623740
refs/heads/master
2021-09-28T08:12:03.654931
2018-11-15T20:54:49
2018-11-15T20:54:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,161
h
#pragma once #include <functional> #include "Future.h" template<typename T> class Promise { void ensureInitialized() const { if (!state) { throw std::runtime_error("Promise does not have state"); } } public: void setPool(ThreadPool *threadPool) { state->threadPool = threadPool; } Promise() : state(std::make_shared<FutureState<T> >()), futureExists(false) { state->hasPromise = true; } Promise(Promise<T> &&promise) noexcept : state(std::move(promise.state)), futureExists(promise.futureExists.load()) { futureExists = promise.futureExists ? true : false; } ~Promise() { if (state) { state->hasPromise = false; state->conditionVariable.notify_one(); } } Promise &operator=(Promise<T> &&promise) noexcept { futureExists = promise.futureExists.load(); state = std::move(promise.state); return *this; }; Promise(Promise<T> const &) = delete; Promise &operator=(Promise<T> const &) = delete; Future<T> getFuture() { if (futureExists) { throw std::runtime_error("Future already set"); } futureExists = true; return Future<T>(state); } void set(const T &value) { ensureInitialized(); std::unique_lock<std::mutex> lock(state->mutex); if (state->isReady) { throw std::runtime_error("value already set"); } state->value = value; state->isReady = true; state->conditionVariable.notify_one(); } void set(T &&v) { ensureInitialized(); std::unique_lock<std::mutex> lock(state->mutex); if (state->isReady) { throw std::runtime_error("value already set"); } state->value = std::move(v); state->isReady = true; state->conditionVariable.notify_one(); } void setException(const std::exception_ptr &exceptionPtr) { ensureInitialized(); std::unique_lock<std::mutex> lock(state->mutex); if (state->exceptionPtr) { throw std::runtime_error("error already set"); } state->exceptionPtr = exceptionPtr; state->isReady = true; state->conditionVariable.notify_one(); } private: std::shared_ptr<FutureState<T> > state; std::atomic<bool> futureExists; }; template<> class Promise<void> { void ensureInitialized() const { if (!state) { throw std::runtime_error("Promise does not have state"); } } public: Promise() : state(std::make_shared<FutureState<void> >()), futureExists(false) { state->hasPromise = true; } ~Promise() { if (state) { state->hasPromise = false; state->conditionVariable.notify_one(); } } Promise(Promise<void> &&promise) noexcept : state(std::move(promise.state)), futureExists(promise.futureExists.load()) { } Promise &operator=(Promise<void> &&promise) noexcept { futureExists = promise.futureExists.load(); state = std::move(promise.state); return *this; }; Promise(Promise<void> const &) = delete; Promise &operator=(Promise<void> const &) = delete; Future<void> getFuture() { if (futureExists) { throw std::runtime_error("Future already set"); } futureExists = true; return Future<void>(state); } void set() { ensureInitialized(); if (state->isReady) { throw std::runtime_error("value already set"); } state->isReady = true; state->conditionVariable.notify_one(); } void setException(const std::exception_ptr &exceptionPtr) { ensureInitialized(); std::unique_lock<std::mutex> lock(state->mutex); if (state->exceptionPtr) { throw std::runtime_error("error already set"); } state->exceptionPtr = exceptionPtr; state->isReady = true; state->conditionVariable.notify_one(); }; private: std::shared_ptr<FutureState<void> > state; std::atomic<bool> futureExists; }; template<typename T> class Promise<T &> { void ensureInitialized() const { if (!state) { throw std::runtime_error("Promise does not have state"); } } public: Promise() : state(std::make_shared<FutureState<T &> >()), futureExists(false) { state->hasPromise = true; } ~Promise() { if (state) { state->hasPromise = false; state->conditionVariable.notify_one(); } } Promise(Promise &&promise) noexcept : state(std::move(promise.state)), futureExists(promise.futureExists.load()) { } Promise &operator=(Promise &&promise) noexcept { futureExists = promise.futureExists.load(); state = std::move(promise.state); return *this; }; Promise(const Promise &) = delete; Promise &operator=(const Promise &) = delete; Future<T &> getFuture() { if (futureExists) { throw std::runtime_error("Future already set"); } futureExists = true; return Future<T &>(state); } void set(T &v) { ensureInitialized(); std::unique_lock<std::mutex> lock(state->mutex); if (state->isReady) { throw std::runtime_error("value already set"); } state->value = &v; state->isReady = true; state->conditionVariable.notify_one(); } void setException(const std::exception_ptr &exceptionPtr) { ensureInitialized(); std::unique_lock<std::mutex> lock(state->mutex); if (state->exceptionPtr) { throw std::runtime_error("error already set"); } state->exceptionPtr = exceptionPtr; state->isReady = true; state->conditionVariable.notify_one(); } private: std::shared_ptr<FutureState<T &> > state; std::atomic<bool> futureExists; };
[ "anton17.04.1998@gmail.com" ]
anton17.04.1998@gmail.com
8b32a8635834168d57c311d5b8419347f8e3f639
cd004ef6ad32218c7153bd8c06cc83818975154a
/FDK/LrpCommon/Server_Server.hpp
f086164d79722a0e9a51d1a3fc33f5d05429982d
[ "MIT" ]
permissive
marmysh/FDK
11b7890c26f7aa024af8ea82fcb7c141326d2e6f
cc6696a8eded9355e4789b0193872332f46cb792
refs/heads/master
2020-12-14T18:56:28.229987
2016-07-13T13:50:42
2016-07-13T13:50:42
63,467,798
1
0
null
2016-07-16T05:51:14
2016-07-16T05:51:14
null
UTF-8
C++
false
false
10,000
hpp
// This is always generated file. Do not change anything. // handlers of Server component namespace { const unsigned short LrpComponent_Server_Id = 0; const unsigned short LrpMethod_Server_OnHeartBeatRequest_Id = 0; const unsigned short LrpMethod_Server_OnHeartBeatResponse_Id = 1; const unsigned short LrpMethod_Server_OnCurrenciesInfoRequest_Id = 2; const unsigned short LrpMethod_Server_OnSymbolsInfoRequest_Id = 3; const unsigned short LrpMethod_Server_OnSessionInfoRequest_Id = 4; const unsigned short LrpMethod_Server_OnSubscribeToQuotesRequest_Id = 5; const unsigned short LrpMethod_Server_OnUnsubscribeQuotesRequest_Id = 6; const unsigned short LrpMethod_Server_OnComponentsInfoRequest_Id = 7; const unsigned short LrpMethod_Server_OnDataHistoryRequest_Id = 8; const unsigned short LrpMethod_Server_OnFileChunkRequest_Id = 9; const unsigned short LrpMethod_Server_OnBarsHistoryMetaInfoFileRequest_Id = 10; const unsigned short LrpMethod_Server_OnQuotesHistoryMetaInfoFileRequest_Id = 11; typedef void (*LrpInvoke_Server_Method_Handler)(size_t offset, MemoryBuffer& buffer, LrpChannel* pChannel); void LrpInvoke_Server_OnHeartBeatRequest(size_t offset, MemoryBuffer& buffer, LrpChannel* pChannel) { pChannel;// if all methods of LrpChannel are static then the next line generates warning #4100 auto& component = pChannel->GetServer(); component; // if all methods of component are static then the next line generates warning #4189 component.OnHeartBeatRequest(); buffer.Reset(offset); } void LrpInvoke_Server_OnHeartBeatResponse(size_t offset, MemoryBuffer& buffer, LrpChannel* pChannel) { pChannel;// if all methods of LrpChannel are static then the next line generates warning #4100 auto& component = pChannel->GetServer(); component; // if all methods of component are static then the next line generates warning #4189 component.OnHeartBeatResponse(); buffer.Reset(offset); } void LrpInvoke_Server_OnCurrenciesInfoRequest(size_t offset, MemoryBuffer& buffer, LrpChannel* pChannel) { pChannel;// if all methods of LrpChannel are static then the next line generates warning #4100 auto& component = pChannel->GetServer(); component; // if all methods of component are static then the next line generates warning #4189 auto arg0 = ReadAString(buffer); component.OnCurrenciesInfoRequest(arg0); buffer.Reset(offset); } void LrpInvoke_Server_OnSymbolsInfoRequest(size_t offset, MemoryBuffer& buffer, LrpChannel* pChannel) { pChannel;// if all methods of LrpChannel are static then the next line generates warning #4100 auto& component = pChannel->GetServer(); component; // if all methods of component are static then the next line generates warning #4189 auto arg0 = ReadAString(buffer); component.OnSymbolsInfoRequest(arg0); buffer.Reset(offset); } void LrpInvoke_Server_OnSessionInfoRequest(size_t offset, MemoryBuffer& buffer, LrpChannel* pChannel) { pChannel;// if all methods of LrpChannel are static then the next line generates warning #4100 auto& component = pChannel->GetServer(); component; // if all methods of component are static then the next line generates warning #4189 auto arg0 = ReadAString(buffer); component.OnSessionInfoRequest(arg0); buffer.Reset(offset); } void LrpInvoke_Server_OnSubscribeToQuotesRequest(size_t offset, MemoryBuffer& buffer, LrpChannel* pChannel) { pChannel;// if all methods of LrpChannel are static then the next line generates warning #4100 auto& component = pChannel->GetServer(); component; // if all methods of component are static then the next line generates warning #4189 auto arg0 = ReadAString(buffer); auto arg1 = ReadAStringArray(buffer); auto arg2 = ReadInt32(buffer); component.OnSubscribeToQuotesRequest(arg0, arg1, arg2); buffer.Reset(offset); } void LrpInvoke_Server_OnUnsubscribeQuotesRequest(size_t offset, MemoryBuffer& buffer, LrpChannel* pChannel) { pChannel;// if all methods of LrpChannel are static then the next line generates warning #4100 auto& component = pChannel->GetServer(); component; // if all methods of component are static then the next line generates warning #4189 auto arg0 = ReadAString(buffer); auto arg1 = ReadAStringArray(buffer); component.OnUnsubscribeQuotesRequest(arg0, arg1); buffer.Reset(offset); } void LrpInvoke_Server_OnComponentsInfoRequest(size_t offset, MemoryBuffer& buffer, LrpChannel* pChannel) { pChannel;// if all methods of LrpChannel are static then the next line generates warning #4100 auto& component = pChannel->GetServer(); component; // if all methods of component are static then the next line generates warning #4189 auto arg0 = ReadAString(buffer); auto arg1 = ReadInt32(buffer); component.OnComponentsInfoRequest(arg0, arg1); buffer.Reset(offset); } void LrpInvoke_Server_OnDataHistoryRequest(size_t offset, MemoryBuffer& buffer, LrpChannel* pChannel) { pChannel;// if all methods of LrpChannel are static then the next line generates warning #4100 auto& component = pChannel->GetServer(); component; // if all methods of component are static then the next line generates warning #4189 auto arg0 = ReadAString(buffer); auto arg1 = ReadDataHistoryRequest(buffer); component.OnDataHistoryRequest(arg0, arg1); buffer.Reset(offset); } void LrpInvoke_Server_OnFileChunkRequest(size_t offset, MemoryBuffer& buffer, LrpChannel* pChannel) { pChannel;// if all methods of LrpChannel are static then the next line generates warning #4100 auto& component = pChannel->GetServer(); component; // if all methods of component are static then the next line generates warning #4189 auto arg0 = ReadAString(buffer); auto arg1 = ReadAString(buffer); auto arg2 = ReadUInt32(buffer); component.OnFileChunkRequest(arg0, arg1, arg2); buffer.Reset(offset); } void LrpInvoke_Server_OnBarsHistoryMetaInfoFileRequest(size_t offset, MemoryBuffer& buffer, LrpChannel* pChannel) { pChannel;// if all methods of LrpChannel are static then the next line generates warning #4100 auto& component = pChannel->GetServer(); component; // if all methods of component are static then the next line generates warning #4189 auto arg0 = ReadAString(buffer); auto arg1 = ReadAString(buffer); auto arg2 = ReadInt32(buffer); auto arg3 = ReadAString(buffer); component.OnBarsHistoryMetaInfoFileRequest(arg0, arg1, arg2, arg3); buffer.Reset(offset); } void LrpInvoke_Server_OnQuotesHistoryMetaInfoFileRequest(size_t offset, MemoryBuffer& buffer, LrpChannel* pChannel) { pChannel;// if all methods of LrpChannel are static then the next line generates warning #4100 auto& component = pChannel->GetServer(); component; // if all methods of component are static then the next line generates warning #4189 auto arg0 = ReadAString(buffer); auto arg1 = ReadAString(buffer); auto arg2 = ReadBoolean(buffer); component.OnQuotesHistoryMetaInfoFileRequest(arg0, arg1, arg2); buffer.Reset(offset); } LrpInvoke_Server_Method_Handler gServerHandlers[] = { LrpInvoke_Server_OnHeartBeatRequest, LrpInvoke_Server_OnHeartBeatResponse, LrpInvoke_Server_OnCurrenciesInfoRequest, LrpInvoke_Server_OnSymbolsInfoRequest, LrpInvoke_Server_OnSessionInfoRequest, LrpInvoke_Server_OnSubscribeToQuotesRequest, LrpInvoke_Server_OnUnsubscribeQuotesRequest, LrpInvoke_Server_OnComponentsInfoRequest, LrpInvoke_Server_OnDataHistoryRequest, LrpInvoke_Server_OnFileChunkRequest, LrpInvoke_Server_OnBarsHistoryMetaInfoFileRequest, LrpInvoke_Server_OnQuotesHistoryMetaInfoFileRequest, }; HRESULT LrpInvoke_Server(size_t offset, size_t methodId, MemoryBuffer& buffer, LrpChannel* pChannel) { if(methodId >= 12) { return LRP_INVALID_METHOD_ID; } gServerHandlers[methodId](offset, buffer, pChannel); return S_OK; } } // components handler namespace { typedef HRESULT (*LrpInvoke_Component_Handler)(size_t offset, size_t methodId, MemoryBuffer& buffer, LrpChannel* pChannel); LrpInvoke_Component_Handler gHandlers[] = { LrpInvoke_Server, }; } namespace { HRESULT LrpInvokeEx(size_t offset, size_t componentId, size_t methodId, MemoryBuffer& buffer, LrpChannel* pChannel) { if(componentId >= 1) { return LRP_INVALID_COMPONENT_ID; } HRESULT result = LRP_EXCEPTION; try { try { result = gHandlers[componentId](offset, methodId, buffer, pChannel); return result; } catch(const std::exception& e) { buffer.Reset(offset); WriteInt32(-1, buffer); WriteAString(e.what(), buffer); } catch(...) { result = E_FAIL; } } catch(...) { result = E_FAIL; } return result; } } extern "C" HRESULT __stdcall LrpInvoke(unsigned __int16 componentId, unsigned __int16 methodId, void* heap, unsigned __int32* pSize, void** ppData, unsigned __int32* pCapacity) { MemoryBuffer buffer(heap, *ppData, *pSize, *pCapacity); HRESULT result = LrpInvokeEx(0, componentId, methodId, buffer, nullptr); *pSize = static_cast<unsigned __int32>(buffer.GetSize()); *ppData = buffer.GetData(); *pCapacity = static_cast<unsigned __int32>(buffer.GetCapacity()); buffer = MemoryBuffer(); return result; } extern "C" const char* __stdcall LrpSignature() { return "$Exceptions;" "$Server;" "OnHeartBeatRequest@649F60FAC31A75EF0179222C5C27655D;" "OnHeartBeatResponse@53584CC68A5EF9F98311B4D86431576D;" "OnCurrenciesInfoRequest@E6F0091DB9E7B73AE0CEA7CD77318241;" "OnSymbolsInfoRequest@83BCDF2EEBC55F2EF1AEFBCE150E9FCF;" "OnSessionInfoRequest@A941B0F5C96CF054661A0F6925751F99;" "OnSubscribeToQuotesRequest@48BD3703EA5F3D3D116930EC0F7D6E5B;" "OnUnsubscribeQuotesRequest@65D0C196E1F746602C717772463A9910;" "OnComponentsInfoRequest@80705679A4CE1A94C0A95C109D91661A;" "OnDataHistoryRequest@A51124B279EE15597282498B005B2ACF;" "OnFileChunkRequest@EFEF9C78B68ED7950A413964030A0149;" "OnBarsHistoryMetaInfoFileRequest@C9559DB271D8ACDD57378A460FB87FED;" "OnQuotesHistoryMetaInfoFileRequest@84B7650F68B7EE82E499673405B98DA0;" ""; }
[ "chronoxor@gmail.com" ]
chronoxor@gmail.com
431fbd28ad5e4a08b800cd51c12b59ce88c90ecf
a179a141970ac96057643f09b97871709097c2a4
/GFG/BT_BST/delete_tree.cpp
cde75a8599906a3bcde578c6854728a67e941b8f
[]
no_license
rahulranjan96/Programming
7ce784b31300d0703149f2e60d8a2923247f6399
dbd4a0bef7dc667f6505d59b9ed5177927bb63c5
refs/heads/master
2021-03-24T10:18:41.811818
2016-10-25T04:45:49
2016-10-25T04:45:49
71,860,279
0
0
null
null
null
null
UTF-8
C++
false
false
1,304
cpp
#include <iostream> #include <cstdio> #include <cstdlib> #include <queue> #include <stack> using namespace std; typedef struct Node{ int key; struct Node *left; struct Node *right; }node; node* insert(node *root,int key) { if(root==NULL) { root=(node*)malloc(sizeof(node)); root->key=key; root->left=NULL; root->right=NULL; } else if(key>=root->key) root->right=insert(root->right,key); else if(key<root->key) root->left=insert(root->left,key); return root; } void deleteTree(node *root) { if(root!=NULL) { delete(root->left); delete(root->right); free(root); } } void inorder(node *root) { if(root!=NULL) { inorder(root->left); cout<<root->key<<" "; inorder(root->right); } } int main() { int c,key; node *root=NULL; while(1) { cout<<"1:Insert\n2:Print\n3:Delete\n4:Exit\nEnter Choice:"; cin>>c; switch(c) { case 1:cout<<"Enter key to be inserted:"; cin>>key; root=insert(root,key); break; case 2:inorder(root); cout<<endl; break; case 3:deleteTree(root); root=NULL; break; case 4:return 0; default:cout<<"Please enter a valid choice\n"; } } return 0; }
[ "rahulranjanyadav96@gmail.com" ]
rahulranjanyadav96@gmail.com
191b7755965470350479a03e49b33d1c77cb892a
b516ffaa751c248a0f085e165e0da022dcd97df4
/BonEngine/inc/Engine/Engine.h
ef849b97d9e41f19a8d67d97defdeb9b42a4ce5b
[ "MIT" ]
permissive
parhelia512/BonEngine
0c90909cb15cfaa73a2d7da69e1b0b85fc8dec0d
49cec684c2307715df0958ed673ff077eac0a395
refs/heads/master
2023-02-17T14:22:24.429552
2021-07-30T21:05:33
2021-07-30T21:05:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,411
h
/*****************************************************************//** * \file Engine.h * \brief Define the main class that manage the game main loop. * * \author Ronen Ness * \date May 2020 *********************************************************************/ #pragma once #include "../dllimport.h" #include "../Assets/IAssets.h" #include "../Gfx/IGfx.h" #include "../Sfx/ISfx.h" #include "../Game/IGame.h" #include "../Input/IInput.h" #include "../Log/ILog.h" #include "../UI/IUI.h" #include "../Diagnostics/IDiagnostics.h" #include "../Framework/Exceptions.h" #include "Defs.h" #include <vector> #pragma warning ( push ) #pragma warning ( disable: 4251 ) // "..needs to have dll-interface to be used by clients..." it's ok in this case because its private. namespace bon { namespace engine { /** * The main class that runs the BonEngine engine. * This is the class that gets instanciated and fire up the game main loop. */ class BON_DLLEXPORT Engine { private: // is the engine currently running? bool _isRunning = false; // active managers - you can replace them before Start() is called. assets::IAssets* _assetsManager = nullptr; gfx::IGfx* _gfxManager = nullptr; sfx::ISfx* _sfxManager = nullptr; game::IGame* _gameManager = nullptr; input::IInput* _inputManager = nullptr; log::ILog* _logManager = nullptr; diagnostics::IDiagnostics* _diagnosticsManager = nullptr; ui::IUI* _uiManager = nullptr; // list of all manager instances std::vector<IManager*> _managers; std::vector<IManager*> _customManagers; // how many times the active scene got switched unsigned int _scenesSwitchCount = 0; // engine state EngineStates _state = EngineStates::BeforeInitialize; // currently active scene Scene* _activeScene = nullptr; Scene* _previousScene = nullptr; Scene* _nextScene = nullptr; // mark if engine is being destroyed bool _destroyed = false; // mark if the main loop have started during this run. note: this doesn't mean that engine wasn't already closed. bool _mainLoopStarted = false; // count update frames unsigned long long _updatesCount = 0; // count fixed update frames unsigned long long _fixedUpdatesCount = 0; // total elapsed time since application started double _elapsedTime = 0.0; public: /** * Fixed updates inverval, in seconds. */ double FixedUpdatesInterval = 30.0 / 1000.0; /** * Start running the engine. * * \param scene Active scene to set on start. */ void Start(Scene& startingScene); /** * Stop running the engine. * This will end the application. */ void Stop(); /** * Set the currently active scene. * Note: will actually change the scene after current frame ends. * * \param scene Active scene to set. */ void SetScene(Scene& scene); /** * Set the currently active assets manager. * Note: the pointer you set must not be deleted until the end of the program, unless you replace it manually. * * \param manager New assets manager. */ inline void SetAssetsManager(assets::IAssets* manager) { AssertIfRunning(); _assetsManager = manager; } /** * Get assets manager instance. * * \return Assets manager. */ inline assets::IAssets& Assets() { return *_assetsManager; } /** * Set the currently active gfx manager. * Note: the pointer you set must not be deleted until the end of the program, unless you replace it manually. * * \param manager New gfx manager. */ inline void SetGfxManager(gfx::IGfx* manager) { AssertIfRunning(); _gfxManager = manager; } /** * Get gfx manager instance. * * \return Gfx manager. */ inline gfx::IGfx& Gfx() { return *_gfxManager; } /** * Set the currently active sfx manager. * Note: the pointer you set must not be deleted until the end of the program, unless you replace it manually. * * \param manager New sfx manager. */ inline void SetSfxManager(sfx::ISfx* manager) { AssertIfRunning(); _sfxManager = manager; } /** * Get sfx manager instance. * * \return Sfx manager. */ inline sfx::ISfx& Sfx() { return *_sfxManager; } /** * Set the currently active game manager. * Note: the pointer you set must not be deleted until the end of the program, unless you replace it manually. * * \param manager New game manager. */ inline void SetGameManager(game::IGame* manager) { AssertIfRunning(); _gameManager = manager; } /** * Get game manager instance. * * \return Game manager. */ inline game::IGame& Game() { return *_gameManager; } /** * Set the currently active input manager. * Note: the pointer you set must not be deleted until the end of the program, unless you replace it manually. * * \param manager New input manager. */ inline void SetInputManager(input::IInput* manager) { AssertIfRunning(); _inputManager = manager; } /** * Get input manager instance. * * \return Input manager. */ inline input::IInput& Input() { return *_inputManager; } /** * Set the currently active log manager. * Note: the pointer you set must not be deleted until the end of the program, unless you replace it manually. * * \param manager New log manager. */ inline void SetLogManager(log::ILog* manager) { AssertIfRunning(); _logManager = manager; } /** * Get log manager instance. * * \return log manager. */ inline log::ILog& Log() { return *_logManager; } /** * Set the currently active diagnostics manager. * Note: the pointer you set must not be deleted until the end of the program, unless you replace it manually. * * \param manager New diagnostics manager. */ inline void SetDiagnosticsManager(diagnostics::IDiagnostics* manager) { AssertIfRunning(); _diagnosticsManager = manager; } /** * Get diagnostics manager instance. * * \return diagnostics manager. */ inline diagnostics::IDiagnostics& Diagnostics() { return *_diagnosticsManager; } /** * Set the currently active ui manager. * Note: the pointer you set must not be deleted until the end of the program, unless you replace it manually. * * \param manager New UI manager. */ inline void SetUIManager(ui::IUI* manager) { AssertIfRunning(); _uiManager = manager; } /** * Get UI manager instance. * * \return UI manager. */ inline ui::IUI& UI() { return *_uiManager; } /** * Register a custom manager class. * * \param manager Manager to add. */ void RegisterCustomManager(IManager* manager); /** * Get if the engine is currently running. * * \return If engine is running. */ inline bool Running() const { return _isRunning; } /** * Get if the engine started the disposing sequence. * Thins may behave unexpectedly during this time. * * \return If engine is destroyed / being destroyed. */ inline bool Destroyed() const { return _destroyed; } /** * Get manager by id. * This method is slower so it is recommended to cache the manager after getting it. * For built-in managers, use the specific getters. * * \param id Manager id to get. * \return Manager instance. */ IManager* GetManagerById(const char* id); /** * Get how many update calls we had since main loop started. * * \return Updates count. */ inline unsigned long long UpdatesCount() const { return _updatesCount; } /** * Get how many fixed update calls we had since main loop started. * * \return Updates count. */ inline unsigned long long FixedUpdatesCount() const { return _fixedUpdatesCount; } /** * Return engine's current state. * * \return Engine's state. */ inline EngineStates CurrentState() const { return _state; } /** * Get the previously loaded scene. * Note: scene may already be deleted at this point. * * \return Previous scene, or nullptr if called from first scene loaded. */ inline Scene* PreviousScene() const { return _previousScene; } /** * Get the currently active scene. * * \return Active scene, or nullptr if not set yet. */ inline Scene* ActiveScene() const { return _activeScene; } /** * Get how many times we switched scenes. * * \return How many times we switched scenes. */ inline unsigned int SwitchedScenesCount() const { return _scenesSwitchCount; } private: /** * Throw exception if engine is running. */ inline void AssertIfRunning() const { if (_isRunning) { throw framework::InvalidState("Cannot perform this action after engine had started!"); } } /** * Throw exception if engine is NOT running. */ inline void AssertIfNotRunning() const { if (!_isRunning) { throw framework::InvalidState("Cannot perform this action before engine had started!"); } } /** * Do the actual scene switch, from _activeScene to _nextScene. */ void DoSceneSwitch(); /** * Start the engine's main loop. */ void StartMainLoop(); /** * Cleanup resources after main loop ends. */ void CleanUp(); }; } } #pragma warning (pop)
[ "RonenNess@gmail.com" ]
RonenNess@gmail.com
5cd51f2eefe35c079bf0a6b95fd417d0fa910f53
e672c441b7cb2fbfc5af72b18a6c7cd1621efc7d
/general/base/ChatParsing.cpp
4ab2925295aa715b532ad5c8997bbe65bc99cf15
[]
no_license
tgjklmda/CatchChallenger
f7b16da8ebcd3ef61e08c6e51015d49c4e8cbefb
beea053f581ecf9732aa887c6b6e5e4ff8769e9e
refs/heads/master
2020-12-25T12:28:10.163407
2013-02-14T13:23:46
2013-02-14T13:23:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,411
cpp
#include "ChatParsing.h" using namespace CatchChallenger; QString ChatParsing::new_chat_message(QString pseudo,Player_type player_type,Chat_type chat_type,QString text) { QString returned_html; returned_html+="<div style=\""; switch(chat_type) { case Chat_type_local://local break; case Chat_type_all://all break; case Chat_type_clan://clan returned_html+="color:#FFBF00;"; break; case Chat_type_aliance://aliance returned_html+="color:#60BF20;"; break; case Chat_type_pm://to player returned_html+="color:#5C255F;"; break; case Chat_type_system://system returned_html+="color:#707070;font-style:italic;font-size:small;"; break; case Chat_type_system_important://system importance: hight returned_html+="color:#60BF20;"; break; default: break; } switch(player_type) { case Player_type_normal://normal player break; case Player_type_premium://premium player break; case Player_type_gm://gm returned_html+="font-weight:bold;"; break; case Player_type_dev://dev returned_html+="font-weight:bold;"; break; default: break; } returned_html+="\">"; switch(player_type) { case Player_type_normal://normal player break; case Player_type_premium://premium player returned_html+="<img src=\":/images/chat/premium.png\" alt\"\" />"; break; case Player_type_gm://gm returned_html+="<img src=\":/images/chat/admin.png\" alt\"\" />"; break; case Player_type_dev://dev returned_html+="<img src=\":/images/chat/developer.png\" alt\"\" />"; break; default: break; } if(chat_type==Chat_type_system || chat_type==Chat_type_system_important) returned_html+=QString("%1").arg(text); else returned_html+=QString("%1: %2").arg(pseudo).arg(toSmilies(toHtmlEntities(text))); returned_html+="</div>"; return returned_html; } QString ChatParsing::toHtmlEntities(QString text) { text.replace("&","&amp;"); text.replace("\"","&quot;"); text.replace("'","&#039;"); text.replace("<","&lt;"); text.replace(">","&gt;"); return text; } QString ChatParsing::toSmilies(QString text) { text.replace(":)","<img src=\":/images/smiles/face-smile.png\" alt=\"\" style=\"vertical-align:middle;\" />"); text.replace(":|","<img src=\":/images/smiles/face-plain.png\" alt=\"\" style=\"vertical-align:middle;\" />"); text.replace(":(","<img src=\":/images/smiles/face-sad.png\" alt=\"\" style=\"vertical-align:middle;\" />"); text.replace(":P","<img src=\":/images/smiles/face-raspberry.png\" alt=\"\" style=\"vertical-align:middle;\" />"); text.replace(":p","<img src=\":/images/smiles/face-raspberry.png\" alt=\"\" style=\"vertical-align:middle;\" />"); text.replace(":D","<img src=\":/images/smiles/face-laugh.png\" alt=\"\" style=\"vertical-align:middle;\" />"); text.replace(":o","<img src=\":/images/smiles/face-surprise.png\" alt=\"\" style=\"vertical-align:middle;\" />"); text.replace(";)","<img src=\":/images/smiles/face-wink.png\" alt=\"\" style=\"vertical-align:middle;\" />"); return text; }
[ "alpha_one_x86@first-world.info" ]
alpha_one_x86@first-world.info
817395801d2ef98d2a8fc9abaedd094fc60a9632
8c46efa71edb8413bb46deb36b347627834a0c77
/Common/math/triangle.cpp
2bb95e19975d28924fbaaa8701266a76408f0f92
[ "MIT" ]
permissive
azhugg/Common
4f5b08d3f8dc66936b7eb243a5db2b3379fba06a
239caba7912454a239e2162cad479fb1dd4ced7e
refs/heads/master
2021-08-18T18:58:12.723498
2017-11-23T15:41:11
2017-11-23T15:41:11
null
0
0
null
null
null
null
UHC
C++
false
false
1,992
cpp
#include "stdafx.h" #include "triangle.h" using namespace common; Triangle::Triangle() { } Triangle::Triangle( const Vector3& v1, const Vector3& v2, const Vector3 &v3 ): a(v1), b(v2), c( v3 ) { } // Init void Triangle::Create( const Vector3& v1, const Vector3& v2, const Vector3& v3 ) { a = v1; b = v2; c = v3; } // Triangle::Intersect //pfT, pfU, pfV : out BOOL Triangle::Intersect( const Vector3& vOrig, const Vector3& vDir, float *pfT, float *pfU, float *pfV ) const { static float u, v; // Find vectors for two edges sharing vert0 static Vector3 vEdge1; static Vector3 vEdge2; vEdge1 = b - a; vEdge2 = c - a; // Begin calculating determinant - also used to calculate U parameter static Vector3 vP; vP = vDir.CrossProduct( vEdge2 ); // If determinant is near zero, ray lies in plane of triangle float fDet = vEdge1.DotProduct( vP ); if( fDet < 0.0001F ) { return FALSE; } //if // Calculate distance from vert0 to ray origin static Vector3 vT; vT = vOrig - a; // Calculate U parameter and test bounds u = vT.DotProduct( vP ); if( u < 0.0F || u > fDet ) { return FALSE; } //if // Prepare to test V parameter static Vector3 vQ; vQ = vT.CrossProduct( vEdge1 ); // Calculate V parameter and test bounds v = vDir.DotProduct( vQ ); if( v < 0.0F || u + v > fDet ) { return FALSE; } //if // Calculate t, scale parameters, ray intersects triangle float fInvDet = 1.0F / fDet; if (pfT) *pfT = vEdge2.DotProduct( vQ ) * fInvDet; if (pfU) *pfU = u * fInvDet; if (pfV) *pfV = v * fInvDet; return TRUE; } // vPos와 Triangle의 거리를 리턴한다. float Triangle::Distance( const Vector3& vPos ) const { Vector3 center; center.x = (a.x + b.x + c.x) / 3.f; center.y = (a.y + b.y + c.y) / 3.f; center.z = (a.z + b.z + c.z) / 3.f; return (vPos - center).Length(); } Vector3 Triangle::Normal() const { const Vector3 v0 = (b - a).Normal(); const Vector3 v1 = (c - a).Normal(); return v0.CrossProduct(v1).Normal(); }
[ "jjuiddong@gmail.com" ]
jjuiddong@gmail.com
bca319cfd190afd4473cbff347a81eb1571ed5cf
e65a4dbfbfb0e54e59787ba7741efee12f7687f3
/devel/libphonenumber/files/patch-src_phonenumbers_base_synchronization_lock.h
6455ae783a95ca7b43526b694ad124c520ac0fef
[ "BSD-2-Clause" ]
permissive
freebsd/freebsd-ports
86f2e89d43913412c4f6b2be3e255bc0945eac12
605a2983f245ac63f5420e023e7dce56898ad801
refs/heads/main
2023-08-30T21:46:28.720924
2023-08-30T19:33:44
2023-08-30T19:33:44
1,803,961
916
918
NOASSERTION
2023-09-08T04:06:26
2011-05-26T11:15:35
null
UTF-8
C++
false
false
689
h
--- src/phonenumbers/base/synchronization/lock.h.orig 2020-06-18 13:06:40 UTC +++ src/phonenumbers/base/synchronization/lock.h @@ -22,7 +22,7 @@ #elif (__cplusplus >= 201103L) && defined(I18N_PHONENUMBERS_USE_STDMUTEX) // C++11 Lock implementation based on std::mutex. #include "phonenumbers/base/synchronization/lock_stdmutex.h" -#elif defined(__linux__) || defined(__APPLE__) || defined(I18N_PHONENUMBERS_HAVE_POSIX_THREAD) +#elif defined(__linux__) || defined(__APPLE__) || defined(I18N_PHONENUMBERS_HAVE_POSIX_THREAD) || defined(__FreeBSD__) #include "phonenumbers/base/synchronization/lock_posix.h" #elif defined(WIN32) #include "phonenumbers/base/synchronization/lock_win32.h"
[ "jhale@FreeBSD.org" ]
jhale@FreeBSD.org
5a5bafc37a73a009d6777f95038161f03ede3feb
c32829b434b3527a9545fa5db37af62fba818508
/WinSTDyn/GUI/CIWidget.cpp
5df78e24c9f2412bda933da224f5b1fe8a6a4668
[ "MIT" ]
permissive
chen0040/ogre-war-game-simulator
63dabfbf9e4bbfe4d1489cf7e67e2f93215af1c9
58eee268eae0612d206e7eb0b8e495708db1ef27
refs/heads/master
2021-01-20T06:14:31.772192
2017-09-06T00:27:39
2017-09-06T00:27:39
101,493,196
0
0
null
null
null
null
UTF-8
C++
false
false
1,186
cpp
#include "stdafx.h" #include "CIWidget.h" #include "GUIManager.h" #include <Ogre.h> #include <sstream> CIWidget::CIWidget(CIWidget* parentWidget, CEGUI::Window* parentWindow) { mParentWidget=parentWidget; mParentWindow=parentWindow; if(mParentWindow == NULL) { mParentWindow=CEGUI::System::getSingletonPtr()->getGUISheet(); } } void CIWidget::initializeComponents(const std::string& rootId) { mRootId=rootId; CEGUI::WindowManager* wm=CEGUI::WindowManager::getSingletonPtr(); if(wm->isWindowPresent(mRootId)) { std::ostringstream oss; oss << "wm->isWindowPresent(" << mRootId << ")==true"; throw Ogre::Exception(42, oss.str().c_str(), "CIWidget::initializeComponents(const std::string& rootId)"); } else { this->create(); } this->subscribeEvents(); } CIWidget::~CIWidget() { this->unsubscribeEvents(); } void CIWidget::showWindow() { mRootWindow->show(); } void CIWidget::hideWindow() { mRootWindow->hide(); } std::string CIWidget::getUIId(const std::string& localUIId) const { return mRootId+std::string("/")+localUIId; } void CIWidget::setPosition(float x, float y) { mRootWindow->setPosition(CEGUI::UVector2(cegui_reldim(x), cegui_reldim(y))); }
[ "xs0040@gmail.com" ]
xs0040@gmail.com
f4aa4dc33b66831298a5643799449bb5772a8cf9
ca57d57bec37faeb57899a80df5b4d267a536ac5
/src/sun_ray/main.cpp
173954ba0111b04b0d7d4e54c8529f44ac64a053
[ "BSD-3-Clause" ]
permissive
fuersten/sun_ray
ed875b2a5a2c0f9fd8bfb7321921b1b70c205a3a
b882d67cd9747f61b50def4c1414e7552ba917c0
refs/heads/main
2023-04-17T04:08:18.860499
2021-04-27T10:15:50
2021-04-27T10:15:50
335,270,596
2
0
BSD-3-Clause
2021-04-27T10:03:57
2021-02-02T11:46:17
C++
UTF-8
C++
false
false
450
cpp
// // main.cpp // sun_ray // // Created by Lars-Christian Fürstenberg on 21.12.19. // Copyright © 2019 Lars-Christian Fürstenberg. All rights reserved. // #include <sun_ray/init.h> #include <iostream> #include "application.h" int main(int argc, const char* argv[]) { std::vector<std::string> args; for (int n = 0; n < argc; ++n) { args.emplace_back(argv[n]); } return sunray::Application{std::cout, std::cerr, args}.run(); }
[ "lcf@miztli.de" ]
lcf@miztli.de
e5c12b0574c3bf450189731b5f0757062d16aaa4
ba96d7f21540bd7504e61954f01a6d77f88dea6f
/build/Android/Debug/app/src/main/include/Uno.IO.CppXliStreamHandle.h
fc0a34d65b6761d1b238b90dcd284f38aa16ddf6
[]
no_license
GetSomefi/haslaamispaivakirja
096ff35fe55e3155293e0030c91b4bbeafd512c7
9ba6766987da4af3b662e33835231b5b88a452b3
refs/heads/master
2020-03-21T19:54:24.148074
2018-11-09T06:44:18
2018-11-09T06:44:18
138,976,977
0
0
null
null
null
null
UTF-8
C++
false
false
474
h
// This file was generated based on /usr/local/share/uno/Packages/UnoCore/1.6.1/Source/Uno/IO/CppXliStream.uno. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <uBase/Stream.h> #include <Uno.Object.h> namespace uBase { class Stream; } namespace g{ namespace Uno{ namespace IO{ // internal extern struct CppXliStreamHandle :10 // { uStructType* CppXliStreamHandle_typeof(); struct CppXliStreamHandle { }; // } }}} // ::g::Uno::IO
[ "peyte.com@gmail.com" ]
peyte.com@gmail.com
b37c4be4aacb765dae92d77c993add50d6bd0dd0
e38c42dbf7de211b770898449b70313255085518
/template/template/class.cpp
e70cfb03ccc3599ab7a46559f2cefc5d8d7b4d61
[]
no_license
CycMei/cccccc
b59fc5ecdaab0e22b49f8419699b16a49bf8fa88
3b50ab3fe197acf0c37e46854d76c232eda252e8
refs/heads/master
2021-05-04T03:49:13.541088
2016-10-13T09:04:19
2016-10-13T09:04:19
70,788,670
0
0
null
null
null
null
UTF-8
C++
false
false
3,424
cpp
#include<iostream> #include<vector> #include<memory> #include<string> #include<initializer_list> #include<boost\bimap.hpp> template<typename T>class Blob { public: typedef T value_type; typedef typename std::vector<T>::size_type size_type; Blob(); Blob(std::initializer_list<T> il); size_type size() const { return data->size(); } bool empty() const { data->empty(); } void push_back(const T &t) { data->push_back(t); } void push_back(T &&t) { data->push_back(std::move(t)); } void pop_back(); T &back(); T &operator[](size_type i); private: std::shared_ptr<std::vector<T>> data; void check(size_type i, const std::string &msg) const; }; template<class T = int> class Numbes { private: T val; public: Numbes(T v = 0) :val(v) {}; }; Numbes<long double> lots_of_precision; Numbes<> average; class DebugDelete { public: DebugDelete(std::ostream &s = std::cout) :os(s) {} template<typename T> void operator()(T *p) const { delete p; } private: std::ostream &os; }; void test() { int *p = new int(0); DebugDelete()(p); std::unique_ptr<int, DebugDelete> pps(new int(), DebugDelete()); } template<typename T> class copyB { template<typename It> copyB(It b, It e); }; template<typename T> template<typename It> copyB<T>::copyB(It b, It e) { } extern template class copyB<std::string>; unsigned int myINT; template<typename T> class Stack{}; void fc(Stack<char>){} class Exercise { Stack<double> &rsd; Stack<int> si; }; void copyMain() { //Stack<char> *sc; int iObj = sizeof(Stack<std::string>); } namespace stdds { //std::vector<int&> vcs; template<typename T> void g(T&& val){} template<typename T> void gg(T val){} template<typename T> void ggg(const T &val){} template<typename T> void gc(T &&val){ std::vector<T> v; } template<typename T> typename std::remove_reference<T>::type &&move(T &&t) { return static_cast<typename std::remove_reference<T>::type&&>(t); } int i = 0; const int ci = i; void test() { g(i); g(ci); g(ci*i); g(i = ci); gg(i); gg(ci); gg(ci*i); gg(i = ci); ggg(i); ggg(ci); ggg(ci*i); ggg(i = ci); gc(42); // gc(i); } }; namespace trans { template<typename T1, typename T2> void flip1( T1 &&t1, T2 &&t2) { } template<typename T1, typename T2> void fss(const T1 &&t1, const T2 &&t2) { } void test() { int i = 0; int j = i; const int &c = i; flip1(i, j); //fss(i, j); } } namespace tracsws { template<typename T> void f(T t) { std::cout << 1 << std::endl; } template<typename T> void f(const T *t) { std::cout << 2 << std::endl; } template<typename T> void g(T t) { std::cout << 3 << std::endl; } template<typename T> void g(T *t) { std::cout << 4 << std::endl; } template<typename...Args> void g(Args...args) { std::cout << sizeof...(Args); std::cout << sizeof...(args); } template<typename T> std::ostream &print(std::ostream &os, const T &t) { return os << t; } template<typename T, typename...Args> std::ostream &print(std::ostream &os, const T &t, const Args... rest) { os << t << " ,"; return print(os, rest...); } template<class... Args> void emplace_back(Args&&...) { } template<typename T> int compare(const T&, const T&) {}; template<> int compare(const char *const &p1,const char *const &p2){} }; void main() { using namespace tracsws; int i = 42, *p = &i; const int ci = 0, *p2 = &ci; g(42); g(p); g(ci); g(p2); f(42); f(p); f(ci); f(p2); }
[ "chayalikemei@outlook.com" ]
chayalikemei@outlook.com
06368b96e5b0f45657b098ec3288f6fe7c864113
8b50e46c29b21a8c9c52091ddeb1856d17b9c570
/Chapter12/09/thread9/textdialog.h
88573c72ff4f8938fc7e57532fde2e5e3ae0554d
[]
no_license
anthonychl/Foundations-of-Qt-Development
ef6e7234263c51ca15c3cf4332dc0122367f45d7
34f5a84c65ca1da074f83345dd0d2431c911f36b
refs/heads/master
2020-07-03T05:53:04.035264
2019-08-11T19:56:18
2019-08-11T19:56:18
201,809,232
0
0
null
null
null
null
UTF-8
C++
false
false
542
h
#ifndef TEXTDIALOG_H #define TEXTDIALOG_H #include <QDialog> #include "textandnumber.h" #include <QAbstractButton> #include <QMutex> namespace Ui { class TextDialog; } class TextDialog : public QDialog { Q_OBJECT public: /* explicit TextDialog(QWidget *parent = 0); ~TextDialog();*/ TextDialog(); ~TextDialog(); public slots: void showText(TextAndNumber tan); private slots: void buttonClicked(QAbstractButton*); private: Ui::TextDialog *ui; int count; QMutex mutex; }; #endif // TEXTDIALOG_H
[ "anthonychl.dev@gmail.com" ]
anthonychl.dev@gmail.com
9c0a5f3c976d06cb5556be723819f89656f62200
0cd648478fbca2085d4be739caf9cbf0a57ab70c
/9-sequential_container/9.21-add_elements.cpp
51f2617cc740853ba9d9c0b5dc04a5f7aa6387a1
[]
no_license
icrelae/cpp_primer
f3fb497b96736f944701aecc25dd182f1e8cd73d
1ed1fef52356626440ca354fada0b673fce67465
refs/heads/master
2021-01-12T07:29:15.036680
2017-11-17T22:47:39
2017-11-17T22:47:39
76,966,712
0
0
null
null
null
null
UTF-8
C++
false
false
658
cpp
/* 2016.11.19 16:12 * P_309 * !!! * ??? * for deque, insert at head and tail costing constant time, at other site will be very time-consuming !!! * insert/eplace enlements into vector/string/deque will cause invalidation of iterators/references/pointers point to it !!! * * allocate new memory for every insert ??? */ #include <iostream> #include <string> #include <vector> #include <deque> #include <list> using namespace std; int main(int argc, char **argv) { vector<string> lst; string word; auto iter = lst.begin(); while (cin >> word) iter = lst.insert(iter, word); for (const auto itList : lst) cout << itList << ' '; return 0; }
[ "anadia@163.com" ]
anadia@163.com
89b44afeba4883ff4343e20e32d6d6ffb9b19fbd
c09c94210c61918d7fe8a5782761c10ddfc3f002
/案例7_类的继承与派生/6-5 多重继承派生类构造函数.cpp
607bba413d4961a8ee908b7ce7ce3401f4f10f52
[]
no_license
SWQXDBA/Pintia_C-
b0c05476193e39669c45c7f949e528a21579d7d0
014b48ae12142117922f490a6b25f4f6227829c2
refs/heads/master
2023-05-02T08:19:51.145454
2021-05-26T05:18:12
2021-05-26T05:18:12
365,187,119
1
0
null
null
null
null
UTF-8
C++
false
false
1,228
cpp
#include <iostream> #include <cstdio> #include <string> using namespace std; //class Teacher //{public: // Teacher(string nam,int a,string t) // {name=nam; // age=a; // title=t;} // void display() // {cout<<"name:"<<name<<endl; // cout<<"age"<<age<<endl; // cout<<"title:"<<title<<endl; // } //protected: // string name; // int age; // string title; //}; // //class Student //{public: // Student(string nam,char s,float sco) // {name1=nam; // sex=s; // score=sco;} // void display1() // {cout<<"name:"<<name1<<endl; // cout<<"sex:"<<sex<<endl; // cout<<"score:"<<score<<endl; // } //protected: // string name1; // char sex; // float score; //}; class Graduate:public Teacher,public Student{ private: float wage; public: Graduate(const string &name,int age,char sex,const string &title,float score,float wages):Teacher(name,age,title), Student(name,sex,score),wage(wages){} void show(){ printf("name:%s\n" "age:%d\n" "sex:%c\n" "score:%g\n" "title:%s\n" "wages:%g\n",name.c_str(),age,sex,score,title.c_str(),wage); } };
[ "SWQXDBA2" ]
SWQXDBA2
c99cf373b34b49b8374c2f78850e8c97fc665ff0
ee61f27df1463ebe0e77c2184cced2b587d6f61c
/app/src/main/cpp/include/seeta/QualityOfPoseEx.h
1e9e4d0430be08b0f307a591aade044dac272a28
[]
no_license
crisgol/SeetafaceJni
1e42179326aa163bcead0acc61c030a90a1386e9
1efbf765f765e7c5d78480fb1fd1f627f1d3e591
refs/heads/master
2023-06-26T15:12:40.175594
2021-07-21T14:45:49
2021-07-21T14:45:49
388,300,550
3
0
null
null
null
null
UTF-8
C++
false
false
1,699
h
// // Created by kier on 2019-07-24. // #ifndef SEETA_QUALITYEVALUATOR_QUALITYOFPOSEEX_H #define SEETA_QUALITYEVALUATOR_QUALITYOFPOSEEX_H #include "QualityStructure.h" namespace seeta { namespace v3 { class QualityOfPoseEx : public QualityRule { public: enum PROPERTY { YAW_LOW_THRESHOLD = 0, YAW_HIGH_THRESHOLD = 1, PITCH_LOW_THRESHOLD = 2, PITCH_HIGH_THRESHOLD = 3, ROLL_LOW_THRESHOLD = 4, ROLL_HIGH_THRESHOLD = 5 }; using self = QualityOfPoseEx; using supper = QualityRule; /** * Construct with recommend parameters */ SEETA_API QualityOfPoseEx(const SeetaModelSetting &setting); SEETA_API ~QualityOfPoseEx() override; SEETA_API QualityResult check( const SeetaImageData &image, const SeetaRect &face, const SeetaPointF *points, const int32_t N) override; SEETA_API float get(PROPERTY property); SEETA_API void set(PROPERTY property, float value); private: QualityOfPoseEx(const QualityOfPoseEx &) = delete; QualityOfPoseEx &operator=(const QualityOfPoseEx &) = delete; private: void *m_data; float m_yaw_low; float m_pitch_low; float m_roll_low; float m_yaw_high; float m_pitch_high; float m_roll_high; }; } using namespace v3; } #endif //SEETA_QUALITYEVALUATOR_QUALITYOFPOSEEX_H
[ "1299204885@qq.com" ]
1299204885@qq.com
3361eab1ae980ca6bb16921c589f76ffe41fdb88
c30a94fda11a05853c959cde74c302400298e46a
/Astronomy Solar System/LightManager.h
922ec4f16d44c8a269bce3d9aad3f3b093f9cb34
[]
no_license
cmilatinov/solar-system-sim
eb98f1eff213132683f8b49ea9f5837c9617e4d9
00502f19feb739a6b09ca2d589437dde0edcb466
refs/heads/master
2023-01-24T15:25:15.668799
2019-03-16T19:37:20
2019-03-16T19:37:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
229
h
#include <vector> #include "Light.h" #pragma once class LightManager { public: LightManager(Light * sun); ~LightManager(); const static int maxLights = 1; void addLight(Light * l); std::vector<Light*> getAllLights(); };
[ "milatinovcristian@gmail.com" ]
milatinovcristian@gmail.com
6e92bed032c003268d3ae9e0f42e5d6655b865d4
e1ad82f32e73b0a9750eb1a3eaf23b46a531cf12
/lines/src/main.cpp
21e32ad758351f8c1f100b3b9387b909d234b6f7
[]
no_license
markbirss/PicoQVGA
fb7f6deef67a1bed88b568fdf71528e073463c9e
7d29c62ea1cda46bbec03f63b4d5fb8c8173700e
refs/heads/main
2023-08-08T01:56:43.813250
2021-09-16T20:30:53
2021-09-16T20:30:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,903
cpp
// **************************************************************************** // // Main code // // **************************************************************************** #include "include.h" #define LINENUM 50 // number of lines #define SPEEDMIN 2.0f // minimal speed #define SPEEDMAX 7.0f // maximal speed #define LENMIN 40 // minimal length of color #define LENMAX 200 // maximal length of color #define LEVMIN (3*80) // minimal bright level // coordinates enum { C_X1 = 0, C_Y1, C_X2, C_Y2, C_NUM // number of coordinates }; // current coordinate of the head float Coord[C_NUM]; // coordinate u16 CoordMax[C_NUM]; // max. coordinate float Delta[C_NUM]; // delta u8 R, G, B; // length of color segment int ColLen; // lines typedef struct { u8 r, g, b; // line color int coord[C_NUM]; // line coordinates } sLine; sLine Lines[LINENUM]; // list of lines int Head; // head index int main() { int i, j, k, rr, gg, bb; sLine* line; // initialize line head to random position and color CoordMax[C_X1] = WIDTH-1; CoordMax[C_Y1] = HEIGHT-1; CoordMax[C_X2] = WIDTH-1; CoordMax[C_Y2] = HEIGHT-1; for (i = 0; i < C_NUM; i++) { Coord[i] = RandU16Max(CoordMax[i]); Delta[i] = RandFloatMinMax(SPEEDMIN, SPEEDMAX); if ((RandU8() & 1) != 0) Delta[i] = -Delta[i]; } do { R = RandU8(); G = RandU8(); B = RandU8(); } while (R+G+B < LEVMIN); Head = 0; ColLen = RandU8MinMax(LENMIN,LENMAX); memset(Lines, 0, sizeof(Lines)); // main loop while (true) { // wait for VSync WaitVSync(); // draw lines j = Head; for (i = 0; i < LINENUM; i++) { // pointer to the line line = &Lines[j]; // calculate color components rr = (int)((float)line->r * i / (LINENUM-1) + 0.5f); if (rr > 255) rr = 255; gg = (int)((float)line->g * i / (LINENUM-1) + 0.5f); if (gg > 255) gg = 255; bb = (int)((float)line->b * i / (LINENUM-1) + 0.5f); if (bb > 255) bb = 255; // draw line DrawLine(line->coord[C_X1], line->coord[C_Y1], line->coord[C_X2], line->coord[C_Y2], COLRGB(rr,gg,bb)); // shift line index j++; if (j >= LINENUM) j = 0; } // generate new head line j = Head; line = &Lines[j]; for (i = 0; i < C_NUM; i++) line->coord[i] = (int)(Coord[i] + 0.5f); line->r = R; line->g = G; line->b = B; // shift header j++; if (j >= LINENUM) j = 0; Head = j; // shift coordinates for (i = 0; i < C_NUM; i++) { Coord[i] += Delta[i]; if (Coord[i] < 0) { Coord[i] = 0; Delta[i] = RandFloatMinMax(SPEEDMIN, SPEEDMAX); } if (Coord[i] > CoordMax[i]) { Coord[i] = CoordMax[i]; Delta[i] = -RandFloatMinMax(SPEEDMIN, SPEEDMAX); } } // generate new color ColLen--; if (ColLen <= 0) { ColLen = RandU8MinMax(LENMIN,LENMAX); do { R = RandU8(); G = RandU8(); B = RandU8(); } while (R+G+B < LEVMIN); } } }
[ "Panda38@seznam.cz" ]
Panda38@seznam.cz
f018c0b1e27af2148c95b021fb7548d198b3e06c
ddad5e9ee062d18c33b9192e3db95b58a4a67f77
/strings/strtoint.h
02f06465777432aa653bb97474872f3b478ddfe0
[ "BSD-2-Clause" ]
permissive
romange/gaia
c7115acf55e4b4939f8111f08e5331dff964fd02
8ef14627a4bf42eba83bb6df4d180beca305b307
refs/heads/master
2022-01-11T13:35:22.352252
2021-12-28T16:11:13
2021-12-28T16:11:13
114,404,005
84
17
BSD-2-Clause
2021-12-28T16:11:14
2017-12-15T19:20:34
C++
UTF-8
C++
false
false
3,287
h
// Copyright 2008 Google Inc. All Rights Reserved. // // Architecture-neutral plug compatible replacements for strtol() friends. // // Long's have different lengths on ILP-32 and LP-64 platforms, and so overflow // behavior across the two varies when strtol() and similar are used to parse // 32-bit integers. Similar problems exist with atoi(), because although it // has an all-integer interface, it uses strtol() internally, and so suffers // from the same narrowing problems on assignments to int. // // Examples: // errno = 0; // i = strtol("3147483647", NULL, 10); // printf("%d, errno %d\n", i, errno); // // 32-bit platform: 2147483647, errno 34 // // 64-bit platform: -1147483649, errno 0 // // printf("%d\n", atoi("3147483647")); // // 32-bit platform: 2147483647 // // 64-bit platform: -1147483649 // // A way round this is to define local replacements for these, and use them // instead of the standard libc functions. // // In most 32-bit cases the replacements can be inlined away to a call to the // libc function. In a couple of 64-bit cases, however, adapters are required, // to provide the right overflow and errno behavior. // #ifndef BASE_STRTOINT_H_ #define BASE_STRTOINT_H_ #include <stdlib.h> // For strtol* functions. #include <string> using std::string; #include "base/integral_types.h" #include "base/macros.h" #include "base/port.h" // Adapter functions for handling overflow and errno. int32 strto32_adapter(const char *nptr, char **endptr, int base); uint32 strtou32_adapter(const char *nptr, char **endptr, int base); // Conversions to a 32-bit integer can pass the call to strto[u]l on 32-bit // platforms, but need a little extra work on 64-bit platforms. inline int32 strto32(const char *nptr, char **endptr, int base) { if (sizeof(int32) == sizeof(long)) return static_cast<int32>(strtol(nptr, endptr, base)); else return strto32_adapter(nptr, endptr, base); } inline uint32 strtou32(const char *nptr, char **endptr, int base) { if (sizeof(uint32) == sizeof(unsigned long)) return static_cast<uint32>(strtoul(nptr, endptr, base)); else return strtou32_adapter(nptr, endptr, base); } // For now, long long is 64-bit on all the platforms we care about, so these // functions can simply pass the call to strto[u]ll. inline int64 strto64(const char *nptr, char **endptr, int base) { COMPILE_ASSERT(sizeof(int64) == sizeof(long long), sizeof_int64_is_not_sizeof_long_long); return strtoll(nptr, endptr, base); } inline uint64 strtou64(const char *nptr, char **endptr, int base) { COMPILE_ASSERT(sizeof(uint64) == sizeof(unsigned long long), sizeof_uint64_is_not_sizeof_long_long); return strtoull(nptr, endptr, base); } // Although it returns an int, atoi() is implemented in terms of strtol, and // so has differing overflow and underflow behavior. atol is the same. inline int32 atoi32(const char *nptr) { return strto32(nptr, NULL, 10); } inline int64 atoi64(const char *nptr) { return strto64(nptr, NULL, 10); } // Convenience versions of the above that take a string argument. inline int32 atoi32(const string &s) { return atoi32(s.c_str()); } inline int64 atoi64(const string &s) { return atoi64(s.c_str()); } #endif // BASE_STRTOINT_H_
[ "romange@gmail.com" ]
romange@gmail.com
a1309ce9c0a05b1e19eee994d8b6fe25515474f2
fdaa5c780752bcd7b68b59e34b03f40ffe30613d
/image.cpp
16127f003e4f7a74766ae6ed3bd78f51e0d7d956
[]
no_license
JD-DA/BarjoKart
07d65f1609b519aabbd8dc6ab921c5d186c4024e
6a6469ac7026a032fc0c01dc14da4c5d1bc58f26
refs/heads/master
2023-08-10T22:51:26.677829
2021-03-31T05:03:04
2021-03-31T05:03:04
404,103,524
0
0
null
null
null
null
UTF-8
C++
false
false
9,044
cpp
#include <iostream> #include <cstdlib> #include <stdio.h> #include <png.h> #include <png++/png.hpp> #include <toml++/toml.h> #include "image.hpp" Image::Image(){ } Image::~Image(){ for (int i = 0; i < this->height; i++) { delete(matrice[i]); } delete(matrice); /*for (std::list<std::pair<int,int>>::iterator i = zoneArrive.begin(); i != zoneArrive.end(); ++i) { delete(i); }*/ } void Image::build_image(std::string fichier){ std::cout<<"Construction de l'image..."<<std::endl; std::cout<<fichier<<std::endl; png::image< png::rgba_pixel > image(fichier); int nbPixelArrive=0; this->width=image.get_width(); this->height=image.get_height(); std::cout<<"Largeur : "<<width<<" Hauteur : "<<height<<std::endl; int r; int g; int b; //int a; this->matrice = new char*[height]; //int size = 0; //bool test; for (unsigned int i = 0; i <(unsigned int) this->height; ++i) { this->matrice[i]= new char[width]; for(unsigned int j=0;j<(unsigned int) this->width;++j){ r = image.get_pixel(j,i).red; g = image.get_pixel(j,i).green; b = image.get_pixel(j,i).blue; //a=image.get_pixel(j,i).alpha; //std::cout<<r<<' '<<g<<' '<<b<<std::endl; if((r==255 and g==255 and b==255)){ this->matrice[i][j]='b'; //putchar(' '); }else if(r==arrivalColorR and g==arrivalColorG and b==arrivalColorB){ this->matrice[i][j]='a'; nbPixelArrive++; zoneArrive.push_back(std::pair<int,int>(i,j)); //putchar('a'); }else if(r==0 and g==0 and b==0){ this->matrice[i][j]='n'; //putchar('n'); }else{ this->matrice[i][j]='g'; //putchar('g'); } } //putchar('\n'); } std::cout<<"Image contruite !"<<std::endl; std::cout<<"Nb de pixel de la zone d'arrivée : "<<nbPixelArrive<<std::endl; std::cout<<"Taille de la liste : "<<zoneArrive.size()<<std::endl; } void Image::load_data(std::string fpng,std::string ftoml){ toml::table tbl; try{ tbl = toml::parse_file(ftoml); //std::cout<<tbl<<std::endl; std::cout<<"Lecture du .toml..."<<std::endl; maxAcceleration = tbl["acc_max"].value<int>().value(); arrivalColorR = (tbl["couleur_arrivee"][0].value<int>().value()); arrivalColorG = (tbl["couleur_arrivee"][1].value<int>().value()); arrivalColorB = (tbl["couleur_arrivee"][2].value<int>().value()); departureX= (tbl["depart"]["x"].value<int>().value()); departureY= (tbl["depart"]["y"].value<int>().value()); std::cout<<"Acceleration Max : "<<maxAcceleration<<std::endl; std::cout<<"Couleur d'arrivée :"<<arrivalColorR<<' '<<arrivalColorG<<' '<<arrivalColorB<<std::endl; std::cout<<"Position de départ : x->"<<departureX<<" y->"<<departureY<<std::endl; build_image(fpng); }catch(const toml::parse_error& err){ std::cerr<<"La lecture du toml a échouée :\n"<<err<<"\n"; } } /* Permet de verifier le bonne lecture du fichier png via la creation d'un fichier pgm copiant l'image et donnant aux differentes zones un niveau de gris different. */ void Image::affichage(char* fichierSortie){ FILE* fichier = fopen(fichierSortie,"w"); if(fichier!=NULL){ fputs("P2",fichier); fputs("\n",fichier); fprintf(fichier, "# image générée par Image::affichage\n"); fprintf(fichier, "%d\t", width); fprintf(fichier, "%d\n", height); fprintf(fichier, "%d\n", 255); std::cout<<"Écriture PGM..."<<std::endl; int num; for(int i=0; i<height;i++){ for(int j=0;j<width;j++){ char cara =matrice[i][j]; if(cara=='b'){ //utilisé pour afficher les directions /*if(i<2*(j)+(y-2*x)){ if(i>-0.5*j+(y+0.5*x)){ if(i>0.5*j+(y-0.5*x)){ num = 200; }else{ num = 150; } }else{ if(i>-2*j+(y+2*x)){ num = 100; }else{ num = 50; } } }else{ if(i>-0.5*j+(y+0.5*x)){ if(i>-2*j+(y+2*x)){ num = 250; }else{ num = 200; } }else{ if(i>0.5*j+(y-0.5*x)){ num = 150; }else{ num = 100; } } }*/ num = 255; }else if(cara=='n'){ num = 0; }else if (cara=='a'){ num = 50; }else{ //std::cout<<"Charactère bizarre : i="<<i<<" j="<<j<<std::endl; num = 100; } fprintf(fichier, "%d ", num); } //putchar('\n'); } fclose(fichier); std::cout<<"L'image a été écrite, allez voir :"<<fichierSortie<<std::endl; } else{ std::cout<<"Erreur d'ouverture du fichier"<<std::endl; } } void Image::affichageDirection(const char* fichierSortie, int x,int y){ FILE* fichier = fopen(fichierSortie,"w"); if(fichier!=NULL){ fputs("P2",fichier); fputs("\n",fichier); fprintf(fichier, "# image générée par Image::affichage\n"); fprintf(fichier, "%d\t", width); fprintf(fichier, "%d\n", height); fprintf(fichier, "%d\n", 255); std::cout<<"Écriture PGM..."<<std::endl; int num; for(int i=0; i<height;i++){ for(int j=0;j<width;j++){ char cara =matrice[i][j]; if(cara=='b'){ if(i<2*(j)+(y-2*x)){ if(i>-0.5*j+(y+0.5*x)){ if(i>0.5*j+(y-0.5*x)){ num = 200; }else{ num = 150; } }else{ if(i>-2*j+(y+2*x)){ num = 100; }else{ num = 50; } } }else{ if(i>-0.5*j+(y+0.5*x)){ if(i>-2*j+(y+2*x)){ num = 250; }else{ num = 200; } }else{ if(i>0.5*j+(y-0.5*x)){ num = 150; }else{ num = 100; } } } }else if(cara=='n'){ num = 0; }else if (cara=='a'){ num = 50; }else{ num = 100; } fprintf(fichier, "%d ", num); } } fclose(fichier); std::cout<<"L'image a été écrite, allez voir :"<<fichierSortie<<std::endl; } else{ std::cout<<"Erreur d'ouverture du fichier"<<std::endl; } } bool Image::verifierPixel(int x,int y){ return matrice[y-1][x-1]!='n'; } bool Image::verifierPixel2(int x,int y){ return matrice[y][x]!='n'; } bool Image::verifierPixel3(int x,int y){ bool test= matrice[y][x]!='n'; if(x-1>0){ test = test and matrice[y][x-1]!='n'; } if(y-1>0){ test = test and matrice[y-1][x]!='n'; } if(y+1<height){ test = test and matrice[y+1][x]!='n'; } if(x+1<width){ test = test and matrice[y][x+1]!='n'; } return test; } bool Image::verifierArrivee(int x,int y){ return matrice[y-1][x-1]=='a'; } bool Image::verifierArrivee2(int x,int y){ return matrice[y][x]=='a'; } /** * renvoi une paire de coordonnées de type y/x correspondant au centre de la zone d'arrivée(origine en haut à gauche) **/ std::pair<int,int> Image::centreZoneArrivee(){ std::list<std::pair<int,int>>::iterator i = zoneArrive.begin(); int res=0; while(res<zoneArrive.size()/2){ i++; res++; } return (*i); } /** * Pour un point donné, renvoie la direction vers laquelle se trouve le plus grand nombre de pixel qui composent la zone d'arrivée * **/ std::map<std::string,int> Image::direction(int x,int y){ std::map<std::string,int> map; int n = 0; map.insert(std::pair<std::string,int>("n",0)); map.insert(std::pair<std::string,int>("e",0)); map.insert(std::pair<std::string,int>("s",0)); map.insert(std::pair<std::string,int>("o",0)); map.insert(std::pair<std::string,int>("ne",0)); map.insert(std::pair<std::string,int>("no",0)); map.insert(std::pair<std::string,int>("so",0)); map.insert(std::pair<std::string,int>("se",0)); int e = 0; int s = 0; int o = 0; int ne = 0; int no = 0; int se = 0; int so = 0; //float diff = y-x; for (std::list<std::pair<int,int>>::iterator it = zoneArrive.begin(); it != zoneArrive.end(); ++it) { int xa=(*it).second; int ya=(*it).first; if(ya<2*xa+(y-2*x)){ if(ya>-0.5*xa+(y+0.5*x)){ if(ya>0.5*xa+(y-0.5*x)){ ++se; map["se"]++; }else{ ++e; map["e"]++; } }else{ if(ya>-2*xa+(y+2*x)){ ++ne; map["ne"]++; }else{ ++n; map["n"]++; } } }else{ if(ya>-0.5*xa+(y+0.5*x)){ if(ya>-2*xa+(y+2*x)){ ++s; map["s"]++; }else{ ++so; map["so"]++; } }else{ if(ya>0.5*xa+(y-0.5*x)){ ++o; map["o"]++; }else{ ++no; map["no"]++; } } } } std::cout<<"n "<<n<<" ne "<<ne<<" e "<<e<<" se "<<se<<" s "<<s<<" so "<<so<<" o "<<o<<" no "<<no<<std::endl; return map; } /** * Renvoi un int qui correpond au potentiel de ce point dans cette direction, c'est à dire la distance qui le sépare du prochain obstacle * **/ int Image::potentiel(std::string dir, int x,int y){ int pasX; int pasY; if(strcmp(dir.c_str(),"n")==0){ pasX=0; pasY=-1; }else if(strcmp(dir.c_str(),"no")==0){ pasX=-1; pasY=-1; }else if(strcmp(dir.c_str(),"o")==0){ pasX=-1; pasY=0; }else if(strcmp(dir.c_str(),"so")==0){ pasX=-1; pasY=1; }else if(strcmp(dir.c_str(),"s")==0){ pasX=0; pasY=1; }else if(strcmp(dir.c_str(),"se")==0){ pasX=1; pasY=-1; }else if(strcmp(dir.c_str(),"e")==0){ pasX=1; pasY=0; }else{ //ne pasX=1; pasY=-1; } int nbPasPotentiels = 0; x+=pasX; y+=pasY; while(verifierPixel2(x,y)){ nbPasPotentiels++; x+=pasX; y+=pasY; } return nbPasPotentiels; }
[ "jean-daniel.de-ambrogi@etu.univ-orleans.fr" ]
jean-daniel.de-ambrogi@etu.univ-orleans.fr
90d8c12d1519358247f873732dac9855de848e35
a88124690a500e728229ae1c3646721b8f5a4c82
/two_sets_ii.cpp
c687936ad29daadd709a1a4377baf7c2ef815d39
[ "MIT" ]
permissive
ShinAKS/cses_solutions
237eedaaa2940d57b1b666a808ad93c9a9169a3c
e4ebcf80c010785f1b73df7aa8052da07ad549e0
refs/heads/master
2022-12-22T21:12:30.568416
2020-10-01T13:54:31
2020-10-01T13:54:31
300,294,172
0
0
null
null
null
null
UTF-8
C++
false
false
1,038
cpp
#include <bits/stdc++.h> #define ll long long #define int long long #define pb push_back #define pii pair<int,int> #define vi vector<int> #define vii vector<pii> #define mi map<int,int> #define mii map<pii,int> #define all(a) (a).begin(),(a).end() #define ff first #define ss second #define sz(x) (int)x.size() #define endl '\n' #define hell 1000000007 #define rep(i,a,b) for(int i=a;i<b;i++) using namespace std; const int P = (500*501)/2+1; ll dp[501][P]; int32_t main(){ cin.tie(NULL); ios::sync_with_stdio(false); //insert code int n; cin>>n; ll s = (n*(n+1))/2; if (s%2){ cout<<0<<endl; return 0; } memset(dp,0,sizeof(dp)); dp[0][0] = 1; rep(i,1,n+1){ rep(j,0,s/2+1){ if (j == 0)dp[i][j] = 1; else{ dp[i][j] = dp[i-1][j]; if (j>=i-1)dp[i][j] = (dp[i][j]+dp[i-1][j-i+1])%hell; } } } /* rep(i,0,n+1){ rep(j,0,s/2+1)cout<<dp[i][j]<<" "; cout<<endl; } */ cout<<dp[n][s/2]<<endl; }
[ "ayushsinha0@gmail.com" ]
ayushsinha0@gmail.com
bbf0bf528cdfbb06688515f9abbd6183a406f69c
76290c3f22ac436c52f29e9be5119d96cda551e7
/AESGUI/AlertDialog.h
f2da3e04189df3104f2a82a4a6cd319ce930aeb7
[]
no_license
CH-Chang/1091-AESGUI
8fbc912c06e7a3f6bd27b173f503be800764df18
57a839caec719310d45d4640b9213637fb230a78
refs/heads/main
2023-01-10T22:59:13.277015
2020-11-19T13:25:05
2020-11-19T13:25:05
309,672,086
1
0
null
null
null
null
BIG5
C++
false
false
713
h
#pragma once #include <QDialog> #include <QCursor> #include <QMouseEvent> #include "ui_AlertDialog.h" class AlertDialog : public QDialog { Q_OBJECT public: AlertDialog(QWidget *parent = Q_NULLPTR); ~AlertDialog(); void setTitle(QString); void setMessage(QString); private: // 變數 int moveFlag = false; Ui::AlertDialog ui; QPoint movePosition; void init(); void initView(); void initInteraction(); protected: // 重載方法 virtual void mousePressEvent(QMouseEvent *); virtual void mouseMoveEvent(QMouseEvent *); virtual void mouseReleaseEvent(QMouseEvent *); public slots: void onCloseClicked(); void onMaximizeClicked(); void onMinimizeClicked(); void onComfirmClicked(); };
[ "hew12233@gmail.com" ]
hew12233@gmail.com
93a605c1c4541fd59e4678178629e63009e17137
4fd87b5a8b7008822bdecf8346e4895257da4e38
/my_plugin/stringsearch_handle.cpp
f4b6920e4c7ad4b7c4c151c5968101f18b0265ac
[ "BSD-2-Clause" ]
permissive
zachturing/decaf-plugin
5dfcb5e9a7884a5bb4d8db9232abebe3f3f05c59
630b9e8781121ec211944f9f1470cf17c88b2a04
refs/heads/master
2020-03-19T08:06:05.837517
2018-06-05T09:50:30
2018-06-05T09:50:30
136,175,798
1
0
null
null
null
null
UTF-8
C++
false
false
8,291
cpp
#ifdef __cplusplus extern "C" { #endif #include <sys/time.h> #include "DECAF_main.h" #include "DECAF_callback.h" #include "DECAF_callback_common.h" #include "vmi_callback.h" #include "utils/Output.h" #include "DECAF_target.h" #include "hookapi.h" #include "shared/vmi_callback.h" #include "vmi_c_wrapper.h" #include "shared/tainting/taintcheck_opt.h" #include "function_map.h" #include "DECAF_types.h" #include "config.h" #ifdef __cplusplus } #endif #include "stringsearch_handle.h" #include <cstdio> #include <cstdlib> #include <ctype.h> #include <cmath> #include <map> #include <fstream> #include <sstream> #include <string> #include <iostream> using namespace std; extern DECAF_Handle mem_read_handle; extern DECAF_Handle mem_write_handle; extern FILE *stringsearch_log; uint8_t tofind[MAX_STRINGS][MAX_STRLEN]; uint32_t strlens[MAX_STRINGS]; char buf[MAX_SEARCH_LEN]; int num_strings = 0; int n_callers = 16; char target_file_name[512]; struct string_pos { uint32_t val[MAX_STRINGS]; string_pos() { bzero(val, sizeof(val)); } }; void stringsearch_cleanup() { DECAF_printf("stringsearch_cleanup.\n"); if(stringsearch_log != NULL) { fclose(stringsearch_log); stringsearch_log = NULL; DECAF_printf("close file stringsearch_log.\n"); } if(mem_read_handle != DECAF_NULL_HANDLE) { DECAF_unregister_callback(DECAF_MEM_READ_CB, mem_read_handle); mem_read_handle = NULL; } if(mem_write_handle != DECAF_NULL_HANDLE) { DECAF_unregister_callback(DECAF_MEM_WRITE_CB, mem_write_handle); mem_write_handle = NULL; } } int mem_callback(void *buf, int size, bool is_write, int *pMatchLen) { //DECAF_printf("mem_callback.\n"); string_pos sp; int offset = -1; for (unsigned int i = 0; i < size; i++) { uint8_t val = ((uint8_t *)buf)[i]; for(int str_idx = 0; str_idx < num_strings; str_idx++) { if (tofind[str_idx][sp.val[str_idx]] == val) { sp.val[str_idx]++; } else { sp.val[str_idx] = 0; } if (sp.val[str_idx] == strlens[str_idx]) //第str_idx个字符串匹配成功 { // Victory! //DECAF_printf("%s Match of str %s\n", (is_write ? "WRITE" : "READ"), tofind[str_idx]); fprintf(stringsearch_log, "%s Match of str %s\n", (is_write ? "WRITE" : "READ"), tofind[str_idx]); fprintf(stringsearch_log, "addr:0x%x\n", (uint8_t*)buf + i - strlens[str_idx]); *pMatchLen = strlens[str_idx]; //记录当前匹配的字符串的长度 fprintf(stringsearch_log, "match string len is %d.\n", *pMatchLen); int index = 1; for(; index <= strlens[str_idx]; ++index) { fprintf(stringsearch_log, "0x%x:%c\n", (char*)buf + i - strlens[str_idx] + index, *((char*)buf + i - strlens[str_idx] + index)); } //DECAF_printf("Victory\n"); fprintf(stringsearch_log, "%s\n\n", "Victory"); fflush(stringsearch_log); sp.val[str_idx] = 0; offset = i; break; } } } return offset; } /* * @function name:parse_file * @function:解析存放待搜索字符串的文件.字符串包括两种,同panda * @params: stringsfile:存放待搜索字符串的文件名 * @return:正确解析返回true,反之返回false */ bool parse_file(const char* stringsfile) { ifstream search_strings(stringsfile); if(!search_strings) { DECAF_printf("Couldn't open %s; no strings to search for. Exiting.\n", stringsfile); return false; } string line; while(getline(search_strings, line)) { DECAF_printf("line:%s\n", line.c_str()); istringstream iss(line); if(line[0] == '"') //解析 " xxx " 双引号括起来的字符串 { size_t len = line.size() - 2; //获取字符串的长度 memcpy(tofind[num_strings], line.substr(1, len).c_str(), len); strlens[num_strings] = len; } else //解析以":"分隔的十六进制字节序列 { string x; int i = 0; while(getline(iss, x, ':')) { tofind[num_strings][i++] = (uint8_t)strtoul(x.c_str(), NULL, 16); if(i >= MAX_STRLEN) { printf("WARN: Reached max number of characters (%d) on string %d, truncating.\n", MAX_STRLEN, num_strings); break; } } strlens[num_strings] = i; } DECAF_printf("stringsearch: added string of length %d to search set\n", strlens[num_strings]); if(++num_strings >= MAX_STRINGS) { //最多搜索MAX_STRINGS个字符序列,这里定义的是100 DECAF_printf("WARN: maximum number of strings (%d) reached, will not load any more.\n", MAX_STRINGS); break; } } search_strings.close(); return true; } void do_mem_read_cb(DECAF_Callback_Params *param) { //DECAF_printf("do_mem_read_cb.\n"); CPUState *env=param->be.env; if(env == NULL) { DECAF_printf("env is NULL\n"); return; } uint32_t eip = DECAF_getPC(cpu_single_env); uint32_t cr3 = DECAF_getPGD(cpu_single_env); char name[128]; tmodinfo_t dm; if(VMI_locate_module_c(eip, cr3, name, &dm) == -1) { strcpy(name, "<None>"); bzero(&dm, sizeof(dm)); } for(int i = 0; i < PROC_NUM; ++i) { if(strcmp(name, procname[i]) == 0) //说明触发此回调函数的进程是我们所关注的进程 { DECAF_read_mem_with_pgd(cpu_single_env, cr3, param->mr.vaddr, MAX_SEARCH_LEN, (void*)buf); int bytes_read = 0; int offset = mem_callback(buf, MAX_SEARCH_LEN, false, &bytes_read); //返回匹配的最后的一个字符的位置 if(offset != -1) { fprintf(stringsearch_log, "%s:\n", name); fprintf(stringsearch_log, "proc name :%s offset :%d tainted bytes :%d\n", name, offset + 1, bytes_read); //因为下标从0开始,所以表示位置时要加1 uint8_t* taint_flag= new uint8_t[bytes_read]; memset((void*)taint_flag, 0xff, bytes_read); //打上污点标签 taintcheck_taint_virtmem(param->mr.vaddr + offset - STRING_LEN + 1, bytes_read, taint_flag); fflush(stringsearch_log); //fprintf(stringsearch_log, "vaddr:0x%x\n", param->mr.vaddr + offset - STRING_LEN); //fprintf(stringsearch_log, "vaddr->paddr:%x\n", DECAF_get_phys_addr(cpu_single_env, param->mr.vaddr + offset - STRING_LEN)); //fprintf(stringsearch_log, "guest os virtual address:%x\n", cpu_single_env->regs[R_EBP]); delete[] taint_flag; break; } } } } void do_mem_write_cb(DECAF_Callback_Params *param) { //DECAF_printf("do_mem_write_cb.\n"); CPUState *env=param->be.env; if(env == NULL) { DECAF_printf("env is NULL\n"); return; } uint32_t eip = DECAF_getPC(cpu_single_env); uint32_t cr3 = DECAF_getPGD(cpu_single_env); char name[128]; tmodinfo_t dm; if(VMI_locate_module_c(eip, cr3, name, &dm) == -1) { strcpy(name, "<None>"); bzero(&dm, sizeof(dm)); } for(int i = 0; i < PROC_NUM; ++i) { if(strcmp(name, procname[i]) == 0) //说明触发此回调函数的进程是我们所关注的进程 { DECAF_read_mem_with_pgd(cpu_single_env, cr3, param->mr.vaddr, MAX_SEARCH_LEN, (void*)buf); int bytes_read = 0; int offset = mem_callback(buf, MAX_SEARCH_LEN, true, &bytes_read); if(offset != -1) { fprintf(stringsearch_log, "%s:\n", name); fprintf(stringsearch_log, "proc name :%s offset :%d tainted bytes :%d\n", name, offset + 1, bytes_read); int bytes_read = STRING_LEN; uint8_t* taint_flag= new uint8_t[bytes_read]; memset((void*)taint_flag, 0xff, bytes_read); taintcheck_taint_virtmem(param->mr.vaddr + offset - STRING_LEN + 1, bytes_read, taint_flag); //fprintf(stringsearch_log, "vaddr:0x%x\n", param->mr.vaddr); //fprintf(stringsearch_log, "paddr:0x%x\n", param->mr.paddr); fflush(stringsearch_log); delete[] taint_flag; break; } } } }
[ "zach_turing@outlook.com" ]
zach_turing@outlook.com
6a96ac4a63a5dccdafa1bc8e1d73b11c8e829806
c831d5b1de47a062e1e25f3eb3087404b7680588
/webkit/Source/WebKit/Storage/StorageNamespaceImpl.h
ae161e1b58fb0623eebd4805769fad3e40639f27
[ "BSD-2-Clause" ]
permissive
naver/sling
705b09c6bba6a5322e6478c8dc58bfdb0bfb560e
5671cd445a2caae0b4dd0332299e4cfede05062c
refs/heads/master
2023-08-24T15:50:41.690027
2016-12-20T17:19:13
2016-12-20T17:27:47
75,152,972
126
6
null
2022-10-31T00:25:34
2016-11-30T04:59:07
C++
UTF-8
C++
false
false
3,138
h
/* * Copyright (C) 2008 Apple Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef StorageNamespaceImpl_h #define StorageNamespaceImpl_h #include <WebCore/SecurityOriginHash.h> #include <WebCore/StorageArea.h> #include <WebCore/StorageNamespace.h> #include <wtf/HashMap.h> #include <wtf/RefPtr.h> #include <wtf/text/WTFString.h> namespace WebCore { class StorageAreaImpl; class StorageNamespaceImpl : public StorageNamespace { public: WEBCORE_EXPORT static RefPtr<StorageNamespaceImpl> createSessionStorageNamespace(unsigned quota); WEBCORE_EXPORT static RefPtr<StorageNamespaceImpl> getOrCreateLocalStorageNamespace(const String& databasePath, unsigned quota); virtual ~StorageNamespaceImpl(); void close(); // Not removing the origin's StorageArea from m_storageAreaMap because // we're just deleting the underlying db file. If an item is added immediately // after file deletion, we want the same StorageArea to eventually trigger // a sync and for StorageAreaSync to recreate the backing db file. void clearOriginForDeletion(SecurityOrigin*); void clearAllOriginsForDeletion(); void sync(); void closeIdleLocalStorageDatabases(); private: StorageNamespaceImpl(StorageType, const String& path, unsigned quota); RefPtr<StorageArea> storageArea(RefPtr<SecurityOrigin>&&) override; RefPtr<StorageNamespace> copy(Page* newPage) override; typedef HashMap<RefPtr<SecurityOrigin>, RefPtr<StorageAreaImpl>> StorageAreaMap; StorageAreaMap m_storageAreaMap; StorageType m_storageType; // Only used if m_storageType == LocalStorage and the path was not "" in our constructor. String m_path; RefPtr<StorageSyncManager> m_syncManager; // The default quota for each new storage area. unsigned m_quota; bool m_isShutdown; }; } // namespace WebCore #endif // StorageNamespaceImpl_h
[ "daewoong.jang@navercorp.com" ]
daewoong.jang@navercorp.com
5729fab1fbc3c2302e7ea7999c80fafe556a29d5
03d625a9296d7820d5ae64bdbf934c8a822af568
/Node.cpp
0a61d2d49f13b5761c81a85907b106907839181c
[]
no_license
kutycoi123/BpTree
0906b049d6fc70e0bea4cdb2e3b3a2b6569ac23b
dbfb56d629766afa3ad21a677442a628c279184f
refs/heads/main
2023-04-19T04:58:53.042650
2021-04-21T21:09:41
2021-04-21T21:09:41
360,306,843
0
0
null
null
null
null
UTF-8
C++
false
false
14,250
cpp
#include "Node.h" /*======== NODE class implementation ========*/ Node::Node(int limit) : keysLimit(limit), parent(nullptr){ } bool Node::hasKey(int k) const noexcept{ auto it = std::find(keys.begin(), keys.end(), k); return it != keys.end(); } int Node::getIndexOfKey(int k) const noexcept{ auto it = std::find(keys.begin(), keys.end(), k); if(it != keys.end()){ return std::distance(keys.begin(), it); } return -1; } bool Node::isLimitExceeded() const noexcept{ return keys.size() > keysLimit; } std::string Node::keysToString() const noexcept{ if(keys.size() == 0) return "[]"; std::string res = "["; std::for_each(keys.begin(), keys.end(), [&res](int key){ res += std::to_string(key) + ","; }); res.pop_back(); //pop the last ',' res += "]"; return res; } Node* Node::getLeftSibling() const noexcept{ if(!parent){ return nullptr; } auto par = static_cast<InteriorNode*>(parent); auto keyAssociatedWithThisNode = std::upper_bound(par->keys.begin(), par->keys.end(), keys.front()); int idxOfNextPtr = std::distance(par->keys.begin(), keyAssociatedWithThisNode); if(idxOfNextPtr > 0){ return par->next[idxOfNextPtr-1].get(); } return nullptr; } Node* Node::getRightSibling() const noexcept{ if(!parent){ return nullptr; } auto par = static_cast<InteriorNode*>(parent); auto keyAssociatedWithThisNode = std::upper_bound(par->keys.begin(), par->keys.end(), keys.front()); int idxOfNextPtr = std::distance(par->keys.begin(), keyAssociatedWithThisNode); if(idxOfNextPtr+1 < par->next.size()){ return par->next[idxOfNextPtr+1].get(); } return nullptr; } bool Node::coalescible(int k) const noexcept{ return keys.size() + k <= keysLimit ; } /*===================== END OF NODE =======================================*/ /*==================== InteriorNode class implementation ==========================*/ InteriorNode::InteriorNode(int keysLimit) : Node(keysLimit){ next.reserve(keysLimit+1); } InteriorNode::InteriorNode(int keysLimit, std::unique_ptr<Node> n) : Node(keysLimit){ next.push_back(std::move(n)); } bool InteriorNode::isLeafNode() const noexcept{ return false; } bool InteriorNode::isFullEnough() const noexcept{ return next.size() >= ((keysLimit + 1) / 2); } bool InteriorNode::isRedistributable() const noexcept{ return next.size() - 1 >= ((keysLimit + 1) / 2); } void InteriorNode::cleanNode() noexcept{ keys.clear(); next.clear(); } void InteriorNode::insertKey(int k, std::unique_ptr<Node> newNode) noexcept{ auto keyPos = std::upper_bound(keys.begin(), keys.end(), k); auto nextPos = next.begin() + std::distance(keys.begin(), keyPos) + 1; keys.insert(keyPos, k); newNode->parent = this; next.insert(nextPos, std::move(newNode)); } Node* InteriorNode::getNextNode(int k) const noexcept{ auto upperBoundOfK = std::upper_bound(keys.begin(), keys.end(), k); auto nextNodeIndex = std::distance(keys.begin(), upperBoundOfK); return next[nextNodeIndex].get(); } int InteriorNode::split(InteriorNode* newSplitNode) noexcept{ //Split keys in original interior node to new split node int numOfRemainingKeys = ceil(keysLimit/2.0); int numOfSplitKeys = floor(keysLimit/2.0); auto keysBegin = keys.begin(); auto keysEnd = keys.end(); newSplitNode->keys.resize(numOfSplitKeys); //Allocate memories for split keys std::copy(keysBegin + numOfRemainingKeys + 1, keysEnd, newSplitNode->keys.begin()); //Spit keys to new node keys.erase(keysBegin + numOfRemainingKeys + 1, keysEnd); //Erase split keys and keep remaining keys in original node //Last key is now to be removed and inserted into node's parent //The rest keys are kept in original node auto removedKey = keys.back(); keys.pop_back(); //Split next node pointers auto nextNodesBegin = next.begin(); auto nextNodesEnd = next.end(); int numOfNextNodesInOriginalNode = ceil((keysLimit+2)/2.0); auto nextNodesInSplitNodeBegin = nextNodesBegin + numOfNextNodesInOriginalNode; for(auto it = nextNodesInSplitNodeBegin; it != nextNodesEnd ; ++it){ if((*it) != nullptr) (*it)->parent = newSplitNode; newSplitNode->next.push_back(std::move(*it)); } next.erase(nextNodesInSplitNodeBegin, nextNodesEnd); return removedKey; } InteriorNode* InteriorNode::getLeftSibling() const noexcept{ return static_cast<InteriorNode*>(Node::getLeftSibling()); } InteriorNode* InteriorNode::getRightSibling() const noexcept{ return static_cast<InteriorNode*>(Node::getRightSibling()); } Node* InteriorNode::removeKey(int k, int keyOfNextNodeToBeRemoved) noexcept{ auto keyPos = getIndexOfKey(k); if(keyPos == -1) return this; auto nextPos = keyPos; if(keyOfNextNodeToBeRemoved >= keys[keyPos]) nextPos = keyPos + 1; keys.erase(keys.begin() + keyPos); next.erase(next.begin() + nextPos); if(isFullEnough()) return this; InteriorNode* leftSibling = getLeftSibling(); InteriorNode* rightSibling = getRightSibling(); if(leftSibling && leftSibling->isRedistributable()){ return redistributeLeftInterior(leftSibling); }else if(rightSibling && rightSibling->isRedistributable()){ return redistributeRightInterior(rightSibling); }else if(leftSibling && leftSibling->coalescible(keys.size())){ return coalescLeftInterior(leftSibling, k); }else if(rightSibling && rightSibling->coalescible(keys.size())){ return coalescRightInterior(rightSibling, k); } return this; } Node* InteriorNode::redistributeLeftInterior(InteriorNode* sibling) noexcept{ Node* par = sibling->parent; auto upperBoundOfRedistributedKey = std::upper_bound(par->keys.begin(), par->keys.end(), sibling->keys.front()); auto parentKey = upperBoundOfRedistributedKey - 1; keys.insert(keys.begin(), *parentKey); *parentKey = sibling->keys.back(); sibling->keys.pop_back(); std::unique_ptr<Node> newNext = std::move(sibling->next.back()); sibling->next.pop_back(); newNext->parent = this; next.insert(next.begin(), std::move(newNext)); return this; } Node* InteriorNode::redistributeRightInterior(InteriorNode* sibling) noexcept{ Node* par = sibling->parent; auto parentKey = std::upper_bound(par->keys.begin(), par->keys.end(), keys.front()); keys.insert(keys.end(), *parentKey); *parentKey = sibling->keys.front(); sibling->keys.erase(sibling->keys.begin()); std::unique_ptr<Node> newNext = std::move(sibling->next.front()); newNext->parent = this; sibling->next.erase(sibling->next.begin()); next.insert(next.end(), std::move(newNext)); return this; } Node* InteriorNode::coalescLeftInterior(InteriorNode* sibling, int firstKeyAlreadyRemoved) noexcept{ if(!sibling->coalescible(keys.size())) return this; auto keyBetween2Coalesced = std::upper_bound(parent->keys.begin(), parent->keys.end(), sibling->keys.front()); sibling->keys.insert(sibling->keys.end(), *keyBetween2Coalesced); sibling->keys.insert(sibling->keys.end(), keys.begin(), keys.end()); //Update parent pointer of each next node before coalescing with sibling for(auto& nextNode : next){ nextNode->parent = static_cast<Node*>(sibling); } sibling->next.insert(sibling->next.end(), std::make_move_iterator(next.begin()), std::make_move_iterator(next.end())); int keyToBeRemoved = firstKeyAlreadyRemoved; if(keys.size() > 0) keyToBeRemoved = keys.front(); cleanNode(); return static_cast<InteriorNode*>(parent)->removeKey(*keyBetween2Coalesced, keyToBeRemoved); } Node* InteriorNode::coalescRightInterior(InteriorNode* sibling, int firstKeyAlreadyRemoved) noexcept{ if(!sibling->coalescible(keys.size())) return this; auto keyBetween2Coalesced = std::upper_bound(parent->keys.begin(), parent->keys.end(), keys.front()); sibling->keys.insert(sibling->keys.begin(), *keyBetween2Coalesced); sibling->keys.insert(sibling->keys.begin(), keys.begin(), keys.end()); //Update parent pointer of each next node before coalescing with sibling for(auto& nextNode : next){ nextNode->parent = static_cast<Node*>(sibling); } sibling->next.insert(sibling->next.begin(), std::make_move_iterator(next.begin()), std::make_move_iterator(next.end())); int keyToBeRemoved = firstKeyAlreadyRemoved; if(keys.size() > 0) keyToBeRemoved = keys.front(); cleanNode(); return static_cast<InteriorNode*>(parent)->removeKey(*keyBetween2Coalesced, keyToBeRemoved); } /*===================== End of InteriorNode =========================================*/ /*==================== LeafNode class implementation =================================*/ LeafNode::LeafNode(int keysLimit) : Node(keysLimit), nextLeaf(nullptr), prevLeaf(nullptr){ vals.reserve(keysLimit); } void LeafNode::cleanNode() noexcept{ keys.clear(); vals.clear(); } bool LeafNode::isFullEnough() const noexcept{ return vals.size() >= ((keysLimit + 1) / 2); } bool LeafNode::isRedistributable() const noexcept{ return vals.size() - 1 >= ((keysLimit + 1) / 2); } std::string LeafNode::getVal(int k) const noexcept{ int keyIndex = getIndexOfKey(k); if(keyIndex == -1) return ""; return vals[keyIndex]; } std::string LeafNode::valsToString() const noexcept{ std::string res = ""; std::for_each(vals.begin(), vals.end(), [&res](const std::string& val){ res += val + "\n"; }); res.pop_back(); return res; } bool LeafNode::isLeafNode() const noexcept{ return true; } Node* LeafNode::getNextNode(int i) const noexcept{ return nextLeaf; } void LeafNode::insertKey(int k, const std::string& v) noexcept{ auto keyPos = std::upper_bound(keys.begin(), keys.end(), k); auto valPos = vals.begin() + std::distance(keys.begin(), keyPos); keys.insert(keyPos, k); vals.insert(valPos, v); } int LeafNode::split(LeafNode* newSplitNode) noexcept{ //Split keys auto keysBegin= keys.begin(); auto keysEnd = keys.end(); int numOfRemainingKeys = ceil((keysLimit + 1)/2.0); int numOfSplitKeys = keys.size() - numOfRemainingKeys; newSplitNode->keys.resize(numOfSplitKeys); //Allocate memories for new node's keys std::copy(keysBegin + numOfRemainingKeys, keysEnd, (newSplitNode->keys).begin()); //Split keys to new node keys.erase(keysBegin + numOfRemainingKeys, keysEnd); //Erase split keys and keep remaining keys in original node //Split values auto valsBegin = vals.begin(); auto valsEnd = vals.end(); auto numOfRemainingVals = numOfRemainingKeys; newSplitNode->vals.resize(numOfSplitKeys); //Allocate memories for new node's vals std::copy(valsBegin + numOfRemainingVals, valsEnd, newSplitNode->vals.begin()); //Split vals to new node vals.erase(valsBegin + numOfRemainingVals, valsEnd); //Erase split vals and keep remaining vals in original node newSplitNode->nextLeaf = nextLeaf; newSplitNode->prevLeaf = this; nextLeaf = newSplitNode; if(newSplitNode->nextLeaf) newSplitNode->nextLeaf->prevLeaf = newSplitNode; return newSplitNode->keys.front(); } LeafNode* LeafNode::getLeftSibling() const noexcept{ return static_cast<LeafNode*>(Node::getLeftSibling()); } LeafNode* LeafNode::getRightSibling() const noexcept{ return static_cast<LeafNode*>(Node::getRightSibling()); } Node* LeafNode::removeKey(int k) noexcept{ auto keyPos = getIndexOfKey(k); if(keyPos == -1) return this; auto valPos = keyPos; keys.erase(keys.begin() + keyPos); vals.erase(vals.begin() + valPos); if(isFullEnough()) return this; LeafNode* leftSibling = getLeftSibling(); LeafNode* rightSibling = getRightSibling(); if(leftSibling && leftSibling->isRedistributable()){ return redistributeLeftLeaf(leftSibling); }else if(rightSibling && rightSibling->isRedistributable()){ return redistributeRightLeaf(rightSibling); }else if(leftSibling && leftSibling->coalescible(keys.size())){ return coalescLeftLeaf(leftSibling, k); }else if(rightSibling && rightSibling->coalescible(keys.size())){ return coalescRightLeaf(rightSibling, k); } return this; } Node* LeafNode::redistributeLeftLeaf(LeafNode* sibling) noexcept{ int distributedKey = sibling->keys.back(); sibling->keys.pop_back(); std::string distributedVal = sibling->vals.back(); sibling->vals.pop_back(); keys.insert(keys.begin(), distributedKey); vals.insert(vals.begin(), distributedVal); Node* par = parent; auto parentKey = std::upper_bound(par->keys.begin(), par->keys.end(), distributedKey); *parentKey = distributedKey; return this; } Node* LeafNode::redistributeRightLeaf(LeafNode* sibling) noexcept{ int distributedKey = sibling->keys.front(); sibling->keys.erase(sibling->keys.begin()); std::string distributedVal = sibling->vals.front(); sibling->vals.erase(sibling->vals.begin()); keys.push_back(distributedKey); vals.push_back(distributedVal); Node* par = parent; auto upperBoundOfDistributedKey = std::upper_bound(par->keys.begin(), par->keys.end(), distributedKey); auto parentKey = upperBoundOfDistributedKey - 1; *parentKey = sibling->keys.front(); return this; } Node* LeafNode::coalescLeftLeaf(LeafNode* sibling, int firstKeyAlreadyRemoved) noexcept{ if(!sibling->coalescible(keys.size())) return this; sibling->keys.insert(sibling->keys.end(), keys.begin(), keys.end()); sibling->vals.insert(sibling->vals.end(), vals.begin(), vals.end()); auto parentKey = std::upper_bound(sibling->parent->keys.begin(), sibling->parent->keys.end(),sibling->keys.front()); sibling->nextLeaf = nextLeaf; if(nextLeaf) nextLeaf->prevLeaf = sibling; int keyToBeRemoved = firstKeyAlreadyRemoved; if(keys.size() > 0) keyToBeRemoved = keys.front(); cleanNode(); return static_cast<InteriorNode*>(parent)->removeKey(*parentKey, keyToBeRemoved); } Node* LeafNode::coalescRightLeaf(LeafNode* sibling, int firstKeyAlreadyRemoved) noexcept{ if(!sibling->coalescible(keys.size())) return this; sibling->keys.insert(sibling->keys.begin(), keys.begin(), keys.end()); sibling->vals.insert(sibling->vals.begin(), vals.begin(), vals.end()); int keyToBeRemoved = firstKeyAlreadyRemoved; if(keys.size() > 0) keyToBeRemoved = keys.front(); auto parentKey = std::upper_bound(sibling->parent->keys.begin(), sibling->parent->keys.end(), keyToBeRemoved); sibling->prevLeaf = prevLeaf; if(prevLeaf) prevLeaf->nextLeaf = sibling; cleanNode(); return static_cast<InteriorNode*>(parent)->removeKey(*parentKey, keyToBeRemoved); } /*=======================End of LeafNode ============================================*/
[ "kutycoi123@gmail.com" ]
kutycoi123@gmail.com
aa98b3f1e225fb7a3ccba6013a7f501bcc9a59a3
755f9e1bbc82a8beb0471c0cb932181a6f83dce3
/surfaceflinger/sdk/IServiceConnection.h
aba66ed641f6f4f7821c7ac22f7cad779e57d4c5
[]
no_license
wjfsanhe/AndroidM_SF
f52d3bba070ce7c9c59c3f18749cecdcb43c5dd9
426e4bfa15e44fe8d96f416eb0e404ba84172d30
refs/heads/master
2020-06-23T12:33:10.479615
2017-02-17T03:18:12
2017-02-17T03:18:12
74,648,648
1
0
null
null
null
null
UTF-8
C++
false
false
2,232
h
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * @author wangjf * @version 1.0 * @date 2016/11/18 * * */ #ifndef ANDROID_ISERVICE_CONNECTION_H #define ANDROID_ISERVICE_CONNECTION_H #include <utils/Errors.h> #include <utils/RefBase.h> #include <binder/IInterface.h> #include <utils/String8.h> #include <utils/String16.h> namespace android { // ---------------------------------------------------------------------------- class ServiceConnection : public virtual RefBase { public: ServiceConnection(){} virtual ~ServiceConnection(){} /** * Called when a connection to the Service has been established, with * the {@link android.os.IBinder} of the communication channel to the * Service. * * @param name The concrete component name of the service that has * been connected. * * @param service The IBinder of the Service's communication channel, * which you can now make calls on. */ virtual void onServiceConnected(String16 name, sp<IBinder> service)=0; }; class IServiceConnection : public ServiceConnection,public IInterface { public: DECLARE_META_INTERFACE(ServiceConnection) }; class BnServiceConnection:public BnInterface<IServiceConnection>,private IBinder::DeathRecipient { public: virtual status_t onTransact(uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags = 0); private: // This is required by the IBinder::DeathRecipient interface // Bp ternimal can linktoDeath. virtual void binderDied(const wp<IBinder>& who)=0; }; // ---------------------------------------------------------------------------- }; // namespace android #endif // ANDROIDOID_ISERVICE_CONNECTION_H_
[ "wangjianfeng@baofeng.com" ]
wangjianfeng@baofeng.com
960197a19934902c703f04874e13552a84a919bd
74dfb16f483ef51e87d3a3a4b23e29bdd5296c7c
/BigNumber.hpp
622e478ee285893e5b84c71342d3caa8d52e457f
[ "MIT" ]
permissive
Vicshann/Common
090a692010e0d6c6af14dd9a2c4ab2b531d8b16e
dbd6f57e94d4179edcbee1a29de39a4a59bce9e3
refs/heads/master
2023-09-01T12:08:23.348673
2023-08-28T09:56:46
2023-08-28T09:56:46
123,412,494
13
8
null
null
null
null
UTF-8
C++
false
false
7,275
hpp
#pragma once /* Copyright (c) 2018 Victor Sheinmann, Vicshann@gmail.com 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. */ // TODO: Use Platform endianess by default template<int NumOfBits, bool IsSignedInt, typename ElemType=unsigned int> class CBigInt { static const unsigned int NumOfParts = (NumOfBits / sizeof(ElemType))+(bool)(NumOfBits % sizeof(ElemType)); // static_assert(NumOfBits >= (sizeof(ElemType)*8), "NumOfBits is too small for ElemType!" ); ElemType IntParts[NumOfParts]; static constexpr bool IsPlatformLE(void){int val=1; return *(char*)&val;} // Old style: #define ISLE(((union { unsigned x; unsigned char c; }){1}).c) // Or #if 'ABCD' == 0x41424344 ElemType __cdecl ReverseBytes64(ElemType Val) { ElemType res; for(int ctr=0;ctr < sizeof(ElemType);ctr++)((unsigned char*)&res)[ctr] = ((unsigned char*)&Val)[sizeof(ElemType)-1-ctr]; return res; } //------------------------------------------------------------------------------------------------------------ static void ReverseCopy(ElemType* Dst, ElemType* Src, unsigned int Count) // Platform dependant! // Cross platform compile time way to determine endianess? { for(unsigned int ctr=0;ctr < Count;ctr++)Dst[(Count-1)-ctr] = ReverseBytes64(Src[ctr]); } //------------------------------------------------------------------------------------------------------------ static void BigAddU(ElemType* DstNum, ElemType* SrcNum) { bool HaveCarry = false; for(unsigned int ctr=0;ctr < NumOfParts;ctr++) { ElemType DVal = DstNum[ctr]; ElemType DSum = DVal + (ElemType)HaveCarry; if(DVal <= DSum) { ElemType SVal = SrcNum[ctr]; DstNum[ctr] = SVal + DSum; HaveCarry = SVal > (SVal + DSum); } else DstNum[ctr] = SrcNum[ctr]; } } //------------------------------------------------------------------------------------------------------------ static void BigSubU(ElemType* DstNum, ElemType* SrcNum) { bool HaveCarry = false; for(unsigned int ctr=0;ctr < NumOfParts;ctr++) { ElemType DSVal = DstNum[ctr] - (ElemType)HaveCarry; if(DSVal <= ~(ElemType)HaveCarry) { ElemType SVal = SrcNum[ctr]; ElemType RVal = DSVal - SVal; DstNum[ctr] = RVal; HaveCarry = RVal > ~SVal; } else DstNum[ctr] = ~SrcNum[ctr]; } } //------------------------------------------------------------------------------------------------------------ static unsigned int BigCountValParts(ElemType* BigNum) // How many parts(ElemType) with value the number have { int Ctr = NumOfParts; for(;Ctr > 0;Ctr--) { if(BigNum[Ctr-1])break; } return Ctr; } //------------------------------------------------------------------------------------------------------------ static int BigCmpU(ElemType* Num, ElemType* Tgt) { for(int ctr=NumOfParts-1;ctr >= 0;ctr--) { ElemType Val = Tgt[ctr]; if(Num[ctr] > Val)return 1; // Greater if(Num[ctr] < Val)return -1; // Less } return 0; // Equal } //------------------------------------------------------------------------------------------------------------ static void BigDivRemU(ElemType* DstNum, ElemType* SrcNum) // DstNum = DstNum % SrcNum { for(;;) { if(BigCmpU(DstNum, SrcNum) < 0)break; BigSubU(DstNum, SrcNum); } } //------------------------------------------------------------------------------------------------------------ static void BigPower(ElemType* BigMulA, ElemType* BigMulB, ElemType* BigMod) { ElemType TmpBuf[NumOfParts]; ElemType WrkBuf[NumOfParts]; memset(WrkBuf, 0, sizeof(WrkBuf)); memcpy(TmpBuf, BigMulB, sizeof(TmpBuf)); if(unsigned int VPtCnt = BigCountValParts(BigMulA)) { for(unsigned int Idx=0;Idx < VPtCnt;Idx++) { ElemType Value = BigMulA[Idx]; for(unsigned int Ctr=0;Ctr < NumOfParts;Ctr++,Value >>= 1) { if(!Value && ((Idx+1) >= VPtCnt))break; if(Value & 1) { BigAddU(WrkBuf, TmpBuf); // res = (res*Value) % Modulus; BigDivRemU(WrkBuf, BigMod); } BigAddU(TmpBuf, TmpBuf); // pow // Value = (Value*Value) % Modulus; BigDivRemU(TmpBuf, BigMod); } } } memcpy(BigMulB, WrkBuf, sizeof(WrkBuf)); } //------------------------------------------------------------------------------------------------------------ static void BigPowMod(unsigned char* aValue, unsigned char* aExponent, unsigned char* aModulus, unsigned char* aDstBuf) { ElemType vSrcValue[NumOfParts]; ElemType vExponent[NumOfParts]; ElemType vModulus[NumOfParts]; ElemType vBigRes[NumOfParts]; ReverseCopy(vSrcValue, (ElemType*)aValue, NumOfParts); // License ReverseCopy(vExponent, (ElemType*)aExponent, NumOfParts); ReverseCopy(vModulus, (ElemType*)aModulus, NumOfParts); memset(&vBigRes,0,sizeof(vBigRes)); vBigRes[0] = 1; // Make Big One if(unsigned int DParts = BigCountValParts(vExponent)) // Anything ^ 0 = 1 { for(unsigned int CtrA=0;CtrA < DParts;CtrA++) // Valued parts of exponent { bool Flag = (CtrA+1) < DParts; ElemType ExpVal = vExponent[CtrA]; for(unsigned int CtrB=0;(ExpVal || Flag) && (CtrB < (sizeof(ElemType)*8));CtrB++,ExpVal >>= 1) // ExpVal /= 2 // ExpCtr (Number of bits in ElemType) { if(ExpVal & 1)BigPower(vSrcValue, vBigRes, vModulus); BigPower(vSrcValue, vSrcValue, vModulus); } } } ReverseCopy((ElemType*)aDstBuf, vBigRes, NumOfParts); } //------------------------------------------------------------------------------------------------------------ public: //------------------------------------------------------------------------------------------------------------ CBigInt(void):IntParts(0) {} //------------------------------------------------------------------------------------------------------------ void PowMod(unsigned char* aValue, unsigned char* aExponent, unsigned char* aModulus, unsigned char* aDstBuf) { BigPowMod(aValue, aExponent, aModulus, aDstBuf); } //------------------------------------------------------------------------------------------------------------ }; //------------------------------------------------------------------------------------------------------------
[ "Vicshann@gmail.com" ]
Vicshann@gmail.com
0997b54258cc050cdcb22687bdad63bf5bcd9d20
39ad116dab0ba316a6e7f737a031a0f853685d41
/edu116/b.cpp
528adffd7126bd2a19109653b8afb43426661101
[]
no_license
Abunyawa/contests
e0f9d157ce93d3fc5fbff0e3e576f15286272c98
9923df8f167e8091e23f890b01368a3a8f61e452
refs/heads/master
2023-05-31T14:20:31.983437
2023-05-11T14:19:58
2023-05-11T14:19:58
251,015,695
10
0
null
null
null
null
UTF-8
C++
false
false
1,004
cpp
// chrono::system_clock::now().time_since_epoch().count() #include <bits/stdc++.h> #define pb push_back #define eb emplace_back #define mp make_pair #define fi first #define se second #define all(x) (x).begin(), (x).end() #define sz(x) (int)(x).size() #define rep(i, a, b) for (int i = (a); i < (b); ++i) #define debug(x) cerr << #x << " = " << x << endl using namespace std; typedef long long ll; typedef pair<int, int> pii; typedef vector<int> vi; typedef vector<ll> vl; void yes(){ cout<<"YES"<<'\n'; } void no(){ cout<<"NO"<<'\n'; } void solve() { ll n,k; cin>>n>>k; ll cur = 1; ll ans = 0; while(cur<n){ if(cur<=k){ cur*=2; ans++; }else{ break; } } if(cur<n){ ans += (n-cur+k-1)/k; } cout<<ans<<'\n'; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int tt = 1; cin>>tt; while (tt--) { solve(); } return 0; }
[ "abusaid.manap@gmail.com" ]
abusaid.manap@gmail.com
6864b6600ba10911356faf694a673bf25956a21e
94a91b89f420e50a8ac827e3323b5e6ec588820e
/Engine/Core/Components/LightSource (Old).h
4bd70024184258fa40c52ebc4904373747e69aad
[]
no_license
cn1504/OrcRugby
6e5e2dffa795ea2873e60f2b383725068a80a656
af56a70c7aaffe26403a8085f9ea15166127646b
refs/heads/master
2020-03-29T12:55:52.937391
2015-06-29T21:19:30
2015-06-29T21:19:30
26,777,949
0
0
null
null
null
null
UTF-8
C++
false
false
929
h
#pragma once #include "Core.h" #include "Component.h" #include <Bullet/BulletCollision/CollisionDispatch/btGhostObject.h> #include <Renderers/RenderBuffer.h> #include <Renderers/Shader.h> namespace Core { namespace Components { class LightSource : public Component { protected: //Scene* scene; bool shadow; btSphereShape* shape; std::vector<Core::Entity*> litObjects; public: //RenderBuffer* ShadowRB; glm::mat4 Projection; glm::vec3 Color; float Radius; float Intensity; float CosInner; float CosOuter; //LightSource(Scene* scene, glm::vec3 color, float radius, float intensity, float cosInner, float cosOuter, bool castsShadow = false); virtual ~LightSource(); virtual void Load(); virtual void Update(); bool CastsShadow(); std::vector<Core::Entity*>* GetLitObjects(); GLuint GetShadowTexture(); //void WriteShaderUniforms(Shader* shader); }; } }
[ "cnielsenxt@gmail.com" ]
cnielsenxt@gmail.com
a902c98ce80d4527d2edea0d53c67b7c81060c5f
4a761d25954a9dd9aafbcac677a62e83e6785ba3
/src/test/test_concrete.h
4252d50025d682c34c4ef12fa38448f1e34a3773
[ "MIT" ]
permissive
CONCRETE-Project/CONCRETE
4dce6c776857d0fccef094f29aae1228796bd03c
f446b5335bff7f7a6a1ffeba97777339539263b0
refs/heads/master
2022-12-02T16:07:03.999082
2020-08-24T21:25:18
2020-08-24T21:25:18
256,929,363
1
0
null
null
null
null
UTF-8
C++
false
false
1,823
h
// Copyright (c) 2015-2019 The PIVX Core Developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef CONCRETE_TEST_TEST_CONCRETE_H #define CONCRETE_TEST_TEST_CONCRETE_H #include "txdb.h" #include <boost/filesystem.hpp> #include <boost/thread.hpp> extern uint256 insecure_rand_seed; extern FastRandomContext insecure_rand_ctx; static inline void SeedInsecureRand(bool fDeterministic = false) { if (fDeterministic) { insecure_rand_seed = uint256(); } else { insecure_rand_seed = GetRandHash(); } insecure_rand_ctx = FastRandomContext(insecure_rand_seed); } static inline uint32_t InsecureRand32() { return insecure_rand_ctx.rand32(); } static inline uint256 InsecureRand256() { return insecure_rand_ctx.rand256(); } static inline uint64_t InsecureRandBits(int bits) { return insecure_rand_ctx.randbits(bits); } static inline uint64_t InsecureRandRange(uint64_t range) { return insecure_rand_ctx.randrange(range); } static inline bool InsecureRandBool() { return insecure_rand_ctx.randbool(); } static inline std::vector<unsigned char> InsecureRandBytes(size_t len) { return insecure_rand_ctx.randbytes(len); } /** Basic testing setup. * This just configures logging and chain parameters. */ struct BasicTestingSetup { BasicTestingSetup(); ~BasicTestingSetup(); }; /** Testing setup that configures a complete environment. * Included are data directory, coins database, script check threads * and wallet (if enabled) setup. */ struct TestingSetup: public BasicTestingSetup { CCoinsViewDB *pcoinsdbview; boost::filesystem::path pathTemp; boost::thread_group threadGroup; ECCVerifyHandle globalVerifyHandle; TestingSetup(); ~TestingSetup(); }; #endif
[ "ziofabry@hotmail.com" ]
ziofabry@hotmail.com
bb9d943afee3949a448e53d7457f88dc7f327144
ea4a1b9e369c879ff1cc254f0adb5f33649b284f
/Design_Pattern_Project/Interpreter/Boolean_Example_GOF/Parser.h
c0ef4e5051be30b3d09c7efcb3364accc3965482
[]
no_license
jfacoustic/CSCI375_S2017_CMU
a6a1e010a8f9756cf7ec51d5a3579fcaf96815a0
0ca75f32c5f4f100b48b01891413168a36ceacbc
refs/heads/master
2021-01-11T15:52:59.621790
2017-05-09T02:30:04
2017-05-09T02:30:04
79,947,230
0
0
null
null
null
null
UTF-8
C++
false
false
406
h
/* * Parser.h * * Created on: Apr 18, 2017 * Author: joshua */ #ifndef PARSER_H_ #define PARSER_H_ #include <map> #include "BooleanExp.h" class Parser { public: Parser(std::string _expression); virtual ~Parser(); private: std::string expression; std::map<std::string, BooleanExp> parserMap; std::string sortString(); std::string sortedString = sortString(); }; #endif /* PARSER_H_ */
[ "joshfeltonm@gmail.com" ]
joshfeltonm@gmail.com
aaf8eaba78ad385bcbd3754e23dcf79ae97f701c
cdb83d7f079d211a2b5493145ef9bdfef6b6e434
/include/logger.h
8845b7f669822ed9f043967fc2132034a0e50c77
[]
no_license
theDrsh/uComsImpl
a03a7077c98a898ad74af50c60a32f04cfcf8664
2f3ac7f8d1a9cc605e95c2c6ca9b0a59aaba945e
refs/heads/master
2023-02-04T05:38:48.738603
2020-12-09T00:43:08
2020-12-09T00:43:08
318,061,730
0
0
null
null
null
null
UTF-8
C++
false
false
506
h
// Author: Daniel Rush #pragma once #include <stdarg.h> #include <stdio.h> #include <string.h> #include "stm32f3xx_hal.h" enum LoggerLevel { kLogDebug = 0, kLogInfo = 1, kLogError = 2, kLogFatal = 3, kLogLevels, }; const int32_t MSG_SIZE = 256; class Logger { public: void Printf(LoggerLevel Level, const char* format, ...); private: void Write(const char* msg); void FormatMessage(LoggerLevel level, const char* format, va_list args); int foo; char msg_buffer_[MSG_SIZE]; };
[ "rush.daniel95@gmail.com" ]
rush.daniel95@gmail.com
7328dc7759fe1361159d8572c9b78bc8b844cd11
1fd507f588b94402a8c1ffe080e470f65a2b7ee6
/Hall Management Project with C/search.cpp
a87fd00d41723bb3c6eafb969af29c78ca8b5794
[]
no_license
MuhiminOsim/Academic-Projects
769ab00013f915fc651d15e4517b6d1d10c439d4
00252b7efbbedbfff5d5a13aa9af0ec04ec7df6f
refs/heads/master
2023-01-12T10:26:26.864981
2019-12-12T04:35:54
2019-12-12T04:35:54
194,081,586
2
0
null
2023-01-04T01:13:41
2019-06-27T11:18:38
HTML
UTF-8
C++
false
false
2,172
cpp
#include <stdio.h> #include <string.h> #include <stdlib.h> #include "hall.h" void searching(int b, int c){ system("cls"); printf("\n\n\t\t\t\t\t~~~~STUDENT DATA SEARCHING~~~~\n"); printf("\t\t\t\t\t______________________________\n"); int x,y; printf("\n\n\t\t\t\t\tSearch Roll Numbers: "); scanf("%d",&x); if(x<1000000 || x>9999999){ while(x<1000000 || x>9999999){ printf("\n\t\t\t\tPlease Enter A 6 Digits Valid Roll: "); scanf("%d",&x); } } int room,roll,border,year,term,lastd,lastm,lasty,temp,halldue; char *name, *dept, *meal; name=(char *)malloc(30*sizeof(char)); dept=(char *)malloc(10*sizeof(char)); meal=(char *)malloc(3*sizeof(char)); FILE *srch; srch=fopen("student data.txt","r"); temp=0; while(!feof(srch)){ fgets(name,30,srch); fscanf(srch,"%d %d %s %d %d %d %s %d %d %d %d",&roll,&room,dept,&year,&term,&border,meal,&lastd,&lastm,&lasty,&halldue); if(roll==x){ y=strlen(name); name[y-1]='\0'; printf("\n\t\t\t\t\t%s's Profile\n",name); printf("\t\t\t\t\tRoll: %d\n",roll); printf("\t\t\t\t\tRoom No.: %d\n",room); printf("\t\t\t\t\tDepartment: %s\n",dept); printf("\t\t\t\t\tYear: %d\n",year); printf("\t\t\t\t\tTerm: %d\n",term); printf("\t\t\t\t\tBorder: %d\n",border); printf("\t\t\t\t\tMeal status: %s\n",meal); printf("\t\t\t\t\tLast hall due date: %d/%d/%d\n",lastd,lastm,lasty); printf("\t\t\t\t\tHall Due: %d\n",halldue); temp=1; break; } } if(temp==0){ printf("\n\t\t\t\t\tNOT FOUND!\n"); } fclose(srch); printf("\t\t\t\t\tChoose: 1.Search Again\n\t\t\t\t\t\t2.Update Data\n\t\t\t\t\t\t3.Exit\n\t\t\t\t\t\t4.Menu\n\t\t\t\t\t\t"); scanf("%d",&y); if(y<1 || y>4){ while(y<1 || y>4){ printf("\n\t\t\t\t\tPlease Enter A Valid Digit: "); scanf("%d",&y); } } if(y==1) searching(b,c); else if(y==2) update(b,c); else if(y==3) exit(0); else menu(); }
[ "muhiminul@gmail.com" ]
muhiminul@gmail.com
0b5dc127de05952f220089ff6f2cfbc61aa6e773
2e459946616dc440360e9ad6a09fde8ce3b3ca40
/gauss_driver/src/rpi/rpi_diagnostics.cpp
f2bed533717280840666209071b65e9913704fa5
[]
no_license
junjian-zhang/gauss
a09641b831b967ecea69bdf5f60affc21e95461a
849183725d402663d898a93c00a5ba9e4b7ed569
refs/heads/master
2020-04-27T04:22:42.036477
2019-01-31T08:08:47
2019-01-31T08:08:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,333
cpp
#include "gauss_driver/rpi/rpi_diagnostics.h" RpiDiagnostics::RpiDiagnostics() { cpu_temperature = 0; startReadingData(); } int RpiDiagnostics::getRpiCpuTemperature() { return cpu_temperature; } void RpiDiagnostics::readCpuTemperature() { #ifdef __arm__ std::fstream cpu_temp_file("/sys/class/thermal/thermal_zone0/temp", std::ios_base::in); int read_temp; cpu_temp_file >> read_temp; if (read_temp > 0) { cpu_temperature = read_temp / 1000; } #endif } void RpiDiagnostics::startReadingData() { read_hardware_data_thread.reset(new std::thread(boost::bind(&RpiDiagnostics::readHardwareDataLoop, this))); } void RpiDiagnostics::readHardwareDataLoop() { double read_rpi_diagnostics_frequency; ros::param::get("~read_rpi_diagnostics_frequency", read_rpi_diagnostics_frequency); ros::Rate read_rpi_diagnostics_rate = ros::Rate(read_rpi_diagnostics_frequency); while (ros::ok()) { readCpuTemperature(); // check if Rpi is too hot if (cpu_temperature > 75) { ROS_ERROR("Rpi temperature is really high !"); } if (cpu_temperature > 85) { ROS_ERROR("Rpi is too hot, shutdown to avoid any damage"); std::system("sudo shutdown now"); } read_rpi_diagnostics_rate.sleep(); } }
[ "bjq1016@163.com" ]
bjq1016@163.com
a35c491da031ede7af44ed8b04214cf2b0ca00ff
52b624b6937c5cdf358a3734efe6a395305bd93e
/src/SFmpqapi/linux/windows.cpp
e9329e28bb01f1952ed05da13c181e80fc02a416
[ "MIT", "BSD-2-Clause" ]
permissive
actboy168/wc3mapmax
c23e5101f9eda7168b3f8f12e44357be5fbeddbb
46eebca381ca1816d8edb02332f19eb6c7f98f60
refs/heads/master
2021-01-15T15:47:28.771064
2016-11-04T12:50:30
2016-11-04T12:50:30
32,116,740
5
2
null
null
null
null
UTF-8
C++
false
false
4,811
cpp
/* License information for this code is in license.txt */ #include "windows.h" DWORD dwAppLastError=0; void WINAPI SetLastError(DWORD dwLastError) { dwAppLastError=dwLastError; } DWORD WINAPI GetLastError() { return dwAppLastError; } DWORD WINAPI GetCurrentDirectory(DWORD dwBufferLength, LPSTR lpBuffer) { if (lpBuffer==0) return 0; strncpy(lpBuffer,"./",dwBufferLength); return strlen(lpBuffer)+1; } DWORD WINAPI GetDriveType(LPCSTR lpRootPath) { return DRIVE_FIXED; } HANDLE WINAPI CreateFile(LPCSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile) { if (lpFileName==0) return INVALID_HANDLE_VALUE; int nFlags,hFile; if ((dwDesiredAccess&GENERIC_READ && dwDesiredAccess&GENERIC_WRITE) || dwDesiredAccess&GENERIC_ALL) { nFlags = O_RDWR; } else if (dwDesiredAccess&GENERIC_READ) { nFlags = O_RDONLY; } else if (dwDesiredAccess&GENERIC_WRITE) { nFlags = O_WRONLY; } else { nFlags = 0; } switch (dwCreationDisposition) { case CREATE_NEW: hFile = open(lpFileName,0); if (hFile!=-1) {close(hFile);return INVALID_HANDLE_VALUE;} nFlags |= O_CREAT; break; case CREATE_ALWAYS: nFlags |= O_CREAT|O_TRUNC; break; case OPEN_EXISTING: break; case OPEN_ALWAYS: hFile = open(lpFileName,0); if (hFile==-1) nFlags |= O_CREAT; else close(hFile); break; case TRUNCATE_EXISTING: nFlags |= O_TRUNC; break; default: return INVALID_HANDLE_VALUE; } hFile = open(lpFileName,nFlags); if (hFile!=-1) chmod(lpFileName,0644); return (HANDLE)hFile; } BOOL WINAPI CloseHandle(HANDLE hObject) { if (hObject==INVALID_HANDLE_VALUE) return 0; return (BOOL)(close((int)hObject) == 0); } DWORD WINAPI GetFileSize(HANDLE hFile, LPDWORD lpFileSizeHigh) { if (hFile==INVALID_HANDLE_VALUE) return (DWORD)-1; struct stat fileinfo; fstat((int)hFile, &fileinfo); if (lpFileSizeHigh) *lpFileSizeHigh = 0; return (DWORD)fileinfo.st_size; } DWORD WINAPI SetFilePointer(HANDLE hFile, LONG lDistanceToMove, PLONG lpDistanceToMoveHigh, DWORD dwMoveMethod) { if (hFile==INVALID_HANDLE_VALUE) return (DWORD)-1; switch (dwMoveMethod) { case FILE_BEGIN: return (DWORD)lseek((int)hFile, lDistanceToMove, SEEK_SET); case FILE_CURRENT: return (DWORD)lseek((int)hFile, lDistanceToMove, SEEK_CUR); case FILE_END: return (DWORD)lseek((int)hFile, lDistanceToMove, SEEK_END); } return (DWORD)-1; } BOOL WINAPI SetEndOfFile(HANDLE hFile) { if (hFile==INVALID_HANDLE_VALUE) return 0; return (BOOL)(ftruncate((int)hFile, lseek((int)hFile, 0, SEEK_CUR)) == 0); } BOOL WINAPI ReadFile(HANDLE hFile, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, LPDWORD lpNumberOfBytesRead, LPOVERLAPPED lpOverlapped) { if (hFile==INVALID_HANDLE_VALUE || lpBuffer==0) return 0; ssize_t count; if ((count = read((int)hFile, lpBuffer, nNumberOfBytesToRead)) == -1) { if (lpNumberOfBytesRead) *lpNumberOfBytesRead = 0; return FALSE; } if (lpNumberOfBytesRead) *lpNumberOfBytesRead = count; return TRUE; } BOOL WINAPI WriteFile(HANDLE hFile, LPCVOID lpBuffer, DWORD nNumberOfBytesToWrite, LPDWORD lpNumberOfBytesWritten, LPOVERLAPPED lpOverlapped) { if (hFile==INVALID_HANDLE_VALUE || lpBuffer==0) return 0; ssize_t count; if ((count = write((int)hFile, lpBuffer, nNumberOfBytesToWrite)) == -1) { if (lpNumberOfBytesWritten) *lpNumberOfBytesWritten = 0; return FALSE; } if (lpNumberOfBytesWritten) *lpNumberOfBytesWritten = count; return TRUE; } BOOL WINAPI DeleteFile(LPCSTR lpFileName) { if (lpFileName==0) return FALSE; return (BOOL)(unlink(lpFileName) == 0); } char * strlwr(char *lpString) { if (lpString==0) return 0; for (char *lpChar=lpString;lpChar[0]==0;lpChar++) lpChar[0] = tolower(lpChar[0]); return lpString; } char * strupr(char *lpString) { if (lpString==0) return 0; for (char *lpChar=lpString;lpChar[0]==0;lpChar++) lpChar[0] = toupper(lpChar[0]); return lpString; } char * strdup(const char *lpString) { if (lpString==0) return 0; char *lpStrCopy = (char *)malloc(strlen(lpString)+1); if (lpStrCopy==0) return 0; strcpy(lpStrCopy,lpString); return lpStrCopy; } int memicmp(const char *lpString1, const char *lpString2, size_t dwSize) { if (lpString1==0) return -1; if (lpString2==0) return 1; if (dwSize==0) return 0; size_t i; char ch1,ch2; for (i=0;i<dwSize;i++) { ch1 = toupper(lpString1[i]); ch2 = toupper(lpString2[i]); if (ch1 > ch2) return 1; else if (ch1 < ch2) return -1; } return 0; } void SlashToBackslash(char *lpPath) { if (lpPath==0) return; for (;lpPath[0]!=0;lpPath++) if (lpPath[0]=='/') lpPath[0]='\\'; } void BackslashToSlash(char *lpPath) { if (lpPath==0) return; for (;lpPath[0]!=0;lpPath++) if (lpPath[0]=='\\') lpPath[0]='/'; }
[ "actboy168@gmail.com" ]
actboy168@gmail.com
0e3be275a98160495487495b4ae4c15d9d32b992
81533e098a8fd6d8458ef78bec9b7cd468733328
/linux/javacef/cefclient/client_app.cpp
285ffad93031ed5c45b287813a3c5bcc5ed8ceba
[]
no_license
inaauto/javacef
0ec07da810d3ff48d39b83dd51b690e33e0ee75f
a3a11cfef1aca54d34e1bbc9aaff0aa3fb7d01d7
refs/heads/master
2021-01-23T23:52:37.255643
2017-05-31T12:44:02
2017-05-31T12:44:02
59,431,494
2
0
null
2017-01-05T13:51:36
2016-05-22T19:57:08
C++
UTF-8
C++
false
false
15,186
cpp
// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights // reserved. Use of this source code is governed by a BSD-style license that // can be found in the LICENSE file. // This file is shared by cefclient and cef_unittests so don't include using // a qualified path. #include "client_app.h" // NOLINT(build/include) #include <string> #include "include/cef_cookie.h" #include "include/cef_process_message.h" #include "include/cef_task.h" #include "include/cef_v8.h" #include "util.h" // NOLINT(build/include) namespace { // Forward declarations. void SetList(CefRefPtr<CefV8Value> source, CefRefPtr<CefListValue> target); void SetList(CefRefPtr<CefListValue> source, CefRefPtr<CefV8Value> target); // Transfer a V8 value to a List index. void SetListValue(CefRefPtr<CefListValue> list, int index, CefRefPtr<CefV8Value> value) { if (value->IsArray()) { CefRefPtr<CefListValue> new_list = CefListValue::Create(); SetList(value, new_list); list->SetList(index, new_list); } else if (value->IsString()) { list->SetString(index, value->GetStringValue()); } else if (value->IsBool()) { list->SetBool(index, value->GetBoolValue()); } else if (value->IsInt()) { list->SetInt(index, value->GetIntValue()); } else if (value->IsDouble()) { list->SetDouble(index, value->GetDoubleValue()); } } // Transfer a V8 array to a List. void SetList(CefRefPtr<CefV8Value> source, CefRefPtr<CefListValue> target) { ASSERT(source->IsArray()); int arg_length = source->GetArrayLength(); if (arg_length == 0) return; // Start with null types in all spaces. target->SetSize(arg_length); for (int i = 0; i < arg_length; ++i) SetListValue(target, i, source->GetValue(i)); } // Transfer a List value to a V8 array index. void SetListValue(CefRefPtr<CefV8Value> list, int index, CefRefPtr<CefListValue> value) { CefRefPtr<CefV8Value> new_value; CefValueType type = value->GetType(index); switch (type) { case VTYPE_LIST: { CefRefPtr<CefListValue> list = value->GetList(index); new_value = CefV8Value::CreateArray(list->GetSize()); SetList(list, new_value); } break; case VTYPE_BOOL: new_value = CefV8Value::CreateBool(value->GetBool(index)); break; case VTYPE_DOUBLE: new_value = CefV8Value::CreateDouble(value->GetDouble(index)); break; case VTYPE_INT: new_value = CefV8Value::CreateInt(value->GetInt(index)); break; case VTYPE_STRING: new_value = CefV8Value::CreateString(value->GetString(index)); break; default: break; } if (new_value.get()) { list->SetValue(index, new_value); } else { list->SetValue(index, CefV8Value::CreateNull()); } } // Transfer a List to a V8 array. void SetList(CefRefPtr<CefListValue> source, CefRefPtr<CefV8Value> target) { ASSERT(target->IsArray()); int arg_length = source->GetSize(); if (arg_length == 0) return; for (int i = 0; i < arg_length; ++i) SetListValue(target, i, source); } // Handles the native implementation for the client_app extension. class ClientAppExtensionHandler : public CefV8Handler { public: explicit ClientAppExtensionHandler(CefRefPtr<ClientApp> client_app) : client_app_(client_app) { } virtual bool Execute(const CefString& name, CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& exception) { bool handled = false; if (name == "sendMessage") { // Send a message to the browser process. if ((arguments.size() == 1 || arguments.size() == 2) && arguments[0]->IsString()) { CefRefPtr<CefBrowser> browser = CefV8Context::GetCurrentContext()->GetBrowser(); ASSERT(browser.get()); CefString name = arguments[0]->GetStringValue(); if (!name.empty()) { CefRefPtr<CefProcessMessage> message = CefProcessMessage::Create(name); // Translate the arguments, if any. if (arguments.size() == 2 && arguments[1]->IsArray()) SetList(arguments[1], message->GetArgumentList()); browser->SendProcessMessage(PID_BROWSER, message); handled = true; } } } else if (name == "setMessageCallback") { // Set a message callback. if (arguments.size() == 2 && arguments[0]->IsString() && arguments[1]->IsFunction()) { std::string name = arguments[0]->GetStringValue(); CefRefPtr<CefV8Context> context = CefV8Context::GetCurrentContext(); int browser_id = context->GetBrowser()->GetIdentifier(); client_app_->SetMessageCallback(name, browser_id, context, arguments[1]); handled = true; } } else if (name == "removeMessageCallback") { // Remove a message callback. if (arguments.size() == 1 && arguments[0]->IsString()) { std::string name = arguments[0]->GetStringValue(); CefRefPtr<CefV8Context> context = CefV8Context::GetCurrentContext(); int browser_id = context->GetBrowser()->GetIdentifier(); bool removed = client_app_->RemoveMessageCallback(name, browser_id); retval = CefV8Value::CreateBool(removed); handled = true; } } if (!handled) exception = "Invalid method arguments"; return true; } private: CefRefPtr<ClientApp> client_app_; IMPLEMENT_REFCOUNTING(ClientAppExtensionHandler); }; } // namespace ClientApp::ClientApp() { CreateBrowserDelegates(browser_delegates_); CreateRenderDelegates(render_delegates_); // Default schemes that support cookies. cookieable_schemes_.push_back("http"); cookieable_schemes_.push_back("https"); } void ClientApp::SetMessageCallback(const std::string& message_name, int browser_id, CefRefPtr<CefV8Context> context, CefRefPtr<CefV8Value> function) { ASSERT(CefCurrentlyOn(TID_RENDERER)); callback_map_.insert( std::make_pair(std::make_pair(message_name, browser_id), std::make_pair(context, function))); } bool ClientApp::RemoveMessageCallback(const std::string& message_name, int browser_id) { ASSERT(CefCurrentlyOn(TID_RENDERER)); CallbackMap::iterator it = callback_map_.find(std::make_pair(message_name, browser_id)); if (it != callback_map_.end()) { callback_map_.erase(it); return true; } return false; } void ClientApp::OnContextInitialized() { // Register cookieable schemes with the global cookie manager. CefRefPtr<CefCookieManager> manager = CefCookieManager::GetGlobalManager(); ASSERT(manager.get()); manager->SetSupportedSchemes(cookieable_schemes_); BrowserDelegateSet::iterator it = browser_delegates_.begin(); for (; it != browser_delegates_.end(); ++it) (*it)->OnContextInitialized(this); } extern const int MAX_PATH; void ClientApp::OnBeforeChildProcessLaunch( CefRefPtr<CefCommandLine> command_line) { BrowserDelegateSet::iterator it = browser_delegates_.begin(); for (; it != browser_delegates_.end(); ++it) (*it)->OnBeforeChildProcessLaunch(this, command_line); const int MAX_PATH = 512; char cefclient[MAX_PATH];//, cefclient1[MAX_PATH]; if (!getcwd(cefclient, sizeof(cefclient))) return; //sprintf(cefclient1, "%s %s%s", "valgrind", cefclient, "/cefclient"); strcat(cefclient, "/cefclient"); command_line->PrependWrapper(cefclient); } void ClientApp::OnRenderProcessThreadCreated( CefRefPtr<CefListValue> extra_info) { BrowserDelegateSet::iterator it = browser_delegates_.begin(); for (; it != browser_delegates_.end(); ++it) (*it)->OnRenderProcessThreadCreated(this, extra_info); } void ClientApp::OnRenderThreadCreated(CefRefPtr<CefListValue> extra_info) { RenderDelegateSet::iterator it = render_delegates_.begin(); for (; it != render_delegates_.end(); ++it) (*it)->OnRenderThreadCreated(this, extra_info); } void ClientApp::OnWebKitInitialized() { // Register the client_app extension. std::string app_code = "var app;" "if (!app)" " app = {};" "(function() {" " app.sendMessage = function(name, arguments) {" " native function sendMessage();" " return sendMessage(name, arguments);" " };" " app.setMessageCallback = function(name, callback) {" " native function setMessageCallback();" " return setMessageCallback(name, callback);" " };" " app.removeMessageCallback = function(name) {" " native function removeMessageCallback();" " return removeMessageCallback(name);" " };" "})();"; CefRegisterExtension("v8/app", app_code, new ClientAppExtensionHandler(this)); RenderDelegateSet::iterator it = render_delegates_.begin(); for (; it != render_delegates_.end(); ++it) (*it)->OnWebKitInitialized(this); } void ClientApp::OnBrowserCreated(CefRefPtr<CefBrowser> browser) { RenderDelegateSet::iterator it = render_delegates_.begin(); for (; it != render_delegates_.end(); ++it) (*it)->OnBrowserCreated(this, browser); } void ClientApp::OnBrowserDestroyed(CefRefPtr<CefBrowser> browser) { RenderDelegateSet::iterator it = render_delegates_.begin(); for (; it != render_delegates_.end(); ++it) (*it)->OnBrowserDestroyed(this, browser); } bool ClientApp::OnBeforeNavigation(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefRequest> request, NavigationType navigation_type, bool is_redirect) { RenderDelegateSet::iterator it = render_delegates_.begin(); for (; it != render_delegates_.end(); ++it) { if ((*it)->OnBeforeNavigation(this, browser, frame, request, navigation_type, is_redirect)) { return true; } } return false; } void ClientApp::OnContextCreated(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefV8Context> context) { RenderDelegateSet::iterator it = render_delegates_.begin(); for (; it != render_delegates_.end(); ++it) (*it)->OnContextCreated(this, browser, frame, context); } void ClientApp::OnContextReleased(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefV8Context> context) { RenderDelegateSet::iterator it = render_delegates_.begin(); for (; it != render_delegates_.end(); ++it) (*it)->OnContextReleased(this, browser, frame, context); // Remove any JavaScript callbacks registered for the context that has been // released. if (!callback_map_.empty()) { CallbackMap::iterator it = callback_map_.begin(); for (; it != callback_map_.end();) { if (it->second.first->IsSame(context)) callback_map_.erase(it++); else ++it; } } } void ClientApp::OnUncaughtException(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefV8Context> context, CefRefPtr<CefV8Exception> exception, CefRefPtr<CefV8StackTrace> stackTrace) { RenderDelegateSet::iterator it = render_delegates_.begin(); for (; it != render_delegates_.end(); ++it) { (*it)->OnUncaughtException(this, browser, frame, context, exception, stackTrace); } } void ClientApp::OnWorkerContextCreated(int worker_id, const CefString& url, CefRefPtr<CefV8Context> context) { RenderDelegateSet::iterator it = render_delegates_.begin(); for (; it != render_delegates_.end(); ++it) (*it)->OnWorkerContextCreated(this, worker_id, url, context); } void ClientApp::OnWorkerContextReleased(int worker_id, const CefString& url, CefRefPtr<CefV8Context> context) { RenderDelegateSet::iterator it = render_delegates_.begin(); for (; it != render_delegates_.end(); ++it) (*it)->OnWorkerContextReleased(this, worker_id, url, context); } void ClientApp::OnWorkerUncaughtException( int worker_id, const CefString& url, CefRefPtr<CefV8Context> context, CefRefPtr<CefV8Exception> exception, CefRefPtr<CefV8StackTrace> stackTrace) { RenderDelegateSet::iterator it = render_delegates_.begin(); for (; it != render_delegates_.end(); ++it) { (*it)->OnWorkerUncaughtException(this, worker_id, url, context, exception, stackTrace); } } void ClientApp::OnFocusedNodeChanged(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefDOMNode> node) { RenderDelegateSet::iterator it = render_delegates_.begin(); for (; it != render_delegates_.end(); ++it) (*it)->OnFocusedNodeChanged(this, browser, frame, node); } bool ClientApp::OnProcessMessageReceived( CefRefPtr<CefBrowser> browser, CefProcessId source_process, CefRefPtr<CefProcessMessage> message) { ASSERT(source_process == PID_BROWSER); bool handled = false; RenderDelegateSet::iterator it = render_delegates_.begin(); for (; it != render_delegates_.end() && !handled; ++it) { handled = (*it)->OnProcessMessageReceived(this, browser, source_process, message); } if (handled) return true; // Execute the registered JavaScript callback if any. if (!callback_map_.empty()) { CefString message_name = message->GetName(); CallbackMap::const_iterator it = callback_map_.find( std::make_pair(message_name.ToString(), browser->GetIdentifier())); if (it != callback_map_.end()) { // Keep a local reference to the objects. The callback may remove itself // from the callback map. CefRefPtr<CefV8Context> context = it->second.first; CefRefPtr<CefV8Value> callback = it->second.second; // Enter the context. context->Enter(); CefV8ValueList arguments; // First argument is the message name. arguments.push_back(CefV8Value::CreateString(message_name)); // Second argument is the list of message arguments. CefRefPtr<CefListValue> list = message->GetArgumentList(); CefRefPtr<CefV8Value> args = CefV8Value::CreateArray(list->GetSize()); SetList(list, args); arguments.push_back(args); // Execute the callback. CefRefPtr<CefV8Value> retval = callback->ExecuteFunction(NULL, arguments); if (retval.get()) { if (retval->IsBool()) handled = retval->GetBoolValue(); } // Exit the context. context->Exit(); } } return handled; }
[ "wjywbss@gmail.com" ]
wjywbss@gmail.com
69640eedec5c97a8a6f39c0a97d9052ce42bfd43
17198f70b67390e2b6fa30dfda47909e7d26a59b
/src/validationinterface.h
470a2b5fa3edb0d52a7d711266af37d4be6d00d6
[ "MIT" ]
permissive
HighStakesCoin/HighStakes
9d3fd09ce623167d79e100568adea70106efc239
e842f55f7ce6f8df09aea157012a68958b366a90
refs/heads/master
2020-05-04T15:47:57.812490
2019-07-26T07:18:42
2019-07-26T07:18:42
179,256,859
3
3
null
null
null
null
UTF-8
C++
false
false
3,958
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Copyright (c) 2017-2018 The PIVX developers // Copyright (c) 2019 The HighStakes developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_VALIDATIONINTERFACE_H #define BITCOIN_VALIDATIONINTERFACE_H #include <boost/signals2/signal.hpp> #include <boost/shared_ptr.hpp> class CBlock; struct CBlockLocator; class CBlockIndex; class CReserveScript; class CTransaction; class CValidationInterface; class CValidationState; class uint256; // These functions dispatch to one or all registered wallets /** Register a wallet to receive updates from core */ void RegisterValidationInterface(CValidationInterface* pwalletIn); /** Unregister a wallet from core */ void UnregisterValidationInterface(CValidationInterface* pwalletIn); /** Unregister all wallets from core */ void UnregisterAllValidationInterfaces(); /** Push an updated transaction to all registered wallets */ void SyncWithWallets(const CTransaction& tx, const CBlock* pblock); class CValidationInterface { protected: // XX42 virtual void EraseFromWallet(const uint256& hash){}; virtual void UpdatedBlockTip(const CBlockIndex *pindex) {} virtual void SyncTransaction(const CTransaction &tx, const CBlock *pblock) {} virtual void NotifyTransactionLock(const CTransaction &tx) {} virtual void SetBestChain(const CBlockLocator &locator) {} virtual bool UpdatedTransaction(const uint256 &hash) { return false;} virtual void Inventory(const uint256 &hash) {} // XX42 virtual void ResendWalletTransactions(int64_t nBestBlockTime) {} virtual void ResendWalletTransactions() {} virtual void BlockChecked(const CBlock&, const CValidationState&) {} // XX42 virtual void GetScriptForMining(boost::shared_ptr<CReserveScript>&) {}; virtual void ResetRequestCount(const uint256 &hash) {}; friend void ::RegisterValidationInterface(CValidationInterface*); friend void ::UnregisterValidationInterface(CValidationInterface*); friend void ::UnregisterAllValidationInterfaces(); }; struct CMainSignals { // XX42 boost::signals2::signal<void(const uint256&)> EraseTransaction; /** Notifies listeners of updated block chain tip */ boost::signals2::signal<void (const CBlockIndex *)> UpdatedBlockTip; /** Notifies listeners of updated transaction data (transaction, and optionally the block it is found in. */ boost::signals2::signal<void (const CTransaction &, const CBlock *)> SyncTransaction; /** Notifies listeners of an updated transaction lock without new data. */ boost::signals2::signal<void (const CTransaction &)> NotifyTransactionLock; /** Notifies listeners of an updated transaction without new data (for now: a coinbase potentially becoming visible). */ boost::signals2::signal<bool (const uint256 &)> UpdatedTransaction; /** Notifies listeners of a new active block chain. */ boost::signals2::signal<void (const CBlockLocator &)> SetBestChain; /** Notifies listeners about an inventory item being seen on the network. */ boost::signals2::signal<void (const uint256 &)> Inventory; /** Tells listeners to broadcast their data. */ // XX42 boost::signals2::signal<void (int64_t nBestBlockTime)> Broadcast; boost::signals2::signal<void ()> Broadcast; /** Notifies listeners of a block validation result */ boost::signals2::signal<void (const CBlock&, const CValidationState&)> BlockChecked; /** Notifies listeners that a key for mining is required (coinbase) */ // XX42 boost::signals2::signal<void (boost::shared_ptr<CReserveScript>&)> ScriptForMining; /** Notifies listeners that a block has been successfully mined */ boost::signals2::signal<void (const uint256 &)> BlockFound; }; CMainSignals& GetMainSignals(); #endif // BITCOIN_VALIDATIONINTERFACE_H
[ "48958686+HighStakesCoin@users.noreply.github.com" ]
48958686+HighStakesCoin@users.noreply.github.com
4c0d66aa037e18c4513a8f68cceb4e5ca1d9b841
30bdd8ab897e056f0fb2f9937dcf2f608c1fd06a
/Codes/AC/3028.cpp
f9481b72d414c1a100e561f651ceb946304bf71f
[]
no_license
thegamer1907/Code_Analysis
0a2bb97a9fb5faf01d983c223d9715eb419b7519
48079e399321b585efc8a2c6a84c25e2e7a22a61
refs/heads/master
2020-05-27T01:20:55.921937
2019-11-20T11:15:11
2019-11-20T11:15:11
188,403,594
2
1
null
null
null
null
UTF-8
C++
false
false
549
cpp
#include"bits/stdc++.h" #define F(i,j,n) for(register int i=j;i<=n;i++) using namespace std; char t[1000010];int z[1000010],n,l; int main(){ #ifndef ONLINE_JUDGE freopen("article.in","r",stdin); freopen("article.out","w",stdout); #endif gets(t+1);n=strlen(t+1); F(i,2,n){ z[i]=min(z[i-l+1],max(0,l+z[l]-i)); while(i+z[i]<=n&&t[i+z[i]]==t[1+z[i]])z[i]++; if(z[i]+i-1>z[l]+l-1)l=i; } l=-1; F(i,1,n){if(i+z[i]==n+1&&l>=z[i]){puts(t+i);return 0;}l=max(l,z[i]);} puts("Just a legend"); return 0; }
[ "harshitagar1907@gmail.com" ]
harshitagar1907@gmail.com
404dda11e200ca795741ede6eb063e21958a4809
9b10842bf603269fd8986a5eb4d103108fc679ad
/src/led.cpp
d539219a2c9804708102b82f418fca218b88aca8
[ "Apache-2.0" ]
permissive
CasusCura/ArduinoPendant
c962051a0175fb8a0655ff1970cd76b85be64bca
a2158ee731d204daba66971b919a1c9fcce23c28
refs/heads/master
2021-09-10T17:02:06.855660
2018-03-29T18:17:17
2018-03-29T18:17:17
120,350,704
0
0
null
null
null
null
UTF-8
C++
false
false
1,197
cpp
/* * Module: LED * * An abstract LED object. * * Author: Alex Dale @superoxigen * * Copyright (c) 2018 Alex Dale * See LICENSE for information. */ #include <Arduino.h> #include "dlog.h" #include "led.hpp" static inline bool_t flash_state(void) { return ((millis() / LED_FLASH_RATE_MS) % 2) == 1; } Led::Led(Pin * pin): _pin(pin), _led_mode(OFF_MODE) { pin->deactivate(); } void Led::off(void) { if (_led_mode == OFF_MODE) return; _led_mode = OFF_MODE; _pin->deactivate(); } void Led::on(void) { if (_led_mode == ON_MODE) return; _led_mode = ON_MODE; _pin->activate(); } void Led::flash(void) { if (_led_mode == FLASH_MODE) return; _led_mode = FLASH_MODE; } bool_t Led::is_off(void) const { return _led_mode == OFF_MODE; } bool_t Led::is_on(void) const { return _led_mode == ON_MODE; } bool_t Led::is_flashing(void) const { return _led_mode == FLASH_MODE; } void Led::loop(void) { bool_t on; if (_led_mode != FLASH_MODE) return; on = flash_state(); if (on && !_pin->active()) { _pin->activate(); } else if (!on && _pin->active()) { _pin->deactivate(); } }
[ "alex@snowycloud.com" ]
alex@snowycloud.com
37491f644938f03ba30071ecd0f5c507b6cb577c
df74a129d6bc52f4df60c72607a7c0dff747d312
/Ping_Pong/Ping_Pong/FrameRate.cpp
1397aaac3a89241d26641fae99a848ceff344eb7
[]
no_license
Spiritfaer/PingPong
db9cd63cca3f90b3e0f00d9db1fb9209497a43f6
34543061887d93717d3c31af1a4552537a6b0583
refs/heads/master
2021-03-10T03:46:35.499672
2020-03-11T16:20:55
2020-03-11T16:20:55
246,414,151
0
0
null
null
null
null
UTF-8
C++
false
false
444
cpp
#include <iostream> #include "FrameRate.h" FrameRate::FrameRate() { old_time = SDL_GetTicks(); ticks = cur_time = 0; } FrameRate::~FrameRate() {} bool FrameRate::tick(bool db) { cur_time = SDL_GetTicks(); ++ticks; uint32_t tmp = cur_time - old_time; if (tmp > 1000) { old_time = cur_time; if (db) showFPS(ticks); ticks = 0; } return true; } void FrameRate::showFPS(uint32_t t) { std::cout << "FPS = " << t << std::endl; }
[ "30905488+Spiritfaer@users.noreply.github.com" ]
30905488+Spiritfaer@users.noreply.github.com
8a34bf34ab5df85aa8985f35dd11d9ae19cc328b
683a90831bb591526c6786e5f8c4a2b34852cf99
/HackerRank/Implementation/4_jumping_on_the_clouds-Revisited.cpp
a5fdea82c7be605851116e86376550425065be43
[]
no_license
dbetm/cp-history
32a3ee0b19236a759ce0a6b9ba1b72ceb56b194d
0ceeba631525c4776c21d547e5ab101f10c4fe70
refs/heads/main
2023-04-29T19:36:31.180763
2023-04-15T18:03:19
2023-04-15T18:03:19
164,786,056
8
0
null
null
null
null
UTF-8
C++
false
false
373
cpp
#include <bits/stdc++.h> using namespace std; int main(int argc, char* argv[]){ int n, k, i, e = 100; cin >> n >> k; int C[n]; for (int i = 0; i < n; i++){ cin >> C[i]; } i = 0; while (true) { e--; i = (i + k) % n; if(C[i] == 1) e -= 2; if(i == 0) break; } cout << e << endl; return 0; }
[ "davbetm@gmail.com" ]
davbetm@gmail.com
7d905f338b2f042b3b85869e1af33334a5c21327
9cbb3af861bbfb738f7adcdbb34339634d29e0f0
/hindex.cpp
e8e968de74e1067a6a138e54d6c98bfffc5d241a
[]
no_license
ZebraFarm/OpenKattis
d3fcffd34e0fe87fb5e53ecd75236baea7a3fed5
b9748fde5547d4c5d596da61867a92eb3d4defc3
refs/heads/master
2021-06-21T11:32:18.454409
2021-06-16T06:10:35
2021-06-16T06:10:35
192,035,775
0
0
null
null
null
null
UTF-8
C++
false
false
337
cpp
#include <iostream> #include <array> #include <algorithm> using namespace std; int main(){ int i,n,H=0; cin >> n; int s[n] = {0}; for(i=0;i<n;i++) cin >> s[i]; sort(s,s+n); if(s[0]>n)H=n; else{ for(i=0;i<n;i++){ if(H != s[i]) { if(min(s[i],n-i)>H) H= min(s[i],n-i); else break; } } } cout << H << endl; }
[ "cole.sibbald@protonmail.com" ]
cole.sibbald@protonmail.com
584dba44f99ce0550e7c1234af4b2250ae5aaf2b
693f6694c179ea26c34f4cfd366bcf875edd5511
/trains/train18/G.cpp
6ab358289234c5df0ecac50ba27c2e52002587bd
[]
no_license
romanasa/olymp_codes
db4a2a6af72c5cc1f2e6340f485e5d96d8f0b218
52dc950496ab28c4003bf8c96cbcdb0350f0646a
refs/heads/master
2020-05-07T18:54:47.966848
2019-05-22T19:41:38
2019-05-22T19:41:38
180,765,711
0
0
null
null
null
null
UTF-8
C++
false
false
622
cpp
#include <bits/stdc++.h> #define err(...) fprintf(stderr, __VA_ARGS__), fflush(stderr) #define x first #define y second #define mp make_pair #define pub push_back #define all(v) (v).begin(), (v).end() //236695ZVSVG using namespace std; typedef long long ll; typedef double db; int main() { #ifdef WIN freopen("01", "r", stdin); #else freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif // WIN int n, sum = 0; cin >> n; for (int i = 1; i <= n; i++) { int x; string s; cin >> x >> s; sum += x; } cout << sum; return 0; }
[ "romanfml31@gmail.com" ]
romanfml31@gmail.com
e338cf24ccd6ea51289ff7ce24a899bb76420300
20dfc88e522e758bb4d85900e2d1ac494b68bc3c
/src/Array.cpp
1638e51b356aafd0ae1711a3f9f557f509a15410
[]
no_license
weilunandro/CPPReview
c2fee41cad8fe582d4e3817ab4c692cf44a026d4
b4e9ec83673f2d35ae334719df7e794a8139d1ec
refs/heads/master
2020-03-08T09:12:03.553431
2018-04-04T09:37:59
2018-04-04T09:37:59
128,041,015
0
0
null
null
null
null
UTF-8
C++
false
false
304
cpp
// // Created by Andro Wei on 04/04/2018. // #include "Array.h" template<typename T> Array::Array(int capacity) { assert(capacity > 0); mCapacity = capacity; mData = new T[mCapacity]; } Array::~Array() { if (mData != nullptr) { delete[] mData; mData = nullptr; } }
[ "andro.wei@blackboard.com" ]
andro.wei@blackboard.com
c28381c1f2c5f4c2224d1d1d80d4e31205cf11f1
a7acea5217a9b84212d14614acc5d11f79de360d
/Shunyaev/cw/Source/AVLTree.cpp
0b9f308e548bf14241be1968aa82d4a517e7b674
[]
no_license
makometr/ADS-9304
f45309de83d11fa3ac8ee4edda54ffcd24906cd4
8bd69ab3726f15b1db3439876cc46985470d1a12
refs/heads/master
2023-02-15T21:05:50.387147
2021-01-06T13:46:42
2021-01-06T13:46:42
296,394,391
3
27
null
2021-01-07T21:16:59
2020-09-17T17:19:21
C++
UTF-8
C++
false
false
2,372
cpp
#include "AVLTree.h" #include "Node.h" AVLTree* AVLTree::ptr_tree_ = nullptr; AVLTree::AVLTree() { std::string str; bool is_correct = true; do { std::cout << "Enter set of digits: "; std::getline(std::cin, str); int counter = 0; for (int i = 0; i < str.size(); i++) { if ((str[i] >= 'A' && str[i] <= 'Z') || (str[i] >= 'a' && str[i] <= 'z')) { counter++; } } if (counter > 0) { is_correct = false; std::cout << "Wrong input!\n"; } else { is_correct = true; } } while (!is_correct); std::istringstream iss(str); int digit; while (iss >> digit) { this->Insert(digit); } } AVLTree::~AVLTree() { } AVLTree* AVLTree::GetTree() { if (ptr_tree_ == nullptr) { ptr_tree_ = new AVLTree(); } return ptr_tree_; } void AVLTree::DeleteTree() { delete ptr_tree_; ptr_tree_ = nullptr; } // Demonstation void AVLTree::PrintTree(std::shared_ptr<Node> node, int tab) { int temp = tab; std::string str = ""; while (temp != 0) { str += " "; temp--; } if(node != nullptr) { std::cout << str << node->key_ << '\n'; if (node->left_ != nullptr) { AVLTree::PrintTree(node->left_, tab + 1); } if (node->right_ != nullptr) { AVLTree::PrintTree(node->right_, tab + 1); } } else { std::cout << "Tree is empty!\n"; } } void AVLTree::Demonstration(DemoState state) { int input = 0; if (state == DemoState::InsertDemo) { std::cout << "\nInput key with you want to insert: "; std::cin >> input; this->Insert(input, DemoState::InsertDemo); std::cout << "\n ---< Tree after insert key " << input << " >--- \n\n"; this->PrintTree(this->Front()); } else if (state == DemoState::RemoveDemo) { std::cout << "\nInput key with you want to remove: "; std::cin >> input; this->Remove(input, DemoState::RemoveDemo); std::cout << "\n ---< Tree after remove key " << input << " >--- \n\n"; this->PrintTree(this->Front()); } } /////////////////////////////////////////////////////////////////////// std::shared_ptr<Node> AVLTree::Front() { return this->head_; } std::shared_ptr<Node> AVLTree::Find(int key, DemoState state) { return Node::Find(key, this->head_); } void AVLTree::Remove(int key, DemoState state) { this->head_ = Node::Remove(key, this->head_, state); } void AVLTree::Insert(int key, DemoState state) { this->head_ = Node::Insert(key, this->head_, state); }
[ "a.v.shunaev@gmail.com" ]
a.v.shunaev@gmail.com
4c14c1221980d74c3ae04cdb8243031fa610bf93
470f22152362130ed7efe7bbd17e56dc6e0233ef
/OSMCtrlTimerEventHandler.h
fa53ed26c8a75b6e86f72c546089e1cbea197431
[]
no_license
luke18/EleVehOsm
1e109527f0a3858b39fe29ab8212d5ed6e0b4c3c
3d204fe57d6cf2a9e2d393b4c09d4cd4ece1aaf1
refs/heads/master
2021-01-17T06:26:54.962098
2014-05-23T03:30:28
2014-05-23T03:30:28
14,163,954
1
0
null
null
null
null
UTF-8
C++
false
false
2,059
h
/* Module : OSMCtrlTimerEventHandler.H Purpose: Defines the interface for COSMCtrlTimerEventHandler class Created: PJN / 10-04-2011 Copyright (c) 2011 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) All rights reserved. Copyright / Usage Details: You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) when your product is released in binary form. You are allowed to modify the source code in any way you want except you cannot modify the copyright details at the top of each module. If you want to distribute source code with your application, then you are only allowed to distribute versions released by the author. This is to maintain a single distribution point for the source code. */ ///////////////////////// Macros / Includes /////////////////////////////////// #pragma once #ifndef __OSMCTRLTIMEREVENTHANDLER_H__ #define __OSMCTRLTIMEREVENTHANDLER_H__ ////////////////////////////////// Classes //////////////////////////////////// //Forward declaration class COSMCtrl; #ifndef COSMCTRL_NOANIMATION //The timer event handler class for Windows Animation support class ATL_NO_VTABLE COSMCtrlTimerEventHandler : public ATL::CComObjectRootEx<ATL::CComSingleThreadModel>, public IUIAnimationTimerEventHandler { public: //Constructors / Destructors COSMCtrlTimerEventHandler(); //Methods static HRESULT CreateInstance(ATL::CComObjectNoLock<COSMCtrlTimerEventHandler>** ppTimerEventHandler); BEGIN_COM_MAP(COSMCtrlTimerEventHandler) COM_INTERFACE_ENTRY(IUIAnimationTimerEventHandler) END_COM_MAP() DECLARE_PROTECT_FINAL_CONSTRUCT() DECLARE_NOT_AGGREGATABLE(COSMCtrlTimerEventHandler) //IUIAnimationTimerEventHandler support virtual HRESULT STDMETHODCALLTYPE OnPreUpdate(); virtual HRESULT STDMETHODCALLTYPE OnPostUpdate(); virtual HRESULT STDMETHODCALLTYPE OnRenderingTooSlow(UINT32 framesPerSecond); //Member variables COSMCtrl* m_pOSMCtrl; }; #endif #endif //__OSMCTRLTIMEREVENTHANDLER_H__
[ "s_tao16@sina.com" ]
s_tao16@sina.com
74b43ed2e30e91fe40e7a5b42dd678db5f99e73b
897f04199dff9d69351d8c1ad8290d26f2ec7e67
/include/radical/polynomial_vignetting_model.h
c5be14da0cf56c260a1d1db5847269b0ee2eb613
[ "MIT" ]
permissive
wangchuantong/radical
14f18ac9bda36618595d5de11c2ec2089eff5528
cce899af3b78a339204eab8201e67d8a6cb98b1a
refs/heads/master
2021-09-20T06:21:14.021768
2018-08-05T18:08:44
2018-08-05T18:08:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,850
h
/****************************************************************************** * Copyright (c) 2016 Sergey Alexandrov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. ******************************************************************************/ #pragma once #include <radical/vignetting_model.h> namespace radical { /** This model parameterizes vignetting response using an even order polynomial. * * Specifically, vignetting response at a given image location x is computed as: * \f[ * V(\mathbf{x}) = 1 + \sum_{n=1}^{k}\beta_{n}(\mathbf{x} - \mathbf{c})^{2n}, * \f] * * where c is the center of symmetry of the vignetting response. * Template argument \c Degree is the order of the polynomial divided by two (k from the formula). * Each color channel has its own model coefficients. The number of coefficients per channel is \c Degree + 2. First * two numbers define c, and the remaining are betas. * * \note The implementation is generic and supports polynomials of different degree. However, the model is explicitly * instantiated only with \c Degree = 3. */ template <unsigned int Degree> class PolynomialVignettingModel : public VignettingModel { public: using Ptr = std::shared_ptr<PolynomialVignettingModel<Degree>>; PolynomialVignettingModel(cv::InputArray coefficients, cv::Size image_size); PolynomialVignettingModel(const std::string& filename); virtual std::string getName() const override; virtual void save(const std::string& filename) const override; virtual cv::Vec3f operator()(const cv::Vec2f& p) const override; using VignettingModel::operator(); virtual cv::Size getImageSize() const override; virtual cv::Mat getModelCoefficients() const override; private: cv::Mat coefficients_; cv::Size image_size_; }; } // namespace radical
[ "alexandrov88@gmail.com" ]
alexandrov88@gmail.com
46dfbcd0f42e0a7bd4b7bee501cfc0b06a885b82
1cc631c61d85076c192a6946acb35d804f0620e4
/Source/third_party/boost_1_58_0/libs/math/test/test_ibeta.cpp
9f66c38ebe4c40d689e9cf78e6e86d7c72b10b47
[ "BSL-1.0" ]
permissive
reven86/dreamfarmgdk
f9746e1c0e701f243c7dd2f14394970cc47346d9
4d5c26701bf05e89eef56ddd4553814aa6b0e770
refs/heads/master
2021-01-19T00:58:04.259208
2016-10-04T21:29:28
2016-10-04T21:33:10
906,953
2
5
null
null
null
null
UTF-8
C++
false
false
13,170
cpp
// (C) Copyright John Maddock 2006. // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <pch_light.hpp> #include "test_ibeta.hpp" #if !defined(TEST_FLOAT) && !defined(TEST_DOUBLE) && !defined(TEST_LDOUBLE) && !defined(TEST_REAL_CONCEPT) # define TEST_FLOAT # define TEST_DOUBLE # define TEST_LDOUBLE # define TEST_REAL_CONCEPT #endif // // DESCRIPTION: // ~~~~~~~~~~~~ // // This file tests the incomplete beta functions beta, // betac, ibeta and ibetac. There are two sets of tests, spot // tests which compare our results with selected values computed // using the online special function calculator at // functions.wolfram.com, while the bulk of the accuracy tests // use values generated with NTL::RR at 1000-bit precision // and our generic versions of these functions. // // Note that when this file is first run on a new platform many of // these tests will fail: the default accuracy is 1 epsilon which // is too tight for most platforms. In this situation you will // need to cast a human eye over the error rates reported and make // a judgement as to whether they are acceptable. Either way please // report the results to the Boost mailing list. Acceptable rates of // error are marked up below as a series of regular expressions that // identify the compiler/stdlib/platform/data-type/test-data/test-function // along with the maximum expected peek and RMS mean errors for that // test. // void expected_results() { // // Define the max and mean errors expected for // various compilers and platforms. // const char* largest_type; #ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS if(boost::math::policies::digits<double, boost::math::policies::policy<> >() == boost::math::policies::digits<long double, boost::math::policies::policy<> >()) { largest_type = "(long\\s+)?double"; } else { largest_type = "long double"; } #else largest_type = "(long\\s+)?double"; #endif // // Darwin: just one special case for real_concept: // add_expected_result( "[^|]*", // compiler "[^|]*", // stdlib "Mac OS", // platform "real_concept", // test type(s) "(?i).*large.*", // test data group ".*", 400000, 50000); // test function // // Linux - results depend quite a bit on the // processor type, and how good the std::pow // function is for that processor. // add_expected_result( "[^|]*", // compiler "[^|]*", // stdlib "linux", // platform largest_type, // test type(s) "(?i).*small.*", // test data group ".*", 350, 100); // test function add_expected_result( "[^|]*", // compiler "[^|]*", // stdlib "linux", // platform largest_type, // test type(s) "(?i).*medium.*", // test data group ".*", 300, 80); // test function // // Deficiencies in pow function really kick in here for // large arguments. Note also that the tests here get // *very* extreme due to the increased exponent range // of 80-bit long doubles. Also effect Mac OS. // add_expected_result( "[^|]*", // compiler "[^|]*", // stdlib "linux|Mac OS", // platform largest_type, // test type(s) "(?i).*large.*", // test data group ".*", 200000, 10000); // test function #ifndef BOOST_MATH_NO_REAL_CONCEPT_TESTS add_expected_result( "[^|]*", // compiler "[^|]*", // stdlib "linux|Mac OS|Sun.*", // platform "double", // test type(s) "(?i).*large.*", // test data group ".*", 40, 20); // test function #endif add_expected_result( "[^|]*", // compiler "[^|]*", // stdlib "linux|Mac OS", // platform "real_concept", // test type(s) "(?i).*medium.*", // test data group ".*", 350, 100); // test function // // HP-UX: // // Large value tests include some with *very* extreme // results, thanks to the large exponent range of // 128-bit long doubles. // add_expected_result( "[^|]*", // compiler "[^|]*", // stdlib "HP-UX", // platform largest_type, // test type(s) "(?i).*large.*", // test data group ".*", 200000, 10000); // test function // // Tru64: // add_expected_result( ".*Tru64.*", // compiler ".*", // stdlib ".*", // platform largest_type, // test type(s) "(?i).*large.*", // test data group ".*", 130000, 10000); // test function // // Sun OS: // add_expected_result( "[^|]*", // compiler "[^|]*", // stdlib "Sun.*", // platform largest_type, // test type(s) "(?i).*large.*", // test data group ".*", 130000, 10000); // test function add_expected_result( "[^|]*", // compiler "[^|]*", // stdlib "Sun.*", // platform largest_type, // test type(s) "(?i).*small.*", // test data group ".*", 130, 30); // test function add_expected_result( "[^|]*", // compiler "[^|]*", // stdlib "Sun.*", // platform largest_type, // test type(s) "(?i).*medium.*", // test data group ".*", 200, 40); // test function add_expected_result( "[^|]*", // compiler "[^|]*", // stdlib "Sun.*", // platform "real_concept", // test type(s) "(?i).*medium.*", // test data group ".*", 200, 40); // test function add_expected_result( "[^|]*", // compiler "[^|]*", // stdlib "Sun.*", // platform "real_concept", // test type(s) "(?i).*small.*", // test data group ".*", 130, 30); // test function // // MinGW: // add_expected_result( "GNU[^|]*", // compiler "[^|]*", // stdlib "Win32[^|]*", // platform "real_concept", // test type(s) "(?i).*medium.*", // test data group ".*", 400, 50); // test function add_expected_result( "GNU.*", // compiler ".*", // stdlib "Win32.*", // platform "double", // test type(s) "(?i).*large.*", // test data group ".*", 20, 10); // test function add_expected_result( "GNU.*", // compiler ".*", // stdlib "Win32.*", // platform largest_type, // test type(s) "(?i).*large.*", // test data group ".*", 200000, 10000); // test function #ifdef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS // // No long doubles: // add_expected_result( "[^|]*", // compiler "[^|]*", // stdlib BOOST_PLATFORM, // platform largest_type, // test type(s) "(?i).*large.*", // test data group ".*", 13000, 500); // test function #endif // // Catch all cases come last: // add_expected_result( "[^|]*", // compiler "[^|]*", // stdlib "[^|]*", // platform largest_type, // test type(s) "(?i).*small.*", // test data group ".*", 90, 25); // test function add_expected_result( "[^|]*", // compiler "[^|]*", // stdlib "[^|]*", // platform largest_type, // test type(s) "(?i).*medium.*", // test data group ".*", 350, 50); // test function add_expected_result( "[^|]*", // compiler "[^|]*", // stdlib "[^|]*", // platform largest_type, // test type(s) "(?i).*large.*", // test data group ".*", 5000, 500); // test function add_expected_result( "[^|]*", // compiler "[^|]*", // stdlib "[^|]*", // platform "real_concept", // test type(s) "(?i).*small.*", // test data group ".*", 90, 25); // test function add_expected_result( "[^|]*", // compiler "[^|]*", // stdlib "[^|]*", // platform "real_concept", // test type(s) "(?i).*medium.*", // test data group ".*", 200, 50); // test function add_expected_result( "[^|]*", // compiler "[^|]*", // stdlib "[^|]*", // platform "real_concept", // test type(s) "(?i).*large.*", // test data group ".*", 200000, 50000); // test function // catch all default is 2eps for all types: add_expected_result( "[^|]*", // compiler "[^|]*", // stdlib "[^|]*", // platform "[^|]*", // test type(s) "[^|]*", // test data group ".*", 2, 2); // test function // // Finish off by printing out the compiler/stdlib/platform names, // we do this to make it easier to mark up expected error rates. // std::cout << "Tests run with " << BOOST_COMPILER << ", " << BOOST_STDLIB << ", " << BOOST_PLATFORM << std::endl; } BOOST_AUTO_TEST_CASE( test_main ) { expected_results(); BOOST_MATH_CONTROL_FP; #ifdef TEST_GSL gsl_set_error_handler_off(); #endif #ifdef TEST_FLOAT test_spots(0.0F); #endif #ifdef TEST_DOUBLE test_spots(0.0); #endif #ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS #ifdef TEST_LDOUBLE test_spots(0.0L); #endif #if !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x582)) #ifdef TEST_REAL_CONCEPT test_spots(boost::math::concepts::real_concept(0.1)); #endif #endif #endif #ifdef TEST_FLOAT test_beta(0.1F, "float"); #endif #ifdef TEST_DOUBLE test_beta(0.1, "double"); #endif #ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS #ifdef TEST_LDOUBLE test_beta(0.1L, "long double"); #endif #ifndef BOOST_MATH_NO_REAL_CONCEPT_TESTS #ifdef TEST_REAL_CONCEPT test_beta(boost::math::concepts::real_concept(0.1), "real_concept"); #endif #endif #else std::cout << "<note>The long double tests have been disabled on this platform " "either because the long double overloads of the usual math functions are " "not available at all, or because they are too inaccurate for these tests " "to pass.</note>" << std::cout; #endif }
[ "reven86@gmail.com" ]
reven86@gmail.com
a8f6535d105a1df09f4e3aa2f63715bb702bd0e5
70572481e57934f8f3e345e7ca31b126bf69046e
/Celeste/Include/Registries/ScriptableObjectRegistry.h
705b70e8bf1b3b34f001354ed99b93fd840b5884
[]
no_license
AlanWills/Celeste
9ff00468d753fd320f44022b64eb8efa0a20eb27
b78bf2d3ebc2a68db9b0f2cc41da730d3a23b2f9
refs/heads/master
2021-05-24T04:03:18.927078
2020-07-21T21:30:28
2020-07-21T21:30:28
59,947,731
0
0
null
null
null
null
UTF-8
C++
false
false
3,429
h
#pragma once #include "CelesteDllExport.h" #include "FileSystem/Path.h" #include "tinyxml2.h" #include "Objects/ScriptableObject.h" #include "Reflection/Type.h" #include <functional> #include <unordered_map> namespace Celeste { class CelesteDllExport ScriptableObjectRegistry { public: using CreateFactoryFunction = std::function<std::unique_ptr<ScriptableObject>(const std::string&)>; using LoadFactoryFunction = std::function<std::unique_ptr<ScriptableObject>(const Path&)>; private: using InstantiationMapKey = std::string; using InstantiationMapValue = std::tuple<CreateFactoryFunction, LoadFactoryFunction>; using InstantiationMap = std::unordered_map<InstantiationMapKey, InstantiationMapValue>; using InstantiationMapPair = std::pair<InstantiationMapKey, InstantiationMapValue>; public: ScriptableObjectRegistry() = delete; ScriptableObjectRegistry(const ScriptableObjectRegistry&) = delete; ScriptableObjectRegistry& operator=(const ScriptableObjectRegistry&) = delete; template <typename T> static bool addScriptableObject(); template <typename T> static void removeScriptableObject() { removeScriptableObject(T::type_name()); } template <typename T> static bool hasScriptableObject() { return hasScriptableObject(T::type_name()); } template <typename T> static std::unique_ptr<T> createScriptableObject(const std::string& name) { std::unique_ptr<ScriptableObject> scriptableObject = createScriptableObject(T::type_name(), name); return std::move(std::unique_ptr<T>(static_cast<T*>(scriptableObject.release()))); } template <typename T> static std::unique_ptr<T> loadScriptableObject(const Path& path) { std::unique_ptr<ScriptableObject> scriptableObject = loadScriptableObject(path); return std::move(std::unique_ptr<T>(static_cast<T*>(scriptableObject.release()))); } static std::unique_ptr<ScriptableObject> loadScriptableObject(const Path& path); static void removeScriptableObject(const std::string& objectName) { if (!hasScriptableObject(objectName)) { return; } getInstantiationMap().erase(objectName); } static bool hasScriptableObject(const std::string& objectName) { return !getInstantiationMap().empty() && getInstantiationMap().find(objectName) != getInstantiationMap().end(); } static std::unique_ptr<ScriptableObject> createScriptableObject(const std::string& typeName, const std::string& name) { if (hasScriptableObject(typeName)) { return std::move(std::get<0>(getInstantiationMap()[typeName])(name)); } return std::unique_ptr<ScriptableObject>(); } private: static InstantiationMap& getInstantiationMap(); }; //------------------------------------------------------------------------------------------------ template <typename T> bool ScriptableObjectRegistry::addScriptableObject() { const Reflection::Type<T>& typeInfo = Reflection::Type<T>(); if (!hasScriptableObject(typeInfo.getName())) { getInstantiationMap().emplace(typeInfo.getName(), std::make_pair( &ScriptableObject::create<T>, &ScriptableObject::load<T>)); return true; } ASSERT_FAIL(); return false; } }
[ "alawills@googlemail.com" ]
alawills@googlemail.com
8cd9b03fd2a03ef25072903311e8e85632bce350
6e26cc31306e0885a8d174805b9ccd380e1879ac
/tests/src/PassingCarTests.cpp
4195cbd105d84fb4df3a185c0b791aa987417568
[]
no_license
FreekDS/ProjectGP
e6e1379c51fa57d61604a1e6d389991d290158ce
4050764d70902011a0167d850742dd7484a755bd
refs/heads/master
2021-10-11T00:50:48.637902
2019-01-20T11:03:00
2019-01-20T11:03:00
157,843,495
0
0
null
null
null
null
UTF-8
C++
false
false
2,611
cpp
#include <PassingCarTests.h> #include <TestClasses.h> #include <GLL/Transformation.h> using namespace RoadFighter; /** * Tests the constructor of the PassingCar. */ TEST_F(PassingCarTests, Constructor) { shared_ptr<Player> player = make_shared<PlayerTest>(); shared_ptr<World> world = make_shared<WorldTest>(); PassingCarTest p_car(player, world); EXPECT_FALSE(p_car.canBeDestroyed()); EXPECT_EQ(p_car.getType(), EntityType::PASSING_CAR); EXPECT_TRUE(p_car.getMovespeed(1) > 3 && p_car.getMovespeed(1) < 8); } /** * Tests the update function of the passing car. */ TEST_F(PassingCarTests, update) { shared_ptr<Player> player = make_shared<PlayerTest>(); shared_ptr<World> world = make_shared<WorldTest>(); PassingCarTest p_car(player, world); double yPos = p_car.getPos().y; p_car.update(); EXPECT_TRUE(p_car.getPos().y < yPos); p_car.crash(); p_car.update(); EXPECT_EQ(p_car.getMovespeed(1), 0); } /** * Tests the canBeDestroyed function of the PassingCar. */ TEST_F(PassingCarTests, canBeDestroyed) { shared_ptr<Player> player = make_shared<PlayerTest>(); shared_ptr<World> world = make_shared<WorldTest>(); PassingCarTest p_car(player, world); auto trans = Transformation::getInstance(); EXPECT_FALSE(p_car.canBeDestroyed()); p_car.setPos(0, 2*trans->getYRange().first); EXPECT_FALSE(p_car.canBeDestroyed()); p_car.setPos(0, 2*trans->getYRange().first-0.00001); EXPECT_TRUE(p_car.canBeDestroyed()); } /** * Tests the moveDown function of the Passing Car */ TEST_F(PassingCarTests, moveDown) { shared_ptr<Player> player = make_shared<PlayerTest>(); shared_ptr<World> world = make_shared<WorldTest>(); PassingCarTest p_car(player, world); double yPos = p_car.getPos().y; p_car.moveDown(); EXPECT_TRUE(p_car.getPos().y < yPos); } /** * Tests the initializePosition function of the PassingCar. */ TEST_F(PassingCarTests, initializePosition) { shared_ptr<Player> player = make_shared<PlayerTest>(); shared_ptr<World> world = make_shared<WorldTest>(); PassingCarTest p_car(player, world); auto trans = Transformation::getInstance(); p_car.initializePosition(); EXPECT_EQ(p_car.getPos().y, trans->getYRange().second+p_car.getWidth()); // as initializePos uses random values, we test this 1000 times for(int i = 0; i<1000; i++){ p_car.initializePosition(); ASSERT_TRUE(p_car.getPos().x > world->getLeftBoundary() + p_car.getWidth()/2); ASSERT_TRUE(p_car.getPos().x < world->getRightBoundary() - p_car.getWidth()/2); } }
[ "freek.de.sagher21@gmail.com" ]
freek.de.sagher21@gmail.com
0f965898876a9f6efb98541143c19e20e20f573c
472d7820a5f5d9d5ab2ec150eab0c9bdeb2008c7
/Sodi/odisim/incV60/int_bus.H
e9cf1465b3978fbb46493d31d6fcab01459c3d62
[]
no_license
slacker247/GPDA
1ad5ebe0bea4528d9a3472d3c34580648ffb670e
fa9006d0877a691f1ddffe88799c844a3e8a669a
refs/heads/master
2022-10-08T07:39:09.786313
2020-06-10T22:22:58
2020-06-10T22:22:58
105,063,261
2
0
null
null
null
null
UTF-8
C++
false
false
1,629
h
// int_bus.H header file #ifndef intbus_object #define intbus_object #include <math.h> #include "base_space.H" #include "spline6.H" #define NSPIBUS 3 /************************************************************************ * int_bus object * ************************************************************************/ class C_INT_BUS : public C_BASE_SPACE { private: double resolution; // resolution for integration double maxstep; // maximum time step double V0[3]; // velocity at the start of the bus double Vend[3]; // velocity at impact C_SPLINE6 splines[NSPIBUS]; // array of splines for bus int nsplines; // number of splines for bus double tspline[NSPIBUS]; // time per spline double massrocket; // mass of the rocket int nrvs; // number of rvs protected: public: C_INT_BUS(); void set_resolution(double rs) {resolution = rs;} void set_maxstep(double ms) {maxstep = ms;} void set_massrocket(double mr) {massrocket = mr;} double get_massrocket(double ) {return massrocket;} void integrate(); void init_values(); void update_impact() {;} //...... virtual functions virtual void check_spline6(); virtual void get_pos_vel(double t, double rt[3], double vt[3]); virtual int get_n_splines() {return nsplines;} virtual C_SPLINE6 *get_splines() {return splines;} virtual void create_rvs(int n) {nrvs = n;} virtual void init(double r[3], double v[3]); virtual double get_timp() {return Tend;} virtual double *get_imp_pos() {return Rend;} virtual double *get_imp_vel() {return Vend;} }; #endif
[ "jeffmac710@gmail.com" ]
jeffmac710@gmail.com
01b2f2b98c39f8ac771f3c75656090ebf2c9dba9
079a2e1d756d11a355d9e915013d2660a1f28968
/Hazel/src/Hazel/Scene/Components.h
7bab075e76c41ab4887aa0c4a8354b8b2999e9f2
[ "Apache-2.0" ]
permissive
marshal-it/Hazel
fd84f1a37b939ba462a8659cf098c1f2b3d56e95
f28eb557593ef782a9ea1e61fa8c5f53a4b25e4a
refs/heads/master
2022-11-22T18:35:44.781007
2020-07-25T07:55:44
2020-07-25T07:55:44
279,866,369
0
0
Apache-2.0
2020-07-25T07:55:46
2020-07-15T12:46:46
null
UTF-8
C++
false
false
849
h
#pragma once #include <glm/glm.hpp> namespace Hazel { struct TagComponent { std::string Tag; TagComponent() = default; TagComponent(const TagComponent&) = default; TagComponent(const std::string& tag) : Tag(tag) {} }; struct TransformComponent { glm::mat4 Transform{ 1.0f }; TransformComponent() = default; TransformComponent(const TransformComponent&) = default; TransformComponent(const glm::mat4 & transform) : Transform(transform) {} operator glm::mat4& () { return Transform; } operator const glm::mat4& () const { return Transform; } }; struct SpriteRendererComponent { glm::vec4 Color{ 1.0f, 1.0f, 1.0f, 1.0f }; SpriteRendererComponent() = default; SpriteRendererComponent(const SpriteRendererComponent&) = default; SpriteRendererComponent(const glm::vec4& color) : Color(color) {} }; }
[ "y@nchernikov.com" ]
y@nchernikov.com
e802ddeb4453510ed16b3fd02897339ea78c680b
3326db8648ecd23fabebbdece3a0db662b409664
/Code Jam/2018/Round 2/temp.cpp
4181c379bd4eabaf3e851698f16a7c1969709634
[]
no_license
fazlerahmanejazi/Competitive-Programming
96b9e934a72a978a9cae69ae50dd02ee84b6ca87
796021cdc7196d84976ee7c9e565c9e7feefce09
refs/heads/master
2021-11-10T08:23:31.128762
2019-12-24T22:11:12
2019-12-24T22:11:12
117,171,389
3
1
null
2021-10-30T20:31:10
2018-01-12T00:39:16
C++
UTF-8
C++
false
false
1,606
cpp
#include <bits/stdc++.h> using namespace std ; #define inf 0x3f3f3f3f #define INF 1000111000111000111LL #define mod 1000000007 #define pi acos(-1.0) #define eps 1e-8 #define endl '\n' #define mp make_pair #define mt make_tuple #define pb push_back #define fi first #define se second #define all(cc) (cc).begin(),(cc).end() using lli = long long int ; using pii = pair<int, int> ; using vi = vector<int> ; using vb = vector<bool> ; using vvi = vector<vector<int>> ; using vlli = vector<long long int> ; using vpii = vector<pair<int, int>> ; int main() { ios_base::sync_with_stdio (false) ; cin.tie(0) ; cout.tie(0) ; int T ; cin>> T ; for(int tc=1 ; tc<=T ; tc++) { lli r, b, ans=0, curr, x, y, extra, X, Y ; cin>> r >> b ; for(lli i=0 ; i<=sqrt(r)+10 ; i++) for(lli j=0 ; j<=sqrt(b)+10 ; j++) { x=((i*(i+1))/2)*(j+1) ; y=((j*(j+1))/2)*(i+1) ; if(x<=r && y<=b) { x=r-x ; y=b-y ; extra=0 ; curr=(i+1)*(j+1)-1 ; for(lli k=0 ; k<=i+1 ; k++) for(lli l=0 ; l<=j+1 ; l++) { if(k==i+1 && l==j+1) continue ; X=((j+1)*k)+((l-1)*l)/2 ; Y=((i+1)*l)+((k-1)*k)/2 ; if(X<=y && Y<=x) extra=k+l ; } ans=max(ans, curr+extra) ; } } cout<< "Case #" << tc << ": " << ans << endl ; } }
[ "ahmed.belal98@gmail.com" ]
ahmed.belal98@gmail.com
d569bd9379e3fe0012777ab80f0225c165ff1dda
f966f69ba37033e4a320c5534a8175a9a831ef4b
/hybridge/core/HGESurrogate.cpp
6713800b02338f9b2c83b189aeaa15eb581f97d4
[ "MIT" ]
permissive
jcmoore/ggframework
8281091b189a37dcc8b6d17a91a71cd901f7530d
574933e107dedec887adae4dad84ac734f4a5116
refs/heads/master
2016-09-08T02:39:12.194561
2012-12-13T11:47:48
2012-12-13T11:47:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
965
cpp
// // HGESurrogate.cpp // hybridge // // Created by The Narrator on 8/14/12. // Copyright (c) 2012 Starduu. All rights reserved. // #include "core/HGESurrogate.h" NS_HGE_BEGIN HGESurrogate::HGESurrogate() : HGEPreserve() { } HGESurrogate::~HGESurrogate() { } bool HGESurrogate::destroyJSON(JSONValue& json, bool firstResponder) { bool didDestroy = 0; if (firstResponder) { didDestroy = !0; firstResponder = 0; } return didDestroy; } bool HGESurrogate::createJSON(JSONValue& json, bool firstResponder) { bool didCreate = 0; if (json.IsObject()) { if (firstResponder) { JSONValue& substitution = json[JSON_SUBSTITUTION_DECLARATION]; if (!substitution.IsUndefined()) { this->carry(substitution); didCreate = !0; firstResponder = 0; } } } return didCreate; } bool HGESurrogate::enactJSON(JSONValue& task, JSONValue& json, bool firstResponder) { bool didEnact = 0; return didEnact; } NS_HGE_END
[ "starduu@Justin-C-Moores-MacBook-Pro.local" ]
starduu@Justin-C-Moores-MacBook-Pro.local
a1ecec761d21fe795b614af24c8f3a1d932250fa
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/httpd/gumtree/httpd_new_hunk_16.cpp
6be129eff69c6d1d6d024ca13dba42fd52741709
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
512
cpp
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Invalid expression \"%s\" in file %s", expr, r->filename); *was_error = 1; return retval; } } if (current == (struct parse_node *) NULL) { new->left = root; new->left->parent = new; new->parent = (struct parse_node *) NULL; root = new;
[ "993273596@qq.com" ]
993273596@qq.com
68f3b19dffe4001c00d28fa60c1a3ca457985f0c
feea0886aaf6218a3f605bbc4d871a8116e232b0
/LSDFlowInfo.cpp
9c3d1cc83df47d4019144da4f7bb119265651f30
[]
no_license
MNiMORPH/LSDTopoTools_FloodplainTerraceExtraction
4c35aa434f601dce6ef9a21477f67d760ad6fa2d
0d13667f56999cc6d5c7f8d0787a44c4b16337d9
refs/heads/master
2022-05-20T01:55:15.298527
2018-01-05T11:33:40
2018-01-05T11:33:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
268,797
cpp
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // LSDFlowInfo // Land Surface Dynamics FlowInfo // // An object within the University // of Edinburgh Land Surface Dynamics group topographic toolbox // for organizing flow routing under the Fastscape algorithm // (see Braun and Willett, Geomorphology 2013, v180, p 170-179) // // // Developed by: // Simon M. Mudd // Martin D. Hurst // David T. Milodowski // Stuart W.D. Grieve // Declan A. Valters // Fiona Clubb // // Copyright (C) 2013 Simon M. Mudd 2013 // // Developer can be contacted by simon.m.mudd _at_ ed.ac.uk // // Simon Mudd // University of Edinburgh // School of GeoSciences // Drummond Street // Edinburgh, EH8 9XP // Scotland // United Kingdom // // This program is free software; // you can redistribute it and/or modify it under the terms of the // GNU General Public License as published by the Free Software Foundation; // either version 2 of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; // without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // See the GNU General Public License for more details. // // You should have received a copy of the // GNU General Public License along with this program; // if not, write to: // Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, // Boston, MA 02110-1301 // USA // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // LSDFlowInfo.cpp // cpp file for the LSDFlowInfo object // LSD stands for Land Surface Dynamics // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // This object is written by // Simon M. Mudd, University of Edinburgh // David Milodowski, University of Edinburgh // Martin D. Hurst, British Geological Survey // Fiona Clubb, University of Edinburgh // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // Version 0.1.0 21/10/2013 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //----------------------------------------------------------------- //DOCUMENTATION URL: http://www.geos.ed.ac.uk/~s0675405/LSD_Docs/ //----------------------------------------------------------------- #ifndef LSDFlowInfo_CPP #define LSDFlowInfo_CPP #include <iostream> #include <fstream> #include <iomanip> #include <vector> #include <string> #include <cstring> #include <algorithm> #include <math.h> #include "TNT/tnt.h" #include "LSDFlowInfo.hpp" #include "LSDIndexRaster.hpp" #include "LSDStatsTools.hpp" //#include "LSDRaster.hpp" using namespace std; using namespace TNT; //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // Create function, this is empty, you need to include a filename // // SMM 01/06/2012 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= void LSDFlowInfo::create() { //cout << endl << "-------------------------------" << endl; //cout << "I am an empty flow info object. " << endl; //cout << "Did you forget to give me a DEM?" << endl; //cout << endl << "-------------------------------" << endl; //exit(EXIT_FAILURE); } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // Create function, this creates from a pickled file // fname is the name of the pickled flow info file // // SMM 01/06/2012 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- void LSDFlowInfo::create(string fname) { unpickle(fname); } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // This defaults to no flux boundary conditions //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- void LSDFlowInfo::create(LSDRaster& TopoRaster) { vector<string> BoundaryConditions(4, "No Flux"); create(BoundaryConditions, TopoRaster); } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // this function calcualtes the receiver nodes // it returns the receiver vector r_i // it also returns a flow direction array in this ordering: // // 7 0 1 // 6 -1 2 // 5 4 3 // // note this is different from ArcMap flowdirection // int Arc_flowdir; // flow direction in arcmap format // // 32 64 128 // // 16 -- 1 // // 8 4 2 // one can convert nthese indices using the LSDIndexRaster object // note in arc the row index increases down (to the south) // // SMM 01/06/2012 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- void LSDFlowInfo::create(vector<string>& temp_BoundaryConditions, LSDRaster& TopoRaster) { // initialize several data members BoundaryConditions = temp_BoundaryConditions; //cout << "TBC" << endl; NRows = TopoRaster.get_NRows(); //cout << "Rows: " << NRows << endl; NCols = TopoRaster.get_NCols(); //cout << "Cols: " << NCols << endl; XMinimum = TopoRaster.get_XMinimum(); //cout << "Xmin: " << XMinimum << endl; YMinimum = TopoRaster.get_YMinimum(); //cout << "Ymin: " << YMinimum << endl; NoDataValue = int(TopoRaster.get_NoDataValue()); //cout << "NDV: " << NoDataValue << endl; DataResolution = TopoRaster.get_DataResolution(); //cout << "Data resolution: " <<DataResolution << endl; GeoReferencingStrings = TopoRaster.get_GeoReferencingStrings(); //cout << "GRS" << endl; //cout << "1" << endl; // Declare matrices for calculating flow routing float one_ov_root2 = 0.707106781; float target_elev; // a placeholder for the elevation of the potential receiver float slope; float max_slope; // the maximum slope away from a node int max_slope_index; // index into the maximum slope int row, col; // index for the rows and column int receive_row,receive_col; string::iterator string_iterator; // used to get characters from string // we need logic for all of the boundaries. // there are 3 kinds of edge boundaries: // no flux // base level // periodic // These are denoted in a vector of strings. // the vector has four elements // North boundary, East boundary, South bondary and West boundary // the strings can be any length, as long as the first letter corresponds to the // first letter of the boundary condition. It is not case sensitive. // go through the boundaries // A NOTE ON CARDINAL DIRECTIONS // If one looks at the raster data, the top row in the data corresponds to the NORTH boundary // This is the row that is first read into the code // so row 0 is the NORTH boundary // row NRows-1 is the SOUTH boundary // column 0 is the WEST boundary // column NCols-1 is the EAST boundary vector<float> slopes(8,NoDataValue); vector<int> row_kernal(8); vector<int> col_kernal(8); int ndv = NoDataValue; NDataNodes = 0; // the number of nodes in the raster that have data int one_if_a_baselevel_node; // this is a switch used to tag baseleve nodes // the first thing you need to do is construct a topoglogy matrix // the donor, receiver, etc lists are as long as the number of nodes. // these are made of vectors that are exactly dimension n, which is the number of nodes with // data. Each of these nodes has several index vectors, that point the program to where the node is // we construct these index vectors first // we need to loop through all the data before we calcualte slopes because the // receiver node indices must be known before the slope calculations are run vector<int> empty_vec; RowIndex = empty_vec; ColIndex = empty_vec; BaseLevelNodeList = empty_vec; ReceiverVector = empty_vec; Array2D<int> ndv_raster(NRows,NCols,ndv); NodeIndex = ndv_raster.copy(); FlowDirection = ndv_raster.copy(); FlowLengthCode = ndv_raster.copy(); //cout << "2" << endl; // loop through the topo data finding places where there is actually data for (row = 0; row<NRows; row++) { for (col = 0; col<NCols; col++) { // only do calcualtions if there is data if(TopoRaster.RasterData[row][col] != NoDataValue) { RowIndex.push_back(row); ColIndex.push_back(col); NodeIndex[row][col] = NDataNodes; NDataNodes++; } } } //cout << "3" << endl; // now the row and col index are populated by the row and col of the node in row i // and the node index has the indeces into the row and col vectors // next up, make d, delta, and D vectors vector<int> ndn_vec(NDataNodes,0); vector<int> ndn_nodata_vec(NDataNodes,ndv); vector<int> ndn_plusone_vec(NDataNodes+1,0); vector<int> w_vector(NDataNodes,0); NDonorsVector = ndn_vec; DonorStackVector = ndn_vec; DeltaVector = ndn_plusone_vec; SVector = ndn_nodata_vec; BLBasinVector = ndn_nodata_vec; // this vector starts out empty and then base level nodes are added to it for (row = 0; row<NRows; row++) { for (col = 0; col<NCols; col++) { // only do calcualtions if there is data if(TopoRaster.RasterData[row][col] != NoDataValue) { // calcualte 8 slopes // no slopes mean get NoDataValue entries // the algorithm loops through the neighbors to the cells, collecting // receiver indices. The order is // 7 0 1 // 6 - 2 // 5 4 3 // where the above directions are cardinal directions // do slope 0 row_kernal[0] = row-1; row_kernal[1] = row-1; row_kernal[2] = row; row_kernal[3] = row+1; row_kernal[4] = row+1; row_kernal[5] = row+1; row_kernal[6] = row; row_kernal[7] = row-1; col_kernal[0] = col; col_kernal[1] = col+1; col_kernal[2] = col+1; col_kernal[3] = col+1; col_kernal[4] = col; col_kernal[5] = col-1; col_kernal[6] = col-1; col_kernal[7] = col-1; // check for periodic boundary conditions if( BoundaryConditions[0].find("P") == 0 || BoundaryConditions[0].find("p") == 0 ) { if( BoundaryConditions[2].find("P") != 0 && BoundaryConditions[2].find("p") != 0 ) { cout << "WARNING!!! North boundary is periodic! Changing South boundary to periodic" << endl; BoundaryConditions[2] = "P"; } } if( BoundaryConditions[1].find("P") == 0 || BoundaryConditions[1].find("p") == 0 ) { if( BoundaryConditions[3].find("P") != 0 && BoundaryConditions[3].find("p") != 0 ) { cout << "WARNING!!! East boundary is periodic! Changing West boundary to periodic" << endl; BoundaryConditions[3] = "P"; } } if( BoundaryConditions[2].find("P") == 0 || BoundaryConditions[2].find("p") == 0 ) { if( BoundaryConditions[0].find("P") != 0 && BoundaryConditions[0].find("p") != 0 ) { cout << "WARNING!!! South boundary is periodic! Changing North boundary to periodic" << endl; BoundaryConditions[0] = "P"; } } if( BoundaryConditions[3].find("P") == 0 || BoundaryConditions[3].find("p") == 0 ) { if( BoundaryConditions[1].find("P") != 0 && BoundaryConditions[1].find("p") != 0 ) { cout << "WARNING!!! West boundary is periodic! Changing East boundary to periodic" << endl; BoundaryConditions[1] = "P"; } } // reset baselevel switch for boundaries one_if_a_baselevel_node = 0; // NORTH BOUNDARY if (row == 0) { if( BoundaryConditions[0].find("B") == 0 || BoundaryConditions[0].find("b") == 0 ) { one_if_a_baselevel_node = 1; } else { // if periodic, reflect across to south boundary if( BoundaryConditions[0].find("P") == 0 || BoundaryConditions[0].find("p") == 0 ) { row_kernal[0] = NRows-1; row_kernal[1] = NRows-1; row_kernal[7] = NRows-1; } else { row_kernal[0] = ndv; row_kernal[1] = ndv; row_kernal[7] = ndv; } } } // EAST BOUNDAY if (col == NCols-1) { if( BoundaryConditions[1].find("B") == 0 || BoundaryConditions[1].find("b") == 0 ) { one_if_a_baselevel_node = 1; } else { if( BoundaryConditions[1].find("P") == 0 || BoundaryConditions[1].find("p") == 0) { col_kernal[1] = 0; col_kernal[2] = 0; col_kernal[3] = 0; } else { col_kernal[1] = ndv; col_kernal[2] = ndv; col_kernal[3] = ndv; } } } // SOUTH BOUNDARY if (row == NRows-1) { if( BoundaryConditions[2].find("B") == 0 || BoundaryConditions[2].find("b") == 0 ) { one_if_a_baselevel_node = 1; } else { if( BoundaryConditions[2].find("P") == 0 || BoundaryConditions[2].find("p") == 0) { row_kernal[3] = 0; row_kernal[4] = 0; row_kernal[5] = 0; } else { row_kernal[3] = ndv; row_kernal[4] = ndv; row_kernal[5] = ndv; } } } // WEST BOUNDARY if (col == 0) { if( BoundaryConditions[3].find("B") == 0 || BoundaryConditions[3].find("b") == 0 ) { one_if_a_baselevel_node = 1; } else { if( BoundaryConditions[3].find("P") == 0 || BoundaryConditions[3].find("p") == 0) { col_kernal[5] = NCols-1; col_kernal[6] = NCols-1; col_kernal[7] = NCols-1; } else { col_kernal[5] = ndv; col_kernal[6] = ndv; col_kernal[7] = ndv; } } } // now loop through the surrounding nodes, calculating the slopes // slopes with NoData get NoData slopes // reminder of ordering: // 7 0 1 // 6 - 2 // 5 4 3 // first logic for baselevel node if (one_if_a_baselevel_node == 1) { // get reciever index FlowDirection[row][col] = -1; ReceiverVector.push_back(NodeIndex[row][col]); FlowLengthCode[row][col] = 0; } // now the rest of the nodes else { FlowLengthCode[row][col] = 0; // set flow length code to 0, this gets reset // if there is a maximum slope max_slope = 0; max_slope_index = -1; receive_row = row; receive_col = col; for (int slope_iter = 0; slope_iter<8; slope_iter++) { if (row_kernal[slope_iter] == ndv || col_kernal[slope_iter] == ndv) { slopes[slope_iter] = NoDataValue; } else { target_elev = TopoRaster.RasterData[ row_kernal[slope_iter] ][ col_kernal[slope_iter] ]; if(target_elev == NoDataValue) { slopes[slope_iter] = NoDataValue; } else { if(slope_iter%2 == 0) { //cout << "LINE 988, cardinal direction, slope iter = " << slope_iter << endl; slope = TopoRaster.RasterData[row][col]-target_elev; } else { slope = one_ov_root2*(TopoRaster.RasterData[row][col]-target_elev); } if (slope > max_slope) { max_slope_index = slope_iter; receive_row = row_kernal[slope_iter]; receive_col = col_kernal[slope_iter]; max_slope = slope; if(slope_iter%2 == 0) { FlowLengthCode[row][col] = 1; } else { FlowLengthCode[row][col] = 2; } } } } } // get reciever index FlowDirection[row][col] = max_slope_index; ReceiverVector.push_back(NodeIndex[receive_row][receive_col]); } // end if baselevel boundary conditional // if the node is a base level node, add it to the base level node list if (FlowLengthCode[row][col] == 0) { BaseLevelNodeList.push_back(NodeIndex[row][col]); } } // end if there is data conditional } // end col loop } // end row loop // first create the number of donors vector // from braun and willett eq. 5 for(int i = 0; i<NDataNodes; i++) { NDonorsVector[ ReceiverVector[i] ]++; } // now create the delta vector // this starts on the last element and works its way backwards // from Braun and Willett eq 7 and 8 DeltaVector[NDataNodes] = NDataNodes; for(int i = NDataNodes; i>0; i--) { DeltaVector[i-1] = DeltaVector[i] - NDonorsVector[i-1]; } // now the DonorStack and the r vectors. These come from Braun and Willett // equation 9. // Note that in the manscript I have there is a typo in eqaution 9 // (Jean Braun's code is correct) // it should be w_{r_i} = w_{r_i}+1 int r_index; int w_index; int delta_index; for (int i = 0; i<NDataNodes; i++) { r_index = ReceiverVector[i]; delta_index = DeltaVector[ r_index ]; w_index = w_vector[ r_index ]; DonorStackVector[ delta_index+w_index ] = i; w_vector[r_index] += 1; //cout << "i: " << i << " r_i: " << r_index << " delta_i: " << delta_index << " w_index: " << w_index << endl; } // now go through the base level node list, building the drainage tree for each of these nodes as one goes along int n_base_level_nodes; n_base_level_nodes = BaseLevelNodeList.size(); int k; int j_index; int begin_delta_index, end_delta_index; int l_index; j_index = 0; for (int i = 0; i<n_base_level_nodes; i++) { k = BaseLevelNodeList[i]; // set k to the base level node // This doesn't seem to be in Braun and Willet but to get the ordering correct you // need to make sure that the base level node appears first in the donorstack // of nodes contributing to the baselevel node. // For example, if base level node is 4, with 4 donors // and the donor stack has 3 4 8 9 // the code has to put the 4 first. if (DonorStackVector[ DeltaVector[k] ] != k) { int this_index = DonorStackVector[ DeltaVector[k] ]; int bs_node = k; for(int ds_node = 1; ds_node < NDonorsVector[k]; ds_node++) { if( DonorStackVector[ DeltaVector[k] + ds_node ] == bs_node ) { DonorStackVector[ DeltaVector[k] ] = k; DonorStackVector[ DeltaVector[k] + ds_node ] = this_index; } } } // now run recursive algorithm begin_delta_index = DeltaVector[k]; end_delta_index = DeltaVector[k+1]; //cout << "base_level_node is: " << k << " begin_index: " << begin_delta_index << " end: " << end_delta_index << endl; for (int delta_index = begin_delta_index; delta_index<end_delta_index; delta_index++) { l_index = DonorStackVector[delta_index]; add_to_stack(l_index, j_index, k); } } // now calcualte the indices calculate_upslope_reference_indices(); } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // // This function returns the x and y location of a row and column // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- void LSDFlowInfo::get_x_and_y_locations(int row, int col, double& x_loc, double& y_loc) { x_loc = XMinimum + float(col)*DataResolution + 0.5*DataResolution; // Slightly different logic for y because the DEM starts from the top corner y_loc = YMinimum + float(NRows-row)*DataResolution - 0.5*DataResolution; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // // This function returns the x and y location of a row and column // Same as above but with floats // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- void LSDFlowInfo::get_x_and_y_locations(int row, int col, float& x_loc, float& y_loc) { x_loc = XMinimum + float(col)*DataResolution + 0.5*DataResolution; // Slightly different logic for y because the DEM starts from the top corner y_loc = YMinimum + float(NRows-row)*DataResolution - 0.5*DataResolution; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // // Function to convert a node position with a row and column to a lat // and long coordinate // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- void LSDFlowInfo::get_lat_and_long_locations(int row, int col, double& lat, double& longitude, LSDCoordinateConverterLLandUTM Converter) { // get the x and y locations of the node double x_loc,y_loc; get_x_and_y_locations(row, col, x_loc, y_loc); // get the UTM zone of the node int UTM_zone; bool is_North; get_UTM_information(UTM_zone, is_North); //cout << endl << endl << "Line 1034, UTM zone is: " << UTM_zone << endl; if(UTM_zone == NoDataValue) { lat = NoDataValue; longitude = NoDataValue; } else { // set the default ellipsoid to WGS84 int eId = 22; double xld = double(x_loc); double yld = double(y_loc); // use the converter to convert to lat and long double Lat,Long; Converter.UTMtoLL(eId, yld, xld, UTM_zone, is_North, Lat, Long); lat = Lat; longitude = Long; } } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // // This function gets the UTM zone // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- void LSDFlowInfo::get_UTM_information(int& UTM_zone, bool& is_North) { // set up strings and iterators map<string,string>::iterator iter; //check to see if there is already a map info string string mi_key = "ENVI_map_info"; iter = GeoReferencingStrings.find(mi_key); if (iter != GeoReferencingStrings.end() ) { string info_str = GeoReferencingStrings[mi_key] ; // now parse the string vector<string> mapinfo_strings; istringstream iss(info_str); while( iss.good() ) { string substr; getline( iss, substr, ',' ); mapinfo_strings.push_back( substr ); } UTM_zone = atoi(mapinfo_strings[7].c_str()); //cout << "Line 1041, UTM zone: " << UTM_zone << endl; //cout << "LINE 1042 LSDRaster, N or S: " << mapinfo_strings[7] << endl; // find if the zone is in the north string n_str = "n"; string N_str = "N"; is_North = false; size_t found = mapinfo_strings[8].find(N_str); if (found!=std::string::npos) { is_North = true; } found = mapinfo_strings[8].find(n_str); if (found!=std::string::npos) { is_North = true; } //cout << "is_North is: " << is_North << endl; } else { UTM_zone = NoDataValue; is_North = false; } } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // // Checks to see is a point is in the raster // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- bool LSDFlowInfo::check_if_point_is_in_raster(float X_coordinate, float Y_coordinate) { bool is_in_raster = true; // Shift origin to that of dataset float X_coordinate_shifted_origin = X_coordinate - XMinimum - DataResolution*0.5; float Y_coordinate_shifted_origin = Y_coordinate - YMinimum - DataResolution*0.5; // Get row and column of point int col_point = int(X_coordinate_shifted_origin/DataResolution); int row_point = (NRows - 1) - int(round(Y_coordinate_shifted_origin/DataResolution)); if(col_point < 0 || col_point > NCols-1 || row_point < 0 || row_point > NRows -1) { is_in_raster = false; } return is_in_raster; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // algorithms for searching the vectors // This gets the reciever of current_node (its node, row, and column) // // SMM 01/06/2012 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= void LSDFlowInfo::retrieve_receiver_information(int current_node, int& receiver_node, int& receiver_row, int& receiver_col) { int rn, rr, rc; rn = ReceiverVector[current_node]; rr = RowIndex[rn]; rc = ColIndex[rn]; receiver_node = rn; receiver_row = rr; receiver_col = rc; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // algorithms for searching the vectors // This gets the row and column of the current node // // SMM 01/06/2012 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= void LSDFlowInfo::retrieve_current_row_and_col(int current_node,int& curr_row, int& curr_col) { int cr, cc; cr = RowIndex[current_node]; cc = ColIndex[current_node]; curr_row = cr; curr_col = cc; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // algorithms for searching the vectors // This gets the X and Y coordinates of the current node // // BG 20/02/2017 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= void LSDFlowInfo::get_x_and_y_from_current_node(int current_node, float& current_X, float& current_Y) { int cr,cc; retrieve_current_row_and_col(current_node, cr,cc); get_x_and_y_locations(cr, cc, current_X, current_Y); } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // algorithms for searching the vectors // This gets the row and column of the current node // // SMM 01/06/2012 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= void LSDFlowInfo::print_vector_of_nodeindices_to_csv_file(vector<int>& nodeindex_vec, string outfilename) { // fid the last '.' in the filename to use in the scv filename unsigned dot = outfilename.find_last_of("."); string prefix = outfilename.substr(0,dot); //string suffix = str.substr(dot); string insert = "_nodeindices_for_Arc.csv"; string outfname = prefix+insert; cout << "the Arc filename is: " << outfname << endl; int n_nodes = nodeindex_vec.size(); int n_nodeindeces = RowIndex.size(); // open the outfile ofstream csv_out; csv_out.open(outfname.c_str()); csv_out.precision(8); csv_out << "x,y,node,row,col" << endl; int current_row, current_col; float x,y; // loop through node indices in vector for (int i = 0; i<n_nodes; i++) { int current_node = nodeindex_vec[i]; // make sure the nodeindex isn't out of bounds if (current_node < n_nodeindeces) { // get the row and column retrieve_current_row_and_col(current_node,current_row, current_col); // get the x and y location of the node // the last 0.0001*DataResolution is to make sure there are no integer data points x = XMinimum + float(current_col)*DataResolution + 0.5*DataResolution + 0.0001*DataResolution; // the last 0.0001*DataResolution is to make sure there are no integer data points // y coord a bit different since the DEM starts from the top corner y = YMinimum + float(NRows-current_row)*DataResolution - 0.5*DataResolution + 0.0001*DataResolution;; csv_out << x << "," << y << "," << current_node << "," << current_row << "," << current_col << endl; } } csv_out.close(); } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // This function takes a list of junctions and prints them to a csv file //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= void LSDFlowInfo::print_vector_of_nodeindices_to_csv_file_with_latlong(vector<int>& nodeindex_vec, string outfilename) { int n_nodes = (nodeindex_vec.size()); int this_node; int row,col; double x_loc,y_loc; double latitude,longitude; // open the outfile ofstream sources_out; sources_out.open(outfilename.c_str()); sources_out.precision(9); sources_out << "node,x,y,latitude,longitude" << endl; // this is for latitude and longitude LSDCoordinateConverterLLandUTM Converter; for (int i = 0; i<n_nodes; i++) { this_node = nodeindex_vec[i]; // get the row and column retrieve_current_row_and_col(this_node,row,col); // get the x and y locations get_x_and_y_locations(row, col, x_loc, y_loc); // get the lat and long locations get_lat_and_long_locations(row, col, latitude, longitude, Converter); // print to file sources_out << this_node << "," << x_loc << "," << y_loc << "," << latitude << "," << longitude << endl; } sources_out.close(); } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // Write nodeindex vector to csv file, and give each row a unique ID // // SWDG after SMM 2/2/2016 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= void LSDFlowInfo::print_vector_of_nodeindices_to_csv_file_Unique(vector<int>& nodeindex_vec, string outfilename) { // fid the last '.' in the filename to use in the scv filename unsigned dot = outfilename.find_last_of("."); string prefix = outfilename.substr(0,dot); //string suffix = str.substr(dot); string insert = "_nodeindices_for_Arc.csv"; string outfname = prefix+insert; cout << "the Arc filename is: " << outfname << endl; int n_nodes = nodeindex_vec.size(); int n_nodeindeces = RowIndex.size(); // open the outfile ofstream csv_out; csv_out.open(outfname.c_str()); csv_out.precision(8); csv_out << "x,y,node,row,col,unique_ID" << endl; int current_row, current_col; float x,y; // loop through node indices in vector for (int i = 0; i<n_nodes; i++) { int current_node = nodeindex_vec[i]; // make sure the nodeindex isn't out of bounds if (current_node < n_nodeindeces) { // get the row and column retrieve_current_row_and_col(current_node,current_row, current_col); // get the x and y location of the node // the last 0.0001*DataResolution is to make sure there are no integer data points x = XMinimum + float(current_col)*DataResolution + 0.5*DataResolution + 0.0001*DataResolution; // the last 0.0001*DataResolution is to make sure there are no integer data points // y coord a bit different since the DEM starts from the top corner y = YMinimum + float(NRows-current_row)*DataResolution - 0.5*DataResolution + 0.0001*DataResolution;; csv_out << x << "," << y << "," << current_node << "," << current_row << "," << current_col << "," << i << endl; } } csv_out.close(); } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // this function returns the base level node with the greatest drainage area // // SMM 01/06/2012 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= int LSDFlowInfo::retrieve_largest_base_level() { int n_bl = BaseLevelNodeList.size(); // get the number of baselevel nodes int max_bl = 0; for (int i = 0; i<n_bl; i++) { if(NContributingNodes[ BaseLevelNodeList[i] ] > max_bl) { max_bl = NContributingNodes[ BaseLevelNodeList[i] ]; } } return max_bl; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // this function returns the base level node with the greatest drainage area // // SMM 01/06/2012 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= int LSDFlowInfo::retrieve_base_level_node(int node) { int CurrentNode = node; int ReceiverNode, ReceiverRow, ReceiverCol; // set initial ReceiverNode so that you can enter while loop retrieve_receiver_information(CurrentNode, ReceiverNode, ReceiverRow, ReceiverCol); // now follow the nodes down to the receiver. while(ReceiverNode != CurrentNode) { CurrentNode = ReceiverNode; retrieve_receiver_information(CurrentNode, ReceiverNode, ReceiverRow, ReceiverCol); } return ReceiverNode; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // Get the node for a cell at a given row and column //@author DTM //@date 08/11/2013 //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- int LSDFlowInfo::retrieve_node_from_row_and_column(int row, int column) { int Node = NodeIndex[row][column]; return Node; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // gets a vector of all the donors to a given node // @author SMM // @date 19/09/2014 //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- vector<int> LSDFlowInfo::retrieve_donors_to_node(int current_node) { // get the numver of donors int NDonors = NDonorsVector[current_node]; // create the vecotr of donating nodes vector<int> donorvec(NDonors,NoDataValue); // loop over the donating nodes, getting their nodeindicies for(int dnode = 0; dnode<NDonors; dnode++) { donorvec[dnode] = DonorStackVector[ DeltaVector[current_node]+dnode]; } return donorvec; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // get the drainage area of a node in km^2 // FJC 06/02/17 //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- float LSDFlowInfo::get_DrainageArea_square_km(int this_node) { int NContributingPixels = NContributingNodes[this_node]; float DrainageArea = NContributingPixels*DataResolution*DataResolution; float DrainageAreaKm = DrainageArea/1000000; return DrainageAreaKm; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // recursive add_to_stack routine, from Braun and Willett eq. 12 and 13 // // SMM 01/06/2012 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- void LSDFlowInfo::add_to_stack(int lm_index, int& j_index, int bl_node) { //cout << "j_index: " << j_index << " and s_vec: " << lm_index << endl; SVector[j_index] = lm_index; BLBasinVector[j_index] = bl_node; j_index++; int begin_m,end_m; int l_index; // if donating to itself, need escape hatch if ( lm_index == bl_node) { begin_m = 0; end_m = 0; } else { begin_m = DeltaVector[lm_index]; end_m = DeltaVector[ lm_index+1]; } //cout << "lm_index: " << lm_index << " begin_m: " << begin_m << " end m: " << end_m << endl; for( int m_index = begin_m; m_index<end_m; m_index++) { //cout << "recursion, begin_m: " << begin_m << " and end_m: " << end_m << endl; l_index = DonorStackVector[m_index]; add_to_stack(l_index, j_index, bl_node); } } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // this function pickles the data from the flowInfo object into a binary format // which can be read by the unpickle function later // the filename DOES NOT include and extension: this is added by the // function // // WARNING: These files are HUGE and testing indicates they don't save much time // // SMM 01/06/2012 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= void LSDFlowInfo::pickle(string filename) { string ext = ".FIpickle"; string hdr_ext = ".FIpickle.hdr"; string hdr_fname = filename+hdr_ext; string data_fname = filename+ext; ofstream header_out; header_out.open(hdr_fname.c_str()); int contributing_nodes = int(NContributingNodes.size()); int BLNodes = int(BaseLevelNodeList.size()); // print the header file header_out << "ncols " << NCols << "\nnrows " << NRows << "\nxllcorner " << setprecision(14) << XMinimum << "\nyllcorner " << setprecision(14) << YMinimum << "\ncellsize " << DataResolution << "\nNODATA_value " << NoDataValue << "\nNDataNodes " << NDataNodes << "\nNBaseLevelNodes " << BLNodes << "\nNContributingNodes " << contributing_nodes << "\nBoundaryConditions "; for(int i = 0; i<4; i++) { header_out << " " << BoundaryConditions[i]; } header_out << endl; header_out.close(); cout << "sizes RC indices: " << RowIndex.size() << " " << ColIndex.size() << endl; cout << "BLNL size: " << BaseLevelNodeList.size() << endl; cout << "donors: " << NDonorsVector.size() << " Reciev: " << ReceiverVector.size() << endl; cout << "delta: " << DeltaVector.size() << " S: " << SVector.size() << endl; cout << "donorstack: " << DonorStackVector.size() << " BBasin: " << BLBasinVector.size() << endl; cout << "SVectorIndex " << SVectorIndex.size() << " NContrib: " << NContributingNodes.size() << endl; // now do the main data ofstream data_ofs(data_fname.c_str(), ios::out | ios::binary); int temp; for (int i=0; i<NRows; ++i) { for (int j=0; j<NCols; ++j) { temp = NodeIndex[i][j]; data_ofs.write(reinterpret_cast<char *>(&temp),sizeof(temp)); } } for (int i=0; i<NRows; ++i) { for (int j=0; j<NCols; ++j) { temp = FlowDirection[i][j]; data_ofs.write(reinterpret_cast<char *>(&temp),sizeof(temp)); } } for (int i=0; i<NRows; ++i) { for (int j=0; j<NCols; ++j) { temp = FlowLengthCode[i][j]; data_ofs.write(reinterpret_cast<char *>(&temp),sizeof(temp)); } } for (int i = 0; i<NDataNodes; i++) { temp = RowIndex[i]; data_ofs.write(reinterpret_cast<char *>(&temp),sizeof(temp)); } for (int i = 0; i<NDataNodes; i++) { temp = ColIndex[i]; data_ofs.write(reinterpret_cast<char *>(&temp),sizeof(temp)); } for (int i = 0; i<BLNodes; i++) { temp = BaseLevelNodeList[i]; data_ofs.write(reinterpret_cast<char *>(&temp),sizeof(temp)); } for (int i = 0; i<NDataNodes; i++) { temp = NDonorsVector[i]; data_ofs.write(reinterpret_cast<char *>(&temp),sizeof(temp)); } for (int i = 0; i<NDataNodes; i++) { temp = ReceiverVector[i]; data_ofs.write(reinterpret_cast<char *>(&temp),sizeof(temp)); } for (int i = 0; i<NDataNodes+1; i++) { temp = DeltaVector[i]; data_ofs.write(reinterpret_cast<char *>(&temp),sizeof(temp)); } for (int i = 0; i<NDataNodes; i++) { temp = DonorStackVector[i]; data_ofs.write(reinterpret_cast<char *>(&temp),sizeof(temp)); } for (int i = 0; i<NDataNodes; i++) { temp = SVector[i]; data_ofs.write(reinterpret_cast<char *>(&temp),sizeof(temp)); } for (int i = 0; i<NDataNodes; i++) { temp = BLBasinVector[i]; data_ofs.write(reinterpret_cast<char *>(&temp),sizeof(temp)); } for (int i = 0; i<NDataNodes; i++) { temp = SVectorIndex[i]; data_ofs.write(reinterpret_cast<char *>(&temp),sizeof(temp)); } for (int i = 0; i<contributing_nodes; i++) { temp = NContributingNodes[i]; data_ofs.write(reinterpret_cast<char *>(&temp),sizeof(temp)); } data_ofs.close(); } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // this unpickles a pickled flow info object. It is folded into a create function // // SMM 01/06/2012 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= void LSDFlowInfo::unpickle(string filename) { string ext = ".FIpickle"; string hdr_ext = ".FIpickle.hdr"; string hdr_fname = filename+hdr_ext; string data_fname = filename+ext; ifstream header_in; header_in.open(hdr_fname.c_str()); string temp_str; int contributing_nodes; vector<string> bc(4); int BLNodes; header_in >> temp_str >> NCols >> temp_str >> NRows >> temp_str >> XMinimum >> temp_str >> YMinimum >> temp_str >> DataResolution >> temp_str >> NoDataValue >> temp_str >> NDataNodes >> temp_str >> BLNodes >> temp_str >> contributing_nodes >> temp_str >> bc[0] >> bc[1] >> bc[2] >> bc[3]; header_in.close(); BoundaryConditions = bc; // now read the data, using the binary stream option ifstream ifs_data(data_fname.c_str(), ios::in | ios::binary); if( ifs_data.fail() ) { cout << "\nFATAL ERROR: the data file \"" << data_fname << "\" doesn't exist" << endl; exit(EXIT_FAILURE); } else { // initialze the arrays Array2D<int> data_array(NRows,NCols,NoDataValue); NodeIndex = data_array.copy(); FlowDirection = data_array.copy(); FlowLengthCode = data_array.copy(); vector<int> data_vector(NDataNodes,NoDataValue); vector<int> BLvector(BLNodes,NoDataValue); vector<int> deltaV(NDataNodes+1,NoDataValue); vector<int> CNvec(contributing_nodes,NoDataValue); int temp; for (int i=0; i<NRows; ++i) { for (int j=0; j<NCols; ++j) { ifs_data.read(reinterpret_cast<char*>(&temp), sizeof(temp)); NodeIndex[i][j] =temp; } } for (int i=0; i<NRows; ++i) { for (int j=0; j<NCols; ++j) { ifs_data.read(reinterpret_cast<char*>(&temp), sizeof(temp)); FlowDirection[i][j] =temp; } } for (int i=0; i<NRows; ++i) { for (int j=0; j<NCols; ++j) { ifs_data.read(reinterpret_cast<char*>(&temp), sizeof(temp)); FlowLengthCode[i][j] =temp; } } RowIndex = data_vector; for (int i=0; i<NDataNodes; ++i) { ifs_data.read(reinterpret_cast<char*>(&temp), sizeof(temp)); RowIndex[i] =temp; } ColIndex = data_vector; for (int i=0; i<NDataNodes; ++i) { ifs_data.read(reinterpret_cast<char*>(&temp), sizeof(temp)); ColIndex[i] =temp; } BaseLevelNodeList = BLvector; for (int i=0; i<BLNodes; ++i) { ifs_data.read(reinterpret_cast<char*>(&temp), sizeof(temp)); BaseLevelNodeList[i] =temp; } NDonorsVector = data_vector; for (int i=0; i<NDataNodes; ++i) { ifs_data.read(reinterpret_cast<char*>(&temp), sizeof(temp)); NDonorsVector[i] =temp; } ReceiverVector = data_vector; for (int i=0; i<NDataNodes; ++i) { ifs_data.read(reinterpret_cast<char*>(&temp), sizeof(temp)); ReceiverVector[i] =temp; } DeltaVector = deltaV; for (int i=0; i<NDataNodes+1; ++i) { ifs_data.read(reinterpret_cast<char*>(&temp), sizeof(temp)); DeltaVector[i] =temp; } DonorStackVector = data_vector; for (int i=0; i<NDataNodes; ++i) { ifs_data.read(reinterpret_cast<char*>(&temp), sizeof(temp)); DonorStackVector[i] =temp; } SVector = data_vector; for (int i=0; i<NDataNodes; ++i) { ifs_data.read(reinterpret_cast<char*>(&temp), sizeof(temp)); SVector[i] =temp; } BLBasinVector = data_vector; for (int i=0; i<NDataNodes; ++i) { ifs_data.read(reinterpret_cast<char*>(&temp), sizeof(temp)); BLBasinVector[i] =temp; } SVectorIndex = data_vector; for (int i=0; i<NDataNodes; ++i) { ifs_data.read(reinterpret_cast<char*>(&temp), sizeof(temp)); SVectorIndex[i] =temp; } NContributingNodes = CNvec; for (int i=0; i<contributing_nodes; ++i) { ifs_data.read(reinterpret_cast<char*>(&temp), sizeof(temp)); NContributingNodes[i] =temp; } } ifs_data.close(); cout << "sizes RC indices: " << RowIndex.size() << " " << ColIndex.size() << endl; cout << "BLNL size: " << BaseLevelNodeList.size() << endl; cout << "donors: " << NDonorsVector.size() << " Reciev: " << ReceiverVector.size() << endl; cout << "delta: " << DeltaVector.size() << " S: " << SVector.size() << endl; cout << "donorstack: " << DonorStackVector.size() << " BBasin: " << BLBasinVector.size() << endl; cout << "SVectorIndex " << SVectorIndex.size() << " NContrib: " << NContributingNodes.size() << endl; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // SCRIPTS FOR LOADING CSV DATA // ported from LSDSpatialCSVReader // FJC 23/03/17 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // // This loads a csv file // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- map<string, vector<string> > LSDFlowInfo::load_csv_data(string filename) { // make sure the filename works ifstream ifs(filename.c_str()); if( ifs.fail() ) { cout << "\nFATAL ERROR: Trying to load csv file, but the file" << filename << "doesn't exist; check your filename" << endl; exit(EXIT_FAILURE); } else { cout << "I have opened the csv file." << endl; } // Initiate the data map map<string, vector<string> > data_map; map<string, int > temp_vec_vec_key; vector< vector<string> > temp_vec_vec; map<string, vector<string> > temp_data_map; // << "Data map size is: " << data_map.size() << endl; //cout << "longitude size is: " << longitude.size() << endl; // initiate the string to hold the file string line_from_file; vector<string> empty_string_vec; vector<string> this_string_vec; string temp_string; // get the headers from the first line getline(ifs, line_from_file); // reset the string vec this_string_vec = empty_string_vec; // create a stringstream stringstream ss(line_from_file); ss.precision(9); while( ss.good() ) { string substr; getline( ss, substr, ',' ); // remove the spaces substr.erase(remove_if(substr.begin(), substr.end(), ::isspace), substr.end()); // remove control characters substr.erase(remove_if(substr.begin(), substr.end(), ::iscntrl), substr.end()); // add the string to the string vec this_string_vec.push_back( substr ); } // now check the data map int n_headers = int(this_string_vec.size()); vector<string> header_vector = this_string_vec; for (int i = 0; i<n_headers; i++) { temp_data_map[header_vector[i]] = empty_string_vec; } // now loop through the rest of the lines, getting the data. while( getline(ifs, line_from_file)) { //cout << "Getting line, it is: " << line_from_file << endl; // reset the string vec this_string_vec = empty_string_vec; // create a stringstream stringstream ss(line_from_file); while( ss.good() ) { string substr; getline( ss, substr, ',' ); // remove the spaces substr.erase(remove_if(substr.begin(), substr.end(), ::isspace), substr.end()); // remove control characters substr.erase(remove_if(substr.begin(), substr.end(), ::iscntrl), substr.end()); // add the string to the string vec this_string_vec.push_back( substr ); } //cout << "Yoyoma! size of the string vec: " << this_string_vec.size() << endl; if ( int(this_string_vec.size()) <= 0) { cout << "Hey there, I am trying to load your csv data but you seem not to have" << endl; cout << "enough columns in your file. I am ignoring a line" << endl; } else { int n_cols = int(this_string_vec.size()); //cout << "N cols is: " << n_cols << endl; for (int i = 0; i<n_cols; i++) { temp_data_map[header_vector[i]].push_back(this_string_vec[i]); } //cout << "Done with this line." << endl; } } data_map = temp_data_map; cout << "I loaded a csv with the keys: " << endl; for( map<string, vector<string> >::iterator it = data_map.begin(); it != data_map.end(); ++it) { cout << "Key is: " <<it->first << "\n"; } return data_map; } //============================================================================== //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // // This returns the string vector of data from a given column name // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- vector<string> LSDFlowInfo::get_data_column(string column_name, map<string, vector<string> > data_map) { vector<string> data_vector; if ( data_map.find(column_name) == data_map.end() ) { // not found cout << "I'm afraid the column "<< column_name << " is not in this dataset" << endl; } else { data_vector = data_map[column_name]; } return data_vector; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // Converts a data column to a float vector //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- vector<float> LSDFlowInfo::data_column_to_float(string column_name, map<string, vector<string> > data_map) { vector<string> string_vec = get_data_column(column_name, data_map); vector<float> float_vec; int N_data_elements = string_vec.size(); for(int i = 0; i<N_data_elements; i++) { float_vec.push_back( atof(string_vec[i].c_str())); } return float_vec; } // Converts a data column to a float vector vector<int> LSDFlowInfo::data_column_to_int(string column_name, map<string, vector<string> > data_map) { vector<string> string_vec = get_data_column(column_name, data_map); vector<int> int_vec; int N_data_elements = string_vec.size(); if (N_data_elements == 0) { cout << "Couldn't read in the data column. Check the column name!" << endl; } for(int i = 0; i<N_data_elements; i++) { int_vec.push_back( atoi(string_vec[i].c_str())); } return int_vec; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // END OF CSV FUNCTIONS //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // Method to ingest the channel heads raster generated using channel_heads_driver.cpp // into a vector of source nodes so that an LSDJunctionNetwork can be created easily // from them. Assumes the FlowInfo object has the same dimensions as the channel // heads raster. // // Takes the filename and extension of the channel heads raster. // // SWDG 05/12/12 // // Update: 6/6/14 Happy 3rd birthday Skye!!!! // SMM // Now if the file extension is "csv" then the script reads a csv channel heads // file // // Update 30/09/14 Altered structure of function, but key difference is that it // is now much better in how it goes about reading in channel heads using // the coordinates, so that channel heads for a region determined usiong one DEM // can be loaded in to another covering a subsample of the area, or a different // resolution, which was impossible before. // DTM //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= vector<int> LSDFlowInfo::Ingest_Channel_Heads(string filename, string extension, int input_switch){ vector<int> Sources; int CH_node; // if this is a csv file, read its contents directly into the node index vector if(extension == "csv") { if(input_switch != 0 && input_switch != 1 && input_switch != 2) { cout << "\t Note, you have specified an unsupported value for the input switch. Note: \n\t\t 0=take node index\n\t\t 1=take row and column indices\n\t\t 2=take x and y coordinates" << endl; cout << "\t ...taking node index by default" << endl; } ifstream ch_csv_in; string fname = filename +"."+extension; ch_csv_in.open(fname.c_str()); if(not ch_csv_in.good()) { cout << "You are trying to ingest a sources file that doesn't exist!!" << endl; cout << fname << endl; cout << "Check your filename" << endl; exit(EXIT_FAILURE); } cout << "fname is: " << fname << endl; string sline = ""; getline(ch_csv_in,sline); vector<int> nodeindex,rowindex,colindex; vector<float> x_coord,y_coord; // TODO This needs to be rplaced with the csv reader!!! while(!ch_csv_in.eof()) { char name[256]; ch_csv_in.getline(name,256); sline = name; // a very tedious way to get the right bit of data. There is probably a // better way to do this but this way works if (sline.size() > 0) { // column index string prefix = sline.substr(0,sline.size()); unsigned comma = sline.find_last_of(","); string suffix = prefix.substr(comma+1,prefix.size()); colindex.push_back(atoi(suffix.c_str())); // row index prefix = sline.substr(0,comma); comma = prefix.find_last_of(","); suffix = prefix.substr(comma+1,prefix.size()); rowindex.push_back(atoi(suffix.c_str())); // node index prefix = sline.substr(0,comma); comma = prefix.find_last_of(","); suffix = prefix.substr(comma+1,prefix.size()); nodeindex.push_back(atoi(suffix.c_str())); // y coordinate prefix = sline.substr(0,comma); comma = prefix.find_last_of(","); suffix = prefix.substr(comma+1,prefix.size()); y_coord.push_back(atof(suffix.c_str())); // x coordinate prefix = sline.substr(0,comma); comma = prefix.find_last_of(","); suffix = prefix.substr(comma+1,prefix.size()); x_coord.push_back(atof(suffix.c_str())); } } int node; // use row and column indices to locate source nodes. if(input_switch == 1) { for(int i = 0; i < int(rowindex.size()); ++i) { if(rowindex[i]<NRows && rowindex[i]>=0 && colindex[i]<NCols && colindex[i] >=0 && NodeIndex[rowindex[i]][colindex[i]]!=NoDataValue) { node = retrieve_node_from_row_and_column(rowindex[i],colindex[i]); Sources.push_back(node); } } } // Use coordinates to locate source nodes. Note that this enables the use // of LiDAR derived channel heads in coarser DEMs of the same area or // subsets of the original DEM for more efficient processing. else if(input_switch == 2) { vector<int> Sources_temp; int N_coords = x_coord.size(); int N_sources_1 = 0; for(int i = 0; i < N_coords; ++i) { node = get_node_index_of_coordinate_point(x_coord[i], y_coord[i]); if (node != NoDataValue) { // Test 1 - Check for channel heads that fall in same pixel int test1 = 0; N_sources_1 = Sources_temp.size(); for(int i_test=0; i_test<N_sources_1;++i_test) { if(node==Sources_temp[i_test]) test1 = 1; } if(test1==0) Sources_temp.push_back(node); else cout << "\t\t ! removed node from sources list - coincident with another source node" << endl; } } // Test 2 - Need to do some extra checks to load sources correctly. int N_sources_2 = Sources_temp.size(); for(int i = 0; i<N_sources_2; ++i) { int test2 = 0; for(int i_test = 0; i_test<int(Sources_temp.size()); ++i_test) { if(i!=i_test) { if(is_node_upstream(Sources_temp[i],Sources_temp[i_test])==true) test2 = 1; } } if(test2 ==0) Sources.push_back(Sources_temp[i]); else cout << "\t\t ! removed node from sources list - other sources upstream" << endl; } } // Using Node Index directly (default) else Sources = nodeindex; } // if not the code assums a sources raster. else { LSDIndexRaster CHeads(filename, extension); for (int i = 0; i < NRows; ++i) { for (int j = 0; j < NCols; ++j) { if (CHeads.get_data_element(i,j) != NoDataValue) { CH_node = retrieve_node_from_row_and_column(i,j); if (CH_node != NoDataValue) { Sources.push_back(CH_node); } } } } } return Sources; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // Method to ingest the channel heads raster generated using channel_heads_driver.cpp // into a vector of source nodes so that an LSDJunctionNetwork can be created easily // from them. Assumes the FlowInfo object has the same dimensions as the channel // heads raster. // // Takes the filename and extension of the channel heads raster. // // SWDG 05/12/12 // // Update: 6/6/14 Happy 3rd birthday Skye!!!! // SMM // Now if the file extension is "csv" then the script reads a csv channel heads // file // // Update 30/09/14 Altered structure of function, but key difference is that it // is now much better in how it goes about reading in channel heads using // the coordinates, so that channel heads for a region determined usiong one DEM // can be loaded in to another covering a subsample of the area, or a different // resolution, which was impossible before. // DTM // // ******************************************************************************************* // UPDATE 23/03/17 - NEW OVERLOADED CHANNEL HEADS INGESTION ROUTINE. This ONLY works with the // csv file as this seems to be the best way of reading in the channel heads. Other formats // should now be obsolete. // Finds the appropriate column from the csv based on the string of the heading rather // than by column number, so should work with different versions of the output sources // csv file. // // Input switch tells what the columns the code should be looking for: // 0 - use the node index // 1 - use rows and columns // 2 - use x and y (UTM coordinates) // Could add in a 3rd switch for lat long but this requires a bunch of extra porting that // I can't be bothered to do right now. // FJC // ***************************************************************************************** //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= vector<int> LSDFlowInfo::Ingest_Channel_Heads(string filename, int input_switch) { vector<int> Sources; int CH_node; // load the csv file map<string, vector<string> > data_map = load_csv_data(filename+".csv"); // now check the input switch to search for the various columns if (input_switch == 0) { // use the node index vector<int> NodeIndices = data_column_to_int("node", data_map); Sources = NodeIndices; } else if (input_switch == 1) { // use the rows and columns vector<int> rows = data_column_to_int("row", data_map); vector<int> cols = data_column_to_int("col", data_map); for (int i = 0; i < int(rows.size()); i++) { int NI = retrieve_node_from_row_and_column(rows[i], cols[i]); Sources.push_back(NI); } } else if (input_switch == 2) { // use x and y (UTM coordinates) vector<float> x_coord = data_column_to_float("x", data_map); vector<float> y_coord = data_column_to_float("y", data_map); int N_coords = x_coord.size(); vector<int> Sources_temp; int N_sources_1 = 0; for(int i = 0; i < N_coords; ++i) { int node = get_node_index_of_coordinate_point(x_coord[i], y_coord[i]); if (node != NoDataValue) { // Test 1 - Check for channel heads that fall in same pixel int test1 = 0; N_sources_1 = Sources_temp.size(); for(int i_test=0; i_test<N_sources_1;++i_test) { if(node==Sources_temp[i_test]) test1 = 1; } if(test1==0) Sources_temp.push_back(node); else cout << "\t\t ! removed node from sources list - coincident with another source node" << endl; } } // Test 2 - Need to do some extra checks to load sources correctly. int N_sources_2 = Sources_temp.size(); for(int i = 0; i<N_sources_2; ++i) { int test2 = 0; for(int i_test = 0; i_test<int(Sources_temp.size()); ++i_test) { if(i!=i_test) { if(is_node_upstream(Sources_temp[i],Sources_temp[i_test])==true) test2 = 1; } } if(test2 ==0) Sources.push_back(Sources_temp[i]); else cout << "\t\t ! removed node from sources list - other sources upstream" << endl; } } else { cout << "You have not supplied a valid input switch! Please supply either 0, 1, or 2." << endl; } return Sources; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // Method to ingest sources from OS MasterMap Water Network Layer (csv) // into a vector of source nodes so that an LSDJunctionNetwork can be created easily // from them. // // Takes the filename and extension of the channel heads raster. // // FJC 28/11/2016 //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= vector<int> LSDFlowInfo::Ingest_Channel_Heads_OS(string csv_filename) { vector<int> Sources; // read in the CSV file ifstream input_csv; string dot = "."; string extension = "csv"; string fname = csv_filename+dot+extension; cout << "The CSV filename is: " << fname << endl; input_csv.open(fname.c_str()); // check for correct input if (not input_csv.good()) { cout << "I can't read the CSV file! Check your filename." << endl; } //int object_ID, name, source_ID, PosAlong; //float X,Y; vector<float> X_coords, Y_coords; // read in the file while(!input_csv.eof()) { string line; getline(input_csv,line); // get the x and y coords to vectors istringstream ss(line); string param; int i=0; while(getline(ss, param, ',')) { if (i == 4) { X_coords.push_back(atof(param.c_str())); } if (i == 5) { Y_coords.push_back(atof(param.c_str())); } i++; } } vector<int> Sources_temp; int N_coords = X_coords.size(); int N_sources_1 = 0; for(int i = 0; i < N_coords; ++i) { int node = get_node_index_of_coordinate_point(X_coords[i], Y_coords[i]); if (node != NoDataValue) { // Test 1 - Check for channel heads that fall in same pixel int test1 = 0; N_sources_1 = Sources_temp.size(); for(int i_test=0; i_test<N_sources_1;++i_test) { if(node==Sources_temp[i_test]) test1 = 1; } if(test1==0) Sources_temp.push_back(node); else cout << "\t\t ! removed node from sources list - coincident with another source node" << endl; } } // Test 2 - Need to do some extra checks to load sources correctly. int N_sources_2 = Sources_temp.size(); for(int i = 0; i<N_sources_2; ++i) { cout << flush << "\t Source: " << i << " of " << N_sources_2 << "\r"; int test2 = 0; for(int i_test = 0; i_test<int(Sources_temp.size()); ++i_test) { if(i!=i_test) { if(is_node_upstream(Sources_temp[i],Sources_temp[i_test])==true) test2 = 1; } } if(test2 ==0) Sources.push_back(Sources_temp[i]); //else cout << "\t\t ! removed node from sources list - other sources upstream" << endl; } cout << "Returning sources..." << endl; return Sources; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // this prints the flownet information // // SMM 01/06/2012 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= void LSDFlowInfo::print_flow_info_vectors(string filename) { string string_filename; string dot = "."; string extension = "txt"; string_filename = filename+dot+extension; cout << "The filename is " << string_filename << endl; // print out all the donor, reciever and stack info ofstream donor_info_out; donor_info_out.open(string_filename.c_str()); for(int i = 0; i<NDataNodes; i++) { donor_info_out << i << " "; } donor_info_out << endl; for(int i = 0; i<NDataNodes; i++) { donor_info_out << ReceiverVector[i] << " "; } donor_info_out << endl; for(int i = 0; i<NDataNodes; i++) { donor_info_out << NDonorsVector[i] << " "; } donor_info_out << endl; for(int i = 0; i<NDataNodes+1; i++) { donor_info_out << DeltaVector[i] << " "; } donor_info_out << endl; for(int i = 0; i<NDataNodes; i++) { donor_info_out << DonorStackVector[i] << " "; } donor_info_out << endl; for(int i = 0; i<NDataNodes; i++) { donor_info_out << SVector[i] << " "; } donor_info_out << endl; if( int(SVectorIndex.size()) == NDataNodes) { for(int i = 0; i<NDataNodes; i++) { donor_info_out << SVectorIndex[i] << " "; } donor_info_out << endl; for(int i = 0; i<NDataNodes; i++) { donor_info_out << NContributingNodes[i] << " "; } donor_info_out << endl; } donor_info_out.close(); } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // these functions write the index arrays to index rasters // // // SMM 01/06/2012 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= LSDIndexRaster LSDFlowInfo::write_NodeIndex_to_LSDIndexRaster() { cout << "NRows: " << NRows << " and NCols: " << NCols << endl; LSDIndexRaster temp_nodeindex(NRows,NCols,XMinimum,YMinimum,DataResolution,NoDataValue,NodeIndex,GeoReferencingStrings); return temp_nodeindex; } LSDIndexRaster LSDFlowInfo::write_FlowDirection_to_LSDIndexRaster() { LSDIndexRaster temp_flowdir(NRows,NCols,XMinimum,YMinimum,DataResolution,NoDataValue,FlowDirection,GeoReferencingStrings); return temp_flowdir; } LSDIndexRaster LSDFlowInfo::write_FlowLengthCode_to_LSDIndexRaster() { LSDIndexRaster temp_flc(NRows,NCols,XMinimum,YMinimum,DataResolution,NoDataValue,FlowLengthCode,GeoReferencingStrings); return temp_flc; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // This function writes an LSDIndesxRaster given a list of node indices // // // SMM 01/06/2012 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= LSDIndexRaster LSDFlowInfo::write_NodeIndexVector_to_LSDIndexRaster(vector<int>& nodeindexvec) { int n_node_indices = nodeindexvec.size(); //cout << "The number of nodeindices is: " << n_node_indices << endl; Array2D<int> chan(NRows,NCols,NoDataValue); //cout << "Raster nr: " << chan.dim1() << " nc: " << chan.dim2() << endl; int curr_row, curr_col; for(int i = 0; i<n_node_indices; i++) { // make sure there is no segmentation fault for bad data // Note: bad data is ignored if(nodeindexvec[i] <= NDataNodes) { retrieve_current_row_and_col(nodeindexvec[i],curr_row, curr_col); if(chan[curr_row][curr_col] == NoDataValue) { chan[curr_row][curr_col] = 1; } else { chan[curr_row][curr_col]++; } } else { cout << "WARNING: LSDFlowInfo::write_NodeIndexVector_to_LSDIndexRaster" << " node index does not exist!"<< endl; } } LSDIndexRaster temp_chan(NRows,NCols,XMinimum,YMinimum,DataResolution,NoDataValue,chan,GeoReferencingStrings); return temp_chan; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // This function writes an LSDIndesxRaster given a list of node indices, and give every // pixel its nodeindex value, which is unique. // // SWDG after SMM 2/2/16 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= LSDIndexRaster LSDFlowInfo::write_NodeIndexVector_to_LSDIndexRaster_Unique(vector<int>& nodeindexvec) { int n_node_indices = nodeindexvec.size(); Array2D<int> chan(NRows,NCols,NoDataValue); int curr_row, curr_col; for(int i = 0; i<n_node_indices; i++){ // make sure there is no segmentation fault for bad data // Note: bad data is ignored if(nodeindexvec[i] <= NDataNodes){ retrieve_current_row_and_col(nodeindexvec[i], curr_row, curr_col); if(chan[curr_row][curr_col] == NoDataValue){ chan[curr_row][curr_col] = i; } else{ //revisted points will be overwritten, most recent id will be pres chan[curr_row][curr_col] = i; } } else { cout << "WARNING: LSDFlowInfo::write_NodeIndexVector_to_LSDIndexRaster" << " node index does not exist!"<< endl; } } LSDIndexRaster temp_chan(NRows,NCols,XMinimum,YMinimum,DataResolution,NoDataValue,chan,GeoReferencingStrings); return temp_chan; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // // This function calcualtes the contributing pixels // it can be converted to contributing area by multiplying by the // DataResolution^2 // // This function used the S vector index and NContributing nodes to calculate the area // // // SMM 01/06/2012 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= LSDIndexRaster LSDFlowInfo::write_NContributingNodes_to_LSDIndexRaster() { Array2D<int> contributing_pixels(NRows,NCols,NoDataValue); int row,col; // loop through the node vector, adding pixels to receiver nodes for(int node = 0; node<NDataNodes; node++) { row = RowIndex[node]; col = ColIndex[node]; contributing_pixels[row][col] = NContributingNodes[node]; } LSDIndexRaster temp_cp(NRows,NCols,XMinimum,YMinimum,DataResolution,NoDataValue,contributing_pixels,GeoReferencingStrings); return temp_cp; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // writes a index raster in arc format // LSD format: // 7 0 1 // 6 -1 2 // 5 4 3 // int Arc_flowdir; // flow direction in arcmap format // // 32 64 128 // // 16 0 1 // // 8 4 2 // // // SMM 01/06/2012 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= LSDIndexRaster LSDFlowInfo::write_FlowDirection_to_LSDIndexRaster_Arcformat() { Array2D<int> FlowDirectionArc(NRows,NCols,NoDataValue); for(int row = 0; row<NRows; row++) { for (int col = 0; col<NCols; col++) { if ( FlowDirection[row][col] == -1) { FlowDirectionArc[row][col] = 0; } else if ( FlowDirection[row][col] == 0) { FlowDirectionArc[row][col] = 64; } else if ( FlowDirection[row][col] == 1) { FlowDirectionArc[row][col] = 128; } else if ( FlowDirection[row][col] == 2) { FlowDirectionArc[row][col] = 1; } else if ( FlowDirection[row][col] == 3) { FlowDirectionArc[row][col] = 2; } else if ( FlowDirection[row][col] == 4) { FlowDirectionArc[row][col] = 4; } else if ( FlowDirection[row][col] == 5) { FlowDirectionArc[row][col] = 8; } else if ( FlowDirection[row][col] == 6) { FlowDirectionArc[row][col] = 16; } else if ( FlowDirection[row][col] == 7) { FlowDirectionArc[row][col] = 32; } } } LSDIndexRaster temp_fd(NRows,NCols,XMinimum,YMinimum,DataResolution,NoDataValue,FlowDirectionArc,GeoReferencingStrings); return temp_fd; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // This function writes the drainage area (number of contributing nodes // * DataResolution^2) to an LSDRaster object // Added by FC 15/11/12 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= LSDRaster LSDFlowInfo::write_DrainageArea_to_LSDRaster() { // initialise the 2D array int row,col; // node index float ndv = float(NoDataValue); float this_DA; Array2D<float> DrainageArea_local(NRows,NCols,ndv); for(int node = 0; node<NDataNodes; node++) { row = RowIndex[node]; col = ColIndex[node]; //cout << NContributingNodes[node] << endl; this_DA = float(NContributingNodes[node])*DataResolution*DataResolution; DrainageArea_local[row][col] = this_DA; } // create the LSDRaster object LSDRaster DrainageArea(NRows,NCols,XMinimum,YMinimum,DataResolution,ndv,DrainageArea_local,GeoReferencingStrings); return DrainageArea; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // This function calcualtes the contributing pixels // it can be converted to contributing area by multiplying by the // DataResolution^2 // In this function a pixel that has no donors has a contributing pixel value of 0 // // // SMM 01/06/2012 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= LSDIndexRaster LSDFlowInfo::calculate_n_pixels_contributing_from_upslope() { Array2D<int> contributing_pixels(NRows,NCols,NoDataValue); int row,col; int receive_row, receive_col; int receiver_node; // loop through the s vector, adding pixels to receiver nodes for(int node = NDataNodes-1; node>=0; node--) { row = RowIndex[SVector[node]]; col = ColIndex[SVector[node]]; // if the pixel exists and has no contributing pixels, // change from nodata to zero if(contributing_pixels[row][col] == NoDataValue) { contributing_pixels[row][col] = 0; } receiver_node = ReceiverVector[ SVector[node] ] ; receive_row = RowIndex[ receiver_node ]; receive_col = ColIndex[ receiver_node ]; cout << "node " << node << " pixel: " << SVector[node] << " receiver: " << receiver_node << endl; cout << "contributing: " << contributing_pixels[row][col] << endl; if ( receiver_node == SVector[node]) { // do nothing } else if ( contributing_pixels[receive_row][receive_col] == NoDataValue) { contributing_pixels[receive_row][receive_col] = contributing_pixels[row][col]+1; } else { contributing_pixels[receive_row][receive_col] += contributing_pixels[row][col]+1; } cout << "recieving: " << contributing_pixels[receive_row][receive_col] << endl; } LSDIndexRaster temp_cp(NRows,NCols,XMinimum,YMinimum,DataResolution,NoDataValue,contributing_pixels,GeoReferencingStrings); return temp_cp; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // This function calcualtes the contributing pixels // it can be converted to contributing area by multiplying by the // DataResolution^2 // // In this function a pixel that has no donors contributes its own flow // // // SMM 01/06/2012 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= void LSDFlowInfo::calculate_upslope_reference_indices() { vector<int> vectorized_area(NDataNodes,1); SVectorIndex = vectorized_area; int receiver_node; int donor_node; // loop through the s vector, adding pixels to receiver nodes for(int node = NDataNodes-1; node>=0; node--) { donor_node = SVector[node]; receiver_node = ReceiverVector[ donor_node ]; // every node is visited once and only once so we can map the // unique positions of the nodes to the SVector SVectorIndex[donor_node] = node; // add the upslope area (note no action is taken // for base level nodes since they donate to themselves and // we must avoid float counting if (donor_node != receiver_node) { vectorized_area[ receiver_node ] += vectorized_area[ donor_node ]; } } NContributingNodes = vectorized_area; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // This function returns a integer vector containing all the node numbers upslope // of of the node with number node_number_outlet // // SMM 01/06/2012 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- vector<int> LSDFlowInfo::get_upslope_nodes(int node_number_outlet) { vector<int> us_nodes; if(node_number_outlet < 0 || node_number_outlet > NDataNodes-1) { cout << "the node index does not exist" << endl; exit(EXIT_FAILURE); } int start_SVector_node = SVectorIndex[node_number_outlet]; int end_SVector_node = start_SVector_node+NContributingNodes[node_number_outlet]; for(int node = start_SVector_node; node < end_SVector_node; node++) { us_nodes.push_back(SVector[node]); } return us_nodes; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // This function takes a list of source nodes and creates a raster where // the pixels have a value of 1 where there are upslope nodes and nodata otherwise //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- LSDRaster LSDFlowInfo::get_upslope_node_mask(vector<int> source_nodes) { // initiate the data array Array2D<float> this_raster(NRows,NCols,NoDataValue); // loop through the nodes, collecting upslope nodes int n_nodes = int(source_nodes.size()); int this_node; //int us_node; int curr_row,curr_col; float is_us = 1.0; // go through all the source nodes, find their upslope nodes // and set the value of these nodes to 1.0 on the data array for (int n = 0; n<n_nodes; n++) { this_node = source_nodes[n]; // check if it is in the DEM if (this_node < NDataNodes) { vector<int> upslope_nodes = get_upslope_nodes(this_node); int n_us_nodes = int(upslope_nodes.size()); for(int us = 0; us<n_us_nodes; us++) { retrieve_current_row_and_col(upslope_nodes[us],curr_row,curr_col); this_raster[curr_row][curr_col]=is_us; } } } // now create the raster LSDRaster temp_us(NRows,NCols,XMinimum,YMinimum,DataResolution,NoDataValue,this_raster,GeoReferencingStrings); return temp_us; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // This function takes a list of source nodes and creates a raster where // the pixels have a value of upslope_value // where there are upslope nodes and NoData otherwise //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- LSDRaster LSDFlowInfo::get_upslope_node_mask(vector<int> source_nodes, vector<float> upslope_values) { // initiate the data array Array2D<float> this_raster(NRows,NCols,NoDataValue); if (source_nodes.size() == upslope_values.size()) { // loop through the nodes, collecting upslope nodes int n_nodes = int(source_nodes.size()); int this_node; //int us_node; int curr_row,curr_col; // go through all the source nodes, find their upslope nodes // and set the value of these nodes to 1.0 on the data array for (int n = 0; n<n_nodes; n++) { this_node = source_nodes[n]; // check if it is in the DEM if (this_node < NDataNodes) { vector<int> upslope_nodes = get_upslope_nodes(this_node); int n_us_nodes = int(upslope_nodes.size()); for(int us = 0; us<n_us_nodes; us++) { retrieve_current_row_and_col(upslope_nodes[us],curr_row,curr_col); this_raster[curr_row][curr_col]= upslope_values[n]; } } } } else { cout << "The uplsope vlaues vector needs to be the same lengths as the sources vector!" << endl; cout << "Returning an nodata raster" << endl; } // now create the raster LSDRaster temp_us(NRows,NCols,XMinimum,YMinimum,DataResolution,NoDataValue,this_raster,GeoReferencingStrings); return temp_us; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // // Accumulate some variable (such a precipitation) from an accumulation raster // // This requires summing all upslope nodes for every node. It seems a bit inefficient // but the other simple alternative is to do a sort() operation initially and then // move from upslope node down. There is probably a more efficient way to do this // and this algorithm should be revisited later to see if we can speed it up. // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= LSDRaster LSDFlowInfo::upslope_variable_accumulator(LSDRaster& accum_raster) { int raster_NRows, raster_NCols; float raster_XMin, raster_YMin, raster_DataRes; // first check to make sure the raster dimensions match that of the // raster upon which LSDFlowInfo is based raster_NRows = accum_raster.get_NRows(); raster_NCols = accum_raster.get_NCols(); raster_XMin = accum_raster.get_XMinimum(); raster_YMin = accum_raster.get_YMinimum(); raster_DataRes = accum_raster.get_DataResolution(); if (raster_NRows != NRows || raster_NCols != NCols || raster_XMin != XMinimum || raster_YMin != YMinimum || raster_DataRes != DataResolution) { cout << "Warning!!, LSDFlowInfo::upslope_area_accumulator\n" << "Accumulation raster does not match dimensions of original raster" << endl; return accum_raster; } else { // create the data array Array2D<float> accumulated_data_array(NRows,NCols,NoDataValue); // loop through all the nodes, accumulating the areas for(int this_node = 0; this_node <NDataNodes; this_node++) { // get the upslope nodes vector<int> node_vec = get_upslope_nodes(this_node); // loop through these nodes, adding them to the accumulator float this_node_accumulated = 0; int this_row, this_col; for (int ni = 0; ni<int(node_vec.size()); ni++) { retrieve_current_row_and_col(node_vec[ni],this_row,this_col); this_node_accumulated += accum_raster.get_data_element(this_row, this_col); } // write the accumulated variable to the array int curr_row, curr_col; retrieve_current_row_and_col(this_node,curr_row,curr_col); accumulated_data_array[curr_row][curr_col] = this_node_accumulated; } // create the raster LSDRaster accumulated_flow(NRows, NCols, XMinimum, YMinimum, DataResolution, NoDataValue, accumulated_data_array,GeoReferencingStrings); return accumulated_flow; } } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // This function tests whether the test is upstream of the current node // // FC 01/06/2012 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= int LSDFlowInfo::is_node_upstream(int current_node, int test_node) { int i = 0; int start_SVector_node = SVectorIndex[current_node]; int end_SVector_node = start_SVector_node+NContributingNodes[current_node]; int SVector_test_node = SVectorIndex[test_node]; for(int node = start_SVector_node; node < end_SVector_node; node++) { if (node == SVector_test_node) { i = 1; } } return i; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // This function tests whether a node is a base level node // // FC 01/06/2012 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= int LSDFlowInfo::is_node_base_level(int node) { int i = 0; for (int j = 0; j < int(BaseLevelNodeList.size()); j++) { if (node == BaseLevelNodeList[j]) { i = 1; } } return i; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // This function redurns a vector of node indices to all the donor // nodes of a particular node // // SMM 21/10/2013 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= vector<int> LSDFlowInfo::get_donor_nodes(int current_node) { int start_D = DeltaVector[current_node]; int end_D = DeltaVector[current_node+1]; vector<int> donor_nodes; for(int this_node = start_D; this_node<end_D; this_node++) { //cout << "node " << current_node << " and donor: " << DonorStackVector[ this_node ] << endl; donor_nodes.push_back( DonorStackVector[ this_node ] ); } return donor_nodes; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // This function calculates the chi function for all the nodes upslope a given node // it takes a node list // // // SMM 01/06/2012 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- vector<float> LSDFlowInfo::get_upslope_chi(int starting_node, float m_over_n, float A_0) { vector<int> upslope_pixel_list = get_upslope_nodes(starting_node); vector<float> chi_vec = get_upslope_chi(upslope_pixel_list, m_over_n, A_0); return chi_vec; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // This function calculates the chi function for all the nodes upslope a given node // it takes a node list // // // SMM 01/06/2012 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- vector<float> LSDFlowInfo::get_upslope_chi(int starting_node, float m_over_n, float A_0, LSDRaster& Discharge) { vector<int> upslope_pixel_list = get_upslope_nodes(starting_node); vector<float> chi_vec = get_upslope_chi(upslope_pixel_list, m_over_n, A_0, Discharge); return chi_vec; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // This function is called from the the get_upslope_chi that only has an integer // it returns the acutal chi values in a vector //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- vector<float> LSDFlowInfo::get_upslope_chi(vector<int>& upslope_pixel_list, float m_over_n, float A_0) { int receiver_node; int IndexOfReceiverInUplsopePList; float root2 = 1.41421356; float diag_length = root2*DataResolution; float dx; float pixel_area = DataResolution*DataResolution; int node,row,col; // get the number of nodes upslope int n_nodes_upslope = upslope_pixel_list.size(); vector<float> chi_vec(n_nodes_upslope,0.0); if(n_nodes_upslope != NContributingNodes[ upslope_pixel_list[0] ]) { cout << "LSDFlowInfo::get_upslope_chi, the contributing pixels don't agree" << endl; exit(EXIT_FAILURE); } int start_SVector_node = SVectorIndex[ upslope_pixel_list[0] ]; for (int n_index = 1; n_index<n_nodes_upslope; n_index++) { node = upslope_pixel_list[n_index]; receiver_node = ReceiverVector[ node ]; IndexOfReceiverInUplsopePList = SVectorIndex[receiver_node]-start_SVector_node; row = RowIndex[node]; col = ColIndex[node]; if (FlowLengthCode[row][col] == 2) { dx = diag_length; } else { dx = DataResolution; } chi_vec[n_index] = dx*(pow( (A_0/ (float(NContributingNodes[node])*pixel_area) ),m_over_n)) + chi_vec[IndexOfReceiverInUplsopePList]; // cout << "node: " << upslope_pixel_list[n_index] << " receiver: " << receiver_node // << " SIndexReciever: " << IndexOfReceiverInUplsopePList // << " and checked: " << upslope_pixel_list[IndexOfReceiverInUplsopePList] // << " and chi: " << chi_vec[n_index] << endl; } return chi_vec; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // This function is called from the the get_upslope_chi that only has an integer // it returns the acutal chi values in a vector // same as above but uses a discharge raster //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- vector<float> LSDFlowInfo::get_upslope_chi(vector<int>& upslope_pixel_list, float m_over_n, float A_0, LSDRaster& Discharge) { int receiver_node; int IndexOfReceiverInUplsopePList; float root2 = 1.41421356; float diag_length = root2*DataResolution; float dx; int node,row,col; // get the number of nodes upslope int n_nodes_upslope = upslope_pixel_list.size(); vector<float> chi_vec(n_nodes_upslope,0.0); if(n_nodes_upslope != NContributingNodes[ upslope_pixel_list[0] ]) { cout << "LSDFlowInfo::get_upslope_chi, the contributing pixels don't agree" << endl; exit(EXIT_FAILURE); } int start_SVector_node = SVectorIndex[ upslope_pixel_list[0] ]; for (int n_index = 1; n_index<n_nodes_upslope; n_index++) { node = upslope_pixel_list[n_index]; receiver_node = ReceiverVector[ node ]; IndexOfReceiverInUplsopePList = SVectorIndex[receiver_node]-start_SVector_node; row = RowIndex[node]; col = ColIndex[node]; if (FlowLengthCode[row][col] == 2) { dx = diag_length; } else { dx = DataResolution; } chi_vec[n_index] = dx*(pow( (A_0/ ( Discharge.get_data_element(row, col) ) ),m_over_n)) + chi_vec[IndexOfReceiverInUplsopePList]; // cout << "node: " << upslope_pixel_list[n_index] << " receiver: " << receiver_node // << " SIndexReciever: " << IndexOfReceiverInUplsopePList // << " and checked: " << upslope_pixel_list[IndexOfReceiverInUplsopePList] // << " and chi: " << chi_vec[n_index] << endl; } return chi_vec; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // This function takes a list of starting nodes and calucaltes chi // it assumes each chi value has the same base level. //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- LSDRaster LSDFlowInfo::get_upslope_chi_from_multiple_starting_nodes(vector<int>& starting_nodes, float m_over_n, float A_0, float area_threshold) { // some variables for writing to the raster int curr_row; int curr_col; int curr_node; float PixelArea = DataResolution*DataResolution; float DrainArea; // an array to hold the chi values Array2D<float> new_chi(NRows,NCols,NoDataValue); int n_starting_nodes = int(starting_nodes.size()); for(int sn = 0; sn<n_starting_nodes; sn++) { // first check to see if this node has already been visited. If it has // all upslope nodes have also been visited so there is no point continuing // with this node retrieve_current_row_and_col(starting_nodes[sn],curr_row,curr_col); if(new_chi[curr_row][curr_col] == NoDataValue) { vector<float> us_chi = get_upslope_chi(starting_nodes[sn], m_over_n, A_0); vector<int> upslope_pixel_list = get_upslope_nodes(starting_nodes[sn]); int n_chi_nodes = int(us_chi.size()); for (int cn = 0; cn<n_chi_nodes; cn++) { // get the current row and column curr_node = upslope_pixel_list[cn]; retrieve_current_row_and_col(curr_node,curr_row,curr_col); // check to see if the drainage area is greater than the threshold // if so, calcualte chi DrainArea = PixelArea*NContributingNodes[curr_node]; if(DrainArea > area_threshold) { new_chi[curr_row][curr_col]= us_chi[cn]; } } } } LSDRaster chi_map(NRows, NCols, XMinimum, YMinimum, DataResolution, NoDataValue, new_chi,GeoReferencingStrings); return chi_map; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // This function takes a list of starting nodes and calucaltes chi // it assumes each chi value has the same base level. // Same as above but calculates using discharge //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- LSDRaster LSDFlowInfo::get_upslope_chi_from_multiple_starting_nodes(vector<int>& starting_nodes, float m_over_n, float A_0, float area_threshold, LSDRaster& Discharge ) { // some variables for writing to the raster int curr_row; int curr_col; int curr_node; float PixelArea = DataResolution*DataResolution; float DrainArea; // an array to hold the chi values Array2D<float> new_chi(NRows,NCols,NoDataValue); int n_starting_nodes = int(starting_nodes.size()); for(int sn = 0; sn<n_starting_nodes; sn++) { // first check to see if this node has already been visited. If it has // all upslope nodes have also been visited so there is no point continuing // with this node retrieve_current_row_and_col(starting_nodes[sn],curr_row,curr_col); if(new_chi[curr_row][curr_col] == NoDataValue) { vector<float> us_chi = get_upslope_chi(starting_nodes[sn], m_over_n, A_0,Discharge); vector<int> upslope_pixel_list = get_upslope_nodes(starting_nodes[sn]); int n_chi_nodes = int(us_chi.size()); for (int cn = 0; cn<n_chi_nodes; cn++) { // get the current row and column curr_node = upslope_pixel_list[cn]; retrieve_current_row_and_col(curr_node,curr_row,curr_col); // check to see if the drainage area is greater than the threshold // if so, calcualte chi DrainArea = PixelArea*NContributingNodes[curr_node]; if(DrainArea > area_threshold) { new_chi[curr_row][curr_col]= us_chi[cn]; } } } } LSDRaster chi_map(NRows, NCols, XMinimum, YMinimum, DataResolution, NoDataValue, new_chi,GeoReferencingStrings); return chi_map; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // This function assumes all base level nodes are at the same base level // and calculates chi for them. Essentially it covers the entire map in // chi values. // This function is probably most appropriate for looking at numerical // model results //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- LSDRaster LSDFlowInfo::get_upslope_chi_from_all_baselevel_nodes(float m_over_n, float A_0, float area_threshold) { LSDRaster all_chi = get_upslope_chi_from_multiple_starting_nodes(BaseLevelNodeList, m_over_n, A_0, area_threshold); return all_chi; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // This function assumes all base level nodes are at the same base level // and calculates chi for them. Essentially it covers the entire map in // chi values. // This function is probably most appropriate for looking at numerical // model results // same as above but calculates with a discharge //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- LSDRaster LSDFlowInfo::get_upslope_chi_from_all_baselevel_nodes(float m_over_n, float A_0, float area_threshold, LSDRaster& Discharge) { LSDRaster all_chi = get_upslope_chi_from_multiple_starting_nodes(BaseLevelNodeList, m_over_n, A_0, area_threshold, Discharge); return all_chi; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // // distance from outlet function // this is overloaded. // if it isn't provided any argument, it calculates the distance from outlet // of all the base level nodes // if it is given a node index number or a row and column, then // the distance from outlet includes all the distances upstream of that node // // // SMM 01/06/2012 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= LSDRaster LSDFlowInfo::distance_from_outlet() { // initialize the array2d that will become the LSDRaster float ndv = float(NoDataValue); Array2D<float> flow_distance(NRows,NCols,ndv); // initialize the 1/root(2) float root2 = 1.41421356; float diag_length = root2*DataResolution; int row,col,bl_row,bl_col,receive_row,receive_col; int start_node = 0; int end_node; int nodes_in_bl_tree; int baselevel_node; // loop through the base level node list int n_base_level_nodes = BaseLevelNodeList.size(); for(int bl = 0; bl<n_base_level_nodes; bl++) { baselevel_node = BaseLevelNodeList[bl]; bl_row = RowIndex[baselevel_node]; bl_col = ColIndex[baselevel_node]; // get the number of nodes upslope and including this node nodes_in_bl_tree = NContributingNodes[baselevel_node]; //cout << "LINE 938, FlowInfo, base level: " << bl << " with " << nodes_in_bl_tree << " nodes upstream" << endl; end_node = start_node+nodes_in_bl_tree; // set the distance of the outlet to zero flow_distance[bl_row][bl_col] = 0; // now loop through stack for(int s_node = start_node; s_node < end_node; s_node++) { //cout << "Line 953 flow info, s_node is: " << s_node << endl; //cout << SVector.size() << " " << ReceiverVector.size() << " " << RowIndex.size() << " " << ColIndex.size() << endl; row = RowIndex[ SVector[ s_node] ]; col = ColIndex[ SVector[ s_node] ]; //cout << "got rows and columns " << row << " " << col << endl; receive_row = RowIndex[ ReceiverVector[SVector[s_node] ]]; receive_col = ColIndex[ ReceiverVector[SVector[s_node] ]]; //cout << "get receive " << receive_row << " " << receive_col << endl; if ( FlowLengthCode[row][col] == 1) { flow_distance[row][col] = flow_distance[receive_row][receive_col]+DataResolution; } else if ( FlowLengthCode[row][col] == 2 ) { flow_distance[row][col] = flow_distance[receive_row][receive_col] + diag_length; } //cout << "Flow distance: " << flow_distance << endl; } start_node = end_node; } //cout << "LINE 971 FlowInfo Flow distance complete, flow_distance is: " << endl; //cout << flow_distance << endl; LSDRaster FlowLength(NRows,NCols,XMinimum,YMinimum,DataResolution,ndv, flow_distance,GeoReferencingStrings); return FlowLength; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // // This function get the d8 slope. It points downslope from each node // // SMM 22/09/2014 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- LSDRaster LSDFlowInfo::calculate_d8_slope(LSDRaster& Elevation) { float ndv = float(NoDataValue); Array2D<float> d8_slope(NRows,NCols,ndv); // these save a bit of computational expense. float root_2 = pow(2, 0.5); float dx_root2 = root_2*DataResolution; int this_row; int this_col; int r_row; int r_col; int r_node; float dx; for (int node = 0; node<NDataNodes; node++) { // get the row and column retrieve_current_row_and_col(node,this_row,this_col); // get the distance between nodes. Depends on flow direction switch (retrieve_flow_length_code_of_node(node)) { case 0: dx = -99; break; case 1: dx = DataResolution; break; case 2: dx = dx_root2; break; default: dx = -99; break; } // get the reciever information retrieve_receiver_information(node,r_node, r_row, r_col); // now calculate the slope if (r_node == node) { d8_slope[this_row][this_col] = 0; } else { d8_slope[this_row][this_col] = (1/dx)* (Elevation.get_data_element(this_row,this_col) -Elevation.get_data_element(r_row,r_col)); } } LSDRaster d8_slope_raster(NRows,NCols,XMinimum,YMinimum,DataResolution,ndv, d8_slope,GeoReferencingStrings); return d8_slope_raster; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // // // this finds the node that is farthest upstream from a given node // // // SMM 01/06/2012 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= int LSDFlowInfo::find_farthest_upslope_node(int node, LSDRaster& DistFromOutlet) { // set the farthest node to the current node; if the node has no contributing pixels // the function will just return itself int farthest_upslope_node = node; // first get the nodes that are upslope vector<int> upslope_node_list = get_upslope_nodes(node); int row, col; float this_flow_distance; // now loop through these, looking for the farthest upstream node float farthest = 0.0; int n_upslope_nodes = upslope_node_list.size(); for (int i = 0; i<n_upslope_nodes; i++) { // get the row and col of upslope nodes row = RowIndex[ upslope_node_list[i] ]; col = ColIndex[ upslope_node_list[i] ]; // get the flow distance this_flow_distance = DistFromOutlet.get_data_element(row, col); // test if it is the farthest if (this_flow_distance > farthest) { farthest = this_flow_distance; farthest_upslope_node = upslope_node_list[i]; } } return farthest_upslope_node; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // // This function takes a list of nodes and sorts them according to a sorting // raster // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- vector<int> LSDFlowInfo::sort_node_list_based_on_raster(vector<int> node_vec, LSDRaster& SortingRaster) { // First make a vector of the data from the sorting vector vector<float> VectorisedData; vector<float> SortedData; vector<int> SortedNodes; vector<size_t> index_map; int row,col; // loop through node vec, getting the value of the raster at each node int n_nodes = int(node_vec.size()); for (int n = 0; n<n_nodes; n++) { retrieve_current_row_and_col(node_vec[n],row,col); // now get the data element VectorisedData.push_back(SortingRaster.get_data_element(row,col)); } // now sort that data using the matlab sort matlab_float_sort(VectorisedData, SortedData, index_map); // now sort the nodes based on this sorting matlab_int_reorder(node_vec, index_map, SortedNodes); return SortedNodes; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // // This function takes a list of nodes and sorts them according to a sorting // raster // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- vector<int> LSDFlowInfo::sort_node_list_based_on_raster(vector<int> node_vec, LSDIndexRaster& SortingRaster) { // First make a vector of the data from the sorting vector vector<int> VectorisedData; vector<int> SortedData; vector<int> SortedNodes; vector<size_t> index_map; int row,col; // loop through node vec, getting the value of the raster at each node int n_nodes = int(node_vec.size()); for (int n = 0; n<n_nodes; n++) { retrieve_current_row_and_col(node_vec[n],row,col); // now get the data element VectorisedData.push_back(SortingRaster.get_data_element(row,col)); } // now sort that data using the matlab sort matlab_int_sort(VectorisedData, SortedData, index_map); // now sort the nodes based on this sorting matlab_int_reorder(node_vec, index_map, SortedNodes); return SortedNodes; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // get node index of point from X and Y coordinates // this is different from the above function in that it does not snap to the nearest channel // // FJC 11/02/14 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= int LSDFlowInfo::get_node_index_of_coordinate_point(float X_coordinate, float Y_coordinate) { // Shift origin to that of dataset float X_coordinate_shifted_origin = X_coordinate - XMinimum - DataResolution*0.5; float Y_coordinate_shifted_origin = Y_coordinate - YMinimum - DataResolution*0.5; // Get row and column of point int col_point = int(X_coordinate_shifted_origin/DataResolution); int row_point = (NRows-1) - int(round(Y_coordinate_shifted_origin/DataResolution)); // Get node of point int CurrentNode; if(col_point>=0 && col_point<NCols && row_point>=0 && row_point<NRows) { CurrentNode = retrieve_node_from_row_and_column(row_point, col_point); } else { CurrentNode = NoDataValue; } return CurrentNode; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // Get vector of nodeindices from a csv file with X and Y coordinates // The csv file must have the format: ID, X, Y // // FJC 14/02/17 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= void LSDFlowInfo::get_nodeindices_from_csv(string csv_filename, vector<int>& NIs, vector<float>& X_coords, vector<float>& Y_coords) { ifstream csv_input(csv_filename.c_str()); vector<int> temp_NIs; vector<float> temp_X_Coords; vector<float> temp_Y_Coords; //initiate the string to hold the file string line_from_file; vector<string> empty_string_vec; vector<string> this_string_vec; string temp_string; // discard the first line getline(csv_input, line_from_file); // now loop through the rest of the lines while (getline(csv_input,line_from_file)) { // reset the string vec this_string_vec = empty_string_vec; // create a stringstream stringstream ss(line_from_file); while (ss.good()) { string substr; getline(ss,substr,','); // remove the spaces substr.erase(remove_if(substr.begin(), substr.end(), ::isspace), substr.end()); // remove control characters substr.erase(remove_if(substr.begin(), substr.end(), ::iscntrl), substr.end()); // add the string to the string vec this_string_vec.push_back( substr ); } // for some reason our compiler can't deal with stof so converting to doubles double X_coordinate = atof(this_string_vec[1].c_str()); double Y_coordinate = atof(this_string_vec[2].c_str()); // Shift origin to that of dataset float X_coordinate_shifted_origin = X_coordinate - XMinimum - DataResolution*0.5; float Y_coordinate_shifted_origin = Y_coordinate - YMinimum - DataResolution*0.5; // Get row and column of point int col_point = int(X_coordinate_shifted_origin/DataResolution); int row_point = (NRows-1) - int(round(Y_coordinate_shifted_origin/DataResolution)); // Get node of point int CurrentNode = NoDataValue; if(col_point>=0 && col_point<NCols && row_point>=0 && row_point<NRows) { CurrentNode = retrieve_node_from_row_and_column(row_point, col_point); } if (CurrentNode != NoDataValue) { temp_X_Coords.push_back(float(X_coordinate)); temp_Y_Coords.push_back(float(Y_coordinate)); temp_NIs.push_back(CurrentNode); } } //copy to output vectors NIs = temp_NIs; X_coords = temp_X_Coords; Y_coords = temp_Y_Coords; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // For a given node, find the nearest point in the raster that is not a NoDataValue and // snap it to the node. User must specify the search radius in pixels. // FJC 08/02/17 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= float LSDFlowInfo::snap_RasterData_to_Node(int NodeIndex, LSDRaster& InputRaster, int search_radius) { float RasterValue_at_Node; Array2D<float> InputRasterData = InputRaster.get_RasterData(); int i,j; retrieve_current_row_and_col(NodeIndex,i,j); if (InputRasterData[i][j] != NoDataValue) { // The node index already has a raster value! RasterValue_at_Node = InputRasterData[i][j]; } else { vector<float> Data_in_window; vector<float> Dists_in_window; vector<float> Dists_in_window_sorted; vector<size_t> index_map; Data_in_window.reserve(4 * search_radius); Dists_in_window.reserve(4 * search_radius); Dists_in_window_sorted.reserve(4 * search_radius); index_map.reserve(4 * search_radius); //set up the bounding box int i_min = i - search_radius; int i_max = i + search_radius; int j_min = j - search_radius; int j_max = j + search_radius; //out of bounds checking if (i_min < 0){i_min = 0;} if (j_min < 0){j_min = 0;} if (i_max > (NRows - 1)){i_max = (NRows - 1);} if (j_max > (NCols - 1)){j_max = (NCols - 1);} // only iterate over the search area. for (int row = i_min; row < i_max; ++row){ for (int col = j_min; col < j_max; ++col){ if (InputRasterData[row][col] != NoDataValue) { //get the raster data and distance at each point in the window Data_in_window.push_back(InputRasterData[row][col]); float Dist = distbetween(i,j,row,col); Dists_in_window.push_back(Dist); } } } if (int(Data_in_window.size()) != 0) { matlab_float_sort(Dists_in_window, Dists_in_window_sorted, index_map); // return the raster value at the smallest distance from the point RasterValue_at_Node = Data_in_window[index_map[0]]; } else { // if no raster values in the window then return nodatavalue RasterValue_at_Node = NoDataValue; } } return RasterValue_at_Node; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // a get sources version that uses the flow accumulation pixels // // // SMM 01/06/2012 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= vector<int> LSDFlowInfo::get_sources_index_threshold(LSDIndexRaster& FlowPixels, int threshold) { vector<int> sources; int row,col; //int n_donors; int donor_row,donor_col; int thresh_switch; int donor_node; // drop down through the stack // if the node is greater than or equal to the threshold // check all the donors // if there are no donors, then the node is a source // if none of the donors are greater than the threshold, then it also is a source for (int node = 0; node<NDataNodes; node++) { row = RowIndex[node]; col = ColIndex[node]; // see if node is greater than threshold if(FlowPixels.get_data_element(row,col)>=threshold) { //cout << "node " << node << " is a potential source, it has a value of " // << FlowPixels.get_data_element(row,col) // << "and it has " << NDonorsVector[node] <<" donors " << endl; // if it doesn't have donors, it is a source if(NDonorsVector[node] == 0) { sources.push_back(node); } else { thresh_switch = 1; // figure out where the donor nodes are, and if // the donor node is greater than the threshold for(int dnode = 0; dnode<NDonorsVector[node]; dnode++) { donor_node = DonorStackVector[ DeltaVector[node]+dnode]; donor_row = RowIndex[ donor_node ]; donor_col = ColIndex[ donor_node ]; // we don't float count base level nodes, which donate to themselves if (donor_node != node) { // if the donor node is greater than the threshold, // then this node is not a threhold if(FlowPixels.get_data_element(donor_row,donor_col)>=threshold) { thresh_switch = 0; } } //cout << "thresh_switch is: " << thresh_switch << endl; } // if all of the donors are below the threhold, this is a source if (thresh_switch == 1) { sources.push_back(node); } } } } return sources; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // a get sources version that uses a threshold of drainage area * slope^2 // // // FJC 11/02/14 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= vector<int> LSDFlowInfo::get_sources_slope_area(LSDIndexRaster& FlowPixels, LSDRaster& Slope, int threshold) { vector<int> sources; int row,col; //int n_donors; int donor_row,donor_col; int thresh_switch; int donor_node; // drop down through the stack // if the node is greater than or equal to the threshold // check all the donors // if there are no donors, then the node is a source // if none of the donors are greater than the threshold, then it also is a source for (int node = 0; node<NDataNodes; node++) { row = RowIndex[node]; col = ColIndex[node]; float area = FlowPixels.get_data_element(row,col); float slope = Slope.get_data_element(row,col); float SA_product = area * (slope*slope); // see if node is greater than threshold if(SA_product >= threshold) { //cout << "node " << node << " is a potential source, it has a value of " // << SA_product // << "and it has " << NDonorsVector[node] <<" donors " << endl; // if it doesn't have donors, it is a source if(NDonorsVector[node] == 0) { sources.push_back(node); } else { thresh_switch = 1; // figure out where the donor nodes are, and if // the donor node is greater than the threshold for(int dnode = 0; dnode<NDonorsVector[node]; dnode++) { donor_node = DonorStackVector[ DeltaVector[node]+dnode]; donor_row = RowIndex[ donor_node ]; donor_col = ColIndex[ donor_node ]; // we don't float count base level nodes, which donate to themselves if (donor_node != node) { // if the donor node is greater than the threshold, // then this node is not a threhold float area_donor = FlowPixels.get_data_element(donor_row,donor_col); float slope_donor = Slope.get_data_element(donor_row,donor_col); float SA_product_donor = area_donor * (slope_donor*slope_donor); if(SA_product_donor >= threshold) { thresh_switch = 0; } } //cout << "thresh_switch is: " << thresh_switch << endl; } // if all of the donors are below the threhold, this is a source if (thresh_switch == 1) { sources.push_back(node); } } } } return sources; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // a get sources version that uses the X and Y coordinates of mapped channel heads // // // FJC 17/02/14 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= vector<int> LSDFlowInfo::get_sources_from_mapped_channel_heads(vector<float>& X_coords, vector<float>& Y_coords) { vector<int> SourceNodes; cout << "N of channel heads: " << X_coords.size() << endl; for (unsigned int i = 0; i < X_coords.size(); i++) { int NI = get_node_index_of_coordinate_point(X_coords[i], Y_coords[i]); if (NI != NoDataValue) { SourceNodes.push_back(NI); } } return SourceNodes; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // Perform a downslope trace using D8 from a given point source (i,j). //Overwrites input parameters to return a raster of the path, the length of the //trace and the final pixel coordinates of the trace. // SWDG 20/1/14 //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= void LSDFlowInfo::D8_Trace(int i, int j, LSDIndexRaster StreamNetwork, float& length, int& receiver_row, int& receiver_col, Array2D<int>& Path){ float root_2 = 1.4142135623; Array2D<int> stnet = StreamNetwork.get_RasterData(); length = 0; int node; int reciever_node = retrieve_node_from_row_and_column(i, j); receiver_row = i; receiver_col = j; Path[receiver_row][receiver_col] = 1; while (StreamNetwork.get_data_element(receiver_row, receiver_col) == NoDataValue){ // need to do edge checking retrieve_receiver_information(reciever_node, node, receiver_row, receiver_col); Path[receiver_row][receiver_col] = 1; //update length if (retrieve_flow_length_code_of_node(reciever_node) == 1){ length += DataResolution; } else if (retrieve_flow_length_code_of_node(reciever_node) == 2){ length += (DataResolution * root_2); } reciever_node = node; } } // Move the location of the channel head downslope by a user defined distance. // Returns A vector of node indexes pointing to the moved heads. // SWDG 27/11/15 void LSDFlowInfo::MoveChannelHeadDown(vector<int> Sources, float MoveDist, vector<int>& DownslopeSources, vector<int>& FinalHeads){ float root_2 = 1.4142135623; float length; int receiver_row; int receiver_col; int node; //for loop goes here to iterate over the Sources vector for(int q=0; q<int(Sources.size());++q){ length = 0; int reciever_node = Sources[q]; while (length < MoveDist){ retrieve_receiver_information(reciever_node, node, receiver_row, receiver_col); //update length if (retrieve_flow_length_code_of_node(reciever_node) == 1){ length += DataResolution; } else if (retrieve_flow_length_code_of_node(reciever_node) == 2){ length += (DataResolution * root_2); } else if (retrieve_flow_length_code_of_node(reciever_node) == 0){break;} reciever_node = node; } DownslopeSources.push_back(reciever_node); FinalHeads.push_back(Sources[q]); } //end of for loop } // Move the location of the channel head upslope by a user defined distance. // Returns A vector of node indexes pointing to the moved heads. // SWDG 27/11/15 void LSDFlowInfo::MoveChannelHeadUp(vector<int> Sources, float MoveDist, LSDRaster DEM, vector<int>& UpslopeSources, vector<int>& FinalHeads){ float root_2 = 1.4142135623; float length; Array2D<float> Elevation = DEM.get_RasterData(); int new_node; int new_i; int new_j; //for loop goes here to iterate over the Sources vector for(int q=0; q<int(Sources.size());++q){ length = 0; int i; int j; retrieve_current_row_and_col(Sources[q], i, j); //test for channel heads at edges if (i == 0 || i == NRows - 1 || j == 0 || j == NCols - 1){ cout << "Hit an edge, skipping" << endl; } else{ while (length < MoveDist){ float currentElevation; int Direction; //1 is cardinal 2 is diagonal //find the neighbour with the maximum Elevation currentElevation = Elevation[i][j]; //top left if(currentElevation < Elevation[i-1][j-1]){ currentElevation = Elevation[i-1][j-1]; new_i = i-1; new_j = j-1; Direction = 2; } //top if(currentElevation < Elevation[i][j-1]){ currentElevation = Elevation[i][j-1]; new_i = i; new_j = j-1; Direction = 1; } //top right if(currentElevation < Elevation[i+1][j-1]){ currentElevation = Elevation[i+1][j-1]; new_i = i+1; new_j = j-1; Direction = 2; } //right if(currentElevation < Elevation[i+1][j]){ currentElevation = Elevation[i+1][j]; new_i = i+1; new_j = j; Direction = 1; } //botom right if(currentElevation < Elevation[i+1][j+1]){ currentElevation = Elevation[i+1][j+1]; new_i = i+1; new_j = j+1; Direction = 2; } //bottom if(currentElevation < Elevation[i][j+1]){ currentElevation = Elevation[i][j+1]; new_i = i; new_j = j+1; Direction = 1; } //bottom left if(currentElevation < Elevation[i-1][j+1]){ currentElevation = Elevation[i-1][j+1]; new_i = i-1; new_j = j+1; Direction = 2; } //left if(currentElevation < Elevation[i-1][j]){ currentElevation = Elevation[i-1][j]; new_i = i-1; new_j = j; Direction = 1; } //test that we have not hit the ridge //this will exit the loop and add the final visited //node to the upper soureces vector if (currentElevation == Elevation[i][j]){ cout << "Warning, unable to move channel head " << Sources[q] << " up by user defined distance" << endl; break; } //update length if (Direction == 1){ length += DataResolution; } else if (Direction == 2){ length += (DataResolution * root_2); } i = new_i; j = new_j; } } new_node = retrieve_node_from_row_and_column(i,j); UpslopeSources.push_back(new_node); FinalHeads.push_back(Sources[q]); } //end of for loop } void LSDFlowInfo::HilltopFlowRoutingOriginal(LSDRaster Elevation, LSDRaster Hilltops, LSDRaster Slope, LSDRaster Aspect, LSDIndexRaster StreamNetwork) { //Declare parameters int i,j,a,b; //double X,Y; float dem_res = DataResolution; //float mean_slope, relief; int ndv = NoDataValue; double slope_total, length, d; int flag, count; double PI = 3.14159265; double degs, degs_old, degs_new, theta; double s_local, s_edge; double xo, yo, xi, yi, temp_yo1, temp_yo2, temp_xo1, temp_xo2; // a direction flag numbered 1,2,3,4 for E,S,W,N respectively int dir; double xmin = XMinimum; double ymin = YMinimum; double ymax = ymin + NRows*dem_res; //double xmax = xmin + NCols*dem_res; //Declare Arrays //Get data arrays from LSDRasters Array2D<float> zeta = Elevation.get_RasterData(); //elevation Array2D<int> stnet = StreamNetwork.get_RasterData(); // stream network Array2D<float> aspect = Aspect.get_RasterData(); //aspect Array2D<float> hilltops = Hilltops.get_RasterData(); //hilltops Array2D<float> slope = Slope.get_RasterData(); //hilltops Array2D<float> rads(NRows,NCols); Array2D<float> path(NRows, NCols); Array2D<float> blank(NRows,NCols,NoDataValue); int vec_size = 1000000; Array1D<double> easting(NCols); Array1D<double> northing(NRows); Array1D<double> east_vec(vec_size); Array1D<double> north_vec(vec_size); //for creating file names for hillslope profiles string file_part_1 = "prof_"; string file_part_2; string file_part_3 = ".txt"; string filename; char filename_c[256]; //calculate northing and easting for (i=0;i<NRows;++i){ northing[i] = ymax - i*dem_res - 0.5; } for (j=0;j<NCols;++j){ easting[j] = xmin + j*dem_res + 0.5; } int ht_count = 0; // cycle through study area, find hilltops and trace downstream for (i=1; i<NRows-1; ++i) { for (j=1; j<NCols-1; ++j) { // ignore edge cells and non-hilltop cells // route initial node by aspect and get outlet coordinates if (hilltops[i][j] != ndv) { //reset slope, length, hillslope flag and pixel counter slope_total = 0; length = 0; flag = true; count = 1; //copt blank raster to map hillslope trace path = blank.copy(); //update hilltop counter ++ht_count; //get aspect in radians degs = aspect[i][j]; theta = (M_PI/180.)*((-1*degs)+90.); //setup indices a = i; b = j; path[a][b] = 1; //add first pixel to easting northing vectors east_vec[0] = easting[b]; north_vec[0] = northing[a]; //get local slope s_local = slope[a][b]; //test direction, calculate outlet coordinates and update indicies // easterly, dir == 1 if (degs >= 45 && degs < 135) { //find location where trace exits the cell and distance xo = 1., yo = (1.+tan(theta))/2.; d = abs(1./(2.*cos(theta))); //transmit to next cell over xi = 0., yi = yo; dir = 1; //add to vector east_vec[count] = easting[b] + 0.5*dem_res; north_vec[count] = northing[a] + yo - 0.5*dem_res; //increment indices ++b; //check we're not right in the corner! if (yi == 0) yi = 0.00001; else if (yi == 1) yi = 1 - 0.00001; } //southerly else if (degs >= 135 && degs < 225) { //find location where trace exits the cell and distance xo = (1-(1/tan(theta)))/2, yo = 0; d = abs(1/(2*cos((PI/2)-theta))); //transmit to next cell over xi = xo, yi = 1; dir = 2; //add to vector east_vec[count] = easting[b] + xo - 0.5*dem_res; north_vec[count] = northing[a] - 0.5*dem_res; //increment indices ++a; //check we're not right in the corner! if (xi == 0) xi = 0.00001; else if (xi == 1) xi = 1 - 0.00001; } // westerly else if (degs >= 225 && degs < 315) { //find location where trace exits the cell and distance xo = 0, yo = (1-tan(theta))/2; d = abs(1/(2*cos(theta))); //transmit to next cell over xi = 1, yi = yo; dir = 3; //add to vector east_vec[count] = easting[b] -0.5*dem_res; north_vec[count] = northing[a] + yo - 0.5*dem_res; //increment indices --b; //check we're not right in the corner! if (yi == 0) yi = 0.00001; else if (yi == 1) yi = 1 - 0.00001; } //northerly else if (degs >= 315 || degs < 45) { //find location where trace exits the cell and distance xo = (1+(1/tan(theta)))/2, yo = 1; d = abs(1/(2*cos((PI/2) - theta))); //transmit to next cell over xi = xo, yi = 0; dir = 4; //add to vector east_vec[count] = easting[b] + xo - 0.5*dem_res; north_vec[count] = northing[a] + 0.5*dem_res; //increment indices --a; //check we're not right in the corner! if (xi == 0) xi = 0.00001; else if (xi == 1) xi = 1 - 0.00001; } else { cout << "FATAL ERROR, Kinematic routing algorithm encountered null aspect value" << endl; exit(EXIT_FAILURE); } //collect slopes and totals weighted by path length //slope_total += s_local*d; //length += d; s_local = slope[a][b]; //continue trace until a stream node is encountered while (flag == true) { path[a][b] = 1; degs_old = degs; degs_new = aspect[a][b]; theta = (M_PI/180.)*((-1*degs_new)+90.); ++ count; //Test for perimeter flow paths if ((dir == 1 && degs_new > 0 && degs_new < 180) || (dir == 2 && degs_new > 90 && degs_new < 270) || (dir == 3 && degs_new > 180 && degs_new < 360) || ((dir == 4 && degs_new > 270) || (dir == 4 && degs_new < 90))) { //DO NORMAL FLOW PATH //set xo, yo to 0 and 1 in turn and test for true outlet (xi || yi == 0 || 1) temp_yo1 = yi + (1-xi)*tan(theta); // xo = 1 temp_xo1 = xi + (1-yi)*(1/tan(theta)); // yo = 1 temp_yo2 = yi - xi*tan(theta); // xo = 0 temp_xo2 = xi - yi*(1/tan(theta)); // yo = 0 // can't outlet at same point as inlet if (dir == 1) temp_yo2 = -1; else if (dir == 2) temp_xo1 = -1; else if (dir == 3) temp_yo1 = -1; else if (dir == 4) temp_xo2 = -1; s_local = slope[a][b]; if (temp_yo1 <= 1 && temp_yo1 > 0) { xo = 1, yo = temp_yo1; d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 0, yi = yo, dir = 1; east_vec[count] = easting[b] + 0.5*dem_res; north_vec[count] = northing[a] + yo - 0.5*dem_res; ++b; if (xi== 0 && yi == 0) yi = 0.00001; else if (xi== 0 && yi == 1) yi = 1 - 0.00001; } else if (temp_xo2 <= 1 && temp_xo2 > 0) { xo = temp_xo2, yo = 0; d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 1, dir = 2; east_vec[count] = easting[b] + xo - 0.5*dem_res; north_vec[count] = northing[a] - 0.5*dem_res; ++a; if (xi== 0 && yi == 1) xi = 0.00001; else if (xi== 1 && yi == 1) xi = 1 - 0.00001; } else if (temp_yo2 <= 1 && temp_yo2 > 0) { xo = 0, yo = temp_yo2; d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1, yi = yo, dir = 3; east_vec[count] = easting[b] -0.5*dem_res; north_vec[count] = northing[a] + yo - 0.5*dem_res; --b; if (xi== 1 && yi == 0) yi = 0.00001; else if (xi== 1 && yi == 1) yi = 1 - 0.00001; } else if (temp_xo1 <= 1 && temp_xo1 > 0) { xo = temp_xo1, yo = 1; d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 0, dir = 4; east_vec[count] = easting[b] + xo - 0.5*dem_res; north_vec[count] = northing[a] + 0.5*dem_res; --a; if (xi == 0 && yi == 0) xi = 0.00001; else if (xi== 1 && yi == 0) xi = 1 - 0.00001; } slope_total += s_local*d; } else { // ROUTE ALONG EDGES if (dir == 1) { if (degs_old <= 90 || degs_new >= 270) { xo = 0.00001, yo = 1; s_edge = abs(s_local*sin(theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 1-yo; dir = 4; east_vec[count] = easting[b] + xo - 0.5*dem_res; north_vec[count] = northing[a] + 0.5*dem_res; --a; } else if (degs_old > 90 && degs_new < 270) { xo = 0.00001, yo = 0; s_edge = abs(s_local*sin((PI/2)-theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 1-yo; dir = 2; east_vec[count] = easting[b] + xo - 0.5*dem_res; north_vec[count] = northing[a] - 0.5*dem_res; ++a; } else { cout << "Flow unable to route N or S" << endl; exit(EXIT_FAILURE); } } else if (dir == 2) { if (degs_old <= 180 && degs_new >= 0) { xo = 1, yo = 1-0.00001; s_edge = abs(s_local*sin((2/PI)-theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1-xo, yi = yo; dir = 1; east_vec[count] = easting[b] + 0.5*dem_res; north_vec[count] = northing[a] + yo - 0.5*dem_res; ++b; } else if (degs_old > 180 && degs_new < 360) { xo = 0, yo = 1-0.00001; s_edge = abs(s_local*sin(theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1-xo, yi = yo; dir = 3; east_vec[count] = easting[b] -0.5*dem_res; north_vec[count] = northing[a] + yo - 0.5*dem_res; --b; } else { cout << "Flow unable to route E or W" << endl; exit(EXIT_FAILURE); } } else if (dir == 3) { if (degs_old <= 270 && degs_new >= 90) { xo = 1-0.00001, yo = 0; s_edge = abs(s_local*sin(theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 1-yo; dir = 2; east_vec[count] = easting[b] + xo - 0.5*dem_res; north_vec[count] = northing[a] - 0.5*dem_res; ++a; } else if (degs_old > 270 || degs_new < 90) { xo = 1-0.00001, yo = 1; s_edge = abs(s_local*sin((2/PI) - theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 1- yo; dir = 4; east_vec[count] = easting[b] + xo - 0.5*dem_res; north_vec[count] = northing[a] + 0.5*dem_res; --a; } else { cout << "Flow unable to route N or S" << endl; exit(EXIT_FAILURE); } } else if (dir == 4) { if (degs_old <= 360 && degs_new >= 180) { xo = 0, yo = 0.00001; s_edge = abs(s_local*sin((PI/2) - theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1-xo, yi = yo; dir = 3; east_vec[count] = easting[b] -0.5*dem_res; north_vec[count] = northing[a] + yo - 0.5*dem_res; --b; } else if (degs_old > 0 && degs_new < 180) { xo = 1, yo = 0.00001; s_edge = abs(s_local*sin(theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1-xo, yi = yo; dir = 1; east_vec[count] = easting[b] + 0.5*dem_res; north_vec[count] = northing[a] + yo - 0.5*dem_res; ++b; } else { cout << "Flow unable to route E or W" << endl; exit(EXIT_FAILURE); } } slope_total += s_edge*d; } length += d; degs = degs_new; //cout << "[a][b]: " << a << " " << b << endl; if (a <= 0 || b <= 0 || a >= NRows-1 || b >= NCols-1) flag = false; else if (stnet[a][b] != ndv || path[a][b] == 1) flag = false; } //if trace finished at a stream, print hillslope info. if (a <= 0 || b <= 0 || a >= NRows-1 || b >= NCols-1) continue; else { if (path[a][b] == 1) { cout << "Didn't make it to a channel!" << endl; } // // PRINT TO FILE Cht Sbar Relief Lh // X = xmin + j*dem_res; // Y = ymin + (NRows-i)*dem_res; // relief = zeta[i][j] - zeta[a][b]; // length = length*dem_res; // mean_slope = slope_total/(length/dem_res); // ofs << X << " " << Y << " " << seg[i][j] << " " // << cht[i][j] << " " << mean_slope << " " // << relief << " " << length << " " << "/n"; //area[a][b] << "\n"; //PRINT FILE OF PATH NODES FOR EACH HILLSLOPE VECTOR stringstream s; s << ht_count; file_part_2 = s.str(); filename = file_part_1; filename.append(file_part_2), filename.append(file_part_3); strcpy(filename_c,filename.c_str()); ofstream prof_out; prof_out.open(filename_c); prof_out << "Easting " << "Northing" << endl; prof_out.precision(10); for (int c=0;c<count;++c) { prof_out << east_vec[c] << " " << north_vec[c] << endl; } prof_out.close(); } } //return condition for debugging purposes only //if (ht_count > 50) return; } } } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // Hilltop flow routing code built around original code from Martin Hurst. Based on // Lea (1992), with improvements discussed by Tarboton (1997) and a solution to the // problem of looping flow paths implemented. // // This code is SLOW but robust, a refactored version may appear, but there may not be // enough whisky in Scotland to support that endeavour. // // The algorithm now checks for local uphill flows and in the case of identifying one, // D8 flow path is used to push the flow into the centre of the steepest downslope // cell, at which point the trace is restarted. The same technique is used to cope // with self intersections of the flow path. These problems are not solved in the // original paper and I think they are caused at least in part by the high resolution // topogrpahy we are using. // // The code is also now built to take a d infinity flow direction raster instead of an // aspect raster. See Tarboton (1997) for discussions on why this is the best solution. // // The Basins input raster is used to code each hilltop into a basin to allow basin // averaging to take place. // // The final 5 parameters are used to set up printing flow paths to files for visualisation, // if this is not needed simply pass in false to the two boolean switches and empty variables for the // others, and the code will run as normal. // // The structure of the returned vector< Array2D<float> > is as follows: // [0] Hilltop Network coded with stream ID // [1] Hillslope Lengths // [2] Slope // [3] Relief // // SWDG 12/2/14 //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= vector< Array2D<float> > LSDFlowInfo::HilltopFlowRouting(LSDRaster Elevation, LSDRaster Hilltops, LSDRaster Slope, LSDIndexRaster StreamNetwork, LSDRaster Aspect, string Prefix, LSDIndexRaster Basins, LSDRaster PlanCurvature, bool print_paths_switch, int thinning, string trace_path, bool basin_filter_switch, vector<int> Target_Basin_Vector){ //Declare parameters int i,j; int a = 0; int b = 0; float X,Y; float mean_slope, relief; float length, d; int flag; int count = 0; int DivergentCountFlag = 0; //Flag used to count the number of divergent cells encountered in a trace int PlanarCountFlag; float PI = 3.14159265; float degs, degs_new, theta; float s_local, s_edge; float xo, yo, xi, yi, temp_yo1, temp_yo2, temp_xo1, temp_xo2; bool skip_trace; //flag used to skip traces where no path to a stream can be found. Will only occur on noisy, raw topography float E_Star = 0; float R_Star = 0; float EucDist = 0; //debugging counters int ns_count = 0; int s_count = 0; int neg_count = 0; int edge_count = 0; int ht_count = 0; // a direction flag numbered 1,2,3,4 for E,S,W,N respectively int dir; float ymax = YMinimum + NRows*DataResolution; //Get data arrays from LSDRasters Array2D<float> zeta = Elevation.get_RasterData(); //elevation Array2D<int> stnet = StreamNetwork.get_RasterData(); // stream network Array2D<float> aspect = Aspect.get_RasterData(); //aspect Array2D<float> hilltops = Hilltops.get_RasterData(); //hilltops Array2D<float> slope = Slope.get_RasterData(); //hilltops Array2D<int> basin = Basins.get_RasterData(); //basins //empty arrays for data to be stored in Array2D<float> rads(NRows,NCols); Array2D<float> path(NRows, NCols, 0.0); Array2D<float> blank(NRows, NCols, 0.0); Array2D<float> RoutedHilltops(NRows,NCols,NoDataValue); Array2D<float> HillslopeLength_Array(NRows,NCols,NoDataValue); Array2D<float> Slope_Array(NRows,NCols,NoDataValue); Array2D<float> Relief_Array(NRows,NCols,NoDataValue); //vector to store the output data arrays in one vector that can be returned vector< Array2D<float> > OutputArrays; int vec_size = 1000000; Array1D<double> easting(NCols); Array1D<double> northing(NRows); Array1D<double> east_vec(vec_size); Array1D<double> north_vec(vec_size); ofstream ofs; //create the output filename from the user supplied filename prefix stringstream ss_filename; ss_filename << Prefix << "_HilltopData.csv"; ofs.open(ss_filename.str().c_str()); if( ofs.fail() ){ cout << "\nFATAL ERROR: unable to write to " << ss_filename.str() << endl; exit(EXIT_FAILURE); } ofs << "X,Y,i,j,hilltop_id,S,R,Lh,BasinID,a,b,StreamID,HilltopSlope,DivergentCount\n"; //calculate northing and easting for (i=0;i<NRows;++i){ northing[i] = ymax - i*DataResolution - 0.5; } for (j=0;j<NCols;++j){ easting[j] = XMinimum + j*DataResolution + 0.5; } //convert aspects to radians with east as theta = 0/2*pi for (i=0; i<NRows; ++i) { for (j=0; j<NCols; ++j) { //convert aspects to radians with east as theta = 0/2*pi if (rads[i][j] != NoDataValue) rads[i][j] = BearingToRad(aspect[i][j]); } } // cycle through study area, find hilltops and trace downstream for (i=1; i<NRows-1; ++i) { cout << flush << "\tRow: " << i << " of = " << NRows-1 << " \r"; for (j=1; j<NCols-1; ++j) { // ignore edge cells and non-hilltop cells // route initial node by aspect and get outlet coordinates if (hilltops[i][j] != NoDataValue) { length = 0; flag = true; count = 1; path = blank.copy(); DivergentCountFlag = 0; //initialise count of divergent cells in trace PlanarCountFlag = 0; skip_trace = false; //initialise skip trace flag as false, will only be switched if no path to stream can be found. Very rare. E_Star = 0; R_Star = 0; EucDist = 0; ++ht_count; degs = aspect[i][j]; theta = rads[i][j]; a = i; b = j; path[a][b] += 1; east_vec[0] = easting[b]; north_vec[0] = northing[a]; s_local = slope[a][b]; //test direction, calculate outlet coordinates and update indicies // easterly if (degs >= 45 && degs < 135) { //cout << "\neasterly" << endl; xo = 1, yo = (1+tan(theta))/2; d = abs(1/(2*cos(theta))); xi = 0, yi = yo; dir = 1; east_vec[count] = easting[b] + 0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; ++b; if (yi == 0) yi = 0.00001; else if (yi == 1) yi = 1 - 0.00001; } //southerly else if (degs >= 135 && degs < 225) { //cout << "\nsoutherly" << endl; xo = (1-(1/tan(theta)))/2, yo = 0; d = abs(1/(2*cos((PI/2)-theta))); xi = xo, yi = 1; dir = 2; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] - 0.5*DataResolution; ++a; if (xi == 0) xi = 0.00001; else if (xi == 1) xi = 1 - 0.00001; } // westerly else if (degs >= 225 && degs < 315) { xo = 0, yo = (1-tan(theta))/2; d = abs(1/(2*cos(theta))); xi = 1, yi = yo; dir = 3; east_vec[count] = easting[b] -0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; --b; if (yi == 0) yi = 0.00001; else if (yi == 1) yi = 1 - 0.00001; } //northerly else if (degs >= 315 || degs < 45) { xo = (1+(1/tan(theta)))/2, yo = 1; d = abs(1/(2*cos((PI/2) - theta))); xi = xo, yi = 0; dir = 4; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] + 0.5*DataResolution; --a; if (xi == 0) xi = 0.00001; else if (xi == 1) xi = 1 - 0.00001; } else { cout << "FATAL ERROR, Kinematic routing algorithm enountered null aspect value" << endl; exit(EXIT_FAILURE); } //collect slopes and totals weighted by path length length += d; s_local = slope[a][b]; //continue trace until a stream node is encountered while (flag == true && a > 0 && a < NRows-1 && b > 0 && b < NCols-1) { //added boudary checking to catch cells which flow off the edge of the DEM tile. path[a][b] += 1; degs_new = aspect[a][b]; theta = rads[a][b]; ++count; //Test for perimeter flow paths if ((dir == 1 && degs_new > 0 && degs_new < 180) || (dir == 2 && degs_new > 90 && degs_new < 270) || (dir == 3 && degs_new > 180 && degs_new < 360) || ((dir == 4 && degs_new > 270) || (dir == 4 && degs_new < 90))) { //DO NORMAL FLOW PATH //set xo, yo to 0 and 1 in turn and test for true outlet (xi || yi == 0 || 1) temp_yo1 = yi + (1-xi)*tan(theta); // xo = 1 temp_xo1 = xi + (1-yi)*(1/tan(theta)); // yo = 1 temp_yo2 = yi - xi*tan(theta); // xo = 0 temp_xo2 = xi - yi*(1/tan(theta)); // yo = 0 // can't outlet at same point as inlet if (dir == 1) temp_yo2 = -1; else if (dir == 2) temp_xo1 = -1; else if (dir == 3) temp_yo1 = -1; else if (dir == 4) temp_xo2 = -1; s_local = slope[a][b]; if (temp_yo1 <= 1 && temp_yo1 > 0) { xo = 1, yo = temp_yo1; d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 0, yi = yo, dir = 1; east_vec[count] = easting[b] + 0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; ++b; if (xi== 0 && yi == 0) yi = 0.00001; else if (xi== 0 && yi == 1) yi = 1 - 0.00001; } else if (temp_xo2 <= 1 && temp_xo2 > 0) { xo = temp_xo2, yo = 0; d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 1, dir = 2; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] - 0.5*DataResolution; ++a; if (xi== 0 && yi == 1) xi = 0.00001; else if (xi== 1 && yi == 1) xi = 1 - 0.00001; } else if (temp_yo2 <= 1 && temp_yo2 > 0) { xo = 0, yo = temp_yo2; d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1, yi = yo, dir = 3; east_vec[count] = easting[b] -0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; --b; if (xi== 1 && yi == 0) yi = 0.00001; else if (xi== 1 && yi == 1) yi = 1 - 0.00001; } else if (temp_xo1 <= 1 && temp_xo1 > 0) { xo = temp_xo1, yo = 1; d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 0, dir = 4; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] + 0.5*DataResolution; --a; if (xi == 0 && yi == 0) xi = 0.00001; else if (xi== 1 && yi == 0) xi = 1 - 0.00001; } } else { // ROUTE ALONG EDGES if (dir == 1) { if (degs_new <= 90 || degs_new >= 270) { //secondary compenent of flow is north xo = 0.00001, yo = 1; s_edge = abs(s_local*sin(theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 1-yo; dir = 4; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] + 0.5*DataResolution; --a; } else if (degs_new > 90 && degs_new < 270) { //secondary component is south xo = 0.00001, yo = 0; s_edge = abs(s_local*sin((PI/2)-theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 1-yo; dir = 2; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] - 0.5*DataResolution; ++a; } else { cout << "Flow unable to route N or S " << endl; //something has gone very wrong... cout << "Trace skipped.\n" << endl; skip_trace = true; //exit(EXIT_FAILURE); } } else if (dir == 2) { if (degs_new >= 0 && degs_new <= 180) { //secondary component is East xo = 1, yo = 1-0.00001; s_edge = abs(s_local*sin((2/PI)-theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1-xo, yi = yo; dir = 1; east_vec[count] = easting[b] + 0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; ++b; } else if (degs_new > 180 && degs_new <= 360) { //secondary component is West xo = 0, yo = 1-0.00001; s_edge = abs(s_local*sin(theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1-xo, yi = yo; dir = 3; east_vec[count] = easting[b] -0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; --b; } else { cout << "Flow unable to route E or W" << endl; //something has gone very wrong... cout << "Trace skipped.\n" << endl; skip_trace = true; //exit(EXIT_FAILURE); } } else if (dir == 3) { if (degs_new >= 90 && degs_new <= 270) { //secondary component is South xo = 1-0.00001, yo = 0; s_edge = abs(s_local*sin(theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 1-yo; dir = 2; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] - 0.5*DataResolution; ++a; } else if (degs_new > 270 || degs_new < 90) { //secondary component is North xo = 1-0.00001, yo = 1; s_edge = abs(s_local*sin((2/PI) - theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 1- yo; dir = 4; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] + 0.5*DataResolution; --a; } else { cout << "Flow unable to route N or S" << endl; //something has gone very wrong... cout << "Trace skipped.\n" << endl; skip_trace = true; //exit(EXIT_FAILURE); } } else if (dir == 4) { if (degs_new >= 180 && degs_new <= 360) { //secondary component is West xo = 0, yo = 0.00001; s_edge = abs(s_local*sin((PI/2) - theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1-xo, yi = yo; dir = 3; east_vec[count] = easting[b] -0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; --b; } else if (degs_new >= 0 && degs_new < 180) { //secondary component is East xo = 1, yo = 0.00001; s_edge = abs(s_local*sin(theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1-xo, yi = yo; dir = 1; east_vec[count] = easting[b] + 0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; ++b; } else { cout << "Flow unable to route E or W" << endl; //something has gone very wrong... cout << "Trace skipped.\n" << endl; skip_trace = true; //exit(EXIT_FAILURE); } } } if (path[a][b] < 1){ // only update length on 'first slosh' length += d; } else if (path[a][b] >= 3){ //update the skip trace flag so we can categorise each trace skip_trace = true; } degs = degs_new; // test for plan curvature here and set a flag if flow is divergent or convergent but continue trace regardless // The larger the counter the more convergent or divergent the trace is if (abs(PlanCurvature.get_data_element(a,b)) > (0.001)){ ++DivergentCountFlag; } else { ++PlanarCountFlag; } if (a == 0 || b == 0 || a == NRows-1 || b == NCols-1 || stnet[a][b] != NoDataValue || stnet[a-1][b-1] != NoDataValue || stnet[a][b-1] != NoDataValue || stnet[a+1][b-1] != NoDataValue || stnet[a+1][b] != NoDataValue || stnet[a+1][b+1] != NoDataValue || stnet[a][b+1] != NoDataValue || stnet[a-1][b+1] != NoDataValue || stnet[a-1][b] != NoDataValue || path[a][b] >= 3 || skip_trace == true) flag = false; } if (a == 0 || b == 0 || a == NRows-1 || b == NCols-1 ){ // avoid going out of bounds. // this is caused by having a hilltop on the first row or col away from the border // eg i or j == 1 or nrows/ncols - 2 and flowing towards the edge. // can fix with a test here for if streamnet[a][b] != NDV otherwise trace will fail *correctly* ++edge_count; } else { //if trace finished at a stream, print hillslope info. if (stnet[a][b] != NoDataValue || stnet[a-1][b-1] != NoDataValue || stnet[a][b-1] != NoDataValue || stnet[a+1][b-1] != NoDataValue || stnet[a+1][b] != NoDataValue || stnet[a+1][b+1] != NoDataValue || stnet[a][b+1] != NoDataValue || stnet[a-1][b+1] != NoDataValue || stnet[a-1][b] != NoDataValue) { path[a][b] = 1; ++s_count; X = XMinimum + j*DataResolution; Y = YMinimum - (NRows-i)*DataResolution; relief = zeta[i][j] - zeta[a][b]; mean_slope = relief/(length * DataResolution); // update arrays with the current metrics RoutedHilltops[i][j] = 1; HillslopeLength_Array[i][j] = (length * DataResolution); Slope_Array[i][j] = mean_slope; Relief_Array[i][j] = relief; //calculate an E* and R* Value assuming S_c of 0.8 E_Star = (2.0 * abs(hilltops[i][j])*(length*DataResolution))/0.8; R_Star = relief/((length*DataResolution)*0.8); //calulate the Euclidean distance between the start and end points of the trace EucDist = sqrt((pow(((i+0.5)-(a+yo)),2) + pow(((j+0.5)-(b+xo)),2))) * DataResolution; if (relief > 0){ ofs << X << "," << Y << "," << i << "," << j << "," << hilltops[i][j] << "," << mean_slope << "," << relief << "," << length*DataResolution << "," << basin[i][j] << "," << a << "," << b << "," << stnet[a][b] << "," << slope[i][j] << "," << DivergentCountFlag << "," << PlanarCountFlag << "," << E_Star << "," << R_Star << "," << EucDist << "\n"; } else { ++neg_count; } } else{ //unable to route using aspects //this will encompass skipped traces ofs << "fail: " << a << " " << b << " " << i << " " << j << endl; ++ns_count; } } //This block checks the various path printing options and writes the data out accordingly if (print_paths_switch == true){ if (ht_count % thinning == 0){ if (hilltops[i][j] != NoDataValue && skip_trace == false){ //check that the current i,j tuple corresponds to a hilltop, ie there is actually a trace to write to file, and check that the trace was valid. //create stringstream object to create filename ofstream pathwriter; //create the output filename from the user supplied path stringstream ss_path; ss_path << trace_path << i << "_" << j << "_trace.txt"; pathwriter.open(ss_path.str().c_str()); if(pathwriter.fail() ){ cout << "\nFATAL ERROR: unable to write to " << ss_path.str() << endl; exit(EXIT_FAILURE); } for (int v = 0; v < count+1; ++v){ if (basin_filter_switch == false){ pathwriter << setiosflags(ios::fixed) << setprecision(7) << east_vec[v] << " " << north_vec[v] << " " << DivergentCountFlag << " " << length << " " << PlanarCountFlag << " " << E_Star << " " << R_Star << " " << EucDist << endl; } else if (basin_filter_switch == true && find(Target_Basin_Vector.begin(), Target_Basin_Vector.end(), basin[a][b]) != Target_Basin_Vector.end() && find(Target_Basin_Vector.begin(), Target_Basin_Vector.end(), basin[i][j]) != Target_Basin_Vector.end()){ //is this correct? evaulating to not equal one past the end of the vector should equal that the value is found pathwriter << setiosflags(ios::fixed) << setprecision(7) << east_vec[v] << " " << north_vec[v] << " " << DivergentCountFlag << " " << length << " " << PlanarCountFlag << " " << E_Star << " " << R_Star << " " << EucDist << endl; } } pathwriter.close(); } } } // End of path printing logic } } //for loop i,j } ofs.close(); //add the data arrays to the output vector OutputArrays.push_back(RoutedHilltops); OutputArrays.push_back(HillslopeLength_Array); OutputArrays.push_back(Slope_Array); OutputArrays.push_back(Relief_Array); //Print debugging info to screen cout << endl; //push output onto new line cout << "Hilltop count: " << ht_count << endl; cout << "Stream count: " << s_count << endl; cout << "Fail count: " << ns_count << endl; cout << "Uphill count: " << neg_count << endl; cout << "Edge count: " << edge_count << endl; return OutputArrays; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // Hilltop flow routing code built around original code from Martin Hurst. Based on // Lea (1992), with improvements discussed by Tarboton (1997) and a solution to the // problem of looping flow paths implemented. // // THIS VERSION OF THE CODE RETAINS THE FLOODING METHOD TO ALLOW TRACES TO BE USED // ON RAW TOPOGRPAHY TO GET EVENT SCALE HILLSLOPE LENGTHS WITH NO SMOOTHING. IN // MOST CASES USE THE MAIN METHOD, TO ANALYSE SEDIMENT TRANSPORT OVER GEOMORPHIC TIME. // // This code is SLOW but robust, a refactored version may appear, but there may not be // enough whisky in Scotland to support that endeavour. // // The algorithm now checks for local uphill flows and in the case of identifying one, // D8 flow path is used to push the flow into the centre of the steepest downslope // cell, at which point the trace is restarted. The same technique is used to cope // with self intersections of the flow path. These problems are not solved in the // original paper and I think they are caused at least in part by the high resolution // topogrpahy we are using. // // The code is also now built to take a d infinity flow direction raster instead of an // aspect raster. See Tarboton (1997) for discussions on why this is the best solution. // // The Basins input raster is used to code each hilltop into a basin to allow basin // averaging to take place. // // The final 5 parameters are used to set up printing flow paths to files for visualisation, // if this is not needed simply pass in false to the two boolean switches and empty variables for the // others, and the code will run as normal. // // The structure of the returned vector< Array2D<float> > is as follows: // [0] Hilltop Network coded with stream ID // [1] Hillslope Lengths // [2] Slope // [3] Relief // // SWDG 12/2/14 //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= vector< Array2D<float> > LSDFlowInfo::HilltopFlowRouting_RAW(LSDRaster Elevation, LSDRaster Hilltops, LSDRaster Slope, LSDIndexRaster StreamNetwork, LSDRaster D_inf_Flowdir, string Prefix, LSDIndexRaster Basins, LSDRaster PlanCurvature, bool print_paths_switch, int thinning, string trace_path, bool basin_filter_switch, vector<int> Target_Basin_Vector){ //Declare parameters int i,j; int a = 0; int b = 0; float X,Y; float mean_slope, relief; float length, d; int flag; int count = 0; int DivergentCountFlag = 0; //Flag used to count the number of divergent cells encountered in a trace int PlanarCountFlag = 0; float PI = 3.14159265; float degs, degs_old, degs_new, theta; float s_local, s_edge; float xo, yo, xi, yi, temp_yo1, temp_yo2, temp_xo1, temp_xo2; bool skip_trace; //flag used to skip traces where no path to a stream can be found. Will only occur on noisy, raw topography float E_Star = 0; float R_Star = 0; float EucDist = 0; //debugging counters int ns_count = 0; int s_count = 0; int neg_count = 0; int edge_count = 0; int ht_count = 0; // a direction flag numbered 1,2,3,4 for E,S,W,N respectively int dir; float ymax = YMinimum + NRows*DataResolution; //Get data arrays from LSDRasters Array2D<float> zeta = Elevation.get_RasterData(); //elevation Array2D<int> stnet = StreamNetwork.get_RasterData(); // stream network Array2D<float> aspect = D_inf_Flowdir.get_RasterData(); //aspect Array2D<float> hilltops = Hilltops.get_RasterData(); //hilltops Array2D<float> slope = Slope.get_RasterData(); //hilltops Array2D<int> basin = Basins.get_RasterData(); //basins //empty arrays for data to be stored in Array2D<float> rads(NRows,NCols); Array2D<float> path(NRows, NCols, 0.0); Array2D<float> blank(NRows, NCols, 0.0); Array2D<float> RoutedHilltops(NRows,NCols,NoDataValue); Array2D<float> HillslopeLength_Array(NRows,NCols,NoDataValue); Array2D<float> Slope_Array(NRows,NCols,NoDataValue); Array2D<float> Relief_Array(NRows,NCols,NoDataValue); //vector to store the output data arrays in one vector that can be returned vector< Array2D<float> > OutputArrays; int vec_size = 1000000; Array1D<double> easting(NCols); Array1D<double> northing(NRows); Array1D<double> east_vec(vec_size); Array1D<double> north_vec(vec_size); ofstream ofs; //create the output filename from the user supplied filename prefix stringstream ss_filename; ss_filename << Prefix << "_HilltopData_RAW.csv"; ofs.open(ss_filename.str().c_str()); if( ofs.fail() ){ cout << "\nFATAL ERROR: unable to write to " << ss_filename.str() << endl; exit(EXIT_FAILURE); } ofs << "X,Y,hilltop_id,S,R,Lh,BasinID,StreamID,HilltopSlope,DivergentCount\n"; //calculate northing and easting for (i=0;i<NRows;++i){ northing[i] = ymax - i*DataResolution - 0.5; } for (j=0;j<NCols;++j){ easting[j] = XMinimum + j*DataResolution + 0.5; } //convert aspects to radians with east as theta = 0/2*pi for (i=0; i<NRows; ++i) { for (j=0; j<NCols; ++j) { //convert aspects to radians with east as theta = 0/2*pi if (rads[i][j] != NoDataValue) rads[i][j] = BearingToRad(aspect[i][j]); } } // cycle through study area, find hilltops and trace downstream for (i=1; i<NRows-1; ++i) { cout << flush << "\tRow: " << i << " of = " << NRows-1 << " \r"; for (j=1; j<NCols-1; ++j) { // ignore edge cells and non-hilltop cells // route initial node by aspect and get outlet coordinates if (hilltops[i][j] != NoDataValue) { length = 0; flag = true; count = 1; path = blank.copy(); DivergentCountFlag = 0; //initialise count of divergent cells in trace skip_trace = false; //initialise skip trace flag as false, will only be switched if no path to stream can be found. Very rare. ++ht_count; degs = aspect[i][j]; theta = rads[i][j]; a = i; b = j; path[a][b] += 1; east_vec[0] = easting[b]; north_vec[0] = northing[a]; s_local = slope[a][b]; //test direction, calculate outlet coordinates and update indicies // easterly if (degs >= 45 && degs < 135) { //cout << "\neasterly" << endl; xo = 1, yo = (1+tan(theta))/2; d = abs(1/(2*cos(theta))); xi = 0, yi = yo; dir = 1; east_vec[count] = easting[b] + 0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; ++b; if (yi == 0) yi = 0.00001; else if (yi == 1) yi = 1 - 0.00001; } //southerly else if (degs >= 135 && degs < 225) { //cout << "\nsoutherly" << endl; xo = (1-(1/tan(theta)))/2, yo = 0; d = abs(1/(2*cos((PI/2)-theta))); xi = xo, yi = 1; dir = 2; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] - 0.5*DataResolution; ++a; if (xi == 0) xi = 0.00001; else if (xi == 1) xi = 1 - 0.00001; } // westerly else if (degs >= 225 && degs < 315) { xo = 0, yo = (1-tan(theta))/2; d = abs(1/(2*cos(theta))); xi = 1, yi = yo; dir = 3; east_vec[count] = easting[b] -0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; --b; if (yi == 0) yi = 0.00001; else if (yi == 1) yi = 1 - 0.00001; } //northerly else if (degs >= 315 || degs < 45) { xo = (1+(1/tan(theta)))/2, yo = 1; d = abs(1/(2*cos((PI/2) - theta))); xi = xo, yi = 0; dir = 4; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] + 0.5*DataResolution; --a; if (xi == 0) xi = 0.00001; else if (xi == 1) xi = 1 - 0.00001; } else { cout << "FATAL ERROR, Kinematic routing algorithm enountered null aspect value" << endl; exit(EXIT_FAILURE); } //collect slopes and totals weighted by path length length += d; s_local = slope[a][b]; //continue trace until a stream node is encountered while (flag == true && a > 0 && a < NRows-1 && b > 0 && b < NCols-1) { //added boudary checking to catch cells which flow off the edge of the DEM tile. int a_2 = a; int b_2 = b; path[a][b] += 1; degs_old = degs; degs_new = aspect[a][b]; theta = rads[a][b]; ++count; //Test for perimeter flow paths if ((dir == 1 && degs_new > 0 && degs_new < 180) || (dir == 2 && degs_new > 90 && degs_new < 270) || (dir == 3 && degs_new > 180 && degs_new < 360) || ((dir == 4 && degs_new > 270) || (dir == 4 && degs_new < 90))) { //DO NORMAL FLOW PATH //set xo, yo to 0 and 1 in turn and test for true outlet (xi || yi == 0 || 1) temp_yo1 = yi + (1-xi)*tan(theta); // xo = 1 temp_xo1 = xi + (1-yi)*(1/tan(theta)); // yo = 1 temp_yo2 = yi - xi*tan(theta); // xo = 0 temp_xo2 = xi - yi*(1/tan(theta)); // yo = 0 // can't outlet at same point as inlet if (dir == 1) temp_yo2 = -1; else if (dir == 2) temp_xo1 = -1; else if (dir == 3) temp_yo1 = -1; else if (dir == 4) temp_xo2 = -1; s_local = slope[a][b]; if (temp_yo1 <= 1 && temp_yo1 > 0) { xo = 1, yo = temp_yo1; d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 0, yi = yo, dir = 1; east_vec[count] = easting[b] + 0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; ++b; if (xi== 0 && yi == 0) yi = 0.00001; else if (xi== 0 && yi == 1) yi = 1 - 0.00001; } else if (temp_xo2 <= 1 && temp_xo2 > 0) { xo = temp_xo2, yo = 0; d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 1, dir = 2; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] - 0.5*DataResolution; ++a; if (xi== 0 && yi == 1) xi = 0.00001; else if (xi== 1 && yi == 1) xi = 1 - 0.00001; } else if (temp_yo2 <= 1 && temp_yo2 > 0) { xo = 0, yo = temp_yo2; d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1, yi = yo, dir = 3; east_vec[count] = easting[b] -0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; --b; if (xi== 1 && yi == 0) yi = 0.00001; else if (xi== 1 && yi == 1) yi = 1 - 0.00001; } else if (temp_xo1 <= 1 && temp_xo1 > 0) { xo = temp_xo1, yo = 1; d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 0, dir = 4; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] + 0.5*DataResolution; --a; if (xi == 0 && yi == 0) xi = 0.00001; else if (xi== 1 && yi == 0) xi = 1 - 0.00001; } } else { // ROUTE ALONG EDGES if (dir == 1) { if (degs_new <= 90 || degs_new >= 270) { //secondary compenent of flow is north xo = 0.00001, yo = 1; s_edge = abs(s_local*sin(theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 1-yo; dir = 4; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] + 0.5*DataResolution; --a; } else if (degs_new > 90 && degs_new < 270) { //secondary component is south xo = 0.00001, yo = 0; s_edge = abs(s_local*sin((PI/2)-theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 1-yo; dir = 2; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] - 0.5*DataResolution; ++a; } else { cout << "Flow unable to route N or S " << endl; //something has gone very wrong... cout << "Trace skipped.\n" << endl; skip_trace = true; //exit(EXIT_FAILURE); } } else if (dir == 2) { if (degs_new >= 0 && degs_new <= 180) { //secondary component is East xo = 1, yo = 1-0.00001; s_edge = abs(s_local*sin((2/PI)-theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1-xo, yi = yo; dir = 1; east_vec[count] = easting[b] + 0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; ++b; } else if (degs_new > 180 && degs_new <= 360) { //secondary component is West xo = 0, yo = 1-0.00001; s_edge = abs(s_local*sin(theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1-xo, yi = yo; dir = 3; east_vec[count] = easting[b] -0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; --b; } else { cout << "Flow unable to route E or W" << endl; //something has gone very wrong... cout << "Trace skipped.\n" << endl; //something has gone very wrong... skip_trace = true; //exit(EXIT_FAILURE); } } else if (dir == 3) { if (degs_new >= 90 && degs_new <= 270) { //secondary component is South xo = 1-0.00001, yo = 0; s_edge = abs(s_local*sin(theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 1-yo; dir = 2; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] - 0.5*DataResolution; ++a; } else if (degs_new > 270 || degs_new < 90) { //secondary component is North xo = 1-0.00001, yo = 1; s_edge = abs(s_local*sin((2/PI) - theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 1- yo; dir = 4; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] + 0.5*DataResolution; --a; } else { cout << "Flow unable to route N or S" << endl; //something has gone very wrong... cout << "Trace skipped.\n" << endl; //something has gone very wrong... skip_trace = true; //exit(EXIT_FAILURE); } } else if (dir == 4) { if (degs_new >= 180 && degs_new <= 360) { //secondary component is West xo = 0, yo = 0.00001; s_edge = abs(s_local*sin((PI/2) - theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1-xo, yi = yo; dir = 3; east_vec[count] = easting[b] -0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; --b; } else if (degs_new >= 0 && degs_new < 180) { //secondary component is East xo = 1, yo = 0.00001; s_edge = abs(s_local*sin(theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1-xo, yi = yo; dir = 1; east_vec[count] = easting[b] + 0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; ++b; } else { cout << "Flow unable to route E or W" << endl; //something has gone very wrong... cout << "Trace skipped.\n" << endl; //something has gone very wrong... skip_trace = true; //exit(EXIT_FAILURE); } } } if (path[a][b] < 1){ // only update length on 'first slosh' length += d; } degs = degs_new; if(zeta[a][b] - zeta[a_2][b_2] > 0){ length -= d; //remove uphill length from trace a = a_2; b = b_2; //restart trace degs = aspect[a][b]; theta = rads[a][b]; path[a][b] += 1; s_local = slope[a][b]; length += sqrt((pow((xo-0.5),2) + pow((yo-0.5),2))); //update length to cope with the 'jump' to the centre of the cell to restart the trace //test direction, calculate outlet coordinates and update indicies // easterly if (degs >= 45 && degs < 135) { xo = 1, yo = (1+tan(theta))/2; d = abs(1/(2*cos(theta))); xi = 0, yi = yo; dir = 1; east_vec[count] = easting[b] + 0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; ++b; } //southerly else if (degs >= 135 && degs < 225) { xo = (1-(1/tan(theta)))/2, yo = 0; d = abs(1/(2*cos((PI/2)-theta))); xi = xo, yi = 1; dir = 2; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] - 0.5*DataResolution; ++a; } // westerly else if (degs >= 225 && degs < 315) { xo = 0, yo = (1-tan(theta))/2; d = abs(1/(2*cos(theta))); xi = 1, yi = yo; dir = 3; east_vec[count] = easting[b] -0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; --b; } //northerly else if (degs >= 315 || degs < 45) { xo = (1+(1/tan(theta)))/2, yo = 1; d = abs(1/(2*cos((PI/2) - theta))); xi = xo, yi = 0; dir = 4; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] + 0.5*DataResolution; --a; } else { cout << "FATAL ERROR, Kinematic routing algorithm enountered null aspect value" << endl; exit(EXIT_FAILURE); } //collect slopes and totals weighted by path length length += d; s_local = slope[a][b]; } if (path[a][b] >= 1){ //self intersect/'slosh' degs = aspect[a][b]; theta = rads[a][b]; path[a][b] += 1; s_local = slope[a][b]; a_2 = a; b_2 = b; length += sqrt((pow((xo-0.5),2) + pow((yo-0.5),2))); //update length to cope with the 'jump' to the centre of the cell to restart the trace //test direction, calculate outlet coordinates and update indicies // easterly if (degs >= 45 && degs < 135) { xo = 1, yo = (1+tan(theta))/2; d = abs(1/(2*cos(theta))); xi = 0, yi = yo; dir = 1; east_vec[count] = easting[b] + 0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; ++b; } //southerly else if (degs >= 135 && degs < 225) { xo = (1-(1/tan(theta)))/2, yo = 0; d = abs(1/(2*cos((PI/2)-theta))); xi = xo, yi = 1; dir = 2; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] - 0.5*DataResolution; ++a; } // westerly else if (degs >= 225 && degs < 315) { xo = 0, yo = (1-tan(theta))/2; d = abs(1/(2*cos(theta))); xi = 1, yi = yo; dir = 3; east_vec[count] = easting[b] -0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; --b; } //northerly else if (degs >= 315 || degs < 45) { xo = (1+(1/tan(theta)))/2, yo = 1; d = abs(1/(2*cos((PI/2) - theta))); xi = xo, yi = 0; dir = 4; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] + 0.5*DataResolution; --a; } else { cout << "FATAL ERROR, Kinematic routing algorithm enountered null aspect value" << endl; exit(EXIT_FAILURE); } //collect slopes and totals weighted by path length length += d; s_local = slope[a][b]; } // test for plan curvature here and set a flag if flow is divergent or convergent but continue trace regardless // The larger the counter the more convergent or divergent the trace is if (abs(PlanCurvature.get_data_element(a,b)) > (0.001)){ ++DivergentCountFlag; } else { ++PlanarCountFlag; } if (path[a][b] >=3){ //update flag if a trace cannot complete, so that we can track errors. skip_trace = true; } if (a == 0 || b == 0 || a == NRows-1 || b == NCols-1 || stnet[a][b] != NoDataValue || stnet[a-1][b-1] != NoDataValue || stnet[a][b-1] != NoDataValue || stnet[a+1][b-1] != NoDataValue || stnet[a+1][b] != NoDataValue || stnet[a+1][b+1] != NoDataValue || stnet[a][b+1] != NoDataValue || stnet[a-1][b+1] != NoDataValue || stnet[a-1][b] != NoDataValue || path[a][b] >= 3 || skip_trace == true) flag = false; } if (a == 0 || b == 0 || a == NRows-1 || b == NCols-1 ){ // avoid going out of bounds. // this is caused by having a hilltop on the first row or col away from the border // eg i or j == 1 or nrows/ncols - 2 and flowing towards the edge. // can fix with a test here for if streamnet[a][b] != NDV otherwise trace will fail *correctly* ++edge_count; } else { //if trace finished at a stream, print hillslope info. if (stnet[a][b] != NoDataValue || stnet[a-1][b-1] != NoDataValue || stnet[a][b-1] != NoDataValue || stnet[a+1][b-1] != NoDataValue || stnet[a+1][b] != NoDataValue || stnet[a+1][b+1] != NoDataValue || stnet[a][b+1] != NoDataValue || stnet[a-1][b+1] != NoDataValue || stnet[a-1][b] != NoDataValue) { path[a][b] = 1; ++s_count; X = XMinimum + j*DataResolution; Y = YMinimum - (NRows-i)*DataResolution; relief = zeta[i][j] - zeta[a][b]; mean_slope = relief/(length * DataResolution); // update arrays with the current metrics RoutedHilltops[i][j] = 1; HillslopeLength_Array[i][j] = (length * DataResolution); Slope_Array[i][j] = mean_slope; Relief_Array[i][j] = relief; //calculate an E* and R* Value assuming S_c of 0.8 E_Star = (2.0 * abs(hilltops[i][j])*(length*DataResolution))/0.8; R_Star = relief/((length*DataResolution)*0.8); //calulate the Euclidean distance between the start and end points of the trace EucDist = sqrt((pow(((i+0.5)-(a+yo)),2) + pow(((j+0.5)-(b+xo)),2))) * DataResolution; if (relief > 0){ ofs << X << "," << Y << "," << hilltops[i][j] << "," << mean_slope << "," << relief << "," << length*DataResolution << "," << basin[i][j] << "," << stnet[a][b] << "," << slope[i][j] << "," << DivergentCountFlag << "," << PlanarCountFlag << "," << E_Star << "," << R_Star << "," << EucDist << "\n"; } else { ++neg_count; } } else{ //unable to route using aspects //this will encompass the skipped traces ofs << "fail: " << a << " " << b << " " << i << " " << j << endl; ++ns_count; } } //This block checks the various path printing options and writes the data out accordingly if (print_paths_switch == true){ if (ht_count % thinning == 0){ if (hilltops[i][j] != NoDataValue && skip_trace == false){ //check that the current i,j tuple corresponds to a hilltop and has a valid trace, ie there is actually a trace to write to file. //create stringstream object to create filename ofstream pathwriter; //create the output filename from the user supplied path stringstream ss_path; ss_path << trace_path << i << "_" << j << "_trace.txt"; pathwriter.open(ss_path.str().c_str()); if(pathwriter.fail() ){ cout << "\nFATAL ERROR: unable to write to " << ss_path.str() << endl; exit(EXIT_FAILURE); } for (int v = 0; v < count+1; ++v){ if (basin_filter_switch == false){ pathwriter << setiosflags(ios::fixed) << setprecision(7) << east_vec[v] << " " << north_vec[v] << " " << DivergentCountFlag << " " << length << " " << PlanarCountFlag << " " << E_Star << " " << R_Star << " " << EucDist << endl; } else if (basin_filter_switch == true && find(Target_Basin_Vector.begin(), Target_Basin_Vector.end(), basin[a][b]) != Target_Basin_Vector.end() && find(Target_Basin_Vector.begin(), Target_Basin_Vector.end(), basin[i][j]) != Target_Basin_Vector.end()){ //is this correct? evaulating to not equal one past the end of the vector should equal that the value is found pathwriter << setiosflags(ios::fixed) << setprecision(7) << east_vec[v] << " " << north_vec[v] << " " << DivergentCountFlag << " " << length << " " << PlanarCountFlag << " " << E_Star << " " << R_Star << " " << EucDist << endl; } } pathwriter.close(); } } } // End of path printing logic } } //for loop i,j } ofs.close(); //add the data arrays to the output vector OutputArrays.push_back(RoutedHilltops); OutputArrays.push_back(HillslopeLength_Array); OutputArrays.push_back(Slope_Array); OutputArrays.push_back(Relief_Array); //Print debugging info to screen cout << endl; //push output onto new line cout << "Hilltop count: " << ht_count << endl; cout << "Stream count: " << s_count << endl; cout << "Fail count: " << ns_count << endl; cout << "Uphill count: " << neg_count << endl; cout << "Edge count: " << edge_count << endl; return OutputArrays; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // Hilltop flow routing code built around original code from Martin Hurst. Based on // Lea (1992), with improvements discussed by Tarboton (1997) and a solution to the // problem of looping flow paths implemented. // // THIS VERSION OF THE CODE RETAINS THE FLOODING METHOD TO ALLOW TRACES TO BE USED // ON RAW TOPOGRPAHY TO GET EVENT SCALE HILLSLOPE LENGTHS WITH NO SMOOTHING. IN // MOST CASES USE THE MAIN METHOD, TO ANALYSE SEDIMENT TRANSPORT OVER GEOMORPHIC TIME. // // This code is SLOW but robust, a refactored version may appear, but there may not be // enough whisky in Scotland to support that endeavour. // // The algorithm now checks for local uphill flows and in the case of identifying one, // D8 flow path is used to push the flow into the centre of the steepest downslope // cell, at which point the trace is restarted. The same technique is used to cope // with self intersections of the flow path. These problems are not solved in the // original paper and I think they are caused at least in part by the high resolution // topogrpahy we are using. // // The code is also now built to take a d infinity flow direction raster instead of an // aspect raster. See Tarboton (1997) for discussions on why this is the best solution. // // The Basins input raster is used to code each hilltop into a basin to allow basin // averaging to take place. // // The final 5 parameters are used to set up printing flow paths to files for visualisation, // if this is not needed simply pass in false to the two boolean switches and empty variables for the // others, and the code will run as normal. // // This version is used to generate elevation profiles of the traces. The elevation data is encoded within // the trace files. // // The structure of the returned vector< Array2D<float> > is as follows: // [0] Hilltop Network coded with stream ID // [1] Hillslope Lengths // [2] Slope // [3] Relief // // SWDG 25/3/15 //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= vector< Array2D<float> > LSDFlowInfo::HilltopFlowRouting_Profile(LSDRaster Elevation, LSDRaster Hilltops, LSDRaster Slope, LSDIndexRaster StreamNetwork, LSDRaster D_inf_Flowdir, string Prefix, LSDIndexRaster Basins, bool print_paths_switch, int thinning, string trace_path, bool basin_filter_switch, vector<int> Target_Basin_Vector){ //Declare parameters int i,j; int a = 0; int b = 0; float X,Y; float mean_slope, relief; float length, d; int flag; int count = 0; float PI = 3.14159265; float degs, degs_old, degs_new, theta; float s_local, s_edge; float xo, yo, xi, yi, temp_yo1, temp_yo2, temp_xo1, temp_xo2; bool skip_trace; //flag used to skip traces where no path to a stream can be found. Will only occur on noisy, raw topography //debugging counters int ns_count = 0; int s_count = 0; int neg_count = 0; int edge_count = 0; int ht_count = 0; // a direction flag numbered 1,2,3,4 for E,S,W,N respectively int dir; float ymax = YMinimum + NRows*DataResolution; //Get data arrays from LSDRasters Array2D<float> zeta = Elevation.get_RasterData(); //elevation Array2D<int> stnet = StreamNetwork.get_RasterData(); // stream network Array2D<float> aspect = D_inf_Flowdir.get_RasterData(); //aspect Array2D<float> hilltops = Hilltops.get_RasterData(); //hilltops Array2D<float> slope = Slope.get_RasterData(); //hilltops Array2D<int> basin = Basins.get_RasterData(); //basins //empty arrays for data to be stored in Array2D<float> rads(NRows,NCols); Array2D<float> path(NRows, NCols, 0.0); Array2D<float> blank(NRows, NCols, 0.0); Array2D<float> RoutedHilltops(NRows,NCols,NoDataValue); Array2D<float> HillslopeLength_Array(NRows,NCols,NoDataValue); Array2D<float> Slope_Array(NRows,NCols,NoDataValue); Array2D<float> Relief_Array(NRows,NCols,NoDataValue); //vector to store the output data arrays in one vector that can be returned vector< Array2D<float> > OutputArrays; int vec_size = 1000000; Array1D<double> easting(NCols); Array1D<double> northing(NRows); Array1D<double> east_vec(vec_size); Array1D<double> north_vec(vec_size); vector<float> ZetaList; vector<float> LengthList; ofstream ofs; //create the output filename from the user supplied filename prefix stringstream ss_filename; ss_filename << Prefix << "_HilltopData_RAW.csv"; ofs.open(ss_filename.str().c_str()); if( ofs.fail() ){ cout << "\nFATAL ERROR: unable to write to " << ss_filename.str() << endl; exit(EXIT_FAILURE); } ofs << "X,Y,hilltop_id,S,R,Lh,BasinID,StreamID,HilltopSlope\n"; //calculate northing and easting for (i=0;i<NRows;++i){ northing[i] = ymax - i*DataResolution - 0.5; } for (j=0;j<NCols;++j){ easting[j] = XMinimum + j*DataResolution + 0.5; } //convert aspects to radians with east as theta = 0/2*pi for (i=0; i<NRows; ++i) { for (j=0; j<NCols; ++j) { //convert aspects to radians with east as theta = 0/2*pi if (rads[i][j] != NoDataValue) rads[i][j] = BearingToRad(aspect[i][j]); } } // cycle through study area, find hilltops and trace downstream for (i=1; i<NRows-1; ++i) { cout << flush << "\tRow: " << i << " of = " << NRows-1 << " \r"; for (j=1; j<NCols-1; ++j) { // ignore edge cells and non-hilltop cells // route initial node by aspect and get outlet coordinates if (hilltops[i][j] != NoDataValue) { length = 0; flag = true; count = 1; path = blank.copy(); skip_trace = false; //initialise skip trace flag as false, will only be switched if no path to stream can be found. Very rare. ++ht_count; degs = aspect[i][j]; theta = rads[i][j]; a = i; b = j; path[a][b] += 1; east_vec[0] = easting[b]; north_vec[0] = northing[a]; s_local = slope[a][b]; ZetaList.clear(); LengthList.clear(); //test direction, calculate outlet coordinates and update indicies // easterly if (degs >= 45 && degs < 135) { //cout << "\neasterly" << endl; xo = 1, yo = (1+tan(theta))/2; d = abs(1/(2*cos(theta))); xi = 0, yi = yo; dir = 1; east_vec[count] = easting[b] + 0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; ++b; if (yi == 0) yi = 0.00001; else if (yi == 1) yi = 1 - 0.00001; } //southerly else if (degs >= 135 && degs < 225) { //cout << "\nsoutherly" << endl; xo = (1-(1/tan(theta)))/2, yo = 0; d = abs(1/(2*cos((PI/2)-theta))); xi = xo, yi = 1; dir = 2; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] - 0.5*DataResolution; ++a; if (xi == 0) xi = 0.00001; else if (xi == 1) xi = 1 - 0.00001; } // westerly else if (degs >= 225 && degs < 315) { xo = 0, yo = (1-tan(theta))/2; d = abs(1/(2*cos(theta))); xi = 1, yi = yo; dir = 3; east_vec[count] = easting[b] -0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; --b; if (yi == 0) yi = 0.00001; else if (yi == 1) yi = 1 - 0.00001; } //northerly else if (degs >= 315 || degs < 45) { xo = (1+(1/tan(theta)))/2, yo = 1; d = abs(1/(2*cos((PI/2) - theta))); xi = xo, yi = 0; dir = 4; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] + 0.5*DataResolution; --a; if (xi == 0) xi = 0.00001; else if (xi == 1) xi = 1 - 0.00001; } else { cout << "FATAL ERROR, Kinematic routing algorithm enountered null aspect value" << endl; exit(EXIT_FAILURE); } //collect slopes and totals weighted by path length length += d; s_local = slope[a][b]; //continue trace until a stream node is encountered while (flag == true && a > 0 && a < NRows-1 && b > 0 && b < NCols-1) { //added boudary checking to catch cells which flow off the edge of the DEM tile. int a_2 = a; int b_2 = b; path[a][b] += 1; degs_old = degs; degs_new = aspect[a][b]; theta = rads[a][b]; ++count; //Test for perimeter flow paths if ((dir == 1 && degs_new > 0 && degs_new < 180) || (dir == 2 && degs_new > 90 && degs_new < 270) || (dir == 3 && degs_new > 180 && degs_new < 360) || ((dir == 4 && degs_new > 270) || (dir == 4 && degs_new < 90))) { //DO NORMAL FLOW PATH //set xo, yo to 0 and 1 in turn and test for true outlet (xi || yi == 0 || 1) temp_yo1 = yi + (1-xi)*tan(theta); // xo = 1 temp_xo1 = xi + (1-yi)*(1/tan(theta)); // yo = 1 temp_yo2 = yi - xi*tan(theta); // xo = 0 temp_xo2 = xi - yi*(1/tan(theta)); // yo = 0 // can't outlet at same point as inlet if (dir == 1) temp_yo2 = -1; else if (dir == 2) temp_xo1 = -1; else if (dir == 3) temp_yo1 = -1; else if (dir == 4) temp_xo2 = -1; s_local = slope[a][b]; if (temp_yo1 <= 1 && temp_yo1 > 0) { xo = 1, yo = temp_yo1; d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 0, yi = yo, dir = 1; east_vec[count] = easting[b] + 0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; ++b; if (xi== 0 && yi == 0) yi = 0.00001; else if (xi== 0 && yi == 1) yi = 1 - 0.00001; } else if (temp_xo2 <= 1 && temp_xo2 > 0) { xo = temp_xo2, yo = 0; d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 1, dir = 2; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] - 0.5*DataResolution; ++a; if (xi== 0 && yi == 1) xi = 0.00001; else if (xi== 1 && yi == 1) xi = 1 - 0.00001; } else if (temp_yo2 <= 1 && temp_yo2 > 0) { xo = 0, yo = temp_yo2; d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1, yi = yo, dir = 3; east_vec[count] = easting[b] -0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; --b; if (xi== 1 && yi == 0) yi = 0.00001; else if (xi== 1 && yi == 1) yi = 1 - 0.00001; } else if (temp_xo1 <= 1 && temp_xo1 > 0) { xo = temp_xo1, yo = 1; d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 0, dir = 4; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] + 0.5*DataResolution; --a; if (xi == 0 && yi == 0) xi = 0.00001; else if (xi== 1 && yi == 0) xi = 1 - 0.00001; } } else { // ROUTE ALONG EDGES if (dir == 1) { if (degs_new <= 90 || degs_new >= 270) { //secondary compenent of flow is north xo = 0.00001, yo = 1; s_edge = abs(s_local*sin(theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 1-yo; dir = 4; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] + 0.5*DataResolution; --a; } else if (degs_new > 90 && degs_new < 270) { //secondary component is south xo = 0.00001, yo = 0; s_edge = abs(s_local*sin((PI/2)-theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 1-yo; dir = 2; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] - 0.5*DataResolution; ++a; } else { cout << "Flow unable to route N or S " << endl; //something has gone very wrong... cout << "Trace skipped.\n" << endl; skip_trace = true; //exit(EXIT_FAILURE); } } else if (dir == 2) { if (degs_new >= 0 && degs_new <= 180) { //secondary component is East xo = 1, yo = 1-0.00001; s_edge = abs(s_local*sin((2/PI)-theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1-xo, yi = yo; dir = 1; east_vec[count] = easting[b] + 0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; ++b; } else if (degs_new > 180 && degs_new <= 360) { //secondary component is West xo = 0, yo = 1-0.00001; s_edge = abs(s_local*sin(theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1-xo, yi = yo; dir = 3; east_vec[count] = easting[b] -0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; --b; } else { cout << "Flow unable to route E or W" << endl; //something has gone very wrong... cout << "Trace skipped.\n" << endl; //something has gone very wrong... skip_trace = true; //exit(EXIT_FAILURE); } } else if (dir == 3) { if (degs_new >= 90 && degs_new <= 270) { //secondary component is South xo = 1-0.00001, yo = 0; s_edge = abs(s_local*sin(theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 1-yo; dir = 2; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] - 0.5*DataResolution; ++a; } else if (degs_new > 270 || degs_new < 90) { //secondary component is North xo = 1-0.00001, yo = 1; s_edge = abs(s_local*sin((2/PI) - theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 1- yo; dir = 4; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] + 0.5*DataResolution; --a; } else { cout << "Flow unable to route N or S" << endl; //something has gone very wrong... cout << "Trace skipped.\n" << endl; //something has gone very wrong... skip_trace = true; //exit(EXIT_FAILURE); } } else if (dir == 4) { if (degs_new >= 180 && degs_new <= 360) { //secondary component is West xo = 0, yo = 0.00001; s_edge = abs(s_local*sin((PI/2) - theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1-xo, yi = yo; dir = 3; east_vec[count] = easting[b] -0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; --b; } else if (degs_new >= 0 && degs_new < 180) { //secondary component is East xo = 1, yo = 0.00001; s_edge = abs(s_local*sin(theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1-xo, yi = yo; dir = 1; east_vec[count] = easting[b] + 0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; ++b; } else { cout << "Flow unable to route E or W" << endl; //something has gone very wrong... cout << "Trace skipped.\n" << endl; //something has gone very wrong... skip_trace = true; //exit(EXIT_FAILURE); } } } if (path[a][b] < 1){ // only update length on 'first slosh' length += d; } degs = degs_new; if(zeta[a][b] - zeta[a_2][b_2] > 0){ length -= d; //remove uphill length from trace a = a_2; b = b_2; //restart trace degs = aspect[a][b]; theta = rads[a][b]; path[a][b] += 1; s_local = slope[a][b]; length += sqrt((pow((xo-0.5),2) + pow((yo-0.5),2))); //update length to cope with the 'jump' to the centre of the cell to restart the trace //test direction, calculate outlet coordinates and update indicies // easterly if (degs >= 45 && degs < 135) { xo = 1, yo = (1+tan(theta))/2; d = abs(1/(2*cos(theta))); xi = 0, yi = yo; dir = 1; east_vec[count] = easting[b] + 0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; ++b; } //southerly else if (degs >= 135 && degs < 225) { xo = (1-(1/tan(theta)))/2, yo = 0; d = abs(1/(2*cos((PI/2)-theta))); xi = xo, yi = 1; dir = 2; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] - 0.5*DataResolution; ++a; } // westerly else if (degs >= 225 && degs < 315) { xo = 0, yo = (1-tan(theta))/2; d = abs(1/(2*cos(theta))); xi = 1, yi = yo; dir = 3; east_vec[count] = easting[b] -0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; --b; } //northerly else if (degs >= 315 || degs < 45) { xo = (1+(1/tan(theta)))/2, yo = 1; d = abs(1/(2*cos((PI/2) - theta))); xi = xo, yi = 0; dir = 4; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] + 0.5*DataResolution; --a; } else { cout << "FATAL ERROR, Kinematic routing algorithm enountered null aspect value" << endl; exit(EXIT_FAILURE); } //collect slopes and totals weighted by path length length += d; s_local = slope[a][b]; } if (path[a][b] >= 1){ //self intersect/'slosh' degs = aspect[a][b]; theta = rads[a][b]; path[a][b] += 1; s_local = slope[a][b]; a_2 = a; b_2 = b; length += sqrt((pow((xo-0.5),2) + pow((yo-0.5),2))); //update length to cope with the 'jump' to the centre of the cell to restart the trace //test direction, calculate outlet coordinates and update indicies // easterly if (degs >= 45 && degs < 135) { xo = 1, yo = (1+tan(theta))/2; d = abs(1/(2*cos(theta))); xi = 0, yi = yo; dir = 1; east_vec[count] = easting[b] + 0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; ++b; } //southerly else if (degs >= 135 && degs < 225) { xo = (1-(1/tan(theta)))/2, yo = 0; d = abs(1/(2*cos((PI/2)-theta))); xi = xo, yi = 1; dir = 2; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] - 0.5*DataResolution; ++a; } // westerly else if (degs >= 225 && degs < 315) { xo = 0, yo = (1-tan(theta))/2; d = abs(1/(2*cos(theta))); xi = 1, yi = yo; dir = 3; east_vec[count] = easting[b] -0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; --b; } //northerly else if (degs >= 315 || degs < 45) { xo = (1+(1/tan(theta)))/2, yo = 1; d = abs(1/(2*cos((PI/2) - theta))); xi = xo, yi = 0; dir = 4; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] + 0.5*DataResolution; --a; } else { cout << "FATAL ERROR, Kinematic routing algorithm enountered null aspect value" << endl; exit(EXIT_FAILURE); } //collect slopes and totals weighted by path length length += d; s_local = slope[a][b]; } if (path[a][b] >=3){ //update flag if a trace cannot complete, so that we can track errors. skip_trace = true; } ZetaList.push_back(zeta[a][b]); LengthList.push_back(length*DataResolution); if (a == 0 || b == 0 || a == NRows-1 || b == NCols-1 || stnet[a][b] != NoDataValue || stnet[a-1][b-1] != NoDataValue || stnet[a][b-1] != NoDataValue || stnet[a+1][b-1] != NoDataValue || stnet[a+1][b] != NoDataValue || stnet[a+1][b+1] != NoDataValue || stnet[a][b+1] != NoDataValue || stnet[a-1][b+1] != NoDataValue || stnet[a-1][b] != NoDataValue || path[a][b] >= 3 || skip_trace == true) flag = false; } if (a == 0 || b == 0 || a == NRows-1 || b == NCols-1 ){ // avoid going out of bounds. // this is caused by having a hilltop on the first row or col away from the border // eg i or j == 1 or nrows/ncols - 2 and flowing towards the edge. // can fix with a test here for if streamnet[a][b] != NDV otherwise trace will fail *correctly* ++edge_count; } else { //if trace finished at a stream, print hillslope info. if (stnet[a][b] != NoDataValue || stnet[a-1][b-1] != NoDataValue || stnet[a][b-1] != NoDataValue || stnet[a+1][b-1] != NoDataValue || stnet[a+1][b] != NoDataValue || stnet[a+1][b+1] != NoDataValue || stnet[a][b+1] != NoDataValue || stnet[a-1][b+1] != NoDataValue || stnet[a-1][b] != NoDataValue) { path[a][b] = 1; ++s_count; X = XMinimum + j*DataResolution; Y = YMinimum - (NRows-i)*DataResolution; relief = zeta[i][j] - zeta[a][b]; mean_slope = relief/(length * DataResolution); // update arrays with the current metrics RoutedHilltops[i][j] = 1; HillslopeLength_Array[i][j] = (length * DataResolution); Slope_Array[i][j] = mean_slope; Relief_Array[i][j] = relief; if (relief > 0){ ofs << X << "," << Y << "," << hilltops[i][j] << "," << mean_slope << "," << relief << "," << length*DataResolution << "," << basin[i][j] << "," << stnet[a][b] << "," << slope[i][j] << "\n"; } else { ++neg_count; } } else{ //unable to route using aspects //this will encompass the skipped traces ofs << "fail: " << a << " " << b << " " << i << " " << j << endl; ++ns_count; } } //This block checks the various path printing options and writes the data out accordingly if (print_paths_switch == true){ if (ht_count % thinning == 0){ if (hilltops[i][j] != NoDataValue && skip_trace == false){ //check that the current i,j tuple corresponds to a hilltop and has a valid trace, ie there is actually a trace to write to file. //create stringstream object to create filename ofstream pathwriter; //create the output filename from the user supplied path stringstream ss_path; ss_path << trace_path << i << "_" << j << "_trace.txt"; pathwriter.open(ss_path.str().c_str()); if(pathwriter.fail() ){ cout << "\nFATAL ERROR: unable to write to " << ss_path.str() << endl; exit(EXIT_FAILURE); } for (int v = 0; v < count+1; ++v){ if (basin_filter_switch == false){ pathwriter << setiosflags(ios::fixed) << setprecision(7) << east_vec[v] << " " << north_vec[v] << " " << ZetaList[v] << " " << LengthList[v] << endl; } else if (basin_filter_switch == true && find(Target_Basin_Vector.begin(), Target_Basin_Vector.end(), basin[a][b]) != Target_Basin_Vector.end() && find(Target_Basin_Vector.begin(), Target_Basin_Vector.end(), basin[i][j]) != Target_Basin_Vector.end()){ //is this correct? evaulating to not equal one past the end of the vector should equal that the value is found pathwriter << setiosflags(ios::fixed) << setprecision(7) << east_vec[v] << " " << north_vec[v] << " " << ZetaList[v] << " " << LengthList[v] << endl; } } pathwriter.close(); } } } // End of path printing logic } } //for loop i,j } ofs.close(); //add the data arrays to the output vector OutputArrays.push_back(RoutedHilltops); OutputArrays.push_back(HillslopeLength_Array); OutputArrays.push_back(Slope_Array); OutputArrays.push_back(Relief_Array); //Print debugging info to screen cout << endl; //push output onto new line cout << "Hilltop count: " << ht_count << endl; cout << "Stream count: " << s_count << endl; cout << "Fail count: " << ns_count << endl; cout << "Uphill count: " << neg_count << endl; cout << "Edge count: " << edge_count << endl; return OutputArrays; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // // This function makes a mask of all the pixels that recieve flow (d8) // from a pixel that is either nodata or is on the boundary of the DEM // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- LSDIndexRaster LSDFlowInfo::find_cells_influenced_by_nodata(LSDIndexRaster& Bordered_mask, LSDRaster& Topography) { // set up the array Array2D<int> influenced_mask(NRows,NCols,int(NoDataValue)); for(int row = 0; row <NRows; row++) { for(int col = 0; col<NCols; col++) { if(Topography.get_data_element(row,col) != NoDataValue) { influenced_mask[row][col] = 0; } } } int curr_node; int next_node; int next_row,next_col; // now loop through every node in the array for(int row = 0; row <NRows; row++) { for(int col = 0; col<NCols; col++) { if(Topography.get_data_element(row,col) != NoDataValue) { // this node has data. // first see if it has already been tagged if(influenced_mask[row][col] != 1) { //See if it is borderd by a NDV if(Bordered_mask.get_data_element(row,col) == 1) { // it is bordered by nodata. Work your way down the node list curr_node = retrieve_node_from_row_and_column(row, col); next_node = ReceiverVector[curr_node]; influenced_mask[row][col] = 1; retrieve_current_row_and_col(next_node, next_row, next_col); //cout << "I am bordered by NDV, entering search loop" << endl; //cout << "Row: " << row << " col: " << col << " node: " << curr_node // << " receiver: " << next_node << " next infl mask: " // << influenced_mask[next_row][next_col] << endl; // loop until you hit another influenced node or a baselevel node while(next_node != curr_node && influenced_mask[next_row][next_col] != 1 ) { curr_node = next_node; next_node = ReceiverVector[curr_node]; // the index here say next row and column but actually this is // preserved from the previous loop so is the current node. influenced_mask[next_row][next_col] = 1; // get the row and column of the receiver retrieve_current_row_and_col(next_node, next_row, next_col); //cout << "Looping thought influence, next influenced is: " // << influenced_mask[next_row][next_col] << endl; } } } } } } // now write the mask as an LSDIndexRaster LSDIndexRaster Influence_by_NDV(NRows,NCols,XMinimum,YMinimum, DataResolution,int(NoDataValue),influenced_mask,GeoReferencingStrings); return Influence_by_NDV; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //---------------------------------------------------------------------------------------- // get_raster_values_for_nodes //---------------------------------------------------------------------------------------- // This function gets the values from a raster corresponding to the given nodes. vector<float> LSDFlowInfo::get_raster_values_for_nodes(LSDRaster& Raster, vector<int>& node_indices) { int N_nodes = node_indices.size(); vector<float> return_values(N_nodes,float(NoDataValue)); int row=0; int col=0; for(int i = 0; i < N_nodes; ++i) { if(node_indices[i] == NoDataValue) { return_values[i] = NoDataValue; } else { retrieve_current_row_and_col(node_indices[i],row,col); return_values[i] = Raster.get_data_element(row,col); } } return return_values; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // Hilltop flow routing code built around original code from Martin Hurst. Based on // Lea (1992), with improvements discussed by Tarboton (1997) and a solution to the // problem of looping flow paths implemented. // // This version performs a single trace from a specified node, and routes down until it // reaches a channel pixel // // THIS VERSION OF THE CODE RETAINS THE FLOODING METHOD TO ALLOW TRACES TO BE USED // ON RAW TOPOGRPAHY TO GET EVENT SCALE HILLSLOPE LENGTHS WITH NO SMOOTHING. IN // MOST CASES USE THE MAIN METHOD, TO ANALYSE SEDIMENT TRANSPORT OVER GEOMORPHIC TIME. // // This code is SLOW but robust, a refactored version may appear, but there may not be // enough whisky in Scotland to support that endeavour. // // The algorithm now checks for local uphill flows and in the case of identifying one, // D8 flow path is used to push the flow into the centre of the steepest downslope // cell, at which point the trace is restarted. The same technique is used to cope // with self intersections of the flow path. These problems are not solved in the // original paper and I think they are caused at least in part by the high resolution // topogrpahy we are using. // // The code is also now built to take a d infinity flow direction raster instead of an // aspect raster. See Tarboton (1997) for discussions on why this is the best solution. // // There are 4 outputs: // output_trace_coordinates - the output coordinates tracing the flow path // output_trace_metrics - the metrics derived from the flow routing // (i) X // (i) Y // (i) mean slope // (i) hillslope relief // (i) hillslope length // (i) channel ID @ lower boundary // output_channel_node -the nodeindex at the bounding channel // skip_trace - a bool object that specifies whether this trace has routed // successfully to the channel. // // SWDG (adapted by DTM) 23/3/15 //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= void LSDFlowInfo::D_Inf_single_trace_to_channel(LSDRaster Elevation, int start_node, LSDIndexRaster StreamNetwork, LSDRaster D_inf_Flowdir, vector< vector<float> >& output_trace_coordinates, vector<float>& output_trace_metrics, int& output_channel_node, bool& skip_trace) { //Declare parameters int i,j; int a = 0; int b = 0; float X,Y; float mean_slope, relief; float length, d; // int flag; int count = 0; // int DivergentCountFlag = 0; //Flag used to count the number of divergent cells encountered in a trace float PI = 3.14159265; float degs, degs_old, degs_new, theta; // float s_local, s_edge; float xo, yo, xi, yi, temp_yo1, temp_yo2, temp_xo1, temp_xo2; // bool skip_trace; //flag used to skip traces where no path to a stream can be found. Will only occur on noisy, raw topography //debugging counters int ns_count = 0; int s_count = 0; int neg_count = 0; int edge_count = 0; // int ht_count = 0; // a direction flag numbered 1,2,3,4 for E,S,W,N respectively int dir; float ymax = YMinimum + NRows*DataResolution; //Get data arrays from LSDRasters Array2D<float> zeta = Elevation.get_RasterData(); //elevation Array2D<int> stnet = StreamNetwork.get_RasterData(); // stream network Array2D<float> aspect = D_inf_Flowdir.get_RasterData(); //aspect // Array2D<float> slope = Slope.get_RasterData(); //slope Array2D<float> rads(NRows,NCols,NoDataValue); Array2D<float> path(NRows, NCols,0.0); Array2D<float> blank(NRows,NCols,0.0); int channel_node = int(NoDataValue); vector<float> trace_metrics; vector< vector<float> > trace_coordinates; vector<float> empty; trace_coordinates.push_back(empty); trace_coordinates.push_back(empty); int vec_size = 1000000; Array1D<double> easting(NCols); Array1D<double> northing(NRows); Array1D<double> east_vec(vec_size); Array1D<double> north_vec(vec_size); //calculate northing and easting for (i=0;i<NRows;++i) { northing[i] = ymax - i*DataResolution - 0.5; } for (j=0;j<NCols;++j) { easting[j] = XMinimum + j*DataResolution + 0.5; } // find node and trace downstream // ignore edge cells and non-hilltop cells // route initial node by aspect and get outlet coordinates int start_row, start_col; retrieve_current_row_and_col(start_node,start_row,start_col); bool flag = false; if (zeta[start_row][start_col] != NoDataValue) { length = 0; flag = true; count = 1; path = blank.copy(); // DivergentCountFlag = 0; //initialise count of divergent cells in trace skip_trace = false; //initialise skip trace flag as false, will only be switched if no path to stream can be found. Very rare. // ++ht_count; degs = aspect[start_row][start_col]; theta = BearingToRad(aspect[start_row][start_col]); a = start_row; b = start_col; path[a][b] += 1; east_vec[0] = easting[b]; north_vec[0] = northing[a]; // s_local = slope[a][b]; //test direction, calculate outlet coordinates and update indicies // easterly if (degs >= 45 && degs < 135) { //cout << "\neasterly" << endl; xo = 1, yo = (1+tan(theta))/2; d = abs(1/(2*cos(theta))); xi = 0, yi = yo; dir = 1; east_vec[count] = easting[b] + 0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; ++b; if (yi == 0) yi = 0.00001; else if (yi == 1) yi = 1 - 0.00001; } //southerly else if (degs >= 135 && degs < 225) { //cout << "\nsoutherly" << endl; xo = (1-(1/tan(theta)))/2, yo = 0; d = abs(1/(2*cos((PI/2)-theta))); xi = xo, yi = 1; dir = 2; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] - 0.5*DataResolution; ++a; if (xi == 0) xi = 0.00001; else if (xi == 1) xi = 1 - 0.00001; } // westerly else if (degs >= 225 && degs < 315) { xo = 0, yo = (1-tan(theta))/2; d = abs(1/(2*cos(theta))); xi = 1, yi = yo; dir = 3; east_vec[count] = easting[b] -0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; --b; if (yi == 0) yi = 0.00001; else if (yi == 1) yi = 1 - 0.00001; } //northerly else if (degs >= 315 || degs < 45) { xo = (1+(1/tan(theta)))/2, yo = 1; d = abs(1/(2*cos((PI/2) - theta))); xi = xo, yi = 0; dir = 4; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] + 0.5*DataResolution; --a; if (xi == 0) xi = 0.00001; else if (xi == 1) xi = 1 - 0.00001; } else { cout << "FATAL ERROR, Kinematic routing algorithm enountered null aspect value" << endl; exit(EXIT_FAILURE); } //collect slopes and totals weighted by path length length += d; // s_local = slope[a][b]; // place coordinates into output vector trace_coordinates[0].push_back(east_vec[count]); trace_coordinates[1].push_back(north_vec[count]); //continue trace until a stream node is encountered while (flag == true && a > 0 && a < NRows-1 && b > 0 && b < NCols-1) //added boudary checking to catch cells which flow off the edge of the DEM tile. { int a_2 = a; int b_2 = b; path[a][b] += 1; degs_old = degs; degs_new = aspect[a][b]; theta = BearingToRad(aspect[a][b]); ++count; // cout << "TEST1" << endl; //Test for perimeter flow paths if ((dir == 1 && degs_new > 0 && degs_new < 180) || (dir == 2 && degs_new > 90 && degs_new < 270) || (dir == 3 && degs_new > 180 && degs_new < 360) || ((dir == 4 && degs_new > 270) || (dir == 4 && degs_new < 90))) { // cout << "TEST1a" << endl; //DO NORMAL FLOW PATH //set xo, yo to 0 and 1 in turn and test for true outlet (xi || yi == 0 || 1) temp_yo1 = yi + (1-xi)*tan(theta); // xo = 1 temp_xo1 = xi + (1-yi)*(1/tan(theta)); // yo = 1 temp_yo2 = yi - xi*tan(theta); // xo = 0 temp_xo2 = xi - yi*(1/tan(theta)); // yo = 0 // can't outlet at same point as inlet if (dir == 1) temp_yo2 = -1; else if (dir == 2) temp_xo1 = -1; else if (dir == 3) temp_yo1 = -1; else if (dir == 4) temp_xo2 = -1; // s_local = slope[a][b]; if (temp_yo1 <= 1 && temp_yo1 > 0) { xo = 1, yo = temp_yo1; d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 0; yi = yo; dir = 1; east_vec[count] = easting[b] + 0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; ++b; if (xi== 0 && yi == 0) yi = 0.00001; else if (xi== 0 && yi == 1) yi = 1 - 0.00001; } else if (temp_xo2 <= 1 && temp_xo2 > 0) { xo = temp_xo2, yo = 0; d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo; yi = 1; dir = 2; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] - 0.5*DataResolution; ++a; if (xi== 0 && yi == 1) xi = 0.00001; else if (xi== 1 && yi == 1) xi = 1 - 0.00001; } else if (temp_yo2 <= 1 && temp_yo2 > 0) { xo = 0, yo = temp_yo2; d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1; yi = yo; dir = 3; east_vec[count] = easting[b] -0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; --b; if (xi== 1 && yi == 0) yi = 0.00001; else if (xi== 1 && yi == 1) yi = 1 - 0.00001; } else if (temp_xo1 <= 1 && temp_xo1 > 0) { xo = temp_xo1, yo = 1; d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo; yi = 0; dir = 4; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] + 0.5*DataResolution; --a; if (xi == 0 && yi == 0) xi = 0.00001; else if (xi== 1 && yi == 0) xi = 1 - 0.00001; } // cout << "TEST1_end" << endl; } else { // ROUTE ALONG EDGES // cout << "TEST-" << endl; if (dir == 1) { // cout << "TEST2" << endl; if (degs_new <= 90 || degs_new >= 270) //secondary compenent of flow is north { xo = 0.00001; yo = 1; // s_edge = abs(s_local*sin(theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo; yi = 1-yo; dir = 4; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] + 0.5*DataResolution; --a; } else if (degs_new > 90 && degs_new < 270) //secondary component is south { xo = 0.00001; yo = 0; // s_edge = abs(s_local*sin((PI/2)-theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo; yi = 1-yo; dir = 2; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] - 0.5*DataResolution; ++a; } else { cout << "Flow unable to route N or S " << endl; //something has gone very wrong... cout << "Trace skipped.\n" << endl; skip_trace = true; //exit(EXIT_FAILURE); } } else if (dir == 2) { // cout << "TEST3" << endl; if (degs_new >= 0 && degs_new <= 180) //secondary component is East { xo = 1, yo = 1-0.00001; // s_edge = abs(s_local*sin((2/PI)-theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1-xo, yi = yo; dir = 1; east_vec[count] = easting[b] + 0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; ++b; } else if (degs_new > 180 && degs_new <= 360) //secondary component is West { xo = 0, yo = 1-0.00001; // s_edge = abs(s_local*sin(theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1-xo, yi = yo; dir = 3; east_vec[count] = easting[b] -0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; --b; } else { cout << "Flow unable to route E or W" << endl; //something has gone very wrong... cout << "Trace skipped.\n" << endl; //something has gone very wrong... skip_trace = true; //exit(EXIT_FAILURE); } } else if (dir == 3) { // cout << "TEST4" << endl; if(degs_new >= 90 && degs_new <= 270) //secondary component is South { xo = 1-0.00001; yo = 0; // s_edge = abs(s_local*sin(theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo; yi = 1-yo; dir = 2; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] - 0.5*DataResolution; ++a; } else if (degs_new > 270 || degs_new < 90) //secondary component is North { xo = 1-0.00001, yo = 1; // s_edge = abs(s_local*sin((2/PI) - theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo; yi = 1- yo; dir = 4; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] + 0.5*DataResolution; --a; } else { cout << "Flow unable to route N or S" << endl; //something has gone very wrong... cout << "Trace skipped.\n" << endl; //something has gone very wrong... skip_trace = true; //exit(EXIT_FAILURE); } } else if (dir == 4) { // cout << "TEST5" << endl; if(degs_new >= 180 && degs_new <= 360) //secondary component is West { xo = 0, yo = 0.00001; // s_edge = abs(s_local*sin((PI/2) - theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1-xo; yi = yo; dir = 3; east_vec[count] = easting[b] -0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; --b; } else if (degs_new >= 0 && degs_new < 180) //secondary component is East { xo = 1, yo = 0.00001; // s_edge = abs(s_local*sin(theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1-xo, yi = yo; dir = 1; east_vec[count] = easting[b] + 0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; ++b; } else { cout << "Flow unable to route E or W" << endl; //something has gone very wrong... cout << "Trace skipped.\n" << endl; //something has gone very wrong... skip_trace = true; //exit(EXIT_FAILURE); } } // cout << "TEST6" << endl; } if (path[a][b] < 1) length += d; // only update length on 'first slosh' degs = degs_new; if(zeta[a][b] - zeta[a_2][b_2] > 0) { length -= d; //remove uphill length from trace a = a_2; b = b_2; // cout << "TEST7" << endl; //restart trace degs = aspect[a][b]; theta = BearingToRad(aspect[a][b]); path[a][b] += 1; // s_local = slope[a][b]; length += sqrt((pow((xo-0.5),2) + pow((yo-0.5),2))); //update length to cope with the 'jump' to the centre of the cell to restart the trace //test direction, calculate outlet coordinates and update indices easterly if (degs >= 45 && degs < 135) { xo = 1, yo = (1+tan(theta))/2; d = abs(1/(2*cos(theta))); xi = 0, yi = yo; dir = 1; east_vec[count] = easting[b] + 0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; ++b; } //southerly else if (degs >= 135 && degs < 225) { xo = (1-(1/tan(theta)))/2, yo = 0; d = abs(1/(2*cos((PI/2)-theta))); xi = xo, yi = 1; dir = 2; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] - 0.5*DataResolution; ++a; } // westerly else if (degs >= 225 && degs < 315) { xo = 0, yo = (1-tan(theta))/2; d = abs(1/(2*cos(theta))); xi = 1, yi = yo; dir = 3; east_vec[count] = easting[b] -0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; --b; } //northerly else if (degs >= 315 || degs < 45) { xo = (1+(1/tan(theta)))/2, yo = 1; d = abs(1/(2*cos((PI/2) - theta))); xi = xo, yi = 0; dir = 4; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] + 0.5*DataResolution; --a; } else { cout << "FATAL ERROR, Kinematic routing algorithm enountered null aspect value" << endl; exit(EXIT_FAILURE); } //collect slopes and totals weighted by path length length += d; // s_local = slope[a][b]; } if (path[a][b] >= 1) //self intersect/'slosh' { degs = aspect[a][b]; theta = rads[a][b]; path[a][b] += 1; // s_local = slope[a][b]; a_2 = a; b_2 = b; length += sqrt((pow((xo-0.5),2) + pow((yo-0.5),2))); //update length to cope with the 'jump' to the centre of the cell to restart the trace //test direction, calculate outlet coordinates and update indices // easterly if (degs >= 45 && degs < 135) { xo = 1, yo = (1+tan(theta))/2; d = abs(1/(2*cos(theta))); xi = 0, yi = yo; dir = 1; east_vec[count] = easting[b] + 0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; ++b; } //southerly else if (degs >= 135 && degs < 225) { xo = (1-(1/tan(theta)))/2, yo = 0; d = abs(1/(2*cos((PI/2)-theta))); xi = xo, yi = 1; dir = 2; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] - 0.5*DataResolution; ++a; } // westerly else if (degs >= 225 && degs < 315) { xo = 0, yo = (1-tan(theta))/2; d = abs(1/(2*cos(theta))); xi = 1, yi = yo; dir = 3; east_vec[count] = easting[b] -0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; --b; } //northerly else if (degs >= 315 || degs < 45) { xo = (1+(1/tan(theta)))/2, yo = 1; d = abs(1/(2*cos((PI/2) - theta))); xi = xo, yi = 0; dir = 4; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] + 0.5*DataResolution; --a; } else { cout << "FATAL ERROR, Kinematic routing algorithm enountered null aspect value" << endl; exit(EXIT_FAILURE); } //collect slopes and totals weighted by path length length += d; // s_local = slope[a][b]; } // test for plan curvature here and set a flag if flow is divergent or convergent but continue trace regardless // The larger the counter the more convergent or divergent the trace is // if (abs(PlanCurvature.get_data_element(a,b)) > (0.001)) ++DivergentCountFlag; if (path[a][b] >=3) skip_trace = true;//update flag if a trace cannot complete, so that we can track errors. if (a == 0 || b == 0 || a == NRows-1 || b == NCols-1 || stnet[a][b] != NoDataValue || stnet[a-1][b-1] != NoDataValue || stnet[a][b-1] != NoDataValue || stnet[a+1][b-1] != NoDataValue || stnet[a+1][b] != NoDataValue || stnet[a+1][b+1] != NoDataValue || stnet[a][b+1] != NoDataValue || stnet[a-1][b+1] != NoDataValue || stnet[a-1][b] != NoDataValue || path[a][b] >= 3 || skip_trace == true) flag = false; // save trace coordinates for this iteration. trace_coordinates[0].push_back(east_vec[count]); trace_coordinates[1].push_back(north_vec[count]); } if (a == 0 || b == 0 || a == NRows-1 || b == NCols-1 ) { // avoid going out of bounds. // this is caused by having a hilltop on the first row or col away from the border // eg i or j == 1 or nrows/ncols - 2 and flowing towards the edge. // can fix with a test here for if streamnet[a][b] != NDV otherwise trace will fail *correctly* ++edge_count; } else { //if trace finished at a stream, print hillslope info. if (stnet[a][b] != NoDataValue || stnet[a-1][b-1] != NoDataValue || stnet[a][b-1] != NoDataValue || stnet[a+1][b-1] != NoDataValue || stnet[a+1][b] != NoDataValue || stnet[a+1][b+1] != NoDataValue || stnet[a][b+1] != NoDataValue || stnet[a-1][b+1] != NoDataValue || stnet[a-1][b] != NoDataValue) { path[a][b] = 1; ++s_count; X = XMinimum + j*DataResolution; Y = YMinimum - (NRows-i)*DataResolution; relief = zeta[start_row][start_col] - zeta[a][b]; mean_slope = relief/(length * DataResolution); trace_metrics.push_back(X); trace_metrics.push_back(Y); trace_metrics.push_back(float(start_node)); trace_metrics.push_back(mean_slope); trace_metrics.push_back(relief); trace_metrics.push_back(length*DataResolution); if (stnet[a][b] != NoDataValue) { channel_node = retrieve_node_from_row_and_column(a,b); trace_metrics.push_back(float(channel_node)); } // find nearest channel pixel within 1m buffer - if more than one, choose furthest downstream else { float min_elev=NoDataValue; if (stnet[a-1][b-1] != NoDataValue) { if (min_elev == NoDataValue || zeta[a-1][b-1] < min_elev) { min_elev = zeta[a-1][b-1]; channel_node = retrieve_node_from_row_and_column(a-1,b-1); } } else if (stnet[a-1][b] != NoDataValue) { if (min_elev == NoDataValue || zeta[a-1][b] < min_elev) { min_elev = zeta[a-1][b]; channel_node = retrieve_node_from_row_and_column(a-1,b); } } else if (stnet[a-1][b+1] != NoDataValue) { if (min_elev == NoDataValue || zeta[a-1][b+1] < min_elev) { min_elev = zeta[a-1][b+1]; channel_node = retrieve_node_from_row_and_column(a-1,b+1); } } else if (stnet[a][b-1] != NoDataValue) { if (min_elev == NoDataValue || zeta[a][b-1] < min_elev) { min_elev = zeta[a][b-1]; channel_node = retrieve_node_from_row_and_column(a,b-1); } } else if (stnet[a][b+1] != NoDataValue) { if (min_elev == NoDataValue || zeta[a][b+1] < min_elev) { min_elev = zeta[a][b+1]; channel_node = retrieve_node_from_row_and_column(a,b+1); } } else if (stnet[a+1][b-1] != NoDataValue) { if (min_elev == NoDataValue || zeta[a+1][b-1] < min_elev) { min_elev = zeta[a+1][b-1]; channel_node = retrieve_node_from_row_and_column(a+1,b-1); } } else if (stnet[a+1][b] != NoDataValue) { if (min_elev == NoDataValue || zeta[a+1][b] < min_elev) { min_elev = zeta[a+1][b]; channel_node = retrieve_node_from_row_and_column(a+1,b); } } else if (stnet[a+1][b+1] != NoDataValue) { if (min_elev == NoDataValue || zeta[a+1][b+1] < min_elev) { min_elev = zeta[a+1][b+1]; channel_node = retrieve_node_from_row_and_column(a+1,b+1); } } trace_metrics.push_back(float(channel_node)); } // if (relief > 0) ofs << X << "," << Y << "," << hilltops[i][j] << "," << mean_slope << "," << relief << "," << length*DataResolution << "," << basin[i][j] << "," << stnet[a][b] << "," << slope[i][j] << "," << DivergentCountFlag << "\n"; // else ++neg_count; if (relief <= 0) ++neg_count; } else { //unable to route using aspects //this will encompass the skipped traces // ofs << "fail: " << a << " " << b << " " << i << " " << j << endl; ++ns_count; } } } output_trace_coordinates = trace_coordinates; output_trace_metrics = trace_metrics; output_channel_node = channel_node; } //---------------------------------------------------------------------------------------------------------------------- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // Hilltop flow routing code built around original code from Martin Hurst. Based on // Lea (1992), with improvements discussed by Tarboton (1997) and a solution to the // problem of looping flow paths implemented. // // This code is SLOW but robust, a refactored version may appear, but there may not be // enough whisky in Scotland to support that endeavour. // // The algorithm now checks for local uphill flows and in the case of identifying one, // D8 flow path is used to push the flow into the centre of the steepest downslope // cell, at which point the trace is restarted. The same technique is used to cope // with self intersections of the flow path. These problems are not solved in the // original paper and I think they are caused at least in part by the high resolution // topogrpahy we are using. // // The code is also now built to take a d infinity flow direction raster instead of an // aspect raster. See Tarboton (1997) for discussions on why this is the best solution. // // The Basins input raster is used to code each hilltop into a basin to allow basin // averaging to take place. // // The final 5 parameters are used to set up printing flow paths to files for visualisation, // if this is not needed simply pass in false to the two boolean switches and empty variables for the // others, and the code will run as normal. // // The structure of the returned vector< Array2D<float> > is as follows: // [0] Hilltop Network coded with stream ID // [1] Hillslope Lengths // [2] Slope // [3] Relief // (4) Fraction Rock Exposure // // SWDG 12/2/14 //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= vector< Array2D<float> > LSDFlowInfo::HilltopFlowRoutingBedrock(LSDRaster Elevation, LSDRaster Hilltops, LSDRaster Slope, LSDIndexRaster StreamNetwork, LSDRaster Aspect, string Prefix, LSDIndexRaster Basins, LSDRaster PlanCurvature, bool print_paths_switch, int thinning, string trace_path, bool basin_filter_switch, vector<int> Target_Basin_Vector, LSDRaster RockExposure){ //Declare parameters int i,j; int a = 0; int b = 0; float X,Y; float mean_slope, relief; float length, d; float rock_exposure; int flag; int count = 0; int DivergentCountFlag = 0; //Flag used to count the number of divergent cells encountered in a trace int PlanarCountFlag; float PI = 3.14159265; float degs, degs_new, theta; float s_local, s_edge; float xo, yo, xi, yi, temp_yo1, temp_yo2, temp_xo1, temp_xo2; bool skip_trace; //flag used to skip traces where no path to a stream can be found. Will only occur on noisy, raw topography float E_Star = 0; float R_Star = 0; float EucDist = 0; //debugging counters int ns_count = 0; int s_count = 0; int neg_count = 0; int edge_count = 0; int ht_count = 0; // a direction flag numbered 1,2,3,4 for E,S,W,N respectively int dir; float ymax = YMinimum + NRows*DataResolution; //Get data arrays from LSDRasters Array2D<float> zeta = Elevation.get_RasterData(); //elevation Array2D<int> stnet = StreamNetwork.get_RasterData(); // stream network Array2D<float> aspect = Aspect.get_RasterData(); //aspect Array2D<float> hilltops = Hilltops.get_RasterData(); //hilltops Array2D<float> slope = Slope.get_RasterData(); //hilltops Array2D<int> basin = Basins.get_RasterData(); //basins Array2D<float> rock = RockExposure.get_RasterData(); // Rock Exposure //empty arrays for data to be stored in Array2D<float> rads(NRows,NCols); Array2D<float> path(NRows, NCols, 0.0); Array2D<float> blank(NRows, NCols, 0.0); Array2D<float> RoutedHilltops(NRows,NCols,NoDataValue); Array2D<float> HillslopeLength_Array(NRows,NCols,NoDataValue); Array2D<float> Slope_Array(NRows,NCols,NoDataValue); Array2D<float> Relief_Array(NRows,NCols,NoDataValue); Array2D<float> Rock_Array(NRows,NCols,NoDataValue); //vector to store the output data arrays in one vector that can be returned vector< Array2D<float> > OutputArrays; int vec_size = 1000000; Array1D<double> easting(NCols); Array1D<double> northing(NRows); Array1D<double> east_vec(vec_size); Array1D<double> north_vec(vec_size); ofstream ofs; //create the output filename from the user supplied filename prefix stringstream ss_filename; ss_filename << Prefix << "_HilltopData.csv"; ofs.open(ss_filename.str().c_str()); if( ofs.fail() ){ cout << "\nFATAL ERROR: unable to write to " << ss_filename.str() << endl; exit(EXIT_FAILURE); } ofs << "X,Y,hilltop_id,S,R,Lh,BasinID,StreamID,HilltopSlope,DivergentCount\n"; //calculate northing and easting for (i=0;i<NRows;++i){ northing[i] = ymax - i*DataResolution - 0.5; } for (j=0;j<NCols;++j){ easting[j] = XMinimum + j*DataResolution + 0.5; } //convert aspects to radians with east as theta = 0/2*pi for (i=0; i<NRows; ++i) { for (j=0; j<NCols; ++j) { //convert aspects to radians with east as theta = 0/2*pi if (rads[i][j] != NoDataValue) rads[i][j] = BearingToRad(aspect[i][j]); } } // cycle through study area, find hilltops and trace downstream for (i=1; i<NRows-1; ++i) { cout << flush << "\tRow: " << i << " of = " << NRows-1 << " \r"; for (j=1; j<NCols-1; ++j) { // ignore edge cells and non-hilltop cells // route initial node by aspect and get outlet coordinates if (hilltops[i][j] != NoDataValue) { length = 0; rock_exposure = 0; flag = true; count = 1; path = blank.copy(); DivergentCountFlag = 0; //initialise count of divergent cells in trace PlanarCountFlag = 0; skip_trace = false; //initialise skip trace flag as false, will only be switched if no path to stream can be found. Very rare. E_Star = 0; R_Star = 0; EucDist = 0; ++ht_count; degs = aspect[i][j]; theta = rads[i][j]; a = i; b = j; path[a][b] += 1; east_vec[0] = easting[b]; north_vec[0] = northing[a]; s_local = slope[a][b]; //test direction, calculate outlet coordinates and update indicies // easterly if (degs >= 45 && degs < 135) { //cout << "\neasterly" << endl; xo = 1, yo = (1+tan(theta))/2; d = abs(1/(2*cos(theta))); xi = 0, yi = yo; dir = 1; east_vec[count] = easting[b] + 0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; ++b; if (yi == 0) yi = 0.00001; else if (yi == 1) yi = 1 - 0.00001; } //southerly else if (degs >= 135 && degs < 225) { //cout << "\nsoutherly" << endl; xo = (1-(1/tan(theta)))/2, yo = 0; d = abs(1/(2*cos((PI/2)-theta))); xi = xo, yi = 1; dir = 2; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] - 0.5*DataResolution; ++a; if (xi == 0) xi = 0.00001; else if (xi == 1) xi = 1 - 0.00001; } // westerly else if (degs >= 225 && degs < 315) { xo = 0, yo = (1-tan(theta))/2; d = abs(1/(2*cos(theta))); xi = 1, yi = yo; dir = 3; east_vec[count] = easting[b] -0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; --b; if (yi == 0) yi = 0.00001; else if (yi == 1) yi = 1 - 0.00001; } //northerly else if (degs >= 315 || degs < 45) { xo = (1+(1/tan(theta)))/2, yo = 1; d = abs(1/(2*cos((PI/2) - theta))); xi = xo, yi = 0; dir = 4; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] + 0.5*DataResolution; --a; if (xi == 0) xi = 0.00001; else if (xi == 1) xi = 1 - 0.00001; } else { cout << "FATAL ERROR, Kinematic routing algorithm enountered null aspect value" << endl; exit(EXIT_FAILURE); } //collect slopes and totals weighted by path length length += d; s_local = slope[a][b]; rock_exposure += rock[a][b]*d; //continue trace until a stream node is encountered while (flag == true && a > 0 && a < NRows-1 && b > 0 && b < NCols-1) { //added boudary checking to catch cells which flow off the edge of the DEM tile. path[a][b] += 1; degs_new = aspect[a][b]; theta = rads[a][b]; ++count; //Test for perimeter flow paths if ((dir == 1 && degs_new > 0 && degs_new < 180) || (dir == 2 && degs_new > 90 && degs_new < 270) || (dir == 3 && degs_new > 180 && degs_new < 360) || ((dir == 4 && degs_new > 270) || (dir == 4 && degs_new < 90))) { //DO NORMAL FLOW PATH //set xo, yo to 0 and 1 in turn and test for true outlet (xi || yi == 0 || 1) temp_yo1 = yi + (1-xi)*tan(theta); // xo = 1 temp_xo1 = xi + (1-yi)*(1/tan(theta)); // yo = 1 temp_yo2 = yi - xi*tan(theta); // xo = 0 temp_xo2 = xi - yi*(1/tan(theta)); // yo = 0 // can't outlet at same point as inlet if (dir == 1) temp_yo2 = -1; else if (dir == 2) temp_xo1 = -1; else if (dir == 3) temp_yo1 = -1; else if (dir == 4) temp_xo2 = -1; s_local = slope[a][b]; if (temp_yo1 <= 1 && temp_yo1 > 0) { xo = 1, yo = temp_yo1; d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 0, yi = yo, dir = 1; east_vec[count] = easting[b] + 0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; ++b; if (xi== 0 && yi == 0) yi = 0.00001; else if (xi== 0 && yi == 1) yi = 1 - 0.00001; } else if (temp_xo2 <= 1 && temp_xo2 > 0) { xo = temp_xo2, yo = 0; d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 1, dir = 2; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] - 0.5*DataResolution; ++a; if (xi== 0 && yi == 1) xi = 0.00001; else if (xi== 1 && yi == 1) xi = 1 - 0.00001; } else if (temp_yo2 <= 1 && temp_yo2 > 0) { xo = 0, yo = temp_yo2; d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1, yi = yo, dir = 3; east_vec[count] = easting[b] -0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; --b; if (xi== 1 && yi == 0) yi = 0.00001; else if (xi== 1 && yi == 1) yi = 1 - 0.00001; } else if (temp_xo1 <= 1 && temp_xo1 > 0) { xo = temp_xo1, yo = 1; d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 0, dir = 4; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] + 0.5*DataResolution; --a; if (xi == 0 && yi == 0) xi = 0.00001; else if (xi== 1 && yi == 0) xi = 1 - 0.00001; } } else { // ROUTE ALONG EDGES if (dir == 1) { if (degs_new <= 90 || degs_new >= 270) { //secondary compenent of flow is north xo = 0.00001, yo = 1; s_edge = abs(s_local*sin(theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 1-yo; dir = 4; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] + 0.5*DataResolution; --a; } else if (degs_new > 90 && degs_new < 270) { //secondary component is south xo = 0.00001, yo = 0; s_edge = abs(s_local*sin((PI/2)-theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 1-yo; dir = 2; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] - 0.5*DataResolution; ++a; } else { cout << "Flow unable to route N or S " << endl; //something has gone very wrong... cout << "Trace skipped.\n" << endl; skip_trace = true; //exit(EXIT_FAILURE); } } else if (dir == 2) { if (degs_new >= 0 && degs_new <= 180) { //secondary component is East xo = 1, yo = 1-0.00001; s_edge = abs(s_local*sin((2/PI)-theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1-xo, yi = yo; dir = 1; east_vec[count] = easting[b] + 0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; ++b; } else if (degs_new > 180 && degs_new <= 360) { //secondary component is West xo = 0, yo = 1-0.00001; s_edge = abs(s_local*sin(theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1-xo, yi = yo; dir = 3; east_vec[count] = easting[b] -0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; --b; } else { cout << "Flow unable to route E or W" << endl; //something has gone very wrong... cout << "Trace skipped.\n" << endl; skip_trace = true; //exit(EXIT_FAILURE); } } else if (dir == 3) { if (degs_new >= 90 && degs_new <= 270) { //secondary component is South xo = 1-0.00001, yo = 0; s_edge = abs(s_local*sin(theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 1-yo; dir = 2; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] - 0.5*DataResolution; ++a; } else if (degs_new > 270 || degs_new < 90) { //secondary component is North xo = 1-0.00001, yo = 1; s_edge = abs(s_local*sin((2/PI) - theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 1- yo; dir = 4; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] + 0.5*DataResolution; --a; } else { cout << "Flow unable to route N or S" << endl; //something has gone very wrong... cout << "Trace skipped.\n" << endl; skip_trace = true; //exit(EXIT_FAILURE); } } else if (dir == 4) { if (degs_new >= 180 && degs_new <= 360) { //secondary component is West xo = 0, yo = 0.00001; s_edge = abs(s_local*sin((PI/2) - theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1-xo, yi = yo; dir = 3; east_vec[count] = easting[b] -0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; --b; } else if (degs_new >= 0 && degs_new < 180) { //secondary component is East xo = 1, yo = 0.00001; s_edge = abs(s_local*sin(theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1-xo, yi = yo; dir = 1; east_vec[count] = easting[b] + 0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; ++b; } else { cout << "Flow unable to route E or W" << endl; //something has gone very wrong... cout << "Trace skipped.\n" << endl; skip_trace = true; //exit(EXIT_FAILURE); } } } if (path[a][b] < 1){ // only update length on 'first slosh' length += d; rock_exposure += rock[a][b]*d; } else if (path[a][b] >= 3){ //update the skip trace flag so we can categorise each trace skip_trace = true; } degs = degs_new; // test for plan curvature here and set a flag if flow is divergent or convergent but continue trace regardless // The larger the counter the more convergent or divergent the trace is if (abs(PlanCurvature.get_data_element(a,b)) > (0.001)){ ++DivergentCountFlag; } else { ++PlanarCountFlag; } if (a == 0 || b == 0 || a == NRows-1 || b == NCols-1 || stnet[a][b] != NoDataValue || stnet[a-1][b-1] != NoDataValue || stnet[a][b-1] != NoDataValue || stnet[a+1][b-1] != NoDataValue || stnet[a+1][b] != NoDataValue || stnet[a+1][b+1] != NoDataValue || stnet[a][b+1] != NoDataValue || stnet[a-1][b+1] != NoDataValue || stnet[a-1][b] != NoDataValue || path[a][b] >= 3 || skip_trace == true) flag = false; } if (a == 0 || b == 0 || a == NRows-1 || b == NCols-1 ){ // avoid going out of bounds. // this is caused by having a hilltop on the first row or col away from the border // eg i or j == 1 or nrows/ncols - 2 and flowing towards the edge. // can fix with a test here for if streamnet[a][b] != NDV otherwise trace will fail *correctly* ++edge_count; } else { //if trace finished at a stream, print hillslope info. if (stnet[a][b] != NoDataValue || stnet[a-1][b-1] != NoDataValue || stnet[a][b-1] != NoDataValue || stnet[a+1][b-1] != NoDataValue || stnet[a+1][b] != NoDataValue || stnet[a+1][b+1] != NoDataValue || stnet[a][b+1] != NoDataValue || stnet[a-1][b+1] != NoDataValue || stnet[a-1][b] != NoDataValue) { path[a][b] = 1; ++s_count; X = XMinimum + j*DataResolution; Y = YMinimum - (NRows-i)*DataResolution; relief = zeta[i][j] - zeta[a][b]; mean_slope = relief/(length * DataResolution); // update arrays with the current metrics RoutedHilltops[i][j] = 1; HillslopeLength_Array[i][j] = (length * DataResolution); Slope_Array[i][j] = mean_slope; Relief_Array[i][j] = relief; Rock_Array[i][j] = rock_exposure/length; //calculate an E* and R* Value assuming S_c of 0.8 E_Star = (2.0 * abs(hilltops[i][j])*(length*DataResolution))/0.8; R_Star = relief/((length*DataResolution)*0.8); //calulate the Euclidean distance between the start and end points of the trace EucDist = sqrt((pow(((i+0.5)-(a+yo)),2) + pow(((j+0.5)-(b+xo)),2))) * DataResolution; if (relief > 0){ ofs << X << "," << Y << "," << hilltops[i][j] << "," << mean_slope << "," << relief << "," << length*DataResolution << "," << basin[i][j] << "," << stnet[a][b] << "," << slope[i][j] << "," << DivergentCountFlag << "," << PlanarCountFlag << "," << E_Star << "," << R_Star << "," << EucDist << "," << rock_exposure/length << "\n"; } else { ++neg_count; } } else{ //unable to route using aspects //this will encompass skipped traces ofs << "fail: " << a << " " << b << " " << i << " " << j << endl; ++ns_count; } } //This block checks the various path printing options and writes the data out accordingly if (print_paths_switch == true){ if (ht_count % thinning == 0){ if (hilltops[i][j] != NoDataValue && skip_trace == false){ //check that the current i,j tuple corresponds to a hilltop, ie there is actually a trace to write to file, and check that the trace was valid. //create stringstream object to create filename ofstream pathwriter; //create the output filename from the user supplied path stringstream ss_path; ss_path << trace_path << i << "_" << j << "_trace.txt"; pathwriter.open(ss_path.str().c_str()); if(pathwriter.fail() ){ cout << "\nFATAL ERROR: unable to write to " << ss_path.str() << endl; exit(EXIT_FAILURE); } for (int v = 0; v < count+1; ++v){ if (basin_filter_switch == false){ pathwriter << setiosflags(ios::fixed) << setprecision(7) << east_vec[v] << " " << north_vec[v] << " " << DivergentCountFlag << " " << length << " " << PlanarCountFlag << " " << E_Star << " " << R_Star << " " << EucDist << "," << rock_exposure/length << endl; } else if (basin_filter_switch == true && find(Target_Basin_Vector.begin(), Target_Basin_Vector.end(), basin[a][b]) != Target_Basin_Vector.end() && find(Target_Basin_Vector.begin(), Target_Basin_Vector.end(), basin[i][j]) != Target_Basin_Vector.end()){ //is this correct? evaulating to not equal one past the end of the vector should equal that the value is found pathwriter << setiosflags(ios::fixed) << setprecision(7) << east_vec[v] << " " << north_vec[v] << " " << DivergentCountFlag << " " << length << " " << PlanarCountFlag << " " << E_Star << " " << R_Star << " " << EucDist << "," << rock_exposure/length << endl; } } pathwriter.close(); } } } // End of path printing logic } } //for loop i,j } ofs.close(); //add the data arrays to the output vector OutputArrays.push_back(RoutedHilltops); OutputArrays.push_back(HillslopeLength_Array); OutputArrays.push_back(Slope_Array); OutputArrays.push_back(Relief_Array); OutputArrays.push_back(Rock_Array); //Print debugging info to screen cout << endl; //push output onto new line cout << "Hilltop count: " << ht_count << endl; cout << "Stream count: " << s_count << endl; cout << "Fail count: " << ns_count << endl; cout << "Uphill count: " << neg_count << endl; cout << "Edge count: " << edge_count << endl; return OutputArrays; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // This method removes end nodes which are not the uppermost extent of the channel network. // SWDG 23/7/15 //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= vector<int> LSDFlowInfo::ProcessEndPointsToChannelHeads(LSDIndexRaster Ends){ Array2D<int> EndArray = Ends.get_RasterData(); vector<int> Sources; //make a map containing each nodeindex where true means it is a valid channel head, eg the top of the network map<int,bool> EndStatus; vector<int> EndNodes; for(int i=1; i<NRows-1; ++i){ for(int j=1; j<NCols-1; ++j){ if (EndArray[i][j] != NoDataValue){ int nodeindex = retrieve_node_from_row_and_column (i,j); EndStatus[nodeindex] = true; EndNodes.push_back(nodeindex); } } } for (int q = 0; q < int(EndNodes.size());++q){ cout << flush << q << " of " << EndNodes.size() << "\r"; int CurrentNode = EndNodes[q]; if (EndStatus[CurrentNode] == true){ bool stop = false; while (stop == false){ int DownslopeNode; int Downslopei; int Downslopej; //get steepest descent neighbour retrieve_receiver_information(CurrentNode,DownslopeNode,Downslopei,Downslopej); if (find(EndNodes.begin(), EndNodes.end(), DownslopeNode) != EndNodes.end()){ EndStatus[DownslopeNode] = false; stop = true; } //check for out of bounds if (Downslopei == 0 || Downslopei == NRows - 1 || Downslopej == 0 || Downslopej == NCols - 1){ stop = true; } //check for a node with no downslope neughbours if (CurrentNode == DownslopeNode){ stop = true; } CurrentNode = DownslopeNode; } } } cout << endl; for (int q = 0; q < int(EndNodes.size());++q){ if (EndStatus[EndNodes[q]] == true){ Sources.push_back(EndNodes[q]); } } return Sources; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // This method removes single pixel channels from a channel network. // SWDG 23/7/15 //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- vector<int> LSDFlowInfo::RemoveSinglePxChannels(LSDIndexRaster StreamNetwork, vector<int> Sources){ for (int q = 0; q < int(Sources.size());++q){ int CurrentNode = Sources[q]; int Currenti; int Currentj; retrieve_current_row_and_col(CurrentNode,Currenti,Currentj); int CurrentOrder = StreamNetwork.get_data_element(Currenti,Currentj); //get steepest descent neighbour int DownslopeNode; int Downslopei; int Downslopej; retrieve_receiver_information(CurrentNode,DownslopeNode,Downslopei,Downslopej); int DownslopeOrder = StreamNetwork.get_data_element(Downslopei,Downslopej); if (CurrentOrder != DownslopeOrder){ //remove the value from the list of nodes -> Sources is passed by val, so this will not change values in sources outide this method Sources.erase(remove(Sources.begin(), Sources.end(), Sources[q]), Sources.end()); } } return Sources; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // This function starts from a given node index and then goes downstream // until it either hits a baselevel node or until it has accumulated a // number of visited pixels //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- int LSDFlowInfo::get_downslope_node_after_fixed_visited_nodes(int source_node, int outlet_node, int n_nodes_to_visit, LSDIndexRaster& VisitedRaster) { int n_visited = 0; int current_node, receiver_node,row, col; int bottom_node; bool Am_I_at_the_bottom_of_the_channel = false; current_node = source_node; // you start from the source node and work your way downstream while( Am_I_at_the_bottom_of_the_channel == false ) { // get the reciever node retrieve_receiver_information(current_node,receiver_node, row,col); // check if this is a base level node if (current_node == receiver_node) { Am_I_at_the_bottom_of_the_channel = true; bottom_node = receiver_node; } else if (receiver_node == outlet_node) { Am_I_at_the_bottom_of_the_channel = true; bottom_node = receiver_node; } else { // check to see if this node has been visited, if so increment the n_visited // iterator if (VisitedRaster.get_data_element(row,col) == 1) { n_visited++; } else { VisitedRaster.set_data_element(row, col, 1); } // see if we have collected enough nodes to visit if (n_visited >= n_nodes_to_visit) { Am_I_at_the_bottom_of_the_channel = true; bottom_node = receiver_node; } } current_node = receiver_node; } return bottom_node; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // This function gets the flow length between two nodes. // FJC 29/09/16 //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- float LSDFlowInfo::get_flow_length_between_nodes(int UpstreamNode, int DownstreamNode) { float length = 0; float root_2 = 1.4142135623; if (UpstreamNode == DownstreamNode) { cout << "You've picked the same node! Flow Length is 0." << endl; } else { int upstream_test = is_node_upstream(DownstreamNode, UpstreamNode); if (upstream_test != 1) { cout << "FlowInfo 7430: FATAL ERROR: The selected node is not upstream" << endl; length = float(NoDataValue); } else { bool ReachedChannel = false; int CurrentNode = UpstreamNode; while (ReachedChannel == false) { //get receiver information int ReceiverNode, ReceiverRow, ReceiverCol; retrieve_receiver_information(CurrentNode, ReceiverNode, ReceiverRow, ReceiverCol); //if node is at baselevel then exit if (CurrentNode == ReceiverNode) { ReachedChannel = true; //cout << "You reached a baselevel node, returning baselevel" << endl; } //if receiver is a channel > threshold then get the stream order if (ReceiverNode == DownstreamNode) { ReachedChannel = true; } else { //move downstream CurrentNode = ReceiverNode; // update length if (retrieve_flow_length_code_of_node(ReceiverNode) == 1){ length += DataResolution; } else if (retrieve_flow_length_code_of_node(ReceiverNode) == 2){ length += (DataResolution * root_2); } } } } } return length; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // This function gets the Euclidian distance between two nodes in metres // FJC 17/02/17 //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- float LSDFlowInfo::get_Euclidian_distance(int node_A, int node_B) { int row_A, row_B, col_A, col_B; // get the row and cols of the nodes retrieve_current_row_and_col(node_A, row_A, col_A); retrieve_current_row_and_col(node_B, row_B, col_B); float row_length = (row_B - row_A)*DataResolution; float col_length = (col_B - col_A)*DataResolution; //find the distance between these nodes float dist = sqrt(row_length*row_length + col_length*col_length); return dist; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // Snap a given point to the nearest hilltop pixel, within a search radius. // Returns the nodeindex of the snapped point. // SWDG 23/1/17 //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- int LSDFlowInfo::snap_to_hilltop(int a, int b, int search_radius, LSDRaster& Hilltops){ int tmpNode; if (Hilltops.get_data_element(a,b) != NoDataValue){ // The point is already on a hilltop pixel! tmpNode = retrieve_node_from_row_and_column(a,b); } else{ vector<int> Nodes_in_window; vector<float> Dists_in_window; vector<float> Dists_in_window_sorted; vector<size_t> index_map; Nodes_in_window.reserve(4 * search_radius); Dists_in_window.reserve(4 * search_radius); Dists_in_window_sorted.reserve(4 * search_radius); index_map.reserve(4 * search_radius); //set up the bounding box int a_min = a - search_radius; int a_max = a + search_radius; int b_min = b - search_radius; int b_max = b + search_radius; //out of bounds checking if (a_min < 0){a_min = 0;} if (b_min < 0){b_min = 0;} if (a_max > (NRows - 1)){a_max = (NRows - 1);} if (b_max > (NCols - 1)){b_max = (NCols - 1);} // only iterate over the search area. for (int i = a_min; i < a_max; ++i){ for (int j = b_min; j < b_max; ++j){ if (Hilltops.get_data_element(i, j) != NoDataValue){ //get the nodeindex and distance from user defined point for each cell in the search window tmpNode = retrieve_node_from_row_and_column(i,j); Nodes_in_window.push_back(tmpNode); float Dist = distbetween(a,b,i,j); Dists_in_window.push_back(Dist); } } } matlab_float_sort(Dists_in_window, Dists_in_window_sorted, index_map); //the hilltop node with the smallest distance to the user defined point tmpNode = Nodes_in_window[index_map[0]]; } return tmpNode; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // Wrapper around snap_to_hilltop function to process a collection of utm points. // Writes the the nodeindex of each snapped point to SnappedNodes and the // coordinate count (first coordinate pair is 0, second is 1 and so on) is written // to Valid_node_IDs. // SWDG 23/1/17 //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- void LSDFlowInfo::snap_to_hilltops(vector<float> x_locs, vector<float> y_locs, int search_radius, LSDRaster& Hilltops, vector<int>& SnappedNodes, vector<int>& Valid_node_IDs){ for (int q = 0; q < int(x_locs.size()); ++q){ bool is_in_raster = check_if_point_is_in_raster(x_locs[q], y_locs[q]); if (is_in_raster){ // Shift origin to that of dataset float X_coordinate_shifted_origin = x_locs[q] - XMinimum; float Y_coordinate_shifted_origin = y_locs[q] - YMinimum; // Get row and column of point int col_point = int(X_coordinate_shifted_origin/DataResolution); int row_point = (NRows - 1) - int(round(Y_coordinate_shifted_origin/DataResolution)); int tmpNode = snap_to_hilltop(row_point, col_point, search_radius, Hilltops); SnappedNodes.push_back(tmpNode); Valid_node_IDs.push_back(q); } } } #endif
[ "f.clubb@ed.ac.uk" ]
f.clubb@ed.ac.uk
7b50a97d025cb090808b09da91f7dc77c579013e
6bda09c40dfee96f6d11c09ca7f37587858337d9
/app/src/main/cpp/dalvik/dalvik_method_replace.cpp
67d6242a654788a682be224d00747687b7c97d34
[]
no_license
chenzhentao/AndFixDemo
4b3df6aed4cd037500fff798ec57fa1dded165da
c36be0b11722e592e46fe48bd507e53e31939b01
refs/heads/master
2020-06-03T13:52:48.812780
2019-06-12T15:08:12
2019-06-12T15:08:12
191,593,265
0
0
null
null
null
null
UTF-8
C++
false
false
3,844
cpp
/* * * Copyright (c) 2015, alipay.com * * 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. */ /** * dalvik_method_replace.cpp * * @author : sanping.li@alipay.com * */ #include <time.h> #include <stdlib.h> #include <stddef.h> #include <assert.h> #include <stdbool.h> #include <fcntl.h> #include <dlfcn.h> #include <sys/stat.h> #include <dirent.h> #include <unistd.h> #include <ctype.h> #include <errno.h> #include <utime.h> #include <sys/types.h> #include <sys/wait.h> #include "dalvik.h" #include "../common.h" static void* dvm_dlsym(void *hand, const char *name) { void* ret = dlsym(hand, name); char msg[1024] = { 0 }; snprintf(msg, sizeof(msg) - 1, "0x%x", ret); LOGD("%s = %s\n", name, msg); return ret; } extern jboolean __attribute__ ((visibility ("hidden"))) dalvik_setup( JNIEnv* env, int apilevel) { void* dvm_hand = dlopen("libdvm.so", RTLD_NOW); if (dvm_hand) { // dvmDecodeIndirectRef_fnPtr = (dvmDecodeIndirectRef_func)dvm_dlsym(dvm_hand, // apilevel > 10 ? // "_Z20dvmDecodeIndirectRefP6ThreadP8_jobject" : // "dvmDecodeIndirectRef"); // if (!dvmDecodeIndirectRef_fnPtr) { // return JNI_FALSE; // } // dvmThreadSelf_fnPtr = (dvmThreadSelf_func)dvm_dlsym(dvm_hand, // apilevel > 10 ? "_Z13dvmThreadSelfv" : "dvmThreadSelf"); dvmDecodeIndirectRef_fnPtr = (dvmDecodeIndirectRef_func)dvm_dlsym(dvm_hand, apilevel > 10 ? "_Z20dvmDecodeIndirectRefP6ThreadP8_jobject" : "dvmDecodeIndirectRef"); if (!dvmDecodeIndirectRef_fnPtr) { return JNI_FALSE; } dvmThreadSelf_fnPtr = (dvmThreadSelf_func)dvm_dlsym(dvm_hand, apilevel > 10 ? "_Z13dvmThreadSelfv" : "dvmThreadSelf"); if (!dvmThreadSelf_fnPtr) { return JNI_FALSE; } jclass clazz = env->FindClass("java/lang/reflect/Method"); jClassMethod = env->GetMethodID(clazz, "getDeclaringClass", "()Ljava/lang/Class;"); return JNI_TRUE; } else { return JNI_FALSE; } } extern void __attribute__ ((visibility ("hidden"))) dalvik_replaceMethod( JNIEnv* env, jobject src, jobject dest) { jobject clazz = env->CallObjectMethod(dest, jClassMethod); ClassObject* clz = (ClassObject*) dvmDecodeIndirectRef_fnPtr( dvmThreadSelf_fnPtr(), clazz); clz->status = CLASS_INITIALIZED; Method* meth = (Method*) env->FromReflectedMethod(src); Method* target = (Method*) env->FromReflectedMethod(dest); LOGD("dalvikMethod: %s", meth->name); // meth->clazz = target->clazz; meth->accessFlags |= ACC_PUBLIC; meth->methodIndex = target->methodIndex; meth->jniArgInfo = target->jniArgInfo; meth->registersSize = target->registersSize; meth->outsSize = target->outsSize; meth->insSize = target->insSize; meth->prototype = target->prototype; meth->insns = target->insns; meth->nativeFunc = target->nativeFunc; } extern void dalvik_setFieldFlag(JNIEnv* env, jobject field) { Field* dalvikField = (Field*) env->FromReflectedField(field); dalvikField->accessFlags = dalvikField->accessFlags & (~ACC_PRIVATE) | ACC_PUBLIC; LOGD("dalvik_setFieldFlag: %d ", dalvikField->accessFlags); }
[ "thomas.chenzh@gmail.com" ]
thomas.chenzh@gmail.com
2306d35701f8b6ceec396110d6a9d829ffc038b7
6ced41da926682548df646099662e79d7a6022c5
/aws-cpp-sdk-inspector2/include/aws/inspector2/model/AggregationType.h
7df7b5ef21aedaecb51304ce84085745f64696a1
[ "Apache-2.0", "MIT", "JSON" ]
permissive
irods/aws-sdk-cpp
139104843de529f615defa4f6b8e20bc95a6be05
2c7fb1a048c96713a28b730e1f48096bd231e932
refs/heads/main
2023-07-25T12:12:04.363757
2022-08-26T15:33:31
2022-08-26T15:33:31
141,315,346
0
1
Apache-2.0
2022-08-26T17:45:09
2018-07-17T16:24:06
C++
UTF-8
C++
false
false
788
h
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/inspector2/Inspector2_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> namespace Aws { namespace Inspector2 { namespace Model { enum class AggregationType { NOT_SET, FINDING_TYPE, PACKAGE, TITLE, REPOSITORY, AMI, AWS_EC2_INSTANCE, AWS_ECR_CONTAINER, IMAGE_LAYER, ACCOUNT }; namespace AggregationTypeMapper { AWS_INSPECTOR2_API AggregationType GetAggregationTypeForName(const Aws::String& name); AWS_INSPECTOR2_API Aws::String GetNameForAggregationType(AggregationType value); } // namespace AggregationTypeMapper } // namespace Model } // namespace Inspector2 } // namespace Aws
[ "aws-sdk-cpp-automation@github.com" ]
aws-sdk-cpp-automation@github.com
e384db75a5286c4576fdca59980d1d5e2e7e242e
13fceab2387662dcbf1c2f2536b5345aa4752c56
/Optimization/mba/MBA.cpp
b155ba22f1ba8b3b7c637b526f87392692124531
[]
no_license
Playfloor/CS544
b015c66e19aafcabff6c1a2e61ba85582a81de89
b7f6ee0e1e494137faa5285f3239d385453b6a7f
refs/heads/master
2021-12-23T02:50:15.199743
2017-10-27T05:33:35
2017-10-27T05:33:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,147
cpp
#define DEBUG_TYPE "cs544mba" #include "llvm/Support/Debug.h" #include "llvm/ADT/Statistic.h" STATISTIC(MBACount, "The # of modified instructions"); #include "llvm/Pass.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/Module.h" #include "llvm/IR/Function.h" #include "llvm/Support/raw_ostream.h" #include "llvm/IR/InstrTypes.h" #include "llvm/Transforms/Utils/BasicBlockUtils.h" /***************************************** * Pass implementation *****************************************/ using namespace llvm; // anonymous namespace -> avoid exporting unneeded symbols namespace { // A pass that perform a simple instruction substitution // see http://llvm.org/docs/WritingAnLLVMPass.html#the-basicblockpass-class class MBA : public BasicBlockPass { public: // The address of this static is used to uniquely identify this pass in the // pass registry. The PassManager relies on this address to find instance of // analyses passes and build dependencies on demand. // The value does not matter. static char ID; MBA() : BasicBlockPass(ID) { } // Called once for each module, before the calls on the basic blocks. bool doInitialization(Module &M) override { // do nothing return false; } // Called for each basic block of the module // Rely on the equality: a + b == (a ^ b) + 2 * (a & b) bool runOnBasicBlock(BasicBlock &BB) override { bool modified = false; // Can't use a for-range loop because we want to delete the instruction from // the list we're iterating when replacing it. for (Instruction &Inst : BB) { // not a regular C++ dynamic_cast! // see http://llvm.org/docs/ProgrammersManual.html#the-isa-cast-and-dyn-cast-templates auto *BinOp = dyn_cast<BinaryOperator>(&Inst); if (!BinOp) // The instruction is not a binary operator, we don't handle it. continue; unsigned Opcode = BinOp->getOpcode(); if (Opcode != Instruction::Add || !BinOp->getType()->isIntegerTy()) // Only handle integer add. // Note instead of doing a dyn_cast to a BinaryOperator above, we could // have done directly a dyn_cast to AddOperator, but this way seems more // effective to later add other operators. continue; // The IRBuilder helps you inserting instructions in a clean and fast way // see http://llvm.org/docs/ProgrammersManual.html#creating-and-inserting-new-instructions IRBuilder<> Builder(BinOp); Value *NewValue = Builder.CreateAdd(Builder.CreateXor(BinOp->getOperand(0), BinOp->getOperand(1)), Builder.CreateMul(ConstantInt::get(BinOp->getType(), 2), Builder.CreateAnd(BinOp->getOperand(0), BinOp->getOperand(1))) ); // ReplaceInstWithValue basically does this (`IIT' is passed by reference): // IIT->replaceAllUsesWith(NewValue); // IIT = BB.getInstList.erase(IIT); // // `erase' returns a valid iterator of the instruction before the // one that has been erased. This keeps iterators valid. // // see also // http://llvm.org/docs/ProgrammersManual.html#replacing-an-instruction-with-another-value BasicBlock::iterator it(Inst); ReplaceInstWithValue(BB.getInstList(), it, NewValue); modified = true; // update statistics! // They are printed out with -stats on the opt command line ++MBACount; } return modified; } }; } // pass registration is done through the constructor of static objects... /* opt pass registration */ char MBA::ID = 0; static RegisterPass<MBA> X("cs544mba", // the option name -> -cs544mba "Mixed Boolean Arithmetic Substitution (CS544)", // option description true, // true as we don't modify the CFG false // true if we're writing an analysis );
[ "baris.aktemur@ozyegin.edu.tr" ]
baris.aktemur@ozyegin.edu.tr
d35ecd3221d58d111d0ac573388f9a6b1fb65acb
06f822b1f2061f7ce03a9659a7017dfcebd3e209
/ATcoder/Contest/Educaional_DP_Contest_/I_Coins.cpp
f70919a70f64abd6165b724c9c73a89d63c0f72e
[]
no_license
SuuTTT/acm
f5ba1e6365fb0191490cba3dbac35031ec4e23b0
61fe500a89b2d41a17a010a1f65169ef21206fb5
refs/heads/master
2020-12-27T17:32:38.844016
2020-05-13T04:27:53
2020-05-13T04:27:53
237,983,067
0
0
null
null
null
null
UTF-8
C++
false
false
696
cpp
#include <bits/stdc++.h> using namespace std; #define rep(i,j,k) for(int i = (int)j;i <= (int)k;i ++) #define debug(x) cerr<<#x<<":"<<x<<endl const int maxn=(int)1e6+5; double p[maxn],dp[3004][3004],ans; int main(){ ios::sync_with_stdio(false);cin.tie(0);cout.tie(0); int n; cin>>n; rep(i,1,n)cin>>p[i]; dp[0][0]=1; rep(i,1,n)rep(j,0,i){ dp[i][j]=dp[i-1][j]*(1-p[i])+(j>0?dp[i-1][j-1]*p[i]:0); //debug(i),debug(dp[i][j]); } rep(j,0,n){ if(j>n-j)ans+=dp[n][j]; } //cout<<ans<<endl; printf("%.20lf",ans); } /* 3 0.30 0.60 0.80 head>tail 的概率 dp[i][#head] dp[i][j]=dp[i-1][j] dp[i-1][j-1] O(1)计算 最后求和 */
[ "1015011749@qq.com" ]
1015011749@qq.com
430b1fafb0e031d0ab34b7c66eb201d19753a66e
9474152ba242f656bd472808d00d420ee3d9048f
/concatenation_distance_matrix.cpp
5e8482dc23843e3df3c623523cbea35edfe1ef35
[]
no_license
mohammadroghani/bio
93fb9e9be74424ade078e3c03e2e604343105a9f
6f6966e7dd97f7d6410c6c89029c0775aef84fc4
refs/heads/master
2021-05-11T00:48:42.909765
2018-01-27T20:45:16
2018-01-27T20:45:16
118,311,508
0
0
null
null
null
null
UTF-8
C++
false
false
2,011
cpp
#include<iostream> #include<fstream> #include<sstream> #include<vector> #include<map> using namespace std; int dp[20000][20000]; int mat[7][5][5]; const int inf=1e9; string con[5]; map<pair<string,string>, pair<int,int> > m; /** finding edit distance of s and t match = 0 mismatch = 1 gap = 1 return minimum edit distance of s and t **/ int align(string s, string t){ int match=0,mismatch=1,gap=1,ret=inf; for(int i=0;i<=s.size();i++)for(int j=0;j<=t.size();j++)dp[i][j]=inf; for(int i=0;i<=s.size();i++)dp[i][0]=i; for(int j=1;j<=t.size();j++)dp[0][j]=j; for(int i=1;i<=s.size();i++){ for(int j=1;j<=t.size();j++){ dp[i][j]=min(dp[i-1][j],dp[i][j-1])+gap; if(s[i-1]==t[j-1])dp[i][j]=min(dp[i][j],dp[i-1][j-1]+match); else dp[i][j]=min(dp[i][j],dp[i-1][j-1]+mismatch); } } return dp[s.size()][t.size()]; } //names of ebola string names[]={ "Zaire", "TaiForest", "Sudan", "Reston", "Bundibugyo" }; //names of genes string Gene[]={ "NP", "VP35", "VP40", "GP", "VP30", "VP24", "L" }; int main(){ ifstream cin("output/gene_alignment"); string x,y; int lo,hi; while(cin>>x>>y>>lo>>hi){ m[make_pair(x,y)]=make_pair(lo,hi); } //concatenate genes for every ebolas for(int i=0;i<5;i++){ string name="resources/"+names[i]+"_genome.fasta"; ifstream cin(name); string t=""; string tmp; cin>>tmp; string last=tmp.substr(1,tmp.size()-1); getline(cin,tmp); while(getline(cin,tmp)){ tmp=tmp.substr(0,tmp.size()-1); t+=tmp; } string left=t; for(int k=0;k<7;k++){ pair<int,int> range_left=m[make_pair(names[i],Gene[k])]; string new_left=left.substr(range_left.first,range_left.second-range_left.first); con[i]+=new_left; } } ofstream cout("output/concatenation.csv"); for(int i=0;i<5;i++){ cout<<names[i]; if(i!=4)cout<<","; } cout<<endl; //finding edit distance of every pair of new strings for(int i=0;i<5;i++){ for(int j=0;j<5;j++){ cout<<align(con[i],con[j]); if(j!=4)cout<<","; } cout<<endl; } return 0; }
[ "mohammadroghani43@gmail.com" ]
mohammadroghani43@gmail.com
bc810f99c5bfa87b2e41e8fe5bfc4e4f3128674b
ddb0a69a05394070d295840410274a7647164a3c
/src/owners.hpp
9b7d23ae8897ae6c97ada50557a41ff29d9af17e
[ "BSD-2-Clause", "BSD-2-Clause-Views" ]
permissive
waffle-iron/omega_h2
093757624965286b18ffd6815383e465a718078a
3f078ffe5ef1e11dea85c2a4fcaef79b735d2683
refs/heads/master
2020-12-30T23:08:38.285470
2016-08-24T12:51:23
2016-08-24T12:51:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,850
hpp
#ifndef OWNERS_HPP #define OWNERS_HPP #include "internal.hpp" namespace Omega_h { /* compute owners for copies of a new partitioning, based on a mapping (Dist) from new copies to old owners (their owners in the old partitioning). each of the old owners is made responsible for all its new copies and selecting an owner among them. thus, if both the old and new partitioning are "good", this should be a highly scalable way to update parallel connectivity the (own_ranks) argument is optional. It may be left uninitialized (Read<I32>(), !own_ranks.exists()), in which case the owner rank will be chosen with a preference for ranks that have less copies, and in the case two ranks have the same number of copies, the smallest rank will be chosen. if (own_ranks) is specified, they will dictate the ownership of the new copies and are expected to be consistent. */ Remotes update_ownership(Dist new_ents2old_owners, Read<I32> own_ranks); /* uses update_ownership() with a linear partitioning of global numbers as the old partitioning. if global numbers obey good linear arrangement properties, the old partition should be decent and so this is an effective fallback if only globals are available */ Remotes owners_from_globals( CommPtr comm, Read<GO> globals, Read<I32> own_ranks); template <typename T> Read<T> reduce_data_to_owners( Read<T> copy_data, Dist copies2owners, Int ncomps); void globals_from_owners(Mesh* new_mesh, Int ent_dim); #define INST_DECL(T) \ extern template Read<T> reduce_data_to_owners( \ Read<T> copy_data, Dist copies2owners, Int ncomps); INST_DECL(I8) INST_DECL(I32) INST_DECL(I64) INST_DECL(Real) #undef INST_DECL } // end namespace Omega_h #endif
[ "dan.a.ibanez@gmail.com" ]
dan.a.ibanez@gmail.com
6a7ffd24188e61e3b97f984803b9771823b35c8c
de731acd890706423eced969f3195a2b5f084ae1
/lib/childrens-price.cpp
1862e75f24549f21f2e2e9d0f988276ae8ed31a2
[]
no_license
guydunton/Refactoring-example-cpp
e3c7e054f813f05336b12101a6da9242fb62c6c3
46b90c46f039829378a41dd464572d419adbc4ae
refs/heads/master
2020-04-26T11:10:09.953891
2019-03-02T23:22:30
2019-03-02T23:22:30
173,507,686
1
0
null
null
null
null
UTF-8
C++
false
false
413
cpp
#include "childrens-price.hpp" #include "movie.hpp" int ChildrensPrice::getPriceCode() const { return Movie::CHILDREN; } std::unique_ptr<Price> ChildrensPrice::clonePrice() { return std::make_unique<ChildrensPrice>(*this); } double ChildrensPrice::getCharge(int daysRented) const { const double baseCharge = 1.5; if (daysRented > 3) return baseCharge + (daysRented - 3) * 1.5; return baseCharge; }
[ "guy.dunton@gmail.com" ]
guy.dunton@gmail.com
ad0f3883f54c1b3fb6dca942b487d272060b8525
2c19ace35b57b17411575984f1656ec0c237436c
/Map.cpp
b9e9d9c0398b449832b35aab1a920d240eb2f9c1
[]
no_license
rane1700/ex4
51ca9154b373f56762695437286cd2288318b452
2024de009dde405e49ee713be9ed1ef9bd87696d
refs/heads/master
2021-04-29T01:09:16.946390
2017-01-02T19:20:15
2017-01-02T19:20:15
77,784,885
0
0
null
null
null
null
UTF-8
C++
false
false
639
cpp
// // Created by shani on 11/28/16. // #include "Map.h" #include "Node.h" #include "PointHistory.h" /** * constractor */ Map::Map(){} /** * destructor */ Map::~Map(){} /** * prints map */ /** * prints map */ void Map::print(){} /** * gets the path from a start point to a goal point * @param speed - the speed of the cab (1 or 2) * @return false if there is no path to the goal point, else return true. */ bool Map::run(int speed){} /** * gets neighbors of certian points according to map */ bool Map::getNeighbors(){} /** * * @return current point */ Node* Map::getCurrent(){} std::vector<Node*> Map:: getPass(){}
[ "ranee1700@gmail.com" ]
ranee1700@gmail.com
7af8f9573736e2b6034ba6d33525f5398ca7740d
82437e831c8e89c092d4125cca71ace24d364f5e
/wasabi/devices/unicone/firmware/genesis/hardware.inc
6d6c597ec73aea6123bc3ad370334033f83d2c75
[]
no_license
qixiaobo/navi-misc
93ac98f3d07eed0a1e6e620fd5f53880c5aac2a4
1f9099d40cc638d681eebbc85c0b8455dab21607
refs/heads/master
2021-06-06T11:53:00.644309
2016-10-27T06:01:26
2016-10-27T06:01:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,391
inc
; ; Sega Genesis Net-controller Interface ; ; Wasabi Net-controllers Project ; Micah Dowty <micah@navi.cx> ; ; This device emulates two 3-button Sega Genesis ; controllers. It accepts low-speed USB requests ; with the desired state of each controller. ; ; The controller interface is described well at: ; http://www-2.cs.cmu.edu/~chuck/infopg/segasix.txt ; ; The prototype was mounted inside the Genesis console ; itself, with a USB type B plug added to the back. ; This gives us control over the reset button and ; frees us from the low-quality connectors used on ; the front. This same firmware should work fine ; with normal DB-9 cables connecting it to the controller ; ports. ; ; The PIC16C745 power and USB are connected as ; described in the data sheet. I/Os are allocated ; as follows. Note that all controller pins were ; connected via resistors so that externally ; attached controllers can override the USB interface. ; This is unnecessary if you're connecting this to the ; genesis externally. The multiplexed outputs on PORTA ; used 1k resistors, (for speed) others used 47k ; resistors (to avoid overpowering the controller's ; 10k pull-up resistors) ; ; RB4: Controller 1, pin 7 (select) ; RB5: Controller 2, pin 7 (select) ; RB6: Reserved (interrupt-on-change) ; RB7: Reserved (interrupt-on-change) ; ; RA0: Controller 1, pin 6 (A/B) ; RA1: Controller 1, pin 9 (Start/C) ; RA2: Controller 2, pin 6 (A/B) ; RA3: Controller 2, pin 9 (Start/C) ; ; RB0: Controller 1, pin 1 (up) ; RB1: Controller 1, pin 2 (down) ; RB2: Controller 1, pin 3 (left) ; RB3: Controller 1, pin 4 (right) ; ; RC0: Controller 2, pin 1 (up) ; RC1: Controller 2, pin 2 (down) ; RC2: Controller 2, pin 3 (left) ; RC6: Controller 2, pin 4 (right) ; ; RA5: Reset button output ; RC7: Power switch output #define PIN_C1_SELECT PORTB, 4 #define PIN_C2_SELECT PORTB, 5 #define PIN_C1_A_B PORTA, 0 #define PIN_C1_START_C PORTA, 1 #define PIN_C2_A_B PORTA, 2 #define PIN_C2_START_C PORTA, 3 #define PIN_C1_UP PORTB, 0 #define PIN_C1_DOWN PORTB, 1 #define PIN_C1_LEFT PORTB, 2 #define PIN_C1_RIGHT PORTB, 3 #define PIN_C2_UP PORTC, 0 #define PIN_C2_DOWN PORTC, 1 #define PIN_C2_LEFT PORTC, 2 #define PIN_C2_RIGHT PORTC, 6 #define PIN_RESET PORTA, 5 ; Pulls high when active, high-z when inactive #define TRIS_RESET TRISA, 5 #define PIN_POWER PORTC, 7 ; --- The End ---
[ "micah@scanlime.org" ]
micah@scanlime.org
c19ca24ed0298c053af0672731a051182c101e22
f441609b808e945299e0c425621cfa032f6eec77
/LIstaRange/q8.cpp
a84b0375eea1b0ea21abbdeff44c35b89bb2af9a
[]
no_license
gbrsouza/Lists
b0de7df1f16ca027960f1a784951b10563bd8a47
096bf896d9052629cc28d3ed88e8ebc683c4ce98
refs/heads/master
2021-06-13T14:16:23.646716
2017-04-03T17:40:13
2017-04-03T17:40:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
987
cpp
#include <iostream> #include <iterator> #include <utility> int * unique ( int *first , int *last ); int main () { int A [] = { 1 , 2 , 1 , 2 , 3 , 3 , 1 , 2 , 4 , 5 , 3 , 4 , 5 }; // aplicar unique sobre A auto last = unique( std::begin(A), std::end(A)); // O comando abaixo deveria imprimir A com o conteudo 1 , 2 , 3 , 4 , 5. for ( auto i(std::begin(A)); i != last ; ++i ) std::cout << * i << " " ; std::cout << std::endl ; // Mostra o novo tamanho de A , que seria 5. std::cout << " >>> O comprimento ( logico ) de A apos unique ()e: " << std::distance ( std::begin ( A ) , last ) << " \n "; return 0; } int * unique ( int *first , int *last ) { auto iSlow(first+1); auto iFast(first+1); auto aux(first); bool unico; for(/*empty*/; iFast != last; ++iFast) { unico = true; for (auto i(aux); i != iSlow and unico; ++i) { if(*i == *iFast) unico = false; } if (unico){ std::swap(*iSlow,*iFast); iSlow++; } } return iSlow; }
[ "gabriel_feg@hotmail.com" ]
gabriel_feg@hotmail.com
bc2076be3336f9b46da44dbf37c07e9a3e1db7e5
728688c8496619a15cdc7130e8f3236b2600238a
/실습3/RangeArray.cpp
547dd3872dab23119aec3f2299e6e31b8baae7bc
[]
no_license
jennifer06065/comsil_3_github
a0f9f186b4fb0c5da117c9f8112a070aa17795a4
caf333ea482a2b72e84108e09f71ebc02bd692c3
refs/heads/master
2022-12-29T10:40:41.402334
2020-10-06T07:46:29
2020-10-06T07:46:29
301,641,672
0
0
null
null
null
null
UTF-8
C++
false
false
432
cpp
#include <iostream> using namespace std; #include "RangeArray.h" RangeArray::RangeArray(int a, int b) : Array(b-a+1) { low = a; high = b; } RangeArray::~RangeArray() {} int RangeArray::baseValue() { return low; } int RangeArray::endValue() { return high; } int& RangeArray::operator[](int i) { i=i-low; return Array::operator[](i); } int RangeArray::operator[](int i) const { i=i-low; return Array::operator[](i); }
[ "jennifer0606@naver.com" ]
jennifer0606@naver.com
97ffea240d74c5e6c47bd94492b51aa80e297dd6
09b3e549e9793824d6d4b7b6c29a30442747d533
/screens/Screen.h
58d1b95e08032eadbffddeffe9f6855cfcf04e5e
[ "MIT" ]
permissive
insano10/arduino-tetris
80c5a4f3b2e646a1410ec2f19cc838c7006165bf
3827c5ac7e02f4d499ba2bd76fa71c6d5a575851
refs/heads/master
2021-01-01T06:34:00.208946
2015-07-05T15:34:03
2015-07-05T15:34:03
38,570,230
0
0
null
null
null
null
UTF-8
C++
false
false
535
h
/* * Screen.h * * Created on: 1 May 2012 * Author: insano10 */ #ifndef SCREEN_H_ #define SCREEN_H_ #include "../controls/InputShield.h" #include "../data/HiScores.h" class Screen { public: Screen(InputShield* input_shield, HiScores* hiScore); virtual ~Screen(); virtual void activate(); virtual Screen* getNextScreen(); protected: void pressAToContinue(); INPUTSHIELD_STATE_T input_state_; InputShield* input_shield_; HiScores* hi_score_; }; #endif /* SCREEN_H_ */
[ "jdommett@gmail.com" ]
jdommett@gmail.com
360cfd406f686374fb1c6b3b21b6a354c1264a19
265620eb6a8de39b6eaf28c909b34e3bd25117ba
/OutExcelFileThread.h
d8246adaa69b3df7ec1e1e1173ca83f8a77e0fac
[]
no_license
isliulin/uesoft-AutoIPED
7e6f4d961ddc899b5f3c990f67beaca947ba4ff0
c11e3ea3a7d08faa462bc731e142844d4d4c3ed9
refs/heads/master
2022-01-13T15:32:45.190482
2013-09-30T08:33:08
2013-09-30T08:33:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,518
h
#if !defined(AFX_OUTEXCELFILETHREAD_H__70F153EE_80C8_426D_81CF_1D2C4A65AF78__INCLUDED_) #define AFX_OUTEXCELFILETHREAD_H__70F153EE_80C8_426D_81CF_1D2C4A65AF78__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // OutExcelFileThread.h : header file // #include "Autoipedview.h" ///////////////////////////////////////////////////////////////////////////// // COutExcelFileThread thread class COutExcelFileThread : public CWinThread { DECLARE_DYNCREATE(COutExcelFileThread) protected: // Attributes public: COutExcelFileThread(); // protected constructor used by dynamic creation virtual ~COutExcelFileThread(); // Operations public: bool SetPow(long double _x, long _y); void OutInsulExplainTbl(); void PutCurView(CAutoIPEDView* pCurView); // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(COutExcelFileThread) public: virtual BOOL InitInstance(); virtual int ExitInstance(); //}}AFX_VIRTUAL // Implementation protected: // Generated message map functions //{{AFX_MSG(COutExcelFileThread) // NOTE - the ClassWizard will add and remove member functions here. //}}AFX_MSG DECLARE_MESSAGE_MAP() private: CAutoIPEDView* m_pCurView; }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_OUTEXCELFILETHREAD_H__70F153EE_80C8_426D_81CF_1D2C4A65AF78__INCLUDED_)
[ "uesoft@163.com" ]
uesoft@163.com
1febd37175c925405cc8bd2f3f789a6497002ac8
fb7efe44f4d9f30d623f880d0eb620f3a81f0fbd
/net/cert/multi_log_ct_verifier_unittest.cc
fa4a894e653e1ba762aa93a847cbbc79da44c149
[ "BSD-3-Clause" ]
permissive
wzyy2/chromium-browser
2644b0daf58f8b3caee8a6c09a2b448b2dfe059c
eb905f00a0f7e141e8d6c89be8fb26192a88c4b7
refs/heads/master
2022-11-23T20:25:08.120045
2018-01-16T06:41:26
2018-01-16T06:41:26
117,618,467
3
2
BSD-3-Clause
2022-11-20T22:03:57
2018-01-16T02:09:10
null
UTF-8
C++
false
false
10,624
cc
// Copyright 2013 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/cert/multi_log_ct_verifier.h" #include <memory> #include <string> #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/metrics/histogram.h" #include "base/metrics/histogram_samples.h" #include "base/metrics/statistics_recorder.h" #include "base/values.h" #include "net/base/net_errors.h" #include "net/cert/ct_log_verifier.h" #include "net/cert/ct_serialization.h" #include "net/cert/pem_tokenizer.h" #include "net/cert/sct_status_flags.h" #include "net/cert/signed_certificate_timestamp.h" #include "net/cert/signed_certificate_timestamp_and_status.h" #include "net/cert/x509_certificate.h" #include "net/log/net_log_source_type.h" #include "net/log/net_log_with_source.h" #include "net/log/test_net_log.h" #include "net/log/test_net_log_entry.h" #include "net/test/cert_test_util.h" #include "net/test/ct_test_util.h" #include "net/test/test_data_directory.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using testing::_; using testing::Mock; namespace net { namespace { const char kLogDescription[] = "somelog"; const char kSCTCountHistogram[] = "Net.CertificateTransparency.SCTsPerConnection"; class MockSCTObserver : public CTVerifier::Observer { public: MOCK_METHOD2(OnSCTVerified, void(X509Certificate* cert, const ct::SignedCertificateTimestamp* sct)); }; class MultiLogCTVerifierTest : public ::testing::Test { public: void SetUp() override { scoped_refptr<const CTLogVerifier> log( CTLogVerifier::Create(ct::GetTestPublicKey(), kLogDescription, "https://ct.example.com", "dns.example.com")); ASSERT_TRUE(log); log_verifiers_.push_back(log); verifier_.reset(new MultiLogCTVerifier()); verifier_->AddLogs(log_verifiers_); std::string der_test_cert(ct::GetDerEncodedX509Cert()); chain_ = X509Certificate::CreateFromBytes( der_test_cert.data(), der_test_cert.length()); ASSERT_TRUE(chain_.get()); embedded_sct_chain_ = CreateCertificateChainFromFile(GetTestCertsDirectory(), "ct-test-embedded-cert.pem", X509Certificate::FORMAT_AUTO); ASSERT_TRUE(embedded_sct_chain_.get()); } bool CheckForEmbeddedSCTInNetLog(const TestNetLog& net_log) { TestNetLogEntry::List entries; net_log.GetEntries(&entries); if (entries.size() != 2) return false; const TestNetLogEntry& received = entries[0]; std::string embedded_scts; if (!received.GetStringValue("embedded_scts", &embedded_scts)) return false; if (embedded_scts.empty()) return false; const TestNetLogEntry& parsed = entries[1]; base::ListValue* scts; if (!parsed.GetListValue("scts", &scts) || scts->GetSize() != 1) { return false; } base::DictionaryValue* the_sct; if (!scts->GetDictionary(0, &the_sct)) return false; std::string origin; if (!the_sct->GetString("origin", &origin)) return false; if (origin != "Embedded in certificate") return false; std::string verification_status; if (!the_sct->GetString("verification_status", &verification_status)) return false; if (verification_status != "Verified") return false; return true; } // Returns true is |chain| is a certificate with embedded SCTs that can be // successfully extracted. bool VerifySinglePrecertificateChain(scoped_refptr<X509Certificate> chain) { SignedCertificateTimestampAndStatusList scts; verifier_->Verify(chain.get(), base::StringPiece(), base::StringPiece(), &scts, NetLogWithSource()); return !scts.empty(); } // Returns true if |chain| is a certificate with a single embedded SCT that // can be successfully extracted and matched to the test log indicated by // |kLogDescription|. bool CheckPrecertificateVerification(scoped_refptr<X509Certificate> chain) { SignedCertificateTimestampAndStatusList scts; TestNetLog test_net_log; NetLogWithSource net_log = NetLogWithSource::Make( &test_net_log, NetLogSourceType::SSL_CONNECT_JOB); verifier_->Verify(chain.get(), base::StringPiece(), base::StringPiece(), &scts, net_log); return ct::CheckForSingleVerifiedSCTInResult(scts, kLogDescription) && ct::CheckForSCTOrigin( scts, ct::SignedCertificateTimestamp::SCT_EMBEDDED) && CheckForEmbeddedSCTInNetLog(test_net_log); } // Histogram-related helper methods int GetValueFromHistogram(const std::string& histogram_name, int sample_index) { base::Histogram* histogram = static_cast<base::Histogram*>( base::StatisticsRecorder::FindHistogram(histogram_name)); if (histogram == NULL) return 0; std::unique_ptr<base::HistogramSamples> samples = histogram->SnapshotSamples(); return samples->GetCount(sample_index); } int NumConnectionsWithSingleSCT() { return GetValueFromHistogram(kSCTCountHistogram, 1); } int NumEmbeddedSCTsInHistogram() { return GetValueFromHistogram("Net.CertificateTransparency.SCTOrigin", ct::SignedCertificateTimestamp::SCT_EMBEDDED); } int NumValidSCTsInStatusHistogram() { return GetValueFromHistogram("Net.CertificateTransparency.SCTStatus", ct::SCT_STATUS_OK); } protected: std::unique_ptr<MultiLogCTVerifier> verifier_; scoped_refptr<X509Certificate> chain_; scoped_refptr<X509Certificate> embedded_sct_chain_; std::vector<scoped_refptr<const CTLogVerifier>> log_verifiers_; }; TEST_F(MultiLogCTVerifierTest, VerifiesEmbeddedSCT) { ASSERT_TRUE(CheckPrecertificateVerification(embedded_sct_chain_)); } TEST_F(MultiLogCTVerifierTest, VerifiesEmbeddedSCTWithPreCA) { scoped_refptr<X509Certificate> chain( CreateCertificateChainFromFile(GetTestCertsDirectory(), "ct-test-embedded-with-preca-chain.pem", X509Certificate::FORMAT_AUTO)); ASSERT_TRUE(chain.get()); ASSERT_TRUE(CheckPrecertificateVerification(chain)); } TEST_F(MultiLogCTVerifierTest, VerifiesEmbeddedSCTWithIntermediate) { scoped_refptr<X509Certificate> chain(CreateCertificateChainFromFile( GetTestCertsDirectory(), "ct-test-embedded-with-intermediate-chain.pem", X509Certificate::FORMAT_AUTO)); ASSERT_TRUE(chain.get()); ASSERT_TRUE(CheckPrecertificateVerification(chain)); } TEST_F(MultiLogCTVerifierTest, VerifiesEmbeddedSCTWithIntermediateAndPreCA) { scoped_refptr<X509Certificate> chain(CreateCertificateChainFromFile( GetTestCertsDirectory(), "ct-test-embedded-with-intermediate-preca-chain.pem", X509Certificate::FORMAT_AUTO)); ASSERT_TRUE(chain.get()); ASSERT_TRUE(CheckPrecertificateVerification(chain)); } TEST_F(MultiLogCTVerifierTest, VerifiesSCTOverX509Cert) { std::string sct_list = ct::GetSCTListForTesting(); SignedCertificateTimestampAndStatusList scts; verifier_->Verify(chain_.get(), base::StringPiece(), sct_list, &scts, NetLogWithSource()); ASSERT_TRUE(ct::CheckForSingleVerifiedSCTInResult(scts, kLogDescription)); ASSERT_TRUE(ct::CheckForSCTOrigin( scts, ct::SignedCertificateTimestamp::SCT_FROM_TLS_EXTENSION)); } TEST_F(MultiLogCTVerifierTest, IdentifiesSCTFromUnknownLog) { std::string sct_list = ct::GetSCTListWithInvalidSCT(); SignedCertificateTimestampAndStatusList scts; verifier_->Verify(chain_.get(), base::StringPiece(), sct_list, &scts, NetLogWithSource()); EXPECT_EQ(1U, scts.size()); EXPECT_EQ("", scts[0].sct->log_description); EXPECT_EQ(ct::SCT_STATUS_LOG_UNKNOWN, scts[0].status); } TEST_F(MultiLogCTVerifierTest, CountsValidSCTsInStatusHistogram) { int num_valid_scts = NumValidSCTsInStatusHistogram(); ASSERT_TRUE(VerifySinglePrecertificateChain(embedded_sct_chain_)); EXPECT_EQ(num_valid_scts + 1, NumValidSCTsInStatusHistogram()); } TEST_F(MultiLogCTVerifierTest, CountsInvalidSCTsInStatusHistogram) { std::string sct_list = ct::GetSCTListWithInvalidSCT(); SignedCertificateTimestampAndStatusList scts; int num_valid_scts = NumValidSCTsInStatusHistogram(); int num_invalid_scts = GetValueFromHistogram( "Net.CertificateTransparency.SCTStatus", ct::SCT_STATUS_LOG_UNKNOWN); verifier_->Verify(chain_.get(), base::StringPiece(), sct_list, &scts, NetLogWithSource()); ASSERT_EQ(num_valid_scts, NumValidSCTsInStatusHistogram()); ASSERT_EQ(num_invalid_scts + 1, GetValueFromHistogram("Net.CertificateTransparency.SCTStatus", ct::SCT_STATUS_LOG_UNKNOWN)); } TEST_F(MultiLogCTVerifierTest, CountsSingleEmbeddedSCTInConnectionsHistogram) { int old_sct_count = NumConnectionsWithSingleSCT(); ASSERT_TRUE(CheckPrecertificateVerification(embedded_sct_chain_)); EXPECT_EQ(old_sct_count + 1, NumConnectionsWithSingleSCT()); } TEST_F(MultiLogCTVerifierTest, CountsSingleEmbeddedSCTInOriginsHistogram) { int old_embedded_count = NumEmbeddedSCTsInHistogram(); ASSERT_TRUE(CheckPrecertificateVerification(embedded_sct_chain_)); EXPECT_EQ(old_embedded_count + 1, NumEmbeddedSCTsInHistogram()); } TEST_F(MultiLogCTVerifierTest, CountsZeroSCTsCorrectly) { int connections_without_scts = GetValueFromHistogram(kSCTCountHistogram, 0); EXPECT_FALSE(VerifySinglePrecertificateChain(chain_)); ASSERT_EQ(connections_without_scts + 1, GetValueFromHistogram(kSCTCountHistogram, 0)); } TEST_F(MultiLogCTVerifierTest, NotifiesOfValidSCT) { MockSCTObserver observer; verifier_->SetObserver(&observer); EXPECT_CALL(observer, OnSCTVerified(embedded_sct_chain_.get(), _)); ASSERT_TRUE(VerifySinglePrecertificateChain(embedded_sct_chain_)); } TEST_F(MultiLogCTVerifierTest, StopsNotifyingCorrectly) { MockSCTObserver observer; verifier_->SetObserver(&observer); EXPECT_CALL(observer, OnSCTVerified(embedded_sct_chain_.get(), _)).Times(1); ASSERT_TRUE(VerifySinglePrecertificateChain(embedded_sct_chain_)); Mock::VerifyAndClearExpectations(&observer); EXPECT_CALL(observer, OnSCTVerified(embedded_sct_chain_.get(), _)).Times(0); verifier_->SetObserver(nullptr); ASSERT_TRUE(VerifySinglePrecertificateChain(embedded_sct_chain_)); } } // namespace } // namespace net
[ "jacob-chen@iotwrt.com" ]
jacob-chen@iotwrt.com
6ccf9c05890a08f3fcf7110cf8d36c7cab9374ab
0cf1e9215a3c5b7ad113b6707eae4dddb23568c0
/String/KMP-next.cpp
b28789f67e13a57ef6f1a31b8f4ea262317a1388
[]
no_license
CrazyPigAndCat/DataStructure
5e1979078a775c014b568823896ae323a6446d1a
004b82087bd356238783158d8ce0b92f4f0bca0b
refs/heads/master
2023-01-10T10:55:53.897841
2020-11-06T13:42:57
2020-11-06T13:42:57
295,995,299
0
0
null
null
null
null
UTF-8
C++
false
false
928
cpp
// // Created by puppet on 2020/10/2. // #include <stdio.h> #define MAXLEN 255 typedef struct{ char ch[MAXLEN]; int length; }SString; int Index_KMP(SString S,SString T,int nextval[]){ int i=1,j=1; while (i<=S.length&&j<T.length){ if(j==0||S.ch[i]==T.ch[j]){ ++i; ++j; }else{ j=nextval[j]; } } if(j>T.length) return i-T.length; else return 0; } void get_next(SString T,int next[]){ int i=1,j=0; next[1]=0; while (i<T.length){ if{j==0||T.ch[i]==Y.ch[j]}{ ++i; ++j; next[i]=j; }else{ j=next[j]; } } } void get_nextval(int next[],int nextval[],SString T){ nextval[1]=0; for(int j=2;j<=T.length;j++){ if(T.ch[next[j]]==T.ch[j]) nextval[j]=nextval[next[j]]; else nextval[j]=next[j]; } }
[ "909395091@qq.com" ]
909395091@qq.com
f15955bcc109a30873408038a7e88c4c7b3a9e75
136247b5cb638464a05592618633aa5ffb88d007
/ui/widget/logwidget.cpp
20c507c04b4227a84c153c45d7f3a2760e038711
[]
no_license
dongdong-2009/spinnery-system
e198fb6fb314b7459bf4e6f0f66d8e55f675e927
14566665407c72cbe9fcef901d55eea48c106797
refs/heads/master
2021-05-28T16:21:47.725660
2014-10-29T12:07:39
2014-10-29T12:07:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
422
cpp
#include "logwidget.h" #include "ui_logwidget.h" #include <QDebug> LogWidget::LogWidget(QWidget *parent) : QWidget(parent), ui(new Ui::LogWidget) { ui->setupUi(this); } LogWidget::~LogWidget() { delete ui; } void LogWidget::on_listWidget_itemSelectionChanged() { int selectIndex=ui->listWidget->currentRow(); if(selectIndex!=-1){ emit this->selectIndexChange(selectIndex); } }
[ "kyyblabla@163.com" ]
kyyblabla@163.com
227decd6dc576104cecfa2ffe65fe438cfa0bfd8
e2029872bcf1feead431d3eb155ddc91036d9317
/Compiler/AST/ASTLiterals_CG.cpp
835fe84a332c46d8f12a051d76ed4bd1c6977ef2
[ "Artistic-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
FingerLeakers/emojicode
604d14a11ca7716b0488bc0d3d5ce3f573bfe2a3
1e5b1a6f287998639cd43152f37482125ab3d96a
refs/heads/master
2020-03-12T06:16:48.757828
2018-04-09T13:02:51
2018-04-09T13:02:51
130,481,785
2
0
null
2018-04-21T14:34:08
2018-04-21T14:34:08
null
UTF-8
C++
false
false
3,287
cpp
// // ASTLiterals_CG.cpp // Emojicode // // Created by Theo Weidmann on 03/09/2017. // Copyright © 2017 Theo Weidmann. All rights reserved. // #include "ASTLiterals.hpp" #include "ASTInitialization.hpp" #include "Compiler.hpp" #include "Generation/CallCodeGenerator.hpp" #include "Generation/FunctionCodeGenerator.hpp" #include "Types/Class.hpp" namespace EmojicodeCompiler { Value* ASTStringLiteral::generate(FunctionCodeGenerator *fg) const { return fg->generator()->stringPool().pool(value_); } Value* ASTBooleanTrue::generate(FunctionCodeGenerator *fg) const { return llvm::ConstantInt::getTrue(fg->generator()->context()); } Value* ASTBooleanFalse::generate(FunctionCodeGenerator *fg) const { return llvm::ConstantInt::getFalse(fg->generator()->context()); } Value* ASTNumberLiteral::generate(FunctionCodeGenerator *fg) const { switch (type_) { case NumberType::Byte: return fg->int8(integerValue_); case NumberType::Integer: return fg->int64(integerValue_); case NumberType::Double: return llvm::ConstantFP::get(llvm::Type::getDoubleTy(fg->generator()->context()), doubleValue_); } } Value* ASTSymbolLiteral::generate(FunctionCodeGenerator *fg) const { return llvm::ConstantInt::get(llvm::Type::getInt32Ty(fg->generator()->context()), value_); } Value* ASTThis::generate(FunctionCodeGenerator *fg) const { return fg->thisValue(); } Value* ASTNoValue::generate(FunctionCodeGenerator *fg) const { if (type_.storageType() == StorageType::Box) { return fg->getBoxOptionalWithoutValue(); } return fg->getSimpleOptionalWithoutValue(type_); } Value* ASTDictionaryLiteral::generate(FunctionCodeGenerator *fg) const { auto dict = ASTInitialization::initObject(fg, ASTArguments(position()), std::u32string(1, 0x1F438), type_); for (auto it = values_.begin(); it != values_.end(); it++) { auto args = ASTArguments(position()); args.addArguments(*it); args.addArguments(*(++it)); CallCodeGenerator(fg, CallType::StaticDispatch).generate(dict, type_, args, std::u32string(1, 0x1F437)); } return dict; } Value* ASTListLiteral::generate(FunctionCodeGenerator *fg) const { auto list = ASTInitialization::initObject(fg, ASTArguments(position()), std::u32string(1, 0x1F438), type_); for (auto value : values_) { auto args = ASTArguments(position()); args.addArguments(value); CallCodeGenerator(fg, CallType::StaticDispatch).generate(list, type_, args, std::u32string(1, 0x1F43B)); } return list; } Value* ASTConcatenateLiteral::generate(FunctionCodeGenerator *fg) const { auto strbuilder = ASTInitialization::initObject(fg, ASTArguments(position()), std::u32string(1, 0x1F195), type_); for (auto &stringNode : values_) { auto args = ASTArguments(position()); args.addArguments(stringNode); CallCodeGenerator(fg, CallType::StaticDispatch).generate(strbuilder, type_, args, std::u32string(1, 0x1F43B)); } return CallCodeGenerator(fg, CallType::StaticDispatch).generate(strbuilder, type_, ASTArguments(position()), std::u32string(1, 0x1F521)); } } // namespace EmojicodeCompiler
[ "hi@idmean.xyz" ]
hi@idmean.xyz
5f51bef74fab6a12e19d140069cd2b0c4ba626a4
88ae8695987ada722184307301e221e1ba3cc2fa
/sandbox/win/src/service_resolver_64.cc
b96816037a221347ed58def272979fd334ad024c
[ "BSD-3-Clause" ]
permissive
iridium-browser/iridium-browser
71d9c5ff76e014e6900b825f67389ab0ccd01329
5ee297f53dc7f8e70183031cff62f37b0f19d25f
refs/heads/master
2023-08-03T16:44:16.844552
2023-07-20T15:17:00
2023-07-23T16:09:30
220,016,632
341
40
BSD-3-Clause
2021-08-13T13:54:45
2019-11-06T14:32:31
null
UTF-8
C++
false
false
8,712
cc
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "sandbox/win/src/service_resolver.h" #include <ntstatus.h> #include <stddef.h> #include <memory> #include "sandbox/win/src/sandbox_nt_util.h" #include "sandbox/win/src/win_utils.h" namespace { #if defined(_M_X64) #pragma pack(push, 1) const ULONG kMmovR10EcxMovEax = 0xB8D18B4C; const USHORT kSyscall = 0x050F; const BYTE kRetNp = 0xC3; const ULONG64 kMov1 = 0x54894808244C8948; const ULONG64 kMov2 = 0x4C182444894C1024; const ULONG kMov3 = 0x20244C89; const USHORT kTestByte = 0x04F6; const BYTE kPtr = 0x25; const BYTE kRet = 0xC3; const USHORT kJne = 0x0375; // Service code for 64 bit systems. struct ServiceEntry { // This struct contains roughly the following code: // 00 mov r10,rcx // 03 mov eax,52h // 08 syscall // 0a ret // 0b xchg ax,ax // 0e xchg ax,ax ULONG mov_r10_rcx_mov_eax; // = 4C 8B D1 B8 ULONG service_id; USHORT syscall; // = 0F 05 BYTE ret; // = C3 BYTE pad; // = 66 USHORT xchg_ax_ax1; // = 66 90 USHORT xchg_ax_ax2; // = 66 90 }; // Service code for 64 bit Windows 8 and Windows 10 1507 (build 10240). struct ServiceEntryW8 { // This struct contains the following code: // 00 48894c2408 mov [rsp+8], rcx // 05 4889542410 mov [rsp+10], rdx // 0a 4c89442418 mov [rsp+18], r8 // 0f 4c894c2420 mov [rsp+20], r9 // 14 4c8bd1 mov r10,rcx // 17 b825000000 mov eax,25h // 1c 0f05 syscall // 1e c3 ret // 1f 90 nop ULONG64 mov_1; // = 48 89 4C 24 08 48 89 54 ULONG64 mov_2; // = 24 10 4C 89 44 24 18 4C ULONG mov_3; // = 89 4C 24 20 ULONG mov_r10_rcx_mov_eax; // = 4C 8B D1 B8 ULONG service_id; USHORT syscall; // = 0F 05 BYTE ret; // = C3 BYTE nop; // = 90 }; // Service code for 64 bit systems with int 2e fallback. Windows 10 1511+ struct ServiceEntryWithInt2E { // This struct contains roughly the following code: // 00 4c8bd1 mov r10,rcx // 03 b855000000 mov eax,52h // 08 f604250803fe7f01 test byte ptr SharedUserData!308, 1 // 10 7503 jne [over syscall] // 12 0f05 syscall // 14 c3 ret // 15 cd2e int 2e // 17 c3 ret ULONG mov_r10_rcx_mov_eax; // = 4C 8B D1 B8 ULONG service_id; USHORT test_byte; // = F6 04 BYTE ptr; // = 25 ULONG user_shared_data_ptr; BYTE one; // = 01 USHORT jne_over_syscall; // = 75 03 USHORT syscall; // = 0F 05 BYTE ret; // = C3 USHORT int2e; // = CD 2E BYTE ret2; // = C3 }; // We don't have an internal thunk for x64. struct ServiceFullThunk { union { ServiceEntry original; ServiceEntryW8 original_w8; ServiceEntryWithInt2E original_int2e_fallback; }; }; #pragma pack(pop) bool IsService(const void* source) { const ServiceEntry* service = reinterpret_cast<const ServiceEntry*>(source); return (kMmovR10EcxMovEax == service->mov_r10_rcx_mov_eax && kSyscall == service->syscall && kRetNp == service->ret); } bool IsServiceW8(const void* source) { const ServiceEntryW8* service = reinterpret_cast<const ServiceEntryW8*>(source); return (kMmovR10EcxMovEax == service->mov_r10_rcx_mov_eax && kMov1 == service->mov_1 && kMov2 == service->mov_2 && kMov3 == service->mov_3); } bool IsServiceWithInt2E(const void* source) { const ServiceEntryWithInt2E* service = reinterpret_cast<const ServiceEntryWithInt2E*>(source); return (kMmovR10EcxMovEax == service->mov_r10_rcx_mov_eax && kTestByte == service->test_byte && kPtr == service->ptr && kJne == service->jne_over_syscall && kSyscall == service->syscall && kRet == service->ret && kRet == service->ret2); } bool IsAnyService(const void* source) { return IsService(source) || IsServiceW8(source) || IsServiceWithInt2E(source); } #elif defined(_M_ARM64) #pragma pack(push, 4) const ULONG kSvc = 0xD4000001; const ULONG kRetNp = 0xD65F03C0; const ULONG kServiceIdMask = 0x001FFFE0; struct ServiceEntry { ULONG svc; ULONG ret; ULONG64 unused; }; struct ServiceFullThunk { ServiceEntry original; }; #pragma pack(pop) bool IsService(const void* source) { const ServiceEntry* service = reinterpret_cast<const ServiceEntry*>(source); return (kSvc == (service->svc & ~kServiceIdMask) && kRetNp == service->ret && 0 == service->unused); } bool IsAnyService(const void* source) { return IsService(source); } #else #error "Unsupported Windows 64-bit Arch" #endif } // namespace namespace sandbox { NTSTATUS ServiceResolverThunk::Setup(const void* target_module, const void* interceptor_module, const char* target_name, const char* interceptor_name, const void* interceptor_entry_point, void* thunk_storage, size_t storage_bytes, size_t* storage_used) { NTSTATUS ret = Init(target_module, interceptor_module, target_name, interceptor_name, interceptor_entry_point, thunk_storage, storage_bytes); if (!NT_SUCCESS(ret)) return ret; size_t thunk_bytes = GetThunkSize(); std::unique_ptr<char[]> thunk_buffer(new char[thunk_bytes]); ServiceFullThunk* thunk = reinterpret_cast<ServiceFullThunk*>(thunk_buffer.get()); if (!IsFunctionAService(&thunk->original)) return STATUS_OBJECT_NAME_COLLISION; ret = PerformPatch(thunk, thunk_storage); if (storage_used) *storage_used = thunk_bytes; return ret; } size_t ServiceResolverThunk::GetThunkSize() const { return sizeof(ServiceFullThunk); } NTSTATUS ServiceResolverThunk::CopyThunk(const void* target_module, const char* target_name, BYTE* thunk_storage, size_t storage_bytes, size_t* storage_used) { NTSTATUS ret = ResolveTarget(target_module, target_name, &target_); if (!NT_SUCCESS(ret)) return ret; size_t thunk_bytes = GetThunkSize(); if (storage_bytes < thunk_bytes) return STATUS_UNSUCCESSFUL; ServiceFullThunk* thunk = reinterpret_cast<ServiceFullThunk*>(thunk_storage); if (!IsFunctionAService(&thunk->original)) return STATUS_OBJECT_NAME_COLLISION; if (storage_used) *storage_used = thunk_bytes; return ret; } bool ServiceResolverThunk::IsFunctionAService(void* local_thunk) const { ServiceFullThunk function_code; SIZE_T read; if (!::ReadProcessMemory(process_, target_, &function_code, sizeof(function_code), &read)) return false; if (sizeof(function_code) != read) return false; if (!IsAnyService(&function_code)) return false; // Save the verified code. memcpy(local_thunk, &function_code, sizeof(function_code)); return true; } NTSTATUS ServiceResolverThunk::PerformPatch(void* local_thunk, void* remote_thunk) { // Patch the original code. ServiceEntry local_service; DCHECK_NT(GetInternalThunkSize() <= sizeof(local_service)); if (!SetInternalThunk(&local_service, sizeof(local_service), nullptr, interceptor_)) return STATUS_UNSUCCESSFUL; // Copy the local thunk buffer to the child. SIZE_T actual; if (!::WriteProcessMemory(process_, remote_thunk, local_thunk, sizeof(ServiceFullThunk), &actual)) return STATUS_UNSUCCESSFUL; if (sizeof(ServiceFullThunk) != actual) return STATUS_UNSUCCESSFUL; // And now change the function to intercept, on the child. if (ntdll_base_) { // Running a unit test. if (!::WriteProcessMemory(process_, target_, &local_service, sizeof(local_service), &actual)) return STATUS_UNSUCCESSFUL; } else { if (!WriteProtectedChildMemory(process_, target_, &local_service, sizeof(local_service))) return STATUS_UNSUCCESSFUL; } return STATUS_SUCCESS; } bool ServiceResolverThunk::VerifyJumpTargetForTesting(void*) const { return true; } } // namespace sandbox
[ "jengelh@inai.de" ]
jengelh@inai.de
954acad462398cc3b0af0a93b56e67d43d900323
4164e13053dab51d02affb94c46c529b37a08347
/tkir_game/tkir_game/PathFinder.h
a759565f8b6e74d5ca72a8e6344e279341aac98e
[]
no_license
tkir/goldenbyte2016
656629f500a4afc0892a7df456ba583cb4791ced
8f2ebeeff24e9b0d96b6cb4a897be1bc5fe0bb67
refs/heads/master
2021-01-10T02:39:04.951688
2016-01-25T19:15:25
2016-01-25T19:15:25
49,377,365
1
0
null
null
null
null
UTF-8
C++
false
false
1,528
h
#pragma once #include "include.h" struct object { Vector2f point[4]; Vector2f centerPoint; float furthestPoint; bool isWall; object(){} object create(Vector2f position, float tileSize); }; class MiniMap { public: object obj; object** miniMap; Vector2u mapSize, countMiniMapTyles; float miniMapTyleSize; std::vector<tmx::MapObject>* solid; void createObj(Vector2f _pos); bool collision(object& _miniMapObj); bool contains(object& _mapObj, sf::Vector2f point); public: MiniMap(){} void create(Vector2u _mapSize, unsigned int _miniMapObjSize = 16, std::vector<tmx::MapObject>* _solid = nullptr); object**& getMiniMap(){ return miniMap; } Vector2u getMiniMapSize(){ return countMiniMapTyles; } std::vector<tmx::MapObject>* getSolid(){ return solid; }; Vector2i getMiniPositionEntyty(Vector2f _entityPosition);//returns number cell in minimap }; class PathFinder { private: MiniMap* map; object*** miniMap; int** distanceMap; Vector2i mapSize, start, target; Vector2f m_start, m_target; tmx::MapObject* entityObj; std::vector<sf::Vector2i> resultPath; std::vector<sf::Vector2f>* smoothPath; bool isPathExist; std::vector<tmx::MapObject>* solid; void smoothing(); bool isObstacle(Vector2f A, Vector2f B, tmx::MapObject* _solid); bool isLinesCross(float x11, float y11, float x12, float y12, float x21, float y21, float x22, float y22); public: PathFinder(tmx::MapObject* entityObj, MiniMap* map, std::vector<sf::Vector2f>* smoothPath = nullptr); void aStar(Vector2f target); };
[ "kirill.titenko@gmail.com" ]
kirill.titenko@gmail.com