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
800f99883a5ce0014adacf6741468451cd7bfb9f
cec302f1b0a1f4c41c3a0b5f9b90d4ab902005a6
/case-studies/h2o/src/H2oEnclave/h2omain/compress.cpp
ddbee838f6cbe3b6250c231af4810246bbbbb0b0
[ "Apache-2.0" ]
permissive
kripa432/Panoply
cf4ea0f63cd3c1216f7a97bc1cf77a14afa019af
6287e7feacc49c4bc6cc0229e793600b49545251
refs/heads/master
2022-09-11T15:06:22.609854
2020-06-03T04:51:59
2020-06-03T04:51:59
266,686,111
0
0
null
2020-05-25T04:53:14
2020-05-25T04:53:14
null
UTF-8
C++
false
false
6,533
cpp
/* * Copyright (c) 2015 DeNA Co., Ltd., Kazuho Oku * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include "h2o.h" #include "h2o/configurator.h" #define DEFAULT_GZIP_QUALITY 1 #define DEFAULT_BROTLI_QUALITY 1 struct compress_configurator_t { h2o_configurator_t super; h2o_compress_args_t *vars, _vars_stack[H2O_CONFIGURATOR_NUM_LEVELS + 1]; }; static const h2o_compress_args_t all_off = {{-1}, {-1}}, all_on = {{DEFAULT_GZIP_QUALITY}, {DEFAULT_BROTLI_QUALITY}}; static int on_config_gzip(h2o_configurator_command_t *cmd, h2o_configurator_context_t *ctx, yoml_t *node) { printf("on_config_gzip \n"); struct compress_configurator_t *self = (void *)cmd->configurator; int mode; if ((mode = (int)h2o_configurator_get_one_of(cmd, node, "OFF,ON")) == -1) return -1; *self->vars = all_off; if (mode != 0) self->vars->gzip.quality = DEFAULT_GZIP_QUALITY; return 0; } static int obtain_quality(yoml_t *node, int min_quality, int max_quality, int default_quality, int *slot) { int tmp; if (node->type != YOML_TYPE_SCALAR) return -1; if (strcasecmp(node->data.scalar, "OFF") == 0) { *slot = -1; return 0; } if (strcasecmp(node->data.scalar, "ON") == 0) { *slot = default_quality; return 0; } if (sscanf(node->data.scalar, "%d", &tmp) == 1 && (min_quality <= tmp && tmp <= max_quality)) { *slot = tmp; return 0; } return -1; } static int on_config_compress(h2o_configurator_command_t *cmd, h2o_configurator_context_t *ctx, yoml_t *node) { printf("on_config_compress \n"); struct compress_configurator_t *self = (void *)cmd->configurator; size_t i; switch (node->type) { case YOML_TYPE_SCALAR: if (strcasecmp(node->data.scalar, "OFF") == 0) { *self->vars = all_off; } else if (strcasecmp(node->data.scalar, "ON") == 0) { *self->vars = all_on; } else { h2o_configurator_errprintf(cmd, node, "scalar argument must be either of: `OFF`, `ON`"); return -1; } break; case YOML_TYPE_SEQUENCE: *self->vars = all_off; for (i = 0; i != node->data.sequence.size; ++i) { yoml_t *element = node->data.sequence.elements[i]; if (element->type == YOML_TYPE_SCALAR && strcasecmp(element->data.scalar, "gzip") == 0) { self->vars->gzip.quality = DEFAULT_GZIP_QUALITY; } else if (element->type == YOML_TYPE_SCALAR && strcasecmp(element->data.scalar, "br") == 0) { self->vars->brotli.quality = DEFAULT_BROTLI_QUALITY; } else { h2o_configurator_errprintf(cmd, element, "element of the sequence must be either of: `gzip`, `br`"); return -1; } } break; case YOML_TYPE_MAPPING: *self->vars = all_off; for (i = 0; i != node->data.mapping.size; ++i) { yoml_t *key = node->data.mapping.elements[i].key; yoml_t *value = node->data.mapping.elements[i].value; if (key->type == YOML_TYPE_SCALAR && strcasecmp(key->data.scalar, "gzip") == 0) { if (obtain_quality(node, 1, 9, DEFAULT_GZIP_QUALITY, &self->vars->gzip.quality) != 0) { h2o_configurator_errprintf( cmd, value, "value of gzip attribute must be either of `OFF`, `ON` or an integer value between 1 and 9"); return -1; } } else if (key->type == YOML_TYPE_SCALAR && strcasecmp(key->data.scalar, "br") == 0) { if (obtain_quality(node, 0, 11, DEFAULT_BROTLI_QUALITY, &self->vars->brotli.quality) != 0) { h2o_configurator_errprintf( cmd, value, "value of br attribute must be either of `OFF`, `ON` or an integer between 0 and 11"); return -1; } } else { h2o_configurator_errprintf(cmd, key, "key must be either of: `gzip`, `br`"); return -1; } } break; default: h2o_fatal("unexpected node type"); break; } return 0; } static int on_config_enter(h2o_configurator_t *configurator, h2o_configurator_context_t *ctx, yoml_t *node) { printf("on_config_enter compress.cpp \n"); struct compress_configurator_t *self = (void *)configurator; ++self->vars; self->vars[0] = self->vars[-1]; return 0; } static int on_config_exit(h2o_configurator_t *configurator, h2o_configurator_context_t *ctx, yoml_t *node) { struct compress_configurator_t *self = (void *)configurator; if (ctx->pathconf != NULL && (self->vars->gzip.quality != -1 || self->vars->brotli.quality != -1)) h2o_compress_register(ctx->pathconf, self->vars); --self->vars; return 0; } void h2o_compress_register_configurator(h2o_globalconf_t *conf) { struct compress_configurator_t *c = (void *)h2o_configurator_create(conf, sizeof(*c)); c->super.enter = on_config_enter; c->super.exit = on_config_exit; h2o_configurator_define_command(&c->super, "compress", H2O_CONFIGURATOR_FLAG_ALL_LEVELS, on_config_compress); h2o_configurator_define_command(&c->super, "gzip", H2O_CONFIGURATOR_FLAG_ALL_LEVELS | H2O_CONFIGURATOR_FLAG_EXPECT_SCALAR, on_config_gzip); c->vars = c->_vars_stack; c->vars->gzip.quality = -1; c->vars->brotli.quality = -1; }
[ "shwetasshinde24@gmail.com" ]
shwetasshinde24@gmail.com
062f9bd1ab767c2d251f3b74469264d5910c0550
67f2da456f3d395de4de6e27fa471df5bf0766f1
/Arduino_Matrix_GUI/include/statHandler.h
fc18feee8903908c78f6c966e52660efe19a93f2
[]
no_license
SjoerdJoosen/Pixl-Impact
eb78e127e77cae581b98b85186fc62e3f3fc93bd
0294bd6a01005280999e83c44bb6980087545789
refs/heads/main
2023-02-16T23:44:08.753548
2021-01-14T11:00:32
2021-01-14T11:00:32
317,810,649
0
0
null
null
null
null
UTF-8
C++
false
false
297
h
#ifndef STATHANDLER_H #define STATHANDLER_H #include <Arduino.h> class StatHandler{ private: int statValue; int oldStatValue; public: StatHandler(){}; StatHandler(int baseStat); int getStat(); void setStat(int valueToSetTo); bool checkForChange(); }; #endif
[ "74236811+reddog34@users.noreply.github.com" ]
74236811+reddog34@users.noreply.github.com
df982ddf40d60bf5dfb998563a278ce5d4c72d32
7810b13f010d84cbe7f40586ecb3a5d60399b821
/google/protobuf/unittest_well_known_types.pb.h
bb5f1160221ee79d69c28cfda47a02a4932e3569
[]
no_license
chrak/MyTestServer
091d9be4d0d9653abc3750ab2b5213b716afc983
189146e3b4d8aeefc93eae6efb14459e25cd3994
refs/heads/master
2022-05-02T13:45:21.738700
2022-04-11T06:35:26
2022-04-11T06:35:26
144,518,444
5
4
null
null
null
null
UTF-8
C++
false
true
180,639
h
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/unittest_well_known_types.proto #ifndef PROTOBUF_google_2fprotobuf_2funittest_5fwell_5fknown_5ftypes_2eproto__INCLUDED #define PROTOBUF_google_2fprotobuf_2funittest_5fwell_5fknown_5ftypes_2eproto__INCLUDED #include <string> #include <google/protobuf/stubs/common.h> #if GOOGLE_PROTOBUF_VERSION < 3001000 #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 3001000 < 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> // IWYU pragma: export #include <google/protobuf/extension_set.h> // IWYU pragma: export #include <google/protobuf/map.h> #include <google/protobuf/map_field_inl.h> #include <google/protobuf/unknown_field_set.h> #include <google/protobuf/any.pb.h> #include <google/protobuf/api.pb.h> #include <google/protobuf/duration.pb.h> #include <google/protobuf/empty.pb.h> #include <google/protobuf/field_mask.pb.h> #include <google/protobuf/source_context.pb.h> #include <google/protobuf/struct.pb.h> #include <google/protobuf/timestamp.pb.h> #include <google/protobuf/type.pb.h> #include <google/protobuf/wrappers.pb.h> // @@protoc_insertion_point(includes) namespace google { namespace protobuf { class Any; class AnyDefaultTypeInternal; extern AnyDefaultTypeInternal _Any_default_instance_; class Api; class ApiDefaultTypeInternal; extern ApiDefaultTypeInternal _Api_default_instance_; class BoolValue; class BoolValueDefaultTypeInternal; extern BoolValueDefaultTypeInternal _BoolValue_default_instance_; class BytesValue; class BytesValueDefaultTypeInternal; extern BytesValueDefaultTypeInternal _BytesValue_default_instance_; class DoubleValue; class DoubleValueDefaultTypeInternal; extern DoubleValueDefaultTypeInternal _DoubleValue_default_instance_; class Duration; class DurationDefaultTypeInternal; extern DurationDefaultTypeInternal _Duration_default_instance_; class Empty; class EmptyDefaultTypeInternal; extern EmptyDefaultTypeInternal _Empty_default_instance_; class Enum; class EnumDefaultTypeInternal; extern EnumDefaultTypeInternal _Enum_default_instance_; class EnumValue; class EnumValueDefaultTypeInternal; extern EnumValueDefaultTypeInternal _EnumValue_default_instance_; class Field; class FieldDefaultTypeInternal; extern FieldDefaultTypeInternal _Field_default_instance_; class FieldMask; class FieldMaskDefaultTypeInternal; extern FieldMaskDefaultTypeInternal _FieldMask_default_instance_; class FloatValue; class FloatValueDefaultTypeInternal; extern FloatValueDefaultTypeInternal _FloatValue_default_instance_; class Int32Value; class Int32ValueDefaultTypeInternal; extern Int32ValueDefaultTypeInternal _Int32Value_default_instance_; class Int64Value; class Int64ValueDefaultTypeInternal; extern Int64ValueDefaultTypeInternal _Int64Value_default_instance_; class ListValue; class ListValueDefaultTypeInternal; extern ListValueDefaultTypeInternal _ListValue_default_instance_; class Method; class MethodDefaultTypeInternal; extern MethodDefaultTypeInternal _Method_default_instance_; class Mixin; class MixinDefaultTypeInternal; extern MixinDefaultTypeInternal _Mixin_default_instance_; class Option; class OptionDefaultTypeInternal; extern OptionDefaultTypeInternal _Option_default_instance_; class SourceContext; class SourceContextDefaultTypeInternal; extern SourceContextDefaultTypeInternal _SourceContext_default_instance_; class StringValue; class StringValueDefaultTypeInternal; extern StringValueDefaultTypeInternal _StringValue_default_instance_; class Struct; class StructDefaultTypeInternal; extern StructDefaultTypeInternal _Struct_default_instance_; class Timestamp; class TimestampDefaultTypeInternal; extern TimestampDefaultTypeInternal _Timestamp_default_instance_; class Type; class TypeDefaultTypeInternal; extern TypeDefaultTypeInternal _Type_default_instance_; class UInt32Value; class UInt32ValueDefaultTypeInternal; extern UInt32ValueDefaultTypeInternal _UInt32Value_default_instance_; class UInt64Value; class UInt64ValueDefaultTypeInternal; extern UInt64ValueDefaultTypeInternal _UInt64Value_default_instance_; class Value; class ValueDefaultTypeInternal; extern ValueDefaultTypeInternal _Value_default_instance_; } // namespace protobuf } // namespace google namespace protobuf_unittest { class MapWellKnownTypes; class MapWellKnownTypesDefaultTypeInternal; extern MapWellKnownTypesDefaultTypeInternal _MapWellKnownTypes_default_instance_; class OneofWellKnownTypes; class OneofWellKnownTypesDefaultTypeInternal; extern OneofWellKnownTypesDefaultTypeInternal _OneofWellKnownTypes_default_instance_; class RepeatedWellKnownTypes; class RepeatedWellKnownTypesDefaultTypeInternal; extern RepeatedWellKnownTypesDefaultTypeInternal _RepeatedWellKnownTypes_default_instance_; class TestWellKnownTypes; class TestWellKnownTypesDefaultTypeInternal; extern TestWellKnownTypesDefaultTypeInternal _TestWellKnownTypes_default_instance_; } // namespace protobuf_unittest namespace protobuf_unittest { // Internal implementation detail -- do not call these. void protobuf_AddDesc_google_2fprotobuf_2funittest_5fwell_5fknown_5ftypes_2eproto(); void protobuf_InitDefaults_google_2fprotobuf_2funittest_5fwell_5fknown_5ftypes_2eproto(); // =================================================================== class TestWellKnownTypes : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:protobuf_unittest.TestWellKnownTypes) */ { public: TestWellKnownTypes(); virtual ~TestWellKnownTypes(); TestWellKnownTypes(const TestWellKnownTypes& from); inline TestWellKnownTypes& operator=(const TestWellKnownTypes& from) { CopyFrom(from); return *this; } static const ::google::protobuf::Descriptor* descriptor(); static const TestWellKnownTypes& default_instance(); static inline const TestWellKnownTypes* internal_default_instance() { return reinterpret_cast<const TestWellKnownTypes*>( &_TestWellKnownTypes_default_instance_); } void Swap(TestWellKnownTypes* other); // implements Message ---------------------------------------------- inline TestWellKnownTypes* New() const PROTOBUF_FINAL { return New(NULL); } TestWellKnownTypes* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL; void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; void CopyFrom(const TestWellKnownTypes& from); void MergeFrom(const TestWellKnownTypes& from); void Clear() PROTOBUF_FINAL; bool IsInitialized() const PROTOBUF_FINAL; size_t ByteSizeLong() const PROTOBUF_FINAL; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const PROTOBUF_FINAL { return InternalSerializeWithCachedSizesToArray(false, output); } int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const PROTOBUF_FINAL; void InternalSwap(TestWellKnownTypes* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { return NULL; } inline void* MaybeArenaPtr() const { return NULL; } public: ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // .google.protobuf.Any any_field = 1; bool has_any_field() const; void clear_any_field(); static const int kAnyFieldFieldNumber = 1; const ::google::protobuf::Any& any_field() const; ::google::protobuf::Any* mutable_any_field(); ::google::protobuf::Any* release_any_field(); void set_allocated_any_field(::google::protobuf::Any* any_field); // .google.protobuf.Api api_field = 2; bool has_api_field() const; void clear_api_field(); static const int kApiFieldFieldNumber = 2; const ::google::protobuf::Api& api_field() const; ::google::protobuf::Api* mutable_api_field(); ::google::protobuf::Api* release_api_field(); void set_allocated_api_field(::google::protobuf::Api* api_field); // .google.protobuf.Duration duration_field = 3; bool has_duration_field() const; void clear_duration_field(); static const int kDurationFieldFieldNumber = 3; const ::google::protobuf::Duration& duration_field() const; ::google::protobuf::Duration* mutable_duration_field(); ::google::protobuf::Duration* release_duration_field(); void set_allocated_duration_field(::google::protobuf::Duration* duration_field); // .google.protobuf.Empty empty_field = 4; bool has_empty_field() const; void clear_empty_field(); static const int kEmptyFieldFieldNumber = 4; const ::google::protobuf::Empty& empty_field() const; ::google::protobuf::Empty* mutable_empty_field(); ::google::protobuf::Empty* release_empty_field(); void set_allocated_empty_field(::google::protobuf::Empty* empty_field); // .google.protobuf.FieldMask field_mask_field = 5; bool has_field_mask_field() const; void clear_field_mask_field(); static const int kFieldMaskFieldFieldNumber = 5; const ::google::protobuf::FieldMask& field_mask_field() const; ::google::protobuf::FieldMask* mutable_field_mask_field(); ::google::protobuf::FieldMask* release_field_mask_field(); void set_allocated_field_mask_field(::google::protobuf::FieldMask* field_mask_field); // .google.protobuf.SourceContext source_context_field = 6; bool has_source_context_field() const; void clear_source_context_field(); static const int kSourceContextFieldFieldNumber = 6; const ::google::protobuf::SourceContext& source_context_field() const; ::google::protobuf::SourceContext* mutable_source_context_field(); ::google::protobuf::SourceContext* release_source_context_field(); void set_allocated_source_context_field(::google::protobuf::SourceContext* source_context_field); // .google.protobuf.Struct struct_field = 7; bool has_struct_field() const; void clear_struct_field(); static const int kStructFieldFieldNumber = 7; const ::google::protobuf::Struct& struct_field() const; ::google::protobuf::Struct* mutable_struct_field(); ::google::protobuf::Struct* release_struct_field(); void set_allocated_struct_field(::google::protobuf::Struct* struct_field); // .google.protobuf.Timestamp timestamp_field = 8; bool has_timestamp_field() const; void clear_timestamp_field(); static const int kTimestampFieldFieldNumber = 8; const ::google::protobuf::Timestamp& timestamp_field() const; ::google::protobuf::Timestamp* mutable_timestamp_field(); ::google::protobuf::Timestamp* release_timestamp_field(); void set_allocated_timestamp_field(::google::protobuf::Timestamp* timestamp_field); // .google.protobuf.Type type_field = 9; bool has_type_field() const; void clear_type_field(); static const int kTypeFieldFieldNumber = 9; const ::google::protobuf::Type& type_field() const; ::google::protobuf::Type* mutable_type_field(); ::google::protobuf::Type* release_type_field(); void set_allocated_type_field(::google::protobuf::Type* type_field); // .google.protobuf.DoubleValue double_field = 10; bool has_double_field() const; void clear_double_field(); static const int kDoubleFieldFieldNumber = 10; const ::google::protobuf::DoubleValue& double_field() const; ::google::protobuf::DoubleValue* mutable_double_field(); ::google::protobuf::DoubleValue* release_double_field(); void set_allocated_double_field(::google::protobuf::DoubleValue* double_field); // .google.protobuf.FloatValue float_field = 11; bool has_float_field() const; void clear_float_field(); static const int kFloatFieldFieldNumber = 11; const ::google::protobuf::FloatValue& float_field() const; ::google::protobuf::FloatValue* mutable_float_field(); ::google::protobuf::FloatValue* release_float_field(); void set_allocated_float_field(::google::protobuf::FloatValue* float_field); // .google.protobuf.Int64Value int64_field = 12; bool has_int64_field() const; void clear_int64_field(); static const int kInt64FieldFieldNumber = 12; const ::google::protobuf::Int64Value& int64_field() const; ::google::protobuf::Int64Value* mutable_int64_field(); ::google::protobuf::Int64Value* release_int64_field(); void set_allocated_int64_field(::google::protobuf::Int64Value* int64_field); // .google.protobuf.UInt64Value uint64_field = 13; bool has_uint64_field() const; void clear_uint64_field(); static const int kUint64FieldFieldNumber = 13; const ::google::protobuf::UInt64Value& uint64_field() const; ::google::protobuf::UInt64Value* mutable_uint64_field(); ::google::protobuf::UInt64Value* release_uint64_field(); void set_allocated_uint64_field(::google::protobuf::UInt64Value* uint64_field); // .google.protobuf.Int32Value int32_field = 14; bool has_int32_field() const; void clear_int32_field(); static const int kInt32FieldFieldNumber = 14; const ::google::protobuf::Int32Value& int32_field() const; ::google::protobuf::Int32Value* mutable_int32_field(); ::google::protobuf::Int32Value* release_int32_field(); void set_allocated_int32_field(::google::protobuf::Int32Value* int32_field); // .google.protobuf.UInt32Value uint32_field = 15; bool has_uint32_field() const; void clear_uint32_field(); static const int kUint32FieldFieldNumber = 15; const ::google::protobuf::UInt32Value& uint32_field() const; ::google::protobuf::UInt32Value* mutable_uint32_field(); ::google::protobuf::UInt32Value* release_uint32_field(); void set_allocated_uint32_field(::google::protobuf::UInt32Value* uint32_field); // .google.protobuf.BoolValue bool_field = 16; bool has_bool_field() const; void clear_bool_field(); static const int kBoolFieldFieldNumber = 16; const ::google::protobuf::BoolValue& bool_field() const; ::google::protobuf::BoolValue* mutable_bool_field(); ::google::protobuf::BoolValue* release_bool_field(); void set_allocated_bool_field(::google::protobuf::BoolValue* bool_field); // .google.protobuf.StringValue string_field = 17; bool has_string_field() const; void clear_string_field(); static const int kStringFieldFieldNumber = 17; const ::google::protobuf::StringValue& string_field() const; ::google::protobuf::StringValue* mutable_string_field(); ::google::protobuf::StringValue* release_string_field(); void set_allocated_string_field(::google::protobuf::StringValue* string_field); // .google.protobuf.BytesValue bytes_field = 18; bool has_bytes_field() const; void clear_bytes_field(); static const int kBytesFieldFieldNumber = 18; const ::google::protobuf::BytesValue& bytes_field() const; ::google::protobuf::BytesValue* mutable_bytes_field(); ::google::protobuf::BytesValue* release_bytes_field(); void set_allocated_bytes_field(::google::protobuf::BytesValue* bytes_field); // .google.protobuf.Value value_field = 19; bool has_value_field() const; void clear_value_field(); static const int kValueFieldFieldNumber = 19; const ::google::protobuf::Value& value_field() const; ::google::protobuf::Value* mutable_value_field(); ::google::protobuf::Value* release_value_field(); void set_allocated_value_field(::google::protobuf::Value* value_field); // @@protoc_insertion_point(class_scope:protobuf_unittest.TestWellKnownTypes) private: ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; ::google::protobuf::Any* any_field_; ::google::protobuf::Api* api_field_; ::google::protobuf::Duration* duration_field_; ::google::protobuf::Empty* empty_field_; ::google::protobuf::FieldMask* field_mask_field_; ::google::protobuf::SourceContext* source_context_field_; ::google::protobuf::Struct* struct_field_; ::google::protobuf::Timestamp* timestamp_field_; ::google::protobuf::Type* type_field_; ::google::protobuf::DoubleValue* double_field_; ::google::protobuf::FloatValue* float_field_; ::google::protobuf::Int64Value* int64_field_; ::google::protobuf::UInt64Value* uint64_field_; ::google::protobuf::Int32Value* int32_field_; ::google::protobuf::UInt32Value* uint32_field_; ::google::protobuf::BoolValue* bool_field_; ::google::protobuf::StringValue* string_field_; ::google::protobuf::BytesValue* bytes_field_; ::google::protobuf::Value* value_field_; mutable int _cached_size_; friend void protobuf_InitDefaults_google_2fprotobuf_2funittest_5fwell_5fknown_5ftypes_2eproto_impl(); friend void protobuf_AddDesc_google_2fprotobuf_2funittest_5fwell_5fknown_5ftypes_2eproto_impl(); friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2funittest_5fwell_5fknown_5ftypes_2eproto(); friend void protobuf_ShutdownFile_google_2fprotobuf_2funittest_5fwell_5fknown_5ftypes_2eproto(); }; // ------------------------------------------------------------------- class RepeatedWellKnownTypes : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:protobuf_unittest.RepeatedWellKnownTypes) */ { public: RepeatedWellKnownTypes(); virtual ~RepeatedWellKnownTypes(); RepeatedWellKnownTypes(const RepeatedWellKnownTypes& from); inline RepeatedWellKnownTypes& operator=(const RepeatedWellKnownTypes& from) { CopyFrom(from); return *this; } static const ::google::protobuf::Descriptor* descriptor(); static const RepeatedWellKnownTypes& default_instance(); static inline const RepeatedWellKnownTypes* internal_default_instance() { return reinterpret_cast<const RepeatedWellKnownTypes*>( &_RepeatedWellKnownTypes_default_instance_); } void Swap(RepeatedWellKnownTypes* other); // implements Message ---------------------------------------------- inline RepeatedWellKnownTypes* New() const PROTOBUF_FINAL { return New(NULL); } RepeatedWellKnownTypes* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL; void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; void CopyFrom(const RepeatedWellKnownTypes& from); void MergeFrom(const RepeatedWellKnownTypes& from); void Clear() PROTOBUF_FINAL; bool IsInitialized() const PROTOBUF_FINAL; size_t ByteSizeLong() const PROTOBUF_FINAL; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const PROTOBUF_FINAL { return InternalSerializeWithCachedSizesToArray(false, output); } int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const PROTOBUF_FINAL; void InternalSwap(RepeatedWellKnownTypes* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { return NULL; } inline void* MaybeArenaPtr() const { return NULL; } public: ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // repeated .google.protobuf.Any any_field = 1; int any_field_size() const; void clear_any_field(); static const int kAnyFieldFieldNumber = 1; const ::google::protobuf::Any& any_field(int index) const; ::google::protobuf::Any* mutable_any_field(int index); ::google::protobuf::Any* add_any_field(); ::google::protobuf::RepeatedPtrField< ::google::protobuf::Any >* mutable_any_field(); const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Any >& any_field() const; // repeated .google.protobuf.Api api_field = 2; int api_field_size() const; void clear_api_field(); static const int kApiFieldFieldNumber = 2; const ::google::protobuf::Api& api_field(int index) const; ::google::protobuf::Api* mutable_api_field(int index); ::google::protobuf::Api* add_api_field(); ::google::protobuf::RepeatedPtrField< ::google::protobuf::Api >* mutable_api_field(); const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Api >& api_field() const; // repeated .google.protobuf.Duration duration_field = 3; int duration_field_size() const; void clear_duration_field(); static const int kDurationFieldFieldNumber = 3; const ::google::protobuf::Duration& duration_field(int index) const; ::google::protobuf::Duration* mutable_duration_field(int index); ::google::protobuf::Duration* add_duration_field(); ::google::protobuf::RepeatedPtrField< ::google::protobuf::Duration >* mutable_duration_field(); const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Duration >& duration_field() const; // repeated .google.protobuf.Empty empty_field = 4; int empty_field_size() const; void clear_empty_field(); static const int kEmptyFieldFieldNumber = 4; const ::google::protobuf::Empty& empty_field(int index) const; ::google::protobuf::Empty* mutable_empty_field(int index); ::google::protobuf::Empty* add_empty_field(); ::google::protobuf::RepeatedPtrField< ::google::protobuf::Empty >* mutable_empty_field(); const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Empty >& empty_field() const; // repeated .google.protobuf.FieldMask field_mask_field = 5; int field_mask_field_size() const; void clear_field_mask_field(); static const int kFieldMaskFieldFieldNumber = 5; const ::google::protobuf::FieldMask& field_mask_field(int index) const; ::google::protobuf::FieldMask* mutable_field_mask_field(int index); ::google::protobuf::FieldMask* add_field_mask_field(); ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldMask >* mutable_field_mask_field(); const ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldMask >& field_mask_field() const; // repeated .google.protobuf.SourceContext source_context_field = 6; int source_context_field_size() const; void clear_source_context_field(); static const int kSourceContextFieldFieldNumber = 6; const ::google::protobuf::SourceContext& source_context_field(int index) const; ::google::protobuf::SourceContext* mutable_source_context_field(int index); ::google::protobuf::SourceContext* add_source_context_field(); ::google::protobuf::RepeatedPtrField< ::google::protobuf::SourceContext >* mutable_source_context_field(); const ::google::protobuf::RepeatedPtrField< ::google::protobuf::SourceContext >& source_context_field() const; // repeated .google.protobuf.Struct struct_field = 7; int struct_field_size() const; void clear_struct_field(); static const int kStructFieldFieldNumber = 7; const ::google::protobuf::Struct& struct_field(int index) const; ::google::protobuf::Struct* mutable_struct_field(int index); ::google::protobuf::Struct* add_struct_field(); ::google::protobuf::RepeatedPtrField< ::google::protobuf::Struct >* mutable_struct_field(); const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Struct >& struct_field() const; // repeated .google.protobuf.Timestamp timestamp_field = 8; int timestamp_field_size() const; void clear_timestamp_field(); static const int kTimestampFieldFieldNumber = 8; const ::google::protobuf::Timestamp& timestamp_field(int index) const; ::google::protobuf::Timestamp* mutable_timestamp_field(int index); ::google::protobuf::Timestamp* add_timestamp_field(); ::google::protobuf::RepeatedPtrField< ::google::protobuf::Timestamp >* mutable_timestamp_field(); const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Timestamp >& timestamp_field() const; // repeated .google.protobuf.Type type_field = 9; int type_field_size() const; void clear_type_field(); static const int kTypeFieldFieldNumber = 9; const ::google::protobuf::Type& type_field(int index) const; ::google::protobuf::Type* mutable_type_field(int index); ::google::protobuf::Type* add_type_field(); ::google::protobuf::RepeatedPtrField< ::google::protobuf::Type >* mutable_type_field(); const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Type >& type_field() const; // repeated .google.protobuf.DoubleValue double_field = 10; int double_field_size() const; void clear_double_field(); static const int kDoubleFieldFieldNumber = 10; const ::google::protobuf::DoubleValue& double_field(int index) const; ::google::protobuf::DoubleValue* mutable_double_field(int index); ::google::protobuf::DoubleValue* add_double_field(); ::google::protobuf::RepeatedPtrField< ::google::protobuf::DoubleValue >* mutable_double_field(); const ::google::protobuf::RepeatedPtrField< ::google::protobuf::DoubleValue >& double_field() const; // repeated .google.protobuf.FloatValue float_field = 11; int float_field_size() const; void clear_float_field(); static const int kFloatFieldFieldNumber = 11; const ::google::protobuf::FloatValue& float_field(int index) const; ::google::protobuf::FloatValue* mutable_float_field(int index); ::google::protobuf::FloatValue* add_float_field(); ::google::protobuf::RepeatedPtrField< ::google::protobuf::FloatValue >* mutable_float_field(); const ::google::protobuf::RepeatedPtrField< ::google::protobuf::FloatValue >& float_field() const; // repeated .google.protobuf.Int64Value int64_field = 12; int int64_field_size() const; void clear_int64_field(); static const int kInt64FieldFieldNumber = 12; const ::google::protobuf::Int64Value& int64_field(int index) const; ::google::protobuf::Int64Value* mutable_int64_field(int index); ::google::protobuf::Int64Value* add_int64_field(); ::google::protobuf::RepeatedPtrField< ::google::protobuf::Int64Value >* mutable_int64_field(); const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Int64Value >& int64_field() const; // repeated .google.protobuf.UInt64Value uint64_field = 13; int uint64_field_size() const; void clear_uint64_field(); static const int kUint64FieldFieldNumber = 13; const ::google::protobuf::UInt64Value& uint64_field(int index) const; ::google::protobuf::UInt64Value* mutable_uint64_field(int index); ::google::protobuf::UInt64Value* add_uint64_field(); ::google::protobuf::RepeatedPtrField< ::google::protobuf::UInt64Value >* mutable_uint64_field(); const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UInt64Value >& uint64_field() const; // repeated .google.protobuf.Int32Value int32_field = 14; int int32_field_size() const; void clear_int32_field(); static const int kInt32FieldFieldNumber = 14; const ::google::protobuf::Int32Value& int32_field(int index) const; ::google::protobuf::Int32Value* mutable_int32_field(int index); ::google::protobuf::Int32Value* add_int32_field(); ::google::protobuf::RepeatedPtrField< ::google::protobuf::Int32Value >* mutable_int32_field(); const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Int32Value >& int32_field() const; // repeated .google.protobuf.UInt32Value uint32_field = 15; int uint32_field_size() const; void clear_uint32_field(); static const int kUint32FieldFieldNumber = 15; const ::google::protobuf::UInt32Value& uint32_field(int index) const; ::google::protobuf::UInt32Value* mutable_uint32_field(int index); ::google::protobuf::UInt32Value* add_uint32_field(); ::google::protobuf::RepeatedPtrField< ::google::protobuf::UInt32Value >* mutable_uint32_field(); const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UInt32Value >& uint32_field() const; // repeated .google.protobuf.BoolValue bool_field = 16; int bool_field_size() const; void clear_bool_field(); static const int kBoolFieldFieldNumber = 16; const ::google::protobuf::BoolValue& bool_field(int index) const; ::google::protobuf::BoolValue* mutable_bool_field(int index); ::google::protobuf::BoolValue* add_bool_field(); ::google::protobuf::RepeatedPtrField< ::google::protobuf::BoolValue >* mutable_bool_field(); const ::google::protobuf::RepeatedPtrField< ::google::protobuf::BoolValue >& bool_field() const; // repeated .google.protobuf.StringValue string_field = 17; int string_field_size() const; void clear_string_field(); static const int kStringFieldFieldNumber = 17; const ::google::protobuf::StringValue& string_field(int index) const; ::google::protobuf::StringValue* mutable_string_field(int index); ::google::protobuf::StringValue* add_string_field(); ::google::protobuf::RepeatedPtrField< ::google::protobuf::StringValue >* mutable_string_field(); const ::google::protobuf::RepeatedPtrField< ::google::protobuf::StringValue >& string_field() const; // repeated .google.protobuf.BytesValue bytes_field = 18; int bytes_field_size() const; void clear_bytes_field(); static const int kBytesFieldFieldNumber = 18; const ::google::protobuf::BytesValue& bytes_field(int index) const; ::google::protobuf::BytesValue* mutable_bytes_field(int index); ::google::protobuf::BytesValue* add_bytes_field(); ::google::protobuf::RepeatedPtrField< ::google::protobuf::BytesValue >* mutable_bytes_field(); const ::google::protobuf::RepeatedPtrField< ::google::protobuf::BytesValue >& bytes_field() const; // @@protoc_insertion_point(class_scope:protobuf_unittest.RepeatedWellKnownTypes) private: ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::Any > any_field_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::Api > api_field_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::Duration > duration_field_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::Empty > empty_field_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldMask > field_mask_field_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::SourceContext > source_context_field_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::Struct > struct_field_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::Timestamp > timestamp_field_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::Type > type_field_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::DoubleValue > double_field_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::FloatValue > float_field_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::Int64Value > int64_field_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::UInt64Value > uint64_field_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::Int32Value > int32_field_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::UInt32Value > uint32_field_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::BoolValue > bool_field_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::StringValue > string_field_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::BytesValue > bytes_field_; mutable int _cached_size_; friend void protobuf_InitDefaults_google_2fprotobuf_2funittest_5fwell_5fknown_5ftypes_2eproto_impl(); friend void protobuf_AddDesc_google_2fprotobuf_2funittest_5fwell_5fknown_5ftypes_2eproto_impl(); friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2funittest_5fwell_5fknown_5ftypes_2eproto(); friend void protobuf_ShutdownFile_google_2fprotobuf_2funittest_5fwell_5fknown_5ftypes_2eproto(); }; // ------------------------------------------------------------------- class OneofWellKnownTypes : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:protobuf_unittest.OneofWellKnownTypes) */ { public: OneofWellKnownTypes(); virtual ~OneofWellKnownTypes(); OneofWellKnownTypes(const OneofWellKnownTypes& from); inline OneofWellKnownTypes& operator=(const OneofWellKnownTypes& from) { CopyFrom(from); return *this; } static const ::google::protobuf::Descriptor* descriptor(); static const OneofWellKnownTypes& default_instance(); enum OneofFieldCase { kAnyField = 1, kApiField = 2, kDurationField = 3, kEmptyField = 4, kFieldMaskField = 5, kSourceContextField = 6, kStructField = 7, kTimestampField = 8, kTypeField = 9, kDoubleField = 10, kFloatField = 11, kInt64Field = 12, kUint64Field = 13, kInt32Field = 14, kUint32Field = 15, kBoolField = 16, kStringField = 17, kBytesField = 18, ONEOF_FIELD_NOT_SET = 0, }; static inline const OneofWellKnownTypes* internal_default_instance() { return reinterpret_cast<const OneofWellKnownTypes*>( &_OneofWellKnownTypes_default_instance_); } void Swap(OneofWellKnownTypes* other); // implements Message ---------------------------------------------- inline OneofWellKnownTypes* New() const PROTOBUF_FINAL { return New(NULL); } OneofWellKnownTypes* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL; void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; void CopyFrom(const OneofWellKnownTypes& from); void MergeFrom(const OneofWellKnownTypes& from); void Clear() PROTOBUF_FINAL; bool IsInitialized() const PROTOBUF_FINAL; size_t ByteSizeLong() const PROTOBUF_FINAL; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const PROTOBUF_FINAL { return InternalSerializeWithCachedSizesToArray(false, output); } int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const PROTOBUF_FINAL; void InternalSwap(OneofWellKnownTypes* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { return NULL; } inline void* MaybeArenaPtr() const { return NULL; } public: ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // .google.protobuf.Any any_field = 1; bool has_any_field() const; void clear_any_field(); static const int kAnyFieldFieldNumber = 1; const ::google::protobuf::Any& any_field() const; ::google::protobuf::Any* mutable_any_field(); ::google::protobuf::Any* release_any_field(); void set_allocated_any_field(::google::protobuf::Any* any_field); // .google.protobuf.Api api_field = 2; bool has_api_field() const; void clear_api_field(); static const int kApiFieldFieldNumber = 2; const ::google::protobuf::Api& api_field() const; ::google::protobuf::Api* mutable_api_field(); ::google::protobuf::Api* release_api_field(); void set_allocated_api_field(::google::protobuf::Api* api_field); // .google.protobuf.Duration duration_field = 3; bool has_duration_field() const; void clear_duration_field(); static const int kDurationFieldFieldNumber = 3; const ::google::protobuf::Duration& duration_field() const; ::google::protobuf::Duration* mutable_duration_field(); ::google::protobuf::Duration* release_duration_field(); void set_allocated_duration_field(::google::protobuf::Duration* duration_field); // .google.protobuf.Empty empty_field = 4; bool has_empty_field() const; void clear_empty_field(); static const int kEmptyFieldFieldNumber = 4; const ::google::protobuf::Empty& empty_field() const; ::google::protobuf::Empty* mutable_empty_field(); ::google::protobuf::Empty* release_empty_field(); void set_allocated_empty_field(::google::protobuf::Empty* empty_field); // .google.protobuf.FieldMask field_mask_field = 5; bool has_field_mask_field() const; void clear_field_mask_field(); static const int kFieldMaskFieldFieldNumber = 5; const ::google::protobuf::FieldMask& field_mask_field() const; ::google::protobuf::FieldMask* mutable_field_mask_field(); ::google::protobuf::FieldMask* release_field_mask_field(); void set_allocated_field_mask_field(::google::protobuf::FieldMask* field_mask_field); // .google.protobuf.SourceContext source_context_field = 6; bool has_source_context_field() const; void clear_source_context_field(); static const int kSourceContextFieldFieldNumber = 6; const ::google::protobuf::SourceContext& source_context_field() const; ::google::protobuf::SourceContext* mutable_source_context_field(); ::google::protobuf::SourceContext* release_source_context_field(); void set_allocated_source_context_field(::google::protobuf::SourceContext* source_context_field); // .google.protobuf.Struct struct_field = 7; bool has_struct_field() const; void clear_struct_field(); static const int kStructFieldFieldNumber = 7; const ::google::protobuf::Struct& struct_field() const; ::google::protobuf::Struct* mutable_struct_field(); ::google::protobuf::Struct* release_struct_field(); void set_allocated_struct_field(::google::protobuf::Struct* struct_field); // .google.protobuf.Timestamp timestamp_field = 8; bool has_timestamp_field() const; void clear_timestamp_field(); static const int kTimestampFieldFieldNumber = 8; const ::google::protobuf::Timestamp& timestamp_field() const; ::google::protobuf::Timestamp* mutable_timestamp_field(); ::google::protobuf::Timestamp* release_timestamp_field(); void set_allocated_timestamp_field(::google::protobuf::Timestamp* timestamp_field); // .google.protobuf.Type type_field = 9; bool has_type_field() const; void clear_type_field(); static const int kTypeFieldFieldNumber = 9; const ::google::protobuf::Type& type_field() const; ::google::protobuf::Type* mutable_type_field(); ::google::protobuf::Type* release_type_field(); void set_allocated_type_field(::google::protobuf::Type* type_field); // .google.protobuf.DoubleValue double_field = 10; bool has_double_field() const; void clear_double_field(); static const int kDoubleFieldFieldNumber = 10; const ::google::protobuf::DoubleValue& double_field() const; ::google::protobuf::DoubleValue* mutable_double_field(); ::google::protobuf::DoubleValue* release_double_field(); void set_allocated_double_field(::google::protobuf::DoubleValue* double_field); // .google.protobuf.FloatValue float_field = 11; bool has_float_field() const; void clear_float_field(); static const int kFloatFieldFieldNumber = 11; const ::google::protobuf::FloatValue& float_field() const; ::google::protobuf::FloatValue* mutable_float_field(); ::google::protobuf::FloatValue* release_float_field(); void set_allocated_float_field(::google::protobuf::FloatValue* float_field); // .google.protobuf.Int64Value int64_field = 12; bool has_int64_field() const; void clear_int64_field(); static const int kInt64FieldFieldNumber = 12; const ::google::protobuf::Int64Value& int64_field() const; ::google::protobuf::Int64Value* mutable_int64_field(); ::google::protobuf::Int64Value* release_int64_field(); void set_allocated_int64_field(::google::protobuf::Int64Value* int64_field); // .google.protobuf.UInt64Value uint64_field = 13; bool has_uint64_field() const; void clear_uint64_field(); static const int kUint64FieldFieldNumber = 13; const ::google::protobuf::UInt64Value& uint64_field() const; ::google::protobuf::UInt64Value* mutable_uint64_field(); ::google::protobuf::UInt64Value* release_uint64_field(); void set_allocated_uint64_field(::google::protobuf::UInt64Value* uint64_field); // .google.protobuf.Int32Value int32_field = 14; bool has_int32_field() const; void clear_int32_field(); static const int kInt32FieldFieldNumber = 14; const ::google::protobuf::Int32Value& int32_field() const; ::google::protobuf::Int32Value* mutable_int32_field(); ::google::protobuf::Int32Value* release_int32_field(); void set_allocated_int32_field(::google::protobuf::Int32Value* int32_field); // .google.protobuf.UInt32Value uint32_field = 15; bool has_uint32_field() const; void clear_uint32_field(); static const int kUint32FieldFieldNumber = 15; const ::google::protobuf::UInt32Value& uint32_field() const; ::google::protobuf::UInt32Value* mutable_uint32_field(); ::google::protobuf::UInt32Value* release_uint32_field(); void set_allocated_uint32_field(::google::protobuf::UInt32Value* uint32_field); // .google.protobuf.BoolValue bool_field = 16; bool has_bool_field() const; void clear_bool_field(); static const int kBoolFieldFieldNumber = 16; const ::google::protobuf::BoolValue& bool_field() const; ::google::protobuf::BoolValue* mutable_bool_field(); ::google::protobuf::BoolValue* release_bool_field(); void set_allocated_bool_field(::google::protobuf::BoolValue* bool_field); // .google.protobuf.StringValue string_field = 17; bool has_string_field() const; void clear_string_field(); static const int kStringFieldFieldNumber = 17; const ::google::protobuf::StringValue& string_field() const; ::google::protobuf::StringValue* mutable_string_field(); ::google::protobuf::StringValue* release_string_field(); void set_allocated_string_field(::google::protobuf::StringValue* string_field); // .google.protobuf.BytesValue bytes_field = 18; bool has_bytes_field() const; void clear_bytes_field(); static const int kBytesFieldFieldNumber = 18; const ::google::protobuf::BytesValue& bytes_field() const; ::google::protobuf::BytesValue* mutable_bytes_field(); ::google::protobuf::BytesValue* release_bytes_field(); void set_allocated_bytes_field(::google::protobuf::BytesValue* bytes_field); OneofFieldCase oneof_field_case() const; // @@protoc_insertion_point(class_scope:protobuf_unittest.OneofWellKnownTypes) private: void set_has_any_field(); void set_has_api_field(); void set_has_duration_field(); void set_has_empty_field(); void set_has_field_mask_field(); void set_has_source_context_field(); void set_has_struct_field(); void set_has_timestamp_field(); void set_has_type_field(); void set_has_double_field(); void set_has_float_field(); void set_has_int64_field(); void set_has_uint64_field(); void set_has_int32_field(); void set_has_uint32_field(); void set_has_bool_field(); void set_has_string_field(); void set_has_bytes_field(); inline bool has_oneof_field() const; void clear_oneof_field(); inline void clear_has_oneof_field(); ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; union OneofFieldUnion { OneofFieldUnion() {} ::google::protobuf::Any* any_field_; ::google::protobuf::Api* api_field_; ::google::protobuf::Duration* duration_field_; ::google::protobuf::Empty* empty_field_; ::google::protobuf::FieldMask* field_mask_field_; ::google::protobuf::SourceContext* source_context_field_; ::google::protobuf::Struct* struct_field_; ::google::protobuf::Timestamp* timestamp_field_; ::google::protobuf::Type* type_field_; ::google::protobuf::DoubleValue* double_field_; ::google::protobuf::FloatValue* float_field_; ::google::protobuf::Int64Value* int64_field_; ::google::protobuf::UInt64Value* uint64_field_; ::google::protobuf::Int32Value* int32_field_; ::google::protobuf::UInt32Value* uint32_field_; ::google::protobuf::BoolValue* bool_field_; ::google::protobuf::StringValue* string_field_; ::google::protobuf::BytesValue* bytes_field_; } oneof_field_; mutable int _cached_size_; ::google::protobuf::uint32 _oneof_case_[1]; friend void protobuf_InitDefaults_google_2fprotobuf_2funittest_5fwell_5fknown_5ftypes_2eproto_impl(); friend void protobuf_AddDesc_google_2fprotobuf_2funittest_5fwell_5fknown_5ftypes_2eproto_impl(); friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2funittest_5fwell_5fknown_5ftypes_2eproto(); friend void protobuf_ShutdownFile_google_2fprotobuf_2funittest_5fwell_5fknown_5ftypes_2eproto(); }; // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- class MapWellKnownTypes : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:protobuf_unittest.MapWellKnownTypes) */ { public: MapWellKnownTypes(); virtual ~MapWellKnownTypes(); MapWellKnownTypes(const MapWellKnownTypes& from); inline MapWellKnownTypes& operator=(const MapWellKnownTypes& from) { CopyFrom(from); return *this; } static const ::google::protobuf::Descriptor* descriptor(); static const MapWellKnownTypes& default_instance(); static inline const MapWellKnownTypes* internal_default_instance() { return reinterpret_cast<const MapWellKnownTypes*>( &_MapWellKnownTypes_default_instance_); } void Swap(MapWellKnownTypes* other); // implements Message ---------------------------------------------- inline MapWellKnownTypes* New() const PROTOBUF_FINAL { return New(NULL); } MapWellKnownTypes* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL; void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; void CopyFrom(const MapWellKnownTypes& from); void MergeFrom(const MapWellKnownTypes& from); void Clear() PROTOBUF_FINAL; bool IsInitialized() const PROTOBUF_FINAL; size_t ByteSizeLong() const PROTOBUF_FINAL; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const PROTOBUF_FINAL { return InternalSerializeWithCachedSizesToArray(false, output); } int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const PROTOBUF_FINAL; void InternalSwap(MapWellKnownTypes* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { return NULL; } inline void* MaybeArenaPtr() const { return NULL; } public: ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // map<int32, .google.protobuf.Any> any_field = 1; int any_field_size() const; void clear_any_field(); static const int kAnyFieldFieldNumber = 1; const ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::Any >& any_field() const; ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::Any >* mutable_any_field(); // map<int32, .google.protobuf.Api> api_field = 2; int api_field_size() const; void clear_api_field(); static const int kApiFieldFieldNumber = 2; const ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::Api >& api_field() const; ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::Api >* mutable_api_field(); // map<int32, .google.protobuf.Duration> duration_field = 3; int duration_field_size() const; void clear_duration_field(); static const int kDurationFieldFieldNumber = 3; const ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::Duration >& duration_field() const; ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::Duration >* mutable_duration_field(); // map<int32, .google.protobuf.Empty> empty_field = 4; int empty_field_size() const; void clear_empty_field(); static const int kEmptyFieldFieldNumber = 4; const ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::Empty >& empty_field() const; ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::Empty >* mutable_empty_field(); // map<int32, .google.protobuf.FieldMask> field_mask_field = 5; int field_mask_field_size() const; void clear_field_mask_field(); static const int kFieldMaskFieldFieldNumber = 5; const ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::FieldMask >& field_mask_field() const; ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::FieldMask >* mutable_field_mask_field(); // map<int32, .google.protobuf.SourceContext> source_context_field = 6; int source_context_field_size() const; void clear_source_context_field(); static const int kSourceContextFieldFieldNumber = 6; const ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::SourceContext >& source_context_field() const; ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::SourceContext >* mutable_source_context_field(); // map<int32, .google.protobuf.Struct> struct_field = 7; int struct_field_size() const; void clear_struct_field(); static const int kStructFieldFieldNumber = 7; const ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::Struct >& struct_field() const; ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::Struct >* mutable_struct_field(); // map<int32, .google.protobuf.Timestamp> timestamp_field = 8; int timestamp_field_size() const; void clear_timestamp_field(); static const int kTimestampFieldFieldNumber = 8; const ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::Timestamp >& timestamp_field() const; ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::Timestamp >* mutable_timestamp_field(); // map<int32, .google.protobuf.Type> type_field = 9; int type_field_size() const; void clear_type_field(); static const int kTypeFieldFieldNumber = 9; const ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::Type >& type_field() const; ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::Type >* mutable_type_field(); // map<int32, .google.protobuf.DoubleValue> double_field = 10; int double_field_size() const; void clear_double_field(); static const int kDoubleFieldFieldNumber = 10; const ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::DoubleValue >& double_field() const; ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::DoubleValue >* mutable_double_field(); // map<int32, .google.protobuf.FloatValue> float_field = 11; int float_field_size() const; void clear_float_field(); static const int kFloatFieldFieldNumber = 11; const ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::FloatValue >& float_field() const; ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::FloatValue >* mutable_float_field(); // map<int32, .google.protobuf.Int64Value> int64_field = 12; int int64_field_size() const; void clear_int64_field(); static const int kInt64FieldFieldNumber = 12; const ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::Int64Value >& int64_field() const; ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::Int64Value >* mutable_int64_field(); // map<int32, .google.protobuf.UInt64Value> uint64_field = 13; int uint64_field_size() const; void clear_uint64_field(); static const int kUint64FieldFieldNumber = 13; const ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::UInt64Value >& uint64_field() const; ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::UInt64Value >* mutable_uint64_field(); // map<int32, .google.protobuf.Int32Value> int32_field = 14; int int32_field_size() const; void clear_int32_field(); static const int kInt32FieldFieldNumber = 14; const ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::Int32Value >& int32_field() const; ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::Int32Value >* mutable_int32_field(); // map<int32, .google.protobuf.UInt32Value> uint32_field = 15; int uint32_field_size() const; void clear_uint32_field(); static const int kUint32FieldFieldNumber = 15; const ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::UInt32Value >& uint32_field() const; ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::UInt32Value >* mutable_uint32_field(); // map<int32, .google.protobuf.BoolValue> bool_field = 16; int bool_field_size() const; void clear_bool_field(); static const int kBoolFieldFieldNumber = 16; const ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::BoolValue >& bool_field() const; ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::BoolValue >* mutable_bool_field(); // map<int32, .google.protobuf.StringValue> string_field = 17; int string_field_size() const; void clear_string_field(); static const int kStringFieldFieldNumber = 17; const ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::StringValue >& string_field() const; ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::StringValue >* mutable_string_field(); // map<int32, .google.protobuf.BytesValue> bytes_field = 18; int bytes_field_size() const; void clear_bytes_field(); static const int kBytesFieldFieldNumber = 18; const ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::BytesValue >& bytes_field() const; ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::BytesValue >* mutable_bytes_field(); // @@protoc_insertion_point(class_scope:protobuf_unittest.MapWellKnownTypes) private: ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; typedef ::google::protobuf::internal::MapEntryLite< ::google::protobuf::int32, ::google::protobuf::Any, ::google::protobuf::internal::WireFormatLite::TYPE_INT32, ::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE, 0 > MapWellKnownTypes_AnyFieldEntry; ::google::protobuf::internal::MapField< ::google::protobuf::int32, ::google::protobuf::Any, ::google::protobuf::internal::WireFormatLite::TYPE_INT32, ::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE, 0 > any_field_; typedef ::google::protobuf::internal::MapEntryLite< ::google::protobuf::int32, ::google::protobuf::Api, ::google::protobuf::internal::WireFormatLite::TYPE_INT32, ::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE, 0 > MapWellKnownTypes_ApiFieldEntry; ::google::protobuf::internal::MapField< ::google::protobuf::int32, ::google::protobuf::Api, ::google::protobuf::internal::WireFormatLite::TYPE_INT32, ::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE, 0 > api_field_; typedef ::google::protobuf::internal::MapEntryLite< ::google::protobuf::int32, ::google::protobuf::Duration, ::google::protobuf::internal::WireFormatLite::TYPE_INT32, ::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE, 0 > MapWellKnownTypes_DurationFieldEntry; ::google::protobuf::internal::MapField< ::google::protobuf::int32, ::google::protobuf::Duration, ::google::protobuf::internal::WireFormatLite::TYPE_INT32, ::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE, 0 > duration_field_; typedef ::google::protobuf::internal::MapEntryLite< ::google::protobuf::int32, ::google::protobuf::Empty, ::google::protobuf::internal::WireFormatLite::TYPE_INT32, ::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE, 0 > MapWellKnownTypes_EmptyFieldEntry; ::google::protobuf::internal::MapField< ::google::protobuf::int32, ::google::protobuf::Empty, ::google::protobuf::internal::WireFormatLite::TYPE_INT32, ::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE, 0 > empty_field_; typedef ::google::protobuf::internal::MapEntryLite< ::google::protobuf::int32, ::google::protobuf::FieldMask, ::google::protobuf::internal::WireFormatLite::TYPE_INT32, ::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE, 0 > MapWellKnownTypes_FieldMaskFieldEntry; ::google::protobuf::internal::MapField< ::google::protobuf::int32, ::google::protobuf::FieldMask, ::google::protobuf::internal::WireFormatLite::TYPE_INT32, ::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE, 0 > field_mask_field_; typedef ::google::protobuf::internal::MapEntryLite< ::google::protobuf::int32, ::google::protobuf::SourceContext, ::google::protobuf::internal::WireFormatLite::TYPE_INT32, ::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE, 0 > MapWellKnownTypes_SourceContextFieldEntry; ::google::protobuf::internal::MapField< ::google::protobuf::int32, ::google::protobuf::SourceContext, ::google::protobuf::internal::WireFormatLite::TYPE_INT32, ::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE, 0 > source_context_field_; typedef ::google::protobuf::internal::MapEntryLite< ::google::protobuf::int32, ::google::protobuf::Struct, ::google::protobuf::internal::WireFormatLite::TYPE_INT32, ::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE, 0 > MapWellKnownTypes_StructFieldEntry; ::google::protobuf::internal::MapField< ::google::protobuf::int32, ::google::protobuf::Struct, ::google::protobuf::internal::WireFormatLite::TYPE_INT32, ::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE, 0 > struct_field_; typedef ::google::protobuf::internal::MapEntryLite< ::google::protobuf::int32, ::google::protobuf::Timestamp, ::google::protobuf::internal::WireFormatLite::TYPE_INT32, ::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE, 0 > MapWellKnownTypes_TimestampFieldEntry; ::google::protobuf::internal::MapField< ::google::protobuf::int32, ::google::protobuf::Timestamp, ::google::protobuf::internal::WireFormatLite::TYPE_INT32, ::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE, 0 > timestamp_field_; typedef ::google::protobuf::internal::MapEntryLite< ::google::protobuf::int32, ::google::protobuf::Type, ::google::protobuf::internal::WireFormatLite::TYPE_INT32, ::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE, 0 > MapWellKnownTypes_TypeFieldEntry; ::google::protobuf::internal::MapField< ::google::protobuf::int32, ::google::protobuf::Type, ::google::protobuf::internal::WireFormatLite::TYPE_INT32, ::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE, 0 > type_field_; typedef ::google::protobuf::internal::MapEntryLite< ::google::protobuf::int32, ::google::protobuf::DoubleValue, ::google::protobuf::internal::WireFormatLite::TYPE_INT32, ::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE, 0 > MapWellKnownTypes_DoubleFieldEntry; ::google::protobuf::internal::MapField< ::google::protobuf::int32, ::google::protobuf::DoubleValue, ::google::protobuf::internal::WireFormatLite::TYPE_INT32, ::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE, 0 > double_field_; typedef ::google::protobuf::internal::MapEntryLite< ::google::protobuf::int32, ::google::protobuf::FloatValue, ::google::protobuf::internal::WireFormatLite::TYPE_INT32, ::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE, 0 > MapWellKnownTypes_FloatFieldEntry; ::google::protobuf::internal::MapField< ::google::protobuf::int32, ::google::protobuf::FloatValue, ::google::protobuf::internal::WireFormatLite::TYPE_INT32, ::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE, 0 > float_field_; typedef ::google::protobuf::internal::MapEntryLite< ::google::protobuf::int32, ::google::protobuf::Int64Value, ::google::protobuf::internal::WireFormatLite::TYPE_INT32, ::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE, 0 > MapWellKnownTypes_Int64FieldEntry; ::google::protobuf::internal::MapField< ::google::protobuf::int32, ::google::protobuf::Int64Value, ::google::protobuf::internal::WireFormatLite::TYPE_INT32, ::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE, 0 > int64_field_; typedef ::google::protobuf::internal::MapEntryLite< ::google::protobuf::int32, ::google::protobuf::UInt64Value, ::google::protobuf::internal::WireFormatLite::TYPE_INT32, ::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE, 0 > MapWellKnownTypes_Uint64FieldEntry; ::google::protobuf::internal::MapField< ::google::protobuf::int32, ::google::protobuf::UInt64Value, ::google::protobuf::internal::WireFormatLite::TYPE_INT32, ::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE, 0 > uint64_field_; typedef ::google::protobuf::internal::MapEntryLite< ::google::protobuf::int32, ::google::protobuf::Int32Value, ::google::protobuf::internal::WireFormatLite::TYPE_INT32, ::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE, 0 > MapWellKnownTypes_Int32FieldEntry; ::google::protobuf::internal::MapField< ::google::protobuf::int32, ::google::protobuf::Int32Value, ::google::protobuf::internal::WireFormatLite::TYPE_INT32, ::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE, 0 > int32_field_; typedef ::google::protobuf::internal::MapEntryLite< ::google::protobuf::int32, ::google::protobuf::UInt32Value, ::google::protobuf::internal::WireFormatLite::TYPE_INT32, ::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE, 0 > MapWellKnownTypes_Uint32FieldEntry; ::google::protobuf::internal::MapField< ::google::protobuf::int32, ::google::protobuf::UInt32Value, ::google::protobuf::internal::WireFormatLite::TYPE_INT32, ::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE, 0 > uint32_field_; typedef ::google::protobuf::internal::MapEntryLite< ::google::protobuf::int32, ::google::protobuf::BoolValue, ::google::protobuf::internal::WireFormatLite::TYPE_INT32, ::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE, 0 > MapWellKnownTypes_BoolFieldEntry; ::google::protobuf::internal::MapField< ::google::protobuf::int32, ::google::protobuf::BoolValue, ::google::protobuf::internal::WireFormatLite::TYPE_INT32, ::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE, 0 > bool_field_; typedef ::google::protobuf::internal::MapEntryLite< ::google::protobuf::int32, ::google::protobuf::StringValue, ::google::protobuf::internal::WireFormatLite::TYPE_INT32, ::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE, 0 > MapWellKnownTypes_StringFieldEntry; ::google::protobuf::internal::MapField< ::google::protobuf::int32, ::google::protobuf::StringValue, ::google::protobuf::internal::WireFormatLite::TYPE_INT32, ::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE, 0 > string_field_; typedef ::google::protobuf::internal::MapEntryLite< ::google::protobuf::int32, ::google::protobuf::BytesValue, ::google::protobuf::internal::WireFormatLite::TYPE_INT32, ::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE, 0 > MapWellKnownTypes_BytesFieldEntry; ::google::protobuf::internal::MapField< ::google::protobuf::int32, ::google::protobuf::BytesValue, ::google::protobuf::internal::WireFormatLite::TYPE_INT32, ::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE, 0 > bytes_field_; mutable int _cached_size_; friend void protobuf_InitDefaults_google_2fprotobuf_2funittest_5fwell_5fknown_5ftypes_2eproto_impl(); friend void protobuf_AddDesc_google_2fprotobuf_2funittest_5fwell_5fknown_5ftypes_2eproto_impl(); friend const ::google::protobuf::uint32* protobuf_Offsets_google_2fprotobuf_2funittest_5fwell_5fknown_5ftypes_2eproto(); friend void protobuf_ShutdownFile_google_2fprotobuf_2funittest_5fwell_5fknown_5ftypes_2eproto(); }; // =================================================================== // =================================================================== #if !PROTOBUF_INLINE_NOT_IN_HEADERS // TestWellKnownTypes // .google.protobuf.Any any_field = 1; inline bool TestWellKnownTypes::has_any_field() const { return this != internal_default_instance() && any_field_ != NULL; } inline void TestWellKnownTypes::clear_any_field() { if (GetArenaNoVirtual() == NULL && any_field_ != NULL) delete any_field_; any_field_ = NULL; } inline const ::google::protobuf::Any& TestWellKnownTypes::any_field() const { // @@protoc_insertion_point(field_get:protobuf_unittest.TestWellKnownTypes.any_field) return any_field_ != NULL ? *any_field_ : *::google::protobuf::Any::internal_default_instance(); } inline ::google::protobuf::Any* TestWellKnownTypes::mutable_any_field() { if (any_field_ == NULL) { any_field_ = new ::google::protobuf::Any; } // @@protoc_insertion_point(field_mutable:protobuf_unittest.TestWellKnownTypes.any_field) return any_field_; } inline ::google::protobuf::Any* TestWellKnownTypes::release_any_field() { // @@protoc_insertion_point(field_release:protobuf_unittest.TestWellKnownTypes.any_field) ::google::protobuf::Any* temp = any_field_; any_field_ = NULL; return temp; } inline void TestWellKnownTypes::set_allocated_any_field(::google::protobuf::Any* any_field) { delete any_field_; any_field_ = any_field; if (any_field) { } else { } // @@protoc_insertion_point(field_set_allocated:protobuf_unittest.TestWellKnownTypes.any_field) } // .google.protobuf.Api api_field = 2; inline bool TestWellKnownTypes::has_api_field() const { return this != internal_default_instance() && api_field_ != NULL; } inline void TestWellKnownTypes::clear_api_field() { if (GetArenaNoVirtual() == NULL && api_field_ != NULL) delete api_field_; api_field_ = NULL; } inline const ::google::protobuf::Api& TestWellKnownTypes::api_field() const { // @@protoc_insertion_point(field_get:protobuf_unittest.TestWellKnownTypes.api_field) return api_field_ != NULL ? *api_field_ : *::google::protobuf::Api::internal_default_instance(); } inline ::google::protobuf::Api* TestWellKnownTypes::mutable_api_field() { if (api_field_ == NULL) { api_field_ = new ::google::protobuf::Api; } // @@protoc_insertion_point(field_mutable:protobuf_unittest.TestWellKnownTypes.api_field) return api_field_; } inline ::google::protobuf::Api* TestWellKnownTypes::release_api_field() { // @@protoc_insertion_point(field_release:protobuf_unittest.TestWellKnownTypes.api_field) ::google::protobuf::Api* temp = api_field_; api_field_ = NULL; return temp; } inline void TestWellKnownTypes::set_allocated_api_field(::google::protobuf::Api* api_field) { delete api_field_; api_field_ = api_field; if (api_field) { } else { } // @@protoc_insertion_point(field_set_allocated:protobuf_unittest.TestWellKnownTypes.api_field) } // .google.protobuf.Duration duration_field = 3; inline bool TestWellKnownTypes::has_duration_field() const { return this != internal_default_instance() && duration_field_ != NULL; } inline void TestWellKnownTypes::clear_duration_field() { if (GetArenaNoVirtual() == NULL && duration_field_ != NULL) delete duration_field_; duration_field_ = NULL; } inline const ::google::protobuf::Duration& TestWellKnownTypes::duration_field() const { // @@protoc_insertion_point(field_get:protobuf_unittest.TestWellKnownTypes.duration_field) return duration_field_ != NULL ? *duration_field_ : *::google::protobuf::Duration::internal_default_instance(); } inline ::google::protobuf::Duration* TestWellKnownTypes::mutable_duration_field() { if (duration_field_ == NULL) { duration_field_ = new ::google::protobuf::Duration; } // @@protoc_insertion_point(field_mutable:protobuf_unittest.TestWellKnownTypes.duration_field) return duration_field_; } inline ::google::protobuf::Duration* TestWellKnownTypes::release_duration_field() { // @@protoc_insertion_point(field_release:protobuf_unittest.TestWellKnownTypes.duration_field) ::google::protobuf::Duration* temp = duration_field_; duration_field_ = NULL; return temp; } inline void TestWellKnownTypes::set_allocated_duration_field(::google::protobuf::Duration* duration_field) { delete duration_field_; if (duration_field != NULL && duration_field->GetArena() != NULL) { ::google::protobuf::Duration* new_duration_field = new ::google::protobuf::Duration; new_duration_field->CopyFrom(*duration_field); duration_field = new_duration_field; } duration_field_ = duration_field; if (duration_field) { } else { } // @@protoc_insertion_point(field_set_allocated:protobuf_unittest.TestWellKnownTypes.duration_field) } // .google.protobuf.Empty empty_field = 4; inline bool TestWellKnownTypes::has_empty_field() const { return this != internal_default_instance() && empty_field_ != NULL; } inline void TestWellKnownTypes::clear_empty_field() { if (GetArenaNoVirtual() == NULL && empty_field_ != NULL) delete empty_field_; empty_field_ = NULL; } inline const ::google::protobuf::Empty& TestWellKnownTypes::empty_field() const { // @@protoc_insertion_point(field_get:protobuf_unittest.TestWellKnownTypes.empty_field) return empty_field_ != NULL ? *empty_field_ : *::google::protobuf::Empty::internal_default_instance(); } inline ::google::protobuf::Empty* TestWellKnownTypes::mutable_empty_field() { if (empty_field_ == NULL) { empty_field_ = new ::google::protobuf::Empty; } // @@protoc_insertion_point(field_mutable:protobuf_unittest.TestWellKnownTypes.empty_field) return empty_field_; } inline ::google::protobuf::Empty* TestWellKnownTypes::release_empty_field() { // @@protoc_insertion_point(field_release:protobuf_unittest.TestWellKnownTypes.empty_field) ::google::protobuf::Empty* temp = empty_field_; empty_field_ = NULL; return temp; } inline void TestWellKnownTypes::set_allocated_empty_field(::google::protobuf::Empty* empty_field) { delete empty_field_; if (empty_field != NULL && empty_field->GetArena() != NULL) { ::google::protobuf::Empty* new_empty_field = new ::google::protobuf::Empty; new_empty_field->CopyFrom(*empty_field); empty_field = new_empty_field; } empty_field_ = empty_field; if (empty_field) { } else { } // @@protoc_insertion_point(field_set_allocated:protobuf_unittest.TestWellKnownTypes.empty_field) } // .google.protobuf.FieldMask field_mask_field = 5; inline bool TestWellKnownTypes::has_field_mask_field() const { return this != internal_default_instance() && field_mask_field_ != NULL; } inline void TestWellKnownTypes::clear_field_mask_field() { if (GetArenaNoVirtual() == NULL && field_mask_field_ != NULL) delete field_mask_field_; field_mask_field_ = NULL; } inline const ::google::protobuf::FieldMask& TestWellKnownTypes::field_mask_field() const { // @@protoc_insertion_point(field_get:protobuf_unittest.TestWellKnownTypes.field_mask_field) return field_mask_field_ != NULL ? *field_mask_field_ : *::google::protobuf::FieldMask::internal_default_instance(); } inline ::google::protobuf::FieldMask* TestWellKnownTypes::mutable_field_mask_field() { if (field_mask_field_ == NULL) { field_mask_field_ = new ::google::protobuf::FieldMask; } // @@protoc_insertion_point(field_mutable:protobuf_unittest.TestWellKnownTypes.field_mask_field) return field_mask_field_; } inline ::google::protobuf::FieldMask* TestWellKnownTypes::release_field_mask_field() { // @@protoc_insertion_point(field_release:protobuf_unittest.TestWellKnownTypes.field_mask_field) ::google::protobuf::FieldMask* temp = field_mask_field_; field_mask_field_ = NULL; return temp; } inline void TestWellKnownTypes::set_allocated_field_mask_field(::google::protobuf::FieldMask* field_mask_field) { delete field_mask_field_; field_mask_field_ = field_mask_field; if (field_mask_field) { } else { } // @@protoc_insertion_point(field_set_allocated:protobuf_unittest.TestWellKnownTypes.field_mask_field) } // .google.protobuf.SourceContext source_context_field = 6; inline bool TestWellKnownTypes::has_source_context_field() const { return this != internal_default_instance() && source_context_field_ != NULL; } inline void TestWellKnownTypes::clear_source_context_field() { if (GetArenaNoVirtual() == NULL && source_context_field_ != NULL) delete source_context_field_; source_context_field_ = NULL; } inline const ::google::protobuf::SourceContext& TestWellKnownTypes::source_context_field() const { // @@protoc_insertion_point(field_get:protobuf_unittest.TestWellKnownTypes.source_context_field) return source_context_field_ != NULL ? *source_context_field_ : *::google::protobuf::SourceContext::internal_default_instance(); } inline ::google::protobuf::SourceContext* TestWellKnownTypes::mutable_source_context_field() { if (source_context_field_ == NULL) { source_context_field_ = new ::google::protobuf::SourceContext; } // @@protoc_insertion_point(field_mutable:protobuf_unittest.TestWellKnownTypes.source_context_field) return source_context_field_; } inline ::google::protobuf::SourceContext* TestWellKnownTypes::release_source_context_field() { // @@protoc_insertion_point(field_release:protobuf_unittest.TestWellKnownTypes.source_context_field) ::google::protobuf::SourceContext* temp = source_context_field_; source_context_field_ = NULL; return temp; } inline void TestWellKnownTypes::set_allocated_source_context_field(::google::protobuf::SourceContext* source_context_field) { delete source_context_field_; source_context_field_ = source_context_field; if (source_context_field) { } else { } // @@protoc_insertion_point(field_set_allocated:protobuf_unittest.TestWellKnownTypes.source_context_field) } // .google.protobuf.Struct struct_field = 7; inline bool TestWellKnownTypes::has_struct_field() const { return this != internal_default_instance() && struct_field_ != NULL; } inline void TestWellKnownTypes::clear_struct_field() { if (GetArenaNoVirtual() == NULL && struct_field_ != NULL) delete struct_field_; struct_field_ = NULL; } inline const ::google::protobuf::Struct& TestWellKnownTypes::struct_field() const { // @@protoc_insertion_point(field_get:protobuf_unittest.TestWellKnownTypes.struct_field) return struct_field_ != NULL ? *struct_field_ : *::google::protobuf::Struct::internal_default_instance(); } inline ::google::protobuf::Struct* TestWellKnownTypes::mutable_struct_field() { if (struct_field_ == NULL) { struct_field_ = new ::google::protobuf::Struct; } // @@protoc_insertion_point(field_mutable:protobuf_unittest.TestWellKnownTypes.struct_field) return struct_field_; } inline ::google::protobuf::Struct* TestWellKnownTypes::release_struct_field() { // @@protoc_insertion_point(field_release:protobuf_unittest.TestWellKnownTypes.struct_field) ::google::protobuf::Struct* temp = struct_field_; struct_field_ = NULL; return temp; } inline void TestWellKnownTypes::set_allocated_struct_field(::google::protobuf::Struct* struct_field) { delete struct_field_; if (struct_field != NULL && struct_field->GetArena() != NULL) { ::google::protobuf::Struct* new_struct_field = new ::google::protobuf::Struct; new_struct_field->CopyFrom(*struct_field); struct_field = new_struct_field; } struct_field_ = struct_field; if (struct_field) { } else { } // @@protoc_insertion_point(field_set_allocated:protobuf_unittest.TestWellKnownTypes.struct_field) } // .google.protobuf.Timestamp timestamp_field = 8; inline bool TestWellKnownTypes::has_timestamp_field() const { return this != internal_default_instance() && timestamp_field_ != NULL; } inline void TestWellKnownTypes::clear_timestamp_field() { if (GetArenaNoVirtual() == NULL && timestamp_field_ != NULL) delete timestamp_field_; timestamp_field_ = NULL; } inline const ::google::protobuf::Timestamp& TestWellKnownTypes::timestamp_field() const { // @@protoc_insertion_point(field_get:protobuf_unittest.TestWellKnownTypes.timestamp_field) return timestamp_field_ != NULL ? *timestamp_field_ : *::google::protobuf::Timestamp::internal_default_instance(); } inline ::google::protobuf::Timestamp* TestWellKnownTypes::mutable_timestamp_field() { if (timestamp_field_ == NULL) { timestamp_field_ = new ::google::protobuf::Timestamp; } // @@protoc_insertion_point(field_mutable:protobuf_unittest.TestWellKnownTypes.timestamp_field) return timestamp_field_; } inline ::google::protobuf::Timestamp* TestWellKnownTypes::release_timestamp_field() { // @@protoc_insertion_point(field_release:protobuf_unittest.TestWellKnownTypes.timestamp_field) ::google::protobuf::Timestamp* temp = timestamp_field_; timestamp_field_ = NULL; return temp; } inline void TestWellKnownTypes::set_allocated_timestamp_field(::google::protobuf::Timestamp* timestamp_field) { delete timestamp_field_; if (timestamp_field != NULL && timestamp_field->GetArena() != NULL) { ::google::protobuf::Timestamp* new_timestamp_field = new ::google::protobuf::Timestamp; new_timestamp_field->CopyFrom(*timestamp_field); timestamp_field = new_timestamp_field; } timestamp_field_ = timestamp_field; if (timestamp_field) { } else { } // @@protoc_insertion_point(field_set_allocated:protobuf_unittest.TestWellKnownTypes.timestamp_field) } // .google.protobuf.Type type_field = 9; inline bool TestWellKnownTypes::has_type_field() const { return this != internal_default_instance() && type_field_ != NULL; } inline void TestWellKnownTypes::clear_type_field() { if (GetArenaNoVirtual() == NULL && type_field_ != NULL) delete type_field_; type_field_ = NULL; } inline const ::google::protobuf::Type& TestWellKnownTypes::type_field() const { // @@protoc_insertion_point(field_get:protobuf_unittest.TestWellKnownTypes.type_field) return type_field_ != NULL ? *type_field_ : *::google::protobuf::Type::internal_default_instance(); } inline ::google::protobuf::Type* TestWellKnownTypes::mutable_type_field() { if (type_field_ == NULL) { type_field_ = new ::google::protobuf::Type; } // @@protoc_insertion_point(field_mutable:protobuf_unittest.TestWellKnownTypes.type_field) return type_field_; } inline ::google::protobuf::Type* TestWellKnownTypes::release_type_field() { // @@protoc_insertion_point(field_release:protobuf_unittest.TestWellKnownTypes.type_field) ::google::protobuf::Type* temp = type_field_; type_field_ = NULL; return temp; } inline void TestWellKnownTypes::set_allocated_type_field(::google::protobuf::Type* type_field) { delete type_field_; if (type_field != NULL && type_field->GetArena() != NULL) { ::google::protobuf::Type* new_type_field = new ::google::protobuf::Type; new_type_field->CopyFrom(*type_field); type_field = new_type_field; } type_field_ = type_field; if (type_field) { } else { } // @@protoc_insertion_point(field_set_allocated:protobuf_unittest.TestWellKnownTypes.type_field) } // .google.protobuf.DoubleValue double_field = 10; inline bool TestWellKnownTypes::has_double_field() const { return this != internal_default_instance() && double_field_ != NULL; } inline void TestWellKnownTypes::clear_double_field() { if (GetArenaNoVirtual() == NULL && double_field_ != NULL) delete double_field_; double_field_ = NULL; } inline const ::google::protobuf::DoubleValue& TestWellKnownTypes::double_field() const { // @@protoc_insertion_point(field_get:protobuf_unittest.TestWellKnownTypes.double_field) return double_field_ != NULL ? *double_field_ : *::google::protobuf::DoubleValue::internal_default_instance(); } inline ::google::protobuf::DoubleValue* TestWellKnownTypes::mutable_double_field() { if (double_field_ == NULL) { double_field_ = new ::google::protobuf::DoubleValue; } // @@protoc_insertion_point(field_mutable:protobuf_unittest.TestWellKnownTypes.double_field) return double_field_; } inline ::google::protobuf::DoubleValue* TestWellKnownTypes::release_double_field() { // @@protoc_insertion_point(field_release:protobuf_unittest.TestWellKnownTypes.double_field) ::google::protobuf::DoubleValue* temp = double_field_; double_field_ = NULL; return temp; } inline void TestWellKnownTypes::set_allocated_double_field(::google::protobuf::DoubleValue* double_field) { delete double_field_; if (double_field != NULL && double_field->GetArena() != NULL) { ::google::protobuf::DoubleValue* new_double_field = new ::google::protobuf::DoubleValue; new_double_field->CopyFrom(*double_field); double_field = new_double_field; } double_field_ = double_field; if (double_field) { } else { } // @@protoc_insertion_point(field_set_allocated:protobuf_unittest.TestWellKnownTypes.double_field) } // .google.protobuf.FloatValue float_field = 11; inline bool TestWellKnownTypes::has_float_field() const { return this != internal_default_instance() && float_field_ != NULL; } inline void TestWellKnownTypes::clear_float_field() { if (GetArenaNoVirtual() == NULL && float_field_ != NULL) delete float_field_; float_field_ = NULL; } inline const ::google::protobuf::FloatValue& TestWellKnownTypes::float_field() const { // @@protoc_insertion_point(field_get:protobuf_unittest.TestWellKnownTypes.float_field) return float_field_ != NULL ? *float_field_ : *::google::protobuf::FloatValue::internal_default_instance(); } inline ::google::protobuf::FloatValue* TestWellKnownTypes::mutable_float_field() { if (float_field_ == NULL) { float_field_ = new ::google::protobuf::FloatValue; } // @@protoc_insertion_point(field_mutable:protobuf_unittest.TestWellKnownTypes.float_field) return float_field_; } inline ::google::protobuf::FloatValue* TestWellKnownTypes::release_float_field() { // @@protoc_insertion_point(field_release:protobuf_unittest.TestWellKnownTypes.float_field) ::google::protobuf::FloatValue* temp = float_field_; float_field_ = NULL; return temp; } inline void TestWellKnownTypes::set_allocated_float_field(::google::protobuf::FloatValue* float_field) { delete float_field_; if (float_field != NULL && float_field->GetArena() != NULL) { ::google::protobuf::FloatValue* new_float_field = new ::google::protobuf::FloatValue; new_float_field->CopyFrom(*float_field); float_field = new_float_field; } float_field_ = float_field; if (float_field) { } else { } // @@protoc_insertion_point(field_set_allocated:protobuf_unittest.TestWellKnownTypes.float_field) } // .google.protobuf.Int64Value int64_field = 12; inline bool TestWellKnownTypes::has_int64_field() const { return this != internal_default_instance() && int64_field_ != NULL; } inline void TestWellKnownTypes::clear_int64_field() { if (GetArenaNoVirtual() == NULL && int64_field_ != NULL) delete int64_field_; int64_field_ = NULL; } inline const ::google::protobuf::Int64Value& TestWellKnownTypes::int64_field() const { // @@protoc_insertion_point(field_get:protobuf_unittest.TestWellKnownTypes.int64_field) return int64_field_ != NULL ? *int64_field_ : *::google::protobuf::Int64Value::internal_default_instance(); } inline ::google::protobuf::Int64Value* TestWellKnownTypes::mutable_int64_field() { if (int64_field_ == NULL) { int64_field_ = new ::google::protobuf::Int64Value; } // @@protoc_insertion_point(field_mutable:protobuf_unittest.TestWellKnownTypes.int64_field) return int64_field_; } inline ::google::protobuf::Int64Value* TestWellKnownTypes::release_int64_field() { // @@protoc_insertion_point(field_release:protobuf_unittest.TestWellKnownTypes.int64_field) ::google::protobuf::Int64Value* temp = int64_field_; int64_field_ = NULL; return temp; } inline void TestWellKnownTypes::set_allocated_int64_field(::google::protobuf::Int64Value* int64_field) { delete int64_field_; if (int64_field != NULL && int64_field->GetArena() != NULL) { ::google::protobuf::Int64Value* new_int64_field = new ::google::protobuf::Int64Value; new_int64_field->CopyFrom(*int64_field); int64_field = new_int64_field; } int64_field_ = int64_field; if (int64_field) { } else { } // @@protoc_insertion_point(field_set_allocated:protobuf_unittest.TestWellKnownTypes.int64_field) } // .google.protobuf.UInt64Value uint64_field = 13; inline bool TestWellKnownTypes::has_uint64_field() const { return this != internal_default_instance() && uint64_field_ != NULL; } inline void TestWellKnownTypes::clear_uint64_field() { if (GetArenaNoVirtual() == NULL && uint64_field_ != NULL) delete uint64_field_; uint64_field_ = NULL; } inline const ::google::protobuf::UInt64Value& TestWellKnownTypes::uint64_field() const { // @@protoc_insertion_point(field_get:protobuf_unittest.TestWellKnownTypes.uint64_field) return uint64_field_ != NULL ? *uint64_field_ : *::google::protobuf::UInt64Value::internal_default_instance(); } inline ::google::protobuf::UInt64Value* TestWellKnownTypes::mutable_uint64_field() { if (uint64_field_ == NULL) { uint64_field_ = new ::google::protobuf::UInt64Value; } // @@protoc_insertion_point(field_mutable:protobuf_unittest.TestWellKnownTypes.uint64_field) return uint64_field_; } inline ::google::protobuf::UInt64Value* TestWellKnownTypes::release_uint64_field() { // @@protoc_insertion_point(field_release:protobuf_unittest.TestWellKnownTypes.uint64_field) ::google::protobuf::UInt64Value* temp = uint64_field_; uint64_field_ = NULL; return temp; } inline void TestWellKnownTypes::set_allocated_uint64_field(::google::protobuf::UInt64Value* uint64_field) { delete uint64_field_; if (uint64_field != NULL && uint64_field->GetArena() != NULL) { ::google::protobuf::UInt64Value* new_uint64_field = new ::google::protobuf::UInt64Value; new_uint64_field->CopyFrom(*uint64_field); uint64_field = new_uint64_field; } uint64_field_ = uint64_field; if (uint64_field) { } else { } // @@protoc_insertion_point(field_set_allocated:protobuf_unittest.TestWellKnownTypes.uint64_field) } // .google.protobuf.Int32Value int32_field = 14; inline bool TestWellKnownTypes::has_int32_field() const { return this != internal_default_instance() && int32_field_ != NULL; } inline void TestWellKnownTypes::clear_int32_field() { if (GetArenaNoVirtual() == NULL && int32_field_ != NULL) delete int32_field_; int32_field_ = NULL; } inline const ::google::protobuf::Int32Value& TestWellKnownTypes::int32_field() const { // @@protoc_insertion_point(field_get:protobuf_unittest.TestWellKnownTypes.int32_field) return int32_field_ != NULL ? *int32_field_ : *::google::protobuf::Int32Value::internal_default_instance(); } inline ::google::protobuf::Int32Value* TestWellKnownTypes::mutable_int32_field() { if (int32_field_ == NULL) { int32_field_ = new ::google::protobuf::Int32Value; } // @@protoc_insertion_point(field_mutable:protobuf_unittest.TestWellKnownTypes.int32_field) return int32_field_; } inline ::google::protobuf::Int32Value* TestWellKnownTypes::release_int32_field() { // @@protoc_insertion_point(field_release:protobuf_unittest.TestWellKnownTypes.int32_field) ::google::protobuf::Int32Value* temp = int32_field_; int32_field_ = NULL; return temp; } inline void TestWellKnownTypes::set_allocated_int32_field(::google::protobuf::Int32Value* int32_field) { delete int32_field_; if (int32_field != NULL && int32_field->GetArena() != NULL) { ::google::protobuf::Int32Value* new_int32_field = new ::google::protobuf::Int32Value; new_int32_field->CopyFrom(*int32_field); int32_field = new_int32_field; } int32_field_ = int32_field; if (int32_field) { } else { } // @@protoc_insertion_point(field_set_allocated:protobuf_unittest.TestWellKnownTypes.int32_field) } // .google.protobuf.UInt32Value uint32_field = 15; inline bool TestWellKnownTypes::has_uint32_field() const { return this != internal_default_instance() && uint32_field_ != NULL; } inline void TestWellKnownTypes::clear_uint32_field() { if (GetArenaNoVirtual() == NULL && uint32_field_ != NULL) delete uint32_field_; uint32_field_ = NULL; } inline const ::google::protobuf::UInt32Value& TestWellKnownTypes::uint32_field() const { // @@protoc_insertion_point(field_get:protobuf_unittest.TestWellKnownTypes.uint32_field) return uint32_field_ != NULL ? *uint32_field_ : *::google::protobuf::UInt32Value::internal_default_instance(); } inline ::google::protobuf::UInt32Value* TestWellKnownTypes::mutable_uint32_field() { if (uint32_field_ == NULL) { uint32_field_ = new ::google::protobuf::UInt32Value; } // @@protoc_insertion_point(field_mutable:protobuf_unittest.TestWellKnownTypes.uint32_field) return uint32_field_; } inline ::google::protobuf::UInt32Value* TestWellKnownTypes::release_uint32_field() { // @@protoc_insertion_point(field_release:protobuf_unittest.TestWellKnownTypes.uint32_field) ::google::protobuf::UInt32Value* temp = uint32_field_; uint32_field_ = NULL; return temp; } inline void TestWellKnownTypes::set_allocated_uint32_field(::google::protobuf::UInt32Value* uint32_field) { delete uint32_field_; if (uint32_field != NULL && uint32_field->GetArena() != NULL) { ::google::protobuf::UInt32Value* new_uint32_field = new ::google::protobuf::UInt32Value; new_uint32_field->CopyFrom(*uint32_field); uint32_field = new_uint32_field; } uint32_field_ = uint32_field; if (uint32_field) { } else { } // @@protoc_insertion_point(field_set_allocated:protobuf_unittest.TestWellKnownTypes.uint32_field) } // .google.protobuf.BoolValue bool_field = 16; inline bool TestWellKnownTypes::has_bool_field() const { return this != internal_default_instance() && bool_field_ != NULL; } inline void TestWellKnownTypes::clear_bool_field() { if (GetArenaNoVirtual() == NULL && bool_field_ != NULL) delete bool_field_; bool_field_ = NULL; } inline const ::google::protobuf::BoolValue& TestWellKnownTypes::bool_field() const { // @@protoc_insertion_point(field_get:protobuf_unittest.TestWellKnownTypes.bool_field) return bool_field_ != NULL ? *bool_field_ : *::google::protobuf::BoolValue::internal_default_instance(); } inline ::google::protobuf::BoolValue* TestWellKnownTypes::mutable_bool_field() { if (bool_field_ == NULL) { bool_field_ = new ::google::protobuf::BoolValue; } // @@protoc_insertion_point(field_mutable:protobuf_unittest.TestWellKnownTypes.bool_field) return bool_field_; } inline ::google::protobuf::BoolValue* TestWellKnownTypes::release_bool_field() { // @@protoc_insertion_point(field_release:protobuf_unittest.TestWellKnownTypes.bool_field) ::google::protobuf::BoolValue* temp = bool_field_; bool_field_ = NULL; return temp; } inline void TestWellKnownTypes::set_allocated_bool_field(::google::protobuf::BoolValue* bool_field) { delete bool_field_; if (bool_field != NULL && bool_field->GetArena() != NULL) { ::google::protobuf::BoolValue* new_bool_field = new ::google::protobuf::BoolValue; new_bool_field->CopyFrom(*bool_field); bool_field = new_bool_field; } bool_field_ = bool_field; if (bool_field) { } else { } // @@protoc_insertion_point(field_set_allocated:protobuf_unittest.TestWellKnownTypes.bool_field) } // .google.protobuf.StringValue string_field = 17; inline bool TestWellKnownTypes::has_string_field() const { return this != internal_default_instance() && string_field_ != NULL; } inline void TestWellKnownTypes::clear_string_field() { if (GetArenaNoVirtual() == NULL && string_field_ != NULL) delete string_field_; string_field_ = NULL; } inline const ::google::protobuf::StringValue& TestWellKnownTypes::string_field() const { // @@protoc_insertion_point(field_get:protobuf_unittest.TestWellKnownTypes.string_field) return string_field_ != NULL ? *string_field_ : *::google::protobuf::StringValue::internal_default_instance(); } inline ::google::protobuf::StringValue* TestWellKnownTypes::mutable_string_field() { if (string_field_ == NULL) { string_field_ = new ::google::protobuf::StringValue; } // @@protoc_insertion_point(field_mutable:protobuf_unittest.TestWellKnownTypes.string_field) return string_field_; } inline ::google::protobuf::StringValue* TestWellKnownTypes::release_string_field() { // @@protoc_insertion_point(field_release:protobuf_unittest.TestWellKnownTypes.string_field) ::google::protobuf::StringValue* temp = string_field_; string_field_ = NULL; return temp; } inline void TestWellKnownTypes::set_allocated_string_field(::google::protobuf::StringValue* string_field) { delete string_field_; if (string_field != NULL && string_field->GetArena() != NULL) { ::google::protobuf::StringValue* new_string_field = new ::google::protobuf::StringValue; new_string_field->CopyFrom(*string_field); string_field = new_string_field; } string_field_ = string_field; if (string_field) { } else { } // @@protoc_insertion_point(field_set_allocated:protobuf_unittest.TestWellKnownTypes.string_field) } // .google.protobuf.BytesValue bytes_field = 18; inline bool TestWellKnownTypes::has_bytes_field() const { return this != internal_default_instance() && bytes_field_ != NULL; } inline void TestWellKnownTypes::clear_bytes_field() { if (GetArenaNoVirtual() == NULL && bytes_field_ != NULL) delete bytes_field_; bytes_field_ = NULL; } inline const ::google::protobuf::BytesValue& TestWellKnownTypes::bytes_field() const { // @@protoc_insertion_point(field_get:protobuf_unittest.TestWellKnownTypes.bytes_field) return bytes_field_ != NULL ? *bytes_field_ : *::google::protobuf::BytesValue::internal_default_instance(); } inline ::google::protobuf::BytesValue* TestWellKnownTypes::mutable_bytes_field() { if (bytes_field_ == NULL) { bytes_field_ = new ::google::protobuf::BytesValue; } // @@protoc_insertion_point(field_mutable:protobuf_unittest.TestWellKnownTypes.bytes_field) return bytes_field_; } inline ::google::protobuf::BytesValue* TestWellKnownTypes::release_bytes_field() { // @@protoc_insertion_point(field_release:protobuf_unittest.TestWellKnownTypes.bytes_field) ::google::protobuf::BytesValue* temp = bytes_field_; bytes_field_ = NULL; return temp; } inline void TestWellKnownTypes::set_allocated_bytes_field(::google::protobuf::BytesValue* bytes_field) { delete bytes_field_; if (bytes_field != NULL && bytes_field->GetArena() != NULL) { ::google::protobuf::BytesValue* new_bytes_field = new ::google::protobuf::BytesValue; new_bytes_field->CopyFrom(*bytes_field); bytes_field = new_bytes_field; } bytes_field_ = bytes_field; if (bytes_field) { } else { } // @@protoc_insertion_point(field_set_allocated:protobuf_unittest.TestWellKnownTypes.bytes_field) } // .google.protobuf.Value value_field = 19; inline bool TestWellKnownTypes::has_value_field() const { return this != internal_default_instance() && value_field_ != NULL; } inline void TestWellKnownTypes::clear_value_field() { if (GetArenaNoVirtual() == NULL && value_field_ != NULL) delete value_field_; value_field_ = NULL; } inline const ::google::protobuf::Value& TestWellKnownTypes::value_field() const { // @@protoc_insertion_point(field_get:protobuf_unittest.TestWellKnownTypes.value_field) return value_field_ != NULL ? *value_field_ : *::google::protobuf::Value::internal_default_instance(); } inline ::google::protobuf::Value* TestWellKnownTypes::mutable_value_field() { if (value_field_ == NULL) { value_field_ = new ::google::protobuf::Value; } // @@protoc_insertion_point(field_mutable:protobuf_unittest.TestWellKnownTypes.value_field) return value_field_; } inline ::google::protobuf::Value* TestWellKnownTypes::release_value_field() { // @@protoc_insertion_point(field_release:protobuf_unittest.TestWellKnownTypes.value_field) ::google::protobuf::Value* temp = value_field_; value_field_ = NULL; return temp; } inline void TestWellKnownTypes::set_allocated_value_field(::google::protobuf::Value* value_field) { delete value_field_; if (value_field != NULL && value_field->GetArena() != NULL) { ::google::protobuf::Value* new_value_field = new ::google::protobuf::Value; new_value_field->CopyFrom(*value_field); value_field = new_value_field; } value_field_ = value_field; if (value_field) { } else { } // @@protoc_insertion_point(field_set_allocated:protobuf_unittest.TestWellKnownTypes.value_field) } // ------------------------------------------------------------------- // RepeatedWellKnownTypes // repeated .google.protobuf.Any any_field = 1; inline int RepeatedWellKnownTypes::any_field_size() const { return any_field_.size(); } inline void RepeatedWellKnownTypes::clear_any_field() { any_field_.Clear(); } inline const ::google::protobuf::Any& RepeatedWellKnownTypes::any_field(int index) const { // @@protoc_insertion_point(field_get:protobuf_unittest.RepeatedWellKnownTypes.any_field) return any_field_.Get(index); } inline ::google::protobuf::Any* RepeatedWellKnownTypes::mutable_any_field(int index) { // @@protoc_insertion_point(field_mutable:protobuf_unittest.RepeatedWellKnownTypes.any_field) return any_field_.Mutable(index); } inline ::google::protobuf::Any* RepeatedWellKnownTypes::add_any_field() { // @@protoc_insertion_point(field_add:protobuf_unittest.RepeatedWellKnownTypes.any_field) return any_field_.Add(); } inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::Any >* RepeatedWellKnownTypes::mutable_any_field() { // @@protoc_insertion_point(field_mutable_list:protobuf_unittest.RepeatedWellKnownTypes.any_field) return &any_field_; } inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Any >& RepeatedWellKnownTypes::any_field() const { // @@protoc_insertion_point(field_list:protobuf_unittest.RepeatedWellKnownTypes.any_field) return any_field_; } // repeated .google.protobuf.Api api_field = 2; inline int RepeatedWellKnownTypes::api_field_size() const { return api_field_.size(); } inline void RepeatedWellKnownTypes::clear_api_field() { api_field_.Clear(); } inline const ::google::protobuf::Api& RepeatedWellKnownTypes::api_field(int index) const { // @@protoc_insertion_point(field_get:protobuf_unittest.RepeatedWellKnownTypes.api_field) return api_field_.Get(index); } inline ::google::protobuf::Api* RepeatedWellKnownTypes::mutable_api_field(int index) { // @@protoc_insertion_point(field_mutable:protobuf_unittest.RepeatedWellKnownTypes.api_field) return api_field_.Mutable(index); } inline ::google::protobuf::Api* RepeatedWellKnownTypes::add_api_field() { // @@protoc_insertion_point(field_add:protobuf_unittest.RepeatedWellKnownTypes.api_field) return api_field_.Add(); } inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::Api >* RepeatedWellKnownTypes::mutable_api_field() { // @@protoc_insertion_point(field_mutable_list:protobuf_unittest.RepeatedWellKnownTypes.api_field) return &api_field_; } inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Api >& RepeatedWellKnownTypes::api_field() const { // @@protoc_insertion_point(field_list:protobuf_unittest.RepeatedWellKnownTypes.api_field) return api_field_; } // repeated .google.protobuf.Duration duration_field = 3; inline int RepeatedWellKnownTypes::duration_field_size() const { return duration_field_.size(); } inline void RepeatedWellKnownTypes::clear_duration_field() { duration_field_.Clear(); } inline const ::google::protobuf::Duration& RepeatedWellKnownTypes::duration_field(int index) const { // @@protoc_insertion_point(field_get:protobuf_unittest.RepeatedWellKnownTypes.duration_field) return duration_field_.Get(index); } inline ::google::protobuf::Duration* RepeatedWellKnownTypes::mutable_duration_field(int index) { // @@protoc_insertion_point(field_mutable:protobuf_unittest.RepeatedWellKnownTypes.duration_field) return duration_field_.Mutable(index); } inline ::google::protobuf::Duration* RepeatedWellKnownTypes::add_duration_field() { // @@protoc_insertion_point(field_add:protobuf_unittest.RepeatedWellKnownTypes.duration_field) return duration_field_.Add(); } inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::Duration >* RepeatedWellKnownTypes::mutable_duration_field() { // @@protoc_insertion_point(field_mutable_list:protobuf_unittest.RepeatedWellKnownTypes.duration_field) return &duration_field_; } inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Duration >& RepeatedWellKnownTypes::duration_field() const { // @@protoc_insertion_point(field_list:protobuf_unittest.RepeatedWellKnownTypes.duration_field) return duration_field_; } // repeated .google.protobuf.Empty empty_field = 4; inline int RepeatedWellKnownTypes::empty_field_size() const { return empty_field_.size(); } inline void RepeatedWellKnownTypes::clear_empty_field() { empty_field_.Clear(); } inline const ::google::protobuf::Empty& RepeatedWellKnownTypes::empty_field(int index) const { // @@protoc_insertion_point(field_get:protobuf_unittest.RepeatedWellKnownTypes.empty_field) return empty_field_.Get(index); } inline ::google::protobuf::Empty* RepeatedWellKnownTypes::mutable_empty_field(int index) { // @@protoc_insertion_point(field_mutable:protobuf_unittest.RepeatedWellKnownTypes.empty_field) return empty_field_.Mutable(index); } inline ::google::protobuf::Empty* RepeatedWellKnownTypes::add_empty_field() { // @@protoc_insertion_point(field_add:protobuf_unittest.RepeatedWellKnownTypes.empty_field) return empty_field_.Add(); } inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::Empty >* RepeatedWellKnownTypes::mutable_empty_field() { // @@protoc_insertion_point(field_mutable_list:protobuf_unittest.RepeatedWellKnownTypes.empty_field) return &empty_field_; } inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Empty >& RepeatedWellKnownTypes::empty_field() const { // @@protoc_insertion_point(field_list:protobuf_unittest.RepeatedWellKnownTypes.empty_field) return empty_field_; } // repeated .google.protobuf.FieldMask field_mask_field = 5; inline int RepeatedWellKnownTypes::field_mask_field_size() const { return field_mask_field_.size(); } inline void RepeatedWellKnownTypes::clear_field_mask_field() { field_mask_field_.Clear(); } inline const ::google::protobuf::FieldMask& RepeatedWellKnownTypes::field_mask_field(int index) const { // @@protoc_insertion_point(field_get:protobuf_unittest.RepeatedWellKnownTypes.field_mask_field) return field_mask_field_.Get(index); } inline ::google::protobuf::FieldMask* RepeatedWellKnownTypes::mutable_field_mask_field(int index) { // @@protoc_insertion_point(field_mutable:protobuf_unittest.RepeatedWellKnownTypes.field_mask_field) return field_mask_field_.Mutable(index); } inline ::google::protobuf::FieldMask* RepeatedWellKnownTypes::add_field_mask_field() { // @@protoc_insertion_point(field_add:protobuf_unittest.RepeatedWellKnownTypes.field_mask_field) return field_mask_field_.Add(); } inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldMask >* RepeatedWellKnownTypes::mutable_field_mask_field() { // @@protoc_insertion_point(field_mutable_list:protobuf_unittest.RepeatedWellKnownTypes.field_mask_field) return &field_mask_field_; } inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldMask >& RepeatedWellKnownTypes::field_mask_field() const { // @@protoc_insertion_point(field_list:protobuf_unittest.RepeatedWellKnownTypes.field_mask_field) return field_mask_field_; } // repeated .google.protobuf.SourceContext source_context_field = 6; inline int RepeatedWellKnownTypes::source_context_field_size() const { return source_context_field_.size(); } inline void RepeatedWellKnownTypes::clear_source_context_field() { source_context_field_.Clear(); } inline const ::google::protobuf::SourceContext& RepeatedWellKnownTypes::source_context_field(int index) const { // @@protoc_insertion_point(field_get:protobuf_unittest.RepeatedWellKnownTypes.source_context_field) return source_context_field_.Get(index); } inline ::google::protobuf::SourceContext* RepeatedWellKnownTypes::mutable_source_context_field(int index) { // @@protoc_insertion_point(field_mutable:protobuf_unittest.RepeatedWellKnownTypes.source_context_field) return source_context_field_.Mutable(index); } inline ::google::protobuf::SourceContext* RepeatedWellKnownTypes::add_source_context_field() { // @@protoc_insertion_point(field_add:protobuf_unittest.RepeatedWellKnownTypes.source_context_field) return source_context_field_.Add(); } inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::SourceContext >* RepeatedWellKnownTypes::mutable_source_context_field() { // @@protoc_insertion_point(field_mutable_list:protobuf_unittest.RepeatedWellKnownTypes.source_context_field) return &source_context_field_; } inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::SourceContext >& RepeatedWellKnownTypes::source_context_field() const { // @@protoc_insertion_point(field_list:protobuf_unittest.RepeatedWellKnownTypes.source_context_field) return source_context_field_; } // repeated .google.protobuf.Struct struct_field = 7; inline int RepeatedWellKnownTypes::struct_field_size() const { return struct_field_.size(); } inline void RepeatedWellKnownTypes::clear_struct_field() { struct_field_.Clear(); } inline const ::google::protobuf::Struct& RepeatedWellKnownTypes::struct_field(int index) const { // @@protoc_insertion_point(field_get:protobuf_unittest.RepeatedWellKnownTypes.struct_field) return struct_field_.Get(index); } inline ::google::protobuf::Struct* RepeatedWellKnownTypes::mutable_struct_field(int index) { // @@protoc_insertion_point(field_mutable:protobuf_unittest.RepeatedWellKnownTypes.struct_field) return struct_field_.Mutable(index); } inline ::google::protobuf::Struct* RepeatedWellKnownTypes::add_struct_field() { // @@protoc_insertion_point(field_add:protobuf_unittest.RepeatedWellKnownTypes.struct_field) return struct_field_.Add(); } inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::Struct >* RepeatedWellKnownTypes::mutable_struct_field() { // @@protoc_insertion_point(field_mutable_list:protobuf_unittest.RepeatedWellKnownTypes.struct_field) return &struct_field_; } inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Struct >& RepeatedWellKnownTypes::struct_field() const { // @@protoc_insertion_point(field_list:protobuf_unittest.RepeatedWellKnownTypes.struct_field) return struct_field_; } // repeated .google.protobuf.Timestamp timestamp_field = 8; inline int RepeatedWellKnownTypes::timestamp_field_size() const { return timestamp_field_.size(); } inline void RepeatedWellKnownTypes::clear_timestamp_field() { timestamp_field_.Clear(); } inline const ::google::protobuf::Timestamp& RepeatedWellKnownTypes::timestamp_field(int index) const { // @@protoc_insertion_point(field_get:protobuf_unittest.RepeatedWellKnownTypes.timestamp_field) return timestamp_field_.Get(index); } inline ::google::protobuf::Timestamp* RepeatedWellKnownTypes::mutable_timestamp_field(int index) { // @@protoc_insertion_point(field_mutable:protobuf_unittest.RepeatedWellKnownTypes.timestamp_field) return timestamp_field_.Mutable(index); } inline ::google::protobuf::Timestamp* RepeatedWellKnownTypes::add_timestamp_field() { // @@protoc_insertion_point(field_add:protobuf_unittest.RepeatedWellKnownTypes.timestamp_field) return timestamp_field_.Add(); } inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::Timestamp >* RepeatedWellKnownTypes::mutable_timestamp_field() { // @@protoc_insertion_point(field_mutable_list:protobuf_unittest.RepeatedWellKnownTypes.timestamp_field) return &timestamp_field_; } inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Timestamp >& RepeatedWellKnownTypes::timestamp_field() const { // @@protoc_insertion_point(field_list:protobuf_unittest.RepeatedWellKnownTypes.timestamp_field) return timestamp_field_; } // repeated .google.protobuf.Type type_field = 9; inline int RepeatedWellKnownTypes::type_field_size() const { return type_field_.size(); } inline void RepeatedWellKnownTypes::clear_type_field() { type_field_.Clear(); } inline const ::google::protobuf::Type& RepeatedWellKnownTypes::type_field(int index) const { // @@protoc_insertion_point(field_get:protobuf_unittest.RepeatedWellKnownTypes.type_field) return type_field_.Get(index); } inline ::google::protobuf::Type* RepeatedWellKnownTypes::mutable_type_field(int index) { // @@protoc_insertion_point(field_mutable:protobuf_unittest.RepeatedWellKnownTypes.type_field) return type_field_.Mutable(index); } inline ::google::protobuf::Type* RepeatedWellKnownTypes::add_type_field() { // @@protoc_insertion_point(field_add:protobuf_unittest.RepeatedWellKnownTypes.type_field) return type_field_.Add(); } inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::Type >* RepeatedWellKnownTypes::mutable_type_field() { // @@protoc_insertion_point(field_mutable_list:protobuf_unittest.RepeatedWellKnownTypes.type_field) return &type_field_; } inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Type >& RepeatedWellKnownTypes::type_field() const { // @@protoc_insertion_point(field_list:protobuf_unittest.RepeatedWellKnownTypes.type_field) return type_field_; } // repeated .google.protobuf.DoubleValue double_field = 10; inline int RepeatedWellKnownTypes::double_field_size() const { return double_field_.size(); } inline void RepeatedWellKnownTypes::clear_double_field() { double_field_.Clear(); } inline const ::google::protobuf::DoubleValue& RepeatedWellKnownTypes::double_field(int index) const { // @@protoc_insertion_point(field_get:protobuf_unittest.RepeatedWellKnownTypes.double_field) return double_field_.Get(index); } inline ::google::protobuf::DoubleValue* RepeatedWellKnownTypes::mutable_double_field(int index) { // @@protoc_insertion_point(field_mutable:protobuf_unittest.RepeatedWellKnownTypes.double_field) return double_field_.Mutable(index); } inline ::google::protobuf::DoubleValue* RepeatedWellKnownTypes::add_double_field() { // @@protoc_insertion_point(field_add:protobuf_unittest.RepeatedWellKnownTypes.double_field) return double_field_.Add(); } inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::DoubleValue >* RepeatedWellKnownTypes::mutable_double_field() { // @@protoc_insertion_point(field_mutable_list:protobuf_unittest.RepeatedWellKnownTypes.double_field) return &double_field_; } inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::DoubleValue >& RepeatedWellKnownTypes::double_field() const { // @@protoc_insertion_point(field_list:protobuf_unittest.RepeatedWellKnownTypes.double_field) return double_field_; } // repeated .google.protobuf.FloatValue float_field = 11; inline int RepeatedWellKnownTypes::float_field_size() const { return float_field_.size(); } inline void RepeatedWellKnownTypes::clear_float_field() { float_field_.Clear(); } inline const ::google::protobuf::FloatValue& RepeatedWellKnownTypes::float_field(int index) const { // @@protoc_insertion_point(field_get:protobuf_unittest.RepeatedWellKnownTypes.float_field) return float_field_.Get(index); } inline ::google::protobuf::FloatValue* RepeatedWellKnownTypes::mutable_float_field(int index) { // @@protoc_insertion_point(field_mutable:protobuf_unittest.RepeatedWellKnownTypes.float_field) return float_field_.Mutable(index); } inline ::google::protobuf::FloatValue* RepeatedWellKnownTypes::add_float_field() { // @@protoc_insertion_point(field_add:protobuf_unittest.RepeatedWellKnownTypes.float_field) return float_field_.Add(); } inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::FloatValue >* RepeatedWellKnownTypes::mutable_float_field() { // @@protoc_insertion_point(field_mutable_list:protobuf_unittest.RepeatedWellKnownTypes.float_field) return &float_field_; } inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::FloatValue >& RepeatedWellKnownTypes::float_field() const { // @@protoc_insertion_point(field_list:protobuf_unittest.RepeatedWellKnownTypes.float_field) return float_field_; } // repeated .google.protobuf.Int64Value int64_field = 12; inline int RepeatedWellKnownTypes::int64_field_size() const { return int64_field_.size(); } inline void RepeatedWellKnownTypes::clear_int64_field() { int64_field_.Clear(); } inline const ::google::protobuf::Int64Value& RepeatedWellKnownTypes::int64_field(int index) const { // @@protoc_insertion_point(field_get:protobuf_unittest.RepeatedWellKnownTypes.int64_field) return int64_field_.Get(index); } inline ::google::protobuf::Int64Value* RepeatedWellKnownTypes::mutable_int64_field(int index) { // @@protoc_insertion_point(field_mutable:protobuf_unittest.RepeatedWellKnownTypes.int64_field) return int64_field_.Mutable(index); } inline ::google::protobuf::Int64Value* RepeatedWellKnownTypes::add_int64_field() { // @@protoc_insertion_point(field_add:protobuf_unittest.RepeatedWellKnownTypes.int64_field) return int64_field_.Add(); } inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::Int64Value >* RepeatedWellKnownTypes::mutable_int64_field() { // @@protoc_insertion_point(field_mutable_list:protobuf_unittest.RepeatedWellKnownTypes.int64_field) return &int64_field_; } inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Int64Value >& RepeatedWellKnownTypes::int64_field() const { // @@protoc_insertion_point(field_list:protobuf_unittest.RepeatedWellKnownTypes.int64_field) return int64_field_; } // repeated .google.protobuf.UInt64Value uint64_field = 13; inline int RepeatedWellKnownTypes::uint64_field_size() const { return uint64_field_.size(); } inline void RepeatedWellKnownTypes::clear_uint64_field() { uint64_field_.Clear(); } inline const ::google::protobuf::UInt64Value& RepeatedWellKnownTypes::uint64_field(int index) const { // @@protoc_insertion_point(field_get:protobuf_unittest.RepeatedWellKnownTypes.uint64_field) return uint64_field_.Get(index); } inline ::google::protobuf::UInt64Value* RepeatedWellKnownTypes::mutable_uint64_field(int index) { // @@protoc_insertion_point(field_mutable:protobuf_unittest.RepeatedWellKnownTypes.uint64_field) return uint64_field_.Mutable(index); } inline ::google::protobuf::UInt64Value* RepeatedWellKnownTypes::add_uint64_field() { // @@protoc_insertion_point(field_add:protobuf_unittest.RepeatedWellKnownTypes.uint64_field) return uint64_field_.Add(); } inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::UInt64Value >* RepeatedWellKnownTypes::mutable_uint64_field() { // @@protoc_insertion_point(field_mutable_list:protobuf_unittest.RepeatedWellKnownTypes.uint64_field) return &uint64_field_; } inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UInt64Value >& RepeatedWellKnownTypes::uint64_field() const { // @@protoc_insertion_point(field_list:protobuf_unittest.RepeatedWellKnownTypes.uint64_field) return uint64_field_; } // repeated .google.protobuf.Int32Value int32_field = 14; inline int RepeatedWellKnownTypes::int32_field_size() const { return int32_field_.size(); } inline void RepeatedWellKnownTypes::clear_int32_field() { int32_field_.Clear(); } inline const ::google::protobuf::Int32Value& RepeatedWellKnownTypes::int32_field(int index) const { // @@protoc_insertion_point(field_get:protobuf_unittest.RepeatedWellKnownTypes.int32_field) return int32_field_.Get(index); } inline ::google::protobuf::Int32Value* RepeatedWellKnownTypes::mutable_int32_field(int index) { // @@protoc_insertion_point(field_mutable:protobuf_unittest.RepeatedWellKnownTypes.int32_field) return int32_field_.Mutable(index); } inline ::google::protobuf::Int32Value* RepeatedWellKnownTypes::add_int32_field() { // @@protoc_insertion_point(field_add:protobuf_unittest.RepeatedWellKnownTypes.int32_field) return int32_field_.Add(); } inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::Int32Value >* RepeatedWellKnownTypes::mutable_int32_field() { // @@protoc_insertion_point(field_mutable_list:protobuf_unittest.RepeatedWellKnownTypes.int32_field) return &int32_field_; } inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Int32Value >& RepeatedWellKnownTypes::int32_field() const { // @@protoc_insertion_point(field_list:protobuf_unittest.RepeatedWellKnownTypes.int32_field) return int32_field_; } // repeated .google.protobuf.UInt32Value uint32_field = 15; inline int RepeatedWellKnownTypes::uint32_field_size() const { return uint32_field_.size(); } inline void RepeatedWellKnownTypes::clear_uint32_field() { uint32_field_.Clear(); } inline const ::google::protobuf::UInt32Value& RepeatedWellKnownTypes::uint32_field(int index) const { // @@protoc_insertion_point(field_get:protobuf_unittest.RepeatedWellKnownTypes.uint32_field) return uint32_field_.Get(index); } inline ::google::protobuf::UInt32Value* RepeatedWellKnownTypes::mutable_uint32_field(int index) { // @@protoc_insertion_point(field_mutable:protobuf_unittest.RepeatedWellKnownTypes.uint32_field) return uint32_field_.Mutable(index); } inline ::google::protobuf::UInt32Value* RepeatedWellKnownTypes::add_uint32_field() { // @@protoc_insertion_point(field_add:protobuf_unittest.RepeatedWellKnownTypes.uint32_field) return uint32_field_.Add(); } inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::UInt32Value >* RepeatedWellKnownTypes::mutable_uint32_field() { // @@protoc_insertion_point(field_mutable_list:protobuf_unittest.RepeatedWellKnownTypes.uint32_field) return &uint32_field_; } inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UInt32Value >& RepeatedWellKnownTypes::uint32_field() const { // @@protoc_insertion_point(field_list:protobuf_unittest.RepeatedWellKnownTypes.uint32_field) return uint32_field_; } // repeated .google.protobuf.BoolValue bool_field = 16; inline int RepeatedWellKnownTypes::bool_field_size() const { return bool_field_.size(); } inline void RepeatedWellKnownTypes::clear_bool_field() { bool_field_.Clear(); } inline const ::google::protobuf::BoolValue& RepeatedWellKnownTypes::bool_field(int index) const { // @@protoc_insertion_point(field_get:protobuf_unittest.RepeatedWellKnownTypes.bool_field) return bool_field_.Get(index); } inline ::google::protobuf::BoolValue* RepeatedWellKnownTypes::mutable_bool_field(int index) { // @@protoc_insertion_point(field_mutable:protobuf_unittest.RepeatedWellKnownTypes.bool_field) return bool_field_.Mutable(index); } inline ::google::protobuf::BoolValue* RepeatedWellKnownTypes::add_bool_field() { // @@protoc_insertion_point(field_add:protobuf_unittest.RepeatedWellKnownTypes.bool_field) return bool_field_.Add(); } inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::BoolValue >* RepeatedWellKnownTypes::mutable_bool_field() { // @@protoc_insertion_point(field_mutable_list:protobuf_unittest.RepeatedWellKnownTypes.bool_field) return &bool_field_; } inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::BoolValue >& RepeatedWellKnownTypes::bool_field() const { // @@protoc_insertion_point(field_list:protobuf_unittest.RepeatedWellKnownTypes.bool_field) return bool_field_; } // repeated .google.protobuf.StringValue string_field = 17; inline int RepeatedWellKnownTypes::string_field_size() const { return string_field_.size(); } inline void RepeatedWellKnownTypes::clear_string_field() { string_field_.Clear(); } inline const ::google::protobuf::StringValue& RepeatedWellKnownTypes::string_field(int index) const { // @@protoc_insertion_point(field_get:protobuf_unittest.RepeatedWellKnownTypes.string_field) return string_field_.Get(index); } inline ::google::protobuf::StringValue* RepeatedWellKnownTypes::mutable_string_field(int index) { // @@protoc_insertion_point(field_mutable:protobuf_unittest.RepeatedWellKnownTypes.string_field) return string_field_.Mutable(index); } inline ::google::protobuf::StringValue* RepeatedWellKnownTypes::add_string_field() { // @@protoc_insertion_point(field_add:protobuf_unittest.RepeatedWellKnownTypes.string_field) return string_field_.Add(); } inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::StringValue >* RepeatedWellKnownTypes::mutable_string_field() { // @@protoc_insertion_point(field_mutable_list:protobuf_unittest.RepeatedWellKnownTypes.string_field) return &string_field_; } inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::StringValue >& RepeatedWellKnownTypes::string_field() const { // @@protoc_insertion_point(field_list:protobuf_unittest.RepeatedWellKnownTypes.string_field) return string_field_; } // repeated .google.protobuf.BytesValue bytes_field = 18; inline int RepeatedWellKnownTypes::bytes_field_size() const { return bytes_field_.size(); } inline void RepeatedWellKnownTypes::clear_bytes_field() { bytes_field_.Clear(); } inline const ::google::protobuf::BytesValue& RepeatedWellKnownTypes::bytes_field(int index) const { // @@protoc_insertion_point(field_get:protobuf_unittest.RepeatedWellKnownTypes.bytes_field) return bytes_field_.Get(index); } inline ::google::protobuf::BytesValue* RepeatedWellKnownTypes::mutable_bytes_field(int index) { // @@protoc_insertion_point(field_mutable:protobuf_unittest.RepeatedWellKnownTypes.bytes_field) return bytes_field_.Mutable(index); } inline ::google::protobuf::BytesValue* RepeatedWellKnownTypes::add_bytes_field() { // @@protoc_insertion_point(field_add:protobuf_unittest.RepeatedWellKnownTypes.bytes_field) return bytes_field_.Add(); } inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::BytesValue >* RepeatedWellKnownTypes::mutable_bytes_field() { // @@protoc_insertion_point(field_mutable_list:protobuf_unittest.RepeatedWellKnownTypes.bytes_field) return &bytes_field_; } inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::BytesValue >& RepeatedWellKnownTypes::bytes_field() const { // @@protoc_insertion_point(field_list:protobuf_unittest.RepeatedWellKnownTypes.bytes_field) return bytes_field_; } // ------------------------------------------------------------------- // OneofWellKnownTypes // .google.protobuf.Any any_field = 1; inline bool OneofWellKnownTypes::has_any_field() const { return oneof_field_case() == kAnyField; } inline void OneofWellKnownTypes::set_has_any_field() { _oneof_case_[0] = kAnyField; } inline void OneofWellKnownTypes::clear_any_field() { if (has_any_field()) { delete oneof_field_.any_field_; clear_has_oneof_field(); } } inline const ::google::protobuf::Any& OneofWellKnownTypes::any_field() const { // @@protoc_insertion_point(field_get:protobuf_unittest.OneofWellKnownTypes.any_field) return has_any_field() ? *oneof_field_.any_field_ : ::google::protobuf::Any::default_instance(); } inline ::google::protobuf::Any* OneofWellKnownTypes::mutable_any_field() { if (!has_any_field()) { clear_oneof_field(); set_has_any_field(); oneof_field_.any_field_ = new ::google::protobuf::Any; } // @@protoc_insertion_point(field_mutable:protobuf_unittest.OneofWellKnownTypes.any_field) return oneof_field_.any_field_; } inline ::google::protobuf::Any* OneofWellKnownTypes::release_any_field() { // @@protoc_insertion_point(field_release:protobuf_unittest.OneofWellKnownTypes.any_field) if (has_any_field()) { clear_has_oneof_field(); ::google::protobuf::Any* temp = oneof_field_.any_field_; oneof_field_.any_field_ = NULL; return temp; } else { return NULL; } } inline void OneofWellKnownTypes::set_allocated_any_field(::google::protobuf::Any* any_field) { clear_oneof_field(); if (any_field) { set_has_any_field(); oneof_field_.any_field_ = any_field; } // @@protoc_insertion_point(field_set_allocated:protobuf_unittest.OneofWellKnownTypes.any_field) } // .google.protobuf.Api api_field = 2; inline bool OneofWellKnownTypes::has_api_field() const { return oneof_field_case() == kApiField; } inline void OneofWellKnownTypes::set_has_api_field() { _oneof_case_[0] = kApiField; } inline void OneofWellKnownTypes::clear_api_field() { if (has_api_field()) { delete oneof_field_.api_field_; clear_has_oneof_field(); } } inline const ::google::protobuf::Api& OneofWellKnownTypes::api_field() const { // @@protoc_insertion_point(field_get:protobuf_unittest.OneofWellKnownTypes.api_field) return has_api_field() ? *oneof_field_.api_field_ : ::google::protobuf::Api::default_instance(); } inline ::google::protobuf::Api* OneofWellKnownTypes::mutable_api_field() { if (!has_api_field()) { clear_oneof_field(); set_has_api_field(); oneof_field_.api_field_ = new ::google::protobuf::Api; } // @@protoc_insertion_point(field_mutable:protobuf_unittest.OneofWellKnownTypes.api_field) return oneof_field_.api_field_; } inline ::google::protobuf::Api* OneofWellKnownTypes::release_api_field() { // @@protoc_insertion_point(field_release:protobuf_unittest.OneofWellKnownTypes.api_field) if (has_api_field()) { clear_has_oneof_field(); ::google::protobuf::Api* temp = oneof_field_.api_field_; oneof_field_.api_field_ = NULL; return temp; } else { return NULL; } } inline void OneofWellKnownTypes::set_allocated_api_field(::google::protobuf::Api* api_field) { clear_oneof_field(); if (api_field) { set_has_api_field(); oneof_field_.api_field_ = api_field; } // @@protoc_insertion_point(field_set_allocated:protobuf_unittest.OneofWellKnownTypes.api_field) } // .google.protobuf.Duration duration_field = 3; inline bool OneofWellKnownTypes::has_duration_field() const { return oneof_field_case() == kDurationField; } inline void OneofWellKnownTypes::set_has_duration_field() { _oneof_case_[0] = kDurationField; } inline void OneofWellKnownTypes::clear_duration_field() { if (has_duration_field()) { delete oneof_field_.duration_field_; clear_has_oneof_field(); } } inline const ::google::protobuf::Duration& OneofWellKnownTypes::duration_field() const { // @@protoc_insertion_point(field_get:protobuf_unittest.OneofWellKnownTypes.duration_field) return has_duration_field() ? *oneof_field_.duration_field_ : ::google::protobuf::Duration::default_instance(); } inline ::google::protobuf::Duration* OneofWellKnownTypes::mutable_duration_field() { if (!has_duration_field()) { clear_oneof_field(); set_has_duration_field(); oneof_field_.duration_field_ = new ::google::protobuf::Duration; } // @@protoc_insertion_point(field_mutable:protobuf_unittest.OneofWellKnownTypes.duration_field) return oneof_field_.duration_field_; } inline ::google::protobuf::Duration* OneofWellKnownTypes::release_duration_field() { // @@protoc_insertion_point(field_release:protobuf_unittest.OneofWellKnownTypes.duration_field) if (has_duration_field()) { clear_has_oneof_field(); ::google::protobuf::Duration* temp = oneof_field_.duration_field_; oneof_field_.duration_field_ = NULL; return temp; } else { return NULL; } } inline void OneofWellKnownTypes::set_allocated_duration_field(::google::protobuf::Duration* duration_field) { clear_oneof_field(); if (duration_field) { if (static_cast< ::google::protobuf::Duration*>(duration_field)->GetArena() != NULL) { ::google::protobuf::Duration* new_duration_field = new ::google::protobuf::Duration; new_duration_field->CopyFrom(*duration_field); duration_field = new_duration_field; } set_has_duration_field(); oneof_field_.duration_field_ = duration_field; } // @@protoc_insertion_point(field_set_allocated:protobuf_unittest.OneofWellKnownTypes.duration_field) } // .google.protobuf.Empty empty_field = 4; inline bool OneofWellKnownTypes::has_empty_field() const { return oneof_field_case() == kEmptyField; } inline void OneofWellKnownTypes::set_has_empty_field() { _oneof_case_[0] = kEmptyField; } inline void OneofWellKnownTypes::clear_empty_field() { if (has_empty_field()) { delete oneof_field_.empty_field_; clear_has_oneof_field(); } } inline const ::google::protobuf::Empty& OneofWellKnownTypes::empty_field() const { // @@protoc_insertion_point(field_get:protobuf_unittest.OneofWellKnownTypes.empty_field) return has_empty_field() ? *oneof_field_.empty_field_ : ::google::protobuf::Empty::default_instance(); } inline ::google::protobuf::Empty* OneofWellKnownTypes::mutable_empty_field() { if (!has_empty_field()) { clear_oneof_field(); set_has_empty_field(); oneof_field_.empty_field_ = new ::google::protobuf::Empty; } // @@protoc_insertion_point(field_mutable:protobuf_unittest.OneofWellKnownTypes.empty_field) return oneof_field_.empty_field_; } inline ::google::protobuf::Empty* OneofWellKnownTypes::release_empty_field() { // @@protoc_insertion_point(field_release:protobuf_unittest.OneofWellKnownTypes.empty_field) if (has_empty_field()) { clear_has_oneof_field(); ::google::protobuf::Empty* temp = oneof_field_.empty_field_; oneof_field_.empty_field_ = NULL; return temp; } else { return NULL; } } inline void OneofWellKnownTypes::set_allocated_empty_field(::google::protobuf::Empty* empty_field) { clear_oneof_field(); if (empty_field) { if (static_cast< ::google::protobuf::Empty*>(empty_field)->GetArena() != NULL) { ::google::protobuf::Empty* new_empty_field = new ::google::protobuf::Empty; new_empty_field->CopyFrom(*empty_field); empty_field = new_empty_field; } set_has_empty_field(); oneof_field_.empty_field_ = empty_field; } // @@protoc_insertion_point(field_set_allocated:protobuf_unittest.OneofWellKnownTypes.empty_field) } // .google.protobuf.FieldMask field_mask_field = 5; inline bool OneofWellKnownTypes::has_field_mask_field() const { return oneof_field_case() == kFieldMaskField; } inline void OneofWellKnownTypes::set_has_field_mask_field() { _oneof_case_[0] = kFieldMaskField; } inline void OneofWellKnownTypes::clear_field_mask_field() { if (has_field_mask_field()) { delete oneof_field_.field_mask_field_; clear_has_oneof_field(); } } inline const ::google::protobuf::FieldMask& OneofWellKnownTypes::field_mask_field() const { // @@protoc_insertion_point(field_get:protobuf_unittest.OneofWellKnownTypes.field_mask_field) return has_field_mask_field() ? *oneof_field_.field_mask_field_ : ::google::protobuf::FieldMask::default_instance(); } inline ::google::protobuf::FieldMask* OneofWellKnownTypes::mutable_field_mask_field() { if (!has_field_mask_field()) { clear_oneof_field(); set_has_field_mask_field(); oneof_field_.field_mask_field_ = new ::google::protobuf::FieldMask; } // @@protoc_insertion_point(field_mutable:protobuf_unittest.OneofWellKnownTypes.field_mask_field) return oneof_field_.field_mask_field_; } inline ::google::protobuf::FieldMask* OneofWellKnownTypes::release_field_mask_field() { // @@protoc_insertion_point(field_release:protobuf_unittest.OneofWellKnownTypes.field_mask_field) if (has_field_mask_field()) { clear_has_oneof_field(); ::google::protobuf::FieldMask* temp = oneof_field_.field_mask_field_; oneof_field_.field_mask_field_ = NULL; return temp; } else { return NULL; } } inline void OneofWellKnownTypes::set_allocated_field_mask_field(::google::protobuf::FieldMask* field_mask_field) { clear_oneof_field(); if (field_mask_field) { set_has_field_mask_field(); oneof_field_.field_mask_field_ = field_mask_field; } // @@protoc_insertion_point(field_set_allocated:protobuf_unittest.OneofWellKnownTypes.field_mask_field) } // .google.protobuf.SourceContext source_context_field = 6; inline bool OneofWellKnownTypes::has_source_context_field() const { return oneof_field_case() == kSourceContextField; } inline void OneofWellKnownTypes::set_has_source_context_field() { _oneof_case_[0] = kSourceContextField; } inline void OneofWellKnownTypes::clear_source_context_field() { if (has_source_context_field()) { delete oneof_field_.source_context_field_; clear_has_oneof_field(); } } inline const ::google::protobuf::SourceContext& OneofWellKnownTypes::source_context_field() const { // @@protoc_insertion_point(field_get:protobuf_unittest.OneofWellKnownTypes.source_context_field) return has_source_context_field() ? *oneof_field_.source_context_field_ : ::google::protobuf::SourceContext::default_instance(); } inline ::google::protobuf::SourceContext* OneofWellKnownTypes::mutable_source_context_field() { if (!has_source_context_field()) { clear_oneof_field(); set_has_source_context_field(); oneof_field_.source_context_field_ = new ::google::protobuf::SourceContext; } // @@protoc_insertion_point(field_mutable:protobuf_unittest.OneofWellKnownTypes.source_context_field) return oneof_field_.source_context_field_; } inline ::google::protobuf::SourceContext* OneofWellKnownTypes::release_source_context_field() { // @@protoc_insertion_point(field_release:protobuf_unittest.OneofWellKnownTypes.source_context_field) if (has_source_context_field()) { clear_has_oneof_field(); ::google::protobuf::SourceContext* temp = oneof_field_.source_context_field_; oneof_field_.source_context_field_ = NULL; return temp; } else { return NULL; } } inline void OneofWellKnownTypes::set_allocated_source_context_field(::google::protobuf::SourceContext* source_context_field) { clear_oneof_field(); if (source_context_field) { set_has_source_context_field(); oneof_field_.source_context_field_ = source_context_field; } // @@protoc_insertion_point(field_set_allocated:protobuf_unittest.OneofWellKnownTypes.source_context_field) } // .google.protobuf.Struct struct_field = 7; inline bool OneofWellKnownTypes::has_struct_field() const { return oneof_field_case() == kStructField; } inline void OneofWellKnownTypes::set_has_struct_field() { _oneof_case_[0] = kStructField; } inline void OneofWellKnownTypes::clear_struct_field() { if (has_struct_field()) { delete oneof_field_.struct_field_; clear_has_oneof_field(); } } inline const ::google::protobuf::Struct& OneofWellKnownTypes::struct_field() const { // @@protoc_insertion_point(field_get:protobuf_unittest.OneofWellKnownTypes.struct_field) return has_struct_field() ? *oneof_field_.struct_field_ : ::google::protobuf::Struct::default_instance(); } inline ::google::protobuf::Struct* OneofWellKnownTypes::mutable_struct_field() { if (!has_struct_field()) { clear_oneof_field(); set_has_struct_field(); oneof_field_.struct_field_ = new ::google::protobuf::Struct; } // @@protoc_insertion_point(field_mutable:protobuf_unittest.OneofWellKnownTypes.struct_field) return oneof_field_.struct_field_; } inline ::google::protobuf::Struct* OneofWellKnownTypes::release_struct_field() { // @@protoc_insertion_point(field_release:protobuf_unittest.OneofWellKnownTypes.struct_field) if (has_struct_field()) { clear_has_oneof_field(); ::google::protobuf::Struct* temp = oneof_field_.struct_field_; oneof_field_.struct_field_ = NULL; return temp; } else { return NULL; } } inline void OneofWellKnownTypes::set_allocated_struct_field(::google::protobuf::Struct* struct_field) { clear_oneof_field(); if (struct_field) { if (static_cast< ::google::protobuf::Struct*>(struct_field)->GetArena() != NULL) { ::google::protobuf::Struct* new_struct_field = new ::google::protobuf::Struct; new_struct_field->CopyFrom(*struct_field); struct_field = new_struct_field; } set_has_struct_field(); oneof_field_.struct_field_ = struct_field; } // @@protoc_insertion_point(field_set_allocated:protobuf_unittest.OneofWellKnownTypes.struct_field) } // .google.protobuf.Timestamp timestamp_field = 8; inline bool OneofWellKnownTypes::has_timestamp_field() const { return oneof_field_case() == kTimestampField; } inline void OneofWellKnownTypes::set_has_timestamp_field() { _oneof_case_[0] = kTimestampField; } inline void OneofWellKnownTypes::clear_timestamp_field() { if (has_timestamp_field()) { delete oneof_field_.timestamp_field_; clear_has_oneof_field(); } } inline const ::google::protobuf::Timestamp& OneofWellKnownTypes::timestamp_field() const { // @@protoc_insertion_point(field_get:protobuf_unittest.OneofWellKnownTypes.timestamp_field) return has_timestamp_field() ? *oneof_field_.timestamp_field_ : ::google::protobuf::Timestamp::default_instance(); } inline ::google::protobuf::Timestamp* OneofWellKnownTypes::mutable_timestamp_field() { if (!has_timestamp_field()) { clear_oneof_field(); set_has_timestamp_field(); oneof_field_.timestamp_field_ = new ::google::protobuf::Timestamp; } // @@protoc_insertion_point(field_mutable:protobuf_unittest.OneofWellKnownTypes.timestamp_field) return oneof_field_.timestamp_field_; } inline ::google::protobuf::Timestamp* OneofWellKnownTypes::release_timestamp_field() { // @@protoc_insertion_point(field_release:protobuf_unittest.OneofWellKnownTypes.timestamp_field) if (has_timestamp_field()) { clear_has_oneof_field(); ::google::protobuf::Timestamp* temp = oneof_field_.timestamp_field_; oneof_field_.timestamp_field_ = NULL; return temp; } else { return NULL; } } inline void OneofWellKnownTypes::set_allocated_timestamp_field(::google::protobuf::Timestamp* timestamp_field) { clear_oneof_field(); if (timestamp_field) { if (static_cast< ::google::protobuf::Timestamp*>(timestamp_field)->GetArena() != NULL) { ::google::protobuf::Timestamp* new_timestamp_field = new ::google::protobuf::Timestamp; new_timestamp_field->CopyFrom(*timestamp_field); timestamp_field = new_timestamp_field; } set_has_timestamp_field(); oneof_field_.timestamp_field_ = timestamp_field; } // @@protoc_insertion_point(field_set_allocated:protobuf_unittest.OneofWellKnownTypes.timestamp_field) } // .google.protobuf.Type type_field = 9; inline bool OneofWellKnownTypes::has_type_field() const { return oneof_field_case() == kTypeField; } inline void OneofWellKnownTypes::set_has_type_field() { _oneof_case_[0] = kTypeField; } inline void OneofWellKnownTypes::clear_type_field() { if (has_type_field()) { delete oneof_field_.type_field_; clear_has_oneof_field(); } } inline const ::google::protobuf::Type& OneofWellKnownTypes::type_field() const { // @@protoc_insertion_point(field_get:protobuf_unittest.OneofWellKnownTypes.type_field) return has_type_field() ? *oneof_field_.type_field_ : ::google::protobuf::Type::default_instance(); } inline ::google::protobuf::Type* OneofWellKnownTypes::mutable_type_field() { if (!has_type_field()) { clear_oneof_field(); set_has_type_field(); oneof_field_.type_field_ = new ::google::protobuf::Type; } // @@protoc_insertion_point(field_mutable:protobuf_unittest.OneofWellKnownTypes.type_field) return oneof_field_.type_field_; } inline ::google::protobuf::Type* OneofWellKnownTypes::release_type_field() { // @@protoc_insertion_point(field_release:protobuf_unittest.OneofWellKnownTypes.type_field) if (has_type_field()) { clear_has_oneof_field(); ::google::protobuf::Type* temp = oneof_field_.type_field_; oneof_field_.type_field_ = NULL; return temp; } else { return NULL; } } inline void OneofWellKnownTypes::set_allocated_type_field(::google::protobuf::Type* type_field) { clear_oneof_field(); if (type_field) { if (static_cast< ::google::protobuf::Type*>(type_field)->GetArena() != NULL) { ::google::protobuf::Type* new_type_field = new ::google::protobuf::Type; new_type_field->CopyFrom(*type_field); type_field = new_type_field; } set_has_type_field(); oneof_field_.type_field_ = type_field; } // @@protoc_insertion_point(field_set_allocated:protobuf_unittest.OneofWellKnownTypes.type_field) } // .google.protobuf.DoubleValue double_field = 10; inline bool OneofWellKnownTypes::has_double_field() const { return oneof_field_case() == kDoubleField; } inline void OneofWellKnownTypes::set_has_double_field() { _oneof_case_[0] = kDoubleField; } inline void OneofWellKnownTypes::clear_double_field() { if (has_double_field()) { delete oneof_field_.double_field_; clear_has_oneof_field(); } } inline const ::google::protobuf::DoubleValue& OneofWellKnownTypes::double_field() const { // @@protoc_insertion_point(field_get:protobuf_unittest.OneofWellKnownTypes.double_field) return has_double_field() ? *oneof_field_.double_field_ : ::google::protobuf::DoubleValue::default_instance(); } inline ::google::protobuf::DoubleValue* OneofWellKnownTypes::mutable_double_field() { if (!has_double_field()) { clear_oneof_field(); set_has_double_field(); oneof_field_.double_field_ = new ::google::protobuf::DoubleValue; } // @@protoc_insertion_point(field_mutable:protobuf_unittest.OneofWellKnownTypes.double_field) return oneof_field_.double_field_; } inline ::google::protobuf::DoubleValue* OneofWellKnownTypes::release_double_field() { // @@protoc_insertion_point(field_release:protobuf_unittest.OneofWellKnownTypes.double_field) if (has_double_field()) { clear_has_oneof_field(); ::google::protobuf::DoubleValue* temp = oneof_field_.double_field_; oneof_field_.double_field_ = NULL; return temp; } else { return NULL; } } inline void OneofWellKnownTypes::set_allocated_double_field(::google::protobuf::DoubleValue* double_field) { clear_oneof_field(); if (double_field) { if (static_cast< ::google::protobuf::DoubleValue*>(double_field)->GetArena() != NULL) { ::google::protobuf::DoubleValue* new_double_field = new ::google::protobuf::DoubleValue; new_double_field->CopyFrom(*double_field); double_field = new_double_field; } set_has_double_field(); oneof_field_.double_field_ = double_field; } // @@protoc_insertion_point(field_set_allocated:protobuf_unittest.OneofWellKnownTypes.double_field) } // .google.protobuf.FloatValue float_field = 11; inline bool OneofWellKnownTypes::has_float_field() const { return oneof_field_case() == kFloatField; } inline void OneofWellKnownTypes::set_has_float_field() { _oneof_case_[0] = kFloatField; } inline void OneofWellKnownTypes::clear_float_field() { if (has_float_field()) { delete oneof_field_.float_field_; clear_has_oneof_field(); } } inline const ::google::protobuf::FloatValue& OneofWellKnownTypes::float_field() const { // @@protoc_insertion_point(field_get:protobuf_unittest.OneofWellKnownTypes.float_field) return has_float_field() ? *oneof_field_.float_field_ : ::google::protobuf::FloatValue::default_instance(); } inline ::google::protobuf::FloatValue* OneofWellKnownTypes::mutable_float_field() { if (!has_float_field()) { clear_oneof_field(); set_has_float_field(); oneof_field_.float_field_ = new ::google::protobuf::FloatValue; } // @@protoc_insertion_point(field_mutable:protobuf_unittest.OneofWellKnownTypes.float_field) return oneof_field_.float_field_; } inline ::google::protobuf::FloatValue* OneofWellKnownTypes::release_float_field() { // @@protoc_insertion_point(field_release:protobuf_unittest.OneofWellKnownTypes.float_field) if (has_float_field()) { clear_has_oneof_field(); ::google::protobuf::FloatValue* temp = oneof_field_.float_field_; oneof_field_.float_field_ = NULL; return temp; } else { return NULL; } } inline void OneofWellKnownTypes::set_allocated_float_field(::google::protobuf::FloatValue* float_field) { clear_oneof_field(); if (float_field) { if (static_cast< ::google::protobuf::FloatValue*>(float_field)->GetArena() != NULL) { ::google::protobuf::FloatValue* new_float_field = new ::google::protobuf::FloatValue; new_float_field->CopyFrom(*float_field); float_field = new_float_field; } set_has_float_field(); oneof_field_.float_field_ = float_field; } // @@protoc_insertion_point(field_set_allocated:protobuf_unittest.OneofWellKnownTypes.float_field) } // .google.protobuf.Int64Value int64_field = 12; inline bool OneofWellKnownTypes::has_int64_field() const { return oneof_field_case() == kInt64Field; } inline void OneofWellKnownTypes::set_has_int64_field() { _oneof_case_[0] = kInt64Field; } inline void OneofWellKnownTypes::clear_int64_field() { if (has_int64_field()) { delete oneof_field_.int64_field_; clear_has_oneof_field(); } } inline const ::google::protobuf::Int64Value& OneofWellKnownTypes::int64_field() const { // @@protoc_insertion_point(field_get:protobuf_unittest.OneofWellKnownTypes.int64_field) return has_int64_field() ? *oneof_field_.int64_field_ : ::google::protobuf::Int64Value::default_instance(); } inline ::google::protobuf::Int64Value* OneofWellKnownTypes::mutable_int64_field() { if (!has_int64_field()) { clear_oneof_field(); set_has_int64_field(); oneof_field_.int64_field_ = new ::google::protobuf::Int64Value; } // @@protoc_insertion_point(field_mutable:protobuf_unittest.OneofWellKnownTypes.int64_field) return oneof_field_.int64_field_; } inline ::google::protobuf::Int64Value* OneofWellKnownTypes::release_int64_field() { // @@protoc_insertion_point(field_release:protobuf_unittest.OneofWellKnownTypes.int64_field) if (has_int64_field()) { clear_has_oneof_field(); ::google::protobuf::Int64Value* temp = oneof_field_.int64_field_; oneof_field_.int64_field_ = NULL; return temp; } else { return NULL; } } inline void OneofWellKnownTypes::set_allocated_int64_field(::google::protobuf::Int64Value* int64_field) { clear_oneof_field(); if (int64_field) { if (static_cast< ::google::protobuf::Int64Value*>(int64_field)->GetArena() != NULL) { ::google::protobuf::Int64Value* new_int64_field = new ::google::protobuf::Int64Value; new_int64_field->CopyFrom(*int64_field); int64_field = new_int64_field; } set_has_int64_field(); oneof_field_.int64_field_ = int64_field; } // @@protoc_insertion_point(field_set_allocated:protobuf_unittest.OneofWellKnownTypes.int64_field) } // .google.protobuf.UInt64Value uint64_field = 13; inline bool OneofWellKnownTypes::has_uint64_field() const { return oneof_field_case() == kUint64Field; } inline void OneofWellKnownTypes::set_has_uint64_field() { _oneof_case_[0] = kUint64Field; } inline void OneofWellKnownTypes::clear_uint64_field() { if (has_uint64_field()) { delete oneof_field_.uint64_field_; clear_has_oneof_field(); } } inline const ::google::protobuf::UInt64Value& OneofWellKnownTypes::uint64_field() const { // @@protoc_insertion_point(field_get:protobuf_unittest.OneofWellKnownTypes.uint64_field) return has_uint64_field() ? *oneof_field_.uint64_field_ : ::google::protobuf::UInt64Value::default_instance(); } inline ::google::protobuf::UInt64Value* OneofWellKnownTypes::mutable_uint64_field() { if (!has_uint64_field()) { clear_oneof_field(); set_has_uint64_field(); oneof_field_.uint64_field_ = new ::google::protobuf::UInt64Value; } // @@protoc_insertion_point(field_mutable:protobuf_unittest.OneofWellKnownTypes.uint64_field) return oneof_field_.uint64_field_; } inline ::google::protobuf::UInt64Value* OneofWellKnownTypes::release_uint64_field() { // @@protoc_insertion_point(field_release:protobuf_unittest.OneofWellKnownTypes.uint64_field) if (has_uint64_field()) { clear_has_oneof_field(); ::google::protobuf::UInt64Value* temp = oneof_field_.uint64_field_; oneof_field_.uint64_field_ = NULL; return temp; } else { return NULL; } } inline void OneofWellKnownTypes::set_allocated_uint64_field(::google::protobuf::UInt64Value* uint64_field) { clear_oneof_field(); if (uint64_field) { if (static_cast< ::google::protobuf::UInt64Value*>(uint64_field)->GetArena() != NULL) { ::google::protobuf::UInt64Value* new_uint64_field = new ::google::protobuf::UInt64Value; new_uint64_field->CopyFrom(*uint64_field); uint64_field = new_uint64_field; } set_has_uint64_field(); oneof_field_.uint64_field_ = uint64_field; } // @@protoc_insertion_point(field_set_allocated:protobuf_unittest.OneofWellKnownTypes.uint64_field) } // .google.protobuf.Int32Value int32_field = 14; inline bool OneofWellKnownTypes::has_int32_field() const { return oneof_field_case() == kInt32Field; } inline void OneofWellKnownTypes::set_has_int32_field() { _oneof_case_[0] = kInt32Field; } inline void OneofWellKnownTypes::clear_int32_field() { if (has_int32_field()) { delete oneof_field_.int32_field_; clear_has_oneof_field(); } } inline const ::google::protobuf::Int32Value& OneofWellKnownTypes::int32_field() const { // @@protoc_insertion_point(field_get:protobuf_unittest.OneofWellKnownTypes.int32_field) return has_int32_field() ? *oneof_field_.int32_field_ : ::google::protobuf::Int32Value::default_instance(); } inline ::google::protobuf::Int32Value* OneofWellKnownTypes::mutable_int32_field() { if (!has_int32_field()) { clear_oneof_field(); set_has_int32_field(); oneof_field_.int32_field_ = new ::google::protobuf::Int32Value; } // @@protoc_insertion_point(field_mutable:protobuf_unittest.OneofWellKnownTypes.int32_field) return oneof_field_.int32_field_; } inline ::google::protobuf::Int32Value* OneofWellKnownTypes::release_int32_field() { // @@protoc_insertion_point(field_release:protobuf_unittest.OneofWellKnownTypes.int32_field) if (has_int32_field()) { clear_has_oneof_field(); ::google::protobuf::Int32Value* temp = oneof_field_.int32_field_; oneof_field_.int32_field_ = NULL; return temp; } else { return NULL; } } inline void OneofWellKnownTypes::set_allocated_int32_field(::google::protobuf::Int32Value* int32_field) { clear_oneof_field(); if (int32_field) { if (static_cast< ::google::protobuf::Int32Value*>(int32_field)->GetArena() != NULL) { ::google::protobuf::Int32Value* new_int32_field = new ::google::protobuf::Int32Value; new_int32_field->CopyFrom(*int32_field); int32_field = new_int32_field; } set_has_int32_field(); oneof_field_.int32_field_ = int32_field; } // @@protoc_insertion_point(field_set_allocated:protobuf_unittest.OneofWellKnownTypes.int32_field) } // .google.protobuf.UInt32Value uint32_field = 15; inline bool OneofWellKnownTypes::has_uint32_field() const { return oneof_field_case() == kUint32Field; } inline void OneofWellKnownTypes::set_has_uint32_field() { _oneof_case_[0] = kUint32Field; } inline void OneofWellKnownTypes::clear_uint32_field() { if (has_uint32_field()) { delete oneof_field_.uint32_field_; clear_has_oneof_field(); } } inline const ::google::protobuf::UInt32Value& OneofWellKnownTypes::uint32_field() const { // @@protoc_insertion_point(field_get:protobuf_unittest.OneofWellKnownTypes.uint32_field) return has_uint32_field() ? *oneof_field_.uint32_field_ : ::google::protobuf::UInt32Value::default_instance(); } inline ::google::protobuf::UInt32Value* OneofWellKnownTypes::mutable_uint32_field() { if (!has_uint32_field()) { clear_oneof_field(); set_has_uint32_field(); oneof_field_.uint32_field_ = new ::google::protobuf::UInt32Value; } // @@protoc_insertion_point(field_mutable:protobuf_unittest.OneofWellKnownTypes.uint32_field) return oneof_field_.uint32_field_; } inline ::google::protobuf::UInt32Value* OneofWellKnownTypes::release_uint32_field() { // @@protoc_insertion_point(field_release:protobuf_unittest.OneofWellKnownTypes.uint32_field) if (has_uint32_field()) { clear_has_oneof_field(); ::google::protobuf::UInt32Value* temp = oneof_field_.uint32_field_; oneof_field_.uint32_field_ = NULL; return temp; } else { return NULL; } } inline void OneofWellKnownTypes::set_allocated_uint32_field(::google::protobuf::UInt32Value* uint32_field) { clear_oneof_field(); if (uint32_field) { if (static_cast< ::google::protobuf::UInt32Value*>(uint32_field)->GetArena() != NULL) { ::google::protobuf::UInt32Value* new_uint32_field = new ::google::protobuf::UInt32Value; new_uint32_field->CopyFrom(*uint32_field); uint32_field = new_uint32_field; } set_has_uint32_field(); oneof_field_.uint32_field_ = uint32_field; } // @@protoc_insertion_point(field_set_allocated:protobuf_unittest.OneofWellKnownTypes.uint32_field) } // .google.protobuf.BoolValue bool_field = 16; inline bool OneofWellKnownTypes::has_bool_field() const { return oneof_field_case() == kBoolField; } inline void OneofWellKnownTypes::set_has_bool_field() { _oneof_case_[0] = kBoolField; } inline void OneofWellKnownTypes::clear_bool_field() { if (has_bool_field()) { delete oneof_field_.bool_field_; clear_has_oneof_field(); } } inline const ::google::protobuf::BoolValue& OneofWellKnownTypes::bool_field() const { // @@protoc_insertion_point(field_get:protobuf_unittest.OneofWellKnownTypes.bool_field) return has_bool_field() ? *oneof_field_.bool_field_ : ::google::protobuf::BoolValue::default_instance(); } inline ::google::protobuf::BoolValue* OneofWellKnownTypes::mutable_bool_field() { if (!has_bool_field()) { clear_oneof_field(); set_has_bool_field(); oneof_field_.bool_field_ = new ::google::protobuf::BoolValue; } // @@protoc_insertion_point(field_mutable:protobuf_unittest.OneofWellKnownTypes.bool_field) return oneof_field_.bool_field_; } inline ::google::protobuf::BoolValue* OneofWellKnownTypes::release_bool_field() { // @@protoc_insertion_point(field_release:protobuf_unittest.OneofWellKnownTypes.bool_field) if (has_bool_field()) { clear_has_oneof_field(); ::google::protobuf::BoolValue* temp = oneof_field_.bool_field_; oneof_field_.bool_field_ = NULL; return temp; } else { return NULL; } } inline void OneofWellKnownTypes::set_allocated_bool_field(::google::protobuf::BoolValue* bool_field) { clear_oneof_field(); if (bool_field) { if (static_cast< ::google::protobuf::BoolValue*>(bool_field)->GetArena() != NULL) { ::google::protobuf::BoolValue* new_bool_field = new ::google::protobuf::BoolValue; new_bool_field->CopyFrom(*bool_field); bool_field = new_bool_field; } set_has_bool_field(); oneof_field_.bool_field_ = bool_field; } // @@protoc_insertion_point(field_set_allocated:protobuf_unittest.OneofWellKnownTypes.bool_field) } // .google.protobuf.StringValue string_field = 17; inline bool OneofWellKnownTypes::has_string_field() const { return oneof_field_case() == kStringField; } inline void OneofWellKnownTypes::set_has_string_field() { _oneof_case_[0] = kStringField; } inline void OneofWellKnownTypes::clear_string_field() { if (has_string_field()) { delete oneof_field_.string_field_; clear_has_oneof_field(); } } inline const ::google::protobuf::StringValue& OneofWellKnownTypes::string_field() const { // @@protoc_insertion_point(field_get:protobuf_unittest.OneofWellKnownTypes.string_field) return has_string_field() ? *oneof_field_.string_field_ : ::google::protobuf::StringValue::default_instance(); } inline ::google::protobuf::StringValue* OneofWellKnownTypes::mutable_string_field() { if (!has_string_field()) { clear_oneof_field(); set_has_string_field(); oneof_field_.string_field_ = new ::google::protobuf::StringValue; } // @@protoc_insertion_point(field_mutable:protobuf_unittest.OneofWellKnownTypes.string_field) return oneof_field_.string_field_; } inline ::google::protobuf::StringValue* OneofWellKnownTypes::release_string_field() { // @@protoc_insertion_point(field_release:protobuf_unittest.OneofWellKnownTypes.string_field) if (has_string_field()) { clear_has_oneof_field(); ::google::protobuf::StringValue* temp = oneof_field_.string_field_; oneof_field_.string_field_ = NULL; return temp; } else { return NULL; } } inline void OneofWellKnownTypes::set_allocated_string_field(::google::protobuf::StringValue* string_field) { clear_oneof_field(); if (string_field) { if (static_cast< ::google::protobuf::StringValue*>(string_field)->GetArena() != NULL) { ::google::protobuf::StringValue* new_string_field = new ::google::protobuf::StringValue; new_string_field->CopyFrom(*string_field); string_field = new_string_field; } set_has_string_field(); oneof_field_.string_field_ = string_field; } // @@protoc_insertion_point(field_set_allocated:protobuf_unittest.OneofWellKnownTypes.string_field) } // .google.protobuf.BytesValue bytes_field = 18; inline bool OneofWellKnownTypes::has_bytes_field() const { return oneof_field_case() == kBytesField; } inline void OneofWellKnownTypes::set_has_bytes_field() { _oneof_case_[0] = kBytesField; } inline void OneofWellKnownTypes::clear_bytes_field() { if (has_bytes_field()) { delete oneof_field_.bytes_field_; clear_has_oneof_field(); } } inline const ::google::protobuf::BytesValue& OneofWellKnownTypes::bytes_field() const { // @@protoc_insertion_point(field_get:protobuf_unittest.OneofWellKnownTypes.bytes_field) return has_bytes_field() ? *oneof_field_.bytes_field_ : ::google::protobuf::BytesValue::default_instance(); } inline ::google::protobuf::BytesValue* OneofWellKnownTypes::mutable_bytes_field() { if (!has_bytes_field()) { clear_oneof_field(); set_has_bytes_field(); oneof_field_.bytes_field_ = new ::google::protobuf::BytesValue; } // @@protoc_insertion_point(field_mutable:protobuf_unittest.OneofWellKnownTypes.bytes_field) return oneof_field_.bytes_field_; } inline ::google::protobuf::BytesValue* OneofWellKnownTypes::release_bytes_field() { // @@protoc_insertion_point(field_release:protobuf_unittest.OneofWellKnownTypes.bytes_field) if (has_bytes_field()) { clear_has_oneof_field(); ::google::protobuf::BytesValue* temp = oneof_field_.bytes_field_; oneof_field_.bytes_field_ = NULL; return temp; } else { return NULL; } } inline void OneofWellKnownTypes::set_allocated_bytes_field(::google::protobuf::BytesValue* bytes_field) { clear_oneof_field(); if (bytes_field) { if (static_cast< ::google::protobuf::BytesValue*>(bytes_field)->GetArena() != NULL) { ::google::protobuf::BytesValue* new_bytes_field = new ::google::protobuf::BytesValue; new_bytes_field->CopyFrom(*bytes_field); bytes_field = new_bytes_field; } set_has_bytes_field(); oneof_field_.bytes_field_ = bytes_field; } // @@protoc_insertion_point(field_set_allocated:protobuf_unittest.OneofWellKnownTypes.bytes_field) } inline bool OneofWellKnownTypes::has_oneof_field() const { return oneof_field_case() != ONEOF_FIELD_NOT_SET; } inline void OneofWellKnownTypes::clear_has_oneof_field() { _oneof_case_[0] = ONEOF_FIELD_NOT_SET; } inline OneofWellKnownTypes::OneofFieldCase OneofWellKnownTypes::oneof_field_case() const { return OneofWellKnownTypes::OneofFieldCase(_oneof_case_[0]); } // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // MapWellKnownTypes // map<int32, .google.protobuf.Any> any_field = 1; inline int MapWellKnownTypes::any_field_size() const { return any_field_.size(); } inline void MapWellKnownTypes::clear_any_field() { any_field_.Clear(); } inline const ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::Any >& MapWellKnownTypes::any_field() const { // @@protoc_insertion_point(field_map:protobuf_unittest.MapWellKnownTypes.any_field) return any_field_.GetMap(); } inline ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::Any >* MapWellKnownTypes::mutable_any_field() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.MapWellKnownTypes.any_field) return any_field_.MutableMap(); } // map<int32, .google.protobuf.Api> api_field = 2; inline int MapWellKnownTypes::api_field_size() const { return api_field_.size(); } inline void MapWellKnownTypes::clear_api_field() { api_field_.Clear(); } inline const ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::Api >& MapWellKnownTypes::api_field() const { // @@protoc_insertion_point(field_map:protobuf_unittest.MapWellKnownTypes.api_field) return api_field_.GetMap(); } inline ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::Api >* MapWellKnownTypes::mutable_api_field() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.MapWellKnownTypes.api_field) return api_field_.MutableMap(); } // map<int32, .google.protobuf.Duration> duration_field = 3; inline int MapWellKnownTypes::duration_field_size() const { return duration_field_.size(); } inline void MapWellKnownTypes::clear_duration_field() { duration_field_.Clear(); } inline const ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::Duration >& MapWellKnownTypes::duration_field() const { // @@protoc_insertion_point(field_map:protobuf_unittest.MapWellKnownTypes.duration_field) return duration_field_.GetMap(); } inline ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::Duration >* MapWellKnownTypes::mutable_duration_field() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.MapWellKnownTypes.duration_field) return duration_field_.MutableMap(); } // map<int32, .google.protobuf.Empty> empty_field = 4; inline int MapWellKnownTypes::empty_field_size() const { return empty_field_.size(); } inline void MapWellKnownTypes::clear_empty_field() { empty_field_.Clear(); } inline const ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::Empty >& MapWellKnownTypes::empty_field() const { // @@protoc_insertion_point(field_map:protobuf_unittest.MapWellKnownTypes.empty_field) return empty_field_.GetMap(); } inline ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::Empty >* MapWellKnownTypes::mutable_empty_field() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.MapWellKnownTypes.empty_field) return empty_field_.MutableMap(); } // map<int32, .google.protobuf.FieldMask> field_mask_field = 5; inline int MapWellKnownTypes::field_mask_field_size() const { return field_mask_field_.size(); } inline void MapWellKnownTypes::clear_field_mask_field() { field_mask_field_.Clear(); } inline const ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::FieldMask >& MapWellKnownTypes::field_mask_field() const { // @@protoc_insertion_point(field_map:protobuf_unittest.MapWellKnownTypes.field_mask_field) return field_mask_field_.GetMap(); } inline ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::FieldMask >* MapWellKnownTypes::mutable_field_mask_field() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.MapWellKnownTypes.field_mask_field) return field_mask_field_.MutableMap(); } // map<int32, .google.protobuf.SourceContext> source_context_field = 6; inline int MapWellKnownTypes::source_context_field_size() const { return source_context_field_.size(); } inline void MapWellKnownTypes::clear_source_context_field() { source_context_field_.Clear(); } inline const ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::SourceContext >& MapWellKnownTypes::source_context_field() const { // @@protoc_insertion_point(field_map:protobuf_unittest.MapWellKnownTypes.source_context_field) return source_context_field_.GetMap(); } inline ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::SourceContext >* MapWellKnownTypes::mutable_source_context_field() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.MapWellKnownTypes.source_context_field) return source_context_field_.MutableMap(); } // map<int32, .google.protobuf.Struct> struct_field = 7; inline int MapWellKnownTypes::struct_field_size() const { return struct_field_.size(); } inline void MapWellKnownTypes::clear_struct_field() { struct_field_.Clear(); } inline const ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::Struct >& MapWellKnownTypes::struct_field() const { // @@protoc_insertion_point(field_map:protobuf_unittest.MapWellKnownTypes.struct_field) return struct_field_.GetMap(); } inline ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::Struct >* MapWellKnownTypes::mutable_struct_field() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.MapWellKnownTypes.struct_field) return struct_field_.MutableMap(); } // map<int32, .google.protobuf.Timestamp> timestamp_field = 8; inline int MapWellKnownTypes::timestamp_field_size() const { return timestamp_field_.size(); } inline void MapWellKnownTypes::clear_timestamp_field() { timestamp_field_.Clear(); } inline const ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::Timestamp >& MapWellKnownTypes::timestamp_field() const { // @@protoc_insertion_point(field_map:protobuf_unittest.MapWellKnownTypes.timestamp_field) return timestamp_field_.GetMap(); } inline ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::Timestamp >* MapWellKnownTypes::mutable_timestamp_field() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.MapWellKnownTypes.timestamp_field) return timestamp_field_.MutableMap(); } // map<int32, .google.protobuf.Type> type_field = 9; inline int MapWellKnownTypes::type_field_size() const { return type_field_.size(); } inline void MapWellKnownTypes::clear_type_field() { type_field_.Clear(); } inline const ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::Type >& MapWellKnownTypes::type_field() const { // @@protoc_insertion_point(field_map:protobuf_unittest.MapWellKnownTypes.type_field) return type_field_.GetMap(); } inline ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::Type >* MapWellKnownTypes::mutable_type_field() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.MapWellKnownTypes.type_field) return type_field_.MutableMap(); } // map<int32, .google.protobuf.DoubleValue> double_field = 10; inline int MapWellKnownTypes::double_field_size() const { return double_field_.size(); } inline void MapWellKnownTypes::clear_double_field() { double_field_.Clear(); } inline const ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::DoubleValue >& MapWellKnownTypes::double_field() const { // @@protoc_insertion_point(field_map:protobuf_unittest.MapWellKnownTypes.double_field) return double_field_.GetMap(); } inline ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::DoubleValue >* MapWellKnownTypes::mutable_double_field() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.MapWellKnownTypes.double_field) return double_field_.MutableMap(); } // map<int32, .google.protobuf.FloatValue> float_field = 11; inline int MapWellKnownTypes::float_field_size() const { return float_field_.size(); } inline void MapWellKnownTypes::clear_float_field() { float_field_.Clear(); } inline const ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::FloatValue >& MapWellKnownTypes::float_field() const { // @@protoc_insertion_point(field_map:protobuf_unittest.MapWellKnownTypes.float_field) return float_field_.GetMap(); } inline ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::FloatValue >* MapWellKnownTypes::mutable_float_field() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.MapWellKnownTypes.float_field) return float_field_.MutableMap(); } // map<int32, .google.protobuf.Int64Value> int64_field = 12; inline int MapWellKnownTypes::int64_field_size() const { return int64_field_.size(); } inline void MapWellKnownTypes::clear_int64_field() { int64_field_.Clear(); } inline const ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::Int64Value >& MapWellKnownTypes::int64_field() const { // @@protoc_insertion_point(field_map:protobuf_unittest.MapWellKnownTypes.int64_field) return int64_field_.GetMap(); } inline ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::Int64Value >* MapWellKnownTypes::mutable_int64_field() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.MapWellKnownTypes.int64_field) return int64_field_.MutableMap(); } // map<int32, .google.protobuf.UInt64Value> uint64_field = 13; inline int MapWellKnownTypes::uint64_field_size() const { return uint64_field_.size(); } inline void MapWellKnownTypes::clear_uint64_field() { uint64_field_.Clear(); } inline const ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::UInt64Value >& MapWellKnownTypes::uint64_field() const { // @@protoc_insertion_point(field_map:protobuf_unittest.MapWellKnownTypes.uint64_field) return uint64_field_.GetMap(); } inline ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::UInt64Value >* MapWellKnownTypes::mutable_uint64_field() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.MapWellKnownTypes.uint64_field) return uint64_field_.MutableMap(); } // map<int32, .google.protobuf.Int32Value> int32_field = 14; inline int MapWellKnownTypes::int32_field_size() const { return int32_field_.size(); } inline void MapWellKnownTypes::clear_int32_field() { int32_field_.Clear(); } inline const ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::Int32Value >& MapWellKnownTypes::int32_field() const { // @@protoc_insertion_point(field_map:protobuf_unittest.MapWellKnownTypes.int32_field) return int32_field_.GetMap(); } inline ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::Int32Value >* MapWellKnownTypes::mutable_int32_field() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.MapWellKnownTypes.int32_field) return int32_field_.MutableMap(); } // map<int32, .google.protobuf.UInt32Value> uint32_field = 15; inline int MapWellKnownTypes::uint32_field_size() const { return uint32_field_.size(); } inline void MapWellKnownTypes::clear_uint32_field() { uint32_field_.Clear(); } inline const ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::UInt32Value >& MapWellKnownTypes::uint32_field() const { // @@protoc_insertion_point(field_map:protobuf_unittest.MapWellKnownTypes.uint32_field) return uint32_field_.GetMap(); } inline ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::UInt32Value >* MapWellKnownTypes::mutable_uint32_field() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.MapWellKnownTypes.uint32_field) return uint32_field_.MutableMap(); } // map<int32, .google.protobuf.BoolValue> bool_field = 16; inline int MapWellKnownTypes::bool_field_size() const { return bool_field_.size(); } inline void MapWellKnownTypes::clear_bool_field() { bool_field_.Clear(); } inline const ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::BoolValue >& MapWellKnownTypes::bool_field() const { // @@protoc_insertion_point(field_map:protobuf_unittest.MapWellKnownTypes.bool_field) return bool_field_.GetMap(); } inline ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::BoolValue >* MapWellKnownTypes::mutable_bool_field() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.MapWellKnownTypes.bool_field) return bool_field_.MutableMap(); } // map<int32, .google.protobuf.StringValue> string_field = 17; inline int MapWellKnownTypes::string_field_size() const { return string_field_.size(); } inline void MapWellKnownTypes::clear_string_field() { string_field_.Clear(); } inline const ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::StringValue >& MapWellKnownTypes::string_field() const { // @@protoc_insertion_point(field_map:protobuf_unittest.MapWellKnownTypes.string_field) return string_field_.GetMap(); } inline ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::StringValue >* MapWellKnownTypes::mutable_string_field() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.MapWellKnownTypes.string_field) return string_field_.MutableMap(); } // map<int32, .google.protobuf.BytesValue> bytes_field = 18; inline int MapWellKnownTypes::bytes_field_size() const { return bytes_field_.size(); } inline void MapWellKnownTypes::clear_bytes_field() { bytes_field_.Clear(); } inline const ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::BytesValue >& MapWellKnownTypes::bytes_field() const { // @@protoc_insertion_point(field_map:protobuf_unittest.MapWellKnownTypes.bytes_field) return bytes_field_.GetMap(); } inline ::google::protobuf::Map< ::google::protobuf::int32, ::google::protobuf::BytesValue >* MapWellKnownTypes::mutable_bytes_field() { // @@protoc_insertion_point(field_mutable_map:protobuf_unittest.MapWellKnownTypes.bytes_field) return bytes_field_.MutableMap(); } #endif // !PROTOBUF_INLINE_NOT_IN_HEADERS // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // @@protoc_insertion_point(namespace_scope) } // namespace protobuf_unittest // @@protoc_insertion_point(global_scope) #endif // PROTOBUF_google_2fprotobuf_2funittest_5fwell_5fknown_5ftypes_2eproto__INCLUDED
[ "chrak@com2us.com" ]
chrak@com2us.com
f0853b9cbbafb3ac8f549a7830b9debf1f8dd44b
5e9fb4da7aed28bdb39f95d85bd6f6cb479e0bd2
/63.5/uniform/time
25e209ba4a1862f3c031fa8c852496d44779f585
[]
no_license
wxyhappy0201/pipeflow_snappyHexMesh
fe0d59852370ca5e276258bc9f7b3a21a9ff1a70
1d534dfb274b3a4db4d1ffa2971d34be985b77aa
refs/heads/master
2022-02-08T17:16:47.004690
2019-07-22T21:39:19
2019-07-22T21:39:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
971
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: v1906 | | \\ / A nd | Web: www.OpenFOAM.com | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class dictionary; location "63.5/uniform"; object time; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // value 63.5; name "63.5"; index 113; deltaT 1; deltaT0 1; // ************************************************************************* //
[ "tong011@e.ntu.edu.sg" ]
tong011@e.ntu.edu.sg
723f720dff4905239abc9d46da2a4c826c953c08
f065801a4839ac08672683b692524d9f604b65f3
/modules/ahci/ahci.h
11855688467597e42c2a5924a815014b2f180586
[ "BSD-3-Clause" ]
permissive
PoisonNinja/Pepper
4f48a06a401d6617496c69fe6550ff8e4dded5b3
ee5773006a02ab05459491c62eab0413994cfe80
refs/heads/master
2022-01-14T16:11:28.079999
2021-12-30T03:34:27
2021-12-30T03:34:27
91,926,989
2
1
null
null
null
null
UTF-8
C++
false
false
10,171
h
#pragma once #include <cpu/interrupt.h> #include <fs/block.h> #include <mm/dma.h> #include <types.h> using FIS_TYPE = enum { FIS_TYPE_REG_H2D = 0x27, // Register FIS - host to device FIS_TYPE_REG_D2H = 0x34, // Register FIS - device to host FIS_TYPE_DMA_ACT = 0x39, // DMA activate FIS - device to host FIS_TYPE_DMA_SETUP = 0x41, // DMA setup FIS - bidirectional FIS_TYPE_DATA = 0x46, // Data FIS - bidirectional FIS_TYPE_BIST = 0x58, // BIST activate FIS - bidirectional FIS_TYPE_PIO_SETUP = 0x5F, // PIO setup FIS - device to host FIS_TYPE_DEV_BITS = 0xA1, // Set device bits FIS - device to host }; #define ATA_STATUS_ERR (1 << 0) /* Error. */ #define ATA_STATUS_DRQ (1 << 3) /* Data Request. */ #define ATA_STATUS_DF (1 << 5) /* Device Fault. */ #define ATA_STATUS_DRDY (1 << 6) /* Device Ready. */ #define ATA_STATUS_BSY (1 << 7) /* Busy. */ /** ATA Commands. */ #define ATA_CMD_READ_DMA 0xC8 /**< READ DMA. */ #define ATA_CMD_READ_DMA_EXT 0x25 /**< READ DMA EXT. */ #define ATA_CMD_READ_SECTORS 0x20 /**< READ SECTORS. */ #define ATA_CMD_READ_SECTORS_EXT 0x24 /**< READ SECTORS EXT. */ #define ATA_CMD_WRITE_DMA 0xCA /**< WRITE DMA. */ #define ATA_CMD_WRITE_DMA_EXT 0x35 /**< WRITE DMA EXT. */ #define ATA_CMD_WRITE_SECTORS 0x30 /**< WRITE SECTORS. */ #define ATA_CMD_WRITE_SECTORS_EXT 0x34 /**< WRITE SECTORS EXT. */ #define ATA_CMD_PACKET 0xA0 /**< PACKET. */ #define ATA_CMD_IDENTIFY_PACKET 0xA1 /**< IDENTIFY PACKET DEVICE. */ #define ATA_CMD_FLUSH_CACHE 0xE7 /**< FLUSH CACHE. */ #define ATA_CMD_FLUSH_CACHE_EXT 0xEA /**< FLUSH CACHE EXT. */ #define ATA_CMD_IDENTIFY 0xEC /**< IDENTIFY DEVICE. */ /** Bits in the Port x Interrupt Enable register. */ #define PXIE_DHRE (1 << 0) /**< Device to Host Register Enable. */ #define PXIE_PSE (1 << 1) /**< PIO Setup FIS Enable. */ #define PXIE_DSE (1 << 2) /**< DMA Setup FIS Enable. */ #define PXIE_SDBE (1 << 3) /**< Set Device Bits Enable. */ #define PXIE_UFE (1 << 4) /**< Unknown FIS Enable. */ #define PXIE_DPE (1 << 5) /**< Descriptor Processed Enable. */ #define PXIE_PCE (1 << 6) /**< Port Connect Change Enable. */ #define PXIE_DMPE (1 << 7) /**< Device Mechanical Presence Enable. */ #define PXIE_PRCE (1 << 22) /**< PhyRdy Change Enable. */ #define PXIE_IPME (1 << 23) /**< Incorrect Port Multiplier Enable. */ #define PXIE_OFE (1 << 24) /**< Overflow Enable. */ #define PXIE_INFE (1 << 26) /**< Interface Non-Fatal Error Enable. */ #define PXIE_IFE (1 << 27) /**< Interface Fatal Error Enable. */ #define PXIE_HBDE (1 << 28) /**< Host Bus Data Error Enable. */ #define PXIE_HBFE (1 << 29) /**< Host Bus Fatal Error Enable. */ #define PXIE_TFEE (1 << 30) /**< Task File Error Enable. */ #define PXIE_CPDE (1 << 31) /**< Cold Port Detect Enable. */ #define PORT_INTR_ERROR \ (PXIE_UFE | PXIE_PCE | PXIE_PRCE | PXIE_IPME | PXIE_OFE | PXIE_INFE | \ PXIE_IFE | PXIE_HBDE | PXIE_HBFE | PXIE_TFEE) constexpr uint32_t PXCMD_ST = 1 << 0; /* 0x00000001 */ constexpr uint32_t PXCMD_SUD = 1 << 1; /* 0x00000002 */ constexpr uint32_t PXCMD_POD = 1 << 2; /* 0x00000004 */ constexpr uint32_t PXCMD_CLO = 1 << 3; /* 0x00000008 */ constexpr uint32_t PXCMD_FRE = 1 << 4; /* 0x00000010 */ constexpr uint32_t PXCMD_CSS(uint32_t val) { return (val >> 8) % 32; } constexpr uint32_t PXCMD_MPSS = 1 << 13; /* 0x00002000 */ constexpr uint32_t PXCMD_FR = 1 << 14; /* 0x00004000 */ constexpr uint32_t PXCMD_CR = 1 << 15; /* 0x00008000 */ constexpr uint32_t PXCMD_CPS = 1 << 16; /* 0x00010000 */ constexpr uint32_t PXCMD_PMA = 1 << 17; /* 0x00020000 */ constexpr uint32_t PXCMD_HPCP = 1 << 18; /* 0x00040000 */ constexpr uint32_t PXCMD_MPSP = 1 << 19; /* 0x00080000 */ constexpr uint32_t PXCMD_CPD = 1 << 20; /* 0x00100000 */ constexpr uint32_t PXCMD_ESP = 1 << 21; /* 0x00200000 */ constexpr uint32_t PXCMD_FBSCP = 1 << 22; /* 0x00400000 */ constexpr uint32_t PXCMD_APSTE = 1 << 23; /* 0x00800000 */ constexpr uint32_t PXCMD_ATAPI = 1 << 24; /* 0x01000000 */ constexpr uint32_t PXCMD_DLAE = 1 << 25; /* 0x02000000 */ constexpr uint32_t PXCMD_ALPE = 1 << 26; /* 0x04000000 */ constexpr uint32_t PXCMD_ASP = 1 << 27; /* 0x08000000 */ constexpr uint32_t PXCMD_ICC(uint32_t val) { return (val >> 28) % 16; } #define AHCI_TYPE_NULL 0x0 #define AHCI_TYPE_SATA 0x00000101 #define AHCI_TYPE_ATAPI 0xEB140101 #define AHCI_TYPE_SEMB 0xC33C0101 #define AHCI_TYPE_PM 0x96690101 #define AHCI_PRDT_MAX_MEMORY 0x1000 #define AHCI_BLOCK_SIZE 512 struct hba_port { uint32_t command_list_base_low; uint32_t command_list_base_high; uint32_t fis_base_low; uint32_t fis_base_high; uint32_t interrupt_status; uint32_t interrupt_enable; uint32_t command; uint32_t reserved_0; uint32_t task_file_data; uint32_t signature; uint32_t sata_status; uint32_t sata_control; uint32_t sata_error; uint32_t sata_active; uint32_t command_issue; uint32_t sata_notification; uint32_t fis_based_switch_control; uint32_t reserved_1[11]; uint32_t vendor[4]; } __attribute__((packed)); constexpr uint32_t GHC_AE = 1U << 31; constexpr uint32_t GHC_MRSM = 1U << 2; constexpr uint32_t GHC_IE = 1U << 1; constexpr uint32_t GHC_HR = 1U << 0; constexpr uint32_t CAP_S64A = 1U << 31; constexpr uint32_t capability_ncs(uint32_t capability) { return (capability & 0x1F00) >> 8; } struct hba_memory { uint32_t capability; uint32_t global_host_control; uint32_t interrupt_status; uint32_t port_implemented; uint32_t version; uint32_t ccc_control; uint32_t ccc_ports; uint32_t em_location; uint32_t em_control; uint32_t ext_capabilities; uint32_t bohc; uint8_t reserved[0xA0 - 0x2C]; uint8_t vendor[0x100 - 0xA0]; struct hba_port ports[32]; } __attribute__((packed)); struct hba_received_fis { uint8_t fis_ds[0x1C]; uint8_t pad_0[0x4]; uint8_t fis_ps[0x14]; uint8_t pad_1[0xC]; uint8_t fis_r[0x14]; uint8_t pad_2[0x4]; uint8_t fis_sdb[0x8]; uint8_t ufis[0x40]; uint8_t reserved[0x60]; } __attribute__((packed)); struct hba_command_header { uint8_t fis_length : 5; uint8_t atapi : 1; uint8_t write : 1; uint8_t prefetchable : 1; uint8_t reset : 1; uint8_t bist : 1; uint8_t clear_busy_upon_r_ok : 1; uint8_t reserved_0 : 1; uint8_t pmport : 4; uint16_t prdt_len; uint32_t prdb_count; uint32_t command_table_base_low; uint32_t command_table_base_high; uint32_t reserved_1[4]; } __attribute__((packed)); struct hba_prdt_entry { uint32_t data_base_low; uint32_t data_base_high; uint32_t reserved_0; uint32_t byte_count : 22; uint32_t reserved_1 : 9; uint32_t interrupt_on_complete : 1; } __attribute__((packed)); struct fis_h2d { uint8_t type; uint8_t pmport : 4; uint8_t reserved_0 : 3; uint8_t c : 1; uint8_t command; uint8_t feature_low; uint8_t lba0; uint8_t lba1; uint8_t lba2; uint8_t device; uint8_t lba3; uint8_t lba4; uint8_t lba5; uint8_t feature_high; uint8_t count_low; uint8_t count_high; uint8_t icc; uint8_t control; uint8_t reserved_1[0x4]; } __attribute__((packed)); struct hba_command_table { uint8_t command_fis[0x40]; uint8_t acmd[0x10]; uint8_t reserved[0x30]; struct hba_prdt_entry prdt[1]; } __attribute__((packed)); /* * ATA identify response data, per the ATA spec at * http://www.t13.org/Documents/UploadedDocuments/docs2009/d2015r1a-ATAATAPI_Command_Set_-_2_ACS-2.pdf * * TODO: Move this to generic ATA header */ enum class ahci_identify { ATA_GENERAL_CONFIGURATION = 0, ATA_SPECIFIC_CONFIGURATION = 2, ATA_SERIAL_NUMBER = 10, ATA_FIRMWARE_REVISION = 23, ATA_MODEL_NUMBER = 27, ATA_TRUSTED_COMPUTING = 48, ATA_CAPABILITY = 49, ATA_FIELD_VALID = 53, ATA_MULTIPLE_SECTOR = 59, ATA_LBA28_CAPACITY = 60, ATA_MULTIWORD_MODES = 63, ATA_PIO_MODES = 64, ATA_MAJOR_VERSION = 80, ATA_MINOR_VERSION = 81, ATA_COMMANDSET_1 = 82, ATA_COMMANDSET_2 = 83, ATA_COMMANDSET_EXTENDED = 84, ATA_CFS_ENABLE_1 = 85, ATA_CFS_ENABLE_2 = 86, ATA_CFS_DEFAULT = 87, ATA_UDMA_MODES = 88, ATA_HW_RESET = 93, ATA_ACOUSTIC = 94, ATA_LBA48_CAPACITY = 100, ATA_REMOVABLE = 127, ATA_SECURITY_STATUS = 128, ATA_CFA_POWER_MODE = 160, ATA_MEDIA_SERIAL_NUMBER = 176, ATA_INTEGRITY = 255, }; namespace pci { class device; } // namespace pci class ahci_controller; class ahci_port : public filesystem::block_device { public: ahci_port(ahci_controller* c, volatile struct hba_port* port); virtual ~ahci_port() override; virtual bool request(filesystem::block_request* request) override; virtual filesystem::sector_t sector_size() override; virtual size_t sg_max_size() override; virtual size_t sg_max_count() override; void handle(); private: int get_free_slot(); bool send_command(uint8_t command, size_t num_blocks, uint8_t write, uint64_t lba, libcxx::unique_ptr<memory::dma::sglist>& sglist); ahci_controller* controller; uint16_t* identify; volatile struct hba_port* port; memory::dma::region command_tables[32]; memory::dma::region fb; memory::dma::region clb; // Precache some geometry stuff to save lookups bool is_lba48; }; class ahci_controller { public: ahci_controller(pci::device* d, dev_t major); void init(); size_t get_ncs(); bool is_64bit(); private: void handler(int, void* data, struct interrupt_context* /* ctx */); dev_t major; ahci_port* ports[32]; volatile struct hba_memory* hba; pci::device* device; interrupt::handler handler_data; };
[ "syscallrax@gmail.com" ]
syscallrax@gmail.com
f52f4957cce501086d0456cbd649fa19909bd5bc
c6b483cc2d7bc9eb6dc5c08ae92aa55ff9b3a994
/examples/adaptor/RawMap.cpp
74ac91e11f72383e5d23dc589d2af8fdb3b84111
[ "Apache-2.0" ]
permissive
oguzdemir/hazelcast-cpp-client
ebffc7137a3a14b9fc5d96e1a1b0eac8aac1e60f
95c4687634a8ac4886d0a9b9b4c17622225261f0
refs/heads/master
2021-01-21T02:53:05.197319
2016-08-24T21:08:14
2016-08-24T21:08:14
63,674,978
0
0
null
2016-07-19T08:16:24
2016-07-19T08:16:23
null
UTF-8
C++
false
false
4,278
cpp
/* * Copyright (c) 2008-2015, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // // Created by İhsan Demir on 21/12/15. // #include <hazelcast/client/HazelcastClient.h> #include <hazelcast/client/adaptor/RawPointerMap.h> #include <hazelcast/client/query/GreaterLessPredicate.h> #include <hazelcast/client/query/QueryConstants.h> class MyEntryListener : public hazelcast::client::EntryListener<std::string, std::string> { public: void entryAdded(const hazelcast::client::EntryEvent<std::string, std::string> &event) { std::cout << "[entryAdded] " << event << std::endl; } void entryRemoved(const hazelcast::client::EntryEvent<std::string, std::string> &event) { std::cout << "[entryRemoved] " << event << std::endl; } void entryUpdated(const hazelcast::client::EntryEvent<std::string, std::string> &event) { std::cout << "[entryAdded] " << event << std::endl; } void entryEvicted(const hazelcast::client::EntryEvent<std::string, std::string> &event) { std::cout << "[entryUpdated] " << event << std::endl; } void entryExpired(const hazelcast::client::EntryEvent<std::string, std::string> &event) { std::cout << "[entryExpired] " << event << std::endl; } void entryMerged(const hazelcast::client::EntryEvent<std::string, std::string> &event) { std::cout << "[entryMerged] " << event << std::endl; } void mapEvicted(const hazelcast::client::MapEvent &event) { std::cout << "[mapEvicted] " << event << std::endl; } void mapCleared(const hazelcast::client::MapEvent &event) { std::cout << "[mapCleared] " << event << std::endl; } }; int main() { hazelcast::client::ClientConfig config; hazelcast::client::HazelcastClient hz(config); hazelcast::client::IMap<std::string, std::string> m = hz.getMap<std::string, std::string>("map"); hazelcast::client::adaptor::RawPointerMap<std::string, std::string> map(m); map.put("1", "Tokyo"); map.put("2", "Paris"); map.put("3", "New York"); std::cout << "Finished loading map" << std::endl; std::auto_ptr<hazelcast::client::DataArray<std::string> > vals = map.values(); std::auto_ptr<hazelcast::client::EntryArray<std::string, std::string> > entries = map.entrySet(); std::cout << "There are " << vals->size() << " values in the map" << std::endl; std::cout << "There are " << entries->size() << " entries in the map" << std::endl; for (size_t i = 0; i < entries->size(); ++i) { const std::string * key = entries->getKey(i); if ((std::string *) NULL == key) { std::cout << "The key at index " << i << " is NULL" << std::endl; } else { std::auto_ptr<std::string> val = entries->releaseValue(i); std::cout << "(Key, Value) for index " << i << " is: (" << *key << ", " << (val.get() == NULL ? "NULL" : *val) << ")" << std::endl; } } MyEntryListener listener; std::string listenerId = map.addEntryListener(listener, true); std::cout << "EntryListener registered" << std::endl; // wait for modifymap executable to run hazelcast::util::sleep(10); map.removeEntryListener(listenerId); // Continuous Query example // Register listener with predicate // Only listen events for entries with key >= 7 listenerId = map.addEntryListener(listener, hazelcast::client::query::GreaterLessPredicate<int>( hazelcast::client::query::QueryConstants::getKeyAttributeName(), 7, true, false), true); // wait for modifymap executable to run hazelcast::util::sleep(10); map.removeEntryListener(listenerId); std::cout << "Finished" << std::endl; return 0; }
[ "ihsan@hazelcast.com" ]
ihsan@hazelcast.com
d1e1e82c5c4258525bb75bc4beed0baa1606669c
b9d335b40359423a868f36bb50533e355f409b38
/Course C++ workshop/HW/part _2/Afeka/part _2/Airline/Airline/main.cpp
ab2afc829ef4492a83db4bb7a09d389eb437449b
[]
no_license
YigalOrn/Afeka
58c8426af091ab854f041781b301c146623f7641
cdf47b5a1241af8e00a1fe9e4912e6617e3fff6b
refs/heads/master
2020-03-14T06:17:22.846129
2019-02-07T10:11:34
2019-02-07T10:11:34
131,480,781
0
0
null
null
null
null
UTF-8
C++
false
false
3,922
cpp
#include "Airline.h" #include <iostream> using namespace std; void main() { //Create Airline Airline airline("EL-AL"); //Create Planes Plane p1(50), p2, p3(200); airline.addPlane(p1); airline.addPlane(p2); airline.addPlane(p3); //Create Staff Members Pilot** pilots = new Pilot*[3]; Attendant** attendants = new Attendant*[3]; pilots[0] = new Pilot(Person("Ross", 32), 5, 35000, 2); pilots[1] = new Pilot(Person("Joey", 41), 11, 42000, 3); pilots[2] = new Pilot(Person("Chandler", 55), 25, 70000, 5); attendants[0] = new Attendant(Person("Phoebe", 20), 1, 5000); attendants[1] = new Attendant(Person("Rachel", 22), 2, 5750); attendants[2] = new Attendant(Person("Monica", 28), 3, 7000); for (int i = 0; i < 3; i++) airline.addCrewMember(*pilots[i]); for (int i = 0; i < 3; i++) airline.addCrewMember(*attendants[i]); //Create Flights Flight f1(&p1, Date(1, 2, 2015), "London", pilots[0]); Flight f2(&p2, Date(11, 12, 2015), "Tomsk", pilots[1]); Flight f3(&p1, Date(4, 9, 2015), "Rome", pilots[2]); Flight f4(&p3, Date(1, 2, 2015), "Tel-Aviv", pilots[0]); airline.addFlight(f1); airline.addFlight(f2); airline.addFlight(f3); airline.addFlight(f4); //add crew members airline.addStaffMemberToFlight(*attendants[1], f1); airline.addStaffMemberToFlight(*attendants[0], f1); airline.addStaffMemberToFlight(*pilots[1], f1); airline.addStaffMemberToFlight(*attendants[1], f2); airline.addStaffMemberToFlight(*attendants[2], f2); airline.addStaffMemberToFlight(*attendants[0], f3); airline.addStaffMemberToFlight(*pilots[1], f3); airline.addStaffMemberToFlight(*pilots[2], f4); //remove crew members airline.removeStaffMemberFromFlight(*attendants[0], f1); airline.removeStaffMemberFromFlight(*attendants[0], f2); // should not work airline.removeStaffMemberFromFlight(*attendants[0], f3); //Create Customers Customer** customers = new Customer*[3]; customers[0] = new Customer(Person("Koko", 37)); customers[1] = new Customer(Person("Momo", 21)); customers[2] = new Customer(Person("Gogo", 45)); for (int i = 0; i < 3; i++) { airline.addCustomer(*customers[i]); } //Create Orders Order o1(Date(1, 1, 2015), customers[0]); o1 += airline.createTicketForFlight(f1); o1 += airline.createTicketForFlight(f1); o1 += airline.createTicketForFlight(f2); Order o2(Date(2, 1, 2015), customers[1]); o2 += airline.createTicketForFlight(f2); o2 += airline.createTicketForFlight(f3); Order o3(Date(11, 5, 2015), customers[2]); o3 += airline.createTicketForFlight(f2); o3 += airline.createTicketForFlight(f3); o3 += airline.createTicketForFlight(f4); Order o4(Date(5, 2, 2015), customers[2]); o4 += airline.createTicketForFlight(f2); // operator += o4 += airline.createTicketForFlight(f3); airline.addOrder(o1); airline.addOrder(o2); airline.addOrder(o3); //remove some tickets o3 -= *(o3.getTickets()[2]); // operator -= o1 -= *(o1.getTickets()[1]); //Cancel an order airline.cancelOrder(o4); cout << airline << endl; //Free the allocations for (int i = 0; i < 3; i++) delete pilots[i]; delete[]pilots; for (int i = 0; i < 3; i++) delete attendants[i]; delete[]attendants; for (int i = 0; i < 3; i++) delete customers[i]; delete[] customers; // Try some operators //operators +, () Date d(1, 1, 2015); cout << d << endl; d = d + 5; cout << d << endl; d = 2 + d; cout << d << endl; d(2, 2, 2016);//operator() cout << d << endl; // operator [] cout << "Find employee by name.. Enter a name : " << endl; char name[100]; cin.getline(name, 100); int size = airline.getFlightsAmount(); Flight*const* flights = airline.getFlights(); int flag = 0; for (int i = 0; i < size; i++) { const AirCrew* const ac = (*flights[i])[name]; if (ac != NULL) { flag = 1; cout << ac << endl; } }//for if (!flag) { cout << "Did not found any staff member by the name " << name << endl; } }//main
[ "yigalorn@gmail.com" ]
yigalorn@gmail.com
11f109901d9356efe211c6a7f2e9aa3b5241b213
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/curl/gumtree/curl_repos_function_1253_curl-7.35.0.cpp
28ffb7ead0f465ad2cb5c31abb1e6c50a44fdc92
[]
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
55,136
cpp
CURLcode Curl_setopt(struct SessionHandle *data, CURLoption option, va_list param) { char *argptr; CURLcode result = CURLE_OK; long arg; #ifndef CURL_DISABLE_HTTP curl_off_t bigsize; #endif switch(option) { case CURLOPT_DNS_CACHE_TIMEOUT: data->set.dns_cache_timeout = va_arg(param, long); break; case CURLOPT_DNS_USE_GLOBAL_CACHE: /* remember we want this enabled */ arg = va_arg(param, long); data->set.global_dns_cache = (0 != arg)?TRUE:FALSE; break; case CURLOPT_SSL_CIPHER_LIST: /* set a list of cipher we want to use in the SSL connection */ result = setstropt(&data->set.str[STRING_SSL_CIPHER_LIST], va_arg(param, char *)); break; case CURLOPT_RANDOM_FILE: /* * This is the path name to a file that contains random data to seed * the random SSL stuff with. The file is only used for reading. */ result = setstropt(&data->set.str[STRING_SSL_RANDOM_FILE], va_arg(param, char *)); break; case CURLOPT_EGDSOCKET: /* * The Entropy Gathering Daemon socket pathname */ result = setstropt(&data->set.str[STRING_SSL_EGDSOCKET], va_arg(param, char *)); break; case CURLOPT_MAXCONNECTS: /* * Set the absolute number of maximum simultaneous alive connection that * libcurl is allowed to have. */ data->set.maxconnects = va_arg(param, long); break; case CURLOPT_FORBID_REUSE: /* * When this transfer is done, it must not be left to be reused by a * subsequent transfer but shall be closed immediately. */ data->set.reuse_forbid = (0 != va_arg(param, long))?TRUE:FALSE; break; case CURLOPT_FRESH_CONNECT: /* * This transfer shall not use a previously cached connection but * should be made with a fresh new connect! */ data->set.reuse_fresh = (0 != va_arg(param, long))?TRUE:FALSE; break; case CURLOPT_VERBOSE: /* * Verbose means infof() calls that give a lot of information about * the connection and transfer procedures as well as internal choices. */ data->set.verbose = (0 != va_arg(param, long))?TRUE:FALSE; break; case CURLOPT_HEADER: /* * Set to include the header in the general data output stream. */ data->set.include_header = (0 != va_arg(param, long))?TRUE:FALSE; break; case CURLOPT_NOPROGRESS: /* * Shut off the internal supported progress meter */ data->set.hide_progress = (0 != va_arg(param, long))?TRUE:FALSE; if(data->set.hide_progress) data->progress.flags |= PGRS_HIDE; else data->progress.flags &= ~PGRS_HIDE; break; case CURLOPT_NOBODY: /* * Do not include the body part in the output data stream. */ data->set.opt_no_body = (0 != va_arg(param, long))?TRUE:FALSE; break; case CURLOPT_FAILONERROR: /* * Don't output the >=300 error code HTML-page, but instead only * return error. */ data->set.http_fail_on_error = (0 != va_arg(param, long))?TRUE:FALSE; break; case CURLOPT_UPLOAD: case CURLOPT_PUT: /* * We want to sent data to the remote host. If this is HTTP, that equals * using the PUT request. */ data->set.upload = (0 != va_arg(param, long))?TRUE:FALSE; if(data->set.upload) { /* If this is HTTP, PUT is what's needed to "upload" */ data->set.httpreq = HTTPREQ_PUT; data->set.opt_no_body = FALSE; /* this is implied */ } else /* In HTTP, the opposite of upload is GET (unless NOBODY is true as then this can be changed to HEAD later on) */ data->set.httpreq = HTTPREQ_GET; break; case CURLOPT_FILETIME: /* * Try to get the file time of the remote document. The time will * later (possibly) become available using curl_easy_getinfo(). */ data->set.get_filetime = (0 != va_arg(param, long))?TRUE:FALSE; break; case CURLOPT_FTP_CREATE_MISSING_DIRS: /* * An FTP option that modifies an upload to create missing directories on * the server. */ switch(va_arg(param, long)) { case 0: data->set.ftp_create_missing_dirs = 0; break; case 1: data->set.ftp_create_missing_dirs = 1; break; case 2: data->set.ftp_create_missing_dirs = 2; break; default: /* reserve other values for future use */ result = CURLE_UNKNOWN_OPTION; break; } break; case CURLOPT_SERVER_RESPONSE_TIMEOUT: /* * Option that specifies how quickly an server response must be obtained * before it is considered failure. For pingpong protocols. */ data->set.server_response_timeout = va_arg( param , long ) * 1000; break; case CURLOPT_TFTP_BLKSIZE: /* * TFTP option that specifies the block size to use for data transmission */ data->set.tftp_blksize = va_arg(param, long); break; case CURLOPT_DIRLISTONLY: /* * An option that changes the command to one that asks for a list * only, no file info details. */ data->set.ftp_list_only = (0 != va_arg(param, long))?TRUE:FALSE; break; case CURLOPT_APPEND: /* * We want to upload and append to an existing file. */ data->set.ftp_append = (0 != va_arg(param, long))?TRUE:FALSE; break; case CURLOPT_FTP_FILEMETHOD: /* * How do access files over FTP. */ data->set.ftp_filemethod = (curl_ftpfile)va_arg(param, long); break; case CURLOPT_NETRC: /* * Parse the $HOME/.netrc file */ data->set.use_netrc = (enum CURL_NETRC_OPTION)va_arg(param, long); break; case CURLOPT_NETRC_FILE: /* * Use this file instead of the $HOME/.netrc file */ result = setstropt(&data->set.str[STRING_NETRC_FILE], va_arg(param, char *)); break; case CURLOPT_TRANSFERTEXT: /* * This option was previously named 'FTPASCII'. Renamed to work with * more protocols than merely FTP. * * Transfer using ASCII (instead of BINARY). */ data->set.prefer_ascii = (0 != va_arg(param, long))?TRUE:FALSE; break; case CURLOPT_TIMECONDITION: /* * Set HTTP time condition. This must be one of the defines in the * curl/curl.h header file. */ data->set.timecondition = (curl_TimeCond)va_arg(param, long); break; case CURLOPT_TIMEVALUE: /* * This is the value to compare with the remote document with the * method set with CURLOPT_TIMECONDITION */ data->set.timevalue = (time_t)va_arg(param, long); break; case CURLOPT_SSLVERSION: /* * Set explicit SSL version to try to connect with, as some SSL * implementations are lame. */ data->set.ssl.version = va_arg(param, long); break; #ifndef CURL_DISABLE_HTTP case CURLOPT_AUTOREFERER: /* * Switch on automatic referer that gets set if curl follows locations. */ data->set.http_auto_referer = (0 != va_arg(param, long))?TRUE:FALSE; break; case CURLOPT_ACCEPT_ENCODING: /* * String to use at the value of Accept-Encoding header. * * If the encoding is set to "" we use an Accept-Encoding header that * encompasses all the encodings we support. * If the encoding is set to NULL we don't send an Accept-Encoding header * and ignore an received Content-Encoding header. * */ argptr = va_arg(param, char *); result = setstropt(&data->set.str[STRING_ENCODING], (argptr && !*argptr)? (char *) ALL_CONTENT_ENCODINGS: argptr); break; case CURLOPT_TRANSFER_ENCODING: data->set.http_transfer_encoding = (0 != va_arg(param, long))?TRUE:FALSE; break; case CURLOPT_FOLLOWLOCATION: /* * Follow Location: header hints on a HTTP-server. */ data->set.http_follow_location = (0 != va_arg(param, long))?TRUE:FALSE; break; case CURLOPT_UNRESTRICTED_AUTH: /* * Send authentication (user+password) when following locations, even when * hostname changed. */ data->set.http_disable_hostname_check_before_authentication = (0 != va_arg(param, long))?TRUE:FALSE; break; case CURLOPT_MAXREDIRS: /* * The maximum amount of hops you allow curl to follow Location: * headers. This should mostly be used to detect never-ending loops. */ data->set.maxredirs = va_arg(param, long); break; case CURLOPT_POSTREDIR: { /* * Set the behaviour of POST when redirecting * CURL_REDIR_GET_ALL - POST is changed to GET after 301 and 302 * CURL_REDIR_POST_301 - POST is kept as POST after 301 * CURL_REDIR_POST_302 - POST is kept as POST after 302 * CURL_REDIR_POST_303 - POST is kept as POST after 303 * CURL_REDIR_POST_ALL - POST is kept as POST after 301, 302 and 303 * other - POST is kept as POST after 301 and 302 */ int postRedir = curlx_sltosi(va_arg(param, long)); data->set.keep_post = postRedir & CURL_REDIR_POST_ALL; } break; case CURLOPT_POST: /* Does this option serve a purpose anymore? Yes it does, when CURLOPT_POSTFIELDS isn't used and the POST data is read off the callback! */ if(va_arg(param, long)) { data->set.httpreq = HTTPREQ_POST; data->set.opt_no_body = FALSE; /* this is implied */ } else data->set.httpreq = HTTPREQ_GET; break; case CURLOPT_COPYPOSTFIELDS: /* * A string with POST data. Makes curl HTTP POST. Even if it is NULL. * If needed, CURLOPT_POSTFIELDSIZE must have been set prior to * CURLOPT_COPYPOSTFIELDS and not altered later. */ argptr = va_arg(param, char *); if(!argptr || data->set.postfieldsize == -1) result = setstropt(&data->set.str[STRING_COPYPOSTFIELDS], argptr); else { /* * Check that requested length does not overflow the size_t type. */ if((data->set.postfieldsize < 0) || ((sizeof(curl_off_t) != sizeof(size_t)) && (data->set.postfieldsize > (curl_off_t)((size_t)-1)))) result = CURLE_OUT_OF_MEMORY; else { char * p; (void) setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL); /* Allocate even when size == 0. This satisfies the need of possible later address compare to detect the COPYPOSTFIELDS mode, and to mark that postfields is used rather than read function or form data. */ p = malloc((size_t)(data->set.postfieldsize? data->set.postfieldsize:1)); if(!p) result = CURLE_OUT_OF_MEMORY; else { if(data->set.postfieldsize) memcpy(p, argptr, (size_t)data->set.postfieldsize); data->set.str[STRING_COPYPOSTFIELDS] = p; } } } data->set.postfields = data->set.str[STRING_COPYPOSTFIELDS]; data->set.httpreq = HTTPREQ_POST; break; case CURLOPT_POSTFIELDS: /* * Like above, but use static data instead of copying it. */ data->set.postfields = va_arg(param, void *); /* Release old copied data. */ (void) setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL); data->set.httpreq = HTTPREQ_POST; break; case CURLOPT_POSTFIELDSIZE: /* * The size of the POSTFIELD data to prevent libcurl to do strlen() to * figure it out. Enables binary posts. */ bigsize = va_arg(param, long); if(data->set.postfieldsize < bigsize && data->set.postfields == data->set.str[STRING_COPYPOSTFIELDS]) { /* Previous CURLOPT_COPYPOSTFIELDS is no longer valid. */ (void) setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL); data->set.postfields = NULL; } data->set.postfieldsize = bigsize; break; case CURLOPT_POSTFIELDSIZE_LARGE: /* * The size of the POSTFIELD data to prevent libcurl to do strlen() to * figure it out. Enables binary posts. */ bigsize = va_arg(param, curl_off_t); if(data->set.postfieldsize < bigsize && data->set.postfields == data->set.str[STRING_COPYPOSTFIELDS]) { /* Previous CURLOPT_COPYPOSTFIELDS is no longer valid. */ (void) setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL); data->set.postfields = NULL; } data->set.postfieldsize = bigsize; break; case CURLOPT_HTTPPOST: /* * Set to make us do HTTP POST */ data->set.httppost = va_arg(param, struct curl_httppost *); data->set.httpreq = HTTPREQ_POST_FORM; data->set.opt_no_body = FALSE; /* this is implied */ break; case CURLOPT_REFERER: /* * String to set in the HTTP Referer: field. */ if(data->change.referer_alloc) { Curl_safefree(data->change.referer); data->change.referer_alloc = FALSE; } result = setstropt(&data->set.str[STRING_SET_REFERER], va_arg(param, char *)); data->change.referer = data->set.str[STRING_SET_REFERER]; break; case CURLOPT_USERAGENT: /* * String to use in the HTTP User-Agent field */ result = setstropt(&data->set.str[STRING_USERAGENT], va_arg(param, char *)); break; case CURLOPT_HTTPHEADER: /* * Set a list with HTTP headers to use (or replace internals with) */ data->set.headers = va_arg(param, struct curl_slist *); break; case CURLOPT_HTTP200ALIASES: /* * Set a list of aliases for HTTP 200 in response header */ data->set.http200aliases = va_arg(param, struct curl_slist *); break; #if !defined(CURL_DISABLE_COOKIES) case CURLOPT_COOKIE: /* * Cookie string to send to the remote server in the request. */ result = setstropt(&data->set.str[STRING_COOKIE], va_arg(param, char *)); break; case CURLOPT_COOKIEFILE: /* * Set cookie file to read and parse. Can be used multiple times. */ argptr = (char *)va_arg(param, void *); if(argptr) { struct curl_slist *cl; /* append the cookie file name to the list of file names, and deal with them later */ cl = curl_slist_append(data->change.cookielist, argptr); if(!cl) { curl_slist_free_all(data->change.cookielist); data->change.cookielist = NULL; return CURLE_OUT_OF_MEMORY; } data->change.cookielist = cl; /* store the list for later use */ } break; case CURLOPT_COOKIEJAR: /* * Set cookie file name to dump all cookies to when we're done. */ result = setstropt(&data->set.str[STRING_COOKIEJAR], va_arg(param, char *)); /* * Activate the cookie parser. This may or may not already * have been made. */ data->cookies = Curl_cookie_init(data, NULL, data->cookies, data->set.cookiesession); break; case CURLOPT_COOKIESESSION: /* * Set this option to TRUE to start a new "cookie session". It will * prevent the forthcoming read-cookies-from-file actions to accept * cookies that are marked as being session cookies, as they belong to a * previous session. * * In the original Netscape cookie spec, "session cookies" are cookies * with no expire date set. RFC2109 describes the same action if no * 'Max-Age' is set and RFC2965 includes the RFC2109 description and adds * a 'Discard' action that can enforce the discard even for cookies that * have a Max-Age. * * We run mostly with the original cookie spec, as hardly anyone implements * anything else. */ data->set.cookiesession = (0 != va_arg(param, long))?TRUE:FALSE; break; case CURLOPT_COOKIELIST: argptr = va_arg(param, char *); if(argptr == NULL) break; Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE); if(Curl_raw_equal(argptr, "ALL")) { /* clear all cookies */ Curl_cookie_clearall(data->cookies); } else if(Curl_raw_equal(argptr, "SESS")) { /* clear session cookies */ Curl_cookie_clearsess(data->cookies); } else if(Curl_raw_equal(argptr, "FLUSH")) { /* flush cookies to file */ Curl_flush_cookies(data, 0); } else { if(!data->cookies) /* if cookie engine was not running, activate it */ data->cookies = Curl_cookie_init(data, NULL, NULL, TRUE); argptr = strdup(argptr); if(!argptr) { result = CURLE_OUT_OF_MEMORY; } else { if(checkprefix("Set-Cookie:", argptr)) /* HTTP Header format line */ Curl_cookie_add(data, data->cookies, TRUE, argptr + 11, NULL, NULL); else /* Netscape format line */ Curl_cookie_add(data, data->cookies, FALSE, argptr, NULL, NULL); free(argptr); } } Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE); break; #endif /* CURL_DISABLE_COOKIES */ case CURLOPT_HTTPGET: /* * Set to force us do HTTP GET */ if(va_arg(param, long)) { data->set.httpreq = HTTPREQ_GET; data->set.upload = FALSE; /* switch off upload */ data->set.opt_no_body = FALSE; /* this is implied */ } break; case CURLOPT_HTTP_VERSION: /* * This sets a requested HTTP version to be used. The value is one of * the listed enums in curl/curl.h. */ arg = va_arg(param, long); #ifndef USE_NGHTTP2 if(arg == CURL_HTTP_VERSION_2_0) return CURLE_UNSUPPORTED_PROTOCOL; #endif data->set.httpversion = arg; break; case CURLOPT_HTTPAUTH: /* * Set HTTP Authentication type BITMASK. */ { int bitcheck; bool authbits; unsigned long auth = va_arg(param, unsigned long); if(auth == CURLAUTH_NONE) { data->set.httpauth = auth; break; } /* the DIGEST_IE bit is only used to set a special marker, for all the rest we need to handle it as normal DIGEST */ data->state.authhost.iestyle = (auth & CURLAUTH_DIGEST_IE)?TRUE:FALSE; if(auth & CURLAUTH_DIGEST_IE) { auth |= CURLAUTH_DIGEST; /* set standard digest bit */ auth &= ~CURLAUTH_DIGEST_IE; /* unset ie digest bit */ } /* switch off bits we can't support */ #ifndef USE_NTLM auth &= ~CURLAUTH_NTLM; /* no NTLM support */ auth &= ~CURLAUTH_NTLM_WB; /* no NTLM_WB support */ #elif !defined(NTLM_WB_ENABLED) auth &= ~CURLAUTH_NTLM_WB; /* no NTLM_WB support */ #endif #ifndef USE_HTTP_NEGOTIATE auth &= ~CURLAUTH_GSSNEGOTIATE; /* no GSS-Negotiate without GSSAPI or WINDOWS_SSPI */ #endif /* check if any auth bit lower than CURLAUTH_ONLY is still set */ bitcheck = 0; authbits = FALSE; while(bitcheck < 31) { if(auth & (1UL << bitcheck++)) { authbits = TRUE; break; } } if(!authbits) return CURLE_NOT_BUILT_IN; /* no supported types left! */ data->set.httpauth = auth; } break; #endif /* CURL_DISABLE_HTTP */ case CURLOPT_CUSTOMREQUEST: /* * Set a custom string to use as request */ result = setstropt(&data->set.str[STRING_CUSTOMREQUEST], va_arg(param, char *)); /* we don't set data->set.httpreq = HTTPREQ_CUSTOM; here, we continue as if we were using the already set type and this just changes the actual request keyword */ break; #ifndef CURL_DISABLE_PROXY case CURLOPT_HTTPPROXYTUNNEL: /* * Tunnel operations through the proxy instead of normal proxy use */ data->set.tunnel_thru_httpproxy = (0 != va_arg(param, long))?TRUE:FALSE; break; case CURLOPT_PROXYPORT: /* * Explicitly set HTTP proxy port number. */ data->set.proxyport = va_arg(param, long); break; case CURLOPT_PROXYAUTH: /* * Set HTTP Authentication type BITMASK. */ { int bitcheck; bool authbits; unsigned long auth = va_arg(param, unsigned long); if(auth == CURLAUTH_NONE) { data->set.proxyauth = auth; break; } /* the DIGEST_IE bit is only used to set a special marker, for all the rest we need to handle it as normal DIGEST */ data->state.authproxy.iestyle = (auth & CURLAUTH_DIGEST_IE)?TRUE:FALSE; if(auth & CURLAUTH_DIGEST_IE) { auth |= CURLAUTH_DIGEST; /* set standard digest bit */ auth &= ~CURLAUTH_DIGEST_IE; /* unset ie digest bit */ } /* switch off bits we can't support */ #ifndef USE_NTLM auth &= ~CURLAUTH_NTLM; /* no NTLM support */ auth &= ~CURLAUTH_NTLM_WB; /* no NTLM_WB support */ #elif !defined(NTLM_WB_ENABLED) auth &= ~CURLAUTH_NTLM_WB; /* no NTLM_WB support */ #endif #ifndef USE_HTTP_NEGOTIATE auth &= ~CURLAUTH_GSSNEGOTIATE; /* no GSS-Negotiate without GSSAPI or WINDOWS_SSPI */ #endif /* check if any auth bit lower than CURLAUTH_ONLY is still set */ bitcheck = 0; authbits = FALSE; while(bitcheck < 31) { if(auth & (1UL << bitcheck++)) { authbits = TRUE; break; } } if(!authbits) return CURLE_NOT_BUILT_IN; /* no supported types left! */ data->set.proxyauth = auth; } break; case CURLOPT_PROXY: /* * Set proxy server:port to use as HTTP proxy. * * If the proxy is set to "" we explicitly say that we don't want to use a * proxy (even though there might be environment variables saying so). * * Setting it to NULL, means no proxy but allows the environment variables * to decide for us. */ result = setstropt(&data->set.str[STRING_PROXY], va_arg(param, char *)); break; case CURLOPT_PROXYTYPE: /* * Set proxy type. HTTP/HTTP_1_0/SOCKS4/SOCKS4a/SOCKS5/SOCKS5_HOSTNAME */ data->set.proxytype = (curl_proxytype)va_arg(param, long); break; case CURLOPT_PROXY_TRANSFER_MODE: /* * set transfer mode (;type=<a|i>) when doing FTP via an HTTP proxy */ switch (va_arg(param, long)) { case 0: data->set.proxy_transfer_mode = FALSE; break; case 1: data->set.proxy_transfer_mode = TRUE; break; default: /* reserve other values for future use */ result = CURLE_UNKNOWN_OPTION; break; } break; #endif /* CURL_DISABLE_PROXY */ #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI) case CURLOPT_SOCKS5_GSSAPI_SERVICE: /* * Set gssapi service name */ result = setstropt(&data->set.str[STRING_SOCKS5_GSSAPI_SERVICE], va_arg(param, char *)); break; case CURLOPT_SOCKS5_GSSAPI_NEC: /* * set flag for nec socks5 support */ data->set.socks5_gssapi_nec = (0 != va_arg(param, long))?TRUE:FALSE; break; #endif case CURLOPT_WRITEHEADER: /* * Custom pointer to pass the header write callback function */ data->set.writeheader = (void *)va_arg(param, void *); break; case CURLOPT_ERRORBUFFER: /* * Error buffer provided by the caller to get the human readable * error string in. */ data->set.errorbuffer = va_arg(param, char *); break; case CURLOPT_FILE: /* * FILE pointer to write to. Or possibly * used as argument to the write callback. */ data->set.out = va_arg(param, void *); break; case CURLOPT_FTPPORT: /* * Use FTP PORT, this also specifies which IP address to use */ result = setstropt(&data->set.str[STRING_FTPPORT], va_arg(param, char *)); data->set.ftp_use_port = (NULL != data->set.str[STRING_FTPPORT]) ? TRUE:FALSE; break; case CURLOPT_FTP_USE_EPRT: data->set.ftp_use_eprt = (0 != va_arg(param, long))?TRUE:FALSE; break; case CURLOPT_FTP_USE_EPSV: data->set.ftp_use_epsv = (0 != va_arg(param, long))?TRUE:FALSE; break; case CURLOPT_FTP_USE_PRET: data->set.ftp_use_pret = (0 != va_arg(param, long))?TRUE:FALSE; break; case CURLOPT_FTP_SSL_CCC: data->set.ftp_ccc = (curl_ftpccc)va_arg(param, long); break; case CURLOPT_FTP_SKIP_PASV_IP: /* * Enable or disable FTP_SKIP_PASV_IP, which will disable/enable the * bypass of the IP address in PASV responses. */ data->set.ftp_skip_ip = (0 != va_arg(param, long))?TRUE:FALSE; break; case CURLOPT_INFILE: /* * FILE pointer to read the file to be uploaded from. Or possibly * used as argument to the read callback. */ data->set.in = va_arg(param, void *); break; case CURLOPT_INFILESIZE: /* * If known, this should inform curl about the file size of the * to-be-uploaded file. */ data->set.infilesize = va_arg(param, long); break; case CURLOPT_INFILESIZE_LARGE: /* * If known, this should inform curl about the file size of the * to-be-uploaded file. */ data->set.infilesize = va_arg(param, curl_off_t); break; case CURLOPT_LOW_SPEED_LIMIT: /* * The low speed limit that if transfers are below this for * CURLOPT_LOW_SPEED_TIME, the transfer is aborted. */ data->set.low_speed_limit=va_arg(param, long); break; case CURLOPT_MAX_SEND_SPEED_LARGE: /* * When transfer uploads are faster then CURLOPT_MAX_SEND_SPEED_LARGE * bytes per second the transfer is throttled.. */ data->set.max_send_speed=va_arg(param, curl_off_t); break; case CURLOPT_MAX_RECV_SPEED_LARGE: /* * When receiving data faster than CURLOPT_MAX_RECV_SPEED_LARGE bytes per * second the transfer is throttled.. */ data->set.max_recv_speed=va_arg(param, curl_off_t); break; case CURLOPT_LOW_SPEED_TIME: /* * The low speed time that if transfers are below the set * CURLOPT_LOW_SPEED_LIMIT during this time, the transfer is aborted. */ data->set.low_speed_time=va_arg(param, long); break; case CURLOPT_URL: /* * The URL to fetch. */ if(data->change.url_alloc) { /* the already set URL is allocated, free it first! */ Curl_safefree(data->change.url); data->change.url_alloc = FALSE; } result = setstropt(&data->set.str[STRING_SET_URL], va_arg(param, char *)); data->change.url = data->set.str[STRING_SET_URL]; break; case CURLOPT_PORT: /* * The port number to use when getting the URL */ data->set.use_port = va_arg(param, long); break; case CURLOPT_TIMEOUT: /* * The maximum time you allow curl to use for a single transfer * operation. */ data->set.timeout = va_arg(param, long) * 1000L; break; case CURLOPT_TIMEOUT_MS: data->set.timeout = va_arg(param, long); break; case CURLOPT_CONNECTTIMEOUT: /* * The maximum time you allow curl to use to connect. */ data->set.connecttimeout = va_arg(param, long) * 1000L; break; case CURLOPT_CONNECTTIMEOUT_MS: data->set.connecttimeout = va_arg(param, long); break; case CURLOPT_ACCEPTTIMEOUT_MS: /* * The maximum time you allow curl to wait for server connect */ data->set.accepttimeout = va_arg(param, long); break; case CURLOPT_USERPWD: /* * user:password to use in the operation */ result = setstropt_userpwd(va_arg(param, char *), &data->set.str[STRING_USERNAME], &data->set.str[STRING_PASSWORD]); break; case CURLOPT_USERNAME: /* * authentication user name to use in the operation */ result = setstropt(&data->set.str[STRING_USERNAME], va_arg(param, char *)); break; case CURLOPT_PASSWORD: /* * authentication password to use in the operation */ result = setstropt(&data->set.str[STRING_PASSWORD], va_arg(param, char *)); break; case CURLOPT_LOGIN_OPTIONS: /* * authentication options to use in the operation */ result = setstropt(&data->set.str[STRING_OPTIONS], va_arg(param, char *)); break; case CURLOPT_XOAUTH2_BEARER: /* * XOAUTH2 bearer token to use in the operation */ result = setstropt(&data->set.str[STRING_BEARER], va_arg(param, char *)); break; case CURLOPT_POSTQUOTE: /* * List of RAW FTP commands to use after a transfer */ data->set.postquote = va_arg(param, struct curl_slist *); break; case CURLOPT_PREQUOTE: /* * List of RAW FTP commands to use prior to RETR (Wesley Laxton) */ data->set.prequote = va_arg(param, struct curl_slist *); break; case CURLOPT_QUOTE: /* * List of RAW FTP commands to use before a transfer */ data->set.quote = va_arg(param, struct curl_slist *); break; case CURLOPT_RESOLVE: /* * List of NAME:[address] names to populate the DNS cache with * Prefix the NAME with dash (-) to _remove_ the name from the cache. * * Names added with this API will remain in the cache until explicitly * removed or the handle is cleaned up. * * This API can remove any name from the DNS cache, but only entries * that aren't actually in use right now will be pruned immediately. */ data->set.resolve = va_arg(param, struct curl_slist *); data->change.resolve = data->set.resolve; break; case CURLOPT_PROGRESSFUNCTION: /* * Progress callback function */ data->set.fprogress = va_arg(param, curl_progress_callback); if(data->set.fprogress) data->progress.callback = TRUE; /* no longer internal */ else data->progress.callback = FALSE; /* NULL enforces internal */ break; case CURLOPT_XFERINFOFUNCTION: /* * Transfer info callback function */ data->set.fxferinfo = va_arg(param, curl_xferinfo_callback); if(data->set.fxferinfo) data->progress.callback = TRUE; /* no longer internal */ else data->progress.callback = FALSE; /* NULL enforces internal */ break; case CURLOPT_PROGRESSDATA: /* * Custom client data to pass to the progress callback */ data->set.progress_client = va_arg(param, void *); break; #ifndef CURL_DISABLE_PROXY case CURLOPT_PROXYUSERPWD: /* * user:password needed to use the proxy */ result = setstropt_userpwd(va_arg(param, char *), &data->set.str[STRING_PROXYUSERNAME], &data->set.str[STRING_PROXYPASSWORD]); break; case CURLOPT_PROXYUSERNAME: /* * authentication user name to use in the operation */ result = setstropt(&data->set.str[STRING_PROXYUSERNAME], va_arg(param, char *)); break; case CURLOPT_PROXYPASSWORD: /* * authentication password to use in the operation */ result = setstropt(&data->set.str[STRING_PROXYPASSWORD], va_arg(param, char *)); break; case CURLOPT_NOPROXY: /* * proxy exception list */ result = setstropt(&data->set.str[STRING_NOPROXY], va_arg(param, char *)); break; #endif case CURLOPT_RANGE: /* * What range of the file you want to transfer */ result = setstropt(&data->set.str[STRING_SET_RANGE], va_arg(param, char *)); break; case CURLOPT_RESUME_FROM: /* * Resume transfer at the give file position */ data->set.set_resume_from = va_arg(param, long); break; case CURLOPT_RESUME_FROM_LARGE: /* * Resume transfer at the give file position */ data->set.set_resume_from = va_arg(param, curl_off_t); break; case CURLOPT_DEBUGFUNCTION: /* * stderr write callback. */ data->set.fdebug = va_arg(param, curl_debug_callback); /* * if the callback provided is NULL, it'll use the default callback */ break; case CURLOPT_DEBUGDATA: /* * Set to a void * that should receive all error writes. This * defaults to CURLOPT_STDERR for normal operations. */ data->set.debugdata = va_arg(param, void *); break; case CURLOPT_STDERR: /* * Set to a FILE * that should receive all error writes. This * defaults to stderr for normal operations. */ data->set.err = va_arg(param, FILE *); if(!data->set.err) data->set.err = stderr; break; case CURLOPT_HEADERFUNCTION: /* * Set header write callback */ data->set.fwrite_header = va_arg(param, curl_write_callback); break; case CURLOPT_WRITEFUNCTION: /* * Set data write callback */ data->set.fwrite_func = va_arg(param, curl_write_callback); if(!data->set.fwrite_func) { data->set.is_fwrite_set = 0; /* When set to NULL, reset to our internal default function */ data->set.fwrite_func = (curl_write_callback)fwrite; } else data->set.is_fwrite_set = 1; break; case CURLOPT_READFUNCTION: /* * Read data callback */ data->set.fread_func = va_arg(param, curl_read_callback); if(!data->set.fread_func) { data->set.is_fread_set = 0; /* When set to NULL, reset to our internal default function */ data->set.fread_func = (curl_read_callback)fread; } else data->set.is_fread_set = 1; break; case CURLOPT_SEEKFUNCTION: /* * Seek callback. Might be NULL. */ data->set.seek_func = va_arg(param, curl_seek_callback); break; case CURLOPT_SEEKDATA: /* * Seek control callback. Might be NULL. */ data->set.seek_client = va_arg(param, void *); break; case CURLOPT_CONV_FROM_NETWORK_FUNCTION: /* * "Convert from network encoding" callback */ data->set.convfromnetwork = va_arg(param, curl_conv_callback); break; case CURLOPT_CONV_TO_NETWORK_FUNCTION: /* * "Convert to network encoding" callback */ data->set.convtonetwork = va_arg(param, curl_conv_callback); break; case CURLOPT_CONV_FROM_UTF8_FUNCTION: /* * "Convert from UTF-8 encoding" callback */ data->set.convfromutf8 = va_arg(param, curl_conv_callback); break; case CURLOPT_IOCTLFUNCTION: /* * I/O control callback. Might be NULL. */ data->set.ioctl_func = va_arg(param, curl_ioctl_callback); break; case CURLOPT_IOCTLDATA: /* * I/O control data pointer. Might be NULL. */ data->set.ioctl_client = va_arg(param, void *); break; case CURLOPT_SSLCERT: /* * String that holds file name of the SSL certificate to use */ result = setstropt(&data->set.str[STRING_CERT], va_arg(param, char *)); break; case CURLOPT_SSLCERTTYPE: /* * String that holds file type of the SSL certificate to use */ result = setstropt(&data->set.str[STRING_CERT_TYPE], va_arg(param, char *)); break; case CURLOPT_SSLKEY: /* * String that holds file name of the SSL key to use */ result = setstropt(&data->set.str[STRING_KEY], va_arg(param, char *)); break; case CURLOPT_SSLKEYTYPE: /* * String that holds file type of the SSL key to use */ result = setstropt(&data->set.str[STRING_KEY_TYPE], va_arg(param, char *)); break; case CURLOPT_KEYPASSWD: /* * String that holds the SSL or SSH private key password. */ result = setstropt(&data->set.str[STRING_KEY_PASSWD], va_arg(param, char *)); break; case CURLOPT_SSLENGINE: /* * String that holds the SSL crypto engine. */ argptr = va_arg(param, char *); if(argptr && argptr[0]) result = Curl_ssl_set_engine(data, argptr); break; case CURLOPT_SSLENGINE_DEFAULT: /* * flag to set engine as default. */ result = Curl_ssl_set_engine_default(data); break; case CURLOPT_CRLF: /* * Kludgy option to enable CRLF conversions. Subject for removal. */ data->set.crlf = (0 != va_arg(param, long))?TRUE:FALSE; break; case CURLOPT_INTERFACE: /* * Set what interface or address/hostname to bind the socket to when * performing an operation and thus what from-IP your connection will use. */ result = setstropt(&data->set.str[STRING_DEVICE], va_arg(param, char *)); break; case CURLOPT_LOCALPORT: /* * Set what local port to bind the socket to when performing an operation. */ data->set.localport = curlx_sltous(va_arg(param, long)); break; case CURLOPT_LOCALPORTRANGE: /* * Set number of local ports to try, starting with CURLOPT_LOCALPORT. */ data->set.localportrange = curlx_sltosi(va_arg(param, long)); break; case CURLOPT_KRBLEVEL: /* * A string that defines the kerberos security level. */ result = setstropt(&data->set.str[STRING_KRB_LEVEL], va_arg(param, char *)); data->set.krb = (NULL != data->set.str[STRING_KRB_LEVEL])?TRUE:FALSE; break; case CURLOPT_GSSAPI_DELEGATION: /* * GSSAPI credential delegation */ data->set.gssapi_delegation = va_arg(param, long); break; case CURLOPT_SSL_VERIFYPEER: /* * Enable peer SSL verifying. */ data->set.ssl.verifypeer = (0 != va_arg(param, long))?TRUE:FALSE; break; case CURLOPT_SSL_VERIFYHOST: /* * Enable verification of the host name in the peer certificate */ arg = va_arg(param, long); /* Obviously people are not reading documentation and too many thought this argument took a boolean when it wasn't and misused it. We thus ban 1 as a sensible input and we warn about its use. Then we only have the 2 action internally stored as TRUE. */ if(1 == arg) { failf(data, "CURLOPT_SSL_VERIFYHOST no longer supports 1 as value!"); return CURLE_BAD_FUNCTION_ARGUMENT; } data->set.ssl.verifyhost = (0 != arg)?TRUE:FALSE; break; #ifdef USE_SSLEAY /* since these two options are only possible to use on an OpenSSL- powered libcurl we #ifdef them on this condition so that libcurls built against other SSL libs will return a proper error when trying to set this option! */ case CURLOPT_SSL_CTX_FUNCTION: /* * Set a SSL_CTX callback */ data->set.ssl.fsslctx = va_arg(param, curl_ssl_ctx_callback); break; case CURLOPT_SSL_CTX_DATA: /* * Set a SSL_CTX callback parameter pointer */ data->set.ssl.fsslctxp = va_arg(param, void *); break; #endif #if defined(USE_SSLEAY) || defined(USE_QSOSSL) || defined(USE_GSKIT) || \ defined(USE_NSS) case CURLOPT_CERTINFO: data->set.ssl.certinfo = (0 != va_arg(param, long))?TRUE:FALSE; break; #endif case CURLOPT_CAINFO: /* * Set CA info for SSL connection. Specify file name of the CA certificate */ result = setstropt(&data->set.str[STRING_SSL_CAFILE], va_arg(param, char *)); break; case CURLOPT_CAPATH: /* * Set CA path info for SSL connection. Specify directory name of the CA * certificates which have been prepared using openssl c_rehash utility. */ /* This does not work on windows. */ result = setstropt(&data->set.str[STRING_SSL_CAPATH], va_arg(param, char *)); break; case CURLOPT_CRLFILE: /* * Set CRL file info for SSL connection. Specify file name of the CRL * to check certificates revocation */ result = setstropt(&data->set.str[STRING_SSL_CRLFILE], va_arg(param, char *)); break; case CURLOPT_ISSUERCERT: /* * Set Issuer certificate file * to check certificates issuer */ result = setstropt(&data->set.str[STRING_SSL_ISSUERCERT], va_arg(param, char *)); break; case CURLOPT_TELNETOPTIONS: /* * Set a linked list of telnet options */ data->set.telnet_options = va_arg(param, struct curl_slist *); break; case CURLOPT_BUFFERSIZE: /* * The application kindly asks for a differently sized receive buffer. * If it seems reasonable, we'll use it. */ data->set.buffer_size = va_arg(param, long); if((data->set.buffer_size> (BUFSIZE -1 )) || (data->set.buffer_size < 1)) data->set.buffer_size = 0; /* huge internal default */ break; case CURLOPT_NOSIGNAL: /* * The application asks not to set any signal() or alarm() handlers, * even when using a timeout. */ data->set.no_signal = (0 != va_arg(param, long))?TRUE:FALSE; break; case CURLOPT_SHARE: { struct Curl_share *set; set = va_arg(param, struct Curl_share *); /* disconnect from old share, if any */ if(data->share) { Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE); if(data->dns.hostcachetype == HCACHE_SHARED) { data->dns.hostcache = NULL; data->dns.hostcachetype = HCACHE_NONE; } #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES) if(data->share->cookies == data->cookies) data->cookies = NULL; #endif if(data->share->sslsession == data->state.session) data->state.session = NULL; data->share->dirty--; Curl_share_unlock(data, CURL_LOCK_DATA_SHARE); data->share = NULL; } /* use new share if it set */ data->share = set; if(data->share) { Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE); data->share->dirty++; if(data->share->hostcache) { /* use shared host cache */ data->dns.hostcache = data->share->hostcache; data->dns.hostcachetype = HCACHE_SHARED; } #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES) if(data->share->cookies) { /* use shared cookie list, first free own one if any */ if(data->cookies) Curl_cookie_cleanup(data->cookies); /* enable cookies since we now use a share that uses cookies! */ data->cookies = data->share->cookies; } #endif /* CURL_DISABLE_HTTP */ if(data->share->sslsession) { data->set.ssl.max_ssl_sessions = data->share->max_ssl_sessions; data->state.session = data->share->sslsession; } Curl_share_unlock(data, CURL_LOCK_DATA_SHARE); } /* check for host cache not needed, * it will be done by curl_easy_perform */ } break; case CURLOPT_PRIVATE: /* * Set private data pointer. */ data->set.private_data = va_arg(param, void *); break; case CURLOPT_MAXFILESIZE: /* * Set the maximum size of a file to download. */ data->set.max_filesize = va_arg(param, long); break; #ifdef USE_SSL case CURLOPT_USE_SSL: /* * Make transfers attempt to use SSL/TLS. */ data->set.use_ssl = (curl_usessl)va_arg(param, long); break; case CURLOPT_SSL_OPTIONS: arg = va_arg(param, long); data->set.ssl_enable_beast = arg&CURLSSLOPT_ALLOW_BEAST?TRUE:FALSE; break; #endif case CURLOPT_FTPSSLAUTH: /* * Set a specific auth for FTP-SSL transfers. */ data->set.ftpsslauth = (curl_ftpauth)va_arg(param, long); break; case CURLOPT_IPRESOLVE: data->set.ipver = va_arg(param, long); break; case CURLOPT_MAXFILESIZE_LARGE: /* * Set the maximum size of a file to download. */ data->set.max_filesize = va_arg(param, curl_off_t); break; case CURLOPT_TCP_NODELAY: /* * Enable or disable TCP_NODELAY, which will disable/enable the Nagle * algorithm */ data->set.tcp_nodelay = (0 != va_arg(param, long))?TRUE:FALSE; break; case CURLOPT_FTP_ACCOUNT: result = setstropt(&data->set.str[STRING_FTP_ACCOUNT], va_arg(param, char *)); break; case CURLOPT_IGNORE_CONTENT_LENGTH: data->set.ignorecl = (0 != va_arg(param, long))?TRUE:FALSE; break; case CURLOPT_CONNECT_ONLY: /* * No data transfer, set up connection and let application use the socket */ data->set.connect_only = (0 != va_arg(param, long))?TRUE:FALSE; break; case CURLOPT_FTP_ALTERNATIVE_TO_USER: result = setstropt(&data->set.str[STRING_FTP_ALTERNATIVE_TO_USER], va_arg(param, char *)); break; case CURLOPT_SOCKOPTFUNCTION: /* * socket callback function: called after socket() but before connect() */ data->set.fsockopt = va_arg(param, curl_sockopt_callback); break; case CURLOPT_SOCKOPTDATA: /* * socket callback data pointer. Might be NULL. */ data->set.sockopt_client = va_arg(param, void *); break; case CURLOPT_OPENSOCKETFUNCTION: /* * open/create socket callback function: called instead of socket(), * before connect() */ data->set.fopensocket = va_arg(param, curl_opensocket_callback); break; case CURLOPT_OPENSOCKETDATA: /* * socket callback data pointer. Might be NULL. */ data->set.opensocket_client = va_arg(param, void *); break; case CURLOPT_CLOSESOCKETFUNCTION: /* * close socket callback function: called instead of close() * when shutting down a connection */ data->set.fclosesocket = va_arg(param, curl_closesocket_callback); break; case CURLOPT_CLOSESOCKETDATA: /* * socket callback data pointer. Might be NULL. */ data->set.closesocket_client = va_arg(param, void *); break; case CURLOPT_SSL_SESSIONID_CACHE: data->set.ssl.sessionid = (0 != va_arg(param, long))?TRUE:FALSE; break; #ifdef USE_LIBSSH2 /* we only include SSH options if explicitly built to support SSH */ case CURLOPT_SSH_AUTH_TYPES: data->set.ssh_auth_types = va_arg(param, long); break; case CURLOPT_SSH_PUBLIC_KEYFILE: /* * Use this file instead of the $HOME/.ssh/id_dsa.pub file */ result = setstropt(&data->set.str[STRING_SSH_PUBLIC_KEY], va_arg(param, char *)); break; case CURLOPT_SSH_PRIVATE_KEYFILE: /* * Use this file instead of the $HOME/.ssh/id_dsa file */ result = setstropt(&data->set.str[STRING_SSH_PRIVATE_KEY], va_arg(param, char *)); break; case CURLOPT_SSH_HOST_PUBLIC_KEY_MD5: /* * Option to allow for the MD5 of the host public key to be checked * for validation purposes. */ result = setstropt(&data->set.str[STRING_SSH_HOST_PUBLIC_KEY_MD5], va_arg(param, char *)); break; #ifdef HAVE_LIBSSH2_KNOWNHOST_API case CURLOPT_SSH_KNOWNHOSTS: /* * Store the file name to read known hosts from. */ result = setstropt(&data->set.str[STRING_SSH_KNOWNHOSTS], va_arg(param, char *)); break; case CURLOPT_SSH_KEYFUNCTION: /* setting to NULL is fine since the ssh.c functions themselves will then rever to use the internal default */ data->set.ssh_keyfunc = va_arg(param, curl_sshkeycallback); break; case CURLOPT_SSH_KEYDATA: /* * Custom client data to pass to the SSH keyfunc callback */ data->set.ssh_keyfunc_userp = va_arg(param, void *); break; #endif /* HAVE_LIBSSH2_KNOWNHOST_API */ #endif /* USE_LIBSSH2 */ case CURLOPT_HTTP_TRANSFER_DECODING: /* * disable libcurl transfer encoding is used */ data->set.http_te_skip = (0 == va_arg(param, long))?TRUE:FALSE; break; case CURLOPT_HTTP_CONTENT_DECODING: /* * raw data passed to the application when content encoding is used */ data->set.http_ce_skip = (0 == va_arg(param, long))?TRUE:FALSE; break; case CURLOPT_NEW_FILE_PERMS: /* * Uses these permissions instead of 0644 */ data->set.new_file_perms = va_arg(param, long); break; case CURLOPT_NEW_DIRECTORY_PERMS: /* * Uses these permissions instead of 0755 */ data->set.new_directory_perms = va_arg(param, long); break; case CURLOPT_ADDRESS_SCOPE: /* * We always get longs when passed plain numericals, but for this value we * know that an unsigned int will always hold the value so we blindly * typecast to this type */ data->set.scope = curlx_sltoui(va_arg(param, long)); break; case CURLOPT_PROTOCOLS: /* set the bitmask for the protocols that are allowed to be used for the transfer, which thus helps the app which takes URLs from users or other external inputs and want to restrict what protocol(s) to deal with. Defaults to CURLPROTO_ALL. */ data->set.allowed_protocols = va_arg(param, long); break; case CURLOPT_REDIR_PROTOCOLS: /* set the bitmask for the protocols that libcurl is allowed to follow to, as a subset of the CURLOPT_PROTOCOLS ones. That means the protocol needs to be set in both bitmasks to be allowed to get redirected to. Defaults to all protocols except FILE and SCP. */ data->set.redir_protocols = va_arg(param, long); break; case CURLOPT_MAIL_FROM: /* Set the SMTP mail originator */ result = setstropt(&data->set.str[STRING_MAIL_FROM], va_arg(param, char *)); break; case CURLOPT_MAIL_AUTH: /* Set the SMTP auth originator */ result = setstropt(&data->set.str[STRING_MAIL_AUTH], va_arg(param, char *)); break; case CURLOPT_MAIL_RCPT: /* Set the list of mail recipients */ data->set.mail_rcpt = va_arg(param, struct curl_slist *); break; case CURLOPT_SASL_IR: /* Enable/disable SASL initial response */ data->set.sasl_ir = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_RTSP_REQUEST: { /* * Set the RTSP request method (OPTIONS, SETUP, PLAY, etc...) * Would this be better if the RTSPREQ_* were just moved into here? */ long curl_rtspreq = va_arg(param, long); Curl_RtspReq rtspreq = RTSPREQ_NONE; switch(curl_rtspreq) { case CURL_RTSPREQ_OPTIONS: rtspreq = RTSPREQ_OPTIONS; break; case CURL_RTSPREQ_DESCRIBE: rtspreq = RTSPREQ_DESCRIBE; break; case CURL_RTSPREQ_ANNOUNCE: rtspreq = RTSPREQ_ANNOUNCE; break; case CURL_RTSPREQ_SETUP: rtspreq = RTSPREQ_SETUP; break; case CURL_RTSPREQ_PLAY: rtspreq = RTSPREQ_PLAY; break; case CURL_RTSPREQ_PAUSE: rtspreq = RTSPREQ_PAUSE; break; case CURL_RTSPREQ_TEARDOWN: rtspreq = RTSPREQ_TEARDOWN; break; case CURL_RTSPREQ_GET_PARAMETER: rtspreq = RTSPREQ_GET_PARAMETER; break; case CURL_RTSPREQ_SET_PARAMETER: rtspreq = RTSPREQ_SET_PARAMETER; break; case CURL_RTSPREQ_RECORD: rtspreq = RTSPREQ_RECORD; break; case CURL_RTSPREQ_RECEIVE: rtspreq = RTSPREQ_RECEIVE; break; default: rtspreq = RTSPREQ_NONE; } data->set.rtspreq = rtspreq; break; } case CURLOPT_RTSP_SESSION_ID: /* * Set the RTSP Session ID manually. Useful if the application is * resuming a previously established RTSP session */ result = setstropt(&data->set.str[STRING_RTSP_SESSION_ID], va_arg(param, char *)); break; case CURLOPT_RTSP_STREAM_URI: /* * Set the Stream URI for the RTSP request. Unless the request is * for generic server options, the application will need to set this. */ result = setstropt(&data->set.str[STRING_RTSP_STREAM_URI], va_arg(param, char *)); break; case CURLOPT_RTSP_TRANSPORT: /* * The content of the Transport: header for the RTSP request */ result = setstropt(&data->set.str[STRING_RTSP_TRANSPORT], va_arg(param, char *)); break; case CURLOPT_RTSP_CLIENT_CSEQ: /* * Set the CSEQ number to issue for the next RTSP request. Useful if the * application is resuming a previously broken connection. The CSEQ * will increment from this new number henceforth. */ data->state.rtsp_next_client_CSeq = va_arg(param, long); break; case CURLOPT_RTSP_SERVER_CSEQ: /* Same as the above, but for server-initiated requests */ data->state.rtsp_next_client_CSeq = va_arg(param, long); break; case CURLOPT_INTERLEAVEDATA: data->set.rtp_out = va_arg(param, void *); break; case CURLOPT_INTERLEAVEFUNCTION: /* Set the user defined RTP write function */ data->set.fwrite_rtp = va_arg(param, curl_write_callback); break; case CURLOPT_WILDCARDMATCH: data->set.wildcardmatch = (0 != va_arg(param, long))?TRUE:FALSE; break; case CURLOPT_CHUNK_BGN_FUNCTION: data->set.chunk_bgn = va_arg(param, curl_chunk_bgn_callback); break; case CURLOPT_CHUNK_END_FUNCTION: data->set.chunk_end = va_arg(param, curl_chunk_end_callback); break; case CURLOPT_FNMATCH_FUNCTION: data->set.fnmatch = va_arg(param, curl_fnmatch_callback); break; case CURLOPT_CHUNK_DATA: data->wildcard.customptr = va_arg(param, void *); break; case CURLOPT_FNMATCH_DATA: data->set.fnmatch_data = va_arg(param, void *); break; #ifdef USE_TLS_SRP case CURLOPT_TLSAUTH_USERNAME: result = setstropt(&data->set.str[STRING_TLSAUTH_USERNAME], va_arg(param, char *)); if(data->set.str[STRING_TLSAUTH_USERNAME] && !data->set.ssl.authtype) data->set.ssl.authtype = CURL_TLSAUTH_SRP; /* default to SRP */ break; case CURLOPT_TLSAUTH_PASSWORD: result = setstropt(&data->set.str[STRING_TLSAUTH_PASSWORD], va_arg(param, char *)); if(data->set.str[STRING_TLSAUTH_USERNAME] && !data->set.ssl.authtype) data->set.ssl.authtype = CURL_TLSAUTH_SRP; /* default to SRP */ break; case CURLOPT_TLSAUTH_TYPE: if(strnequal((char *)va_arg(param, char *), "SRP", strlen("SRP"))) data->set.ssl.authtype = CURL_TLSAUTH_SRP; else data->set.ssl.authtype = CURL_TLSAUTH_NONE; break; #endif case CURLOPT_DNS_SERVERS: result = Curl_set_dns_servers(data, va_arg(param, char *)); break; case CURLOPT_DNS_INTERFACE: result = Curl_set_dns_interface(data, va_arg(param, char *)); break; case CURLOPT_DNS_LOCAL_IP4: result = Curl_set_dns_local_ip4(data, va_arg(param, char *)); break; case CURLOPT_DNS_LOCAL_IP6: result = Curl_set_dns_local_ip6(data, va_arg(param, char *)); break; case CURLOPT_TCP_KEEPALIVE: data->set.tcp_keepalive = (0 != va_arg(param, long))?TRUE:FALSE; break; case CURLOPT_TCP_KEEPIDLE: data->set.tcp_keepidle = va_arg(param, long); break; case CURLOPT_TCP_KEEPINTVL: data->set.tcp_keepintvl = va_arg(param, long); break; default: /* unknown tag and its companion, just ignore: */ result = CURLE_UNKNOWN_OPTION; break; } return result; }
[ "993273596@qq.com" ]
993273596@qq.com
4e2842c37ea1870cda63f375ea9344c09f2a24b2
1af5af91c0d692f7814f57441bee61a3b9ad1f1e
/70-climbing-stairs.cpp
3e505f96131019621398096e95bc9f2610768237
[]
no_license
raiseyang/leetcode
b064cd22fc09cfcf562a886e1e12d752ee2e7c37
4316dab854b17b3c26beb9c016539d4c2067f8e1
refs/heads/master
2022-02-21T19:12:52.990374
2019-09-07T08:23:52
2019-09-07T08:23:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
290
cpp
class Solution { public: int climbStairs(int n) { int c1 = 1, c2 = 2; if (n < 3) return n; for (int i = 3; i <= n; ++i) { int tmp = c1 + c2; c1 = c2; c2 = tmp; } return c2; } };
[ "maxime.limy@gmail.com" ]
maxime.limy@gmail.com
ae7c5e7701da36e38982aa3553911b0084aab8f7
4836ee9e77b6e1c23fbef4db492c147b88267a06
/Algorithm_Training/Blue/Lecture10/5/main.cpp
4da51eab1dc9a1485777da2d73e8dd81ba749ff5
[]
no_license
namnh97/CCode
33da753e575acabea37f69f8ab8a7c2e0d7458cf
bdf85622206b4a8a8ed46867ee15e000f020849b
refs/heads/master
2022-08-16T06:46:43.741051
2022-07-27T02:44:03
2022-07-27T02:44:03
165,805,230
0
0
null
null
null
null
UTF-8
C++
false
false
1,776
cpp
//https://open.kattis.com/problems/shortestpath3 #include<bits/stdc++.h> #define ll long long #define pb push_back #define mp make_pair #define pii pair<int, int> using namespace std; const int MAX = 1001; const int INF = 1e9; struct Edge { int from; int to; int weight; }; vector<Edge> graph; int m, n, q, s; int dist[MAX]; void Bellman(int src) { fill(dist, dist + MAX, INF); dist[src] = 0; for (int i = 0; i < n - 1; i++) { for (auto &edge : graph) { int u = edge.from; int v = edge.to; int w = edge.weight; if (dist[u] != INF && dist[v] > dist[u] + w) { dist[v] = dist[u] + w; } } } for (int i = 0; i < n - 1; i++) { for (auto &edge : graph) { int u = edge.from; int v = edge.to; int w = edge.weight; if (dist[u] != INF && dist[v] > dist[u] + w) { dist[v] = -INF; } } } } void solve() { while (cin >> n >> m >> q >> s && n >= 0 && m >= 0 && q >= 0 && s >= 0) { graph.clear(); for (int i = 0; i < m; i++) { int u, v, w; cin >> u >> v >> w; graph.pb(Edge{u, v, w}); } Bellman(s); for (int i = 0; i < q; i++) { int des; cin >> des; if (dist[des] == INF) { cout << "Impossible" << endl; } else if (dist[des] == -INF) { cout << "-Infinity" << endl; } else { cout << dist[des] << endl; } } cout << endl; } } int main(int argc, char** argv){ #ifndef ONLINE_JUDGE freopen(argv[1], "r", stdin); #endif solve(); return 0; }
[ "namnh997@gmail.com" ]
namnh997@gmail.com
bd1bc2af610a9046e5544ca08621c02386a71268
dfa6ddf5fb513d553d43a028add28cdf40b46249
/474. Ones and Zeroes.cpp
ebee96f01b36b6ab1efa0be6748626890771b2f2
[]
no_license
brucechin/Leetcode
c58eb6eedf3a940841a0ccae18d543fd88b76f65
798e6f1fa128982c7fd141a725b99805131361cb
refs/heads/master
2021-11-22T14:31:53.143147
2021-10-08T06:50:28
2021-10-08T06:50:28
109,366,643
4
0
null
null
null
null
UTF-8
C++
false
false
2,252
cpp
/* In the computer world, use restricted resource you have to generate maximum benefit is what we always want to pursue. For now, suppose you are a dominator of m 0s and n 1s respectively. On the other hand, there is an array with strings consisting of only 0s and 1s. Now your task is to find the maximum number of strings that you can form with given m 0s and n 1s. Each 0 and 1 can be used at most once. Note: The given numbers of 0s and 1s will both not exceed 100 The size of given string array won't exceed 600. Example 1: Input: Array = {"10", "0001", "111001", "1", "0"}, m = 5, n = 3 Output: 4 Explanation: This are totally 4 strings can be formed by the using of 5 0s and 3 1s, which are “10,”0001”,”1”,”0” Example 2: Input: Array = {"10", "0", "1"}, m = 1, n = 1 Output: 2 Explanation: You could form "10", but then you'd have nothing left. Better form "0" and "1". */ class Solution { public: int findMaxForm(vector<string> &strs, int m, int n) { vector<vector<int>> memo(m + 1, vector<int>(n + 1, 0)); int numZeroes, numOnes; for (auto &s : strs) { numZeroes = numOnes = 0; // count number of zeroes and ones in current string for (auto c : s) { if (c == '0') numZeroes++; else if (c == '1') numOnes++; } // memo[i][j] = the max number of strings that can be formed with i 0's and j 1's // from the first few strings up to the current string s // Catch: have to go from bottom right to top left // Why? If a cell in the memo is updated(because s is selected), // we should be adding 1 to memo[i][j] from the previous iteration (when we were not considering s) // If we go from top left to bottom right, we would be using results from this iteration => overcounting for (int i = m; i >= numZeroes; i--) { for (int j = n; j >= numOnes; j--) { memo[i][j] = max(memo[i][j], memo[i - numZeroes][j - numOnes] + 1); } } } return memo[m][n]; } };
[ "1026193951@sjtu.edu.cn" ]
1026193951@sjtu.edu.cn
e4730fd370186636548afde99a9e63ee80d88c32
9b26f6ade6215662db0c706661f86f1a5a8713b7
/FrozenFlame/Game/Source/Objects/WizardEnemy.h
012ba7a9b7697a25031b7a16d803e1c387242e8a
[]
no_license
mbirky/FrozenFlame
d310c753f73bf092bd0e2fa9427b125c30bce568
4264bc86ee66a0c010642ecabf512c920a8082e3
refs/heads/main
2023-04-13T20:22:40.245502
2018-07-06T07:35:16
2018-07-06T07:35:16
361,937,727
0
0
null
null
null
null
UTF-8
C++
false
false
6,274
h
/*********************************************** * Filename: WizardEnemy.h * Date: 10/30/2012 * Mod. Date: 10/30/2012 * Mod. Initials: CM * Author: Charles Meade * Purpose: Function declarations for the wizard enemy object ************************************************/ #ifndef WIZARD_ENEMY_H #define WIZARD_ENEMY_H class CWorldManager; class CLevel; class CWizardSpawner; class CSpawner; #include "enemy.h" #include "../Renderer/Emitter.h" #include "CIceTrap.h" #include "CFireTrap.h" #include "SceneryObject.h" #include "IceEnemy.h" #include "FireEnemy.h" //#include "../Core/CWorldManager.h" enum WizardAnimations {RENEMY_IDLE = 3, RENEMY_WALK, RENEMY_ATTACK, RENEMY_DEATH}; enum WizardSubTypes {FIRST_STAGE,SECOND_STAGE,THIRD_STAGE,FOURTH_STAGE,FINAL_BOSS}; class CWizardEnemy : public CEnemy { private: int m_nNumTrapWavesCreated; int m_nWizardForm; int m_nWizardSubType; bool m_bIsAlive; bool m_bExhausted; float m_fTrapSpawnTimer; bool m_bEscaped; bool m_bDefeated; float m_fTotalHealth; float m_fFinalDeathTimer; float m_fDeathTimeLimit; bool m_bDeathCharging; bool m_bDeathExloding; bool m_bDeathExploded; TImage m_tShadow; int m_nShadowRenderID; CSceneryObject * m_pcBubble; CEmitter* m_pcFireEmitter; CEmitter* m_pcIceEmitter; vec3f m_tInitialPosition; vector<CIceTrap*> m_vIceTraps; vector<CFireTrap*> m_vFireTraps; CPlayerObject* m_pPlayer; CTimer m_tWizTimer; int m_nShapeID; // For Health // stuff for spawning enemies CLevel * m_pcCurrLevel; CIceEnemy * m_pcIceSpawned; CFireEnemy * m_pcFireSpawned; // crystals in final battle vector<CSpawner*> m_vpcWizardSpawners; // Emitters CEmitter * m_pcBubbleBurstEmitter; CEmitter * m_pcBubbleSheenEmitter; CEmitter * m_pcCrashEmitter; CEmitter * m_pcDeathBurstEmitter; CEmitter * m_pcDeathFlowEmitter; CEmitter * m_pcSmokeEmitter; CEmitter * m_pcTakeoffEmitter; CEmitter * m_pcSpawnEmitter; public: /***************************************************************** * CWizardEnemy(): Default constructor for the wizard enemy object * * * Ins: void * * Outs: void * * Returns: n/a * * Mod. Date: 10/30/2012 * Mod. Initials: CM *****************************************************************/ CWizardEnemy(void); /***************************************************************** * ~CWizardEnemy(): Default destructor for the wizard enemy object * * * Ins: void * * Outs: void * * Returns: n/a * * Mod. Date: 10/30/2012 * Mod. Initials: CM *****************************************************************/ ~CWizardEnemy(void); /***************************************************************** * Initialize(): The default funciton that sets all starting values for * this instance of the class * * Ins: void * * Outs: void * * Returns: void * * Mod. Date: 10/30/2012 * Mod. Initials: CM *****************************************************************/ void Initialize(void); /***************************************************************** * Reinitialize(): The default funciton that resets all starting values for * this instance of the class * * Ins: void * * Outs: void * * Returns: void * * Mod. Date: 10/30/2012 * Mod. Initials: CM *****************************************************************/ void Reinitialize(); /***************************************************************** * Update(): Updates all data for the class based off of time * * Ins: fElapsedTime * * Outs: void * * Returns: void * * Mod. Date: 10/30/2012 * Mod. Initials: CM *****************************************************************/ void Update(float fElapsedTime); /***************************************************************** * Uninitialize(): returns the object to the starting state * * Ins: void * * Outs: void * * Returns: void * * Mod. Date: 11/03/2012 * Mod. Initials: CM *****************************************************************/ void Uninitialize(); /***************************************************************** * OnAttack(): runs any logic when this object gets attacked by something * * Ins: void * * Outs: nDamage nElementType * * Returns: void * * Mod. Date: 02/04/2013 * Mod. Initials: BRG *****************************************************************/ void OnAttack(int nDamage,int nElementType); bool GetIsAlive(void) {return m_bIsAlive;} int GetWizardForm() {return m_nWizardForm;} void SetWizardForm(int _nWizardForm) {m_nWizardForm = _nWizardForm;} vec3f GetInitialPosition() {return m_tInitialPosition;} void SetInitialPosition(vec3f _tInitialPosition) {m_tInitialPosition = _tInitialPosition;} bool GetExhausted() {return m_bExhausted;} void SetExhausted(bool _bExhausted) {m_bExhausted = _bExhausted;} void SetWizardSubtype(int nSubType) {m_nWizardSubType = nSubType;}; int GetWizardSubtype() {return m_nWizardSubType;} bool GetEscaped(void) {return m_bEscaped;} void SetEscaped(bool _bEscaped) {m_bEscaped = _bEscaped;} bool GetIsDefeated(void) {return m_bDefeated;} void SetIsDefeated(bool _bDefeated) {m_bDefeated = _bDefeated;} CSceneryObject * GetBubble() {return m_pcBubble;} void HideBubble() { CView::SetIsVisible(GetBubble()->GetRenderID(),false);} void ShowBubble() { CView::SetIsVisible(GetBubble()->GetRenderID(),true);} float GetWizardTime() {return m_tWizTimer.GetElapsedTime();} void SpawnEnemies(); void CrystalDisabled(); void ReactivateCrystals(); void IncrementPhase(); void PushBackWizardSpawner(CSpawner * pcSpawner); void ClearWizardSpawners(); void SetTotalHealth(float fHealth) {m_fTotalHealth = fHealth; }; float GetTotalHealth() {return m_fTotalHealth;}; void SetBubbleBurstEmitterActive(bool bActive); void SetBubbleSheenEmitterActive(bool bActive); void SetCrashEmitterActive(bool bActive); void SetDeathBurstEmitterActive(bool bActive); void SetDeathFlowEmitterActive(bool bActive); void SetSmokeEmitterActive(bool bActive); void SetTakeoffEmitterActive(bool bActive); void SetSpawnEmitterActive(bool bActive); }; #endif
[ "danielmlima@fullsail.edu" ]
danielmlima@fullsail.edu
c2ee8a956229bdac101a2d3adc4a4f73dfa4c1a3
0459ae96bae0b3b2c9858ce5050e60e3b01b000e
/Christian/PROG_II/Uebung_8/svgfile.h
4f2e8210964beaaa8b040fb163dd0ce6f81a8443
[]
no_license
DevCodeOne/WS_1617
f03f19f1317b93483be4133f768c031bdf2bd364
461c7119b0854bbd35f117f0c3f0ccd0b5a3a94c
refs/heads/master
2021-05-03T12:30:16.521386
2017-02-02T09:31:57
2017-02-02T09:31:57
62,337,029
0
0
null
null
null
null
UTF-8
C++
false
false
1,242
h
/* * ++C - C++ introduction * Copyright (C) 2013, 2014, 2015, 2016 Wilhelm Meier <wilhelm.meier@hs-kl.de> * * 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 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <fstream> #include <string> class SVGFile { public: SVGFile(std::string filename); ~SVGFile(); void add(std::string svgElement); private: std::ofstream mFile; // <> nicht-statische Datenelemente (Objektvariablen) werden bei der Destruktion ebenfalls zerstört. static std::string header1; // <> statische Datenelemente (Klassenvariablen) static std::string header2; static std::string header3; static std::string footer1; };
[ "christian.r.dev@googlemail.com" ]
christian.r.dev@googlemail.com
57ef891de81f6fbbeff7fe3046e43ca6a8cb71f8
d9f2430ec0c61e5cb69d01f3abd5667ab4c924c6
/datalust/src/Physics/ContactResolver.cpp
977dc69a5d7779a5c44258ce58ef1cbf4f1efa99
[]
no_license
ProgrammingMoogle/Portfolio
d74aeff998386e6724ab133d8024b194688a6057
8e361dea4b9e523f57525fe2d049667618a6c24d
refs/heads/master
2020-03-27T04:03:17.361681
2018-08-23T22:30:11
2018-08-23T22:30:11
145,908,779
0
1
null
null
null
null
UTF-8
C++
false
false
8,729
cpp
#pragma once /******************************************************************************/ /*! \file ContactResolver.cpp \author Keonwoo Ryoo \par email: keonwoo.ryoo\@digipen.edu \par DigiPen login: keonwoo.ryoo \par Last Update: 9/8/2017 \date 9/8/2017 \brief All content © 2017 DigiPen (USA) Corporation, all rights reserved. */ /******************************************************************************/ #include "ContactResolver.hpp" #include "ForceRegistry.hpp" #include <GameObject/Component.h> #include <GameObject/GameObject.h> #include <Transform/Transform.hpp> #include <Messaging/Messaging.hpp> #include <Engine/Engine.h> /** * \brief */ namespace KPE { /** * \brief * \param contactList */ void ContactResolver::addContactList(ContactList* contactList) { contactLists_.push_back(contactList); } /** * \brief * \param registry * \param dt * \return */ int ContactResolver::resolveContacts(ForceRegistry& registry, float dt) { int numContacts = 0; Messaging::MessageHandler* mHandler = engine.Find<Messaging::MessageHandler>(); //Loop through the vector of ContactLists auto iterList = contactLists_.begin(); for (; iterList != contactLists_.end(); ++iterList) { RigidBody* body = (*iterList)->body; RigidBody* otherBody = (*iterList)->otherBody; //Loop through the list of contacts auto iterContact = (*iterList)->contacts_.begin(); for (; iterContact != (*iterList)->contacts_.end(); ++iterContact) { ++numContacts; //Check what type of contact it is if ((*iterContact)->bound_->getType() == BoundType::BoundBox) { ContactBB* tempContact = static_cast<ContactBB*>((*iterContact)); bool pass = true; //Possible semisolid interaction Messaging::Message msg; msg.id = Messaging::ID::Collision; msg.message.collision.hit_ = false; msg.message.collision.pass_ = &pass; msg.message.collision.body_ = body; msg.message.collision.otherBody_ = otherBody; msg.message.collision.normal_ = tempContact->contactNormal_; msg.message.collision.penetration_ = tempContact->penetration_; mHandler->Post(msg); if (pass) { //Resolve Velocity resolveVelocity(tempContact, body, otherBody, dt); //Resolve Interpenetration if (tempContact->penetration_ > 0.0f) resolvePenetration(tempContact, body, otherBody, dt); //positionalCorrection(tempContact, body, otherBody); } } else { ContactHB* tempContact = static_cast<ContactHB*>((*iterContact)); //Send to messaging Messaging::Message msg; msg.id = Messaging::ID::Collision; msg.message.collision.hit_ = true; //Order RigidBodies (Hitbox, Hurtbox) if (tempContact->bound_->getType() == BoundHitBox) { msg.message.collision.body_ = body; msg.message.collision.otherBody_ = otherBody; msg.message.collision.normal_ = tempContact->contactNormal_; msg.message.collision.penetration_ = tempContact->penetration_; } else if (tempContact->bound_->getType() == BoundHurtBox) { msg.message.collision.body_ = otherBody; msg.message.collision.otherBody_ = body; msg.message.collision.normal_ = -(tempContact->contactNormal_); msg.message.collision.penetration_ = tempContact->penetration_; } mHandler->Post(msg); } } //Delete ContactList } //Clear the list vector clear(); return numContacts; } /** * \brief * \param contact * \param body * \param otherBody * \param dt */ void ContactResolver::resolveVelocity(ContactBB* contact, RigidBody* body, RigidBody* otherBody, float dt) { glm::vec2 tempVel(0); //Temporary velocity vector //Get Total Separating Velocity float separatingVelocity = calculateSeparatingVelocity(contact, body, otherBody); //If no separating velocity, no need to resolve velocity //Separating velocity must be negative. Positive means they are separating, not colliding if (separatingVelocity > 0) return; //Apply restitution float newSepVel = -separatingVelocity * contact->restitution_; //Find velocity caused by acceleration glm::vec2 accCausedVel = body->getLastAcceleration(); if (otherBody) accCausedVel -= otherBody->getLastAcceleration(); float accCausedSepVel = dot(accCausedVel, contact->contactNormal_) * dt; //Apply acceleration velocity to separating velocity if (accCausedSepVel < 0) { newSepVel += -accCausedSepVel * contact->restitution_; if (newSepVel < 0) newSepVel = 0; } //Find the delta velocity float deltaVel = newSepVel - separatingVelocity; //Find total inverse mass of both bodies float totalInverseMass = body->getInverseMass(); if (otherBody) if (otherBody->hasFiniteMass()) totalInverseMass += otherBody->getInverseMass(); if (totalInverseMass <= 0) return; //Find impulse magnitude per inverse mass float impulse = deltaVel / totalInverseMass; //Find impulse per inverse mass glm::vec2 impulsePerInverseMass = contact->contactNormal_ * impulse; //Apply velocities tempVel = body->getVelocity(); tempVel += impulsePerInverseMass * body->getInverseMass(); body->setVelocity(tempVel); if (otherBody) { tempVel = otherBody->getVelocity(); tempVel -= impulsePerInverseMass * otherBody->getInverseMass(); otherBody->setVelocity(tempVel); } } /** * \brief * \param contact * \param body * \param otherBody * \param dt */ void ContactResolver::resolvePenetration(ContactBB* contact, RigidBody* body, RigidBody* otherBody, float dt) { Transform* trans = body->GetParent().Find<Transform>(); Transform* otherTrans = otherBody->GetParent().Find<Transform>(); if (!(otherBody->hasFiniteMass())) { trans->setPosition( trans->getPosition() + contact->penetration_ * contact->contactNormal_); return; } glm::vec2 tempVel(0); if (contact->penetration_ <= 0) return; if ((body->GetParent().GetName() == "Player1" && otherBody->GetParent().GetName() == "Player2") || (body->GetParent().GetName() == "Player2" && otherBody->GetParent().GetName() == "Player1")) { tempVel.x = 0; } //Neither are immovable. float totalInverseMass = body->getInverseMass(); if (otherBody) if (otherBody->hasFiniteMass()) totalInverseMass += otherBody->getInverseMass(); if (totalInverseMass <= 0) return; glm::vec2 pulsePerInverseMass = contact->contactNormal_ * (contact->penetration_ / totalInverseMass); glm::vec2 tempShift(0); tempShift = pulsePerInverseMass * body->getInverseMass(); tempShift += trans->getPosition(); trans->setPosition(tempShift); if (otherBody) { tempShift = -pulsePerInverseMass * otherBody->getInverseMass(); tempShift += otherTrans->getPosition(); otherTrans->setPosition(tempShift); } } /** * \brief * \param contact * \param body * \param otherBody * \return */ float ContactResolver::calculateSeparatingVelocity(ContactBB* contact, RigidBody* body, RigidBody* otherBody) const { glm::vec2 relativeVel = body->getVelocity(); if (otherBody) relativeVel -= otherBody->getVelocity(); return dot(relativeVel, contact->contactNormal_); } /** * \brief * \param contact * \param body * \param otherBody */ void ContactResolver::positionalCorrection( Contact* contact, RigidBody* body, RigidBody* otherBody) { Transform* trans = body->GetParent().Find<Transform>(); Transform* otherTrans = otherBody->GetParent().Find<Transform>(); float percentage = 0.2f; glm::vec2 correction = contact->penetration_ / (body->getInverseMass() + otherBody->getInverseMass()) * percentage * contact->contactNormal_; trans->setPosition( trans->getPosition() + correction * body->getInverseMass()); otherTrans->setPosition( otherTrans->getPosition() + correction * otherBody->getInverseMass()); } /** * \brief */ void ContactResolver::clear(void) { auto iter = contactLists_.begin(); for (; iter != contactLists_.end(); ++iter) { delete *iter; } contactLists_.clear(); } }
[ "42657613+ProgrammingMoogle@users.noreply.github.com" ]
42657613+ProgrammingMoogle@users.noreply.github.com
939f94896cd57620e881c45c0253826fabd2f230
04fa32e35971bcef99074b97fdf0a611005799c5
/VersionC++/vector2d.cpp
fe21f6840bd88bc536dc01a7912bb4b6751c0f7b
[]
no_license
AdrianWennberg/ATak
71cd56c2442b2f9c4c108e7c28a34ef525db7983
07aa97c24b47ec0f3194e04d0d84c15f93ff9444
refs/heads/master
2021-01-22T21:07:39.882646
2017-11-13T06:52:05
2017-11-13T06:52:05
85,395,233
0
0
null
null
null
null
UTF-8
C++
false
false
723
cpp
#include <vector> #include "vector2d.h" using namespace std; template<typename T> Vector2d<T>::Vector2d(int pRows, int pColumns) : mRows(pRows), mColumns(pColumns), mField(pRows * pColumns) { }; template<typename T> void Vector2d<T>::setPosition(int pRow, int pColumn, int value) { if(pRow < mRows && pColumn < mColumns) { mField[pRow * mColumns + pColumn] = value; } }; template<typename T> T *Vector2d<T>::getPositionPointer(int pRow, int pColumn) { return &(mField[pRow * mColumns + pColumn]); }; template<typename T> int Vector2d<T>::getFieldSize() { return mField.size(); }; template<typename T> SquareVector<T>::SquareVector(int size) : Vector2d<T>(size, size) { };
[ "saikoupanda@gmail.com" ]
saikoupanda@gmail.com
1ea6635bfa0287eb51c062178ecc9232e541b9c4
a3be167a074cc31f61bd5df831373d24d4ec008c
/gfg/mimimum_copy_paste.cpp
9611ef4ed5a237fffa7a7cc022faaf92d1899293
[]
no_license
Nimishkhurana/Data-Structures
5a20b0b7882b3e9d2c853433902caba0a4f8b596
579c3d26b89392f75864543db821af40cb07622f
refs/heads/master
2021-07-08T14:36:48.043616
2020-07-29T18:48:03
2020-07-29T18:48:03
160,632,175
2
2
null
2019-10-18T20:10:54
2018-12-06T06:52:10
C++
UTF-8
C++
false
false
305
cpp
#include<iostream> using namespace std; int main(){ int n; cin>>n; int count = 0; for(int i=2;i<n;i++){ while(n%i==0){ count+=i; n/=i; } if(n<=4 && n>1){ count+=n; break; } } cout<<count<<endl; }
[ "nimishkhurana9@gmail.com" ]
nimishkhurana9@gmail.com
d7cf116cc9b22399798acdea65c4ba346afbbd88
539ba303916e1b2bddd364c44cd1a07125449963
/WebServer/settings.ino
f965ae6381d418f97e11a4ecb4e3dc2952d13413
[]
no_license
DanLoad/Web-interface-for-ESP32
bb75ae942cf0b895c4d5fc7a93e6cf55ddbc7226
84c836d7175e05e86ba7a7294d19c48a5a0687d9
refs/heads/master
2021-05-17T03:55:40.604843
2020-03-29T16:38:32
2020-03-29T16:38:32
250,610,565
0
0
null
null
null
null
UTF-8
C++
false
false
1,091
ino
void Settings_read() { settingsWifi = readFile("json/settings/Wifi.json", 4096); settingsNetwork = readFile("json/settings/Network.json", 4096); settingsMqtt = readFile("json/settings/Mqtt.json", 4096); settingsAP = readFile("json/settings/AP.json", 4096); Config = readFile("json/settings/Conf.json", 4096); Serial.print("Settings Read Done"); } void Settings_WiFi() { _ssid = jsonRead(settingsWifi, "ssid"); _password = jsonRead(settingsWifi, "password"); _ssidAP = jsonRead(settingsAP, "ssidAP"); _passwordAP = jsonRead(settingsAP, "passwordAP"); nameMod = jsonRead(Config, "module"); idMod = jsonRead(Config, "name"); host = jsonRead(Config, "host"); Serial.print("Settings WiFi Done >>>>>>"); } void Settings_Mqtt() { String s = ""; int n = 0; host = jsonRead(settingsWifi, "host"); mqttServer = jsonRead(settingsMqtt, "mqttServer"); mqttPort = jsonReadtoInt(settingsMqtt, "mqttPort"); mqttUser = jsonRead(settingsMqtt, "mqttUser"); mqttPassword = jsonRead(settingsMqtt, "mqttPassword"); }
[ "danmetalist@gmail.com" ]
danmetalist@gmail.com
8c9dc9e10025ecf20596a68190fb6848241e7869
2620e0834c1b58a532e9875c9ea040d664027d9d
/app/src/main/cpp/ClientSocketDataDealThread.cpp
01961c092e5d3a1d9db8f7e692174b09917479f2
[]
no_license
EastUp/AndroidJnitSocket
93fbd92911d1bbabc4a6bcc4b15f66091299b4b6
9aa2d33721a6dc0d305b21225f941fd409d25813
refs/heads/master
2023-03-18T02:25:59.210426
2021-03-09T06:05:47
2021-03-09T06:05:47
345,900,747
2
0
null
null
null
null
UTF-8
C++
false
false
4,660
cpp
// // Created by Administrator on 2017/3/3 0003. // #include <sys/socket.h> #include <jni.h> #include <malloc.h> #include <memory.h> #include "my_log.h" #include "ClientSocketDataDealThread.h" pthread_cond_t ClientSocketDataDealThread::cond = PTHREAD_COND_INITIALIZER; pthread_mutex_t ClientSocketDataDealThread::mutex = PTHREAD_MUTEX_INITIALIZER; int ClientSocketDataDealThread::socketFd = 0; char *ClientSocketDataDealThread::getBuffer = NULL; bool ClientSocketDataDealThread::isShoudExit = false; JNIEnv *ClientSocketDataDealThread::env = NULL; jobject ClientSocketDataDealThread::obj = NULL; JavaVM *ClientSocketDataDealThread::javavm = NULL; void *ClientSocketDataDealThread::clientThread(void *args) { javavm->AttachCurrentThread(&ClientSocketDataDealThread::env, NULL); LOGI("%s:ClientSocketDataDealThread is running", TAG); while (!ClientSocketDataDealThread::isShoudExit) { // pthread_mutex_lock(&ClientSocketDataDealThread::mutex); // pthread_cond_wait(&ClientSocketDataDealThread::cond,&ClientSocketDataDealThread::mutex); // pthread_mutex_unlock(&ClientSocketDataDealThread::mutex); LOGI("%s:clientThread wake ", TAG); _SP_SendToClintStream_INFO *myNode = (_SP_SendToClintStream_INFO *) malloc( sizeof(_SP_SendToClintStream_INFO)); int needRecv = sizeof(_SP_SendToClintStream_INFO); char *buffer = (char *) malloc(needRecv); int pos = 0; int len; while (pos < needRecv) { LOGI("%s:needRecv=%d", TAG,needRecv); len = recv(socketFd, buffer + pos,needRecv, 0); LOGI("%s:len = %d", TAG, len); if (len < 0) { LOGI("%s:Server Recieve Data Failed!", TAG); printf("Server Recieve Data Failed!\n"); // break; } pos += len; } // close(new_server_socket); memcpy(myNode, buffer, needRecv); LOGI("%s:recv over Width=%d Height=%d\n",TAG, myNode->_Width, myNode->_Height); // free(buffer); // free(myNode); // int len = recv(socketFd,getBuffer, sizeof(getBuffer),0); LOGI("%s:get data %s,len = %d", TAG, buffer, len); if (ClientSocketDataDealThread::env != NULL && ClientSocketDataDealThread::obj) { jclass cls = ClientSocketDataDealThread::env->GetObjectClass( ClientSocketDataDealThread::obj); // if(cls == NULL){ // LOGI("%s:find class error",TAG); // pthread_exit(NULL); // } jmethodID mid = ClientSocketDataDealThread::env->GetMethodID(cls, "setRecevieData", "([B)V"); ClientSocketDataDealThread::env->DeleteLocalRef(cls); if (mid == NULL) { LOGI("%s:find method1 error", TAG); pthread_exit(NULL); } jbyteArray jarray = ClientSocketDataDealThread::env->NewByteArray(len); ClientSocketDataDealThread::env->SetByteArrayRegion(jarray, 0, len, (jbyte *) buffer); ClientSocketDataDealThread::env->CallVoidMethod(obj, mid, jarray); ClientSocketDataDealThread::env->DeleteLocalRef(jarray); } } LOGI("%s:ClientSocketDataDealThread exit", TAG); return NULL; } ClientSocketDataDealThread::ClientSocketDataDealThread(int fd, jobject obj1) : threadId(0), sendLength(0) { pthread_mutex_init(&mutex, 0); pthread_cond_init(&cond, 0); socketFd = fd; ClientSocketDataDealThread::obj = obj1; getBuffer = new char[100]; sendBuffer = new char[100]; if (pthread_create(&threadId, NULL, ClientSocketDataDealThread::clientThread, NULL) != 0) { LOGI("%s:pthread_create error", TAG); } LOGI("%s:mSTh->getSocketThreadId():%lu", TAG, (long) threadId); } ClientSocketDataDealThread::~ClientSocketDataDealThread() { delete getBuffer; delete sendBuffer; } void ClientSocketDataDealThread::sendData(char *buff, int length) { LOGI("%s:send data %s,len = %d", TAG, buff, length); int len = send(socketFd, buff, length, 0); if (len < 0) { LOGI("%s:send data error,len = %d", TAG, len); } wakeUpThread(); } pthread_t ClientSocketDataDealThread::getSocketThreadId() { return threadId; } void ClientSocketDataDealThread::wakeUpThread() { pthread_mutex_lock(&ClientSocketDataDealThread::mutex); // 设置条件为真 pthread_cond_signal(&ClientSocketDataDealThread::cond); pthread_mutex_unlock(&ClientSocketDataDealThread::mutex); }
[ "eastrisewm@163.com" ]
eastrisewm@163.com
4c253911adb8759cd97753fe49fbdd27a4a7dea1
1218f0e55768af3c39e4f643ce4e0799c10f19da
/stones.cpp
7738e81f6c6665cbaa0560375958159a78322b57
[]
no_license
ravinderdevesh/codechef
a5c35ea185663506f5e263c05e8262e5106802d8
f3bec3e9691afb552bf3d70e9582947958b20243
refs/heads/master
2021-01-19T19:01:49.612685
2015-02-21T16:37:44
2015-02-21T16:37:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
395
cpp
#include <iostream> #include <stdio.h> using namespace std ; int main () { int T ; scanf("%d" , &T) ; while(T--) { string J , S ; cin >> J ; cin >> S ; int count = 0 ; int lj = J.length() ; int ls = S.length() ; for(int i = 0 ; i < ls ; i++) { for(int j = 0 ; j < lj ; j++) { if(S[i] == J[j]) { count++ ; break ; } } } printf("%d\n" , count) ; } }
[ "amangoeliitb@gmail.com" ]
amangoeliitb@gmail.com
9d04ef85f15833ee0424927374eb3d396631da75
2dc9ab0ec71fd31900173fb15a6f2c85753180c4
/third_party/blink/renderer/core/display_lock/display_lock_document_state.h
d7f9ca8cace4b8c39e2fce5046c82ee9541172d8
[ "LGPL-2.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-1.0-or-later", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft", "MIT", "Apache-2.0", "BSD-3-Clause" ]
permissive
Forilan/chromium
ec337c30d23c22d11fbdf814a40b9b4c26000d78
562b20b68672e7831054ec8f160d5f7ae940eae4
refs/heads/master
2023-02-28T02:43:17.744240
2020-05-12T02:23:44
2020-05-12T02:23:44
231,539,724
0
0
BSD-3-Clause
2020-05-12T02:23:45
2020-01-03T07:52:37
null
UTF-8
C++
false
false
6,029
h
// Copyright 2020 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. #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_DISPLAY_LOCK_DISPLAY_LOCK_DOCUMENT_STATE_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_DISPLAY_LOCK_DISPLAY_LOCK_DOCUMENT_STATE_H_ #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/core/display_lock/display_lock_utilities.h" #include "third_party/blink/renderer/platform/heap/heap.h" #include "third_party/blink/renderer/platform/heap/heap_allocator.h" #include "third_party/blink/renderer/platform/heap/member.h" namespace blink { class DisplayLockContext; class Document; class Element; class IntersectionObserver; class IntersectionObserverEntry; // This class is responsible for keeping document level state for the display // locking feature. class CORE_EXPORT DisplayLockDocumentState final : public GarbageCollected<DisplayLockDocumentState> { public: explicit DisplayLockDocumentState(Document* document); // GC. void Trace(Visitor*); // Registers a display lock context with the state. This is used to force all // activatable locks. void AddDisplayLockContext(DisplayLockContext*); void RemoveDisplayLockContext(DisplayLockContext*); int DisplayLockCount() const; // Bookkeeping: the count of all locked display locks. void AddLockedDisplayLock(); void RemoveLockedDisplayLock(); int LockedDisplayLockCount() const; // Bookkeeping: the count of all locked display locks which block all // activation (i.e. content-visibility: hidden locks). void IncrementDisplayLockBlockingAllActivation(); void DecrementDisplayLockBlockingAllActivation(); int DisplayLockBlockingAllActivationCount() const; // Register the given element for intersection observation. Used for detecting // viewport intersections for content-visibility: auto locks. void RegisterDisplayLockActivationObservation(Element*); void UnregisterDisplayLockActivationObservation(Element*); // Returns true if all activatable locks have been forced. bool ActivatableDisplayLocksForced() const; class ScopedForceActivatableDisplayLocks { STACK_ALLOCATED(); public: ScopedForceActivatableDisplayLocks(ScopedForceActivatableDisplayLocks&&); ~ScopedForceActivatableDisplayLocks(); ScopedForceActivatableDisplayLocks& operator=( ScopedForceActivatableDisplayLocks&&); private: friend DisplayLockDocumentState; explicit ScopedForceActivatableDisplayLocks(DisplayLockDocumentState*); DisplayLockDocumentState* state_; }; ScopedForceActivatableDisplayLocks GetScopedForceActivatableLocks(); // Notify the display locks that selection was removed. void NotifySelectionRemoved(); // This is called when the ScopedChainForcedUpdate is created or destroyed. // This is used to ensure that we can create new locks that are immediately // forced by the existing forced scope. // // Consider the situation A -> B -> C, where C is the child node which is the // target of the forced lock (the parameter passed here), and B is its parent // and A is its grandparent. Suppose that A and B have locks, but since style // was blocked by A, B's lock has not been created yet. When we force the // update from C we call `NotifyNodeForced()`, and A's lock is forced by the // given ScopedChainForcedUpdate. Then we process the style and while // processing B's style, we find that there is a new lock there. This lock // needs to be forced immediately, since it is in the ancestor chain of C. // This is done by calling `ForceLockIfNeeded()` below, which adds B's scope // to the chain. At the end of the scope, everything is un-forced and // `EndNodeForcedScope()` is called to clean up state. // // Note that there can only be one scope created at a time, so we don't keep // track of more than one of these scopes. This is enforced by private access // modifier + friends, as well as DCHECKs. void BeginNodeForcedScope( const Node* node, bool self_was_forced, DisplayLockUtilities::ScopedChainForcedUpdate* scope); void EndNodeForcedScope(DisplayLockUtilities::ScopedChainForcedUpdate* scope); // Forces the lock on the given element, if it isn't yet forced but appears on // the ancestor chain for the forced element (which was set via // `BeginNodeForcedScope()`). void ForceLockIfNeeded(Element*); private: struct ForcedNodeInfo { ForcedNodeInfo(const Node* node, bool self_forced, DisplayLockUtilities::ScopedChainForcedUpdate* scope) : node(node), self_forced(self_forced), scope(scope) {} // Since this is created via a Scoped stack-only object, we know that GC // won't run so this is safe to store as an untraced member. UntracedMember<const Node> node; bool self_forced; DisplayLockUtilities::ScopedChainForcedUpdate* scope; }; IntersectionObserver& EnsureIntersectionObserver(); void ProcessDisplayLockActivationObservation( const HeapVector<Member<IntersectionObserverEntry>>&); void ForceLockIfNeededForInfo(Element*, ForcedNodeInfo*); // Note that since this class is owned by the document, it is important not to // take a strong reference for the backpointer. WeakMember<Document> document_ = nullptr; Member<IntersectionObserver> intersection_observer_ = nullptr; HeapHashSet<WeakMember<DisplayLockContext>> display_lock_contexts_; int locked_display_lock_count_ = 0; int display_lock_blocking_all_activation_count_ = 0; // If greater than 0, then the activatable locks are forced. int activatable_display_locks_forced_ = 0; // Contains all of the currently forced node infos, each of which represents // the node that caused the scope to be created. Vector<ForcedNodeInfo> forced_node_info_; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_CORE_DISPLAY_LOCK_DISPLAY_LOCK_DOCUMENT_STATE_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
de461719b14ba64325d4a0bdc5181b3d63401ef9
62126238af2e3e85b9337f66293c2a29946aa2a1
/framework/Thread/ThreadIOS/Sources/SemaphoreIOS.cpp
94dca5fcd1729a164ed30b4f509b8c7a175fd0de
[ "MIT" ]
permissive
metalkin/kigs
b43aa0385bdd9a495c5e30625c33a170df410593
87d1757da56a5579faf1d511375eccd4503224c7
refs/heads/master
2021-02-28T10:29:30.443801
2020-03-06T13:39:38
2020-03-06T13:51:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
588
cpp
#include "SemaphoreIOS.h" #include "Core.h" IMPLEMENT_CLASS_INFO(SemaphoreIOS) SemaphoreIOS::SemaphoreIOS(const kstl::string& name, CLASS_NAME_TREE_ARG) : Semaphore(name, PASS_CLASS_NAME_TREE_ARG) { pthread_mutex_init(&myMutexLock,0); } SemaphoreIOS::~SemaphoreIOS() { pthread_mutex_destroy(&myMutexLock); } bool SemaphoreIOS::addItem(CoreModifiable *item, ItemPosition pos) { pthread_mutex_lock(&myMutexLock); return true; } bool SemaphoreIOS::removeItem(CoreModifiable *item DECLARE_DEFAULT_LINK_NAME) { pthread_mutex_unlock(&myMutexLock); return true; }
[ "stephane.capo@assoria.com" ]
stephane.capo@assoria.com
7fca6015b98a46de8c88ad9670f2c30b424d1ce2
41ce1bb8f39f17d3500e3d3eece7723948e4ad87
/First term/changingPartsOfArray/stdafx.cpp
ddc6d60c2c7048ff13245c96c3c30a97c37f6c5e
[]
no_license
KanaevaEkaterina/Projects.2012-1
6e5c6edc6c6eaca7dcc115fe418985d69163d6cc
69c32b4021a8b3b7f0c8edbe4fbf54514d1c6f14
refs/heads/master
2021-01-10T18:38:12.555013
2013-05-29T08:16:27
2013-05-29T08:16:27
3,605,254
1
0
null
null
null
null
WINDOWS-1251
C++
false
false
575
cpp
// stdafx.cpp: исходный файл, содержащий только стандартные включаемые модули // homework1.5.pch будет предкомпилированным заголовком // stdafx.obj будет содержать предварительно откомпилированные сведения о типе #include "stdafx.h" // TODO: Установите ссылки на любые требующиеся дополнительные заголовки в файле STDAFX.H // , а не в данном файле
[ "kanaeva.katerina6@gmail.com" ]
kanaeva.katerina6@gmail.com
7acdde4794f58997746ce847d49b42d872517820
d8ae6672046671d5fbdb33c81d557e6384d85731
/src/wallet.cpp
985d588a2bf87931eb4d6533a28d5880eebb8345
[ "GPL-3.0-only", "LicenseRef-scancode-free-unknown", "MIT" ]
permissive
Phikzel2/haroldcoin-main-23-may
74862be1e864e8397c7c0fa6e4b9216ed7d9cdbe
f617bb8aa7dbcce1310312f0062a1caf6ebf268c
refs/heads/main
2023-05-05T08:27:37.573453
2021-05-26T19:32:49
2021-05-26T19:32:49
371,049,557
0
0
MIT
2021-05-26T13:46:30
2021-05-26T13:46:29
null
UTF-8
C++
false
false
132,273
cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Copyright (c) 2017-2018 The haroldcoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "wallet.h" #include "base58.h" #include "checkpoints.h" #include "coincontrol.h" #include "kernel.h" #include "masternode-budget.h" #include "net.h" #include "script/script.h" #include "script/sign.h" #include "spork.h" #include "swifttx.h" #include "timedata.h" #include "util.h" #include "utilmoneystr.h" #include <assert.h> #include <boost/algorithm/string/replace.hpp> #include <boost/thread.hpp> using namespace std; /** * Settings */ CFeeRate payTxFee(DEFAULT_TRANSACTION_FEE); CAmount maxTxFee = DEFAULT_TRANSACTION_MAXFEE; unsigned int nTxConfirmTarget = 1; bool bSpendZeroConfChange = true; bool fSendFreeTransactions = false; bool fPayAtLeastCustomFee = true; /** * Fees smaller than this (in duffs) are considered zero fee (for transaction creation) * We are ~100 times smaller then bitcoin now (2015-06-23), set minTxFee 10 times higher * so it's still 10 times lower comparing to bitcoin. * Override with -mintxfee */ CFeeRate CWallet::minTxFee = CFeeRate(10000); /** @defgroup mapWallet * * @{ */ struct CompareValueOnly { bool operator()(const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t1, const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t2) const { return t1.first < t2.first; } }; std::string COutput::ToString() const { return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString(), i, nDepth, FormatMoney(tx->vout[i].nValue)); } const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const { LOCK(cs_wallet); std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash); if (it == mapWallet.end()) return NULL; return &(it->second); } CPubKey CWallet::GenerateNewKey() { AssertLockHeld(cs_wallet); // mapKeyMetadata bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets RandAddSeedPerfmon(); CKey secret; secret.MakeNewKey(fCompressed); // Compressed public keys were introduced in version 0.6.0 if (fCompressed) SetMinVersion(FEATURE_COMPRPUBKEY); CPubKey pubkey = secret.GetPubKey(); assert(secret.VerifyPubKey(pubkey)); // Create new metadata int64_t nCreationTime = GetTime(); mapKeyMetadata[pubkey.GetID()] = CKeyMetadata(nCreationTime); if (!nTimeFirstKey || nCreationTime < nTimeFirstKey) nTimeFirstKey = nCreationTime; if (!AddKeyPubKey(secret, pubkey)) throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed"); return pubkey; } bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey& pubkey) { AssertLockHeld(cs_wallet); // mapKeyMetadata if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey)) return false; // check if we need to remove from watch-only CScript script; script = GetScriptForDestination(pubkey.GetID()); if (HaveWatchOnly(script)) RemoveWatchOnly(script); if (!fFileBacked) return true; if (!IsCrypted()) { return CWalletDB(strWalletFile).WriteKey(pubkey, secret.GetPrivKey(), mapKeyMetadata[pubkey.GetID()]); } return true; } bool CWallet::AddCryptedKey(const CPubKey& vchPubKey, const vector<unsigned char>& vchCryptedSecret) { if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret)) return false; if (!fFileBacked) return true; { LOCK(cs_wallet); if (pwalletdbEncryption) return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]); else return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]); } return false; } bool CWallet::LoadKeyMetadata(const CPubKey& pubkey, const CKeyMetadata& meta) { AssertLockHeld(cs_wallet); // mapKeyMetadata if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey)) nTimeFirstKey = meta.nCreateTime; mapKeyMetadata[pubkey.GetID()] = meta; return true; } bool CWallet::LoadCryptedKey(const CPubKey& vchPubKey, const std::vector<unsigned char>& vchCryptedSecret) { return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); } bool CWallet::AddCScript(const CScript& redeemScript) { if (!CCryptoKeyStore::AddCScript(redeemScript)) return false; if (!fFileBacked) return true; return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript); } bool CWallet::LoadCScript(const CScript& redeemScript) { /* A sanity check was added in pull #3843 to avoid adding redeemScripts * that never can be redeemed. However, old wallets may still contain * these. Do not add them to the wallet and warn. */ if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE) { std::string strAddr = CBitcoinAddress(CScriptID(redeemScript)).ToString(); LogPrintf("%s: Warning: This wallet contains a redeemScript of size %i which exceeds maximum size %i thus can never be redeemed. Do not use address %s.\n", __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr); return true; } return CCryptoKeyStore::AddCScript(redeemScript); } bool CWallet::AddWatchOnly(const CScript& dest) { if (!CCryptoKeyStore::AddWatchOnly(dest)) return false; nTimeFirstKey = 1; // No birthday information for watch-only keys. NotifyWatchonlyChanged(true); if (!fFileBacked) return true; return CWalletDB(strWalletFile).WriteWatchOnly(dest); } bool CWallet::RemoveWatchOnly(const CScript& dest) { AssertLockHeld(cs_wallet); if (!CCryptoKeyStore::RemoveWatchOnly(dest)) return false; if (!HaveWatchOnly()) NotifyWatchonlyChanged(false); if (fFileBacked) if (!CWalletDB(strWalletFile).EraseWatchOnly(dest)) return false; return true; } bool CWallet::LoadWatchOnly(const CScript& dest) { return CCryptoKeyStore::AddWatchOnly(dest); } bool CWallet::AddMultiSig(const CScript& dest) { if (!CCryptoKeyStore::AddMultiSig(dest)) return false; nTimeFirstKey = 1; // No birthday information NotifyMultiSigChanged(true); if (!fFileBacked) return true; return CWalletDB(strWalletFile).WriteMultiSig(dest); } bool CWallet::RemoveMultiSig(const CScript& dest) { AssertLockHeld(cs_wallet); if (!CCryptoKeyStore::RemoveMultiSig(dest)) return false; if (!HaveMultiSig()) NotifyMultiSigChanged(false); if (fFileBacked) if (!CWalletDB(strWalletFile).EraseMultiSig(dest)) return false; return true; } bool CWallet::LoadMultiSig(const CScript& dest) { return CCryptoKeyStore::AddMultiSig(dest); } bool CWallet::Unlock(const SecureString& strWalletPassphrase, bool anonymizeOnly) { SecureString strWalletPassphraseFinal; if (!IsLocked()) { fWalletUnlockAnonymizeOnly = anonymizeOnly; return true; } strWalletPassphraseFinal = strWalletPassphrase; CCrypter crypter; CKeyingMaterial vMasterKey; { LOCK(cs_wallet); BOOST_FOREACH (const MasterKeyMap::value_type& pMasterKey, mapMasterKeys) { if (!crypter.SetKeyFromPassphrase(strWalletPassphraseFinal, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod)) return false; if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey)) continue; // try another master key if (CCryptoKeyStore::Unlock(vMasterKey)) { fWalletUnlockAnonymizeOnly = anonymizeOnly; return true; } } } return false; } bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase) { bool fWasLocked = IsLocked(); SecureString strOldWalletPassphraseFinal = strOldWalletPassphrase; { LOCK(cs_wallet); Lock(); CCrypter crypter; CKeyingMaterial vMasterKey; BOOST_FOREACH (MasterKeyMap::value_type& pMasterKey, mapMasterKeys) { if (!crypter.SetKeyFromPassphrase(strOldWalletPassphraseFinal, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod)) return false; if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey)) return false; if (CCryptoKeyStore::Unlock(vMasterKey)) { int64_t nStartTime = GetTimeMillis(); crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod); pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime))); nStartTime = GetTimeMillis(); crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod); pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2; if (pMasterKey.second.nDeriveIterations < 25000) pMasterKey.second.nDeriveIterations = 25000; LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations); if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod)) return false; if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey)) return false; CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second); if (fWasLocked) Lock(); return true; } } } return false; } void CWallet::SetBestChain(const CBlockLocator& loc) { CWalletDB walletdb(strWalletFile); walletdb.WriteBestBlock(loc); } bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit) { LOCK(cs_wallet); // nWalletVersion if (nWalletVersion >= nVersion) return true; // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way if (fExplicit && nVersion > nWalletMaxVersion) nVersion = FEATURE_LATEST; nWalletVersion = nVersion; if (nVersion > nWalletMaxVersion) nWalletMaxVersion = nVersion; if (fFileBacked) { CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile); if (nWalletVersion > 40000) pwalletdb->WriteMinVersion(nWalletVersion); if (!pwalletdbIn) delete pwalletdb; } return true; } bool CWallet::SetMaxVersion(int nVersion) { LOCK(cs_wallet); // nWalletVersion, nWalletMaxVersion // cannot downgrade below current version if (nWalletVersion > nVersion) return false; nWalletMaxVersion = nVersion; return true; } set<uint256> CWallet::GetConflicts(const uint256& txid) const { set<uint256> result; AssertLockHeld(cs_wallet); std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid); if (it == mapWallet.end()) return result; const CWalletTx& wtx = it->second; std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range; BOOST_FOREACH (const CTxIn& txin, wtx.vin) { if (mapTxSpends.count(txin.prevout) <= 1) continue; // No conflict if zero or one spends range = mapTxSpends.equal_range(txin.prevout); for (TxSpends::const_iterator it = range.first; it != range.second; ++it) result.insert(it->second); } return result; } void CWallet::SyncMetaData(pair<TxSpends::iterator, TxSpends::iterator> range) { // We want all the wallet transactions in range to have the same metadata as // the oldest (smallest nOrderPos). // So: find smallest nOrderPos: int nMinOrderPos = std::numeric_limits<int>::max(); const CWalletTx* copyFrom = NULL; for (TxSpends::iterator it = range.first; it != range.second; ++it) { const uint256& hash = it->second; int n = mapWallet[hash].nOrderPos; if (n < nMinOrderPos) { nMinOrderPos = n; copyFrom = &mapWallet[hash]; } } // Now copy data from copyFrom to rest: for (TxSpends::iterator it = range.first; it != range.second; ++it) { const uint256& hash = it->second; CWalletTx* copyTo = &mapWallet[hash]; if (copyFrom == copyTo) continue; copyTo->mapValue = copyFrom->mapValue; copyTo->vOrderForm = copyFrom->vOrderForm; // fTimeReceivedIsTxTime not copied on purpose // nTimeReceived not copied on purpose copyTo->nTimeSmart = copyFrom->nTimeSmart; copyTo->fFromMe = copyFrom->fFromMe; copyTo->strFromAccount = copyFrom->strFromAccount; // nOrderPos not copied on purpose // cached members not copied on purpose } } /** * Outpoint is spent if any non-conflicted transaction * spends it: */ bool CWallet::IsSpent(const uint256& hash, unsigned int n) const { const COutPoint outpoint(hash, n); pair<TxSpends::const_iterator, TxSpends::const_iterator> range; range = mapTxSpends.equal_range(outpoint); for (TxSpends::const_iterator it = range.first; it != range.second; ++it) { const uint256& wtxid = it->second; std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid); if (mit != mapWallet.end() && mit->second.GetDepthInMainChain() >= 0) return true; // Spent } return false; } void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid) { mapTxSpends.insert(make_pair(outpoint, wtxid)); pair<TxSpends::iterator, TxSpends::iterator> range; range = mapTxSpends.equal_range(outpoint); SyncMetaData(range); } void CWallet::AddToSpends(const uint256& wtxid) { assert(mapWallet.count(wtxid)); CWalletTx& thisTx = mapWallet[wtxid]; if (thisTx.IsCoinBase()) // Coinbases don't spend anything! return; BOOST_FOREACH (const CTxIn& txin, thisTx.vin) AddToSpends(txin.prevout, wtxid); } bool CWallet::GetMasternodeVinAndKeys(CTxIn& txinRet, CPubKey& pubKeyRet, CKey& keyRet, std::string strTxHash, std::string strOutputIndex) { // wait for reindex and/or import to finish if (fImporting || fReindex) return false; // Find possible candidates std::vector<COutput> vPossibleCoins; AvailableCoins(vPossibleCoins, true, NULL, false, ONLY_10000); if (vPossibleCoins.empty()) { LogPrintf("CWallet::GetMasternodeVinAndKeys -- Could not locate any valid masternode vin\n"); return false; } if (strTxHash.empty()) // No output specified, select the first one return GetVinAndKeysFromOutput(vPossibleCoins[0], txinRet, pubKeyRet, keyRet); // Find specific vin uint256 txHash = uint256S(strTxHash); int nOutputIndex; try { nOutputIndex = std::stoi(strOutputIndex.c_str()); } catch (const std::exception& e) { LogPrintf("%s: %s on strOutputIndex\n", __func__, e.what()); return false; } BOOST_FOREACH (COutput& out, vPossibleCoins) if (out.tx->GetHash() == txHash && out.i == nOutputIndex) // found it! return GetVinAndKeysFromOutput(out, txinRet, pubKeyRet, keyRet); LogPrintf("CWallet::GetMasternodeVinAndKeys -- Could not locate specified masternode vin\n"); return false; } bool CWallet::GetVinAndKeysFromOutput(COutput out, CTxIn& txinRet, CPubKey& pubKeyRet, CKey& keyRet) { // wait for reindex and/or import to finish if (fImporting || fReindex) return false; CScript pubScript; txinRet = CTxIn(out.tx->GetHash(), out.i); pubScript = out.tx->vout[out.i].scriptPubKey; // the inputs PubKey CTxDestination address1; ExtractDestination(pubScript, address1); CBitcoinAddress address2(address1); CKeyID keyID; if (!address2.GetKeyID(keyID)) { LogPrintf("CWallet::GetVinAndKeysFromOutput -- Address does not refer to a key\n"); return false; } if (!GetKey(keyID, keyRet)) { LogPrintf("CWallet::GetVinAndKeysFromOutput -- Private key for address is not known\n"); return false; } pubKeyRet = keyRet.GetPubKey(); return true; } bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase) { if (IsCrypted()) return false; CKeyingMaterial vMasterKey; RandAddSeedPerfmon(); vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE); GetRandBytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE); CMasterKey kMasterKey; RandAddSeedPerfmon(); kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE); GetRandBytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE); CCrypter crypter; int64_t nStartTime = GetTimeMillis(); crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod); kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime)); nStartTime = GetTimeMillis(); crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod); kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2; if (kMasterKey.nDeriveIterations < 25000) kMasterKey.nDeriveIterations = 25000; LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations); if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod)) return false; if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey)) return false; { LOCK(cs_wallet); mapMasterKeys[++nMasterKeyMaxID] = kMasterKey; if (fFileBacked) { assert(!pwalletdbEncryption); pwalletdbEncryption = new CWalletDB(strWalletFile); if (!pwalletdbEncryption->TxnBegin()) { delete pwalletdbEncryption; pwalletdbEncryption = NULL; return false; } pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey); } if (!EncryptKeys(vMasterKey)) { if (fFileBacked) { pwalletdbEncryption->TxnAbort(); delete pwalletdbEncryption; } // We now probably have half of our keys encrypted in memory, and half not... // die and let the user reload their unencrypted wallet. assert(false); } // Encryption was introduced in version 0.4.0 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true); if (fFileBacked) { if (!pwalletdbEncryption->TxnCommit()) { delete pwalletdbEncryption; // We now have keys encrypted in memory, but not on disk... // die to avoid confusion and let the user reload their unencrypted wallet. assert(false); } delete pwalletdbEncryption; pwalletdbEncryption = NULL; } Lock(); Unlock(strWalletPassphrase); NewKeyPool(); Lock(); // Need to completely rewrite the wallet file; if we don't, bdb might keep // bits of the unencrypted private key in slack space in the database file. CDB::Rewrite(strWalletFile); } NotifyStatusChanged(this); return true; } int64_t CWallet::IncOrderPosNext(CWalletDB* pwalletdb) { AssertLockHeld(cs_wallet); // nOrderPosNext int64_t nRet = nOrderPosNext++; if (pwalletdb) { pwalletdb->WriteOrderPosNext(nOrderPosNext); } else { CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext); } return nRet; } CWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount) { AssertLockHeld(cs_wallet); // mapWallet CWalletDB walletdb(strWalletFile); // First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap. TxItems txOrdered; // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry // would make this much faster for applications that do this a lot. for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { CWalletTx* wtx = &((*it).second); txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0))); } acentries.clear(); walletdb.ListAccountCreditDebit(strAccount, acentries); BOOST_FOREACH (CAccountingEntry& entry, acentries) { txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry))); } return txOrdered; } void CWallet::MarkDirty() { { LOCK(cs_wallet); BOOST_FOREACH (PAIRTYPE(const uint256, CWalletTx) & item, mapWallet) item.second.MarkDirty(); } } bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFromLoadWallet) { uint256 hash = wtxIn.GetHash(); if (fFromLoadWallet) { mapWallet[hash] = wtxIn; mapWallet[hash].BindWallet(this); AddToSpends(hash); } else { LOCK(cs_wallet); // Inserts only if not already there, returns tx inserted or tx found pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn)); CWalletTx& wtx = (*ret.first).second; wtx.BindWallet(this); bool fInsertedNew = ret.second; if (fInsertedNew) { wtx.nTimeReceived = GetAdjustedTime(); wtx.nOrderPos = IncOrderPosNext(); wtx.nTimeSmart = wtx.nTimeReceived; if (wtxIn.hashBlock != 0) { if (mapBlockIndex.count(wtxIn.hashBlock)) { int64_t latestNow = wtx.nTimeReceived; int64_t latestEntry = 0; { // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future int64_t latestTolerated = latestNow + 300; std::list<CAccountingEntry> acentries; TxItems txOrdered = OrderedTxItems(acentries); for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) { CWalletTx* const pwtx = (*it).second.first; if (pwtx == &wtx) continue; CAccountingEntry* const pacentry = (*it).second.second; int64_t nSmartTime; if (pwtx) { nSmartTime = pwtx->nTimeSmart; if (!nSmartTime) nSmartTime = pwtx->nTimeReceived; } else nSmartTime = pacentry->nTime; if (nSmartTime <= latestTolerated) { latestEntry = nSmartTime; if (nSmartTime > latestNow) latestNow = nSmartTime; break; } } } int64_t blocktime = mapBlockIndex[wtxIn.hashBlock]->GetBlockTime(); wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow)); } else LogPrintf("AddToWallet() : found %s in block %s not in index\n", wtxIn.GetHash().ToString(), wtxIn.hashBlock.ToString()); } AddToSpends(hash); } bool fUpdated = false; if (!fInsertedNew) { // Merge if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock) { wtx.hashBlock = wtxIn.hashBlock; fUpdated = true; } if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex)) { wtx.vMerkleBranch = wtxIn.vMerkleBranch; wtx.nIndex = wtxIn.nIndex; fUpdated = true; } if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe) { wtx.fFromMe = wtxIn.fFromMe; fUpdated = true; } } //// debug print LogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : "")); // Write to disk if (fInsertedNew || fUpdated) if (!wtx.WriteToDisk()) return false; // Break debit/credit balance caches: wtx.MarkDirty(); // Notify UI of new or updated transaction NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED); // notify an external script when a wallet transaction comes in or is updated std::string strCmd = GetArg("-walletnotify", ""); if (!strCmd.empty()) { boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex()); boost::thread t(runCommand, strCmd); // thread runs free } } return true; } /** * Add a transaction to the wallet, or update it. * pblock is optional, but should be provided if the transaction is known to be in a block. * If fUpdate is true, existing transactions will be updated. */ bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate) { { AssertLockHeld(cs_wallet); bool fExisted = mapWallet.count(tx.GetHash()) != 0; if (fExisted && !fUpdate) return false; if (fExisted || IsMine(tx) || IsFromMe(tx)) { CWalletTx wtx(this, tx); // Get merkle branch if transaction was found in a block if (pblock) wtx.SetMerkleBranch(*pblock); return AddToWallet(wtx); } } return false; } void CWallet::SyncTransaction(const CTransaction& tx, const CBlock* pblock) { LOCK2(cs_main, cs_wallet); if (!AddToWalletIfInvolvingMe(tx, pblock, true)) return; // Not one of ours // If a transaction changes 'conflicted' state, that changes the balance // available of the outputs it spends. So force those to be // recomputed, also: BOOST_FOREACH (const CTxIn& txin, tx.vin) { if (mapWallet.count(txin.prevout.hash)) mapWallet[txin.prevout.hash].MarkDirty(); } } void CWallet::EraseFromWallet(const uint256& hash) { if (!fFileBacked) return; { LOCK(cs_wallet); if (mapWallet.erase(hash)) CWalletDB(strWalletFile).EraseTx(hash); } return; } isminetype CWallet::IsMine(const CTxIn& txin) const { { LOCK(cs_wallet); map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash); if (mi != mapWallet.end()) { const CWalletTx& prev = (*mi).second; if (txin.prevout.n < prev.vout.size()) return IsMine(prev.vout[txin.prevout.n]); } } return ISMINE_NO; } CAmount CWallet::GetDebit(const CTxIn& txin, const isminefilter& filter) const { { LOCK(cs_wallet); map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash); if (mi != mapWallet.end()) { const CWalletTx& prev = (*mi).second; if (txin.prevout.n < prev.vout.size()) if (IsMine(prev.vout[txin.prevout.n]) & filter) return prev.vout[txin.prevout.n].nValue; } } return 0; } // Recursively determine the rounds of a given input (How deep is the Obfuscation chain for a given input) int CWallet::GetRealInputObfuscationRounds(CTxIn in, int rounds) const { static std::map<uint256, CMutableTransaction> mDenomWtxes; if (rounds >= 16) return 15; // 16 rounds max uint256 hash = in.prevout.hash; unsigned int nout = in.prevout.n; const CWalletTx* wtx = GetWalletTx(hash); if (wtx != NULL) { std::map<uint256, CMutableTransaction>::const_iterator mdwi = mDenomWtxes.find(hash); // not known yet, let's add it if (mdwi == mDenomWtxes.end()) { LogPrint("obfuscation", "GetInputObfuscationRounds INSERTING %s\n", hash.ToString()); mDenomWtxes[hash] = CMutableTransaction(*wtx); } // found and it's not an initial value, just return it else if (mDenomWtxes[hash].vout[nout].nRounds != -10) { return mDenomWtxes[hash].vout[nout].nRounds; } // bounds check if (nout >= wtx->vout.size()) { // should never actually hit this LogPrint("obfuscation", "GetInputObfuscationRounds UPDATED %s %3d %3d\n", hash.ToString(), nout, -4); return -4; } if (pwalletMain->IsCollateralAmount(wtx->vout[nout].nValue)) { mDenomWtxes[hash].vout[nout].nRounds = -3; LogPrint("obfuscation", "GetInputObfuscationRounds UPDATED %s %3d %3d\n", hash.ToString(), nout, mDenomWtxes[hash].vout[nout].nRounds); return mDenomWtxes[hash].vout[nout].nRounds; } //make sure the final output is non-denominate if (/*rounds == 0 && */ !IsDenominatedAmount(wtx->vout[nout].nValue)) //NOT DENOM { mDenomWtxes[hash].vout[nout].nRounds = -2; LogPrint("obfuscation", "GetInputObfuscationRounds UPDATED %s %3d %3d\n", hash.ToString(), nout, mDenomWtxes[hash].vout[nout].nRounds); return mDenomWtxes[hash].vout[nout].nRounds; } bool fAllDenoms = true; BOOST_FOREACH (CTxOut out, wtx->vout) { fAllDenoms = fAllDenoms && IsDenominatedAmount(out.nValue); } // this one is denominated but there is another non-denominated output found in the same tx if (!fAllDenoms) { mDenomWtxes[hash].vout[nout].nRounds = 0; LogPrint("obfuscation", "GetInputObfuscationRounds UPDATED %s %3d %3d\n", hash.ToString(), nout, mDenomWtxes[hash].vout[nout].nRounds); return mDenomWtxes[hash].vout[nout].nRounds; } int nShortest = -10; // an initial value, should be no way to get this by calculations bool fDenomFound = false; // only denoms here so let's look up BOOST_FOREACH (CTxIn in2, wtx->vin) { if (IsMine(in2)) { int n = GetRealInputObfuscationRounds(in2, rounds + 1); // denom found, find the shortest chain or initially assign nShortest with the first found value if (n >= 0 && (n < nShortest || nShortest == -10)) { nShortest = n; fDenomFound = true; } } } mDenomWtxes[hash].vout[nout].nRounds = fDenomFound ? (nShortest >= 15 ? 16 : nShortest + 1) // good, we a +1 to the shortest one but only 16 rounds max allowed : 0; // too bad, we are the fist one in that chain LogPrint("obfuscation", "GetInputObfuscationRounds UPDATED %s %3d %3d\n", hash.ToString(), nout, mDenomWtxes[hash].vout[nout].nRounds); return mDenomWtxes[hash].vout[nout].nRounds; } return rounds - 1; } // respect current settings int CWallet::GetInputObfuscationRounds(CTxIn in) const { LOCK(cs_wallet); int realObfuscationRounds = GetRealInputObfuscationRounds(in, 0); return realObfuscationRounds > nObfuscationRounds ? nObfuscationRounds : realObfuscationRounds; } bool CWallet::IsDenominated(const CTxIn& txin) const { { LOCK(cs_wallet); map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash); if (mi != mapWallet.end()) { const CWalletTx& prev = (*mi).second; if (txin.prevout.n < prev.vout.size()) return IsDenominatedAmount(prev.vout[txin.prevout.n].nValue); } } return false; } bool CWallet::IsDenominated(const CTransaction& tx) const { /* Return false if ANY inputs are non-denom */ bool ret = true; BOOST_FOREACH (const CTxIn& txin, tx.vin) { if (!IsDenominated(txin)) { ret = false; } } return ret; } bool CWallet::IsDenominatedAmount(CAmount nInputAmount) const { BOOST_FOREACH (CAmount d, obfuScationDenominations) if (nInputAmount == d) return true; return false; } bool CWallet::IsChange(const CTxOut& txout) const { // TODO: fix handling of 'change' outputs. The assumption is that any // payment to a script that is ours, but is not in the address book // is change. That assumption is likely to break when we implement multisignature // wallets that return change back into a multi-signature-protected address; // a better way of identifying which outputs are 'the send' and which are // 'the change' will need to be implemented (maybe extend CWalletTx to remember // which output, if any, was change). if (::IsMine(*this, txout.scriptPubKey)) { CTxDestination address; if (!ExtractDestination(txout.scriptPubKey, address)) return true; LOCK(cs_wallet); if (!mapAddressBook.count(address)) return true; } return false; } int64_t CWalletTx::GetTxTime() const { int64_t n = nTimeSmart; return n ? n : nTimeReceived; } int CWalletTx::GetRequestCount() const { // Returns -1 if it wasn't being tracked int nRequests = -1; { LOCK(pwallet->cs_wallet); if (IsCoinBase()) { // Generated block if (hashBlock != 0) { map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock); if (mi != pwallet->mapRequestCount.end()) nRequests = (*mi).second; } } else { // Did anyone request this transaction? map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash()); if (mi != pwallet->mapRequestCount.end()) { nRequests = (*mi).second; // How about the block it's in? if (nRequests == 0 && hashBlock != 0) { map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock); if (mi != pwallet->mapRequestCount.end()) nRequests = (*mi).second; else nRequests = 1; // If it's in someone else's block it must have got out } } } } return nRequests; } void CWalletTx::GetAmounts(list<COutputEntry>& listReceived, list<COutputEntry>& listSent, CAmount& nFee, string& strSentAccount, const isminefilter& filter) const { nFee = 0; listReceived.clear(); listSent.clear(); strSentAccount = strFromAccount; // Compute fee: CAmount nDebit = GetDebit(filter); if (nDebit > 0) // debit>0 means we signed/sent this transaction { CAmount nValueOut = GetValueOut(); nFee = nDebit - nValueOut; } // Sent/received. for (unsigned int i = 0; i < vout.size(); ++i) { const CTxOut& txout = vout[i]; isminetype fIsMine = pwallet->IsMine(txout); // Only need to handle txouts if AT LEAST one of these is true: // 1) they debit from us (sent) // 2) the output is to us (received) if (nDebit > 0) { // Don't report 'change' txouts if (pwallet->IsChange(txout)) continue; } else if (!(fIsMine & filter)) continue; // In either case, we need to get the destination address CTxDestination address; if (!ExtractDestination(txout.scriptPubKey, address)) { LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n", this->GetHash().ToString()); address = CNoDestination(); } COutputEntry output = {address, txout.nValue, (int)i}; // If we are debited by the transaction, add the output as a "sent" entry if (nDebit > 0) listSent.push_back(output); // If we are receiving the output, add it as a "received" entry if (fIsMine & filter) listReceived.push_back(output); } } void CWalletTx::GetAccountAmounts(const string& strAccount, CAmount& nReceived, CAmount& nSent, CAmount& nFee, const isminefilter& filter) const { nReceived = nSent = nFee = 0; CAmount allFee; string strSentAccount; list<COutputEntry> listReceived; list<COutputEntry> listSent; GetAmounts(listReceived, listSent, allFee, strSentAccount, filter); if (strAccount == strSentAccount) { BOOST_FOREACH (const COutputEntry& s, listSent) nSent += s.amount; nFee = allFee; } { LOCK(pwallet->cs_wallet); BOOST_FOREACH (const COutputEntry& r, listReceived) { if (pwallet->mapAddressBook.count(r.destination)) { map<CTxDestination, CAddressBookData>::const_iterator mi = pwallet->mapAddressBook.find(r.destination); if (mi != pwallet->mapAddressBook.end() && (*mi).second.name == strAccount) nReceived += r.amount; } else if (strAccount.empty()) { nReceived += r.amount; } } } } bool CWalletTx::WriteToDisk() { return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this); } /** * Scan the block chain (starting in pindexStart) for transactions * from or to us. If fUpdate is true, found transactions that already * exist in the wallet will be updated. */ int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate) { int ret = 0; int64_t nNow = GetTime(); CBlockIndex* pindex = pindexStart; { LOCK2(cs_main, cs_wallet); // no need to read and scan block, if block was created before // our wallet birthday (as adjusted for block time variability) while (pindex && nTimeFirstKey && (pindex->GetBlockTime() < (nTimeFirstKey - 7200))) pindex = chainActive.Next(pindex); ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup double dProgressStart = Checkpoints::GuessVerificationProgress(pindex, false); double dProgressTip = Checkpoints::GuessVerificationProgress(chainActive.Tip(), false); while (pindex) { if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0) ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((Checkpoints::GuessVerificationProgress(pindex, false) - dProgressStart) / (dProgressTip - dProgressStart) * 100)))); CBlock block; ReadBlockFromDisk(block, pindex); BOOST_FOREACH (CTransaction& tx, block.vtx) { if (AddToWalletIfInvolvingMe(tx, &block, fUpdate)) ret++; } pindex = chainActive.Next(pindex); if (GetTime() >= nNow + 60) { nNow = GetTime(); LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, Checkpoints::GuessVerificationProgress(pindex)); } } ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI } return ret; } void CWallet::ReacceptWalletTransactions() { LOCK2(cs_main, cs_wallet); BOOST_FOREACH (PAIRTYPE(const uint256, CWalletTx) & item, mapWallet) { const uint256& wtxid = item.first; CWalletTx& wtx = item.second; assert(wtx.GetHash() == wtxid); int nDepth = wtx.GetDepthInMainChain(); if (!wtx.IsCoinBase() && nDepth < 0) { // Try to add to memory pool LOCK(mempool.cs); wtx.AcceptToMemoryPool(false); } } } bool CWalletTx::InMempool() const { LOCK(mempool.cs); if (mempool.exists(GetHash())) { return true; } return false; } void CWalletTx::RelayWalletTransaction(std::string strCommand) { if (!IsCoinBase()) { if (GetDepthInMainChain() == 0) { uint256 hash = GetHash(); LogPrintf("Relaying wtx %s\n", hash.ToString()); if (strCommand == "ix") { mapTxLockReq.insert(make_pair(hash, (CTransaction) * this)); CreateNewLock(((CTransaction) * this)); RelayTransactionLockReq((CTransaction) * this, true); } else { RelayTransaction((CTransaction) * this); } } } } set<uint256> CWalletTx::GetConflicts() const { set<uint256> result; if (pwallet != NULL) { uint256 myHash = GetHash(); result = pwallet->GetConflicts(myHash); result.erase(myHash); } return result; } void CWallet::ResendWalletTransactions() { // Do this infrequently and randomly to avoid giving away // that these are our transactions. if (GetTime() < nNextResend) return; bool fFirst = (nNextResend == 0); nNextResend = GetTime() + GetRand(30 * 60); if (fFirst) return; // Only do it if there's been a new block since last time if (nTimeBestReceived < nLastResend) return; nLastResend = GetTime(); // Rebroadcast any of our txes that aren't in a block yet LogPrintf("ResendWalletTransactions()\n"); { LOCK(cs_wallet); // Sort them in chronological order multimap<unsigned int, CWalletTx*> mapSorted; BOOST_FOREACH (PAIRTYPE(const uint256, CWalletTx) & item, mapWallet) { CWalletTx& wtx = item.second; // Don't rebroadcast until it's had plenty of time that // it should have gotten in already by now. if (nTimeBestReceived - (int64_t)wtx.nTimeReceived > 5 * 60) mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx)); } BOOST_FOREACH (PAIRTYPE(const unsigned int, CWalletTx*) & item, mapSorted) { CWalletTx& wtx = *item.second; wtx.RelayWalletTransaction(); } } } /** @} */ // end of mapWallet /** @defgroup Actions * * @{ */ CAmount CWallet::GetBalance() const { CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsTrusted()) nTotal += pcoin->GetAvailableCredit(); } } return nTotal; } CAmount CWallet::GetAnonymizableBalance() const { if (fLiteMode) return 0; CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsTrusted()) nTotal += pcoin->GetAnonymizableCredit(); } } return nTotal; } CAmount CWallet::GetAnonymizedBalance() const { if (fLiteMode) return 0; CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsTrusted()) nTotal += pcoin->GetAnonymizedCredit(); } } return nTotal; } // Note: calculated including unconfirmed, // that's ok as long as we use it for informational purposes only double CWallet::GetAverageAnonymizedRounds() const { if (fLiteMode) return 0; double fTotal = 0; double fCount = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; uint256 hash = (*it).first; for (unsigned int i = 0; i < pcoin->vout.size(); i++) { CTxIn vin = CTxIn(hash, i); if (IsSpent(hash, i) || IsMine(pcoin->vout[i]) != ISMINE_SPENDABLE || !IsDenominated(vin)) continue; int rounds = GetInputObfuscationRounds(vin); fTotal += (float)rounds; fCount += 1; } } } if (fCount == 0) return 0; return fTotal / fCount; } // Note: calculated including unconfirmed, // that's ok as long as we use it for informational purposes only CAmount CWallet::GetNormalizedAnonymizedBalance() const { if (fLiteMode) return 0; CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; uint256 hash = (*it).first; for (unsigned int i = 0; i < pcoin->vout.size(); i++) { CTxIn vin = CTxIn(hash, i); if (IsSpent(hash, i) || IsMine(pcoin->vout[i]) != ISMINE_SPENDABLE || !IsDenominated(vin)) continue; if (pcoin->GetDepthInMainChain() < 0) continue; int rounds = GetInputObfuscationRounds(vin); nTotal += pcoin->vout[i].nValue * rounds / nObfuscationRounds; } } } return nTotal; } CAmount CWallet::GetDenominatedBalance(bool unconfirmed) const { if (fLiteMode) return 0; CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; nTotal += pcoin->GetDenominatedCredit(unconfirmed); } } return nTotal; } CAmount CWallet::GetUnconfirmedBalance() const { CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (!IsFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0)) nTotal += pcoin->GetAvailableCredit(); } } return nTotal; } CAmount CWallet::GetImmatureBalance() const { CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; nTotal += pcoin->GetImmatureCredit(); } } return nTotal; } CAmount CWallet::GetWatchOnlyBalance() const { CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsTrusted()) nTotal += pcoin->GetAvailableWatchOnlyCredit(); } } return nTotal; } CAmount CWallet::GetUnconfirmedWatchOnlyBalance() const { CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (!IsFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0)) nTotal += pcoin->GetAvailableWatchOnlyCredit(); } } return nTotal; } CAmount CWallet::GetImmatureWatchOnlyBalance() const { CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; nTotal += pcoin->GetImmatureWatchOnlyCredit(); } } return nTotal; } /** * populate vCoins with vector of available COutputs. */ void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl* coinControl, bool fIncludeZeroValue, AvailableCoinsType nCoinType, bool fUseIX) const { vCoins.clear(); { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const uint256& wtxid = it->first; const CWalletTx* pcoin = &(*it).second; if (!CheckFinalTx(*pcoin)) continue; if (fOnlyConfirmed && !pcoin->IsTrusted()) continue; if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0) continue; int nDepth = pcoin->GetDepthInMainChain(false); // do not use IX for inputs that have less then 6 blockchain confirmations if (fUseIX && nDepth < 6) continue; // We should not consider coins which aren't at least in our mempool // It's possible for these to be conflicted via ancestors which we may never be able to detect if (nDepth == 0 && !pcoin->InMempool()) continue; for (unsigned int i = 0; i < pcoin->vout.size(); i++) { bool found = false; if (nCoinType == ONLY_DENOMINATED) { found = IsDenominatedAmount(pcoin->vout[i].nValue); } else if (nCoinType == ONLY_NOT10000IFMN) { found = !(fMasterNode && pcoin->vout[i].nValue == 50000 * COIN); } else if (nCoinType == ONLY_NONDENOMINATED_NOT10000IFMN) { if (IsCollateralAmount(pcoin->vout[i].nValue)) continue; // do not use collateral amounts found = !IsDenominatedAmount(pcoin->vout[i].nValue); if (found && fMasterNode) found = pcoin->vout[i].nValue != 50000 * COIN; // do not use Hot MN funds } else if (nCoinType == ONLY_10000) { found = pcoin->vout[i].nValue == 50000 * COIN; } else { found = true; } if (!found) continue; isminetype mine = IsMine(pcoin->vout[i]); if (IsSpent(wtxid, i)) continue; if (mine == ISMINE_NO) continue; if (mine == ISMINE_WATCH_ONLY) continue; if (IsLockedCoin((*it).first, i) && nCoinType != ONLY_10000) continue; if (pcoin->vout[i].nValue <= 0 && !fIncludeZeroValue) continue; if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs && !coinControl->IsSelected((*it).first, i)) continue; bool fIsSpendable = false; if ((mine & ISMINE_SPENDABLE) != ISMINE_NO) fIsSpendable = true; if ((mine & ISMINE_MULTISIG) != ISMINE_NO) fIsSpendable = true; vCoins.emplace_back(COutput(pcoin, i, nDepth, fIsSpendable)); } } } } map<CBitcoinAddress, vector<COutput> > CWallet::AvailableCoinsByAddress(bool fConfirmed, CAmount maxCoinValue) { vector<COutput> vCoins; AvailableCoins(vCoins, fConfirmed); map<CBitcoinAddress, vector<COutput> > mapCoins; BOOST_FOREACH (COutput out, vCoins) { if (maxCoinValue > 0 && out.tx->vout[out.i].nValue > maxCoinValue) continue; CTxDestination address; if (!ExtractDestination(out.tx->vout[out.i].scriptPubKey, address)) continue; mapCoins[CBitcoinAddress(address)].push_back(out); } return mapCoins; } static void ApproximateBestSubset(vector<pair<CAmount, pair<const CWalletTx*, unsigned int> > > vValue, const CAmount& nTotalLower, const CAmount& nTargetValue, vector<char>& vfBest, CAmount& nBest, int iterations = 1000) { vector<char> vfIncluded; vfBest.assign(vValue.size(), true); nBest = nTotalLower; seed_insecure_rand(); for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++) { vfIncluded.assign(vValue.size(), false); CAmount nTotal = 0; bool fReachedTarget = false; for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++) { for (unsigned int i = 0; i < vValue.size(); i++) { //The solver here uses a randomized algorithm, //the randomness serves no real security purpose but is just //needed to prevent degenerate behavior and it is important //that the rng is fast. We do not use a constant random sequence, //because there may be some privacy improvement by making //the selection random. if (nPass == 0 ? insecure_rand() & 1 : !vfIncluded[i]) { nTotal += vValue[i].first; vfIncluded[i] = true; if (nTotal >= nTargetValue) { fReachedTarget = true; if (nTotal < nBest) { nBest = nTotal; vfBest = vfIncluded; } nTotal -= vValue[i].first; vfIncluded[i] = false; } } } } } } // TODO: find appropriate place for this sort function // move denoms down bool less_then_denom(const COutput& out1, const COutput& out2) { const CWalletTx* pcoin1 = out1.tx; const CWalletTx* pcoin2 = out2.tx; bool found1 = false; bool found2 = false; BOOST_FOREACH (CAmount d, obfuScationDenominations) // loop through predefined denoms { if (pcoin1->vout[out1.i].nValue == d) found1 = true; if (pcoin2->vout[out2.i].nValue == d) found2 = true; } return (!found1 && found2); } bool CWallet::SelectStakeCoins(std::set<std::pair<const CWalletTx*, unsigned int> >& setCoins, CAmount nTargetAmount) const { vector<COutput> vCoins; AvailableCoins(vCoins, true); int64_t nAmountSelected = 0; BOOST_FOREACH (const COutput& out, vCoins) { //make sure not to outrun target amount if (nAmountSelected + out.tx->vout[out.i].nValue > nTargetAmount) continue; //check for min age if (GetTime() - out.tx->GetTxTime() < nStakeMinAge) continue; //check that it is matured if (out.nDepth < (out.tx->IsCoinStake() ? Params().COINBASE_MATURITY() : 10)) continue; //add to our stake set setCoins.insert(make_pair(out.tx, out.i)); nAmountSelected += out.tx->vout[out.i].nValue; } return true; } bool CWallet::MintableCoins() { CAmount nBalance = GetBalance(); if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance)) return error("MintableCoins() : invalid reserve balance amount"); if (nBalance <= nReserveBalance) return false; vector<COutput> vCoins; AvailableCoins(vCoins, true); BOOST_FOREACH (const COutput& out, vCoins) { if (GetTime() - out.tx->GetTxTime() > nStakeMinAge) return true; } return false; } bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, int nConfMine, int nConfTheirs, vector<COutput> vCoins, set<pair<const CWalletTx*, unsigned int> >& setCoinsRet, CAmount& nValueRet) const { setCoinsRet.clear(); nValueRet = 0; // List of values less than target pair<CAmount, pair<const CWalletTx*, unsigned int> > coinLowestLarger; coinLowestLarger.first = std::numeric_limits<CAmount>::max(); coinLowestLarger.second.first = NULL; vector<pair<CAmount, pair<const CWalletTx*, unsigned int> > > vValue; CAmount nTotalLower = 0; random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt); // move denoms down on the list sort(vCoins.begin(), vCoins.end(), less_then_denom); // try to find nondenom first to prevent unneeded spending of mixed coins for (unsigned int tryDenom = 0; tryDenom < 2; tryDenom++) { if (fDebug) LogPrint("selectcoins", "tryDenom: %d\n", tryDenom); vValue.clear(); nTotalLower = 0; BOOST_FOREACH (const COutput& output, vCoins) { if (!output.fSpendable) continue; const CWalletTx* pcoin = output.tx; // if (fDebug) LogPrint("selectcoins", "value %s confirms %d\n", FormatMoney(pcoin->vout[output.i].nValue), output.nDepth); if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs)) continue; int i = output.i; CAmount n = pcoin->vout[i].nValue; if (tryDenom == 0 && IsDenominatedAmount(n)) continue; // we don't want denom values on first run pair<CAmount, pair<const CWalletTx*, unsigned int> > coin = make_pair(n, make_pair(pcoin, i)); if (n == nTargetValue) { setCoinsRet.insert(coin.second); nValueRet += coin.first; return true; } else if (n < nTargetValue + CENT) { vValue.push_back(coin); nTotalLower += n; } else if (n < coinLowestLarger.first) { coinLowestLarger = coin; } } if (nTotalLower == nTargetValue) { for (unsigned int i = 0; i < vValue.size(); ++i) { setCoinsRet.insert(vValue[i].second); nValueRet += vValue[i].first; } return true; } if (nTotalLower < nTargetValue) { if (coinLowestLarger.second.first == NULL) // there is no input larger than nTargetValue { if (tryDenom == 0) // we didn't look at denom yet, let's do it continue; else // we looked at everything possible and didn't find anything, no luck return false; } setCoinsRet.insert(coinLowestLarger.second); nValueRet += coinLowestLarger.first; return true; } // nTotalLower > nTargetValue break; } // Solve subset sum by stochastic approximation sort(vValue.rbegin(), vValue.rend(), CompareValueOnly()); vector<char> vfBest; CAmount nBest; ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000); if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT) ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000); // If we have a bigger coin and (either the stochastic approximation didn't find a good solution, // or the next bigger coin is closer), return the bigger coin if (coinLowestLarger.second.first && ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest)) { setCoinsRet.insert(coinLowestLarger.second); nValueRet += coinLowestLarger.first; } else { string s = "CWallet::SelectCoinsMinConf best subset: "; for (unsigned int i = 0; i < vValue.size(); i++) { if (vfBest[i]) { setCoinsRet.insert(vValue[i].second); nValueRet += vValue[i].first; s += FormatMoney(vValue[i].first) + " "; } } LogPrintf("%s - total %s\n", s, FormatMoney(nBest)); } return true; } bool CWallet::SelectCoins(const CAmount& nTargetValue, set<pair<const CWalletTx*, unsigned int> >& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl, AvailableCoinsType coin_type, bool useIX) const { // Note: this function should never be used for "always free" tx types like dstx vector<COutput> vCoins; AvailableCoins(vCoins, true, coinControl, false, coin_type, useIX); // coin control -> return all selected outputs (we want all selected to go into the transaction for sure) if (coinControl && coinControl->HasSelected()) { BOOST_FOREACH (const COutput& out, vCoins) { if (!out.fSpendable) continue; if (coin_type == ONLY_DENOMINATED) { CTxIn vin = CTxIn(out.tx->GetHash(), out.i); int rounds = GetInputObfuscationRounds(vin); // make sure it's actually anonymized if (rounds < nObfuscationRounds) continue; } nValueRet += out.tx->vout[out.i].nValue; setCoinsRet.insert(make_pair(out.tx, out.i)); } return (nValueRet >= nTargetValue); } //if we're doing only denominated, we need to round up to the nearest .1 HRLD if (coin_type == ONLY_DENOMINATED) { // Make outputs by looping through denominations, from large to small BOOST_FOREACH (CAmount v, obfuScationDenominations) { BOOST_FOREACH (const COutput& out, vCoins) { if (out.tx->vout[out.i].nValue == v //make sure it's the denom we're looking for && nValueRet + out.tx->vout[out.i].nValue < nTargetValue + (0.1 * COIN) + 100 //round the amount up to .1 HRLD over ) { CTxIn vin = CTxIn(out.tx->GetHash(), out.i); int rounds = GetInputObfuscationRounds(vin); // make sure it's actually anonymized if (rounds < nObfuscationRounds) continue; nValueRet += out.tx->vout[out.i].nValue; setCoinsRet.insert(make_pair(out.tx, out.i)); } } } return (nValueRet >= nTargetValue); } return (SelectCoinsMinConf(nTargetValue, 1, 6, vCoins, setCoinsRet, nValueRet) || SelectCoinsMinConf(nTargetValue, 1, 1, vCoins, setCoinsRet, nValueRet) || (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue, 0, 1, vCoins, setCoinsRet, nValueRet))); } struct CompareByPriority { bool operator()(const COutput& t1, const COutput& t2) const { return t1.Priority() > t2.Priority(); } }; bool CWallet::SelectCoinsByDenominations(int nDenom, CAmount nValueMin, CAmount nValueMax, std::vector<CTxIn>& vCoinsRet, std::vector<COutput>& vCoinsRet2, CAmount& nValueRet, int nObfuscationRoundsMin, int nObfuscationRoundsMax) { vCoinsRet.clear(); nValueRet = 0; vCoinsRet2.clear(); vector<COutput> vCoins; AvailableCoins(vCoins, true, NULL, ONLY_DENOMINATED); std::random_shuffle(vCoins.rbegin(), vCoins.rend()); //keep track of each denomination that we have bool fFound10000 = false; bool fFound1000 = false; bool fFound100 = false; bool fFound10 = false; bool fFound1 = false; bool fFoundDot1 = false; //Check to see if any of the denomination are off, in that case mark them as fulfilled if (!(nDenom & (1 << 0))) fFound10000 = true; if (!(nDenom & (1 << 1))) fFound1000 = true; if (!(nDenom & (1 << 2))) fFound100 = true; if (!(nDenom & (1 << 3))) fFound10 = true; if (!(nDenom & (1 << 4))) fFound1 = true; if (!(nDenom & (1 << 5))) fFoundDot1 = true; BOOST_FOREACH (const COutput& out, vCoins) { // masternode-like input should not be selected by AvailableCoins now anyway //if(out.tx->vout[out.i].nValue == 10000*COIN) continue; if (nValueRet + out.tx->vout[out.i].nValue <= nValueMax) { bool fAccepted = false; // Function returns as follows: // // bit 0 - 10000 HRLD+1 ( bit on if present ) // bit 1 - 1000 HRLD+1 // bit 2 - 100 HRLD+1 // bit 3 - 10 HRLD+1 // bit 4 - 1 HRLD+1 // bit 5 - .1 HRLD+1 CTxIn vin = CTxIn(out.tx->GetHash(), out.i); int rounds = GetInputObfuscationRounds(vin); if (rounds >= nObfuscationRoundsMax) continue; if (rounds < nObfuscationRoundsMin) continue; if (fFound10000 && fFound1000 && fFound100 && fFound10 && fFound1 && fFoundDot1) { //if fulfilled //we can return this for submission if (nValueRet >= nValueMin) { //random reduce the max amount we'll submit for anonymity nValueMax -= (rand() % (nValueMax / 5)); //on average use 50% of the inputs or less int r = (rand() % (int)vCoins.size()); if ((int)vCoinsRet.size() > r) return true; } //Denomination criterion has been met, we can take any matching denominations if ((nDenom & (1 << 0)) && out.tx->vout[out.i].nValue == ((10000 * COIN) + 10000000)) { fAccepted = true; } else if ((nDenom & (1 << 1)) && out.tx->vout[out.i].nValue == ((1000 * COIN) + 1000000)) { fAccepted = true; } else if ((nDenom & (1 << 2)) && out.tx->vout[out.i].nValue == ((100 * COIN) + 100000)) { fAccepted = true; } else if ((nDenom & (1 << 3)) && out.tx->vout[out.i].nValue == ((10 * COIN) + 10000)) { fAccepted = true; } else if ((nDenom & (1 << 4)) && out.tx->vout[out.i].nValue == ((1 * COIN) + 1000)) { fAccepted = true; } else if ((nDenom & (1 << 5)) && out.tx->vout[out.i].nValue == ((.1 * COIN) + 100)) { fAccepted = true; } } else { //Criterion has not been satisfied, we will only take 1 of each until it is. if ((nDenom & (1 << 0)) && out.tx->vout[out.i].nValue == ((10000 * COIN) + 10000000)) { fAccepted = true; fFound10000 = true; } else if ((nDenom & (1 << 1)) && out.tx->vout[out.i].nValue == ((1000 * COIN) + 1000000)) { fAccepted = true; fFound1000 = true; } else if ((nDenom & (1 << 2)) && out.tx->vout[out.i].nValue == ((100 * COIN) + 100000)) { fAccepted = true; fFound100 = true; } else if ((nDenom & (1 << 3)) && out.tx->vout[out.i].nValue == ((10 * COIN) + 10000)) { fAccepted = true; fFound10 = true; } else if ((nDenom & (1 << 4)) && out.tx->vout[out.i].nValue == ((1 * COIN) + 1000)) { fAccepted = true; fFound1 = true; } else if ((nDenom & (1 << 5)) && out.tx->vout[out.i].nValue == ((.1 * COIN) + 100)) { fAccepted = true; fFoundDot1 = true; } } if (!fAccepted) continue; vin.prevPubKey = out.tx->vout[out.i].scriptPubKey; // the inputs PubKey nValueRet += out.tx->vout[out.i].nValue; vCoinsRet.push_back(vin); vCoinsRet2.push_back(out); } } return (nValueRet >= nValueMin && fFound10000 && fFound1000 && fFound100 && fFound10 && fFound1 && fFoundDot1); } bool CWallet::SelectCoinsDark(CAmount nValueMin, CAmount nValueMax, std::vector<CTxIn>& setCoinsRet, CAmount& nValueRet, int nObfuscationRoundsMin, int nObfuscationRoundsMax) const { CCoinControl* coinControl = NULL; setCoinsRet.clear(); nValueRet = 0; vector<COutput> vCoins; AvailableCoins(vCoins, true, coinControl, nObfuscationRoundsMin < 0 ? ONLY_NONDENOMINATED_NOT10000IFMN : ONLY_DENOMINATED); set<pair<const CWalletTx*, unsigned int> > setCoinsRet2; //order the array so largest nondenom are first, then denominations, then very small inputs. sort(vCoins.rbegin(), vCoins.rend(), CompareByPriority()); BOOST_FOREACH (const COutput& out, vCoins) { //do not allow inputs less than 1 CENT if (out.tx->vout[out.i].nValue < CENT) continue; //do not allow collaterals to be selected if (IsCollateralAmount(out.tx->vout[out.i].nValue)) continue; if (fMasterNode && out.tx->vout[out.i].nValue == 50000 * COIN) continue; //masternode input if (nValueRet + out.tx->vout[out.i].nValue <= nValueMax) { CTxIn vin = CTxIn(out.tx->GetHash(), out.i); int rounds = GetInputObfuscationRounds(vin); if (rounds >= nObfuscationRoundsMax) continue; if (rounds < nObfuscationRoundsMin) continue; vin.prevPubKey = out.tx->vout[out.i].scriptPubKey; // the inputs PubKey nValueRet += out.tx->vout[out.i].nValue; setCoinsRet.push_back(vin); setCoinsRet2.insert(make_pair(out.tx, out.i)); } } // if it's more than min, we're good to return if (nValueRet >= nValueMin) return true; return false; } bool CWallet::SelectCoinsCollateral(std::vector<CTxIn>& setCoinsRet, CAmount& nValueRet) const { vector<COutput> vCoins; //LogPrintf(" selecting coins for collateral\n"); AvailableCoins(vCoins); //LogPrintf("found coins %d\n", (int)vCoins.size()); set<pair<const CWalletTx*, unsigned int> > setCoinsRet2; BOOST_FOREACH (const COutput& out, vCoins) { // collateral inputs will always be a multiple of DARSEND_COLLATERAL, up to five if (IsCollateralAmount(out.tx->vout[out.i].nValue)) { CTxIn vin = CTxIn(out.tx->GetHash(), out.i); vin.prevPubKey = out.tx->vout[out.i].scriptPubKey; // the inputs PubKey nValueRet += out.tx->vout[out.i].nValue; setCoinsRet.push_back(vin); setCoinsRet2.insert(make_pair(out.tx, out.i)); return true; } } return false; } int CWallet::CountInputsWithAmount(CAmount nInputAmount) { int64_t nTotal = 0; { LOCK(cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsTrusted()) { int nDepth = pcoin->GetDepthInMainChain(false); for (unsigned int i = 0; i < pcoin->vout.size(); i++) { COutput out = COutput(pcoin, i, nDepth, true); CTxIn vin = CTxIn(out.tx->GetHash(), out.i); if (out.tx->vout[out.i].nValue != nInputAmount) continue; if (!IsDenominatedAmount(pcoin->vout[i].nValue)) continue; if (IsSpent(out.tx->GetHash(), i) || IsMine(pcoin->vout[i]) != ISMINE_SPENDABLE || !IsDenominated(vin)) continue; nTotal++; } } } } return nTotal; } bool CWallet::HasCollateralInputs(bool fOnlyConfirmed) const { vector<COutput> vCoins; AvailableCoins(vCoins, fOnlyConfirmed); int nFound = 0; BOOST_FOREACH (const COutput& out, vCoins) if (IsCollateralAmount(out.tx->vout[out.i].nValue)) nFound++; return nFound > 0; } bool CWallet::IsCollateralAmount(CAmount nInputAmount) const { return nInputAmount != 0 && nInputAmount % OBFUSCATION_COLLATERAL == 0 && nInputAmount < OBFUSCATION_COLLATERAL * 5 && nInputAmount > OBFUSCATION_COLLATERAL; } bool CWallet::CreateCollateralTransaction(CMutableTransaction& txCollateral, std::string& strReason) { /* To doublespend a collateral transaction, it will require a fee higher than this. So there's still a significant cost. */ CAmount nFeeRet = 1 * COIN; txCollateral.vin.clear(); txCollateral.vout.clear(); CReserveKey reservekey(this); CAmount nValueIn2 = 0; std::vector<CTxIn> vCoinsCollateral; if (!SelectCoinsCollateral(vCoinsCollateral, nValueIn2)) { strReason = "Error: Obfuscation requires a collateral transaction and could not locate an acceptable input!"; return false; } // make our change address CScript scriptChange; CPubKey vchPubKey; assert(reservekey.GetReservedKey(vchPubKey)); // should never fail, as we just unlocked scriptChange = GetScriptForDestination(vchPubKey.GetID()); reservekey.KeepKey(); BOOST_FOREACH (CTxIn v, vCoinsCollateral) txCollateral.vin.push_back(v); if (nValueIn2 - OBFUSCATION_COLLATERAL - nFeeRet > 0) { //pay collateral charge in fees CTxOut vout3 = CTxOut(nValueIn2 - OBFUSCATION_COLLATERAL, scriptChange); txCollateral.vout.push_back(vout3); } int vinNumber = 0; BOOST_FOREACH (CTxIn v, txCollateral.vin) { if (!SignSignature(*this, v.prevPubKey, txCollateral, vinNumber, int(SIGHASH_ALL | SIGHASH_ANYONECANPAY))) { BOOST_FOREACH (CTxIn v, vCoinsCollateral) UnlockCoin(v.prevout); strReason = "CObfuscationPool::Sign - Unable to sign collateral transaction! \n"; return false; } vinNumber++; } return true; } bool CWallet::GetBudgetSystemCollateralTX(CTransaction& tx, uint256 hash, bool useIX) { CWalletTx wtx; if (GetBudgetSystemCollateralTX(wtx, hash, useIX)) { tx = (CTransaction)wtx; return true; } return false; } bool CWallet::GetBudgetSystemCollateralTX(CWalletTx& tx, uint256 hash, bool useIX) { // make our change address CReserveKey reservekey(pwalletMain); CScript scriptChange; scriptChange << OP_RETURN << ToByteVector(hash); CAmount nFeeRet = 0; std::string strFail = ""; vector<pair<CScript, CAmount> > vecSend; vecSend.push_back(make_pair(scriptChange, BUDGET_FEE_TX)); CCoinControl* coinControl = NULL; bool success = CreateTransaction(vecSend, tx, reservekey, nFeeRet, strFail, coinControl, ALL_COINS, useIX, (CAmount)0); if (!success) { LogPrintf("GetBudgetSystemCollateralTX: Error - %s\n", strFail); return false; } return true; } bool CWallet::ConvertList(std::vector<CTxIn> vCoins, std::vector<CAmount>& vecAmounts) { BOOST_FOREACH (CTxIn i, vCoins) { if (mapWallet.count(i.prevout.hash)) { CWalletTx& wtx = mapWallet[i.prevout.hash]; if (i.prevout.n < wtx.vout.size()) { vecAmounts.push_back(wtx.vout[i.prevout.n].nValue); } } else { LogPrintf("ConvertList -- Couldn't find transaction\n"); } } return true; } bool CWallet::CreateTransaction(const vector<pair<CScript, CAmount> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, std::string& strFailReason, const CCoinControl* coinControl, AvailableCoinsType coin_type, bool useIX, CAmount nFeePay) { if (useIX && nFeePay < CENT) nFeePay = CENT; CAmount nValue = 0; BOOST_FOREACH (const PAIRTYPE(CScript, CAmount) & s, vecSend) { if (nValue < 0) { strFailReason = _("Transaction amounts must be positive"); return false; } nValue += s.second; } if (vecSend.empty() || nValue < 0) { strFailReason = _("Transaction amounts must be positive"); return false; } wtxNew.fTimeReceivedIsTxTime = true; wtxNew.BindWallet(this); CMutableTransaction txNew; { LOCK2(cs_main, cs_wallet); { nFeeRet = 0; if (nFeePay > 0) nFeeRet = nFeePay; while (true) { txNew.vin.clear(); txNew.vout.clear(); wtxNew.fFromMe = true; CAmount nTotalValue = nValue + nFeeRet; double dPriority = 0; // vouts to the payees if (coinControl && !coinControl->fSplitBlock) { BOOST_FOREACH (const PAIRTYPE(CScript, CAmount) & s, vecSend) { CTxOut txout(s.second, s.first); if (txout.IsDust(::minRelayTxFee)) { strFailReason = _("Transaction amount too small"); return false; } txNew.vout.push_back(txout); } } else //UTXO Splitter Transaction { int nSplitBlock; if (coinControl) nSplitBlock = coinControl->nSplitBlock; else nSplitBlock = 1; BOOST_FOREACH (const PAIRTYPE(CScript, CAmount) & s, vecSend) { for (int i = 0; i < nSplitBlock; i++) { if (i == nSplitBlock - 1) { uint64_t nRemainder = s.second % nSplitBlock; txNew.vout.push_back(CTxOut((s.second / nSplitBlock) + nRemainder, s.first)); } else txNew.vout.push_back(CTxOut(s.second / nSplitBlock, s.first)); } } } // Choose coins to use set<pair<const CWalletTx*, unsigned int> > setCoins; CAmount nValueIn = 0; if (!SelectCoins(nTotalValue, setCoins, nValueIn, coinControl, coin_type, useIX)) { if (coin_type == ALL_COINS) { strFailReason = _("Insufficient funds."); } else if (coin_type == ONLY_NOT10000IFMN) { strFailReason = _("Unable to locate enough funds for this transaction that are not equal 10000 HRLD."); } else if (coin_type == ONLY_NONDENOMINATED_NOT10000IFMN) { strFailReason = _("Unable to locate enough Obfuscation non-denominated funds for this transaction that are not equal 10000 HRLD."); } else { strFailReason = _("Unable to locate enough Obfuscation denominated funds for this transaction."); strFailReason += " " + _("Obfuscation uses exact denominated amounts to send funds, you might simply need to anonymize some more coins."); } if (useIX) { strFailReason += " " + _("SwiftTX requires inputs with at least 6 confirmations, you might need to wait a few minutes and try again."); } return false; } BOOST_FOREACH (PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins) { CAmount nCredit = pcoin.first->vout[pcoin.second].nValue; //The coin age after the next block (depth+1) is used instead of the current, //reflecting an assumption the user would accept a bit more delay for //a chance at a free transaction. //But mempool inputs might still be in the mempool, so their age stays 0 int age = pcoin.first->GetDepthInMainChain(); if (age != 0) age += 1; dPriority += (double)nCredit * age; } CAmount nChange = nValueIn - nValue - nFeeRet; //over pay for denominated transactions if (coin_type == ONLY_DENOMINATED) { nFeeRet += nChange; nChange = 0; wtxNew.mapValue["DS"] = "1"; } if (nChange > 0) { // Fill a vout to ourself // TODO: pass in scriptChange instead of reservekey so // change transaction isn't always pay-to-haroldcoin-address CScript scriptChange; // coin control: send change to custom address if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange)) scriptChange = GetScriptForDestination(coinControl->destChange); // no coin control: send change to newly generated address else { // Note: We use a new key here to keep it from being obvious which side is the change. // The drawback is that by not reusing a previous key, the change may be lost if a // backup is restored, if the backup doesn't have the new private key for the change. // If we reused the old key, it would be possible to add code to look for and // rediscover unknown transactions that were written with keys of ours to recover // post-backup change. // Reserve a new key pair from key pool CPubKey vchPubKey; bool ret; ret = reservekey.GetReservedKey(vchPubKey); assert(ret); // should never fail, as we just unlocked scriptChange = GetScriptForDestination(vchPubKey.GetID()); } CTxOut newTxOut(nChange, scriptChange); // Never create dust outputs; if we would, just // add the dust to the fee. if (newTxOut.IsDust(::minRelayTxFee)) { nFeeRet += nChange; nChange = 0; reservekey.ReturnKey(); } else { // Insert change txn at random position: vector<CTxOut>::iterator position = txNew.vout.begin() + GetRandInt(txNew.vout.size() + 1); txNew.vout.insert(position, newTxOut); } } else reservekey.ReturnKey(); // Fill vin BOOST_FOREACH (const PAIRTYPE(const CWalletTx*, unsigned int) & coin, setCoins) txNew.vin.push_back(CTxIn(coin.first->GetHash(), coin.second)); // Sign int nIn = 0; BOOST_FOREACH (const PAIRTYPE(const CWalletTx*, unsigned int) & coin, setCoins) if (!SignSignature(*this, *coin.first, txNew, nIn++)) { strFailReason = _("Signing transaction failed"); return false; } // Embed the constructed transaction data in wtxNew. *static_cast<CTransaction*>(&wtxNew) = CTransaction(txNew); // Limit size unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION); if (nBytes >= MAX_STANDARD_TX_SIZE) { strFailReason = _("Transaction too large"); return false; } dPriority = wtxNew.ComputePriority(dPriority, nBytes); // Can we complete this as a free transaction? if (fSendFreeTransactions && nBytes <= MAX_FREE_TRANSACTION_CREATE_SIZE) { // Not enough fee: enough priority? double dPriorityNeeded = mempool.estimatePriority(nTxConfirmTarget); // Not enough mempool history to estimate: use hard-coded AllowFree. if (dPriorityNeeded <= 0 && AllowFree(dPriority)) break; // Small enough, and priority high enough, to send for free if (dPriorityNeeded > 0 && dPriority >= dPriorityNeeded) break; } CAmount nFeeNeeded = max(nFeePay, GetMinimumFee(nBytes, nTxConfirmTarget, mempool)); // If we made it here and we aren't even able to meet the relay fee on the next pass, give up // because we must be at the maximum allowed fee. if (nFeeNeeded < ::minRelayTxFee.GetFee(nBytes)) { strFailReason = _("Transaction too large for fee policy"); return false; } if (nFeeRet >= nFeeNeeded) // Done, enough fee included break; // Include more fee and try again. nFeeRet = nFeeNeeded; continue; } } } return true; } bool CWallet::CreateTransaction(CScript scriptPubKey, const CAmount& nValue, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, std::string& strFailReason, const CCoinControl* coinControl, AvailableCoinsType coin_type, bool useIX, CAmount nFeePay) { vector<pair<CScript, CAmount> > vecSend; vecSend.push_back(make_pair(scriptPubKey, nValue)); return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, strFailReason, coinControl, coin_type, useIX, nFeePay); } // ppcoin: create coin stake transaction bool CWallet::CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64_t nSearchInterval, CMutableTransaction& txNew, unsigned int& nTxNewTime) { // The following split & combine thresholds are important to security // Should not be adjusted if you don't understand the consequences //int64_t nCombineThreshold = 0; txNew.vin.clear(); txNew.vout.clear(); // Mark coin stake transaction CScript scriptEmpty; scriptEmpty.clear(); txNew.vout.push_back(CTxOut(0, scriptEmpty)); // Choose coins to use CAmount nBalance = GetBalance(); if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance)) return error("CreateCoinStake : invalid reserve balance amount"); if (nBalance <= nReserveBalance) return false; // presstab HyperStake - Initialize as static and don't update the set on every run of CreateCoinStake() in order to lighten resource use static std::set<pair<const CWalletTx*, unsigned int> > setStakeCoins; static int nLastStakeSetUpdate = 0; if (GetTime() - nLastStakeSetUpdate > nStakeSetUpdateTime) { setStakeCoins.clear(); if (!SelectStakeCoins(setStakeCoins, nBalance - nReserveBalance)) return false; nLastStakeSetUpdate = GetTime(); } if (setStakeCoins.empty()) return false; vector<const CWalletTx*> vwtxPrev; CAmount nCredit = 0; CScript scriptPubKeyKernel; //prevent staking a time that won't be accepted if (GetAdjustedTime() <= chainActive.Tip()->nTime) MilliSleep(10000); BOOST_FOREACH (PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setStakeCoins) { //make sure that enough time has elapsed between CBlockIndex* pindex = NULL; BlockMap::iterator it = mapBlockIndex.find(pcoin.first->hashBlock); if (it != mapBlockIndex.end()) pindex = it->second; else { if (fDebug) LogPrintf("CreateCoinStake() failed to find block index \n"); continue; } // Read block header CBlockHeader block = pindex->GetBlockHeader(); bool fKernelFound = false; uint256 hashProofOfStake = 0; COutPoint prevoutStake = COutPoint(pcoin.first->GetHash(), pcoin.second); nTxNewTime = GetAdjustedTime(); //iterates each utxo inside of CheckStakeKernelHash() if (CheckStakeKernelHash(nBits, block, *pcoin.first, prevoutStake, nTxNewTime, nHashDrift, false, hashProofOfStake, true)) { //Double check that this will pass time requirements if (nTxNewTime <= chainActive.Tip()->GetMedianTimePast()) { LogPrintf("CreateCoinStake() : kernel found, but it is too far in the past \n"); continue; } // Found a kernel if (fDebug && GetBoolArg("-printcoinstake", false)) LogPrintf("CreateCoinStake : kernel found\n"); vector<valtype> vSolutions; txnouttype whichType; CScript scriptPubKeyOut; scriptPubKeyKernel = pcoin.first->vout[pcoin.second].scriptPubKey; if (!Solver(scriptPubKeyKernel, whichType, vSolutions)) { LogPrintf("CreateCoinStake : failed to parse kernel\n"); break; } if (fDebug && GetBoolArg("-printcoinstake", false)) LogPrintf("CreateCoinStake : parsed kernel type=%d\n", whichType); if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH) { if (fDebug && GetBoolArg("-printcoinstake", false)) LogPrintf("CreateCoinStake : no support for kernel type=%d\n", whichType); break; // only support pay to public key and pay to address } if (whichType == TX_PUBKEYHASH) // pay to address type { //convert to pay to public key type CKey key; if (!keystore.GetKey(uint160(vSolutions[0]), key)) { if (fDebug && GetBoolArg("-printcoinstake", false)) LogPrintf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType); break; // unable to find corresponding public key } scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG; } else scriptPubKeyOut = scriptPubKeyKernel; txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second)); nCredit += pcoin.first->vout[pcoin.second].nValue; vwtxPrev.push_back(pcoin.first); txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); //presstab HyperStake - calculate the total size of our new output including the stake reward so that we can use it to decide whether to split the stake outputs const CBlockIndex* pIndex0 = chainActive.Tip(); uint64_t nTotalSize = pcoin.first->vout[pcoin.second].nValue + GetBlockValue(pIndex0->nHeight); //presstab HyperStake - if MultiSend is set to send in coinstake we will add our outputs here (values asigned further down) if (nTotalSize / 2 > nStakeSplitThreshold * COIN) txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); //split stake if (fDebug && GetBoolArg("-printcoinstake", false)) LogPrintf("CreateCoinStake : added kernel type=%d\n", whichType); fKernelFound = true; break; } if (fKernelFound) break; // if kernel is found stop searching } if (nCredit == 0 || nCredit > nBalance - nReserveBalance) return false; // Calculate reward CAmount nReward; const CBlockIndex* pIndex0 = chainActive.Tip(); nReward = GetBlockValue(pIndex0->nHeight); nCredit += nReward; CAmount nMinFee = 0; while (true) { // Set output amount if (txNew.vout.size() == 3) { txNew.vout[1].nValue = ((nCredit - nMinFee) / 2 / CENT) * CENT; txNew.vout[2].nValue = nCredit - nMinFee - txNew.vout[1].nValue; } else txNew.vout[1].nValue = nCredit - nMinFee; // Limit size unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION); if (nBytes >= DEFAULT_BLOCK_MAX_SIZE / 5) return error("CreateCoinStake : exceeded coinstake size limit"); CAmount nFeeNeeded = GetMinimumFee(nBytes, nTxConfirmTarget, mempool); // Check enough fee is paid if (nMinFee < nFeeNeeded) { nMinFee = nFeeNeeded; continue; // try signing again } else { if (fDebug) LogPrintf("CreateCoinStake : fee for coinstake %s\n", FormatMoney(nMinFee).c_str()); break; } } //Masternode payment FillBlockPayee(txNew, nMinFee, true); // Sign int nIn = 0; BOOST_FOREACH (const CWalletTx* pcoin, vwtxPrev) { if (!SignSignature(*this, *pcoin, txNew, nIn++)) return error("CreateCoinStake : failed to sign coinstake"); } // Successfully generated coinstake nLastStakeSetUpdate = 0; //this will trigger stake set to repopulate next round return true; } /** * Call after CreateTransaction unless you want to abort */ bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, std::string strCommand) { { LOCK2(cs_main, cs_wallet); LogPrintf("CommitTransaction:\n%s", wtxNew.ToString()); { // This is only to keep the database open to defeat the auto-flush for the // duration of this scope. This is the only place where this optimization // maybe makes sense; please don't do it anywhere else. CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile, "r") : NULL; // Take key pair from key pool so it won't be used again reservekey.KeepKey(); // Add tx to wallet, because if it has change it's also ours, // otherwise just for transaction history. AddToWallet(wtxNew); // Notify that old coins are spent set<uint256> updated_hahes; BOOST_FOREACH (const CTxIn& txin, wtxNew.vin) { // notify only once if (updated_hahes.find(txin.prevout.hash) != updated_hahes.end()) continue; CWalletTx& coin = mapWallet[txin.prevout.hash]; coin.BindWallet(this); NotifyTransactionChanged(this, txin.prevout.hash, CT_UPDATED); updated_hahes.insert(txin.prevout.hash); } if (fFileBacked) delete pwalletdb; } // Track how many getdata requests our transaction gets mapRequestCount[wtxNew.GetHash()] = 0; // Broadcast if (!wtxNew.AcceptToMemoryPool(false)) { // This must not fail. The transaction has already been signed and recorded. LogPrintf("CommitTransaction() : Error: Transaction not valid\n"); return false; } wtxNew.RelayWalletTransaction(strCommand); } return true; } CAmount CWallet::GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool) { // payTxFee is user-set "I want to pay this much" CAmount nFeeNeeded = payTxFee.GetFee(nTxBytes); // user selected total at least (default=true) if (fPayAtLeastCustomFee && nFeeNeeded > 0 && nFeeNeeded < payTxFee.GetFeePerK()) nFeeNeeded = payTxFee.GetFeePerK(); // User didn't set: use -txconfirmtarget to estimate... if (nFeeNeeded == 0) nFeeNeeded = pool.estimateFee(nConfirmTarget).GetFee(nTxBytes); // ... unless we don't have enough mempool data, in which case fall // back to a hard-coded fee if (nFeeNeeded == 0) nFeeNeeded = minTxFee.GetFee(nTxBytes); // prevent user from paying a non-sense fee (like 1 satoshi): 0 < fee < minRelayFee if (nFeeNeeded < ::minRelayTxFee.GetFee(nTxBytes)) nFeeNeeded = ::minRelayTxFee.GetFee(nTxBytes); // But always obey the maximum if (nFeeNeeded > maxTxFee) nFeeNeeded = maxTxFee; return nFeeNeeded; } CAmount CWallet::GetTotalValue(std::vector<CTxIn> vCoins) { CAmount nTotalValue = 0; CWalletTx wtx; BOOST_FOREACH (CTxIn i, vCoins) { if (mapWallet.count(i.prevout.hash)) { CWalletTx& wtx = mapWallet[i.prevout.hash]; if (i.prevout.n < wtx.vout.size()) { nTotalValue += wtx.vout[i.prevout.n].nValue; } } else { LogPrintf("GetTotalValue -- Couldn't find transaction\n"); } } return nTotalValue; } string CWallet::PrepareObfuscationDenominate(int minRounds, int maxRounds) { if (IsLocked()) return _("Error: Wallet locked, unable to create transaction!"); if (obfuScationPool.GetState() != POOL_STATUS_ERROR && obfuScationPool.GetState() != POOL_STATUS_SUCCESS) if (obfuScationPool.GetEntriesCount() > 0) return _("Error: You already have pending entries in the Obfuscation pool"); // ** find the coins we'll use std::vector<CTxIn> vCoins; std::vector<CTxIn> vCoinsResult; std::vector<COutput> vCoins2; CAmount nValueIn = 0; CReserveKey reservekey(this); /* Select the coins we'll use if minRounds >= 0 it means only denominated inputs are going in and coming out */ if (minRounds >= 0) { if (!SelectCoinsByDenominations(obfuScationPool.sessionDenom, 0.1 * COIN, OBFUSCATION_POOL_MAX, vCoins, vCoins2, nValueIn, minRounds, maxRounds)) return _("Error: Can't select current denominated inputs"); } LogPrintf("PrepareObfuscationDenominate - preparing obfuscation denominate . Got: %d \n", nValueIn); { LOCK(cs_wallet); BOOST_FOREACH (CTxIn v, vCoins) LockCoin(v.prevout); } CAmount nValueLeft = nValueIn; std::vector<CTxOut> vOut; /* TODO: Front load with needed denominations (e.g. .1, 1 ) */ // Make outputs by looping through denominations: try to add every needed denomination, repeat up to 5-10 times. // This way we can be pretty sure that it should have at least one of each needed denomination. // NOTE: No need to randomize order of inputs because they were // initially shuffled in CWallet::SelectCoinsByDenominations already. int nStep = 0; int nStepsMax = 5 + GetRandInt(5); while (nStep < nStepsMax) { BOOST_FOREACH (CAmount v, obfuScationDenominations) { // only use the ones that are approved bool fAccepted = false; if ((obfuScationPool.sessionDenom & (1 << 0)) && v == ((10000 * COIN) + 10000000)) { fAccepted = true; } else if ((obfuScationPool.sessionDenom & (1 << 1)) && v == ((1000 * COIN) + 1000000)) { fAccepted = true; } else if ((obfuScationPool.sessionDenom & (1 << 2)) && v == ((100 * COIN) + 100000)) { fAccepted = true; } else if ((obfuScationPool.sessionDenom & (1 << 3)) && v == ((10 * COIN) + 10000)) { fAccepted = true; } else if ((obfuScationPool.sessionDenom & (1 << 4)) && v == ((1 * COIN) + 1000)) { fAccepted = true; } else if ((obfuScationPool.sessionDenom & (1 << 5)) && v == ((.1 * COIN) + 100)) { fAccepted = true; } if (!fAccepted) continue; // try to add it if (nValueLeft - v >= 0) { // Note: this relies on a fact that both vectors MUST have same size std::vector<CTxIn>::iterator it = vCoins.begin(); std::vector<COutput>::iterator it2 = vCoins2.begin(); while (it2 != vCoins2.end()) { // we have matching inputs if ((*it2).tx->vout[(*it2).i].nValue == v) { // add new input in resulting vector vCoinsResult.push_back(*it); // remove corresponting items from initial vectors vCoins.erase(it); vCoins2.erase(it2); CScript scriptChange; CPubKey vchPubKey; // use a unique change address assert(reservekey.GetReservedKey(vchPubKey)); // should never fail, as we just unlocked scriptChange = GetScriptForDestination(vchPubKey.GetID()); reservekey.KeepKey(); // add new output CTxOut o(v, scriptChange); vOut.push_back(o); // subtract denomination amount nValueLeft -= v; break; } ++it; ++it2; } } } nStep++; if (nValueLeft == 0) break; } { // unlock unused coins LOCK(cs_wallet); BOOST_FOREACH (CTxIn v, vCoins) UnlockCoin(v.prevout); } if (obfuScationPool.GetDenominations(vOut) != obfuScationPool.sessionDenom) { // unlock used coins on failure LOCK(cs_wallet); BOOST_FOREACH (CTxIn v, vCoinsResult) UnlockCoin(v.prevout); return "Error: can't make current denominated outputs"; } // randomize the output order std::random_shuffle(vOut.begin(), vOut.end()); // We also do not care about full amount as long as we have right denominations, just pass what we found obfuScationPool.SendObfuscationDenominate(vCoinsResult, vOut, nValueIn - nValueLeft); return ""; } DBErrors CWallet::LoadWallet(bool& fFirstRunRet) { if (!fFileBacked) return DB_LOAD_OK; fFirstRunRet = false; DBErrors nLoadWalletRet = CWalletDB(strWalletFile, "cr+").LoadWallet(this); if (nLoadWalletRet == DB_NEED_REWRITE) { if (CDB::Rewrite(strWalletFile, "\x04pool")) { LOCK(cs_wallet); setKeyPool.clear(); // Note: can't top-up keypool here, because wallet is locked. // User will be prompted to unlock wallet the next operation // the requires a new key. } } if (nLoadWalletRet != DB_LOAD_OK) return nLoadWalletRet; fFirstRunRet = !vchDefaultKey.IsValid(); uiInterface.LoadWallet(this); return DB_LOAD_OK; } DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx) { if (!fFileBacked) return DB_LOAD_OK; DBErrors nZapWalletTxRet = CWalletDB(strWalletFile, "cr+").ZapWalletTx(this, vWtx); if (nZapWalletTxRet == DB_NEED_REWRITE) { if (CDB::Rewrite(strWalletFile, "\x04pool")) { LOCK(cs_wallet); setKeyPool.clear(); // Note: can't top-up keypool here, because wallet is locked. // User will be prompted to unlock wallet the next operation // that requires a new key. } } if (nZapWalletTxRet != DB_LOAD_OK) return nZapWalletTxRet; return DB_LOAD_OK; } bool CWallet::SetAddressBook(const CTxDestination& address, const string& strName, const string& strPurpose) { bool fUpdated = false; { LOCK(cs_wallet); // mapAddressBook std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address); fUpdated = mi != mapAddressBook.end(); mapAddressBook[address].name = strName; if (!strPurpose.empty()) /* update purpose only if requested */ mapAddressBook[address].purpose = strPurpose; } NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO, strPurpose, (fUpdated ? CT_UPDATED : CT_NEW)); if (!fFileBacked) return false; if (!strPurpose.empty() && !CWalletDB(strWalletFile).WritePurpose(CBitcoinAddress(address).ToString(), strPurpose)) return false; return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName); } bool CWallet::DelAddressBook(const CTxDestination& address) { { LOCK(cs_wallet); // mapAddressBook if (fFileBacked) { // Delete destdata tuples associated with address std::string strAddress = CBitcoinAddress(address).ToString(); BOOST_FOREACH (const PAIRTYPE(string, string) & item, mapAddressBook[address].destdata) { CWalletDB(strWalletFile).EraseDestData(strAddress, item.first); } } mapAddressBook.erase(address); } NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED); if (!fFileBacked) return false; CWalletDB(strWalletFile).ErasePurpose(CBitcoinAddress(address).ToString()); return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString()); } bool CWallet::SetDefaultKey(const CPubKey& vchPubKey) { if (fFileBacked) { if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey)) return false; } vchDefaultKey = vchPubKey; return true; } /** * Mark old keypool keys as used, * and generate all new keys */ bool CWallet::NewKeyPool() { { LOCK(cs_wallet); CWalletDB walletdb(strWalletFile); BOOST_FOREACH (int64_t nIndex, setKeyPool) walletdb.ErasePool(nIndex); setKeyPool.clear(); if (IsLocked()) return false; int64_t nKeys = max(GetArg("-keypool", 1000), (int64_t)0); for (int i = 0; i < nKeys; i++) { int64_t nIndex = i + 1; walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey())); setKeyPool.insert(nIndex); } LogPrintf("CWallet::NewKeyPool wrote %d new keys\n", nKeys); } return true; } bool CWallet::TopUpKeyPool(unsigned int kpSize) { { LOCK(cs_wallet); if (IsLocked()) return false; CWalletDB walletdb(strWalletFile); // Top up key pool unsigned int nTargetSize; if (kpSize > 0) nTargetSize = kpSize; else nTargetSize = max(GetArg("-keypool", 1000), (int64_t)0); while (setKeyPool.size() < (nTargetSize + 1)) { int64_t nEnd = 1; if (!setKeyPool.empty()) nEnd = *(--setKeyPool.end()) + 1; if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey()))) throw runtime_error("TopUpKeyPool() : writing generated key failed"); setKeyPool.insert(nEnd); LogPrintf("keypool added key %d, size=%u\n", nEnd, setKeyPool.size()); double dProgress = 100.f * nEnd / (nTargetSize + 1); std::string strMsg = strprintf(_("Loading wallet... (%3.2f %%)"), dProgress); uiInterface.InitMessage(strMsg); } } return true; } void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool) { nIndex = -1; keypool.vchPubKey = CPubKey(); { LOCK(cs_wallet); if (!IsLocked()) TopUpKeyPool(); // Get the oldest key if (setKeyPool.empty()) return; CWalletDB walletdb(strWalletFile); nIndex = *(setKeyPool.begin()); setKeyPool.erase(setKeyPool.begin()); if (!walletdb.ReadPool(nIndex, keypool)) throw runtime_error("ReserveKeyFromKeyPool() : read failed"); if (!HaveKey(keypool.vchPubKey.GetID())) throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool"); assert(keypool.vchPubKey.IsValid()); LogPrintf("keypool reserve %d\n", nIndex); } } void CWallet::KeepKey(int64_t nIndex) { // Remove from key pool if (fFileBacked) { CWalletDB walletdb(strWalletFile); walletdb.ErasePool(nIndex); } LogPrintf("keypool keep %d\n", nIndex); } void CWallet::ReturnKey(int64_t nIndex) { // Return to key pool { LOCK(cs_wallet); setKeyPool.insert(nIndex); } LogPrintf("keypool return %d\n", nIndex); } bool CWallet::GetKeyFromPool(CPubKey& result) { int64_t nIndex = 0; CKeyPool keypool; { LOCK(cs_wallet); ReserveKeyFromKeyPool(nIndex, keypool); if (nIndex == -1) { if (IsLocked()) return false; result = GenerateNewKey(); return true; } KeepKey(nIndex); result = keypool.vchPubKey; } return true; } int64_t CWallet::GetOldestKeyPoolTime() { int64_t nIndex = 0; CKeyPool keypool; ReserveKeyFromKeyPool(nIndex, keypool); if (nIndex == -1) return GetTime(); ReturnKey(nIndex); return keypool.nTime; } std::map<CTxDestination, CAmount> CWallet::GetAddressBalances() { map<CTxDestination, CAmount> balances; { LOCK(cs_wallet); BOOST_FOREACH (PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet) { CWalletTx* pcoin = &walletEntry.second; if (!IsFinalTx(*pcoin) || !pcoin->IsTrusted()) continue; if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0) continue; int nDepth = pcoin->GetDepthInMainChain(); if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1)) continue; for (unsigned int i = 0; i < pcoin->vout.size(); i++) { CTxDestination addr; if (!IsMine(pcoin->vout[i])) continue; if (!ExtractDestination(pcoin->vout[i].scriptPubKey, addr)) continue; CAmount n = IsSpent(walletEntry.first, i) ? 0 : pcoin->vout[i].nValue; if (!balances.count(addr)) balances[addr] = 0; balances[addr] += n; } } } return balances; } set<set<CTxDestination> > CWallet::GetAddressGroupings() { AssertLockHeld(cs_wallet); // mapWallet set<set<CTxDestination> > groupings; set<CTxDestination> grouping; BOOST_FOREACH (PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet) { CWalletTx* pcoin = &walletEntry.second; if (pcoin->vin.size() > 0) { bool any_mine = false; // group all input addresses with each other BOOST_FOREACH (CTxIn txin, pcoin->vin) { CTxDestination address; if (!IsMine(txin)) /* If this input isn't mine, ignore it */ continue; if (!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address)) continue; grouping.insert(address); any_mine = true; } // group change with input addresses if (any_mine) { BOOST_FOREACH (CTxOut txout, pcoin->vout) if (IsChange(txout)) { CTxDestination txoutAddr; if (!ExtractDestination(txout.scriptPubKey, txoutAddr)) continue; grouping.insert(txoutAddr); } } if (grouping.size() > 0) { groupings.insert(grouping); grouping.clear(); } } // group lone addrs by themselves for (unsigned int i = 0; i < pcoin->vout.size(); i++) if (IsMine(pcoin->vout[i])) { CTxDestination address; if (!ExtractDestination(pcoin->vout[i].scriptPubKey, address)) continue; grouping.insert(address); groupings.insert(grouping); grouping.clear(); } } set<set<CTxDestination>*> uniqueGroupings; // a set of pointers to groups of addresses map<CTxDestination, set<CTxDestination>*> setmap; // map addresses to the unique group containing it BOOST_FOREACH (set<CTxDestination> grouping, groupings) { // make a set of all the groups hit by this new group set<set<CTxDestination>*> hits; map<CTxDestination, set<CTxDestination>*>::iterator it; BOOST_FOREACH (CTxDestination address, grouping) if ((it = setmap.find(address)) != setmap.end()) hits.insert((*it).second); // merge all hit groups into a new single group and delete old groups set<CTxDestination>* merged = new set<CTxDestination>(grouping); BOOST_FOREACH (set<CTxDestination>* hit, hits) { merged->insert(hit->begin(), hit->end()); uniqueGroupings.erase(hit); delete hit; } uniqueGroupings.insert(merged); // update setmap BOOST_FOREACH (CTxDestination element, *merged) setmap[element] = merged; } set<set<CTxDestination> > ret; BOOST_FOREACH (set<CTxDestination>* uniqueGrouping, uniqueGroupings) { ret.insert(*uniqueGrouping); delete uniqueGrouping; } return ret; } set<CTxDestination> CWallet::GetAccountAddresses(string strAccount) const { LOCK(cs_wallet); set<CTxDestination> result; BOOST_FOREACH (const PAIRTYPE(CTxDestination, CAddressBookData) & item, mapAddressBook) { const CTxDestination& address = item.first; const string& strName = item.second.name; if (strName == strAccount) result.insert(address); } return result; } bool CReserveKey::GetReservedKey(CPubKey& pubkey) { if (nIndex == -1) { CKeyPool keypool; pwallet->ReserveKeyFromKeyPool(nIndex, keypool); if (nIndex != -1) vchPubKey = keypool.vchPubKey; else { return false; } } assert(vchPubKey.IsValid()); pubkey = vchPubKey; return true; } void CReserveKey::KeepKey() { if (nIndex != -1) pwallet->KeepKey(nIndex); nIndex = -1; vchPubKey = CPubKey(); } void CReserveKey::ReturnKey() { if (nIndex != -1) pwallet->ReturnKey(nIndex); nIndex = -1; vchPubKey = CPubKey(); } void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const { setAddress.clear(); CWalletDB walletdb(strWalletFile); LOCK2(cs_main, cs_wallet); BOOST_FOREACH (const int64_t& id, setKeyPool) { CKeyPool keypool; if (!walletdb.ReadPool(id, keypool)) throw runtime_error("GetAllReserveKeyHashes() : read failed"); assert(keypool.vchPubKey.IsValid()); CKeyID keyID = keypool.vchPubKey.GetID(); if (!HaveKey(keyID)) throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool"); setAddress.insert(keyID); } } bool CWallet::UpdatedTransaction(const uint256& hashTx) { { LOCK(cs_wallet); // Only notify UI if this transaction is in this wallet map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx); if (mi != mapWallet.end()) { NotifyTransactionChanged(this, hashTx, CT_UPDATED); return true; } } return false; } void CWallet::LockCoin(COutPoint& output) { AssertLockHeld(cs_wallet); // setLockedCoins setLockedCoins.insert(output); } void CWallet::UnlockCoin(COutPoint& output) { AssertLockHeld(cs_wallet); // setLockedCoins setLockedCoins.erase(output); } void CWallet::UnlockAllCoins() { AssertLockHeld(cs_wallet); // setLockedCoins setLockedCoins.clear(); } bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const { AssertLockHeld(cs_wallet); // setLockedCoins COutPoint outpt(hash, n); return (setLockedCoins.count(outpt) > 0); } void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts) { AssertLockHeld(cs_wallet); // setLockedCoins for (std::set<COutPoint>::iterator it = setLockedCoins.begin(); it != setLockedCoins.end(); it++) { COutPoint outpt = (*it); vOutpts.push_back(outpt); } } /** @} */ // end of Actions class CAffectedKeysVisitor : public boost::static_visitor<void> { private: const CKeyStore& keystore; std::vector<CKeyID>& vKeys; public: CAffectedKeysVisitor(const CKeyStore& keystoreIn, std::vector<CKeyID>& vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {} void Process(const CScript& script) { txnouttype type; std::vector<CTxDestination> vDest; int nRequired; if (ExtractDestinations(script, type, vDest, nRequired)) { BOOST_FOREACH (const CTxDestination& dest, vDest) boost::apply_visitor(*this, dest); } } void operator()(const CKeyID& keyId) { if (keystore.HaveKey(keyId)) vKeys.push_back(keyId); } void operator()(const CScriptID& scriptId) { CScript script; if (keystore.GetCScript(scriptId, script)) Process(script); } void operator()(const CNoDestination& none) {} }; void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t>& mapKeyBirth) const { AssertLockHeld(cs_wallet); // mapKeyMetadata mapKeyBirth.clear(); // get birth times for keys with metadata for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++) if (it->second.nCreateTime) mapKeyBirth[it->first] = it->second.nCreateTime; // map in which we'll infer heights of other keys CBlockIndex* pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganised; use a 144-block safety margin std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock; std::set<CKeyID> setKeys; GetKeys(setKeys); BOOST_FOREACH (const CKeyID& keyid, setKeys) { if (mapKeyBirth.count(keyid) == 0) mapKeyFirstBlock[keyid] = pindexMax; } setKeys.clear(); // if there are no such keys, we're done if (mapKeyFirstBlock.empty()) return; // find first block that affects those keys, if there are any left std::vector<CKeyID> vAffected; for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) { // iterate over all wallet transactions... const CWalletTx& wtx = (*it).second; BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock); if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) { // ... which are already in a block int nHeight = blit->second->nHeight; BOOST_FOREACH (const CTxOut& txout, wtx.vout) { // iterate over all their outputs CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey); BOOST_FOREACH (const CKeyID& keyid, vAffected) { // ... and all their affected keys std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid); if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight) rit->second = blit->second; } vAffected.clear(); } } } // Extract block timestamps for those keys for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++) mapKeyBirth[it->first] = it->second->GetBlockTime() - 7200; // block times can be 2h off } bool CWallet::AddDestData(const CTxDestination& dest, const std::string& key, const std::string& value) { if (boost::get<CNoDestination>(&dest)) return false; mapAddressBook[dest].destdata.insert(std::make_pair(key, value)); if (!fFileBacked) return true; return CWalletDB(strWalletFile).WriteDestData(CBitcoinAddress(dest).ToString(), key, value); } bool CWallet::EraseDestData(const CTxDestination& dest, const std::string& key) { if (!mapAddressBook[dest].destdata.erase(key)) return false; if (!fFileBacked) return true; return CWalletDB(strWalletFile).EraseDestData(CBitcoinAddress(dest).ToString(), key); } bool CWallet::LoadDestData(const CTxDestination& dest, const std::string& key, const std::string& value) { mapAddressBook[dest].destdata.insert(std::make_pair(key, value)); return true; } bool CWallet::GetDestData(const CTxDestination& dest, const std::string& key, std::string* value) const { std::map<CTxDestination, CAddressBookData>::const_iterator i = mapAddressBook.find(dest); if (i != mapAddressBook.end()) { CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key); if (j != i->second.destdata.end()) { if (value) *value = j->second; return true; } } return false; } void CWallet::AutoCombineDust() { if (IsInitialBlockDownload() || IsLocked()) { return; } map<CBitcoinAddress, vector<COutput> > mapCoinsByAddress = AvailableCoinsByAddress(true, 0); //coins are sectioned by address. This combination code only wants to combine inputs that belong to the same address for (map<CBitcoinAddress, vector<COutput> >::iterator it = mapCoinsByAddress.begin(); it != mapCoinsByAddress.end(); it++) { vector<COutput> vCoins, vRewardCoins; vCoins = it->second; //find masternode rewards that need to be combined CCoinControl* coinControl = new CCoinControl(); CAmount nTotalRewardsValue = 0; BOOST_FOREACH (const COutput& out, vCoins) { //no coins should get this far if they dont have proper maturity, this is double checking if (out.tx->IsCoinStake() && out.tx->GetDepthInMainChain() < COINBASE_MATURITY + 1) continue; if (out.Value() > nAutoCombineThreshold * COIN) continue; COutPoint outpt(out.tx->GetHash(), out.i); coinControl->Select(outpt); vRewardCoins.push_back(out); nTotalRewardsValue += out.Value(); } //if no inputs found then return if (!coinControl->HasSelected()) continue; //we cannot combine one coin with itself if (vRewardCoins.size() <= 1) continue; vector<pair<CScript, CAmount> > vecSend; CScript scriptPubKey = GetScriptForDestination(it->first.Get()); vecSend.push_back(make_pair(scriptPubKey, nTotalRewardsValue)); // Create the transaction and commit it to the network CWalletTx wtx; CReserveKey keyChange(this); // this change address does not end up being used, because change is returned with coin control switch string strErr; CAmount nFeeRet = 0; //get the fee amount CWalletTx wtxdummy; CreateTransaction(vecSend, wtxdummy, keyChange, nFeeRet, strErr, coinControl, ALL_COINS, false, CAmount(0)); vecSend[0].second = nTotalRewardsValue - nFeeRet - 500; if (!CreateTransaction(vecSend, wtx, keyChange, nFeeRet, strErr, coinControl, ALL_COINS, false, CAmount(0))) { LogPrintf("AutoCombineDust createtransaction failed, reason: %s\n", strErr); continue; } if (!CommitTransaction(wtx, keyChange)) { LogPrintf("AutoCombineDust transaction commit failed\n"); continue; } LogPrintf("AutoCombineDust sent transaction\n"); delete coinControl; } } bool CWallet::MultiSend() { if (IsInitialBlockDownload() || IsLocked()) { return false; } if (chainActive.Tip()->nHeight <= nLastMultiSendHeight) { LogPrintf("Multisend: lastmultisendheight is higher than current best height\n"); return false; } std::vector<COutput> vCoins; AvailableCoins(vCoins); int stakeSent = 0; int mnSent = 0; BOOST_FOREACH (const COutput& out, vCoins) { //need output with precise confirm count - this is how we identify which is the output to send if (out.tx->GetDepthInMainChain() != COINBASE_MATURITY + 1) continue; COutPoint outpoint(out.tx->GetHash(), out.i); bool sendMSonMNReward = fMultiSendMasternodeReward && outpoint.IsMasternodeReward(out.tx); bool sendMSOnStake = fMultiSendStake && out.tx->IsCoinStake() && !sendMSonMNReward; //output is either mnreward or stake reward, not both if (!(sendMSOnStake || sendMSonMNReward)) continue; CTxDestination destMyAddress; if (!ExtractDestination(out.tx->vout[out.i].scriptPubKey, destMyAddress)) { LogPrintf("Multisend: failed to extract destination\n"); continue; } //Disabled Addresses won't send MultiSend transactions if (vDisabledAddresses.size() > 0) { for (unsigned int i = 0; i < vDisabledAddresses.size(); i++) { if (vDisabledAddresses[i] == CBitcoinAddress(destMyAddress).ToString()) { LogPrintf("Multisend: disabled address preventing multisend\n"); return false; } } } // create new coin control, populate it with the selected utxo, create sending vector CCoinControl* cControl = new CCoinControl(); COutPoint outpt(out.tx->GetHash(), out.i); cControl->Select(outpt); cControl->destChange = destMyAddress; CWalletTx wtx; CReserveKey keyChange(this); // this change address does not end up being used, because change is returned with coin control switch CAmount nFeeRet = 0; vector<pair<CScript, CAmount> > vecSend; // loop through multisend vector and add amounts and addresses to the sending vector const isminefilter filter = ISMINE_SPENDABLE; CAmount nAmount = 0; for (unsigned int i = 0; i < vMultiSend.size(); i++) { // MultiSend vector is a pair of 1)Address as a std::string 2) Percent of stake to send as an int nAmount = ((out.tx->GetCredit(filter) - out.tx->GetDebit(filter)) * vMultiSend[i].second) / 100; CBitcoinAddress strAddSend(vMultiSend[i].first); CScript scriptPubKey; scriptPubKey = GetScriptForDestination(strAddSend.Get()); vecSend.push_back(make_pair(scriptPubKey, nAmount)); } //get the fee amount CWalletTx wtxdummy; string strErr; CreateTransaction(vecSend, wtxdummy, keyChange, nFeeRet, strErr, cControl, ALL_COINS, false, CAmount(0)); CAmount nLastSendAmount = vecSend[vecSend.size() - 1].second; if (nLastSendAmount < nFeeRet + 500) { LogPrintf("%s: fee of %s is too large to insert into last output\n"); return false; } vecSend[vecSend.size() - 1].second = nLastSendAmount - nFeeRet - 500; // Create the transaction and commit it to the network if (!CreateTransaction(vecSend, wtx, keyChange, nFeeRet, strErr, cControl, ALL_COINS, false, CAmount(0))) { LogPrintf("MultiSend createtransaction failed\n"); return false; } if (!CommitTransaction(wtx, keyChange)) { LogPrintf("MultiSend transaction commit failed\n"); return false; } else fMultiSendNotify = true; delete cControl; //write nLastMultiSendHeight to DB CWalletDB walletdb(strWalletFile); nLastMultiSendHeight = chainActive.Tip()->nHeight; if (!walletdb.WriteMSettings(fMultiSendStake, fMultiSendMasternodeReward, nLastMultiSendHeight)) LogPrintf("Failed to write MultiSend setting to DB\n"); LogPrintf("MultiSend successfully sent\n"); if (sendMSOnStake) stakeSent++; else mnSent++; //stop iterating if we are done if (mnSent > 0 && stakeSent > 0) return true; if (stakeSent > 0 && !fMultiSendMasternodeReward) return true; if (mnSent > 0 && !fMultiSendStake) return true; } return true; } CKeyPool::CKeyPool() { nTime = GetTime(); } CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn) { nTime = GetTime(); vchPubKey = vchPubKeyIn; } CWalletKey::CWalletKey(int64_t nExpires) { nTimeCreated = (nExpires ? GetTime() : 0); nTimeExpires = nExpires; } int CMerkleTx::SetMerkleBranch(const CBlock& block) { AssertLockHeld(cs_main); CBlock blockTmp; // Update the tx's hashBlock hashBlock = block.GetHash(); // Locate the transaction for (nIndex = 0; nIndex < (int)block.vtx.size(); nIndex++) if (block.vtx[nIndex] == *(CTransaction*)this) break; if (nIndex == (int)block.vtx.size()) { vMerkleBranch.clear(); nIndex = -1; LogPrintf("ERROR: SetMerkleBranch() : couldn't find tx in block\n"); return 0; } // Fill in merkle branch vMerkleBranch = block.GetMerkleBranch(nIndex); // Is the tx in a block that's in the main chain BlockMap::iterator mi = mapBlockIndex.find(hashBlock); if (mi == mapBlockIndex.end()) return 0; const CBlockIndex* pindex = (*mi).second; if (!pindex || !chainActive.Contains(pindex)) return 0; return chainActive.Height() - pindex->nHeight + 1; } int CMerkleTx::GetDepthInMainChainINTERNAL(const CBlockIndex*& pindexRet) const { if (hashBlock == 0 || nIndex == -1) return 0; AssertLockHeld(cs_main); // Find the block it claims to be in BlockMap::iterator mi = mapBlockIndex.find(hashBlock); if (mi == mapBlockIndex.end()) return 0; CBlockIndex* pindex = (*mi).second; if (!pindex || !chainActive.Contains(pindex)) return 0; // Make sure the merkle branch connects to this block if (!fMerkleVerified) { if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot) return 0; fMerkleVerified = true; } pindexRet = pindex; return chainActive.Height() - pindex->nHeight + 1; } int CMerkleTx::GetDepthInMainChain(const CBlockIndex*& pindexRet, bool enableIX) const { AssertLockHeld(cs_main); int nResult = GetDepthInMainChainINTERNAL(pindexRet); if (nResult == 0 && !mempool.exists(GetHash())) return -1; // Not in chain, not in mempool if (enableIX) { if (nResult < 6) { int signatures = GetTransactionLockSignatures(); if (signatures >= SWIFTTX_SIGNATURES_REQUIRED) { return nSwiftTXDepth + nResult; } } } return nResult; } int CMerkleTx::GetBlocksToMaturity() const { if (!(IsCoinBase() || IsCoinStake())) return 0; return max(0, (Params().COINBASE_MATURITY() + 1) - GetDepthInMainChain()); } bool CMerkleTx::AcceptToMemoryPool(bool fLimitFree, bool fRejectInsaneFee, bool ignoreFees) { CValidationState state; return ::AcceptToMemoryPool(mempool, state, *this, fLimitFree, NULL, fRejectInsaneFee, ignoreFees); } int CMerkleTx::GetTransactionLockSignatures() const { if (fLargeWorkForkFound || fLargeWorkInvalidChainFound) return -2; if (!IsSporkActive(SPORK_2_SWIFTTX)) return -3; if (!fEnableSwiftTX) return -1; //compile consessus vote std::map<uint256, CTransactionLock>::iterator i = mapTxLocks.find(GetHash()); if (i != mapTxLocks.end()) { return (*i).second.CountSignatures(); } return -1; } bool CMerkleTx::IsTransactionLockTimedOut() const { if (!fEnableSwiftTX) return 0; //compile consessus vote std::map<uint256, CTransactionLock>::iterator i = mapTxLocks.find(GetHash()); if (i != mapTxLocks.end()) { return GetTime() > (*i).second.nTimeout; } return false; }
[ "76849967+Harold-Coin@users.noreply.github.com" ]
76849967+Harold-Coin@users.noreply.github.com
aec2dc05e56c69e0980256a383fe9fed2b0134d5
6ed471f36e5188f77dc61cca24daa41496a6d4a0
/SDK/PrimalItemConsumable_Kibble_BoaEgg_parameters.h
3a727f17af9ca4be647c885e83ee850a99a66337
[]
no_license
zH4x-SDK/zARKSotF-SDK
77bfaf9b4b9b6a41951ee18db88f826dd720c367
714730f4bb79c07d065181caf360d168761223f6
refs/heads/main
2023-07-16T22:33:15.140456
2021-08-27T13:40:06
2021-08-27T13:40:06
400,521,086
0
0
null
null
null
null
UTF-8
C++
false
false
751
h
#pragma once #include "../SDK.h" // Name: ARKSotF, Version: 178.8.0 #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace SDK { //--------------------------------------------------------------------------- // Parameters //--------------------------------------------------------------------------- // Function PrimalItemConsumable_Kibble_BoaEgg.PrimalItemConsumable_Kibble_BoaEgg_C.ExecuteUbergraph_PrimalItemConsumable_Kibble_BoaEgg struct UPrimalItemConsumable_Kibble_BoaEgg_C_ExecuteUbergraph_PrimalItemConsumable_Kibble_BoaEgg_Params { int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "zp2kshield@gmail.com" ]
zp2kshield@gmail.com
430818d690cd563f4429ee7b3dfa63776df05920
0e5ea03c2455b34a2f416c6c94c1669d7fe26e37
/_2018_03_20 BattleShip 1/WhiteMtrl.h
5a31740c520b0f99867c4cc7e9cd95328c4ecfcb
[]
no_license
Arroria/__old_project
8682652fac9a95898b41eff5b4fdfab023cda699
efb655b2356bd95744ba19093f25ab266a625722
refs/heads/master
2020-09-05T08:02:44.806509
2019-11-06T18:01:23
2019-11-06T18:01:23
220,033,980
1
1
null
null
null
null
UTF-8
C++
false
false
252
h
#pragma once #include "Singleton.h" class WhiteMtrl : public Singleton<WhiteMtrl> { private: D3DMATERIAL9 m_mtrl; public: D3DMATERIAL9 GetMtrl(); public: WhiteMtrl(); ~WhiteMtrl(); }; #define WHITEMTRL (SingletonInstance(WhiteMtrl)->GetMtrl())
[ "mermerkwon@naver.com" ]
mermerkwon@naver.com
fb422b294af9b2d6f1cd6a45ba80e502efa6f39f
980f03e45ac8bfb9f0e2bb78673337f8e7db20e6
/src/InputManager.h
0a50dd499b6236669d2385cd65ff5e0de9f514d1
[]
no_license
synystro/lux2Dengine
699fe1d0ec4ed3fdd012c736203465028e560559
8c5810209cea1539867af58c9f9a96ae6e09b24e
refs/heads/master
2023-04-04T11:26:11.943089
2021-03-30T17:23:51
2021-03-30T17:23:51
353,074,834
0
0
null
null
null
null
UTF-8
C++
false
false
698
h
#pragma once #include <vector> #include <algorithm> #include "./Controls.h" class InputManager { private: std::vector<int> keysPressed; public: bool CheckKeyPressed(int key) { if(std::find(keysPressed.begin(), keysPressed.end(), key) != keysPressed.end()) { return true; } keysPressed.push_back(key); return false; } void SetKeyReleased(int key) { if(std::find(keysPressed.begin(), keysPressed.end(), key) != keysPressed.end()) { keysPressed.erase(std::remove(keysPressed.begin(), keysPressed.end(), key), keysPressed.end()); } } };
[ "pedro_araujo@live.com" ]
pedro_araujo@live.com
7ea2d204374e67e137dc9b0d02e0873fd66a21d1
d5550f431e946e009a88020287966b6813c72053
/数据结构课程设计/迷宫优化/迷宫优化.cpp
335b3105d2dca39d7b69bdefffbaf998fcc39e14
[]
no_license
ZZLZHAO/Data-Structure-Course-Design
e4e486dc4025a1e13db564c7327cd3b0b08462d7
205d2f333b3ccb9c7494715b0ef42813deb0149b
refs/heads/main
2023-05-26T13:32:09.019377
2021-06-04T14:13:47
2021-06-04T14:13:47
null
0
0
null
null
null
null
GB18030
C++
false
false
7,930
cpp
#include<iostream> #include<algorithm> #include<string> #include<vector> #include<cmath> #include<queue> #include <Windows.h> #include <time.h> #include <iomanip> #define N 40 // 棋盘/迷宫 的阶数 #define M 20 // 棋盘/迷宫 的阶数 using namespace std; class Node { public: int x, y; // 节点所在位置 int F, G, H; // G:从起点开始,沿着产的路径,移动到网格上指定方格的移动耗费。 // H:从网格上那个方格移动到终点B的预估移动耗费,使用曼哈顿距离。 // F = G + H Node(int a, int b) :x(a), y(b) {} // 重载操作符,使优先队列以F值大小为标准维持堆 bool operator < (const Node& a) const { return F > a.F; } }; // 定义八个方向 int dir[4][2] = { {-1, 0}, {0, -1}, {0, 1}, {1, 0} }; // 优先队列,就相当于open表 priority_queue<Node>que; // 棋盘 int qp[N][M] = { {0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1} , {0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 1}, {0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1}, {0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1}, {1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1}, {0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1}, {0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1}, {1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1}, {0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1}, {0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0}, {0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 1}, {0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1}, {0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1}, {1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, {0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, {0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0}, {0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0}, {0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 0}, {0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1} , {0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 1}, {0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1}, {0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1}, {1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1}, {0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1}, {0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1}, {1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1}, {0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1}, {0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0}, {0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 1}, {0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1}, {0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1}, {1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, {0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, {0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0}, {0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0}, {0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 0} }; bool visit[N][M]; // 访问情况记录,close表 int valF[N][M]; // 记录每个节点对应的F值 int path[N][M][2]; // 存储每个节点的父节点 int Manhuattan(int x, int y, int x1, int y1); // 计算曼哈顿距离 bool NodeIsLegal(int x, int y, int xx, int yy); // 判断位置合法性 void A_start(int x0, int y0, int x1, int y1); // A*算法 void PrintPath(int x1, int y1); // 打印路径 /* ----------------主函数------------------- */ int main() { fill(visit[0], visit[0] + N * M, false); // 将visit数组赋初值false fill(valF[0], valF[0] + N * M, 0); // 初始化F全为0 fill(path[0][0], path[0][0] + N * M * 2, -1); // 路径同样赋初值-1 // // 起点 // 终点 int x0, y0, x1, y1; cout << "输入起点:"; cin >> x0 >> y0; cout << "输入终点:"; cin >> x1 >> y1; x0--; y0--; x1--; y1--; if (!NodeIsLegal(x0, y0, x0, y0)) { cout << "非法起点!" << endl; return 0; } double run_time; LARGE_INTEGER time_start; //开始时间 LARGE_INTEGER time_over; //结束时间 double dqFreq; //计时器频率 LARGE_INTEGER f; //计时器频率 QueryPerformanceFrequency(&f); dqFreq = (double)f.QuadPart; QueryPerformanceCounter(&time_start); //计时开始 A_start(x0, y0, x1, y1); // A*算法 QueryPerformanceCounter(&time_over); //计时结束 run_time = 1000000 * (time_over.QuadPart - time_start.QuadPart) / dqFreq; //乘以1000000把单位由秒化为微秒,精度为1000000/(cpu主频)微秒 cout << "所用时间: " << run_time << endl; PrintPath(x1, y1); // 打印路径 } /* ----------------自定义函数------------------ */ void A_start(int x0, int y0, int x1, int y1) { // 初始化起点 Node node(x0, y0); node.G = 0; node.H = Manhuattan(x0, y0, x1, y1); node.F = node.G + node.H; valF[x0][y0] = node.F; // 起点加入open表 que.push(node); while (!que.empty()) { Node node_top = que.top(); que.pop(); visit[node_top.x][node_top.y] = true; // 访问该点,加入closed表 if (node_top.x == x1 && node_top.y == y1) // 到达终点 break; // 遍历node_top周围的8个位置 for (int i = 0; i < 4; i++) { Node node_next(node_top.x + dir[i][0], node_top.y + dir[i][1]); // 创建一个node_top周围的节点 // 该节点坐标合法 且 未加入close表 if (NodeIsLegal(node_next.x, node_next.y, node_top.x, node_top.y) && !visit[node_next.x][node_next.y]) { // 计算从起点并经过node_top节点到达该节点所花费的代价 node_next.G = int(abs(node_next.x - x0) + abs(node_next.y - y0)); // 计算该节点到终点的曼哈顿距离 node_next.H = Manhuattan(node_next.x, node_next.y, x1, y1); // 从起点经过node_top和该节点到达终点的估计代价 node_next.F = node_next.G + node_next.H; // node_next.F < valF[node_next.x][node_next.y] 说明找到了更优的路径,则进行更新 // valF[node_next.x][node_next.y] == 0 说明该节点还未加入open表中,则加入 if (node_next.F < valF[node_next.x][node_next.y] || valF[node_next.x][node_next.y] == 0) { // 保存该节点的父节点 path[node_next.x][node_next.y][0] = node_top.x; path[node_next.x][node_next.y][1] = node_top.y; valF[node_next.x][node_next.y] = node_next.F; // 修改该节点对应的valF值 que.push(node_next); // 加入open表 } } } } } void PrintPath(int x1, int y1) { if (path[x1][y1][0] == -1 || path[x1][y1][1] == -1) { cout << "没有可行路径!" << endl; return; } int x = x1, y = y1; int a, b; while (x != -1 || y != -1) { qp[x][y] = 2; // 将可行路径上的节点赋值为2 a = path[x][y][0]; b = path[x][y][1]; x = a; y = b; } // □表示未经过的节点, █表示障碍物, ☆表示可行节点 string s[3] = { "□", "█", "☆" }; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) cout << s[qp[i][j]]; cout << endl; } } int Manhuattan(int x, int y, int x1, int y1) { //return (abs(x - x1) + abs(y - y1)) * 10; return pow(x - x1, 2) + pow(y - y1, 2); } bool NodeIsLegal(int x, int y, int xx, int yy) { if (x < 0 || x >= N || y < 0 || y >= M) return false; // 判断边界 if (qp[x][y] == 1) return false; // 判断障碍物 // 两节点成对角型且它们的公共相邻节点存在障碍物 if (x != xx && y != yy && (qp[x][yy] == 1 || qp[xx][y] == 1)) return false; return true; }
[ "1072117118@qq.com" ]
1072117118@qq.com
2cf5faa0ac801941a562ffef5740446db93e309a
d022883d70d769802dc9f22a5a34759558e06193
/src/network/Server.h
af1cada8ebd3809e63abaf11cd66232ed6eec22d
[]
no_license
sokyu-project/sokyu-node
1599e9859a4b08ec29bba8b1f14230807bed8d3a
c3c3b2968d237e8067ac11bafd142d734c6006da
refs/heads/main
2023-03-02T01:48:24.014655
2021-01-28T05:24:58
2021-01-28T05:24:58
333,637,977
0
0
null
null
null
null
UTF-8
C++
false
false
904
h
#ifndef SERVER_H #define SERVER_H #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <netinet/in.h> #include <thread> #include <atomic> #include <mutex> #include "NetworkHandler.h" // Simple TCP server we will use to communicate with other nodes and respond to requests typedef unsigned char byte; class Server { public: Server(int port); virtual ~Server(); bool init(); bool run(std::unique_ptr<NetworkHandler>& handler); void shutdown(); std::atomic<bool> shouldStop; void addSocket(int newSocket); protected: private: int port; int sockfd; byte buffer[2048]; fd_set clientFds; std::mutex socketsMutex; int clientSockets[50]; int maxClients = 50; struct sockaddr_in servaddr; std::thread sThread; }; #endif // SERVER_H
[ "nnemo288@gmail.com" ]
nnemo288@gmail.com
e3fed17e4f134d3a4586de28c294c9e74c534a9c
4d42762ddb5034b84585170ca320f9903024fa7f
/build/iOS/Debug/include/Fuse.Controls.Panel.h
a25e469abcbeea3d347648186595632321b46bf9
[]
no_license
nikitph/omkareshwar-ios
536def600f378946b95362e2e2f98f8f52b588e0
852a1d802b76dbc61c2c45164f180004b7d667e6
refs/heads/master
2021-01-01T18:58:16.397969
2017-08-01T18:53:20
2017-08-01T18:53:20
98,473,502
0
0
null
null
null
null
UTF-8
C++
false
false
4,656
h
// This file was generated based on '/Users/Omkareshwar/Library/Application Support/Fusetools/Packages/Fuse.Controls.Panels/1.1.1/$.uno'. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Fuse.Animations.IResize.h> #include <Fuse.Binding.h> #include <Fuse.Controls.LayoutControl.h> #include <Fuse.Drawing.ISurfaceDrawable.h> #include <Fuse.IActualPlacement.h> #include <Fuse.INotifyUnrooted.h> #include <Fuse.IProperties.h> #include <Fuse.Node.h> #include <Fuse.Scripting.IScriptObject.h> #include <Fuse.Triggers.Actions.ICollapse.h> #include <Fuse.Triggers.Actions.IHide.h> #include <Fuse.Triggers.Actions.IShow.h> #include <Uno.Collections.ICollection-1.h> #include <Uno.Collections.IEnumerable-1.h> #include <Uno.Collections.IList-1.h> #include <Uno.Float2.h> #include <Uno.UX.IPropertyListener.h> namespace g{namespace Fuse{namespace Controls{struct Panel;}}} namespace g{namespace Fuse{namespace Drawing{struct Surface;}}} namespace g{namespace Fuse{namespace Triggers{struct BusyTask;}}} namespace g{namespace Fuse{struct DrawContext;}} namespace g{namespace Fuse{struct LayoutParams;}} namespace g{namespace Fuse{struct VisualBounds;}} namespace g{namespace Uno{namespace Graphics{struct Framebuffer;}}} namespace g{namespace Uno{namespace UX{struct Selector;}}} namespace g{namespace Uno{struct Float4;}} namespace g{ namespace Fuse{ namespace Controls{ // public partial class Panel :1941 // { struct Panel_type : ::g::Fuse::Controls::Control_type { ::g::Fuse::Drawing::ISurfaceDrawable interface15; }; Panel_type* Panel_typeof(); void Panel__ctor_6_fn(Panel* __this); void Panel__ArrangePaddingBox_fn(Panel* __this, ::g::Fuse::LayoutParams* lp); void Panel__CleanupBuffer_fn(Panel* __this); void Panel__CleanupListener_fn(Panel* __this, bool* nextFrame); void Panel__get_Color_fn(Panel* __this, ::g::Uno::Float4* __retval); void Panel__set_Color_fn(Panel* __this, ::g::Uno::Float4* value); void Panel__get_DeferFreeze_fn(Panel* __this, int* __retval); void Panel__set_DeferFreeze_fn(Panel* __this, int* value); void Panel__Draw_fn(Panel* __this, ::g::Fuse::DrawContext* dc); void Panel__EndBusy_fn(Panel* __this); void Panel__FastTrackDrawWithOpacity_fn(Panel* __this, ::g::Fuse::DrawContext* dc, bool* __retval); void Panel__FreezeRooted_fn(Panel* __this); void Panel__FreezeUnrooted_fn(Panel* __this); void Panel__FuseDrawingISurfaceDrawableDraw_fn(Panel* __this, ::g::Fuse::Drawing::Surface* surface); void Panel__FuseDrawingISurfaceDrawableget_ElementSize_fn(Panel* __this, ::g::Uno::Float2* __retval); void Panel__GetContentSize_fn(Panel* __this, ::g::Fuse::LayoutParams* lp, ::g::Uno::Float2* __retval); void Panel__get_HasFreezePrepared_fn(Panel* __this, bool* __retval); void Panel__get_IsFrozen_fn(Panel* __this, bool* __retval); void Panel__set_IsFrozen_fn(Panel* __this, bool* value); void Panel__get_IsLayoutRoot_fn(Panel* __this, bool* __retval); void Panel__get_LocalRenderBounds_fn(Panel* __this, ::g::Fuse::VisualBounds** __retval); void Panel__New3_fn(Panel** __retval); void Panel__OnColorChanged_fn(Panel* __this, ::g::Uno::Float4* value, uObject* origin); void Panel__OnPrepared_fn(Panel* __this, ::g::Fuse::DrawContext* dc); void Panel__OnRooted_fn(Panel* __this); void Panel__OnUnrooted_fn(Panel* __this); void Panel__get_Scale_fn(Panel* __this, ::g::Uno::Float2* __retval); void Panel__SetColor_fn(Panel* __this, ::g::Uno::Float4* value, uObject* origin); void Panel__SetupListener_fn(Panel* __this); struct Panel : ::g::Fuse::Controls::LayoutControl { int _deferFreeze; bool _freezeAwaitPrepared; uStrong< ::g::Fuse::Triggers::BusyTask*> _freezeBusyTask; ::g::Uno::Float2 _frozenActualSize; uStrong< ::g::Uno::Graphics::Framebuffer*> _frozenBuffer; uStrong< ::g::Fuse::VisualBounds*> _frozenRenderBounds; bool _isFrozen; static ::g::Uno::UX::Selector ColorPropertyName_; static ::g::Uno::UX::Selector& ColorPropertyName() { return Panel_typeof()->Init(), ColorPropertyName_; } void ctor_6(); void CleanupBuffer(); void CleanupListener(bool nextFrame); ::g::Uno::Float4 Color(); void Color(::g::Uno::Float4 value); int DeferFreeze(); void DeferFreeze(int value); void EndBusy(); void FreezeRooted(); void FreezeUnrooted(); bool HasFreezePrepared(); bool IsFrozen(); void IsFrozen(bool value); void OnColorChanged(::g::Uno::Float4 value, uObject* origin); void OnPrepared(::g::Fuse::DrawContext* dc); ::g::Uno::Float2 Scale(); void SetColor(::g::Uno::Float4 value, uObject* origin); void SetupListener(); static Panel* New3(); }; // } }}} // ::g::Fuse::Controls
[ "nikitph@gmail.com" ]
nikitph@gmail.com
bdff174d6932bfe8d17a3678c9bdbae015316d31
b4cf51e23c8bfb31f8a2c2e3de94f25e1b7a3109
/include/afina/Executor.h
dba7c5388e945d311c48a46de005858739c0e5bc
[]
no_license
OlegKafanov/afina
4d77fccaacb2b6b34e379e67a770c198b3584fd1
999549aadbe7d01dc8dd44133e2fc90f4bda2113
refs/heads/master
2021-09-05T10:37:46.443781
2018-01-26T13:38:45
2018-01-26T13:38:45
104,130,309
1
0
null
2017-09-19T21:24:26
2017-09-19T21:24:26
null
UTF-8
C++
false
false
2,775
h
#ifndef AFINA_THREADPOOL_H #define AFINA_THREADPOOL_H #include <condition_variable> #include <functional> #include <memory> #include <mutex> #include <queue> #include <string> #include <thread> namespace Afina { /** * # Thread pool */ class Executor { enum class State { // Threadpool is fully operational, tasks could be added and get executed kRun, // Threadpool is on the way to be shutdown, no ned task could be added, but existing will be // completed as requested kStopping, // Threadppol is stopped kStopped }; Executor(std::string name, int size); ~Executor(); /** * Signal thread pool to stop, it will stop accepting new jobs and close threads just after each become * free. All enqueued jobs will be complete. * * In case if await flag is true, call won't return until all background jobs are done and all threads are stopped */ void Stop(bool await = false); /** * Add function to be executed on the threadpool. Method returns true in case if task has been placed * onto execution queue, i.e scheduled for execution and false otherwise. * * That function doesn't wait for function result. Function could always be written in a way to notify caller about * execution finished by itself */ template <typename F, typename... Types> bool Execute(F &&func, Types... args) { // Prepare "task" auto exec = std::bind(std::forward<F>(func), std::forward<Types>(args)...); std::unique_lock<std::mutex> lock(this->mutex); if (state != State::kRun) { return false; } // Enqueue new task tasks.push_back(exec); empty_condition.notify_one(); return true; } private: // No copy/move/assign allowed Executor(const Executor &); // = delete; Executor(Executor &&); // = delete; Executor &operator=(const Executor &); // = delete; Executor &operator=(Executor &&); // = delete; /** * Main function that all pool threads are running. It polls internal task queue and execute tasks */ friend void perform(Executor *executor); /** * Mutex to protect state below from concurrent modification */ std::mutex mutex; /** * Conditional variable to await new data in case of empty queue */ std::condition_variable empty_condition; /** * Vector of actual threads that perorm execution */ std::vector<std::thread> threads; /** * Task queue */ std::deque<std::function<void()>> tasks; /** * Flag to stop bg threads */ State state; }; } // namespace Afina #endif // AFINA_THREADPOOL_H
[ "ph.andronov@corp.mail.ru" ]
ph.andronov@corp.mail.ru
de2e689593c81e0de74f074407886ba0dc1da58b
07110f30a6a30a1a6cce260509c60fb16f0dbf92
/src/include/concore/as_sender.hpp
80553983ded23ce830886b02a4aa0648165bfc21
[ "MIT" ]
permissive
Watch-Later/concore
8d65fe2409684a247f869d8df3952053f32b8149
579d2f84039bbf2d9ebe245096b63867702613c9
refs/heads/master
2023-06-20T02:03:28.396841
2021-06-01T15:23:20
2021-06-01T15:23:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,269
hpp
/** * @file as_sender.hpp * @brief Definition of @ref concore::v1::as_sender "as_sender" * * @see @ref concore::v1::as_sender "as_sender" */ #pragma once #include <concore/as_operation.hpp> #include <utility> namespace concore { inline namespace v1 { /** * @brief Wrapper that transforms a receiver into a functor * * @tparam R The type of the receiver * * @details * * The receiver should model `receiver_of<>`. * * This will store a reference to the receiver; the receiver must not get out of scope. * * When this functor is called set_value() will be called on the receiver. If an exception is * thrown, the set_error() function is called. * * If the functor is never called, the destructor of this object will call set_done(). * * This types models the @ref sender concept. * * @see sender, receiver_of, as_operation */ template <typename E> struct as_sender { //! The value types that defines the values that this sender sends to receivers template <template <typename...> class Tuple, template <typename...> class Variant> using value_types = Variant<Tuple<>>; //! The type of error that this sender sends to receiver template <template <typename...> class Variant> using error_types = Variant<std::exception_ptr>; //! Indicates that this sender never sends a done signal static constexpr bool sends_done = false; //! Constructor explicit as_sender(E e) noexcept : ex_((E &&) e) { #if CONCORE_CXX_HAS_CONCEPTS static_assert(executor<E>, "Type needs to match executor concept"); #endif } //! The connect CPO that returns an operation state object template <typename R> as_operation<E, R> connect(R&& r) && { #if CONCORE_CXX_HAS_CONCEPTS static_assert(receiver_of<R>, "Type needs to match receiver_of concept"); #endif return as_operation<E, R>((E &&) ex_, (R &&) r); } //! @overload template <typename R> as_operation<E, R> connect(R&& r) const& { #if CONCORE_CXX_HAS_CONCEPTS static_assert(receiver_of<R>, "Type needs to match receiver_of concept"); #endif return as_operation<E, R>(ex_, (R &&) r); } private: //! The wrapped executor E ex_; }; } // namespace v1 } // namespace concore
[ "lucteo@lucteo.ro" ]
lucteo@lucteo.ro
88e78929c23e138486ca606abc87344660912868
dc37fe84633264f6c829d69d3f41b64760584a64
/OpenGLConfig/indexbuffer.cpp
e1d41267973ac43a7da8d1aa3a8b8da48c0657c5
[]
no_license
Hyperionlucky/SuperGis
fa958be38ed369ab659d9ad778c5e04f4b9f29c6
99fb4ca20a68328745d4c2d6440cdf424154720d
refs/heads/master
2020-12-27T14:30:12.030399
2020-02-03T10:29:50
2020-02-03T10:29:50
237,936,106
0
0
null
null
null
null
UTF-8
C++
false
false
716
cpp
#include "indexbuffer.h" #include "glcall.h" IndexBuffer::IndexBuffer(const unsigned int* data, unsigned int count, unsigned int modeIn) : count(count), mode(modeIn) { ASSERT(sizeof(unsigned int) == sizeof(GLuint)); GLCall(glGenBuffers(1, &rendererID)); GLCall(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, rendererID)); GLCall(glBufferData(GL_ELEMENT_ARRAY_BUFFER, count * sizeof(unsigned int), data, GL_STATIC_DRAW)); } IndexBuffer::~IndexBuffer() { GLCall(glDeleteBuffers(1, &rendererID)); } void IndexBuffer::Bind() const { GLCall(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, rendererID)); } void IndexBuffer::Unbind() const { GLCall(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0)); }
[ "1943414735@qq.com" ]
1943414735@qq.com
b6c07b2b3d14df4bf3e34a36d9e0800e65fbd560
a7764174fb0351ea666faa9f3b5dfe304390a011
/inc/StepElement_ElementAspect.hxx
92c10c2938acecb17b7ca6b21960d351454af9ff
[]
no_license
uel-dataexchange/Opencascade_uel
f7123943e9d8124f4fa67579e3cd3f85cfe52d91
06ec93d238d3e3ea2881ff44ba8c21cf870435cd
refs/heads/master
2022-11-16T07:40:30.837854
2020-07-08T01:56:37
2020-07-08T01:56:37
276,290,778
0
0
null
null
null
null
UTF-8
C++
false
false
5,151
hxx
// This file is generated by WOK (CPPExt). // Please do not edit this file; modify original file instead. // The copyright and license terms as defined for the original file apply to // this header file considered to be the "object code" form of the original source. #ifndef _StepElement_ElementAspect_HeaderFile #define _StepElement_ElementAspect_HeaderFile #ifndef _Standard_HeaderFile #include <Standard.hxx> #endif #ifndef _Standard_Macro_HeaderFile #include <Standard_Macro.hxx> #endif #ifndef _StepData_SelectType_HeaderFile #include <StepData_SelectType.hxx> #endif #ifndef _Standard_Integer_HeaderFile #include <Standard_Integer.hxx> #endif #ifndef _Handle_Standard_Transient_HeaderFile #include <Handle_Standard_Transient.hxx> #endif #ifndef _Handle_StepData_SelectMember_HeaderFile #include <Handle_StepData_SelectMember.hxx> #endif #ifndef _StepElement_ElementVolume_HeaderFile #include <StepElement_ElementVolume.hxx> #endif #ifndef _StepElement_CurveEdge_HeaderFile #include <StepElement_CurveEdge.hxx> #endif class Standard_Transient; class StepData_SelectMember; //! Representation of STEP SELECT type ElementAspect <br> class StepElement_ElementAspect : public StepData_SelectType { public: void* operator new(size_t,void* anAddress) { return anAddress; } void* operator new(size_t size) { return Standard::Allocate(size); } void operator delete(void *anAddress) { if (anAddress) Standard::Free((Standard_Address&)anAddress); } //! Empty constructor <br> Standard_EXPORT StepElement_ElementAspect(); //! Recognizes a kind of ElementAspect select type <br> //! return 0 <br> Standard_EXPORT Standard_Integer CaseNum(const Handle(Standard_Transient)& ent) const; //! Recognizes a items of select member ElementAspectMember <br> //! 1 -> ElementVolume <br> //! 2 -> Volume3dFace <br> //! 3 -> Volume2dFace <br> //! 4 -> Volume3dEdge <br> //! 5 -> Volume2dEdge <br> //! 6 -> Surface3dFace <br> //! 7 -> Surface2dFace <br> //! 8 -> Surface3dEdge <br> //! 9 -> Surface2dEdge <br> //! 10 -> CurveEdge <br> //! 0 else <br> Standard_EXPORT virtual Standard_Integer CaseMem(const Handle(StepData_SelectMember)& ent) const; //! Returns a new select member the type ElementAspectMember <br> Standard_EXPORT virtual Handle_StepData_SelectMember NewMember() const; //! Set Value for ElementVolume <br> Standard_EXPORT void SetElementVolume(const StepElement_ElementVolume aVal) ; //! Returns Value as ElementVolume (or Null if another type) <br> Standard_EXPORT StepElement_ElementVolume ElementVolume() const; //! Set Value for Volume3dFace <br> Standard_EXPORT void SetVolume3dFace(const Standard_Integer aVal) ; //! Returns Value as Volume3dFace (or Null if another type) <br> Standard_EXPORT Standard_Integer Volume3dFace() const; //! Set Value for Volume2dFace <br> Standard_EXPORT void SetVolume2dFace(const Standard_Integer aVal) ; //! Returns Value as Volume2dFace (or Null if another type) <br> Standard_EXPORT Standard_Integer Volume2dFace() const; //! Set Value for Volume3dEdge <br> Standard_EXPORT void SetVolume3dEdge(const Standard_Integer aVal) ; //! Returns Value as Volume3dEdge (or Null if another type) <br> Standard_EXPORT Standard_Integer Volume3dEdge() const; //! Set Value for Volume2dEdge <br> Standard_EXPORT void SetVolume2dEdge(const Standard_Integer aVal) ; //! Returns Value as Volume2dEdge (or Null if another type) <br> Standard_EXPORT Standard_Integer Volume2dEdge() const; //! Set Value for Surface3dFace <br> Standard_EXPORT void SetSurface3dFace(const Standard_Integer aVal) ; //! Returns Value as Surface3dFace (or Null if another type) <br> Standard_EXPORT Standard_Integer Surface3dFace() const; //! Set Value for Surface2dFace <br> Standard_EXPORT void SetSurface2dFace(const Standard_Integer aVal) ; //! Returns Value as Surface2dFace (or Null if another type) <br> Standard_EXPORT Standard_Integer Surface2dFace() const; //! Set Value for Surface3dEdge <br> Standard_EXPORT void SetSurface3dEdge(const Standard_Integer aVal) ; //! Returns Value as Surface3dEdge (or Null if another type) <br> Standard_EXPORT Standard_Integer Surface3dEdge() const; //! Set Value for Surface2dEdge <br> Standard_EXPORT void SetSurface2dEdge(const Standard_Integer aVal) ; //! Returns Value as Surface2dEdge (or Null if another type) <br> Standard_EXPORT Standard_Integer Surface2dEdge() const; //! Set Value for CurveEdge <br> Standard_EXPORT void SetCurveEdge(const StepElement_CurveEdge aVal) ; //! Returns Value as CurveEdge (or Null if another type) <br> Standard_EXPORT StepElement_CurveEdge CurveEdge() const; protected: private: }; // other Inline functions and methods (like "C++: function call" methods) #endif
[ "shoka.sho2@excel.co.jp" ]
shoka.sho2@excel.co.jp
66aae1da02de6d2e81a45a2d4ce97e839abf6ad6
39924b397975b36d8bb0c685d1fdcf604f14caf5
/IProjectProblem2/Problem2_test/Graph.h
3abe0cbde6035a1d0801115771829d64aa1e7393
[]
no_license
mengcz13/oop2016
519a1d8048212ddeef0f2f15428dd71f3a26296b
2e3d557927d2f5eaa1e361e370255629bf733c78
refs/heads/master
2021-01-21T13:41:35.544044
2016-05-18T04:02:38
2016-05-18T04:02:38
52,948,605
0
0
null
null
null
null
UTF-8
C++
false
false
1,259
h
#ifndef GRAPH_H #define GRAPH_H #include <vector> #include <queue> #include <cmath> struct Point { double x; double y; Point():x(0), y(0) {} Point(double x1, double y1):x(x1), y(y1) {} }; struct Edge { int start; int end; double length; Edge():start(0), end(0), length(0) {} Edge(int s, int e, double l):start(s), end(e), length(l) {} }; struct EdgeGreater { bool operator() (const Edge& e1, const Edge& e2) { return (e1.length > e2.length); } }; struct UnionFind { int* parent; int* setsize; int size; UnionFind(int s): size(s) { parent = new int[size]; setsize = new int[size]; for (int i = 0; i < size; ++i) { parent[i] = -1; setsize[i] = 1; } } ~UnionFind() { delete []parent; delete []setsize; } void connect(int x, int y); int findset(int x); bool isconnected(int x, int y); }; class Graph { public: Graph(std::vector<Point> pv, std::vector<Edge> ev) : pointvec(pv), edgeheap(EdgeGreater(), ev), uf(pv.size()), total_weight(0) {} void MST_Kruskal(); void print(char*); const double get_total_weight() { return total_weight; } private: std::vector<Point> pointvec; std::priority_queue<Edge, std::vector<Edge>, EdgeGreater> edgeheap; std::vector<Edge> mstedge; UnionFind uf; double total_weight; }; #endif
[ "mengcz13@163.com" ]
mengcz13@163.com
9ea73474ab4f505e4e5929aa6869c1f97eceed3a
ee491a9c89b82b0c2732a357e13cbffa6954bdf2
/src/config.h
6495c812f55ec939f429d4e9e849b89c11ab3bf4
[ "MIT" ]
permissive
maxhodak/neat
9a1da908ab55ffa30f096345e1dc097fe7f4cec9
3f844173828eb22009cc8d36c28e75a22adfbae8
refs/heads/master
2021-01-02T08:51:37.479731
2010-02-14T03:23:44
2010-02-14T03:23:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,480
h
#ifndef __CONFIG_H #define __CONFIG_H /******BEGIN LICENSE BLOCK******* * The MIT License * * Copyright (c) 2009 Max Hodak * * 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. ********END LICENSE BLOCK*********/ #include <iostream> #include <string> #include <vector> #include "lua/include/lua.hpp" using namespace std; struct NeatConf { vector<string> monitor_paths; vector<string> sorted_paths; int inter_sort_interval; // seconds }; #endif
[ "maxhodak@gmail.com" ]
maxhodak@gmail.com
5e841693158c2fbef4bc7dd0009fa0f337b1769a
9ef7ae27f57d24b7fa194ed9fc22d95a2ea2f4fa
/Algorithms/prefixSortUsingRandom.cpp
59a4fe6cccca64d6a7a997df89e8b7df7cc5027a
[]
no_license
Rahul365/Coding_Practice
e093b745da5e0d589b57d31ff8d4d5bdae46c583
4430401991defdd79522da229f040c5e48718487
refs/heads/master
2022-07-30T19:59:21.839107
2022-07-02T08:10:50
2022-07-02T08:10:50
241,954,353
1
1
null
null
null
null
UTF-8
C++
false
false
1,498
cpp
#include<bits/stdc++.h> #define seed srand(time(NULL)) using namespace std; int pow(int x,int y){ int r =1; while(y){ if(y&1) r*=x; x = x*x; y>>=1; } return r; } bool sorted(int arr[],int n){ for(int i=1 ;i<n;i++) if(arr[i-1] > arr[i]) return false; return true; } void reverse(int arr[],int n){ int i = 0; int j = n; while(i < j) swap(arr[i],arr[j]),++i,--j; } void prefixSortUsingRandom(int arr[],int n){ while(!sorted(arr,n)){ int index = rand()%n; reverse(arr,index); } } void prefixSort(int arr[],int n){ //find the index of max element //reverse arr[0..index] //reverse arr[0..n-1] int s = n; while(s > 1){ int maxindex = s-1; for(int i= 0;i<=s-1;i++){ if(arr[maxindex] < arr[i]){ maxindex = i; } } //find the index of max element in arr[0..s-1] //then reverse the arr from 0 to maxindex reverse(arr,maxindex);//after this max element is at the front of the array reverse(arr,s-1);//now reverse the array from 0 to s-1 //so that the max element is position at the end here //now reduce the number of elements to sort by 1 --s; } } int main(){ seed; int arr[] = {3,23,1,1,12,1,224,435,34,5234,5}; int n = sizeof(arr)/sizeof(arr[0]); prefixSort(arr,n); for(int i =0;i<n;i++) cout<<arr[i]<<" "; cout<<"\n"; return 0; }
[ "rahul.dhiman365@gmail.com" ]
rahul.dhiman365@gmail.com
72805e7b770675576f4f275adbe9da7d0f925757
514128d3338709b7d38e1dab8535392f71409435
/reconstruction/src/timer/Timer.cpp
154a818f4cdfca16457bdcc03e9c8ace5d3605a5
[]
no_license
fukamikentaro/HeteroEdge
2ba0a1bca7d0b696de60501afa6a133aece73845
39511607c5451076cae6b9fa4979496775b46ec6
refs/heads/master
2022-10-27T09:18:19.751146
2019-07-14T01:11:10
2019-07-14T01:11:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
507
cpp
/* * timer.cpp * * Created on: Jan 3, 2018 * Author: wuyang */ #include "Timer.h" Timer::Timer() { timeUse = 0.f; } Timer::~Timer() { // TODO Auto-generated destructor stub } void Timer::start() { gettimeofday(&tpstart, NULL); } void Timer::end() { gettimeofday(&tpend, NULL); countElapseTime(); } inline void Timer::countElapseTime(){ timeUse = 1000 * (tpend.tv_sec - tpstart.tv_sec) + (tpend.tv_usec - tpstart.tv_usec) / 1000; } long Timer::getTimeUse(){ return timeUse; }
[ "you@example.com" ]
you@example.com
10bb48703bf3fe5c5c52641938f81b08f8905809
164e709dcf03ce4769c3ba8f874da0666c35bc03
/RtTpsRenderLibrary/operation/tps_rl_updatesetupcrosshairoperation.cpp
c15ce66f67d5231cd93f285b515bf44896daa172
[]
no_license
liq07lzucn/tps
b343894bcfd59a71be48bd47d6eff6e010464457
a3be6dc50c5f9a2ff448ecff3f5df1956e26ad4f
refs/heads/master
2021-06-23T16:35:01.349523
2017-08-30T08:09:02
2017-08-30T08:09:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,113
cpp
//////////////////////////////////////////////////////////////// /// Copyright (c) Shanghai United Imaging Healthcare Inc., 2013 /// All rights reserved. /// /// \author Miao Chenfeng chenfeng.miao@united-imaging.com /// /// \file tps_rl_updatesetupcrosshairoperation.cpp /// /// \brief class TpsUpdateSetUpCrosshairOPeration /// /// \version 1.0 /// /// \date 2014/4/10 //////////////////////////////////////////////////////////////// #include "StdAfx.h" #include "RtTpsRenderLibrary/tps_rl_updatesetupcrosshairoperation.h" #include "RtTpsRenderLibrary/tps_rl_editsetuppoigraphicobject.h" #include "RtTpsFramework/tps_fw_modelwarehouse.h" #include "RtTpsRenderLibrary/tps_rl_graphicobjecttypedefines.h" #include "RtTpsFramework/tps_fw_graphicobjectconverterbase.h" #include "RtTpsFramework/tps_fw_arithmeticconverter.h" #include "RtTpsFramework/tps_fw_graphicobjecttypehelper.h" TPS_BEGIN_NAMESPACE TpsUpdateSetUpCrosshairOperation::TpsUpdateSetUpCrosshairOperation(const std::string &imageuid, const Mcsf::Point2f &mousePosition, bool isVisible, FIRST_POSTFIX_COMPONENT section) : mImageuid(imageuid), mMousePosition(mousePosition),mIsVisible(isVisible),mSectionType(section) { } TpsUpdateSetUpCrosshairOperation::~TpsUpdateSetUpCrosshairOperation() { } bool TpsUpdateSetUpCrosshairOperation::ModifyGraphicObject() const { if(mSectionType != AXIAL && mSectionType != EASYPLAN_IMAGE_SECTION) { return true; } auto setupCrossHairGo = mModelWarehouse->GetModelObject( mImageuid + "|" + GOTypeHelper::ToString(GO_TYPE_SETUP_POI)); if(nullptr == setupCrossHairGo) { TPS_LOG_DEV_ERROR<<"Failed to get set up poi"<<mImageuid; return false; } auto setupGo = dynamic_pointer_cast<EditSetupPtGraphicObject>(setupCrossHairGo); if(nullptr == setupGo) { TPS_LOG_DEV_ERROR<<"Failed to convert set up go!"; return false; } setupGo->SetVisible(mIsVisible); setupGo->SetPosition(TpsArithmeticConverter::ConvertToPoint2D(mMousePosition)); setupGo->SetDirty(true); return true; } TPS_END_NAMESPACE
[ "genius52@qq.com" ]
genius52@qq.com
6a24f7c5cc162449b7a66a56e4492725553bb643
404fb17c7661b6fd0085234decd66618722a93b6
/Scripts/BDT/neutral_bdt_train.cxx
962935aa83173805778d1b089413742b4213756f
[]
no_license
ionic-corinthian/Analysis
3485c0be13dfbe531b8cc3029905f0920bfaa991
439d238e313a0441cc0665ec4fb47d7dabdbcae9
refs/heads/master
2020-03-17T17:25:58.236033
2018-05-17T10:11:55
2018-05-17T10:11:55
133,788,080
0
0
null
2018-05-17T09:26:14
2018-05-17T09:08:29
C++
UTF-8
C++
false
false
6,128
cxx
#include <cstdlib> #include <iostream> #include <map> #include <string> #include "TChain.h" #include "TFile.h" #include "TTree.h" #include "TString.h" #include "TObjString.h" #include "TSystem.h" #include "TROOT.h" #include "TMVA/Factory.h" // #include "TMVA/DataLoader.h" #include "TMVA/Tools.h" #include "TMVA/TMVAGui.h" #include "myDecay.cxx" void neutral_bdt_train(const char* TupleName, int year, const char* mag, const char* charge, bool all_mc=false, bool all_data=false) { //=====================// //=== Prepare files ===// //=====================// //=== Setup TMVA ===// TMVA::Tools::Instance(); //=== Open a new file to save the BDT output ===// TFile* outputFile = TFile::Open(Form("/data/lhcb/users/colmmurphy/ReducedTrees/%i/Mag%s/%sCharge/neut_BDT_Output_%s.root", year, mag, charge, TupleName), "RECREATE"); //=== Get instance of TMVA factory to use for training ===// TString fac_name; if (all_mc && !all_data) fac_name = Form("AllMC_%s_%i_Mag%s_%sCharge", TupleName, year, mag, charge); else if (!all_mc && all_data) fac_name = Form("%s_AllDataYears_Mag%s_%sCharge", TupleName, mag, charge); else if (all_mc && all_data ) fac_name = Form("AllMC_%s_AllDataYears_Mag%s_%sCharge", TupleName, mag, charge); else fac_name = Form("%s_%i_Mag%s_%sCharge", TupleName, year, mag, charge); TMVA::Factory *factory = new TMVA::Factory((TString)("neut"+fac_name), outputFile, "V:!Silent:Color:Transformations=I:DrawProgressBar:AnalysisType=Classification"); //=== Weights ===// double signalWeight = 1.0; double backgroundWeight = 1.0; //=== Read in signal tree (MC which has been precut on truth matching info) ===// // if year is set to 999, then read in all MC! TChain* sigTree = new TChain("DecayTree"); if (all_mc) { sigTree->Add(Form("~/TruthMatchedTrees/2011/Mag%s/%sCharge/TM_%s_MC.root", mag, charge, TupleName)); sigTree->Add(Form("~/TruthMatchedTrees/2012/Mag%s/%sCharge/TM_%s_MC.root", mag, charge, TupleName)); sigTree->Add(Form("~/TruthMatchedTrees/2015/Mag%s/%sCharge/TM_%s_MC.root", mag, charge, TupleName)); sigTree->Add(Form("~/TruthMatchedTrees/2016/Mag%s/%sCharge/TM_%s_MC.root", mag, charge, TupleName)); } else sigTree->Add(Form("~/TruthMatchedTrees/%i/Mag%s/%sCharge/TM_%s_MC.root", year, mag, charge, TupleName)); //=== TChain data TTrees together (for mag up and mag down) ===// TChain* dataTree = new TChain("DecayTree"); if (all_data) { dataTree->Add(Form("/data/lhcb/users/colmmurphy/BDT_Output/2011/Mag%s/%sCharge/bkgcut_%s.root", mag, charge, TupleName)); dataTree->Add(Form("/data/lhcb/users/colmmurphy/BDT_Output/2012/Mag%s/%sCharge/bkgcut_%s.root", mag, charge, TupleName)); dataTree->Add(Form("/data/lhcb/users/colmmurphy/BDT_Output/2015/Mag%s/%sCharge/bkgcut_%s.root", mag, charge, TupleName)); dataTree->Add(Form("/data/lhcb/users/colmmurphy/BDT_Output/2016/Mag%s/%sCharge/bkgcut_%s.root", mag, charge, TupleName)); dataTree->Add(Form("/data/lhcb/users/colmmurphy/BDT_Output/2017/Mag%s/%sCharge/bkgcut_%s.root", mag, charge, TupleName)); } else dataTree->Add(Form("/data/lhcb/users/colmmurphy/BDT_Output/%i/Mag%s/%sCharge/bkgcut_%s.root", year, mag, charge, TupleName)); //=== Add the signal and background (i.e. real data) to the BDT trainer ===// factory->AddSignalTree(sigTree, signalWeight); factory->AddBackgroundTree(dataTree, backgroundWeight); std::cout << "--- ADDED TREES SUCCESSFULLY!" << std::endl; //=== Signal has been previously truth matched. Background cut to be in upper B mass sideband ===// //=== Additional cuts are to ensure negative values are not logged! ===// TCut sigcut = ""; TCut bkgcut = ""; //Bu_M>5900. && D0_MIPCHI2_PV<0. && Bach_MIPCHI2_PV<0. && K0_MIPCHI2_PV<0. && P0_MIPCHI2_PV<0. && Bu_FDCHI2_OWNPV<0. && D0_FDCHI2_OWNPV<0. && Bu_DIRA_BPV>1. && D0_DIRA_BPV>1. //=========================================// //=== Add NTuple variables for training ===// //=========================================// //=== Particle momenta ===// factory->AddVariable("Pi0_PT", 'F'); factory->AddVariable("Gamma1_PT", 'F'); factory->AddVariable("Gamma2_PT", 'F'); // factory->AddVariable("Pi0_P", 'F'); // factory->AddVariable("Pi0_PE", 'F'); // factory->AddVariable("Pi0_PX", 'F'); // factory->AddVariable("Pi0_PY", 'F'); // factory->AddVariable("Pi0_PZ", 'F'); //=== Neutral particle variables ===// factory->AddVariable("Gamma1_CL", 'F'); factory->AddVariable("Gamma2_CL", 'F'); // factory->AddVariable("Pi0_ptasy_1.50", 'F'); // factory->AddVariable("Gamma1_ptasy_1.50", 'F'); // factory->AddVariable("Gamma2_ptasy_1.50", 'F'); factory->AddVariable("Gamma1_PP_IsNotE", 'F'); factory->AddVariable("Gamma2_PP_IsNotE", 'F'); std::cout << "--- ADDED VARIABLES SUCCESSFULLY!" << std::endl; //====================================// //=== Run the BDT training/testing ===// //====================================// factory->PrepareTrainingAndTestTree(sigcut,bkgcut,"random"); //=== Add different MVA methods to test here! ===// factory->BookMethod(TMVA::Types::kBDT,"BDT","NTrees=600:MaxDepth=4"); // factory->BookMethod(TMVA::Types::kBDT,"More_Depth","NTrees=400:MaxDepth=8"); // factory->BookMethod(TMVA::Types::kBDT,"More_Trees","NTrees=800:MaxDepth=4"); // factory->BookMethod(TMVA::Types::kBDT,"More_Depth_and_Trees","NTrees=800:MaxDepth=8"); // factory->BookMethod( TMVA::Types::kBDT, "BDTG","!H:!V:NTrees=1000:BoostType=Grad:Shrinkage=0.30:UseBaggedGrad:\GradBaggingFraction=0.6:SeparationType=GiniIndex:nCuts=20:\PruneMethod=CostComplexity:PruneStrength=50:NNodesMax=5" ); std::cout << "--- ABOUT TO TRAIN METHODS!" << std::endl; //=== Train, test, then evaluate all methods ===// factory->TrainAllMethods(); factory->TestAllMethods(); factory->EvaluateAllMethods(); outputFile->Close(); }
[ "colmmurphy@pplxint8.physics.ox.ac.uk" ]
colmmurphy@pplxint8.physics.ox.ac.uk
0dfdf6692287a2c1b6e1c11e873984180d2b9a73
f50da5dfb1d27cf737825705ce5e286bde578820
/Temp/il2cppOutput/il2cppOutput/mscorlib_System_Security_Cryptography_ToBase64Tran1303874555.h
011abe010d6265397ddf81fd268be9da64bab834
[]
no_license
magonicolas/OXpecker
03f0ea81d0dedd030d892bfa2afa4e787e855f70
f08475118dc8f29fc9c89aafea5628ab20c173f7
refs/heads/master
2020-07-05T11:07:21.694986
2016-09-12T16:20:33
2016-09-12T16:20:33
67,150,904
0
0
null
null
null
null
UTF-8
C++
false
false
993
h
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> #include "mscorlib_System_Object837106420.h" #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Security.Cryptography.ToBase64Transform struct ToBase64Transform_t1303874555 : public Il2CppObject { public: // System.Boolean System.Security.Cryptography.ToBase64Transform::m_disposed bool ___m_disposed_2; public: inline static int32_t get_offset_of_m_disposed_2() { return static_cast<int32_t>(offsetof(ToBase64Transform_t1303874555, ___m_disposed_2)); } inline bool get_m_disposed_2() const { return ___m_disposed_2; } inline bool* get_address_of_m_disposed_2() { return &___m_disposed_2; } inline void set_m_disposed_2(bool value) { ___m_disposed_2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif
[ "magonicolas@gmail.com" ]
magonicolas@gmail.com
e4c69a49bb4706081376982f89aff57b1a8a5347
4f58cc74e6270729a7d5dbc171455624d98807b4
/inc/rtspvideocapturer.h
a4e3c941bc56a53fb35bec922cce4053fdfd05b8
[ "Unlicense" ]
permissive
InsZVA/webrtc-streamer
5175776a8591472e5491c13f4dc5ba1aa3f867a8
10ab5dca8e8efc301c86b976ebf1472706eed89b
refs/heads/master
2021-01-12T17:37:10.775369
2016-10-09T10:54:03
2016-10-09T10:54:03
71,618,828
1
0
null
2016-10-22T05:28:05
2016-10-22T05:28:04
null
UTF-8
C++
false
false
10,734
h
/* --------------------------------------------------------------------------- ** This software is in the public domain, furnished "as is", without technical ** support, and with no warranty, express or implied, as to its usefulness for ** any purpose. ** ** rtspvideocapturer.h ** ** -------------------------------------------------------------------------*/ #ifndef RTSPVIDEOCAPTURER_H_ #define RTSPVIDEOCAPTURER_H_ #include <string.h> #include <vector> #include "webrtc/media/base/videocapturer.h" #include "webrtc/base/timeutils.h" #include "liveMedia.hh" #include "BasicUsageEnvironment.hh" #define RTSP_CALLBACK(uri, resultCode, resultString) \ static void continueAfter ## uri(RTSPClient* rtspClient, int resultCode, char* resultString) { static_cast<RTSPConnection*>(rtspClient)->continueAfter ## uri(resultCode, resultString); } \ void continueAfter ## uri (int resultCode, char* resultString); \ /**/ class Environment : public BasicUsageEnvironment { public: Environment(); ~Environment(); void mainloop() { this->taskScheduler().doEventLoop(&m_stop); } void stop() { m_stop = 1; }; protected: char m_stop; }; /* --------------------------------------------------------------------------- ** RTSP client connection interface ** -------------------------------------------------------------------------*/ class RTSPConnection : public RTSPClient { public: /* --------------------------------------------------------------------------- ** RTSP client callback interface ** -------------------------------------------------------------------------*/ class Callback { public: virtual bool onNewSession(const char* media, const char* codec) = 0; virtual bool onData(unsigned char* buffer, ssize_t size) = 0; virtual ssize_t onNewBuffer(unsigned char* buffer, ssize_t size) { return 0; }; }; protected: /* --------------------------------------------------------------------------- ** RTSP client Sink ** -------------------------------------------------------------------------*/ class SessionSink: public MediaSink { public: static SessionSink* createNew(UsageEnvironment& env, Callback* callback) { return new SessionSink(env, callback); } private: SessionSink(UsageEnvironment& env, Callback* callback); virtual ~SessionSink(); void allocate(ssize_t bufferSize); static void afterGettingFrame(void* clientData, unsigned frameSize, unsigned numTruncatedBytes, struct timeval presentationTime, unsigned durationInMicroseconds) { static_cast<SessionSink*>(clientData)->afterGettingFrame(frameSize, numTruncatedBytes, presentationTime, durationInMicroseconds); } void afterGettingFrame(unsigned frameSize, unsigned numTruncatedBytes, struct timeval presentationTime, unsigned durationInMicroseconds); virtual Boolean continuePlaying(); private: size_t m_bufferSize; u_int8_t* m_buffer; Callback* m_callback; ssize_t m_markerSize; }; public: RTSPConnection(UsageEnvironment& env, Callback* callback, const std::string & rtspURL, int verbosityLevel = 255); virtual ~RTSPConnection(); protected: void sendNextCommand(); RTSP_CALLBACK(DESCRIBE,resultCode,resultString); RTSP_CALLBACK(SETUP,resultCode,resultString); RTSP_CALLBACK(PLAY,resultCode,resultString); protected: MediaSession* m_session; MediaSubsession* m_subSession; MediaSubsessionIterator* m_subSessionIter; Callback* m_callback; }; Environment::Environment() : BasicUsageEnvironment(*BasicTaskScheduler::createNew()), m_stop(0) { } Environment::~Environment() { TaskScheduler* scheduler = &this->taskScheduler(); this->reclaim(); delete scheduler; } RTSPConnection::SessionSink::SessionSink(UsageEnvironment& env, Callback* callback) : MediaSink(env) , m_bufferSize(0) , m_buffer(NULL) , m_callback(callback) , m_markerSize(0) { allocate(1024*1024); } RTSPConnection::SessionSink::~SessionSink() { delete [] m_buffer; } void RTSPConnection::SessionSink::allocate(ssize_t bufferSize) { m_bufferSize = bufferSize; m_buffer = new u_int8_t[m_bufferSize]; if (m_callback) { m_markerSize = m_callback->onNewBuffer(m_buffer, m_bufferSize); LOG(INFO) << "markerSize:" << m_markerSize; } } void RTSPConnection::SessionSink::afterGettingFrame(unsigned frameSize, unsigned numTruncatedBytes, struct timeval presentationTime, unsigned durationInMicroseconds) { LOG(LS_VERBOSE) << "NOTIFY size:" << frameSize; if (numTruncatedBytes != 0) { delete [] m_buffer; LOG(INFO) << "buffer too small " << m_bufferSize << " allocate bigger one\n"; allocate(m_bufferSize*2); } else if (m_callback) { if (!m_callback->onData(m_buffer, frameSize+m_markerSize)) { LOG(WARNING) << "NOTIFY failed"; } } this->continuePlaying(); } Boolean RTSPConnection::SessionSink::continuePlaying() { Boolean ret = False; if (source() != NULL) { source()->getNextFrame(m_buffer+m_markerSize, m_bufferSize-m_markerSize, afterGettingFrame, this, onSourceClosure, this); ret = True; } return ret; } RTSPConnection::RTSPConnection(UsageEnvironment& env, Callback* callback, const std::string & rtspURL, int verbosityLevel) : RTSPClient(env, rtspURL.c_str(), verbosityLevel, NULL, 0 #if LIVEMEDIA_LIBRARY_VERSION_INT > 1371168000 ,-1 #endif ) , m_session(NULL) , m_subSessionIter(NULL) , m_callback(callback) { // initiate connection process this->sendNextCommand(); } RTSPConnection::~RTSPConnection() { delete m_subSessionIter; Medium::close(m_session); } void RTSPConnection::sendNextCommand() { if (m_subSessionIter == NULL) { // no SDP, send DESCRIBE this->sendDescribeCommand(continueAfterDESCRIBE); } else { m_subSession = m_subSessionIter->next(); if (m_subSession != NULL) { // still subsession to SETUP if (!m_subSession->initiate()) { LOG(WARNING) << "Failed to initiate " << m_subSession->mediumName() << "/" << m_subSession->codecName() << " subsession: " << envir().getResultMsg(); this->sendNextCommand(); } else { LOG(INFO) << "Initiated " << m_subSession->mediumName() << "/" << m_subSession->codecName() << " subsession"; } this->sendSetupCommand(*m_subSession, continueAfterSETUP); } else { // no more subsession to SETUP, send PLAY this->sendPlayCommand(*m_session, continueAfterPLAY); } } } void RTSPConnection::continueAfterDESCRIBE(int resultCode, char* resultString) { if (resultCode != 0) { LOG(WARNING) << "Failed to DESCRIBE: " << resultString; } else { LOG(INFO) << "Got SDP:\n" << resultString; m_session = MediaSession::createNew(envir(), resultString); m_subSessionIter = new MediaSubsessionIterator(*m_session); this->sendNextCommand(); } delete[] resultString; } void RTSPConnection::continueAfterSETUP(int resultCode, char* resultString) { if (resultCode != 0) { LOG(WARNING) << "Failed to SETUP: " << resultString; } else { m_subSession->sink = SessionSink::createNew(envir(), m_callback); if (m_subSession->sink == NULL) { LOG(WARNING) << "Failed to create a data sink for " << m_subSession->mediumName() << "/" << m_subSession->codecName() << " subsession: " << envir().getResultMsg() << "\n"; } else if (m_callback->onNewSession(m_subSession->mediumName(), m_subSession->codecName())) { LOG(WARNING) << "Created a data sink for the \"" << m_subSession->mediumName() << "/" << m_subSession->codecName() << "\" subsession"; m_subSession->sink->startPlaying(*(m_subSession->readSource()), NULL, NULL); } } delete[] resultString; this->sendNextCommand(); } void RTSPConnection::continueAfterPLAY(int resultCode, char* resultString) { if (resultCode != 0) { LOG(WARNING) << "Failed to PLAY: " << resultString; } else { LOG(INFO) << "PLAY OK"; } delete[] resultString; } #include "webrtc/base/optional.h" #include "webrtc/common_video/h264/sps_parser.h" class RTSPVideoCapturer : public cricket::VideoCapturer, public RTSPConnection::Callback, public rtc::Thread { public: RTSPVideoCapturer(const std::string & uri) : m_connection(m_env,this,uri.c_str()) { LOG(INFO) << "===========================RTSPVideoCapturer" << uri ; } virtual ~RTSPVideoCapturer() { } virtual bool onNewSession(const char* media, const char* codec) { LOG(INFO) << "===========================onNewSession" << media << "/" << codec; bool success = false; if ( (strcmp(media, "video") == 0) && (strcmp(codec, "H264") == 0) ) { success = true; } return success; } virtual bool onData(unsigned char* buffer, ssize_t size) { std::cout << "===========================onData" << size << std::endl; if (!IsRunning()) { return false; } if (!GetCaptureFormat()) { rtc::Optional<webrtc::SpsParser::SpsState> sps = webrtc::SpsParser::ParseSps(buffer, size); if (!sps) { std::cout << "cannot parse sps" << std::endl; } else { std::cout << "add new format " << sps->width << "x" << sps->height << std::endl; std::vector<cricket::VideoFormat> formats; formats.push_back(cricket::VideoFormat(sps->width, sps->height, cricket::VideoFormat::FpsToInterval(25), cricket::FOURCC_H264)); SetSupportedFormats(formats); } } if (!GetCaptureFormat()) { return false; } cricket::CapturedFrame frame; frame.width = GetCaptureFormat()->width; frame.height = GetCaptureFormat()->height; frame.fourcc = GetCaptureFormat()->fourcc; frame.data_size = size; std::unique_ptr<char[]> data(new char[size]); frame.data = data.get(); memcpy(frame.data, buffer, size); SignalFrameCaptured(this, &frame); return true; } virtual cricket::CaptureState Start(const cricket::VideoFormat& format) { SetCaptureFormat(&format); SetCaptureState(cricket::CS_RUNNING); rtc::Thread::Start(); return cricket::CS_RUNNING; } virtual void Stop() { m_env.stop(); rtc::Thread::Stop(); SetCaptureFormat(NULL); SetCaptureState(cricket::CS_STOPPED); } void Run() { m_env.mainloop(); } virtual bool GetPreferredFourccs(std::vector<unsigned int>* fourccs) { fourccs->push_back(cricket::FOURCC_H264); return true; } virtual bool IsScreencast() const { return false; }; virtual bool IsRunning() { return this->capture_state() == cricket::CS_RUNNING; } private: Environment m_env; RTSPConnection m_connection; }; #endif
[ "michel.promonet@free.fr" ]
michel.promonet@free.fr
6c2c6e53a56e0496fb51c9253d272373e37865dc
3fc56bb274d5040a87f63372796412413c7690d6
/source stephan/sensor_geometry.cc
03503c353c9d5ed7024bed3a49c39b6ea407bc51
[]
no_license
dangerousHans/SEPT
b2f7b6badc32c887549dce61d83a9b9b9c4d037c
4feca9c51b59018dfd8ab95ac36d75e848a2a419
refs/heads/master
2021-01-10T12:42:42.121856
2015-11-24T18:00:24
2015-11-24T18:00:24
46,416,501
1
2
null
2015-11-24T10:52:25
2015-11-18T12:12:48
C++
UTF-8
C++
false
false
16,087
cc
/* half sensor geometry adapted from ExN02 for Stereo Impact SEPT $Id: sensor_geometry.cc,v 1.18 2008/02/08 11:52:04 bottcher Exp $ Copyright (c) 2002 Stephan Boettcher <boettcher@physik.uni-kiel.de> */ #include "sensor_geometry.hh" #include "detector_geometry.hh" #include "magnet_geometry.hh" #include "apperture_geometry.hh" #include <G4Region.hh> #include <G4RegionStore.hh> #include <G4ProductionCuts.hh> #include <G4VisAttributes.hh> #include <G4Material.hh> #include <G4Box.hh> #include <G4Tubs.hh> #include <G4PVPlacement.hh> #include <ETUserLimits.hh> #define dG4cerr if (0) G4cerr const double sensor_geometry::infinity = 200.0*mm; // w/o conn., pin-puller const double sensor_geometry::X_width = 52.0*mm; // w/o conn., pin-puller const double sensor_geometry::Y_height = 82.0*mm; // w/o doors const double sensor_geometry::Z_depth = 68.0*mm; // w/o conn., doors, ... const double sensor_geometry::det_X = X_width/2 - 20.0*mm; const double sensor_geometry::det_Y = 9.5*mm; const double sensor_geometry::det_Z = 13.05*mm; const double sensor_geometry::foil_sep = 4.1*mm; // from pips surface // FIXME: The apperture z dimensions are still for 0.6*mm pips_separation const double sensor_geometry::foil_apperture_distance = 20.7*mm; // from pips surface const double sensor_geometry::foil_apperture_depth = 15.4*mm; const double sensor_geometry::foil_apperture_rout = 18.6*mm / 2; const double sensor_geometry::foil_apperture_ropen = 12.4*mm / 2; const int sensor_geometry::foil_apperture_rings = 5; const double sensor_geometry::mag_apperture_distance = 29.3*mm; // from pips surface const double sensor_geometry::mag_apperture_depth = 7.6*mm; const double sensor_geometry::mag_apperture_rout = 23.6*mm / 2; const double sensor_geometry::mag_apperture_ropen = 20.4*mm / 2; const int sensor_geometry::mag_apperture_rings = 3; const double sensor_geometry::house_thickness = 3*mm; const double sensor_geometry::slack = 1*nanometer; const double sensor_geometry::mag_delrin_thickness = 1.2*mm; const double sensor_geometry::foil_delrin_thickness = 0.7*mm; const char *sensor_geometry::space = "Space"; const double sensor_geometry::source_window = 0; // 0.0064*mm; char const * sensor_geometry::source_window_mat = "PET"; sensor_geometry::~sensor_geometry() { } // inline functions inline double sensor_geometry::mag_pips_z() { return det_Z + detector_geometry::pips_z - detector_geometry::pips_separation/2 - detector_geometry::pips_height ; } inline double sensor_geometry::foil_pips_z() { return det_Z + detector_geometry::pips_z + detector_geometry::pips_separation/2 + detector_geometry::pips_height ; } inline double sensor_geometry::mag_det_z() { return det_Z - detector_geometry::stack_height/2 ; } inline double sensor_geometry::foil_det_z() { return det_Z + detector_geometry::stack_height/2 ; } // ------------------------------------- Constructor // ------------------------------------------------- sensor_geometry::sensor_geometry() : G4LogicalVolume(new G4Box("sensor", 2*infinity, 2*infinity, 2*infinity), G4Material::GetMaterial(sensor_geometry::space), "sensor") { SetVisAttributes(G4VisAttributes::Invisible); //-------------------------------------------------------------------- // New logical volume "halfsensor" with region "SensorRegion" //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< G4LogicalVolume *halfsensor = new G4LogicalVolume(new G4Box("halfsensor", infinity, infinity, infinity), G4Material::GetMaterial(sensor_geometry::space), "halfsensor"); halfsensor -> SetVisAttributes (G4VisAttributes::Invisible); G4Region *Sensor_Region = new G4Region("The Sensor Region"); Sensor_Region->AddRootLogicalVolume(halfsensor); // Limits "sensorcuts" for SensorRegion of halfsensor G4UserLimits *sensorcuts = new ETUserLimits("/geometry/sept/limits/sensor", 1*mm, // step max DBL_MAX, // track max DBL_MAX, // Time max 0*keV, // Ekin min 0*mm ); // Range min Sensor_Region->SetUserLimits(sensorcuts); // Place halfsensor in this (world) volume new G4PVPlacement(0, // no rotation G4ThreeVector(-det_X, -det_Y, -det_Z), halfsensor, // its logical volume "halfsensor", // its name this, // its mother volume false, // no boolean operations -1); // no particular field //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> // Limits for world ? G4UserLimits *spacecuts = new ETUserLimits("/geometry/sept/limits/space", 1*mm, // step max DBL_MAX, // track max DBL_MAX, // Time max 0*keV, // Ekin min 0*mm ); // Range min SetUserLimits(spacecuts); //-------------------------------------------------------------------- // New logical volume "detector" with region "Det-Region" //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< G4UserLimits *siliconcuts = new ETUserLimits("/geometry/sept/limits/detector", 0.2*mm, // step max DBL_MAX, // track max DBL_MAX, // Time max 0*keV, // Ekin min 0*mm ); // Range min G4Region *Det_Region = new G4Region("Solid State Detector Region"); Det_Region->SetProductionCuts(new G4ProductionCuts); Det_Region->GetProductionCuts()->SetProductionCut(0.01*mm); Det_Region->GetProductionCuts()->SetProductionCut(0.3*mm, "gamma"); Det_Region->SetUserLimits(siliconcuts); // Create detector "volume" with region "Det_Region" and "siliconcuts" G4LogicalVolume* detector = new detector_geometry; Det_Region->AddRootLogicalVolume(detector); //Place detector in halfsensor new G4PVPlacement(0, // no rotation G4ThreeVector(det_X, det_Y, det_Z), detector, // its logical volume "detector", // its name halfsensor, // its mother volume false, // no boolean operations -1); // no particular field //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> //-------------------------------------------------------------------- // New logical volume "foil" //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< G4LogicalVolume* foil = new foil_geometry; new G4PVPlacement(0, // no rotation G4ThreeVector(det_X, det_Y, foil_pips_z() + foil_sep), foil, // its logical volume "foil", // its name halfsensor, // its mother volume false, // no boolean operations 0); // no particular field //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> //-------------------------------------------------------------------- // New magnet_geometry "magnet" //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< magnet_geometry* magnet = new magnet_geometry; static const double mag_Y = (magnet->size_Y + magnet->gap)/2; //Place first magnet new G4PVPlacement(0, // no rotation G4ThreeVector(det_X, det_Y-mag_Y, 0), magnet, // its logical volume "magnet1", // its name halfsensor, // its mother volume false, // no boolean operations 0); // no particular field //Place second magnet new G4PVPlacement(0, // no rotation G4ThreeVector(det_X, det_Y+mag_Y, 0), magnet, // its logical volume "magnet2", // its name halfsensor, // its mother volume false, // no boolean operations 1); // no particular field //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> //-------------------------------------------------------------------- // New apperture_geometry "mag_app" //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< apperture_geometry *mag_app = new apperture_geometry("magnet_apperture", mag_apperture_rout, mag_apperture_ropen, mag_apperture_rings, mag_apperture_distance, mag_apperture_depth ); double magapp_z = mag_pips_z() - mag_apperture_distance + mag_apperture_depth/2; // Rotation matrix for placement G4RotationMatrix *mirror = new G4RotationMatrix; mirror->rotateX(M_PI); new G4PVPlacement(mirror, G4ThreeVector(det_X, det_Y, magapp_z), mag_app, "magnet_apperture", halfsensor, false, 0); //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> //-------------------------------------------------------------------- // New apperture_geometry "foil_app" //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< apperture_geometry *foil_app = new apperture_geometry("foil_apperture", foil_apperture_rout, foil_apperture_ropen, foil_apperture_rings, foil_apperture_distance, foil_apperture_depth ); double foilapp_z = foil_pips_z() + foil_apperture_distance - foil_apperture_depth/2 ; new G4PVPlacement(0, G4ThreeVector(det_X, det_Y, foilapp_z), foil_app, "foil_apperture", halfsensor, false, 0); //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> if (source_window > 0) { G4LogicalVolume *win = new G4LogicalVolume (new G4Tubs("win", 0, foil_apperture_ropen, source_window/2, 0, 2*M_PI ), G4Material::GetMaterial(source_window_mat), "win" ); new G4PVPlacement(0, G4ThreeVector(det_X, det_Y, foilapp_z + foil_apperture_depth/2 + source_window/2+slack), win, "win", halfsensor, false, 0); win->SetVisAttributes(new G4VisAttributes(G4Colour(1, 1, 0))); } //-------------------------------------------------------------------- // here goes all the sensor housings, magnet yoke, ... // Those 3mm vertical bars at each side of the magnets, the outer // one being part of the housing frame, and the inner one being part // of the center/magnet separator. //-------------------------------------------------------------------- G4LogicalVolume *house = new G4LogicalVolume(new G4Box("house", house_thickness/2 - slack, magnet->gap/2 + magnet->size_Y - slack, magnet->size_Z/2 - slack), G4Material::GetMaterial("Al"), "house"); G4VisAttributes *va = new G4VisAttributes(G4Colour(0.2, 0.2, 0.2)); va->SetVisibility(true); house->SetVisAttributes(va); new G4PVPlacement(0, G4ThreeVector(det_X - magnet->size_X/2 - house_thickness/2, det_Y, 0), house, "house_V1", halfsensor, false, 1 ); new G4PVPlacement(0, G4ThreeVector(det_X + magnet->size_X/2 + house_thickness/2, det_Y, 0), house, "house_V2", halfsensor, false, 2 ); //-------------------------------------------------------------------- // Wrap the detector in Aluminum const double delrin_diameter = detector_geometry::stack_diameter; G4LogicalVolume *mag_delrin = new G4LogicalVolume(new G4Tubs("mag_delrin", detector_geometry::hole_diameter/2 + slack, delrin_diameter/2 - slack, mag_delrin_thickness/2 - slack, 0, 2*M_PI ), G4Material::GetMaterial("Al"), "mag_delrin" ); mag_delrin->SetVisAttributes(va); new G4PVPlacement(0, G4ThreeVector(det_X, det_Y, mag_det_z()-mag_delrin_thickness/2), mag_delrin, "mag_delrin", halfsensor, false, 0 ); dG4cerr << "mag Delrin " << mag_delrin_thickness/mm << "mm at z=" << (mag_det_z()-mag_delrin_thickness/2)/mm << "mm" << G4endl ; //-------------------------------------------------------------------- G4LogicalVolume *foil_delrin = new G4LogicalVolume(new G4Tubs("foil_delrin", detector_geometry::hole_diameter/2 + slack, delrin_diameter/2 - slack, foil_delrin_thickness/2 - slack, 0, 2*M_PI ), G4Material::GetMaterial("Al"), "foil_delrin" ); foil_delrin->SetVisAttributes(va); new G4PVPlacement(0, G4ThreeVector(det_X, det_Y, foil_det_z()+foil_delrin_thickness/2), foil_delrin, "foil_delrin", halfsensor, false, 0 ); dG4cerr << "foil Delrin " << foil_delrin_thickness/mm << "mm at z=" << (foil_det_z()+foil_delrin_thickness/2)/mm << "mm" << G4endl ; //-------------------------------------------------------------------- // CLose the Z-gaps with aluminum plates const double plate_diameter = detector_geometry::stack_diameter; const double plate_hole = magnet_geometry::size_X + 1*mm; const double mag_app_plate_thickness = sensor_geometry::mag_apperture_distance - sensor_geometry::mag_apperture_depth - mag_pips_z() - magnet_geometry::size_Z/2 ; G4LogicalVolume *mag_app_plate = new G4LogicalVolume(new G4Tubs("mag_app_plate", plate_hole/2 + slack, plate_diameter/2 - slack, mag_app_plate_thickness/2 - slack, 0, 2*M_PI ), G4Material::GetMaterial("Al"), "mag_app_plate" ); mag_app_plate->SetVisAttributes(va); new G4PVPlacement(0, G4ThreeVector(det_X, det_Y, - magnet_geometry::size_Z/2 - mag_app_plate_thickness/2), mag_app_plate, "mag_app_plate", halfsensor, false, 0 ); dG4cerr << "Magnet App plate " << mag_app_plate_thickness/mm << "mm at z=" << (- magnet_geometry::size_Z/2 - mag_app_plate_thickness/2)/mm << "mm" << G4endl ; //-------------------------------------------------------------------- const double mag_det_plate_thickness = mag_det_z() - magnet_geometry::size_Z/2 - mag_delrin_thickness ; G4LogicalVolume *mag_det_plate = new G4LogicalVolume(new G4Tubs("mag_det_plate", detector_geometry::hole_diameter/2 + slack, plate_diameter/2 - slack, mag_det_plate_thickness/2 - slack, 0, 2*M_PI ), G4Material::GetMaterial("Al"), "mag_det_plate" ); mag_det_plate->SetVisAttributes(va); new G4PVPlacement(0, G4ThreeVector(det_X, det_Y, magnet_geometry::size_Z/2 + mag_det_plate_thickness/2), mag_det_plate, "mag_det_plate", halfsensor, false, 0 ); dG4cerr << "Magnet Det plate " << mag_det_plate_thickness/mm << "mm at z=" << (magnet_geometry::size_Z/2 + mag_det_plate_thickness/2)/mm << "mm" << G4endl ; //-------------------------------------------------------------------- const double foil_det_plate_thickness = foil_pips_z() + sensor_geometry::foil_apperture_distance - sensor_geometry::foil_apperture_depth - foil_det_z() - foil_delrin_thickness ; G4LogicalVolume *foil_det_plate = new G4LogicalVolume(new G4Tubs("foil_det_plate", detector_geometry::hole_diameter/2 + slack, plate_diameter/2 - slack, foil_det_plate_thickness/2 - slack, 0, 2*M_PI ), G4Material::GetMaterial("Al"), "foil_det_plate" ); foil_det_plate->SetVisAttributes(va); new G4PVPlacement(0, G4ThreeVector(det_X, det_Y, foil_det_z() + foil_delrin_thickness + foil_det_plate_thickness/2), foil_det_plate, "foil_det_plate", halfsensor, false, 0 ); dG4cerr << "Foil Det plate " << foil_det_plate_thickness/mm << "mm at z=" << (foil_det_z() + foil_delrin_thickness + foil_det_plate_thickness/2)/mm << "mm" << G4endl ; //-------------------------------------------------------------------- }
[ "08Merlin@web.de" ]
08Merlin@web.de
a0019ab5724902395ba484bf15ce3aa4c7b32816
402e5a36be25d49f913da94a71647dc28a0ef359
/1.ARDUINO PROJECT/28.lcd 16x2/LCD_12c/counter/counter.ino
af4cb10e64b1a0c04fa4678a0f53eeac0c71a77a
[]
no_license
indrabhekti/Arduino-Project-Code
7b74324dab4361ce6de2d8cc669ac93e72e8d741
17f3266ba4f48bdc968ad81a67a813be1eb10aed
refs/heads/main
2023-05-29T01:53:04.504412
2021-06-04T07:27:42
2021-06-04T07:27:42
373,754,838
0
0
null
null
null
null
UTF-8
C++
false
false
772
ino
#include <Wire.h> // Library untuk komunikasi I2C (harus install library) #include <LiquidCrystal_I2C.h> // Library LCD(harus intall library) // SDA pin di A4 and SCL pin di A5. // Connect LCD via I2C, default address 0x27 (default addres harus di cari dulu)(A0-A2 tidak di jumper) LiquidCrystal_I2C lcd = LiquidCrystal_I2C(0x27, 16, 2); // (default addres,panjang kolom lcd,lebar kolom lcd)(0x27,16,2) 0x27 untuk addres ,16x2 LCD. int count = 0; void setup() { lcd.init(); lcd.backlight(); lcd.backlight(); int temp = 10; lcd.clear(); } void loop() { lcd.clear(); lcd.setCursor(0, 0); // lcd.print( "4bit binary"); // isi kata lcd.setCursor(2, 1); // lcd.print( count); count++; if ( count >= 15) count = 0; delay(2000); }
[ "indrabhektiutomo@gmail.com" ]
indrabhektiutomo@gmail.com
89471ed679263c6b644a3babef3631839cd58f8e
c03ca89bc6256e8948eeb2ae171a2e746188fb1b
/GeneralKnowledgeBook.h
e589a71fac9b30b0dbf4ff34a232cf654f13da7f
[]
no_license
ChangeXuan/BookLib-Cpp
45463907e50b48ab9c220b42ffcac60f0128f71b
58549ebe8272f4c92ec68bbb967605fe1403302a
refs/heads/master
2021-01-20T03:34:27.319050
2017-04-27T04:54:42
2017-04-27T04:54:42
89,556,807
0
0
null
null
null
null
UTF-8
C++
false
false
1,306
h
// // Created by Day on 2017/4/25. // #ifndef BOOKLIB_GENERALKNOWLEDGEBOOK_H #define BOOKLIB_GENERALKNOWLEDGEBOOK_H #include <iostream> #include <cstring> #include "Book.h" using namespace std; class GeneralKnowledgeBooks: public Book { private: string typeName; public: GeneralKnowledgeBooks(); ~GeneralKnowledgeBooks(); enum bookType {NOVEL,MAGAZINE,THOUGHT}; void setBookType(const int type); string &getBookType(); void showGeneralKnowledgeBooks(); }; GeneralKnowledgeBooks::GeneralKnowledgeBooks() { } GeneralKnowledgeBooks::~GeneralKnowledgeBooks() { } void GeneralKnowledgeBooks::setBookType(const int type) { switch (type) { case 0: typeName = "Novel"; break; case 1: typeName = "Magazine"; break; case 2: typeName = "Thought"; break; } } string &GeneralKnowledgeBooks::getBookType() { return typeName; } void GeneralKnowledgeBooks::showGeneralKnowledgeBooks() { string name = getName(); int pages = getPages(); float price = getPrice(); cout << "type:" << typeName << endl; cout << "name:" << name << endl; cout << "pages:" << pages << endl; cout << "price:" << price << endl; } #endif //BOOKLIB_GENERALKNOWLEDGEBOOK_H
[ "YourEmailAddress" ]
YourEmailAddress
c9cc7f1ea25916502778ec8c171ae4600ddfbd8a
3054ded5d75ec90aac29ca5d601e726cf835f76c
/Contests/Others/RPC/2016/10th Contest/E.cpp
baed34b78fa2a59f8bbbc0f0145ca5e4ae00d7f6
[]
no_license
Yefri97/Competitive-Programming
ef8c5806881bee797deeb2ef12416eee83c03add
2b267ded55d94c819e720281805fb75696bed311
refs/heads/master
2022-11-09T20:19:00.983516
2022-04-29T21:29:45
2022-04-29T21:29:45
60,136,956
10
0
null
null
null
null
UTF-8
C++
false
false
464
cpp
/* * RPC 10-th Contest 2016 * Problem E: Laser Mirrors * Status: Accepted */ #include <bits/stdc++.h> using namespace std; int eulerPhi(int n) { int ans = n; for (int p = 2; p * p <= n; p++) { if (n % p == 0) ans -= ans / p; while (n % p == 0) n /= p; } if (n != 1) ans -= ans / n; return ans; } int main() { int t; cin >> t; while (t--) { int n; cin >> n; int ans = eulerPhi(n); cout << ans << endl; } return 0; }
[ "yefri.gaitan97@gmail.com" ]
yefri.gaitan97@gmail.com
a3f94b9ce35b5cecaea905cf604056a5b4504af0
f6d9ab3fc22d6e7bd95f330ec35bd1bfca81332e
/rotation.cpp
aba791bbd3eb4ff5ffb971adac0f8d4b55f692fc
[]
no_license
P-dot/C-_Fundamentals
a920fd992a0daff3ab9751675130c596517a5d6d
90463c058ef4c774c2289f44a373b46a4cbaa8b7
refs/heads/master
2020-07-23T13:46:05.731295
2019-09-10T14:14:21
2019-09-10T14:14:21
207,578,574
0
0
null
null
null
null
UTF-8
C++
false
false
610
cpp
//This function performs left and right rotations unsigned char rol(unsigned char val) { int hightbit; if(val & 0x80) // 0x80 is the high bit only highbit = 1; else highbit = 0; // Left shift (bottom bit becomes 0): val <<= 1 // Rotate the high bit onto the bottom: // val |= highbit; return val; } unsigned char ror(unsigned char val) { int lowbit; if(val & 1) // check the low bit lowbit = 1; else lowbit = 0; val >>= 1; // Right shift by one position // Rotate the low bit onto the top val |= (lowbit << 7); return val; }
[ "usuario@kali" ]
usuario@kali
3a50b59a5f8d9255b10e625074da9695fb631217
21e2d8b4300bf4eca4a2aa47731ee947af6c5ddf
/Iterativos/Abadias/Source.cpp
2a342e394c45a834012a25b49407a6f2fa153880
[]
no_license
AdriPanG/EDA
0ecbb97ad895ab5f99382ed2f9804f2ff6182910
2e6d6c5a269114674e5f05fddc3d5b22779b3f62
refs/heads/master
2020-07-10T12:44:22.822964
2017-09-09T12:09:01
2017-09-09T12:09:01
74,014,498
0
1
null
null
null
null
UTF-8
C++
false
false
789
cpp
#include <iostream> using namespace std; //Precondicion: 0<=n<=long(v) and Paratodo i : 0<=i<n : v[i] >= 0 //Postcondicion: #k : 0<=k<n : Paratodo j : k < j < n : a[k] > numero(v,j) //numero(v,k) = max(Paratodo l : k<l<n : v[l]) int calculaAbadias(int v[], int n, int &abadias) { abadias = 0; int numero = 0; for (int i = n; i > 0; i--) { if ((v[i-1] > v[i] && v[i-1] > numero) || i == n) { numero = v[i-1]; abadias++; } } return abadias; } bool resuelve() { int n; int v[100000]; cin >> n; if (n == 0) return false; for (int i = 0; i < n; i++) { cin >> v[i]; } int abadias; calculaAbadias(v, n, abadias); cout << abadias << endl; return true; } int main() { while (resuelve()) { ; } return 0; }
[ "adripana@ucm.es" ]
adripana@ucm.es
dc03bf262efcda0b2a12a8583efa75a41cab189e
6f714dbab92f0507f13aa582fa992277e42c1777
/Plugin/syslog/SysLogMgr.h
f872d871aa9a2f530b9d72310c134748e29784d1
[]
no_license
sinzuo/bluedon-soc
90d72b966ace8d49b470dab791bd65f0d56d520e
809b59888de2f94b345b36ae33afacdbe103a1dd
refs/heads/master
2020-09-20T17:54:20.882559
2019-11-28T02:27:16
2019-11-28T02:27:16
224,552,658
0
1
null
null
null
null
UTF-8
C++
false
false
5,189
h
/** ************************************************ * COPYRIGHT NOTICE * Copyright (c) 2017, BLUEDON * All rights reserved. * * @file SysLogMgr.h * @brief * * * @version 1.0 * @author xxx * @date 2017年08月03日 * * 修订说明:最初版本 **************************************************/ #ifndef _SYSLOG_MGR_H_ #define _SYSLOG_MGR_H_ #include <log4cxx/logger.h> #include <log4cxx/logstring.h> #include <log4cxx/propertyconfigurator.h> #include "common/BDScModuleBase.h" #include "SysLogUdp.h" #include "SysLogTcp.h" #include "config/BDOptions.h" #include "Poco/Mutex.h" #include <vector> #include <set> #include <list> #include <string> //log4xx宏定义 #define SYSLOG_INFO_V(str) LOG4CXX_INFO(log4cxx::Logger::getLogger("SYSLOG"), str); #define SYSLOG_DEBUG_V(str) LOG4CXX_DEBUG(log4cxx::Logger::getLogger("SYSLOG"), str); #define SYSLOG_WARN_V(str) LOG4CXX_WARN(log4cxx::Logger::getLogger("SYSLOG"), str); #define SYSLOG_ERROR_V(str) LOG4CXX_ERROR(log4cxx::Logger::getLogger("SYSLOG"), str); #define SYSLOG_INFO_S(str) LOG4CXX_INFO(log4cxx::Logger::getLogger("SYSLOG"), #str); #define SYSLOG_DEBUG_S(str) LOG4CXX_DEBUG(log4cxx::Logger::getLogger("SYSLOG"), #str); #define SYSLOG_WARN_S(str) LOG4CXX_WARN(log4cxx::Logger::getLogger("SYSLOG"), #str); #define SYSLOG_ERROR_S(str) LOG4CXX_ERROR(log4cxx::Logger::getLogger("SYSLOG"), #str); typedef struct BDSyslogConfigEx { char chLog4File[100]; int nModuleId; char chModuleName[20]; UInt16 wModuleVersion; int nListenPort; char chRecordSep[2]; //记录分隔符 char chFieldSep[2]; //字段分隔符 char chDelimiter[20]; //分割字符串 bool bUseUdpRecv; //是否用udp接收(默认true) unsigned int nListCtrl; //队列长度控制 unsigned int nBreakCtrl; //report跳出控制 unsigned int nSleepTimeMs; //睡眠时间(毫秒) bool nSendtoKafka; //是否直接发送到kafka }tag_syslog_config_t; //udp,tcp方式相同数据变量 class ShareData { public: static Poco::Mutex m_inputMutex; static std::list<std::string> m_strLogList; static string m_strDelimiter; static long list_num; }; class CSysLogMgr:public CScModuleBase { public: CSysLogMgr(const string &strConfigName); virtual ~CSysLogMgr(void); virtual bool Init(void); //初始化数据,先于Start被调用 virtual bool Start(void); //启动模块 virtual bool Stop(void); //停止模块 virtual bool IsRunning(void); //检查模块是否处于运行状态 virtual UInt32 GetModuleId(void); //获取模块id virtual UInt16 GetModuleVersion(void);//获取模块版本 virtual string GetModuleName(void);//获取模块名称 virtual bool StartTask(const PModIntfDataType pDataType,const void * pData); //开始(下发)任务 virtual bool StopTask(const PModIntfDataType pDataType,const void * pData); //停止(取消)任务 virtual bool SetData(const PModIntfDataType pDataType,const void * pData,Poco::UInt32 dwLength);//调用方下发数据 virtual void* GetData(const PModIntfDataType pDataType,Poco::UInt32& dwRetLen); //调用方获取数据 virtual void FreeData(void * pData); //调用方释放获取到的内存 virtual void SetReportData(pFunc_ReportData pCbReport); //设置上报数据调用指针 virtual void SetFetchData(pFunc_FetchData pCbFetch); //设置获取数据调用指针 protected: bool LoadConfig(void); //加载配置文件 void printConfig(); //打印配置信息 bool Load(void); //加载业务数据 bool ReportData(const PModIntfDataType pDataType,const void * pData,Poco::UInt32 dwLength); //上报数据(主要为监控日志) const char* FetchData(const PModIntfDataType pDataType,Poco::UInt32& dwRetLen); //获取客户端系统参数 private: static string fromBase64(const std::string &source); static void* OnSatrtUdpServer(void *arg); //开启UDP监听以及I/O事件检测 static void* OnSatrtTcpServer(void *arg); //开启TCP监听以及I/O事件检测 static void* OnFetchHandle(void *arg); //Fetch Data 事件线程处理函数 static void* OnReportHandle(void *arg); //Report Data 事件线程处理函数 private: pFunc_ReportData m_pFuncReportData; pFunc_FetchData m_pFuncFetchData; std::string m_strConfigName; //pthread_t p_thread_fetch; //Poco::Mutex m_mutex_fetch; //m_setFetch 队列互斥锁 //list<modintf_datatype_t> m_listFetch; //Fetch 数据任务队列 Poco::FastMutex m_ModMutex; pthread_t p_thread_report; pthread_t p_thread_server; //Poco::Mutex m_mutex_report; UdpClientService* pServer; TcpClientAcceptor* pTcpServer; //add in 2017.04.25 bool m_bIsRunning; bool m_bServerState; //m_bUdpServerState std::set<std::string> m_setPolicy; public: tag_syslog_config_t m_sysLogConfig; }; #endif //_SYSLOG_MGR_H_
[ "1586706912@qq.com" ]
1586706912@qq.com
f13090370ca4d4379e2ad49eebd5360fe2357af9
66949a25a8764ff303887253f5dc3725b026336e
/HelloWorld/datasheet.h
79654e66aaa2797b2e059636c9ea69e7f8ebb0d2
[]
no_license
juniorprincewang/MRL
7526ef76a1c564b7e8b4314e55e46e68faa944bb
b76fa14749e6241ea493d49dbd7b462dbdb5c66e
refs/heads/master
2021-01-18T22:29:30.866122
2017-05-16T01:02:10
2017-05-16T01:02:10
72,534,367
0
0
null
null
null
null
UTF-8
C++
false
false
3,205
h
#pragma execution_character_set("utf-8") #ifndef DATASHEET_H #define DATASHEET_H #include <QLabel> #include <QTableWidget> #include <QLineEdit> #include <QTableWidgetItem> #include <QAction> #include <QItemDelegate> #include <QTableWidgetItem> #include <QString> //#include <QtWidgets> #include <QObject> #include "publicdata.h" class DataSheet : public QWidget { Q_OBJECT public: DataSheet(int rows, int cols, QStringList headers, QWidget *parent = 0); DataSheet(int rows, int cols, QWidget *parent = 0); QVector<double> updateAcuteContents(AssessData *data); QVector<double> updateChronicContents(AssessData *data); void setHeader(QStringList headers); public slots: void updateColor(QTableWidgetItem *item); void returnPressed(); void selectColor(); void selectFont(); void clear(); void actionSum(); void actionAdd(); void actionSubtract(); void actionMultiply(); void actionDivide(); protected: void setupContents(); void createActions(); void actionMath_helper(const QString &title, const QString &op); bool runInputDialog(const QString &title, const QString &c1Text, const QString &c2Text, const QString &opText, const QString &outText, QString *cell1, QString *cell2, QString *outCell); private: QAction *colorAction; QAction *fontAction; QAction *firstSeparator; QAction *cell_sumAction; QAction *cell_addAction; QAction *cell_subAction; QAction *cell_mulAction; QAction *cell_divAction; QAction *secondSeparator; QAction *clearAction; QAction *printAction; QTableWidget *table; }; void decode_position(const QString &pos, int *row, int *col); QString encode_position(int row, int col); enum Columns { COL_NAME, COL_FI, COL_STMR, COL_SOURCE, COL_NEDI, COL_ALL, COL_PERCENT }; class DataSheetItem : public QTableWidgetItem { public: DataSheetItem(); DataSheetItem(const QString &text); QTableWidgetItem *clone() const override; QVariant data(int role) const override; void setData(int role, const QVariant &value) override; QVariant display() const; inline QString formula() const { return QTableWidgetItem::data(Qt::DisplayRole).toString(); } static QVariant computeFormula(const QString &formula, const QTableWidget *widget, const QTableWidgetItem *self = 0); private: mutable bool isResolving; }; class DataSheetDelegate : public QItemDelegate { Q_OBJECT public: DataSheetDelegate(QObject *parent = 0); QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &, const QModelIndex &index) const override; void setEditorData(QWidget *editor, const QModelIndex &index) const override; void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const override; private slots: void commitAndCloseEditor(); void comboBoxChanged(); }; #endif // DATASHEET_H
[ "15201615161@163.com" ]
15201615161@163.com
8c19b48befe5dfb1f1fb01abd44266be61a0078b
85e7114ea63a080c1b9b0579e66c7a2d126cffec
/SDK/SoT_BP_LegendaryTavern_functions.cpp
e8d85971f204ded3e5d4ab3f3d6bb60e453c67eb
[]
no_license
EO-Zanzo/SeaOfThieves-Hack
97094307d943c2b8e2af071ba777a000cf1369c2
d8e2a77b1553154e1d911a3e0c4e68ff1c02ee51
refs/heads/master
2020-04-02T14:18:24.844616
2018-10-24T15:02:43
2018-10-24T15:02:43
154,519,316
0
2
null
null
null
null
UTF-8
C++
false
false
774
cpp
// Sea of Thieves (1.2.6) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "SoT_BP_LegendaryTavern_parameters.hpp" namespace SDK { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function BP_LegendaryTavern.BP_LegendaryTavern_C.UserConstructionScript // (Event, Public, BlueprintCallable, BlueprintEvent) void ABP_LegendaryTavern_C::UserConstructionScript() { static auto fn = UObject::FindObject<UFunction>("Function BP_LegendaryTavern.BP_LegendaryTavern_C.UserConstructionScript"); ABP_LegendaryTavern_C_UserConstructionScript_Params params; UObject::ProcessEvent(fn, &params); } } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "zp2kshield@gmail.com" ]
zp2kshield@gmail.com
e2013904b1a32822b7b4040eeb04826211e6c0c1
5b6268310d80a288f1c5248b2b99f0bc697fcbe4
/linux/ftpServer/FTPServer.cpp
9cc36fb861278055429cf1903a579c935256ef15
[]
no_license
shanlihou/cppDemo
9b9a6a2a90b66d043067b7adf7c8abb9068c811d
2058b6c06cada10c82a25500b33afb8594f35203
refs/heads/master
2021-08-27T22:00:42.649146
2017-12-10T12:47:14
2017-12-10T12:47:14
113,749,151
0
0
null
null
null
null
UTF-8
C++
false
false
69
cpp
#include "myEpoll.h" int main() { MyEpoll::getInstance()->run(); }
[ "shanlihou@gmail.com" ]
shanlihou@gmail.com
db09a88804601d12b545a70315ebab227ff0e4bd
68ed77e9af79655e78f8a61594cc1b12bd278f59
/src/gps/UtcTime.cpp
0ed86c1efcf7d0bcab88d0b230120c02f2a1938a
[ "MIT" ]
permissive
havardhellvik/sensors-and-senders
4ef79205124471d1add5f4ddae14ed004360a2bf
9323457a91e0fcdddfbfe3ffea5fba5a7ed7591d
refs/heads/master
2023-08-16T01:03:28.533747
2021-10-04T10:00:45
2021-10-04T10:02:58
418,494,603
0
0
null
null
null
null
UTF-8
C++
false
false
613
cpp
#include "UtcTime.hpp" #include <cmath> UtcTime::UtcTime() : _start(std::chrono::system_clock::now()) { } double UtcTime::time() const { const auto now = std::chrono::system_clock::now(); std::chrono::duration<double> time_since_start = now - _start; const auto seconds_since_start = time_since_start.count(); const auto hours = std::floor(seconds_since_start / 3600.0); const auto minutes = std::floor(seconds_since_start / 60.0) - hours * 60; const auto seconds = seconds_since_start - hours * 3600 - minutes * 60; return hours * 10000 + minutes * 100 + seconds; }
[ "thomas.evang@km.kongsberg.com" ]
thomas.evang@km.kongsberg.com
64ee64c7c84f209d271be303584ac184cd24faea
ba9322f7db02d797f6984298d892f74768193dcf
/ccc/src/model/GetJobStatusByCallIdRequest.cc
d4d551444671d8680d407ca30da4de44aa90a7d2
[ "Apache-2.0" ]
permissive
sdk-team/aliyun-openapi-cpp-sdk
e27f91996b3bad9226c86f74475b5a1a91806861
a27fc0000a2b061cd10df09cbe4fff9db4a7c707
refs/heads/master
2022-08-21T18:25:53.080066
2022-07-25T10:01:05
2022-07-25T10:01:05
183,356,893
3
0
null
2019-04-25T04:34:29
2019-04-25T04:34:28
null
UTF-8
C++
false
false
1,418
cc
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/ccc/model/GetJobStatusByCallIdRequest.h> using AlibabaCloud::CCC::Model::GetJobStatusByCallIdRequest; GetJobStatusByCallIdRequest::GetJobStatusByCallIdRequest() : RpcServiceRequest("ccc", "2017-07-05", "GetJobStatusByCallId") {} GetJobStatusByCallIdRequest::~GetJobStatusByCallIdRequest() {} std::string GetJobStatusByCallIdRequest::getCallId()const { return callId_; } void GetJobStatusByCallIdRequest::setCallId(const std::string& callId) { callId_ = callId; setParameter("CallId", callId); } std::string GetJobStatusByCallIdRequest::getInstanceId()const { return instanceId_; } void GetJobStatusByCallIdRequest::setInstanceId(const std::string& instanceId) { instanceId_ = instanceId; setParameter("InstanceId", instanceId); }
[ "yixiong.jxy@alibaba-inc.com" ]
yixiong.jxy@alibaba-inc.com
39013a60b41c5ed40342738692c2520bf62421fd
c28515164119e13a9fb4ac10e955d4d0838e7572
/adapters/omnetpp/seed/applications/seed_onoff_client_message_m.h
ba0a8d36f881eecb881c898edaea7496e4278d79
[ "BSD-2-Clause" ]
permissive
kit-tm/seed
ba23bf10f941d462842c2efb6aae307fabefee88
c6d4eaffbe25615b396aeabeae7305b724260d92
refs/heads/master
2021-08-31T18:11:43.488896
2017-12-21T12:48:54
2017-12-21T12:48:54
115,101,138
0
0
null
null
null
null
UTF-8
C++
false
false
2,647
h
// // Generated file, do not edit! Created by nedtool 4.6 from seed_onoff_client_message.msg. // #ifndef _SEED_ONOFF_CLIENT_MESSAGE_M_H_ #define _SEED_ONOFF_CLIENT_MESSAGE_M_H_ #include <omnetpp.h> // nedtool version check #define MSGC_VERSION 0x0406 #if (MSGC_VERSION!=OMNETPP_VERSION) # error Version mismatch! Probably this file was generated by an earlier version of nedtool: 'make clean' should help. #endif /** * Class generated from <tt>seed_onoff_client_message.msg:2</tt> by nedtool. * <pre> * message OnOffMessage * { * int connId; * } * </pre> */ class OnOffMessage : public ::cMessage { protected: int connId_var; private: void copy(const OnOffMessage& other); protected: // protected and unimplemented operator==(), to prevent accidental usage bool operator==(const OnOffMessage&); public: OnOffMessage(const char *name=NULL, int kind=0); OnOffMessage(const OnOffMessage& other); virtual ~OnOffMessage(); OnOffMessage& operator=(const OnOffMessage& other); virtual OnOffMessage *dup() const {return new OnOffMessage(*this);} virtual void parsimPack(cCommBuffer *b); virtual void parsimUnpack(cCommBuffer *b); // field getter/setter methods virtual int getConnId() const; virtual void setConnId(int connId); }; inline void doPacking(cCommBuffer *b, OnOffMessage& obj) {obj.parsimPack(b);} inline void doUnpacking(cCommBuffer *b, OnOffMessage& obj) {obj.parsimUnpack(b);} /** * Class generated from <tt>seed_onoff_client_message.msg:7</tt> by nedtool. * <pre> * message SendPacketMessage * { * int connId; * } * </pre> */ class SendPacketMessage : public ::cMessage { protected: int connId_var; private: void copy(const SendPacketMessage& other); protected: // protected and unimplemented operator==(), to prevent accidental usage bool operator==(const SendPacketMessage&); public: SendPacketMessage(const char *name=NULL, int kind=0); SendPacketMessage(const SendPacketMessage& other); virtual ~SendPacketMessage(); SendPacketMessage& operator=(const SendPacketMessage& other); virtual SendPacketMessage *dup() const {return new SendPacketMessage(*this);} virtual void parsimPack(cCommBuffer *b); virtual void parsimUnpack(cCommBuffer *b); // field getter/setter methods virtual int getConnId() const; virtual void setConnId(int connId); }; inline void doPacking(cCommBuffer *b, SendPacketMessage& obj) {obj.parsimPack(b);} inline void doUnpacking(cCommBuffer *b, SendPacketMessage& obj) {obj.parsimUnpack(b);} #endif // ifndef _SEED_ONOFF_CLIENT_MESSAGE_M_H_
[ "addis.dittebrandt@gmail.com" ]
addis.dittebrandt@gmail.com
ce3ad0b0714892a4dc1c23c65849ea6482fedec0
bb0efbc98574362ec2a769ba5d3c746a761a9d6a
/branches/avilanova/plugins/stable/GpuGlyphs/GPUGlyphs/vtkGlyphMapper.h
edf52951c6b12151c8fb3a7abb7b7c3d101a497d
[]
no_license
BackupTheBerlios/viste-tool-svn
4a19d5c5b9e2148b272d02c82fda8e6a9d041298
9692cff93e5a1b6dcbd47cad189618b556ec65bb
refs/heads/master
2021-01-23T11:07:25.738114
2014-02-06T18:38:54
2014-02-06T18:38:54
40,748,200
0
0
null
null
null
null
UTF-8
C++
false
false
3,500
h
/** * vtkGlyphMapper.h * by Tim Peeters * * 2008-02-27 Tim Peeters * - First version */ #ifndef bmia_vtkGlyphMapper_h #define bmia_vtkGlyphMapper_h #include <vtkVolumeMapper.h> class vtkPointSet; namespace bmia { class vtkMyShaderProgram; class vtkUniformFloat; class vtkUniformIvec3; class vtkUniformVec3; class vtkFBO; class vtkUniformSampler; class vtkUniformBool; /** * Superclass for GPU-based glyph rendering methods. * Volume data is stored in GPU memory using 3D textures. */ class vtkGlyphMapper : public vtkVolumeMapper { public: virtual void Render(vtkRenderer *ren, vtkVolume *vol); /** * Set/Get the PointSet that defines the seed points * for the glyphs to render. */ void SetSeedPoints(vtkPointSet* points); vtkGetObjectMacro(SeedPoints, vtkPointSet); /** * Set/Get the maximum radius of the glyphs in any direction. * This is used for constructing the bounding boxes around the * glyphs in DrawPoints. */ void SetMaxGlyphRadius(float r); vtkGetMacro(MaxGlyphRadius, float); void SetNegateX(bool negate); void SetNegateY(bool negate); void SetNegateZ(bool negate); bool GetNegateX(); bool GetNegateY(); bool GetNegateZ(); void PrintNumberOfSeedPoints(); void SetGlyphScaling(float scale); vtkGetMacro(GlyphScaling, float); protected: vtkGlyphMapper(); ~vtkGlyphMapper(); /** * To be called in subclasses after the shader programs have * been set-up. */ virtual void SetupShaderUniforms(); /** * Check for the needed OpenGL extensions and load them. * When done, set this->Initialized. */ void Initialize(); /** * Load all needed textures. * This function can call LoadTexture(...). */ virtual void LoadTextures() = 0; /** * Load texture and bind it to index texture_index. * The texture data comes from the input ImageData in array * with name array_name. */ void LoadTexture(int texture_index, const char* array_name); /** * Draw the points of the input data. * This method draws bounding boxes around the points such that * the glyphs, with maximum radius MaxGlyphRadius will always fit * in. In some cases (e.g. with lines), this function can be * overridden to use a more restricted bounding box. */ virtual void DrawPoints(); /** * Shader program for rendering to depth buffer. * No lighting calculations need to be done here. */ vtkMyShaderProgram* SPDepth; /** * Shader program for rendering the final scene to the screen. */ vtkMyShaderProgram* SPLight; /** * Call this after activating the shader program! */ virtual void SetTextureLocations() {}; void SetTextureLocation(vtkMyShaderProgram* sp, vtkUniformSampler* sampler); //, const char* texture_name); /** * Draw screen-filling quad ;) */ // void DrawScreenFillingQuad(int width, int height); void DrawScreenFillingQuad(int viewport[4]); private: double GlyphScaling; double MaxGlyphRadius; vtkPointSet* SeedPoints; vtkUniformVec3* UEyePosition; vtkUniformVec3* ULightPosition; vtkUniformIvec3* UTextureDimensions; vtkUniformVec3* UTextureSpacing; vtkUniformFloat* UMaxGlyphRadius; vtkUniformFloat* UGlyphScaling; // vtkShadowMappingHelper* ShadowMappingHelper; vtkFBO* FBODepth; vtkFBO* FBOShadow; bool Initialized; vtkUniformBool* UNegateX; vtkUniformBool* UNegateY; vtkUniformBool* UNegateZ; }; // class vtkGlyphMapper } // namespace bmia #endif // bmia_vtkGlyphMapper_h
[ "viste-tue@ae44682b-4238-4e27-a57b-dd11a28b3479" ]
viste-tue@ae44682b-4238-4e27-a57b-dd11a28b3479
e0a16bd4317247939e2026b017b5bf9962a9e026
e3b588ac490d4ac67a691a618102ef6126096d19
/solution2.cpp
445b4dd9f96ac01851e1dadbd22e363e3759ea9d
[]
no_license
oooooome/LeetCode-cmake
c82d28da56ff12fb40b6b0eeaafc0d5d809b3072
38299c8f4aefd36c235a5bb20ea660c114a4c2e7
refs/heads/master
2023-08-31T04:52:21.098309
2021-10-26T14:06:04
2021-10-26T14:06:04
403,633,759
0
0
null
null
null
null
UTF-8
C++
false
false
1,726
cpp
#include <iostream> //Definition for singly-linked list. struct ListNode { int val; ListNode* next; ListNode() : val(0), next(nullptr) {} ListNode(int x) : val(x), next(nullptr) {} ListNode(int x, ListNode* next) : val(x), next(next) {} }; class Solution2 { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode* res = new ListNode((l1->val + l2->val) % 10); addNode(l1->next, l2->next, (l1->val + l2->val) / 10, res); return res; } void addNode(ListNode* l1, ListNode* l2, int i, ListNode* forwardNode) { ListNode l1o; ListNode l2o; if (l1 != nullptr) { l1o.val = l1->val; l1o.next = l1->next; }else if(i == 0) { forwardNode->next = l2; return; } if (l2 != nullptr) { l2o.val = l2->val; l2o.next = l2->next; }else if(i == 0) { forwardNode->next = l1; return; } int One = (l1o.val + l2o.val + i) % 10; int Ten = (l1o.val + l2o.val + i) / 10; ListNode* res = new ListNode(One); forwardNode->next = res; if (One == 0 && Ten == 0 && l1->next == nullptr && l2->next == nullptr) { return; } else { addNode(l1o.next, l2o.next, Ten, res); } } }; int main() { ListNode l11{ 1, nullptr }; ListNode l12{ 6, &l11 }; ListNode l13{ 0, &l12 }; ListNode l14{ 3, &l13 }; ListNode l15{ 3, &l14 }; /*[1, 6, 0, 3, 3, 6, 7, 2, 0, 1] [6, 3, 0, 8, 9, 6, 6, 9, 6, 1]*/ ListNode l21{ 6, nullptr }; ListNode l22{ 3, &l21 }; ListNode l23{ 0, &l22 }; ListNode l24{ 8, &l23 }; ListNode l25{ 9, &l24 }; ListNode* l1 = &l15; ListNode* l2 = &l25; Solution2 s{}; auto res = s.addTwoNumbers(l1, l2); for (;;) { if (res == nullptr) { break;; } std::cout << res->val; res = res->next; } return 0; }
[ "liruijie@ebupt.com" ]
liruijie@ebupt.com
dd545f02defc260c0984699e2ea0ed24a7d7b9a7
12d3908fc4a374e056041df306e383d95d8ff047
/Programs/prog18.cpp
4358fff151f3f9f7bfa8d3e05c54ddf03421d705
[ "MIT" ]
permissive
rux616/c201
aca5898c506aeb1792aa8b1f9dcf3d797a1cd888
d8509e8d49e52e7326486249ad8d567560bf4ad4
refs/heads/master
2021-01-01T16:14:44.747670
2017-07-20T05:14:24
2017-07-20T05:14:24
97,792,948
0
0
null
null
null
null
UTF-8
C++
false
false
1,991
cpp
/* Prog18.cpp This is a variation of prog17 that demonstrates some struct pointer syntax. ----------------------------------------------------------------------*/ #include <iostream> #include <string> using namespace std; void main (void) { struct StudentRecord { char Name[32]; long IDnumber; int NumberOfExams; int ExamScore[5]; }; StudentRecord Student; StudentRecord *Ptr; // A pointer to a StudentRecord struct strcpy (Student.Name, "John Smith"); Student.IDnumber = 1234321; Student.NumberOfExams = 0; cout << "Student.Name = " << Student.Name << endl; cout << "Student.IDnumber = " << Student.IDnumber << endl; cout << "Student.NumberOfExams = " << Student.NumberOfExams << "\n\n"; Ptr = &Student; cout << "(*Ptr).IDnumber = " << (*Ptr).IDnumber << endl; cout << " Ptr->IDnumber = " << Ptr->IDnumber << endl; } /*-------------------- Program Output ------------------------------ Student.Name = John Smith Student.IDnumber = 1234321 Student.NumberOfExams = 0 (*Ptr).IDnumber = 1234321 Ptr->IDnumber = 1234321 ===================== Program Comments =========================== 1) The assignment statement "Ptr = &Student;" assigns the address of the variable Student to the pointer variable Ptr, i.e. "points" Ptr at Student. 2) Since Ptr holds the address of Student, *Ptr is an alias (another name) for Student. To reference the fields of Student in this way, parentheses are needed around "*Ptr" since the "." operator has very high precedence. This means that the rather awkward reference "(*Ptr).IDnumber)" must be made to access the field IDnumber. Fortunately, C provides another notation that can be used with pointers to record structures. In the example above, "Ptr->IDnumber" is used. */
[ "dan.cassidy.1983@gmail.com" ]
dan.cassidy.1983@gmail.com
de2bd2cbf33c6efe91c3f714de15a82e63a7c231
b3be27b4bf494270c5c953cf711088a10f79de81
/src/catalog/plx/unicode/utf16_from_utf8.h
65dd0c243257578e7faf7d3d53be2bde10422e74
[]
no_license
cpizano/Plex
2973b606933eb14198e337eeb45e725201799e7a
b5ab6224ddb1a1ca0aa59b6f585ec601c913cb15
refs/heads/master
2016-09-05T18:42:34.431460
2016-01-03T21:56:09
2016-01-03T21:56:09
6,571,011
0
0
null
null
null
null
UTF-8
C++
false
false
935
h
//#~def plx::UTF16FromUTF8 /////////////////////////////////////////////////////////////////////////////// // plx::UTF16FromUTF8 namespace plx { std::wstring UTF16FromUTF8(const plx::Range<const uint8_t>& utf8, bool strict) { if (utf8.empty()) return std::wstring(); // Get length and validate string. const int utf16_len = ::MultiByteToWideChar( CP_UTF8, strict ? MB_ERR_INVALID_CHARS : 0, reinterpret_cast<const char*>(utf8.start()), plx::To<int>(utf8.size()), NULL, 0); if (utf16_len == 0) { throw plx::CodecException(__LINE__, nullptr); } std::wstring utf16; utf16.resize(utf16_len); // Now do the conversion without validation. if (!::MultiByteToWideChar( CP_UTF8, 0, reinterpret_cast<const char*>(utf8.start()), plx::To<int>(utf8.size()), &utf16[0], utf16_len)) { throw plx::CodecException(__LINE__, nullptr); } return utf16; } }
[ "cpu@chromium.org" ]
cpu@chromium.org
a052284e3d310e4510f3a1e13d2c297858e01c51
5c56bb3fd918c7d267a5f8dc24470379ea1a3271
/PandaChatServer/mysqlapi/DatabaseMysql.cpp
5c419e6491903210e7bb6257532728b00e256abf
[]
no_license
eric8068/PandaChatProject
8009f267733f5290bedf051f3f6aa0a9216956f0
e374c4ee8446a0c779e426f8542485278b229e89
refs/heads/master
2023-03-18T17:12:22.296316
2020-08-31T05:11:58
2020-08-31T05:11:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,010
cpp
#include "DatabaseMysql.h" #include <fstream> #include <stdarg.h> #include <string.h> //#include "../base/AsyncLog.h" CDatabaseMysql::CDatabaseMysql(void) { //m_Mysql = new MYSQL; m_Mysql = NULL; m_bInit = false; } CDatabaseMysql::~CDatabaseMysql(void) { if (m_Mysql != NULL) { if (m_bInit) { mysql_close(m_Mysql); } //delete m_Mysql; } } bool CDatabaseMysql::initialize(const std::string& host, const std::string& user, const std::string& pwd, const std::string& dbname) { //LOGI << "CDatabaseMysql::Initialize, begin..."; //ClearStoredResults(); if (m_bInit) { mysql_close(m_Mysql); } m_Mysql = mysql_init(m_Mysql); m_Mysql = mysql_real_connect(m_Mysql, host.c_str(), user.c_str(), pwd.c_str(), dbname.c_str(), 0, NULL, 0); //ClearStoredResults(); //LOGI << "mysql info: host=" << host << ", user=" << user << ", password=" << pwd << ", dbname=" << dbname; m_DBInfo.strDBName = dbname; m_DBInfo.strHost = host; m_DBInfo.strUser = user; m_DBInfo.strPwd = pwd; if (m_Mysql) { //LOGI << "m_Mysql address " << (long)m_Mysql; //LOGI << "CDatabaseMysql::Initialize, set names utf8"; mysql_query(m_Mysql, "set names utf8"); //mysql_query(m_Mysql, "set names latin1"); m_bInit = true; return true; } else { //LOGE << "Could not connect to MySQL database at " << host.c_str() // << ", " << mysql_error(m_Mysql); mysql_close(m_Mysql); return false; } //LOGI << "CDatabaseMysql::Initialize, init failed!"; return false; } //TODO: 这个函数要区分一下空数据集和出错两种情况 QueryResult* CDatabaseMysql::query(const char* sql) { if (!m_Mysql) { //LOGI << "CDatabaseMysql::Query, mysql is disconnected!"; if (false == initialize(m_DBInfo.strHost, m_DBInfo.strUser, m_DBInfo.strPwd, m_DBInfo.strDBName)) { return NULL; } } if (!m_Mysql) return 0; MYSQL_RES* result = 0; uint64_t rowCount = 0; uint32_t fieldCount = 0; { //LOGI << sql; int iTempRet = mysql_real_query(m_Mysql, sql, strlen(sql)); if (iTempRet) { unsigned int uErrno = mysql_errno(m_Mysql); //LOGI << "CDatabaseMysql::Query, mysql is abnormal, errno : " << uErrno; if (CR_SERVER_GONE_ERROR == uErrno) { //LOGI << "CDatabaseMysql::Query, mysql is disconnected!"; if (false == initialize(m_DBInfo.strHost, m_DBInfo.strUser, m_DBInfo.strPwd, m_DBInfo.strDBName)) { return NULL; } //LOGI << sql; iTempRet = mysql_real_query(m_Mysql, sql, strlen(sql)); if (iTempRet) { //LOGE << "SQL: " << sql ; //LOGE << "query ERROR: " << mysql_error(m_Mysql); } } else { //LOGE << "SQL: " << sql ; //LOGE << "query ERROR: " << mysql_error(m_Mysql); return NULL; } } //LOGI << "call mysql_store_result"; result = mysql_store_result(m_Mysql); rowCount = mysql_affected_rows(m_Mysql); fieldCount = mysql_field_count(m_Mysql); // end guarded block } if (!result) return NULL; // if (!rowCount) // { //LOGI << "call mysql_free_result"; // mysql_free_result(result); // return NULL; // } QueryResult* queryResult = new QueryResult(result, rowCount, fieldCount); queryResult->nextRow(); return queryResult; } QueryResult* CDatabaseMysql::pquery(const char* format, ...) { if (!format) return NULL; va_list ap; char szQuery[MAX_QUERY_LEN]; va_start(ap, format); int res = vsnprintf(szQuery, MAX_QUERY_LEN, format, ap); va_end(ap); if (res == -1) { //LOGE << "SQL Query truncated (and not execute) for format: " << format; return NULL; } return query(szQuery); } bool CDatabaseMysql::execute(const char* sql) { if (!m_Mysql) return false; { int iTempRet = mysql_query(m_Mysql, sql); if (iTempRet) { unsigned int uErrno = mysql_errno(m_Mysql); //LOGI << "CDatabaseMysql::Query, mysql is abnormal, errno : " << uErrno; if (CR_SERVER_GONE_ERROR == uErrno) { //LOGI << "CDatabaseMysql::Query, mysql is disconnected!"; if (false == initialize(m_DBInfo.strHost, m_DBInfo.strUser, m_DBInfo.strPwd, m_DBInfo.strDBName)) { return false; } //LOGI << sql; iTempRet = mysql_real_query(m_Mysql, sql, strlen(sql)); if (iTempRet) { // LOGE("sql error: %s, sql: %s", mysql_error(m_Mysql), sql); //LOGE << "query ERROR: " << mysql_error(m_Mysql); } } else { //LOGE << "SQL: " << sql; //LOGE << "query ERROR: " << mysql_error(m_Mysql); //LOGE("sql error: %s, sql: %s", mysql_error(m_Mysql), sql); } return false; } } return true; } bool CDatabaseMysql::execute(const char* sql, uint32_t& uAffectedCount, int& nErrno) { if (!m_Mysql) return false; { int iTempRet = mysql_query(m_Mysql, sql); if (iTempRet) { unsigned int uErrno = mysql_errno(m_Mysql); //LOGE << "CDatabaseMysql::Query, mysql is abnormal, errno : " << uErrno; if (CR_SERVER_GONE_ERROR == uErrno) { //LOGE << "CDatabaseMysql::Query, mysql is disconnected!"; if (false == initialize(m_DBInfo.strHost, m_DBInfo.strUser, m_DBInfo.strPwd, m_DBInfo.strDBName)) { return false; } //LOGI << sql; iTempRet = mysql_query(m_Mysql, sql); nErrno = iTempRet; if (iTempRet) { //LOGE << "SQL: " << sql; //LOGE << "query ERROR: " << mysql_error(m_Mysql); } } else { //LOGE << "SQL: " << sql; //LOGE << "query ERROR: " << mysql_error(m_Mysql); } return false; } uAffectedCount = static_cast<uint32_t>(mysql_affected_rows(m_Mysql)); } return true; } bool CDatabaseMysql::pexecute(const char* format, ...) { if (!format) return false; va_list ap; char szQuery[MAX_QUERY_LEN]; va_start(ap, format); int res = vsnprintf(szQuery, MAX_QUERY_LEN, format, ap); va_end(ap); if (res == -1) { //LOGE << "SQL Query truncated (and not execute) for format: " << format; return false; } if (!m_Mysql) return false; { int iTempRet = mysql_query(m_Mysql, szQuery); if (iTempRet) { unsigned int uErrno = mysql_errno(m_Mysql); //LOGE << "CDatabaseMysql::Query, mysql is abnormal, errno : " << uErrno; if (CR_SERVER_GONE_ERROR == uErrno) { //LOGE << "CDatabaseMysql::Query, mysql is disconnected!"; if (false == initialize(m_DBInfo.strHost, m_DBInfo.strUser, m_DBInfo.strPwd, m_DBInfo.strDBName)) { return false; } //LOGI << szQuery; iTempRet = mysql_query(m_Mysql, szQuery); if (iTempRet) { //LOGE << "SQL: " << szQuery; //LOGE << "query ERROR: " << mysql_error(m_Mysql); } } else { //LOGE << "SQL: " << szQuery; //LOGE << "query ERROR: " << mysql_error(m_Mysql); } return false; } } return true; } void CDatabaseMysql::clearStoredResults() { if (!m_Mysql) { return; } MYSQL_RES* result = NULL; while (!mysql_next_result(m_Mysql)) { if ((result = mysql_store_result(m_Mysql)) != NULL) { mysql_free_result(result); } } } uint32_t CDatabaseMysql::getInsertID() { return (uint32_t)mysql_insert_id(m_Mysql); } int32_t CDatabaseMysql::escapeString(char* szDst, const char* szSrc, uint32_t uSize) { if (m_Mysql == NULL) { return 0; } if (szDst == NULL || szSrc == NULL) { return 0; } return mysql_real_escape_string(m_Mysql, szDst, szSrc, uSize); }
[ "405126907@qq.com" ]
405126907@qq.com
db183aadd494908d01dfa0ea5e0f5fae234ee239
a76a2581d5d3c1ec2f9529ab4d1db9f9828341d8
/Common/src/Common/String.h
d0adeb2adebc3c722db8a8ba6246b87ff7cfdd4e
[]
no_license
YanChernikov/IntroToAI
b16f9f08b448db97cf940b299b2a2769b61c9408
9b242862616588c4baf048f07d898083cb5f7caf
refs/heads/master
2021-01-18T21:18:47.738424
2016-05-20T05:08:54
2016-05-20T05:08:54
54,003,690
1
1
null
null
null
null
UTF-8
C++
false
false
1,067
h
#pragma once #include <string> #include <vector> // A series of string manipulation functions that proved useful for parsing // the input text file typedef std::string String; typedef std::vector<String> StringList; String ReadStringFromFile(const String& path); StringList ReadLinesFromFile(const String& path); void WriteStringToFile(const String& string, const String& path); StringList SplitString(const String& string, const String& delimiters); StringList SplitString(const String& string, const char delimiter); StringList Tokenize(const String& string); StringList GetLines(const String& string); const char* FindToken(const char* str, const String& token); const char* FindToken(const String& string, const String& token); String GetBlock(const char* str, const char** outPosition = nullptr); String GetBlock(const String& string, int offset = 0); String GetStatement(const char* str, const char** outPosition = nullptr); bool StartsWith(const String& string, const String& start); int NextInt(const String& string);
[ "yan@tracnode.com" ]
yan@tracnode.com
e2a02bf56df5e0d7f9a40bf61fd226921128a591
90047daeb462598a924d76ddf4288e832e86417c
/chromeos/printing/ppd_provider.cc
aa62d8b35c737ca08ee08911e5d6f78b4f9c4d6c
[ "BSD-3-Clause" ]
permissive
massbrowser/android
99b8c21fa4552a13c06bbedd0f9c88dd4a4ad080
a9c4371682c9443d6e1d66005d4db61a24a9617c
refs/heads/master
2022-11-04T21:15:50.656802
2017-06-08T12:31:39
2017-06-08T12:31:39
93,747,579
2
2
BSD-3-Clause
2022-10-31T10:34:25
2017-06-08T12:36:07
null
UTF-8
C++
false
false
39,322
cc
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chromeos/printing/ppd_provider.h" #include <algorithm> #include <deque> #include <set> #include <unordered_map> #include <utility> #include <vector> #include "base/base64.h" #include "base/bind_helpers.h" #include "base/files/file.h" #include "base/files/file_util.h" #include "base/json/json_parser.h" #include "base/memory/ptr_util.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_split.h" #include "base/strings/string_tokenizer.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/synchronization/lock.h" #include "base/task_runner_util.h" #include "base/threading/sequenced_task_runner_handle.h" #include "base/threading/thread_restrictions.h" #include "base/time/time.h" #include "base/values.h" #include "chromeos/printing/ppd_cache.h" #include "chromeos/printing/printing_constants.h" #include "net/base/load_flags.h" #include "net/http/http_status_code.h" #include "net/url_request/url_fetcher.h" #include "net/url_request/url_fetcher_delegate.h" #include "net/url_request/url_request_context_getter.h" #include "url/gurl.h" namespace chromeos { namespace printing { namespace { // Extract cupsFilter/cupsFilter2 filter names from the contents // of a ppd, pre-split into lines. // cupsFilter2 lines look like this: // // *cupsFilter2: "application/vnd.cups-raster application/vnd.foo 100 // rastertofoo" // // cupsFilter lines look like this: // // *cupsFilter: "application/vnd.cups-raster 100 rastertofoo" // // |field_name| is the starting token we look for (*cupsFilter: or // *cupsFilter2:). // // |num_value_tokens| is the number of tokens we expect to find in the // value string. The filter is always the last of these. // // This function looks at each line in ppd_lines for lines of this format, and, // for each one found, adds the name of the filter (rastertofoo in the examples // above) to the returned set. // // This would be simpler with re2, but re2 is not an allowed dependency in // this part of the tree. std::set<std::string> ExtractCupsFilters( const std::vector<std::string>& ppd_lines, const std::string& field_name, int num_value_tokens) { std::set<std::string> ret; std::string delims(" \n\t\r\""); for (const std::string& line : ppd_lines) { base::StringTokenizer line_tok(line, delims); if (!line_tok.GetNext()) { continue; } if (line_tok.token_piece() != field_name) { continue; } // Skip to the last of the value tokens. for (int i = 0; i < num_value_tokens; ++i) { if (!line_tok.GetNext()) { // Continue the outer loop. goto next_line; } } if (line_tok.token_piece() != "") { ret.insert(line_tok.token_piece().as_string()); } next_line : {} // Lint requires {} instead of ; for an empty statement. } return ret; } // The ppd spec explicitly disallows quotes inside quoted strings, and provides // no way for including escaped quotes in a quoted string. It also requires // that the string be a single line, and that everything in these fields be // 7-bit ASCII. The CUPS spec on these particular fields is not particularly // rigorous, but specifies no way of including escaped spaces in the tokens // themselves, and the cups *code* just parses out these lines with a sscanf // call that uses spaces as delimiters. // // Furthermore, cups (post 1.5) discards all cupsFilter lines if *any* // cupsFilter2 lines exist. // // All of this is a long way of saying the regular-expression based parsing // done here is, to the best of my knowledge, actually conformant to the specs // that exist, and not just a hack. std::vector<std::string> ExtractFiltersFromPpd( const std::string& ppd_contents) { std::vector<std::string> lines = base::SplitString( ppd_contents, "\n\r", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); std::set<std::string> filters = ExtractCupsFilters(lines, "*cupsFilter2:", 4); if (filters.empty()) { // No cupsFilter2 lines found, fall back to looking for cupsFilter lines. filters = ExtractCupsFilters(lines, "*cupsFilter:", 3); } return std::vector<std::string>(filters.begin(), filters.end()); } // Returns false if there are obvious errors in the reference that will prevent // resolution. bool PpdReferenceIsWellFormed(const Printer::PpdReference& reference) { int filled_fields = 0; if (!reference.user_supplied_ppd_url.empty()) { ++filled_fields; GURL tmp_url(reference.user_supplied_ppd_url); if (!tmp_url.is_valid() || !tmp_url.SchemeIs("file")) { LOG(ERROR) << "Invalid url for a user-supplied ppd: " << reference.user_supplied_ppd_url << " (must be a file:// URL)"; return false; } } if (!reference.effective_make_and_model.empty()) { ++filled_fields; } // Should have exactly one non-empty field. return filled_fields == 1; } std::string PpdReferenceToCacheKey(const Printer::PpdReference& reference) { DCHECK(PpdReferenceIsWellFormed(reference)); // The key prefixes here are arbitrary, but ensure we can't have an (unhashed) // collision between keys generated from different PpdReference fields. if (!reference.effective_make_and_model.empty()) { return std::string("em:") + reference.effective_make_and_model; } else { return std::string("up:") + reference.user_supplied_ppd_url; } } struct ManufacturerMetadata { // Key used to look up the printer list on the server. This is initially // populated. std::string reference; // Map from localized printer name to canonical-make-and-model string for // the given printer. Populated on demand. std::unique_ptr<std::unordered_map<std::string, std::string>> printers; }; // Data for an inflight USB metadata resolution. struct UsbDeviceId { int vendor_id; int device_id; }; // A queued request to download printer information for a manufacturer. struct PrinterResolutionQueueEntry { // Localized manufacturer name std::string manufacturer; // URL we are going to pull from. GURL url; // User callback on completion. PpdProvider::ResolvePrintersCallback cb; }; class PpdProviderImpl : public PpdProvider, public net::URLFetcherDelegate { public: // What kind of thing is the fetcher currently fetching? We use this to // determine what to do when the fetcher returns a result. enum FetcherTarget { FT_LOCALES, // Locales metadata. FT_MANUFACTURERS, // List of manufacturers metadata. FT_PRINTERS, // List of printers from a manufacturer. FT_PPD_INDEX, // Master ppd index. FT_PPD, // A Ppd file. FT_USB_DEVICES // USB device id to canonical name map. }; PpdProviderImpl( const std::string& browser_locale, scoped_refptr<net::URLRequestContextGetter> url_context_getter, scoped_refptr<PpdCache> ppd_cache, scoped_refptr<base::SequencedTaskRunner> disk_task_runner, const PpdProvider::Options& options) : browser_locale_(browser_locale), url_context_getter_(url_context_getter), ppd_cache_(ppd_cache), disk_task_runner_(disk_task_runner), options_(options), weak_factory_(this) {} // Resolving manufacturers requires a couple of steps, because of // localization. First we have to figure out what locale to use, which // involves grabbing a list of available locales from the server. Once we // have decided on a locale, we go out and fetch the manufacturers map in that // localization. // // This means when a request comes in, we either queue it and start background // fetches if necessary, or we satisfy it immediately from memory. void ResolveManufacturers(const ResolveManufacturersCallback& cb) override { CHECK(base::SequencedTaskRunnerHandle::IsSet()) << "ResolveManufacturers must be called from a SequencedTaskRunner" "context"; if (cached_metadata_.get() != nullptr) { // We already have this in memory. base::SequencedTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(cb, PpdProvider::SUCCESS, GetManufacturerList())); return; } manufacturers_resolution_queue_.push_back(cb); MaybeStartFetch(); } // If there is work outstanding that requires a URL fetch to complete, start // going on it. void MaybeStartFetch() { if (fetch_inflight_) { // We'll call this again when the outstanding fetch completes. return; } if (!usb_resolution_queue_.empty()) { StartFetch(GetUsbURL(usb_resolution_queue_.front().first.vendor_id), FT_USB_DEVICES); return; } if (!manufacturers_resolution_queue_.empty()) { if (locale_.empty()) { // Don't have a locale yet, figure that out first. StartFetch(GetLocalesURL(), FT_LOCALES); } else { // Get manufacturers based on the locale we have. StartFetch(GetManufacturersURL(locale_), FT_MANUFACTURERS); } return; } if (!printers_resolution_queue_.empty()) { StartFetch(printers_resolution_queue_.front().url, FT_PRINTERS); return; } while (!ppd_resolution_queue_.empty()) { const auto& next = ppd_resolution_queue_.front(); if (!next.first.user_supplied_ppd_url.empty()) { DCHECK(next.first.effective_make_and_model.empty()); GURL url(next.first.user_supplied_ppd_url); DCHECK(url.is_valid()); StartFetch(url, FT_PPD); return; } DCHECK(!next.first.effective_make_and_model.empty()); if (cached_ppd_index_.get() == nullptr) { // Have to have the ppd index before we can resolve by ppd server // key. StartFetch(GetPpdIndexURL(), FT_PPD_INDEX); return; } // Get the URL from the ppd index and start the fetch. auto it = cached_ppd_index_->find(next.first.effective_make_and_model); if (it != cached_ppd_index_->end()) { StartFetch(GetPpdURL(it->second), FT_PPD); return; } // This ppd reference isn't in the index. That's not good. Fail // out the current resolution and go try to start the next // thing if there is one. LOG(ERROR) << "PPD " << next.first.effective_make_and_model << " not found in server index"; FinishPpdResolution(next.second, PpdProvider::INTERNAL_ERROR, std::string()); ppd_resolution_queue_.pop_front(); } } void ResolvePrinters(const std::string& manufacturer, const ResolvePrintersCallback& cb) override { std::unordered_map<std::string, ManufacturerMetadata>::iterator it; if (cached_metadata_.get() == nullptr || (it = cached_metadata_->find(manufacturer)) == cached_metadata_->end()) { // User error. LOG(ERROR) << "Can't resolve printers for unknown manufacturer " << manufacturer; base::SequencedTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(cb, PpdProvider::INTERNAL_ERROR, std::vector<std::string>())); return; } if (it->second.printers.get() != nullptr) { // Satisfy from the cache. base::SequencedTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(cb, PpdProvider::SUCCESS, GetManufacturerPrinterList(it->second))); } else { // We haven't resolved this manufacturer yet. PrinterResolutionQueueEntry entry; entry.manufacturer = manufacturer; entry.url = GetPrintersURL(it->second.reference); entry.cb = cb; printers_resolution_queue_.push_back(entry); MaybeStartFetch(); } } void ResolveUsbIds(int vendor_id, int device_id, const ResolveUsbIdsCallback& cb) override { usb_resolution_queue_.push_back({{vendor_id, device_id}, cb}); MaybeStartFetch(); } bool GetPpdReference(const std::string& manufacturer, const std::string& printer, Printer::PpdReference* reference) const override { std::unordered_map<std::string, ManufacturerMetadata>::iterator top_it; if (cached_metadata_.get() == nullptr) { return false; } auto it = cached_metadata_->find(manufacturer); if (it == cached_metadata_->end() || it->second.printers.get() == nullptr) { return false; } const auto& printers_map = *it->second.printers; auto it2 = printers_map.find(printer); if (it2 == printers_map.end()) { return false; } *reference = Printer::PpdReference(); reference->effective_make_and_model = it2->second; return true; } void ResolvePpd(const Printer::PpdReference& reference, const ResolvePpdCallback& cb) override { // Do a sanity check here, so we can assumed |reference| is well-formed in // the rest of this class. if (!PpdReferenceIsWellFormed(reference)) { FinishPpdResolution(cb, PpdProvider::INTERNAL_ERROR, std::string()); return; } // First step, check the cache. If the cache lookup fails, we'll (try to) // consult the server. ppd_cache_->Find(PpdReferenceToCacheKey(reference), base::Bind(&PpdProviderImpl::ResolvePpdCacheLookupDone, weak_factory_.GetWeakPtr(), reference, cb)); } // Our only sources of long running ops are cache fetches and network fetches. bool Idle() const override { return ppd_cache_->Idle() && !fetch_inflight_; } // Common handler that gets called whenever a fetch completes. Note this // is used both for |fetcher_| fetches (i.e. http[s]) and file-based fetches; // |source| may be null in the latter case. void OnURLFetchComplete(const net::URLFetcher* source) override { switch (fetcher_target_) { case FT_LOCALES: OnLocalesFetchComplete(); break; case FT_MANUFACTURERS: OnManufacturersFetchComplete(); break; case FT_PRINTERS: OnPrintersFetchComplete(); break; case FT_PPD_INDEX: OnPpdIndexFetchComplete(); break; case FT_PPD: OnPpdFetchComplete(); break; case FT_USB_DEVICES: OnUsbFetchComplete(); break; default: LOG(DFATAL) << "Unknown fetch source"; } fetch_inflight_ = false; MaybeStartFetch(); } private: // Return the URL used to look up the supported locales list. GURL GetLocalesURL() { return GURL(options_.ppd_server_root + "/metadata/locales.json"); } GURL GetUsbURL(int vendor_id) { DCHECK_GT(vendor_id, 0); DCHECK_LE(vendor_id, 0xffff); return GURL(base::StringPrintf("%s/metadata/usb-%04x.json", options_.ppd_server_root.c_str(), vendor_id)); } // Return the URL used to get the index of ppd server key -> ppd. GURL GetPpdIndexURL() { return GURL(options_.ppd_server_root + "/metadata/index.json"); } // Return the URL to get a localized manufacturers map. GURL GetManufacturersURL(const std::string& locale) { return GURL(base::StringPrintf("%s/metadata/manufacturers-%s.json", options_.ppd_server_root.c_str(), locale.c_str())); } // Return the URL used to get a list of printers from the manufacturer |ref|. GURL GetPrintersURL(const std::string& ref) { return GURL(base::StringPrintf( "%s/metadata/%s", options_.ppd_server_root.c_str(), ref.c_str())); } // Return the URL used to get a ppd with the given filename. GURL GetPpdURL(const std::string& filename) { return GURL(base::StringPrintf( "%s/ppds/%s", options_.ppd_server_root.c_str(), filename.c_str())); } // Create and return a fetcher that has the usual (for this class) flags set // and calls back to OnURLFetchComplete in this class when it finishes. void StartFetch(const GURL& url, FetcherTarget target) { DCHECK(!fetch_inflight_); DCHECK_EQ(fetcher_.get(), nullptr); fetcher_target_ = target; fetch_inflight_ = true; if (url.SchemeIs("http") || url.SchemeIs("https")) { fetcher_ = net::URLFetcher::Create(url, net::URLFetcher::GET, this); fetcher_->SetRequestContext(url_context_getter_.get()); fetcher_->SetLoadFlags(net::LOAD_BYPASS_CACHE | net::LOAD_DISABLE_CACHE | net::LOAD_DO_NOT_SAVE_COOKIES | net::LOAD_DO_NOT_SEND_COOKIES | net::LOAD_DO_NOT_SEND_AUTH_DATA); fetcher_->Start(); } else if (url.SchemeIs("file")) { disk_task_runner_->PostTaskAndReply( FROM_HERE, base::Bind(&PpdProviderImpl::FetchFile, this, url), base::Bind(&PpdProviderImpl::OnURLFetchComplete, this, nullptr)); } } // Fetch the file pointed at by url and store it in |file_fetch_contents_|. // Use |file_fetch_success_| to indicate success or failure. void FetchFile(const GURL& url) { CHECK(url.is_valid()); CHECK(url.SchemeIs("file")); base::ThreadRestrictions::AssertIOAllowed(); file_fetch_success_ = base::ReadFileToString(base::FilePath(url.path()), &file_fetch_contents_); } void FinishPpdResolution(const ResolvePpdCallback& cb, PpdProvider::CallbackResultCode result_code, const std::string& ppd_contents) { if (result_code == PpdProvider::SUCCESS) { base::SequencedTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(cb, PpdProvider::SUCCESS, ppd_contents, ExtractFiltersFromPpd(ppd_contents))); } else { // Just post the failure. base::SequencedTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(cb, result_code, std::string(), std::vector<std::string>())); } } // Callback when the cache lookup for a ppd request finishes. If we hit in // the cache, satisfy the resolution, otherwise kick it over to the fetcher // queue to be grabbed from a server. void ResolvePpdCacheLookupDone(const Printer::PpdReference& reference, const ResolvePpdCallback& cb, const PpdCache::FindResult& result) { if (result.success) { // Cache hit. FinishPpdResolution(cb, PpdProvider::SUCCESS, result.contents); } else { // Cache miss. Queue it to be satisfied by the fetcher queue. ppd_resolution_queue_.push_back({reference, cb}); MaybeStartFetch(); } } // Handler for the completion of the locales fetch. This response should be a // list of strings, each of which is a locale in which we can answer queries // on the server. The server (should) guarantee that we get 'en' as an // absolute minimum. // // Combine this information with the browser locale to figure out the best // locale to use, and then start a fetch of the manufacturers map in that // locale. void OnLocalesFetchComplete() { std::string contents; if (ValidateAndGetResponseAsString(&contents) != PpdProvider::SUCCESS) { FailQueuedMetadataResolutions(PpdProvider::SERVER_ERROR); return; } auto top_list = base::ListValue::From(base::JSONReader::Read(contents)); if (top_list.get() == nullptr) { // We got something malformed back. FailQueuedMetadataResolutions(PpdProvider::INTERNAL_ERROR); return; } // This should just be a simple list of locale strings. std::vector<std::string> available_locales; bool found_en = false; for (const base::Value& entry : *top_list) { std::string tmp; // Locales should have at *least* a two-character country code. 100 is an // arbitrary upper bound for length to protect against extreme bogosity. if (!entry.GetAsString(&tmp) || tmp.size() < 2 || tmp.size() > 100) { FailQueuedMetadataResolutions(PpdProvider::INTERNAL_ERROR); return; } if (tmp == "en") { found_en = true; } available_locales.push_back(tmp); } if (available_locales.empty() || !found_en) { // We have no locales, or we didn't get an english locale (which is our // ultimate fallback) FailQueuedMetadataResolutions(PpdProvider::INTERNAL_ERROR); return; } // Everything checks out, set the locale, head back to fetch dispatch // to start the manufacturer fetch. locale_ = GetBestLocale(available_locales); } // Called when the |fetcher_| is expected have the results of a // manufacturer map (which maps localized manufacturer names to keys for // looking up printers from that manufacturer). Use this information to // populate manufacturer_map_, and resolve all queued ResolveManufacturers() // calls. void OnManufacturersFetchComplete() { DCHECK_EQ(nullptr, cached_metadata_.get()); std::vector<std::pair<std::string, std::string>> contents; PpdProvider::CallbackResultCode code = ValidateAndParseJSONResponse(&contents); if (code != PpdProvider::SUCCESS) { LOG(ERROR) << "Failed manufacturer parsing"; FailQueuedMetadataResolutions(code); return; } cached_metadata_ = base::MakeUnique< std::unordered_map<std::string, ManufacturerMetadata>>(); for (const auto& entry : contents) { ManufacturerMetadata value; value.reference = entry.second; (*cached_metadata_)[entry.first].reference = entry.second; } std::vector<std::string> manufacturer_list = GetManufacturerList(); // Complete any queued manufacturer resolutions. for (const auto& cb : manufacturers_resolution_queue_) { base::SequencedTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(cb, PpdProvider::SUCCESS, manufacturer_list)); } manufacturers_resolution_queue_.clear(); } // The outstanding fetch associated with the front of // |printers_resolution_queue_| finished, use the response to satisfy that // ResolvePrinters() call. void OnPrintersFetchComplete() { CHECK(cached_metadata_.get() != nullptr); DCHECK(!printers_resolution_queue_.empty()); std::vector<std::pair<std::string, std::string>> contents; PpdProvider::CallbackResultCode code = ValidateAndParseJSONResponse(&contents); if (code != PpdProvider::SUCCESS) { base::SequencedTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(printers_resolution_queue_.front().cb, code, std::vector<std::string>())); } else { // This should be a list of lists of 2-element strings, where the first // element is the localized name of the printer and the second element // is the canonical name of the printer. const std::string& manufacturer = printers_resolution_queue_.front().manufacturer; auto it = cached_metadata_->find(manufacturer); // If we kicked off a resolution, the entry better have already been // in the map. CHECK(it != cached_metadata_->end()); // Create the printer map in the cache, and populate it. auto& manufacturer_metadata = it->second; CHECK(manufacturer_metadata.printers.get() == nullptr); manufacturer_metadata.printers = base::MakeUnique<std::unordered_map<std::string, std::string>>(); for (const auto& entry : contents) { manufacturer_metadata.printers->insert({entry.first, entry.second}); } base::SequencedTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(printers_resolution_queue_.front().cb, PpdProvider::SUCCESS, GetManufacturerPrinterList(manufacturer_metadata))); } printers_resolution_queue_.pop_front(); } // Called when |fetcher_| should have just received the index mapping // ppd server keys to ppd filenames. Use this to populate // |cached_ppd_index_|. void OnPpdIndexFetchComplete() { std::vector<std::pair<std::string, std::string>> contents; PpdProvider::CallbackResultCode code = ValidateAndParseJSONResponse(&contents); if (code != PpdProvider::SUCCESS) { FailQueuedServerPpdResolutions(code); } else { cached_ppd_index_ = base::MakeUnique<std::unordered_map<std::string, std::string>>(); // This should be a list of lists of 2-element strings, where the first // element is the |effective_make_and_model| of the printer and the second // element is the filename of the ppd in the ppds/ directory on the // server. for (const auto& entry : contents) { cached_ppd_index_->insert(entry); } } } // This is called when |fetcher_| should have just downloaded a ppd. If we // downloaded something successfully, use it to satisfy the front of the ppd // resolution queue, otherwise fail out that resolution. void OnPpdFetchComplete() { DCHECK(!ppd_resolution_queue_.empty()); std::string contents; if ((ValidateAndGetResponseAsString(&contents) != PpdProvider::SUCCESS) || contents.size() > kMaxPpdSizeBytes) { FinishPpdResolution(ppd_resolution_queue_.front().second, PpdProvider::SERVER_ERROR, std::string()); } else { ppd_cache_->Store( PpdReferenceToCacheKey(ppd_resolution_queue_.front().first), contents, base::Callback<void()>()); FinishPpdResolution(ppd_resolution_queue_.front().second, PpdProvider::SUCCESS, contents); } ppd_resolution_queue_.pop_front(); } // Called when |fetcher_| should have just downloaded a usb device map // for the vendor at the head of the |usb_resolution_queue_|. void OnUsbFetchComplete() { DCHECK(!usb_resolution_queue_.empty()); std::string contents; std::string buffer; PpdProvider::CallbackResultCode result = ValidateAndGetResponseAsString(&buffer); int desired_device_id = usb_resolution_queue_.front().first.device_id; if (result == PpdProvider::SUCCESS) { // Parse the JSON response. This should be a list of the form // [ // [0x3141, "some canonical name"], // [0x5926, "some othercanonical name"] // ] // So we scan through the response looking for our desired device id. auto top_list = base::ListValue::From(base::JSONReader::Read(buffer)); if (top_list.get() == nullptr) { // We got something malformed back. LOG(ERROR) << "Malformed top list"; result = PpdProvider::INTERNAL_ERROR; } else { // We'll set result to SUCCESS if we do find the device. result = PpdProvider::NOT_FOUND; for (const auto& entry : *top_list) { int device_id; const base::ListValue* sub_list; // Each entry should be a size-2 list with an integer and a string. if (!entry.GetAsList(&sub_list) || sub_list->GetSize() != 2 || !sub_list->GetInteger(0, &device_id) || !sub_list->GetString(1, &contents) || device_id < 0 || device_id > 0xffff) { // Malformed data. LOG(ERROR) << "Malformed line in usb device list"; result = PpdProvider::INTERNAL_ERROR; break; } if (device_id == desired_device_id) { // Found it. result = PpdProvider::SUCCESS; break; } } } } if (result != PpdProvider::SUCCESS) { contents.clear(); } base::SequencedTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(usb_resolution_queue_.front().second, result, contents)); usb_resolution_queue_.pop_front(); } // Something went wrong during metadata fetches. Fail all queued metadata // resolutions with the given error code. void FailQueuedMetadataResolutions(PpdProvider::CallbackResultCode code) { for (const auto& cb : manufacturers_resolution_queue_) { base::SequencedTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(cb, code, std::vector<std::string>())); } manufacturers_resolution_queue_.clear(); } // Fail all server-based ppd resolutions inflight, because we failed to grab // the necessary index data from the server. Note we leave any user-based ppd // resolutions intact, as they don't depend on the data we're missing. void FailQueuedServerPpdResolutions(PpdProvider::CallbackResultCode code) { std::deque<std::pair<Printer::PpdReference, ResolvePpdCallback>> filtered_queue; for (const auto& entry : ppd_resolution_queue_) { if (!entry.first.user_supplied_ppd_url.empty()) { filtered_queue.push_back(entry); } else { FinishPpdResolution(entry.second, code, std::string()); } } ppd_resolution_queue_ = std::move(filtered_queue); } // Given a list of possible locale strings (e.g. 'en-GB'), determine which of // them we should use to best serve results for the browser locale (which was // given to us at construction time). std::string GetBestLocale(const std::vector<std::string>& available_locales) { // First look for an exact match. If we find one, just use that. for (const std::string& available : available_locales) { if (available == browser_locale_) { return available; } } // Next, look for an available locale that is a parent of browser_locale_. // Return the most specific one. For example, if we want 'en-GB-foo' and we // don't have an exact match, but we do have 'en-GB' and 'en', we will // return 'en-GB' -- the most specific match which is a parent of the // requested locale. size_t best_len = 0; size_t best_idx = -1; for (size_t i = 0; i < available_locales.size(); ++i) { const std::string& available = available_locales[i]; if (base::StringPiece(browser_locale_).starts_with(available + "-") && available.size() > best_len) { best_len = available.size(); best_idx = i; } } if (best_idx != static_cast<size_t>(-1)) { return available_locales[best_idx]; } // Last chance for a match, look for the locale that matches the *most* // pieces of locale_, with ties broken by being least specific. So for // example, if we have 'es-GB', 'es-GB-foo' but no 'es' available, and we're // requesting something for 'es', we'll get back 'es-GB' -- the least // specific thing that matches some of the locale. std::vector<base::StringPiece> browser_locale_pieces = base::SplitStringPiece(browser_locale_, "-", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL); size_t best_match_size = 0; size_t best_match_specificity; best_idx = -1; for (size_t i = 0; i < available_locales.size(); ++i) { const std::string& available = available_locales[i]; std::vector<base::StringPiece> available_pieces = base::SplitStringPiece( available, "-", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL); size_t match_size = 0; for (; match_size < available_pieces.size() && match_size < browser_locale_pieces.size(); ++match_size) { if (available_pieces[match_size] != browser_locale_pieces[match_size]) { break; } } if (match_size > 0 && (best_idx == static_cast<size_t>(-1) || match_size > best_match_size || (match_size == best_match_size && available_pieces.size() < best_match_specificity))) { best_idx = i; best_match_size = match_size; best_match_specificity = available_pieces.size(); } } if (best_idx != static_cast<size_t>(-1)) { return available_locales[best_idx]; } // Everything else failed. Throw up our hands and default to english. return "en"; } // Get the results of a fetch. This is a little tricky, because a fetch // may have been done by |fetcher_|, or it may have been a file access, in // which case we want to look at |file_fetch_contents_|. We distinguish // between the cases based on whether or not |fetcher_| is null. // // We return NOT_FOUND for 404 or file not found, SERVER_ERROR for other // errors, SUCCESS if everything was good. CallbackResultCode ValidateAndGetResponseAsString(std::string* contents) { CallbackResultCode ret; if (fetcher_.get() != nullptr) { if (fetcher_->GetStatus().status() != net::URLRequestStatus::SUCCESS) { ret = PpdProvider::SERVER_ERROR; } else if (fetcher_->GetResponseCode() != net::HTTP_OK) { if (fetcher_->GetResponseCode() == net::HTTP_NOT_FOUND) { // A 404 means not found, everything else is a server error. ret = PpdProvider::NOT_FOUND; } else { ret = PpdProvider::SERVER_ERROR; } } else { fetcher_->GetResponseAsString(contents); ret = PpdProvider::SUCCESS; } fetcher_.reset(); } else { // It's a file load. if (file_fetch_success_) { *contents = file_fetch_contents_; } else { contents->clear(); } // A failure to load a file is always considered a NOT FOUND error (even // if the underlying causes is lack of access or similar, this seems to be // the best match for intent. ret = file_fetch_success_ ? PpdProvider::SUCCESS : PpdProvider::NOT_FOUND; file_fetch_contents_.clear(); } return ret; } // Many of our metadata fetches happens to be in the form of a JSON // list-of-lists-of-2-strings. So this just attempts to parse a JSON reply to // |fetcher| into the passed contents vector. A return code of SUCCESS means // the JSON was formatted as expected and we've parsed it into |contents|. On // error the contents of |contents| cleared. PpdProvider::CallbackResultCode ValidateAndParseJSONResponse( std::vector<std::pair<std::string, std::string>>* contents) { contents->clear(); std::string buffer; auto tmp = ValidateAndGetResponseAsString(&buffer); if (tmp != PpdProvider::SUCCESS) { return tmp; } auto top_list = base::ListValue::From(base::JSONReader::Read(buffer)); if (top_list.get() == nullptr) { // We got something malformed back. return PpdProvider::INTERNAL_ERROR; } for (const auto& entry : *top_list) { const base::ListValue* sub_list; contents->push_back({}); if (!entry.GetAsList(&sub_list) || sub_list->GetSize() != 2 || !sub_list->GetString(0, &contents->back().first) || !sub_list->GetString(1, &contents->back().second)) { contents->clear(); return PpdProvider::INTERNAL_ERROR; } } return PpdProvider::SUCCESS; } // Create the list of manufacturers from |cached_metadata_|. Requires that // the manufacturer list has already been resolved. std::vector<std::string> GetManufacturerList() const { CHECK(cached_metadata_.get() != nullptr); std::vector<std::string> ret; ret.reserve(cached_metadata_->size()); for (const auto& entry : *cached_metadata_) { ret.push_back(entry.first); } // TODO(justincarlson) -- this should be a localization-aware sort. sort(ret.begin(), ret.end()); return ret; } // Get the list of printers from a given manufacturer from |cached_metadata_|. // Requires that we have already resolved this from the server. std::vector<std::string> GetManufacturerPrinterList( const ManufacturerMetadata& meta) const { CHECK(meta.printers.get() != nullptr); std::vector<std::string> ret; ret.reserve(meta.printers->size()); for (const auto& entry : *meta.printers) { ret.push_back(entry.first); } // TODO(justincarlson) -- this should be a localization-aware sort. sort(ret.begin(), ret.end()); return ret; } // Map from (localized) manufacturer name to metadata for that manufacturer. // This is populated lazily. If we don't yet have a manufacturer list, the // top pointer will be null. When we create the top level map, then each // value will only contain a reference which can be used to resolve the // printer list from that manufacturer. On demand, we use these references to // resolve the actual printer lists. std::unique_ptr<std::unordered_map<std::string, ManufacturerMetadata>> cached_metadata_; // Cached contents of the server index, which maps a // PpdReference::effective_make_and_model to a url for the corresponding // ppd. // Null until we have fetched the index. std::unique_ptr<std::unordered_map<std::string, std::string>> cached_ppd_index_; // Queued ResolveManufacturers() calls. We will simultaneously resolve // all queued requests, so no need for a deque here. std::vector<ResolveManufacturersCallback> manufacturers_resolution_queue_; // Queued ResolvePrinters() calls. std::deque<PrinterResolutionQueueEntry> printers_resolution_queue_; // Queued ResolvePpd() requests. std::deque<std::pair<Printer::PpdReference, ResolvePpdCallback>> ppd_resolution_queue_; // Queued ResolveUsbIds() requests. std::deque<std::pair<UsbDeviceId, ResolveUsbIdsCallback>> usb_resolution_queue_; // Locale we're using for grabbing stuff from the server. Empty if we haven't // determined it yet. std::string locale_; // If the fetcher is active, what's it fetching? FetcherTarget fetcher_target_; // Fetcher used for all network fetches. This is explicitly reset() when // a fetch has been processed. std::unique_ptr<net::URLFetcher> fetcher_; bool fetch_inflight_ = false; // Locale of the browser, as returned by // BrowserContext::GetApplicationLocale(); const std::string browser_locale_; scoped_refptr<net::URLRequestContextGetter> url_context_getter_; // For file:// fetches, a staging buffer and result flag for loading the file. std::string file_fetch_contents_; bool file_fetch_success_; // Cache of ppd files. scoped_refptr<PpdCache> ppd_cache_; // Where to run disk operations. scoped_refptr<base::SequencedTaskRunner> disk_task_runner_; // Construction-time options, immutable. const PpdProvider::Options options_; base::WeakPtrFactory<PpdProviderImpl> weak_factory_; protected: ~PpdProviderImpl() override {} }; } // namespace // static scoped_refptr<PpdProvider> PpdProvider::Create( const std::string& browser_locale, scoped_refptr<net::URLRequestContextGetter> url_context_getter, scoped_refptr<PpdCache> ppd_cache, scoped_refptr<base::SequencedTaskRunner> disk_task_runner, const PpdProvider::Options& options) { return scoped_refptr<PpdProvider>( new PpdProviderImpl(browser_locale, url_context_getter, ppd_cache, disk_task_runner, options)); } } // namespace printing } // namespace chromeos
[ "xElvis89x@gmail.com" ]
xElvis89x@gmail.com
21bc86e731c4fd214730de842586689cbb419144
4e8fb3672f0c561bf85bd8230c5492e4457f33d1
/dev/include/core/PostEffect_GaussianBlur.h
a5769a04b678da8956ee6d478ebfc6ce5676d0c1
[]
no_license
lythm/ld3d
877abefefcea9b39734857714fe1974a8320fe6c
91de1cca7cca77c1f8eae8e8a9423abc34f9b38f
refs/heads/master
2020-12-24T15:23:29.766231
2014-07-11T04:42:49
2014-07-11T04:42:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
591
h
#pragma once #include "core/PostEffect.h" namespace ld3d { class _DLL_CLASS PostEffect_GaussianBlur : public PostEffect { public: PostEffect_GaussianBlur(void); virtual ~PostEffect_GaussianBlur(void); bool Initialize(RenderManagerPtr pRenderManager); void Render(RenderManagerPtr pRenderer, RenderTexturePtr pInput, RenderTexturePtr pOutput); void Release(); private: MaterialPtr m_pMaterial; RenderManagerPtr m_pRenderManager; MaterialParameterPtr m_pParamInputTex; MaterialParameterPtr m_pParamInputSize; }; }
[ "lythm780522@gmail.com" ]
lythm780522@gmail.com
dfc2457ca777ca78eca77efe41d509e79378cb51
a904c42a45b99c6de6c95cf52ba88001740765e4
/Sources/Maths/Visual/DriverSinwave.cpp
22bd4315cb8b37cbd430c5a84d3bad3b2b2f4ce3
[ "MIT" ]
permissive
lineCode/Acid
0cc31acf1060f0d55631b3cbe31e540e89a44a31
573ca8ea9191f62eaab8ef89c34bf15e70e0c1e4
refs/heads/master
2020-03-28T14:29:58.922933
2018-09-12T06:35:25
2018-09-12T06:35:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
356
cpp
#include "DriverSinwave.hpp" namespace acid { DriverSinwave::DriverSinwave(const float &min, const float &max, const float &length) : IDriver(length), m_min(min), m_amplitude(max - min) { } float DriverSinwave::Calculate(const float &time) { float value = 0.5f + std::sin(2.0f * PI * time) * 0.5f; return m_min + value * m_amplitude; } }
[ "mattparks5855@gmail.com" ]
mattparks5855@gmail.com
f0ec0194df9b99c11bbc6fdc134d75f78aec32d9
51e993226766d8a38a8cbdcb16ef2eb34695349c
/sim/rcp.h
d2c71a6ff2ee5078d83b09b55c33e768531d98fe
[]
no_license
sandyhouse/htsimMPTCP
927d0ef54bf95af3567d103816c78a4cb5d875bf
3f89d904530d28d40891edb172fb972ea7926973
refs/heads/master
2020-03-09T22:25:27.753968
2014-01-30T19:54:45
2014-01-30T19:54:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,279
h
#ifndef RCP_H #define RCP_H /* * An RCP source and sink */ #include <list> #include "config.h" #include "network.h" #include "rcppacket.h" #include "eventlist.h" class RcpSink; class RcpSrc : public PacketSink, public EventSource { friend class RcpSink; public: RcpSrc(RcpLogger* logger, TrafficLogger* pktlogger, EventList &eventlist); void connect(route_t& routeout, route_t& routeback, RcpSink& sink, simtime_picosec startTime); void startflow(); void doNextEvent() { startflow(); } void receivePacket(Packet& pkt); void rtx_timer_hook(simtime_picosec now); // should really be private, but loggers want to see: uint32_t _highest_sent; //seqno is in bytes uint32_t _cwnd; uint32_t _maxcwnd; uint32_t _last_acked; uint32_t _ssthresh; uint16_t _dupacks; uint16_t _mss; uint32_t _unacked; // an estimate of the amount of unacked data WE WANT TO HAVE in the network uint32_t _effcwnd; // an estimate of our current transmission rate, expressed as a cwnd uint32_t _recoverq; bool _in_fast_recovery; private: // Housekeeping RcpLogger* _logger; TrafficLogger* _pktlogger; // Connectivity PacketFlow _flow; RcpSink* _sink; route_t* _route; // Mechanism void inflate_window(); void send_packets(); void retransmit_packet(); simtime_picosec _rtt; simtime_picosec _last_sent_time; }; class RcpSink : public PacketSink, public Logged { friend class RcpSrc; public: RcpSink(); void receivePacket(Packet& pkt); private: // Connectivity void connect(RcpSrc& src, route_t& route); route_t* _route; RcpSrc* _src; // Mechanism void send_ack(); RcpAck::seq_t _cumulative_ack; // the packet we have cumulatively acked list<RcpAck::seq_t> _received; // list of packets above a hole, that we've received }; class RcpRtxTimerScanner : public EventSource { public: RcpRtxTimerScanner::RcpRtxTimerScanner(simtime_picosec scanPeriod, EventList& eventlist); void doNextEvent(); void registerRcp(RcpSrc &rcpsrc); private: simtime_picosec _scanPeriod; typedef list<RcpSrc*> rcps_t; rcps_t _rcps; }; #endif
[ "sdyy1990@gmail.com" ]
sdyy1990@gmail.com
02a951e53ee244aff6ebf0b4797f409435be68c6
6375d90b2a0211053b93e7c65b3b4e67037e74c5
/bookmanager/bookmanager-tests/01_dbConnectTest.cpp
b3dbcb60c69c82068efad9c248dc322d5c215e90
[]
no_license
df-wilson/book-manager-cpp
86fc0c1d45ccf01ae6bd768828da3e58cff80d42
f255b56bdd6cdec7caee7c02d3f8ce1933362a2e
refs/heads/master
2021-01-19T10:36:45.023083
2020-02-08T20:38:35
2020-02-08T20:38:35
87,882,611
0
0
null
null
null
null
UTF-8
C++
false
false
2,260
cpp
#include "catch.hpp" #include "dbConnect.h" #include <SQLiteCpp/SQLiteCpp.h> #include <iostream> #include <string> using namespace dw; using namespace std; TEST_CASE("dbConnect - Test getting initial connection.") { SQLite::Database* connection = db_getConnection(); REQUIRE(connection->getFilename() == "/home/dean/Programming/Cpp/web/Projects/build/bookmanager/bookmanager-tests/db.sqlite"); REQUIRE(db_numAvailableConnections() == 0); REQUIRE(connection->tableExists("books")); SQLite::Statement* query = new SQLite::Statement(*connection, "SELECT * FROM books WHERE user_id = :userId"); query->bind(":userId", 1); //while (query->executeStep()) //{ // std::cout << query->getColumn(1) << std::endl; // std::cout << query->getColumn(2) << std::endl; // std::cout << query->getColumn(3) << std::endl; //} query->executeStep(); REQUIRE(query->getColumn(0).getInt() == 1); REQUIRE(query->getColumn(1).getInt() == 1); REQUIRE(query->getColumn(2).getString() == "Sorcerer's Daughter"); REQUIRE(query->getColumn(3).getString() == "Terry Brooks"); delete query; REQUIRE(db_numAvailableConnections() == 0); db_returnConnection(connection); REQUIRE(db_numAvailableConnections() == 1); db_shutdown(); REQUIRE(db_numAvailableConnections() == 0); } TEST_CASE("dbConnect - Test reusing connection") { SQLite::Database* connection = db_getConnection(); REQUIRE(connection != nullptr); REQUIRE(connection->getFilename() == "/home/dean/Programming/Cpp/web/Projects/build/bookmanager/bookmanager-tests/db.sqlite"); REQUIRE(connection->tableExists("books")); REQUIRE(db_numAvailableConnections() == 0); db_returnConnection(connection); REQUIRE(db_numAvailableConnections() == 1); SQLite::Database* connection2 = db_getConnection(); REQUIRE(db_numAvailableConnections() == 0); REQUIRE(connection != nullptr); REQUIRE(connection->getFilename() == "/home/dean/Programming/Cpp/web/Projects/build/bookmanager/bookmanager-tests/db.sqlite"); REQUIRE(connection->tableExists("books")); db_returnConnection(connection2); REQUIRE(db_numAvailableConnections() == 1); db_shutdown(); REQUIRE(db_numAvailableConnections() == 0); }
[ "deanwilsonbc@gmail.com" ]
deanwilsonbc@gmail.com
fdee6265ba93e9aec0bb2a1e5dec08f513608f2e
69304e6e01ae66df5cec81ece86c44a9c7c53aba
/widget.h
16f294a799dc6a9f924e068236232a4e958070ae
[]
no_license
Lwxiang/MyTrip
55acd5cda63c4b61b3ecab2eaabbe68f7a4109fa
a11dcfa1f020ed9889258234f050c01f53569923
refs/heads/master
2021-01-10T16:58:10.671888
2016-02-29T05:50:35
2016-02-29T05:50:35
52,767,269
0
0
null
null
null
null
UTF-8
C++
false
false
846
h
#ifndef WIDGET_H #define WIDGET_H #include "titlebar.h" #include "toolbar.h" #include "statubar.h" #include "contentwidget.h" #include <QWidget> #include <QRect> #include <QBitmap> #include <QPainter> #include <QFrame> #include <QLabel> #include <QPoint> #include <QMouseEvent> #include <QPushButton> #include <QToolButton> #include <QVBoxLayout> #include <QHBoxLayout> namespace Ui { class Widget; } class Widget : public QFrame { Q_OBJECT public: explicit Widget(QFrame *parent = 0); TitleBar *titlebar; ToolBar *toolbar; ContentWidget *contentwidget; StatuBar *statubar; ~Widget(); protected: void mousePressEvent(QMouseEvent *); void mouseMoveEvent(QMouseEvent *); void mouseReleaseEvent(QMouseEvent *); private: QPoint oldPos; bool mouseDown; Ui::Widget *ui; }; #endif // WIDGET_H
[ "XUN Lwxiang" ]
XUN Lwxiang
dbb853a7b1d52cb9bc73dbffd74ec3a21b941d5a
3e4fd5153015d03f147e0f105db08e4cf6589d36
/Cpp/SDK/io_intro_wall_blacksmith_01_bp_classes.h
797e2a16a504acc64ba736001d5b36af0580526a
[]
no_license
zH4x-SDK/zTorchlight3-SDK
a96f50b84e6b59ccc351634c5cea48caa0d74075
24135ee60874de5fd3f412e60ddc9018de32a95c
refs/heads/main
2023-07-20T12:17:14.732705
2021-08-27T13:59:21
2021-08-27T13:59:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,613
h
#pragma once // Name: Torchlight3, Version: 1.0.0 /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass io_intro_wall_blacksmith_01_bp.io_intro_wall_blacksmith_01_bp_C // 0x0018 (FullSize[0x0280] - InheritedSize[0x0268]) class Aio_intro_wall_blacksmith_01_bp_C : public ABaseStaticObject_C { public: class UBoxComponent* Box2; // 0x0268(0x0008) (BlueprintVisible, ZeroConstructor, InstancedReference, IsPlainOldData, NonTransactional, NoDestructor, UObjectWrapper, HasGetValueTypeHash) class UBoxComponent* Box1; // 0x0270(0x0008) (BlueprintVisible, ZeroConstructor, InstancedReference, IsPlainOldData, NonTransactional, NoDestructor, UObjectWrapper, HasGetValueTypeHash) class UBoxComponent* Box; // 0x0278(0x0008) (BlueprintVisible, ZeroConstructor, InstancedReference, IsPlainOldData, NonTransactional, NoDestructor, UObjectWrapper, HasGetValueTypeHash) static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass io_intro_wall_blacksmith_01_bp.io_intro_wall_blacksmith_01_bp_C"); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "zp2kshield@gmail.com" ]
zp2kshield@gmail.com
a0e13fc1f3440a1af96eba344ae7d4744b1b5418
af009200519ba7d572acf07b9a4fc90e03aceb1f
/src/lassen/Input.hh
e18b0caeac758175723ea6c37a9f1970438aa8df
[ "LicenseRef-scancode-public-domain" ]
permissive
OpenSpeedShop/openspeedshop-test-suite
1d2c050c66f839d25e350a9edddeff4ada47d722
02df4abf2c164722170de9961b8764b8d2b2611f
refs/heads/master
2021-05-01T20:34:12.215991
2020-08-24T18:20:37
2020-08-24T18:20:37
57,010,138
1
0
null
null
null
null
UTF-8
C++
false
false
1,159
hh
#ifndef INPUT_H #define INPUT_H #include "Lassen.hh" namespace Lassen { class MeshConstructor { public: static void MakeRegularMesh( Mesh * mesh, int ndim, int *numGlobal, // total number of zones in each dimension int *globalStart, // global start index in each dimension int *numZones, // number of zone to create in each dimension Real *zoneSize); // size of each zone in each dimension // Create a single domain, which is part of a larger mesh static void MakeRegularDomain( Domain *domain, int ndim, int domainId, // domainID of the domain to create int *numDomain, // number of domains in each dimension int *numGlobalZones, // number of global zones in each dimension Real *zoneSize); // size of each zone in each dimension }; }; #endif
[ "jeg@krellinst.org" ]
jeg@krellinst.org
fdc5500c87d13f8d60be9b26ca89150695bd8845
fba0dfdd038e38d0539910ca869052b6559d2496
/DX11RenderApp/DX11RenderApp/Vertex.cpp
b432c5ee40c1bdee9f077259ed79f94818ec25d9
[]
no_license
shankkkyyy/GFXPROJECT
9c1d82702a9bc3a84a1efbf2e1b21054880696b8
4f537bb7c8d8bde99abcb6088e4a07ed5641b778
refs/heads/master
2021-07-01T16:30:10.020322
2017-09-22T02:01:44
2017-09-22T02:01:44
99,033,428
0
0
null
null
null
null
UTF-8
C++
false
false
2,415
cpp
#include "Vertex.h" const D3D11_INPUT_ELEMENT_DESC InputLayoutDesc::IDPosSize[2] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "SIZE", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 } }; const D3D11_INPUT_ELEMENT_DESC InputLayoutDesc::IDPos[1] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 } }; const D3D11_INPUT_ELEMENT_DESC InputLayoutDesc::IDPosNor[2] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT , 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 } }; const D3D11_INPUT_ELEMENT_DESC InputLayoutDesc::IDBasic32[3] = { {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT , 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0}, {"NORMAL" , 0, DXGI_FORMAT_R32G32B32_FLOAT , 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0}, {"UV" , 0, DXGI_FORMAT_R32G32_FLOAT , 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0} }; const D3D11_INPUT_ELEMENT_DESC InputLayoutDesc::IDBasic32Inst[7] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT , 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "NORMAL" , 0, DXGI_FORMAT_R32G32B32_FLOAT , 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "UV" , 0, DXGI_FORMAT_R32G32_FLOAT , 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "WORLD", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_INSTANCE_DATA, 1 }, { "WORLD", 1, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_INSTANCE_DATA, 1 }, { "WORLD", 2, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_INSTANCE_DATA, 1 }, { "WORLD", 3, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_INSTANCE_DATA, 1 } }; const D3D11_INPUT_ELEMENT_DESC InputLayoutDesc::IDTerrian[2] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT , 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "UV" , 0, DXGI_FORMAT_R32G32_FLOAT , 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 } }; Vertex & Vertex::operator=(const Vertex & _other) { // TODO: insert return statement here pos = _other.pos; nor = _other.nor; uv = _other.uv; return *this; }
[ "dushiweic2@hotmail.com" ]
dushiweic2@hotmail.com
ff7180be40da434378ae43575c243b24b9546ffc
03c42ab1f77bf7371869c7ee34d3551b6f13a0ef
/tlm_vppnoc_lib/vpp_noc_core_v1.0/protocol_data_unit/vppnoc_pdu.h
8e4ba26a5c528195ccc5da9517fc0b94787d5d24
[]
no_license
Hosseinabady/norc
4c654c40012a60d74777d349d20dfb79445e7fb3
c0aa6d77c60b1b88c4ba3526e3e4246c7da6fb00
refs/heads/master
2021-01-13T13:39:13.715637
2016-12-14T01:41:29
2016-12-14T01:41:29
76,404,087
0
0
null
null
null
null
UTF-8
C++
false
false
2,391
h
#ifndef NOC_GENERIC_PAYLOAD_ #define NOC_GENERIC_PAYLOAD_ #include <systemc> #include "protocol_data_unit/vppnoc_pdu_base.h" namespace vppnoc { template <typename HEADER, typename BODY = bool, int size = 10> class vppnoc_pdu : public vppnoc_pdu_base { public: vppnoc_pdu(): vppnoc_pdu_base(), stream_tail(0), stream_head(0) { } friend vppnoc_pdu<HEADER, BODY, size>& operator<< (vppnoc_pdu& left, const vppnoc_pdu& right); friend vppnoc_pdu<HEADER, BODY, size>& operator>> (vppnoc_pdu& left, const vppnoc_pdu& right); public: enum {pci_size = sizeof(HEADER)}; enum {sdu_size = size * sizeof(BODY)}; enum {pdu_size = sizeof(HEADER) + size * sizeof(BODY)}; void reset() { stream_tail = 0; stream_head = 0; } union { struct { HEADER hdr; BODY body[size]; } pdu; bool stream[pdu_size]; } view_as; unsigned int stream_tail; unsigned int stream_head; }; template <typename HEADER, typename BODY, int size, typename HEADER2, typename BODY2, int size2> vppnoc_pdu<HEADER, BODY, size>& operator<< (vppnoc_pdu<HEADER, BODY, size>& left,const vppnoc_pdu<HEADER2, BODY2, size2>& right) { unsigned int free_space = left.pdu_size - left.stream_head; unsigned int fill_capacity = right.sdu_size; unsigned int nbytes = free_space > fill_capacity ? fill_capacity : free_space; memcpy(&(left.view_as.stream[left.stream_head]), (char*)(right.view_as.pdu.body), nbytes); left.stream_head += nbytes; if (left.stream_head == left.pdu_size) { left.stream_head = 0; vppnoc_pdu<HEADER, BODY, size>* tmp = 0; return *tmp; } else { return left; } } template <typename HEADER, typename BODY, int size, typename HEADER2, typename BODY2, int size2> vppnoc_pdu<HEADER, BODY, size>& operator>> (vppnoc_pdu<HEADER, BODY, size>& left,const vppnoc_pdu<HEADER2, BODY2, size2>& right) { unsigned int free_space = right.sdu_size; unsigned int fill_capacity = left.pdu_size - left.stream_tail; unsigned int nbytes = ((free_space > fill_capacity) ? fill_capacity : free_space); memcpy((char*)(right.view_as.pdu.body),&(left.view_as.stream[left.stream_tail]),nbytes); left.stream_tail += nbytes; if (left.stream_tail == left.pdu_size) { left.stream_tail = -1; vppnoc_pdu<HEADER, BODY, size>* tmp = 0; return *tmp; } else { return left; } } } #endif /*NOC_GENERIC_PAYLOAD_*/
[ "mohamamd@hosseinabady.com" ]
mohamamd@hosseinabady.com
6d1ab11b46cc3924f1cba4403d729f1936a81d35
6b3e36e68ae34f85d5d27166687e3479e5333bb4
/Sources/Elastos/Packages/Apps/Dialer/inc/elastos/droid/incallui/CCallButtonFragment.h
4854b7999e46983e4921576b3b6493bf0cb23813
[ "Apache-2.0" ]
permissive
jiawangyu/Elastos5
66bec21d7d364ecb223c75b3ad48258aa05b1540
1aa6fe7e60eaf055a9948154242124b04eae3a02
refs/heads/master
2020-12-11T07:22:13.469074
2016-08-23T09:42:42
2016-08-23T09:42:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,897
h
#ifndef __ELASTOS_DROID_INCALLUI_CCALLBUTTONFRAGMENT_H__ #define __ELASTOS_DROID_INCALLUI_CCALLBUTTONFRAGMENT_H__ #include "Elastos.Droid.Content.h" #include "Elastos.Droid.Os.h" #include "Elastos.Droid.View.h" #include "Elastos.Droid.Widget.h" #include "_Elastos_Droid_InCallUI_CCallButtonFragment.h" #include "elastos/droid/incallui/BaseFragment.h" using Elastos::Droid::Content::IContext; using Elastos::Droid::Os::IBundle; using Elastos::Droid::View::ILayoutInflater; using Elastos::Droid::View::IMenuItem; using Elastos::Droid::View::IView; using Elastos::Droid::View::IViewOnClickListener; using Elastos::Droid::View::IViewGroup; using Elastos::Droid::Widget::ICompoundButton; using Elastos::Droid::Widget::ICompoundButtonOnCheckedChangeListener; using Elastos::Droid::Widget::IImageButton; using Elastos::Droid::Widget::IPopupMenu; using Elastos::Droid::Widget::IPopupMenuOnDismissListener; using Elastos::Droid::Widget::IPopupMenuOnMenuItemClickListener; namespace Elastos { namespace Droid { namespace InCallUI { CarClass(CCallButtonFragment) , public BaseFragment , public IPopupMenuOnMenuItemClickListener , public IPopupMenuOnDismissListener , public IViewOnClickListener , public ICompoundButtonOnCheckedChangeListener , public IUi , public ICallButtonUi , public ICallButtonFragment { private: class OverflowPopupOnMenuItemClickListener : public Object , public IPopupMenuOnMenuItemClickListener { public: OverflowPopupOnMenuItemClickListener( /* [in] */ CCallButtonFragment* host) : mHost(host) {} CAR_INTERFACE_DECL(); // @Override CARAPI OnMenuItemClick( /* [in] */ IMenuItem* item, /* [out] */ Boolean* result); private: CCallButtonFragment* mHost; }; class OverflowPopupOnDismissListener : public Object , public IPopupMenuOnDismissListener { public: OverflowPopupOnDismissListener( /* [in] */ CCallButtonFragment* host) : mHost(host) {} CAR_INTERFACE_DECL(); // @Override CARAPI OnDismiss( /* [in] */ IPopupMenu* popupMenu); private: CCallButtonFragment* mHost; }; public: CAR_INTERFACE_DECL(); CAR_OBJECT_DECL(); CCallButtonFragment(); CARAPI constructor(); // @Override CARAPI_(AutoPtr<IPresenter>) CreatePresenter(); // @Override CARAPI_(AutoPtr<IUi>) GetUi(); // @Override CARAPI OnCreate( /* [in] */ IBundle* savedInstanceState); // @Override CARAPI OnCreateView( /* [in] */ ILayoutInflater* inflater, /* [in] */ IViewGroup* container, /* [in] */ IBundle* savedInstanceState, /* [out] */ IView** view); // @Override CARAPI OnActivityCreated( /* [in] */ IBundle* savedInstanceState); // @Override CARAPI OnResume(); // @Override CARAPI OnCheckedChanged( /* [in] */ ICompoundButton* buttonView, /* [in] */ Boolean isChecked); // @Override CARAPI OnClick( /* [in] */ IView* view); // @Override CARAPI SetEnabled( /* [in] */ Boolean isEnabled); // @Override CARAPI SetMute( /* [in] */ Boolean value); // @Override CARAPI ShowAudioButton( /* [in] */ Boolean show); // @Override CARAPI ShowChangeToVoiceButton( /* [in] */ Boolean show); // @Override CARAPI EnableMute( /* [in] */ Boolean enabled); // @Override CARAPI ShowDialpadButton( /* [in] */ Boolean show); // @Override CARAPI SetHold( /* [in] */ Boolean value); // @Override CARAPI ShowHoldButton( /* [in] */ Boolean show); // @Override CARAPI EnableHold( /* [in] */ Boolean enabled); // @Override CARAPI ShowSwapButton( /* [in] */ Boolean show); // @Override CARAPI ShowChangeToVideoButton( /* [in] */ Boolean show); // @Override CARAPI ShowSwitchCameraButton( /* [in] */ Boolean show); // @Override CARAPI SetSwitchCameraButton( /* [in] */ Boolean isBackFacingCamera); // @Override CARAPI ShowAddCallButton( /* [in] */ Boolean show); // @Override CARAPI ShowMergeButton( /* [in] */ Boolean show); // @Override CARAPI ShowPauseVideoButton( /* [in] */ Boolean show); // @Override CARAPI SetPauseVideoButton( /* [in] */ Boolean isPaused); // @Override CARAPI ShowOverflowButton( /* [in] */ Boolean show); // @Override CARAPI ConfigureOverflowMenu( /* [in] */ Boolean showMergeMenuOption, /* [in] */ Boolean showAddMenuOption, /* [in] */ Boolean showHoldMenuOption, /* [in] */ Boolean showSwapMenuOption); // @Override CARAPI SetAudio( /* [in] */ Int32 mode); // @Override CARAPI SetSupportedAudio( /* [in] */ Int32 modeMask); // @Override CARAPI OnMenuItemClick( /* [in] */ IMenuItem* item, /* [out] */ Boolean* result); // PopupMenu.OnDismissListener implementation; see showAudioModePopup(). // This gets called when the PopupMenu gets dismissed for *any* reason, like // the user tapping outside its bounds, or pressing Back, or selecting one // of the menu items. // @Override CARAPI OnDismiss( /* [in] */ IPopupMenu* menu); /** * Refreshes the "Audio mode" popup if it's visible. This is useful * (for example) when a wired headset is plugged or unplugged, * since we need to switch back and forth between the "earpiece" * and "wired headset" items. * * This is safe to call even if the popup is already dismissed, or even if * you never called showAudioModePopup() in the first place. */ CARAPI_(void) RefreshAudioModePopup(); // @Override CARAPI DisplayDialpad( /* [in] */ Boolean value, /* [in] */ Boolean animate); // @Override CARAPI IsDialpadVisible( /* [out] */ Boolean* visible); // @Override CARAPI GetContext( /* [out] */ IContext** context); private: /** * Checks for supporting modes. If bluetooth is supported, it uses the audio * pop up menu. Otherwise, it toggles the speakerphone. */ CARAPI_(void) OnAudioButtonClicked(); /** * Updates the audio button so that the appriopriate visual layers * are visible based on the supported audio formats. */ CARAPI_(void) UpdateAudioButtons( /* [in] */ Int32 supportedModes); CARAPI_(void) ShowAudioModePopup(); CARAPI_(Boolean) IsSupported( /* [in] */ Int32 mode); CARAPI_(Boolean) IsAudio( /* [in] */ Int32 mode); CARAPI_(void) MaybeSendAccessibilityEvent( /* [in] */ IView* view, /* [in] */ Int32 stringId); private: AutoPtr<IImageButton> mAudioButton; AutoPtr<IImageButton> mChangeToVoiceButton; AutoPtr<IImageButton> mMuteButton; AutoPtr<IImageButton> mShowDialpadButton; AutoPtr<IImageButton> mHoldButton; AutoPtr<IImageButton> mSwapButton; AutoPtr<IImageButton> mChangeToVideoButton; AutoPtr<IImageButton> mSwitchCameraButton; AutoPtr<IImageButton> mAddCallButton; AutoPtr<IImageButton> mMergeButton; AutoPtr<IImageButton> mPauseVideoButton; AutoPtr<IImageButton> mOverflowButton; AutoPtr<IPopupMenu> mAudioModePopup; Boolean mAudioModePopupVisible; AutoPtr<IPopupMenu> mOverflowPopup; Int32 mPrevAudioMode; // Constants for Drawable.setAlpha() static const Int32 HIDDEN; static const Int32 VISIBLE; Boolean mIsEnabled; }; } // namespace InCallUI } // namespace Droid } // namespace Elastos #endif // __ELASTOS_DROID_INCALLUI_CCALLBUTTONFRAGMENT_H__
[ "cao.jing@kortide.com" ]
cao.jing@kortide.com
9b37404d4e67f28f37600f501272933fd8b24bce
a71b70de1877959b73f7e78ee62e9138ec5a2585
/PKU/2400-2499/P2480.cpp
f0fa36690eb374f3e49966f76b425baac6e71551
[]
no_license
HJWAJ/acm_codes
38d32c6d12837b07584198c40ce916546085f636
5fa3ee82cb5114eb3cfe4e6fa2baba0f476f6434
refs/heads/master
2022-01-24T03:00:51.737372
2022-01-14T10:04:05
2022-01-14T10:04:05
151,313,977
0
0
null
null
null
null
UTF-8
C++
false
false
2,154
cpp
#include <cstdlib> #include <cctype> #include <cstring> #include <cstdio> #include <cmath> #include <algorithm> #include <vector> #include <string> #include <iostream> #include <sstream> #include <map> #include <set> #include <queue> #include <stack> #include <fstream> #include <numeric> #include <iomanip> #include <bitset> #include <list> #include <stdexcept> #include <functional> #include <utility> #include <ctime> #include <memory.h> using namespace std; __int64 divi[100005]; __int64 prime[50000]; bool bo[50001]; __int64 p[100005],a[100005]; int prime_table() { int i,j,flag=0; memset(bo,0,sizeof(bo)); bo[0]=bo[1]=1; for(i=2;i<=50000;i++) if(!bo[i]) { prime[flag++]=i; j=i+i; for(;j<=50000;j+=i)bo[j]=1; } return flag; } int divided(__int64 n,__int64 p[],__int64 a[]) { __int64 sq=(__int64)(sqrt(double(n))); int flag=0,num=0; while(1) { if(n==1)break; if(prime[flag]>sq) { p[num]=n; a[num++]=1; break; } if(n%prime[flag]!=0) { flag++; continue; } p[num]=prime[flag]; a[num++]=1; n/=prime[flag]; while(n%prime[flag]==0) { n/=prime[flag]; a[num-1]++; } flag++; } return num; } __int64 divide(__int64 n) { __int64 i,flag=0; for(i=1;i*i<n;i++) { if(n%i==0) { divi[flag++]=i; divi[flag++]=n/i; } } if(i*i==n)divi[flag++]=i; return flag; } __int64 eular(__int64 n) { if(n==1)return 1; int flag=divided(n,p,a),i; //for(i=0;i<flag;i++)cout<<p[i]<<' '<<a[i]<<endl; for(i=0;i<flag;i++) { n/=p[i]; n*=(p[i]-1); } return n; } int main() { __int64 n,ans,flag,i; prime_table(); while(scanf("%I64d",&n)!=EOF) { flag=divide(n); ans=0; for(i=0;i<flag;i++) { //cout<<divi[i]<<endl; ans+=divi[i]*eular(n/divi[i]); } printf("%I64d\n",ans); } return 0; }
[ "jiawei.hua@dianping.com" ]
jiawei.hua@dianping.com
dd1621aa7af8c321977c985708ed216de5ba6610
19f039b593be9401d479b15f97ecb191ef478f46
/RSA-SW/PSME/agent/storage/src/iscsi/config/tgt_config.cpp
e20293c1ae1a22dca3b16b48510705681006cbea
[ "MIT", "BSD-3-Clause", "Apache-2.0" ]
permissive
isabella232/IntelRackScaleArchitecture
9a28e34a7f7cdc21402791f24dad842ac74d07b6
1206d2316e1bd1889b10a1c4f4a39f71bdfa88d3
refs/heads/master
2021-06-04T08:33:27.191735
2016-09-29T09:18:10
2016-09-29T09:18:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,813
cpp
/*! * @section LICENSE * * @copyright * Copyright (c) 2015 Intel Corporation * * @copyright * 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 * * @copyright * http://www.apache.org/licenses/LICENSE-2.0 * * @copyright * 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. * * @section DESCRIPTION */ #include "iscsi/tgt/config/tgt_config.hpp" #include "iscsi/tgt/config/tgt_target_config.hpp" #include "agent-framework/module/target.hpp" #include "logger/logger_factory.hpp" #include <stdexcept> #include <iostream> #include <fstream> #include <cstring> using namespace agent::storage::iscsi::tgt::config; using namespace agent_framework::generic; using namespace std; constexpr const char* TGT_TARGET_CONF_EXTENSION = ".conf"; constexpr const char* TGT_TARGET_CONF_PATH = "/etc/tgt/conf.d/"; void TgtConfig::add_target(const Target::TargetSharedPtr& target) const { TgtTargetConfig tgtTargetConfig(target); auto target_conf_file_name = get_target_conf_file_name(target->get_target_id()); log_info(GET_LOGGER("tgt"), "Add TGT target config file: " + target_conf_file_name); ofstream targetConfigFile; const auto& content = tgtTargetConfig.to_string(); targetConfigFile.open(target_conf_file_name.c_str(), ios_base::out); if (targetConfigFile.is_open()) { targetConfigFile << content; targetConfigFile.close(); } else { throw runtime_error("Error opening file for writing: " + target_conf_file_name); } } void TgtConfig::remove_target(const int32_t target_id) const { auto target_conf_file_name = get_target_conf_file_name(target_id); log_info(GET_LOGGER("tgt"), "Remove TGT target config file: " + target_conf_file_name); if (0 != remove(target_conf_file_name.c_str())) { throw runtime_error("Error removing file: " + target_conf_file_name); } } string TgtConfig::get_target_conf_file_name(const int32_t target_id) const { string configuration_path = m_configuration_path; if (configuration_path.empty()) { log_warning(GET_LOGGER("tgt"), "TGT conf-path is empty. Using default path: " << TGT_TARGET_CONF_PATH); configuration_path = TGT_TARGET_CONF_PATH; } if ('/' != configuration_path.at(configuration_path.size() - 1)) { configuration_path += '/'; } return configuration_path + to_string(target_id) + TGT_TARGET_CONF_EXTENSION; }
[ "chester.kuo@gmail.com" ]
chester.kuo@gmail.com
7aea823a59b8765db5fc58b47d9e74c6fa74ccef
d6c08c1fad41043734f592a5f3e3cca77ff37de3
/src/Token.cpp
82e16243c75b78057240877d7d765731bcf02004
[]
no_license
hstowasser/CompilerProjectV2
c2b547056f3b96dbe70cfa84361619aa78d13225
efe1bbd8c656312a8ff3a1439ff083e1632fee1a
refs/heads/main
2023-03-25T14:10:37.753968
2021-03-28T17:09:02
2021-03-28T17:09:02
340,529,656
0
0
null
null
null
null
UTF-8
C++
false
false
6,055
cpp
#include "Token.hpp" #include <stdio.h> const char * token_type_to_string(token_type_e token_type) { switch (token_type){ case T_IDENTIFIER: return "T_IDENTIFIER"; case T_EOF: return "T_EOF"; case T_SYM_LPAREN: return "T_SYM_LPAREN"; case T_SYM_RPAREN: return "T_SYM_RPAREN"; case T_SYM_LBRACE: return "T_SYM_LBRACE"; case T_SYM_RBRACE: return "T_SYM_RBRACE"; case T_SYM_LBRACKET: return "T_SYM_LBRACKET"; case T_SYM_RBRACKET: return "T_SYM_RBRACKET"; case T_SYM_SEMICOLON: return "T_SYM_SEMICOLON"; case T_SYM_COLON: return "T_SYM_COLON"; case T_SYM_PERIOD: return "T_SYM_PERIOD"; case T_SYM_COMMA: return "T_SYM_COMMA"; case T_OP_BITW_AND: return "T_OP_BITW_AND"; case T_OP_BITW_OR: return "T_OP_BITW_OR"; // case T_OP_BITW_NOT: // return "T_OP_BITW_NOT"; case T_OP_ASIGN_EQUALS: return "T_OP_ASIGN_EQUALS"; case T_OP_TERM_MULTIPLY: return "T_OP_TERM_MULTIPLY"; case T_OP_TERM_DIVIDE: return "T_OP_TERM_DIVIDE"; case T_OP_REL_GREATER: return "T_OP_REL_GREATER"; case T_OP_REL_LESS: return "T_OP_REL_LESS"; case T_OP_REL_GREATER_EQUAL: return "T_OP_REL_GREATER_EQUAL"; case T_OP_REL_LESS_EQUAL: return "T_OP_REL_LESS_EQUAL"; case T_OP_REL_EQUAL: return "T_OP_REL_EQUAL"; case T_OP_REL_NOT_EQUAL: return "T_OP_REL_NOT_EQUAL"; case T_OP_ARITH_PLUS: return "T_OP_ARITH_PLUS"; case T_OP_ARITH_MINUS: return "T_OP_ARITH_MINUS"; case T_CONST_INTEGER: return "T_CONST_INTEGER"; case T_CONST_FLOAT: return "T_CONST_FLOAT"; case T_CONST_STRING: return "T_CONST_STRING"; case T_RW_PROGRAM: return "T_RW_PROGRAM"; case T_RW_IS: return "T_RW_IS"; case T_RW_BEGIN: return "T_RW_BEGIN"; case T_RW_END: return "T_RW_END"; case T_RW_GLOBAL: return "T_RW_GLOBAL"; case T_RW_INTEGER: return "T_RW_INTEGER"; case T_RW_FLOAT: return "T_RW_FLOAT"; case T_RW_STRING: return "T_RW_STRING"; case T_RW_BOOL: return "T_RW_BOOL"; //case T_RW_ENUM: // return "T_RW_ENUM"; case T_RW_PROCEDURE: return "T_RW_PROCEDURE"; case T_RW_VARIABLE: return "T_RW_VARIABLE"; case T_RW_IF: return "T_RW_IF"; case T_RW_THEN: return "T_RW_THEN"; case T_RW_ELSE: return "T_RW_ELSE"; case T_RW_FOR: return "T_RW_FOR"; case T_RW_RETURN: return "T_RW_RETURN"; case T_RW_NOT: return "T_RW_NOT"; // case T_RW_TYPE: // return "T_RW_TYPE"; case T_RW_TRUE: return "T_RW_TRUE"; case T_RW_FALSE: return "T_RW_FALSE"; default: return "T_UNKNOWN"; } } void print_token(token_t token) { printf("Type: %s Line: %d ", token_type_to_string(token.type), token.line_num); if ( token.type == T_IDENTIFIER || token.type == T_CONST_STRING){ printf("value: %s", token.getStringValue()->c_str()); }else if ( token.type == T_CONST_INTEGER) { printf("integer value: %d", token.getIntValue()); }else if ( token.type == T_CONST_FLOAT) { printf("float value: %f", token.getFloatValue()); } printf("\n"); } token_t::token_t() { this->line_num = 0; this->type = T_UNKNOWN; this->_value = NULL; this->tag = NULL; this->value_type = NONE; } token_t::~token_t() { } void token_t::destroy() { if ( this->value_type == INT || this->value_type == FLOAT){ free(this->_value); }else if ( this->value_type == STRING){ delete (std::string*)(this->_value); } } void token_t::setValue(std::string value) { if ( this->_value == NULL){ this->_value = (void*) new std::string(value); this->value_type = STRING; this->tag = (void*)this; } } void token_t::setValue(int value) { if ( this->_value == NULL){ this->_value = malloc(sizeof(int)); if ( this->_value != NULL){ *((int*)this->_value) = value; this->value_type = INT; this->tag = (void*)this; } } } void token_t::setValue(float value) { if ( this->_value == NULL){ this->_value = malloc(sizeof(float)); if ( this->_value != NULL){ *((float*)this->_value) = value; this->value_type = FLOAT; this->tag = (void*)this; } } } std::string* token_t::getStringValue() { if (this->value_type == STRING){ return (std::string*)this->_value; }else{ //return ""; // Error return NULL; } } int token_t::getIntValue() { if (this->value_type == INT){ return *((int*)this->_value); }else{ return 0; // Error } } float token_t::getFloatValue() { if (this->value_type == FLOAT){ return *((float*)this->_value); }else{ return 0; // Error } }
[ "stowasserheiko@gmail.com" ]
stowasserheiko@gmail.com
76b6f91e9e202c51a2401e040291496d6ae60a08
24acf54ec9b57c0450732a0051ea1e4ae91a7190
/Library/Platinum/ThirdParty/Neptune/Source/Data/TLS/Base/NptTlsTrustAnchor_Base_0012.cpp
56aa239b888ec40894ef73f2ee78baa7b4922a51
[ "LicenseRef-scancode-generic-cla" ]
no_license
shawnji2060/KEFWireless-DLNA
c12ac384bba4a80a43234c909cd6c791069ee3b8
98b6886f9ae54571cca66e32ecf1197533a5488b
refs/heads/master
2021-01-18T16:37:50.320261
2017-08-16T08:14:14
2017-08-16T08:14:14
100,464,539
0
1
null
null
null
null
UTF-8
C++
false
false
7,056
cpp
/***************************************************************** | | Neptune - Trust Anchors | | This file is automatically generated by a script, do not edit! | | Copyright (c) 2002-2010, Axiomatic Systems, LLC. | 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 Axiomatic Systems 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 AXIOMATIC SYSTEMS ''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 AXIOMATIC SYSTEMS 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. | ****************************************************************/ #if defined(NPT_CONFIG_ENABLE_TLS) /* Digital Signature Trust Co. Global CA 4 */ const unsigned char NptTlsTrustAnchor_Base_0012_Data[988] = { 0x30,0x82,0x03,0xd8,0x30,0x82,0x02,0xc0 ,0x02,0x11,0x00,0xd0,0x1e,0x40,0x8b,0x00 ,0x00,0x77,0x6d,0x00,0x00,0x00,0x01,0x00 ,0x00,0x00,0x04,0x30,0x0d,0x06,0x09,0x2a ,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01,0x05 ,0x05,0x00,0x30,0x81,0xa9,0x31,0x0b,0x30 ,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02 ,0x75,0x73,0x31,0x0d,0x30,0x0b,0x06,0x03 ,0x55,0x04,0x08,0x13,0x04,0x55,0x74,0x61 ,0x68,0x31,0x17,0x30,0x15,0x06,0x03,0x55 ,0x04,0x07,0x13,0x0e,0x53,0x61,0x6c,0x74 ,0x20,0x4c,0x61,0x6b,0x65,0x20,0x43,0x69 ,0x74,0x79,0x31,0x24,0x30,0x22,0x06,0x03 ,0x55,0x04,0x0a,0x13,0x1b,0x44,0x69,0x67 ,0x69,0x74,0x61,0x6c,0x20,0x53,0x69,0x67 ,0x6e,0x61,0x74,0x75,0x72,0x65,0x20,0x54 ,0x72,0x75,0x73,0x74,0x20,0x43,0x6f,0x2e ,0x31,0x11,0x30,0x0f,0x06,0x03,0x55,0x04 ,0x0b,0x13,0x08,0x44,0x53,0x54,0x43,0x41 ,0x20,0x58,0x32,0x31,0x16,0x30,0x14,0x06 ,0x03,0x55,0x04,0x03,0x13,0x0d,0x44,0x53 ,0x54,0x20,0x52,0x6f,0x6f,0x74,0x43,0x41 ,0x20,0x58,0x32,0x31,0x21,0x30,0x1f,0x06 ,0x09,0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01 ,0x09,0x01,0x16,0x12,0x63,0x61,0x40,0x64 ,0x69,0x67,0x73,0x69,0x67,0x74,0x72,0x75 ,0x73,0x74,0x2e,0x63,0x6f,0x6d,0x30,0x1e ,0x17,0x0d,0x39,0x38,0x31,0x31,0x33,0x30 ,0x32,0x32,0x34,0x36,0x31,0x36,0x5a,0x17 ,0x0d,0x30,0x38,0x31,0x31,0x32,0x37,0x32 ,0x32,0x34,0x36,0x31,0x36,0x5a,0x30,0x81 ,0xa9,0x31,0x0b,0x30,0x09,0x06,0x03,0x55 ,0x04,0x06,0x13,0x02,0x75,0x73,0x31,0x0d ,0x30,0x0b,0x06,0x03,0x55,0x04,0x08,0x13 ,0x04,0x55,0x74,0x61,0x68,0x31,0x17,0x30 ,0x15,0x06,0x03,0x55,0x04,0x07,0x13,0x0e ,0x53,0x61,0x6c,0x74,0x20,0x4c,0x61,0x6b ,0x65,0x20,0x43,0x69,0x74,0x79,0x31,0x24 ,0x30,0x22,0x06,0x03,0x55,0x04,0x0a,0x13 ,0x1b,0x44,0x69,0x67,0x69,0x74,0x61,0x6c ,0x20,0x53,0x69,0x67,0x6e,0x61,0x74,0x75 ,0x72,0x65,0x20,0x54,0x72,0x75,0x73,0x74 ,0x20,0x43,0x6f,0x2e,0x31,0x11,0x30,0x0f ,0x06,0x03,0x55,0x04,0x0b,0x13,0x08,0x44 ,0x53,0x54,0x43,0x41,0x20,0x58,0x32,0x31 ,0x16,0x30,0x14,0x06,0x03,0x55,0x04,0x03 ,0x13,0x0d,0x44,0x53,0x54,0x20,0x52,0x6f ,0x6f,0x74,0x43,0x41,0x20,0x58,0x32,0x31 ,0x21,0x30,0x1f,0x06,0x09,0x2a,0x86,0x48 ,0x86,0xf7,0x0d,0x01,0x09,0x01,0x16,0x12 ,0x63,0x61,0x40,0x64,0x69,0x67,0x73,0x69 ,0x67,0x74,0x72,0x75,0x73,0x74,0x2e,0x63 ,0x6f,0x6d,0x30,0x82,0x01,0x22,0x30,0x0d ,0x06,0x09,0x2a,0x86,0x48,0x86,0xf7,0x0d ,0x01,0x01,0x01,0x05,0x00,0x03,0x82,0x01 ,0x0f,0x00,0x30,0x82,0x01,0x0a,0x02,0x82 ,0x01,0x01,0x00,0xdc,0x75,0xf0,0x8c,0xc0 ,0x75,0x96,0x9a,0xc0,0x62,0x1f,0x26,0xf7 ,0xc4,0xe1,0x9a,0xea,0xe0,0x56,0x73,0x5b ,0x99,0xcd,0x01,0x44,0xa8,0x08,0xb6,0xd5 ,0xa7,0xda,0x1a,0x04,0x18,0x39,0x92,0x4a ,0x78,0xa3,0x81,0xc2,0xf5,0x77,0x7a,0x50 ,0xb4,0x70,0xff,0x9a,0xab,0xc6,0xc7,0xca ,0x6e,0x83,0x4f,0x42,0x98,0xfb,0x26,0x0b ,0xda,0xdc,0x6d,0xd6,0xa9,0x99,0x55,0x52 ,0x67,0xe9,0x28,0x03,0x92,0xdc,0xe5,0xb0 ,0x05,0x9a,0x0f,0x15,0xf9,0x6b,0x59,0x72 ,0x56,0xf2,0xfa,0x39,0xfc,0xaa,0x68,0xee ,0x0f,0x1f,0x10,0x83,0x2f,0xfc,0x9d,0xfa ,0x17,0x96,0xdd,0x82,0xe3,0xe6,0x45,0x7d ,0xc0,0x4b,0x80,0x44,0x1f,0xed,0x2c,0xe0 ,0x84,0xfd,0x91,0x5c,0x92,0x54,0x69,0x25 ,0xe5,0x62,0x69,0xdc,0xe5,0xee,0x00,0x52 ,0xbd,0x33,0x0b,0xad,0x75,0x02,0x85,0xa7 ,0x64,0x50,0x2d,0xc5,0x19,0x19,0x30,0xc0 ,0x26,0xdb,0xc9,0xd3,0xfd,0x2e,0x99,0xad ,0x59,0xb5,0x0b,0x4d,0xd4,0x41,0xae,0x85 ,0x48,0x43,0x59,0xdc,0xb7,0xa8,0xe2,0xa2 ,0xde,0xc3,0x8f,0xd7,0xb8,0xa1,0x62,0xa6 ,0x68,0x50,0x52,0xe4,0xcf,0x31,0xa7,0x94 ,0x85,0xda,0x9f,0x46,0x32,0x17,0x56,0xe5 ,0xf2,0xeb,0x66,0x3d,0x12,0xff,0x43,0xdb ,0x98,0xef,0x77,0xcf,0xcb,0x81,0x8d,0x34 ,0xb1,0xc6,0x50,0x4a,0x26,0xd1,0xe4,0x3e ,0x41,0x50,0xaf,0x6c,0xae,0x22,0x34,0x2e ,0xd5,0x6b,0x6e,0x83,0xba,0x79,0xb8,0x76 ,0x65,0x48,0xda,0x09,0x29,0x64,0x63,0x22 ,0xb9,0xfb,0x47,0x76,0x85,0x8c,0x86,0x44 ,0xcb,0x09,0xdb,0x02,0x03,0x01,0x00,0x01 ,0x30,0x0d,0x06,0x09,0x2a,0x86,0x48,0x86 ,0xf7,0x0d,0x01,0x01,0x05,0x05,0x00,0x03 ,0x82,0x01,0x01,0x00,0xb5,0x36,0x0e,0x5d ,0xe1,0x61,0x28,0x5a,0x11,0x65,0xc0,0x3f ,0x83,0x03,0x79,0x4d,0xbe,0x28,0xa6,0x0b ,0x07,0x02,0x52,0x85,0xcd,0xf8,0x91,0xd0 ,0x10,0x6c,0xb5,0x6a,0x20,0x5b,0x1c,0x90 ,0xd9,0x30,0x3c,0xc6,0x48,0x9e,0x8a,0x5e ,0x64,0xf9,0xa1,0x71,0x77,0xef,0x04,0x27 ,0x1f,0x07,0xeb,0xe4,0x26,0xf7,0x73,0x74 ,0xc9,0x44,0x18,0x1a,0x66,0xd3,0xe0,0x43 ,0xaf,0x91,0x3b,0xd1,0xcb,0x2c,0xd8,0x74 ,0x54,0x3a,0x1c,0x4d,0xca,0xd4,0x68,0xcd ,0x23,0x7c,0x1d,0x10,0x9e,0x45,0xe9,0xf6 ,0x00,0x6e,0xa6,0xcd,0x19,0xff,0x4f,0x2c ,0x29,0x8f,0x57,0x4d,0xc4,0x77,0x92,0xbe ,0xe0,0x4c,0x09,0xfb,0x5d,0x44,0x86,0x66 ,0x21,0xa8,0xb9,0x32,0xa2,0x56,0xd5,0xe9 ,0x8c,0x83,0x7c,0x59,0x3f,0xc4,0xf1,0x0b ,0xe7,0x9d,0xec,0x9e,0xbd,0x9c,0x18,0x0e ,0x3e,0xc2,0x39,0x79,0x28,0xb7,0x03,0x0d ,0x08,0xcb,0xc6,0xe7,0xd9,0x01,0x37,0x50 ,0x10,0xec,0xcc,0x61,0x16,0x40,0xd4,0xaf ,0x31,0x74,0x7b,0xfc,0x3f,0x31,0xa7,0xd0 ,0x47,0x73,0x33,0x39,0x1b,0xcc,0x4e,0x6a ,0xd7,0x49,0x83,0x11,0x06,0xfe,0xeb,0x82 ,0x58,0x33,0x32,0x4c,0xf0,0x56,0xac,0x1e ,0x9c,0x2f,0x56,0x9a,0x7b,0xc1,0x4a,0x1c ,0xa5,0xfd,0x55,0x36,0xce,0xfc,0x96,0x4d ,0xf4,0xb0,0xf0,0xec,0xb7,0x6c,0x82,0xed ,0x2f,0x31,0x99,0x42,0x4c,0xa9,0xb2,0x0d ,0xb8,0x15,0x5d,0xf1,0xdf,0xba,0xc9,0xb5 ,0x4a,0xd4,0x64,0x98,0xb3,0x26,0xa9,0x30 ,0xc8,0xfd,0xa6,0xec,0xab,0x96,0x21,0xad ,0x7f,0xc2,0x78,0xb6}; const unsigned int NptTlsTrustAnchor_Base_0012_Size = 988; #endif
[ "shawnji2060@gmail.com" ]
shawnji2060@gmail.com
485d3f688c1f241e5b724d4749d9be4789902d41
f712d2e44d1de06496d23b69e3a9bd53d46f794a
/net-p2p/dnotes/files/patch-src__net.cpp
9d3d551f526551595cca8fd70a2b11267d5c642d
[ "BSD-2-Clause" ]
permissive
tuaris/FreeBSD-Coin-Ports
931da8f274b3f229efb6a79b4f34ffb2036d4786
330d9f5a10cf7dc1cddc3566b897bd4e6e265d9f
refs/heads/master
2021-06-18T20:21:05.001837
2021-01-20T21:26:44
2021-01-20T21:26:44
21,374,280
4
6
BSD-2-Clause
2018-01-26T09:22:30
2014-07-01T03:40:30
Makefile
UTF-8
C++
false
false
379
cpp
--- src/net.cpp.orig 2014-08-31 15:33:55 UTC +++ src/net.cpp @@ -58,7 +58,7 @@ static bool vfReachable[NET_MAX] = {}; static bool vfLimited[NET_MAX] = {}; static CNode* pnodeLocalHost = NULL; uint64 nLocalHostNonce = 0; -array<int, THREAD_MAX> vnThreadsRunning; +boost::array<int, THREAD_MAX> vnThreadsRunning; static std::vector<SOCKET> vhListenSocket; CAddrMan addrman;
[ "daniel@morante.net" ]
daniel@morante.net
961d2a9d6be822239d0e465931331522e4598690
cc47ba1d94ea53c8afb944d280bdf1e6197f8e3d
/C++/CodeForces/CR694A.cpp
f9444cd8fef37d24cf804a285014e3456aa5eae0
[]
no_license
Pranshu-Tripathi/Programming
60180f9b0c5f879b2a8bf85c3db14afe1fdb45ba
ae7234b293b307a0f38af6f5a7894747f22c5d45
refs/heads/master
2023-06-26T08:17:07.184679
2021-07-28T02:52:43
2021-07-28T02:52:43
226,936,580
0
0
null
null
null
null
UTF-8
C++
false
false
605
cpp
#include<bits/stdc++.h> using namespace std; #define ll long long void _run() { ll n,x; cin >> n >> x; ll arr[n]; ll s1 = 0, s2 = 0; for(int i =0 ; i < n ; i++) { cin >> arr[i]; s1 += arr[i] / x; if(arr[i] % x) { s1 ++; } s2 += arr[i]; } ll ans=0; if(s2%x) { ans++; } s2 = s2/x; s2 += ans; cout<<s2<<" "<<s1<<endl; return; } int main() { ios::sync_with_stdio(false); cin.tie(NULL); int test; cin >> test; while(test--) _run(); return 0; }
[ "mtpranshu2001@gmail.com" ]
mtpranshu2001@gmail.com
231994a748f60ae6cd2eca98aa9ce320dca8dc26
7fae79369bffd6fe98a8d517ce15d93935ac104c
/main.cpp
1dc659e33f33c9c0a168eaa3dfe140f323de221d
[]
no_license
ArielAleksandrus/compilador
a5109d09f6a90c9f0b7964e6b495223ad50d75cf
1a4c5fe2349b8de1b0b5b0a58ac5253e29d9ea80
refs/heads/master
2020-05-21T10:14:56.407885
2016-07-29T17:31:16
2016-07-29T17:31:16
54,926,554
0
0
null
null
null
null
UTF-8
C++
false
false
2,212
cpp
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: main.cpp * Author: aleksandrus * * Created on March 18, 2016, 11:06 AM */ #include <iostream> #include <cstdlib> #include "circular_dep.h" #include "FileReader.h" #include "Parser.h" #include "Tree.h" using namespace std; typedef struct Options{ char fileName[256]; bool printTokens; bool printTree; bool printGlobals; bool printFunctions; bool terminate; }Options; Options* handleArgs(int argc, char** argv){ Options* o = (Options*) calloc(1, sizeof(Options)); strncpy(o->fileName, argv[1], 256); for(int i = 2; i <= argc; i++){ if(strcmp(argv[i - 1], "-h") == 0){ cout << "Usage:\n"; cout << "First argument should be source file's path or -h alone.\n"; cout << "\t-h\t\tPrint available options.\n"; cout << "\t-pto\t\tPrint recognized tokens.\n"; cout << "\t-ptr\t\tPrint elements's tree.\n"; cout << "\t-pg\t\tPrint global variables.\n"; cout << "\t-pf\t\tPrint functions.\n"; cout << "\t-pa\t\tPrint all.\n"; o->terminate = true; } if(strcmp(argv[i - 1], "-pto") == 0){ o->printTokens = true; } if(strcmp(argv[i - 1], "-ptr") == 0){ o->printTree = true; } if(strcmp(argv[i - 1], "-pg") == 0){ o->printGlobals = true; } if(strcmp(argv[i - 1], "-pf") == 0){ o->printFunctions = true; } if(strcmp(argv[i - 1], "-pa") == 0){ o->printTokens = true; o->printTree = true; o->printGlobals = true; o->printFunctions = true; } } return o; } int main(int argc, char** argv) { if(argc < 2){ cout << "Missing file as argument" << endl; exit(1); } Options* o = handleArgs(argc, argv); if(o->terminate) return 0; FileReader* fr = new FileReader(argv[1]); if(o->printTokens) fr->printTokens(); Utils u; u.out.open("a.out"); Tree* t = new Tree(&u); Parser* p = new Parser(fr->getTokens(), t); if(o->printTree) t->printTree(); else { if(o->printGlobals) t->printGlobalVariables(); if(o->printFunctions) t->printFunctions(); } t->semanticAnalysis(); u.out.close(); return 0; }
[ "arielaleksandrus@hotmail.com" ]
arielaleksandrus@hotmail.com
c8f9f07944e3f28b7cc24f46ddd2fb4374d2b62c
fbb664ae602ecf0c1679dbb998f1cfb296a63b17
/tests/catch_malloc.h
3e49d293466a8b0026ae2896fdf18a41287e5bfd
[]
no_license
ADVRHumanoids/RealtimeSvd
82368c56609b1999d972140d64203e58b7111bee
71987b17fb0f71d6b0b906849a5ea0021b00a013
refs/heads/master
2021-07-06T13:08:39.747407
2018-10-22T18:41:56
2018-10-22T18:41:56
153,766,252
1
1
null
2020-07-31T08:47:03
2018-10-19T10:29:06
CMake
UTF-8
C++
false
false
4,556
h
#ifndef __CATCH_MALLOC_H__ #define __CATCH_MALLOC_H__ #include <malloc.h> #include <exception> #include <iostream> #include <functional> namespace XBot { namespace Utils { class MallocFinder { public: static void SetThrowOnMalloc(bool throw_on_malloc) { _throw_on_malloc = throw_on_malloc; } static bool ThrowsOnMalloc() { return _throw_on_malloc; } static void SetThrowOnFree(bool throw_on_free) { _throw_on_free = throw_on_free; } static bool ThrowsOnFree() { return _throw_on_free; } static void Enable() { _is_enabled = true; } static void Disable() { _is_enabled = false; } static bool IsEnabled() { return _is_enabled; } static void OnMalloc() { _f_malloc(); } static void OnFree() { _f_free(); } static void SetOnMalloc(std::function<void(void)> f) { _f_malloc = f; } static void SetOnFree(std::function<void(void)> f) { _f_free = f; } private: static bool _is_enabled; static bool _throw_on_malloc; static bool _throw_on_free; static std::function<void(void)> _f_malloc; static std::function<void(void)> _f_free; }; bool MallocFinder::_is_enabled = false; bool MallocFinder::_throw_on_malloc = false; bool MallocFinder::_throw_on_free = false; std::function<void(void)> MallocFinder::_f_malloc = [](){ printf("Malloc was called!\n");}; std::function<void(void)> MallocFinder::_f_free = [](){ printf("Free was called!\n");}; } } /* Declare a function pointer into which we will store the default malloc */ static void * (* prev_malloc_hook)(size_t, const void *); static void (* prev_free_hook)(void *, const void *); /* Ignore deprecated __malloc_hook */ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" static void * testing_malloc(size_t size, const void * caller); static void testing_free(void * addr, const void * caller); class MallocHookGuard { public: MallocHookGuard() { __malloc_hook = prev_malloc_hook; __free_hook = prev_free_hook; } ~MallocHookGuard() { __malloc_hook = testing_malloc; __free_hook = testing_free; } }; /* Custom malloc */ static void * testing_malloc(size_t size, const void * caller) { (void)caller; /* Set the malloc implementation to the default malloc hook so that we can call it * (otherwise, infinite recursion) */ MallocHookGuard hook_guard; if (XBot::Utils::MallocFinder::IsEnabled()) { XBot::Utils::MallocFinder::OnMalloc(); if(XBot::Utils::MallocFinder::ThrowsOnMalloc()) { throw std::runtime_error("ThrowOnMalloc is enabled"); } } // Execute the requested malloc. void * mem = malloc(size); // Set the malloc hook back to this function, so that we can intercept future mallocs. return mem; } /* Custom free */ static void testing_free(void * addr, const void * caller) { (void)caller; /* Set the malloc implementation to the default malloc hook so that we can call it * (otherwise, infinite recursion) */ __free_hook = prev_free_hook; if (XBot::Utils::MallocFinder::IsEnabled()) { XBot::Utils::MallocFinder::OnFree(); if(XBot::Utils::MallocFinder::ThrowsOnFree()) { throw std::runtime_error("ThrowOnFree is enabled"); } } // Execute the requested malloc. free(addr); // Set the malloc hook back to this function, so that we can intercept future mallocs. __free_hook = testing_free; } /// Function to be called when the malloc hook is initialized. void init_malloc_hook() { // Store the default malloc. prev_malloc_hook = __malloc_hook; prev_free_hook = __free_hook; // Set our custom malloc to the malloc hook. __malloc_hook = testing_malloc; __free_hook = testing_free; } #pragma GCC diagnostic pop /// Set the hook for malloc initialize so that init_malloc_hook gets called. void(*volatile __malloc_initialize_hook)(void) = init_malloc_hook; #endif
[ "arturo.laurenzi@iit.it" ]
arturo.laurenzi@iit.it
f74d082cf319a429b6adbcc470737b197634733c
4b590410d4042c156cfd3d4e874f3a329390a72b
/src/uscxml/messages/MMIMessages.cpp
35e8b66a66fbd995383e58498ac34996a1ad0751
[ "BSD-2-Clause" ]
permissive
su6838354/uscxml
37b93aef528996d2dd66d348f9e1f31b6734ab57
81aa1c79dd158aa7bc76876552e4b1d05ecea656
refs/heads/master
2020-04-06T05:29:54.201412
2015-04-02T11:44:48
2015-04-02T11:44:48
38,090,859
1
0
null
2015-06-26T04:37:32
2015-06-26T04:37:32
null
UTF-8
C++
false
false
18,827
cpp
/** * @file * @author 2012-2013 Stefan Radomski (stefan.radomski@cs.tu-darmstadt.de) * @copyright Simplified BSD * * @cond * This program is free software: you can redistribute it and/or modify * it under the terms of the FreeBSD license as published by the FreeBSD * project. * * 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. * * You should have received a copy of the FreeBSD license along with this * program. If not, see <http://www.opensource.org/licenses/bsd-license>. * @endcond */ #include <string> // MSVC will croak with operator+ on strings if this is not first #include "MMIMessages.h" #include <DOM/Simple/DOMImplementation.hpp> #include <DOM/io/Stream.hpp> #include <DOM/SAX2DOM/SAX2DOM.hpp> #include <SAX/helpers/InputSourceResolver.hpp> #include <uscxml/DOMUtils.h> #include <boost/algorithm/string.hpp> #define TO_EVENT_OPERATOR(type, name, base)\ type::operator Event() const { \ Event ev = base::operator Event();\ ev.setName(name);\ if (representation == MMI_AS_XML) \ ev.setDOM(toXML());\ return ev;\ } #define FIND_MSG_ELEM(elem, doc) \ Element<std::string> elem; \ if (encapsulateInMMI) { \ elem = Element<std::string>(doc.getDocumentElement().getFirstChild()); \ } else { \ elem = Element<std::string>(doc.getDocumentElement()); \ } #define FROM_XML(clazz, enumType, base) \ clazz clazz::fromXML(Arabica::DOM::Node<std::string> node, InterpreterImpl* interpreter) { \ clazz event = base::fromXML(node, interpreter); \ event.type = enumType; \ return event; \ } #define STRING_ATTR_OR_EXPR(element, name)\ (element.hasAttributeNS(nameSpace, "name##Expr") && interpreter ? \ interpreter->getDataModel().evalAsString(element.getAttributeNS(nameSpace, "name##Expr")) : \ (element.hasAttributeNS(nameSpace, #name) ? element.getAttributeNS(nameSpace, #name) : "") \ ) #define FIND_EVENT_NODE(node)\ if (node.getNodeType() == Node_base::DOCUMENT_NODE) \ node = node.getFirstChild(); \ while (node) {\ if (node.getNodeType() == Node_base::ELEMENT_NODE) {\ if (boost::iequals(node.getLocalName(), "MMI")) {\ node = node.getFirstChild();\ continue;\ } else {\ break;\ }\ }\ node = node.getNextSibling();\ }\ namespace uscxml { using namespace Arabica::DOM; std::string MMIEvent::nameSpace = "http://www.w3.org/2008/04/mmi-arch"; MMIEvent::Type MMIEvent::getType(Arabica::DOM::Node<std::string> node) { if (!node || node.getNodeType() != Arabica::DOM::Node_base::ELEMENT_NODE) return INVALID; // MMI container? if (boost::iequals(node.getLocalName(), "MMI")) { node = node.getFirstChild(); if (!node) return INVALID; while(node.getNodeType() != Arabica::DOM::Node_base::ELEMENT_NODE) { node = node.getNextSibling(); if (!node) return INVALID; } } if (boost::iequals(node.getLocalName(), "NEWCONTEXTREQUEST")) return NEWCONTEXTREQUEST; if (boost::iequals(node.getLocalName(), "NEWCONTEXTRESPONSE")) return NEWCONTEXTRESPONSE; if (boost::iequals(node.getLocalName(), "PREPAREREQUEST")) return PREPAREREQUEST; if (boost::iequals(node.getLocalName(), "PREPARERESPONSE")) return PREPARERESPONSE; if (boost::iequals(node.getLocalName(), "STARTREQUEST")) return STARTREQUEST; if (boost::iequals(node.getLocalName(), "STARTRESPONSE")) return STARTRESPONSE; if (boost::iequals(node.getLocalName(), "DONENOTIFICATION")) return DONENOTIFICATION; if (boost::iequals(node.getLocalName(), "CANCELREQUEST")) return CANCELREQUEST; if (boost::iequals(node.getLocalName(), "CANCELRESPONSE")) return CANCELRESPONSE; if (boost::iequals(node.getLocalName(), "PAUSEREQUEST")) return PAUSEREQUEST; if (boost::iequals(node.getLocalName(), "PAUSERESPONSE")) return PAUSERESPONSE; if (boost::iequals(node.getLocalName(), "RESUMEREQUEST")) return RESUMEREQUEST; if (boost::iequals(node.getLocalName(), "RESUMERESPONSE")) return RESUMERESPONSE; if (boost::iequals(node.getLocalName(), "EXTENSIONNOTIFICATION")) return EXTENSIONNOTIFICATION; if (boost::iequals(node.getLocalName(), "CLEARCONTEXTREQUEST")) return CLEARCONTEXTREQUEST; if (boost::iequals(node.getLocalName(), "CLEARCONTEXTRESPONSE")) return CLEARCONTEXTRESPONSE; if (boost::iequals(node.getLocalName(), "STATUSREQUEST")) return STATUSREQUEST; if (boost::iequals(node.getLocalName(), "STATUSRESPONSE")) return STATUSRESPONSE; return INVALID; } Arabica::DOM::Document<std::string> MMIEvent::toXML(bool encapsulateInMMI) const { Arabica::DOM::DOMImplementation<std::string> domFactory = Arabica::SimpleDOM::DOMImplementation<std::string>::getDOMImplementation(); Document<std::string> doc = domFactory.createDocument(nameSpace, "", 0); Element<std::string> msgElem = doc.createElementNS(nameSpace, tagName); msgElem.setAttributeNS(nameSpace, "Source", source); msgElem.setAttributeNS(nameSpace, "Target", target); msgElem.setAttributeNS(nameSpace, "RequestID", requestId); if (dataDOM) { Element<std::string> dataElem = doc.createElementNS(nameSpace, "Data"); Node<std::string> importNode = doc.importNode(dataDOM, true); dataElem.appendChild(importNode); msgElem.appendChild(dataElem); } else if (data.size() > 0) { Element<std::string> dataElem = doc.createElementNS(nameSpace, "Data"); Text<std::string> textElem = doc.createTextNode(data); dataElem.appendChild(textElem); msgElem.appendChild(dataElem); } if (encapsulateInMMI) { Element<std::string> mmiElem = doc.createElementNS(nameSpace, "mmi"); mmiElem.appendChild(msgElem); doc.appendChild(mmiElem); } else { doc.appendChild(msgElem); } return doc; } Arabica::DOM::Document<std::string> ContentRequest::toXML(bool encapsulateInMMI) const { Document<std::string> doc = ContextualizedRequest::toXML(encapsulateInMMI); FIND_MSG_ELEM(msgElem, doc); if (contentURL.href.size() > 0) { Element<std::string> contentURLElem = doc.createElementNS(nameSpace, "ContentURL"); contentURLElem.setAttributeNS(nameSpace, "href", contentURL.href); contentURLElem.setAttributeNS(nameSpace, "fetchtimeout", contentURL.fetchTimeout); contentURLElem.setAttributeNS(nameSpace, "max-age", contentURL.maxAge); msgElem.appendChild(contentURLElem); } else if (contentDOM) { Element<std::string> contentElem = doc.createElementNS(nameSpace, "Content"); Node<std::string> importNode = doc.importNode(contentDOM, true); contentElem.appendChild(importNode); msgElem.appendChild(contentElem); } else if (content.size() > 0) { Element<std::string> contentElem = doc.createElementNS(nameSpace, "Content"); Text<std::string> textElem = doc.createTextNode(content); contentElem.appendChild(textElem); msgElem.appendChild(contentElem); } return doc; } Arabica::DOM::Document<std::string> ContextualizedRequest::toXML(bool encapsulateInMMI) const { Document<std::string> doc = MMIEvent::toXML(encapsulateInMMI); FIND_MSG_ELEM(msgElem, doc); msgElem.setAttributeNS(nameSpace, "Context", context); return doc; } Arabica::DOM::Document<std::string> ExtensionNotification::toXML(bool encapsulateInMMI) const { Document<std::string> doc = ContextualizedRequest::toXML(encapsulateInMMI); FIND_MSG_ELEM(msgElem, doc); msgElem.setAttributeNS(nameSpace, "Name", name); return doc; } Arabica::DOM::Document<std::string> StatusResponse::toXML(bool encapsulateInMMI) const { Document<std::string> doc = ContextualizedRequest::toXML(encapsulateInMMI); FIND_MSG_ELEM(msgElem, doc); if (status == ALIVE) { msgElem.setAttributeNS(nameSpace, "Status", "alive"); } else if(status == DEAD) { msgElem.setAttributeNS(nameSpace, "Status", "dead"); } else if(status == FAILURE) { msgElem.setAttributeNS(nameSpace, "Status", "failure"); } else if(status == SUCCESS) { msgElem.setAttributeNS(nameSpace, "Status", "success"); } return doc; } Arabica::DOM::Document<std::string> StatusInfoResponse::toXML(bool encapsulateInMMI) const { Document<std::string> doc = StatusResponse::toXML(encapsulateInMMI); FIND_MSG_ELEM(msgElem, doc); Element<std::string> statusInfoElem = doc.createElementNS(nameSpace, "StatusInfo"); Text<std::string> statusInfoText = doc.createTextNode(statusInfo); statusInfoElem.appendChild(statusInfoText); msgElem.appendChild(statusInfoElem); return doc; } Arabica::DOM::Document<std::string> StatusRequest::toXML(bool encapsulateInMMI) const { Document<std::string> doc = ContextualizedRequest::toXML(encapsulateInMMI); FIND_MSG_ELEM(msgElem, doc); if (automaticUpdate) { msgElem.setAttributeNS(nameSpace, "RequestAutomaticUpdate", "true"); } else { msgElem.setAttributeNS(nameSpace, "RequestAutomaticUpdate", "false"); } return doc; } MMIEvent MMIEvent::fromXML(Arabica::DOM::Node<std::string> node, InterpreterImpl* interpreter) { MMIEvent msg; FIND_EVENT_NODE(node); Element<std::string> msgElem(node); msg.source = STRING_ATTR_OR_EXPR(msgElem, Source); msg.target = STRING_ATTR_OR_EXPR(msgElem, Target); msg.requestId = STRING_ATTR_OR_EXPR(msgElem, RequestID); msg.tagName = msgElem.getLocalName(); Element<std::string> dataElem; // search for data element node = msgElem.getFirstChild(); while (node) { if (node.getNodeType() == Node_base::ELEMENT_NODE) dataElem = Element<std::string>(node); if (dataElem && boost::iequals(dataElem.getLocalName(), "data")) break; node = node.getNextSibling(); } if (dataElem && boost::iequals(dataElem.getLocalName(), "data") && dataElem.getFirstChild()) { Arabica::DOM::Node<std::string> dataChild = dataElem.getFirstChild(); std::stringstream ss; while (dataChild) { if (dataChild.getNodeType() == Arabica::DOM::Node_base::ELEMENT_NODE) msg.dataDOM = dataChild; ss << dataChild; dataChild = dataChild.getNextSibling(); } msg.data = ss.str(); } return msg; } FROM_XML(NewContextRequest, NEWCONTEXTREQUEST, MMIEvent) FROM_XML(PauseRequest, PAUSEREQUEST, ContextualizedRequest) FROM_XML(ResumeRequest, RESUMEREQUEST, ContextualizedRequest) FROM_XML(ClearContextRequest, CLEARCONTEXTREQUEST, ContextualizedRequest) FROM_XML(CancelRequest, CANCELREQUEST, ContextualizedRequest) FROM_XML(PrepareRequest, PREPAREREQUEST, ContentRequest) FROM_XML(StartRequest, STARTREQUEST, ContentRequest) FROM_XML(PrepareResponse, PREPARERESPONSE, StatusInfoResponse) FROM_XML(StartResponse, STARTRESPONSE, StatusInfoResponse) FROM_XML(CancelResponse, CANCELRESPONSE, StatusInfoResponse) FROM_XML(PauseResponse, PAUSERESPONSE, StatusInfoResponse) FROM_XML(ResumeResponse, RESUMERESPONSE, StatusInfoResponse) FROM_XML(ClearContextResponse, CLEARCONTEXTRESPONSE, StatusInfoResponse) FROM_XML(NewContextResponse, NEWCONTEXTRESPONSE, StatusInfoResponse) FROM_XML(DoneNotification, DONENOTIFICATION, StatusInfoResponse) ContextualizedRequest ContextualizedRequest::fromXML(Arabica::DOM::Node<std::string> node, InterpreterImpl* interpreter) { ContextualizedRequest msg(MMIEvent::fromXML(node, interpreter)); FIND_EVENT_NODE(node); Element<std::string> msgElem(node); msg.context = STRING_ATTR_OR_EXPR(msgElem, Context); return msg; } ExtensionNotification ExtensionNotification::fromXML(Arabica::DOM::Node<std::string> node, InterpreterImpl* interpreter) { ExtensionNotification msg(ContextualizedRequest::fromXML(node, interpreter)); FIND_EVENT_NODE(node); Element<std::string> msgElem(node); msg.name = STRING_ATTR_OR_EXPR(msgElem, Name); msg.type = EXTENSIONNOTIFICATION; return msg; } ContentRequest ContentRequest::fromXML(Arabica::DOM::Node<std::string> node, InterpreterImpl* interpreter) { ContentRequest msg(ContextualizedRequest::fromXML(node, interpreter)); FIND_EVENT_NODE(node); Element<std::string> msgElem(node); Element<std::string> contentElem; node = msgElem.getFirstChild(); while (node) { if (node.getNodeType() == Node_base::ELEMENT_NODE) { contentElem = Element<std::string>(node); if (boost::iequals(contentElem.getLocalName(), "content") || boost::iequals(contentElem.getLocalName(), "contentURL")) break; } node = node.getNextSibling(); } if (contentElem) { if(boost::iequals(contentElem.getLocalName(), "content")) { Arabica::DOM::Node<std::string> contentChild = contentElem.getFirstChild(); std::stringstream ss; while (contentChild) { if (contentChild.getNodeType() == Arabica::DOM::Node_base::ELEMENT_NODE) msg.contentDOM = contentChild; ss << contentChild; contentChild = contentChild.getNextSibling(); } msg.content = ss.str(); } else if(boost::iequals(contentElem.getLocalName(), "contentURL")) { msg.contentURL.href = STRING_ATTR_OR_EXPR(contentElem, href); msg.contentURL.maxAge = STRING_ATTR_OR_EXPR(contentElem, max-age); msg.contentURL.fetchTimeout = STRING_ATTR_OR_EXPR(contentElem, fetchtimeout); } } //msg.content = msgElem.getAttributeNS(nameSpace, "Context"); return msg; } StatusResponse StatusResponse::fromXML(Arabica::DOM::Node<std::string> node, InterpreterImpl* interpreter) { StatusResponse msg(ContextualizedRequest::fromXML(node, interpreter)); FIND_EVENT_NODE(node); Element<std::string> msgElem(node); std::string status = STRING_ATTR_OR_EXPR(msgElem, Status); if (boost::iequals(status, "ALIVE")) { msg.status = ALIVE; } else if(boost::iequals(status, "DEAD")) { msg.status = DEAD; } else if(boost::iequals(status, "FAILURE")) { msg.status = FAILURE; } else if(boost::iequals(status, "SUCCESS")) { msg.status = SUCCESS; } else { msg.status = INVALID; } msg.type = STATUSRESPONSE; return msg; } StatusInfoResponse StatusInfoResponse::fromXML(Arabica::DOM::Node<std::string> node, InterpreterImpl* interpreter) { StatusInfoResponse msg(StatusResponse::fromXML(node, interpreter)); FIND_EVENT_NODE(node); Element<std::string> msgElem(node); Element<std::string> statusInfoElem; node = msgElem.getFirstChild(); while (node) { if (node.getNodeType() == Node_base::ELEMENT_NODE) { statusInfoElem = Element<std::string>(node); if (statusInfoElem && boost::iequals(statusInfoElem.getLocalName(), "statusInfo")) break; } node = node.getNextSibling(); } if (statusInfoElem && boost::iequals(statusInfoElem.getLocalName(), "statusInfo")) { node = statusInfoElem.getFirstChild(); while (node) { if (node.getNodeType() == Node_base::TEXT_NODE) { msg.statusInfo = node.getNodeValue(); break; } node = node.getNextSibling(); } } return msg; } StatusRequest StatusRequest::fromXML(Arabica::DOM::Node<std::string> node, InterpreterImpl* interpreter) { StatusRequest msg(ContextualizedRequest::fromXML(node, interpreter)); FIND_EVENT_NODE(node); Element<std::string> msgElem(node); std::string autoUpdate = STRING_ATTR_OR_EXPR(msgElem, RequestAutomaticUpdate); if (boost::iequals(autoUpdate, "true")) { msg.automaticUpdate = true; } else if(boost::iequals(autoUpdate, "on")) { msg.automaticUpdate = true; } else if(boost::iequals(autoUpdate, "yes")) { msg.automaticUpdate = true; } else if(boost::iequals(autoUpdate, "1")) { msg.automaticUpdate = true; } else { msg.automaticUpdate = false; } msg.type = STATUSREQUEST; return msg; } #ifdef MMI_WITH_OPERATOR_EVENT TO_EVENT_OPERATOR(NewContextRequest, "mmi.request.newcontext", MMIEvent); TO_EVENT_OPERATOR(PauseRequest, "mmi.request.pause", ContextualizedRequest); TO_EVENT_OPERATOR(ResumeRequest, "mmi.request.resume", ContextualizedRequest); TO_EVENT_OPERATOR(CancelRequest, "mmi.request.cancel", ContextualizedRequest); TO_EVENT_OPERATOR(ClearContextRequest, "mmi.request.clearcontext", ContextualizedRequest); TO_EVENT_OPERATOR(StatusRequest, "mmi.request.status", ContextualizedRequest); TO_EVENT_OPERATOR(PrepareRequest, "mmi.request.prepare", ContentRequest); TO_EVENT_OPERATOR(StartRequest, "mmi.request.start", ContentRequest); TO_EVENT_OPERATOR(PrepareResponse, "mmi.response.prepare", StatusInfoResponse); TO_EVENT_OPERATOR(StartResponse, "mmi.response.start", StatusInfoResponse); TO_EVENT_OPERATOR(CancelResponse, "mmi.response.cancel", StatusInfoResponse); TO_EVENT_OPERATOR(PauseResponse, "mmi.response.pause", StatusInfoResponse); TO_EVENT_OPERATOR(ResumeResponse, "mmi.response.resume", StatusInfoResponse); TO_EVENT_OPERATOR(ClearContextResponse, "mmi.response.clearcontext", StatusInfoResponse); TO_EVENT_OPERATOR(NewContextResponse, "mmi.response.newcontext", StatusInfoResponse); TO_EVENT_OPERATOR(DoneNotification, "mmi.notification.done", StatusInfoResponse); MMIEvent::operator Event() const { Event ev; ev.setOriginType("mmi.event"); ev.setOrigin(source); if (representation == MMI_AS_DATA) { if (dataDOM) { ev.data.node = dataDOM; } else { ev.data = Data::fromJSON(data); if (ev.data.empty()) { ev.content = data; } } } return ev; } ContextualizedRequest::operator Event() const { Event ev = MMIEvent::operator Event(); // do we want to represent the context? It's the interpreters name already return ev; } ExtensionNotification::operator Event() const { Event ev = ContextualizedRequest::operator Event(); if (name.length() > 0) { ev.setName(name); } else { ev.setName("mmi.notification.extension"); } return ev; } ContentRequest::operator Event() const { Event ev = ContextualizedRequest::operator Event(); if (representation == MMI_AS_DATA) { if (content.length() > 0) ev.data.compound["content"] = Data(content, Data::VERBATIM); if (contentURL.fetchTimeout.length() > 0) ev.data.compound["contentURL"].compound["fetchTimeout"] = Data(contentURL.fetchTimeout, Data::VERBATIM); if (contentURL.href.length() > 0) ev.data.compound["contentURL"].compound["href"] = Data(contentURL.href, Data::VERBATIM); if (contentURL.maxAge.length() > 0) ev.data.compound["contentURL"].compound["maxAge"] = Data(contentURL.maxAge, Data::VERBATIM); } return ev; } StatusResponse::operator Event() const { Event ev = ContextualizedRequest::operator Event(); ev.setName("mmi.response.status"); if (representation == MMI_AS_DATA) { switch (status) { case ALIVE: ev.data.compound["status"] = Data("alive", Data::VERBATIM); break; case DEAD: ev.data.compound["status"] = Data("dead", Data::VERBATIM); break; case SUCCESS: ev.data.compound["status"] = Data("success", Data::VERBATIM); break; case FAILURE: ev.data.compound["status"] = Data("failure", Data::VERBATIM); break; default: ev.data.compound["status"] = Data("invalid", Data::VERBATIM); } } else { ev.dom = toXML(); } return ev; } #endif }
[ "radomski@tk.informatik.tu-darmstadt.de" ]
radomski@tk.informatik.tu-darmstadt.de
b4c5fffc627e73f3115b63c4b310e5799138cf08
a3fb0091facc6f33be957eba61d7281737aa258e
/ATMView/ATMView/Business/CameraReader.cpp
feae74b7ce8f8a93f6522a569b0e9b1e8a3b10a8
[]
no_license
barry-ran/AEyeAboutPro
b5c7b46c8145423d7456e1ef6d40d82c54ba2faf
830de73c48af1cd1a2d72ff6485e31f7b7d52d45
refs/heads/master
2022-01-18T03:01:44.502618
2019-09-02T03:52:27
2019-09-02T03:52:27
null
0
0
null
null
null
null
GB18030
C++
false
false
3,801
cpp
/*********************************************************************************** * CameraReader.cpp * * Copyright(C): 智慧眼科技股份有限公司 * * Author: YCL * * Date: 2019-06 * * Description: 用于摄像头初始化、打开、设置、采集 ***********************************************************************************/ #include "CameraReader.h" #include "GlogManager.h" #include "ThreadManager.h" CameraReader* CameraReader::m_pInstance = NULL; CameraReader::CameraReader(QObject *parent) : QObject(parent) { moveToThread(ThreadManager::getAgentThread()); ThreadManager::getAgentThread()->start(); } CameraReader::~CameraReader() { } CameraReader* CameraReader::instance() { if (m_pInstance == NULL) { m_pInstance = new CameraReader; } return m_pInstance; } void _stdcall CameraReader::faceCallback( int msgType, const char* msg, void* userData ) { CameraReader* pThis = (CameraReader*)userData; CameraData cameraData; QString msgData = QString::fromLocal8Bit(msg); ParserMsg(msgData, cameraData); switch (msgType) { case STATUS_CHANGED: pThis->emit onMsgReceived(cameraData.subId, cameraData.desMsg); break; case COLLECT_FINISHED: if (cameraData.subId == 0) { pThis->emit onCollectFinished(cameraData); } else { pThis->emit onMsgReceived(cameraData.subId, cameraData.desMsg); } break; } } bool CameraReader::InitSDK(WId winId) { //初始化 int ret = AEFaceColl_Init(&m_collHandle); if (ret != 0) { LOG(INFO)<<"初始化相机SDK失败!!!"; return false; } LOG(INFO)<<"初始化相机SDK成功!!!"; //设置回调 AEFaceColl_SetCallback(m_collHandle, faceCallback, this); //设置预览窗口 AEFaceColl_SetPreviewWindow(m_collHandle, (void*)winId); //设置参数 char params[] = "{\"scenario\":10, \"capture.imageNumber\":1, \"capture.timeout\":30}"; AEFaceColl_SetParameters(m_collHandle, params); return true; } bool CameraReader::openCamera() { if (openCameraModule(0)) { openCameraModule(1); return true; } return false; } bool CameraReader::openCameraModule( int cameraType ) { QString cameraText = (cameraType == 0) ? QStringLiteral("可见光") : QStringLiteral("近红外"); int ret = AEFaceColl_OpenCamera(m_collHandle, cameraType); if (ret != 0) { LOG(INFO)<<"打开"<<cameraText.toLocal8Bit().data()<<"相机失败!!!"; return false; } LOG(INFO)<<"打开"<<cameraText.toLocal8Bit().data()<<"相机成功!!!"; return true; } void CameraReader::closeCamera() { int ret = AEFaceColl_CloseCamera(m_collHandle); if (ret != 0) { emit onMsgReceived(-1, QStringLiteral("关闭摄像头失败")); return; } } void CameraReader::startCollect() { int ret = AEFaceColl_StartCollect(m_collHandle); if (ret != 0) { emit onMsgReceived(-1, QStringLiteral("图像采集失败")); return; } } void CameraReader::ParserMsg( QString msgJson, CameraData& cameraData ) { QScriptEngine engine; QScriptValue sc = engine.evaluate("value=" + msgJson); cameraData.subId = sc.property("subId").toInt32(); cameraData.desMsg = sc.property("description").toString(); if (sc.property("visImageDatas").isArray()) { QScriptValueIterator it(sc.property("visImageDatas")); while (it.hasNext()) { it.next(); CameraData::ImageData imageData; imageData.imageData = it.value().property("image").toString(); QFile file("d:\\test.jpeg"); file.open(QIODevice::ReadWrite | QIODevice::Append); file.write(imageData.imageData.toLocal8Bit(), imageData.imageData.length()); file.waitForBytesWritten(3000); file.flush(); file.close(); if (imageData.imageData.isEmpty()) { continue; } imageData.faceRect = it.value().property("faceRect").toString(); cameraData.imageInfoData.append(imageData); } } }
[ "ycldream815@gmail.com" ]
ycldream815@gmail.com
1de9ef5dcb8c8c43a4263bb59f4ff89c9f384fa0
ba34acc11d45cf644d7ce462c5694ce9662c34c2
/Classes/geometry/recognizer/GeometricRecognizerNode.h
3028df38c0157db3078645fbfef72c495c46046e
[]
no_license
mspenn/Sketch2D
acce625c4631313ba2ef47a5c8f8eadcd332719b
ae7d9f00814ac68fbd8e3fcb39dfac34edfc9883
refs/heads/master
2021-01-12T13:26:35.864853
2019-01-09T12:45:11
2019-01-09T12:45:11
69,162,221
8
7
null
null
null
null
UTF-8
C++
false
false
2,980
h
#ifndef __GEOMETRIC_RECOGNIZER_NODE_H__ #define __GEOMETRIC_RECOGNIZER_NODE_H__ #include "cocos2d.h" #include "gesture\GeometricRecognizer.h" // event #define EVENT_LOADING_TEMPLATE "onLoadingTemplate" #define EVENT_LOADED_TEMPLATE "onLoadedTemplate" /** * Load Template Data for Update Feedback Event */ struct LoadTemplateData { // Constructor LoadTemplateData(int progress, const std::string& hint) { _progress = progress; _hint = hint; } int _progress; // current progress volunm std::string _hint; // hint content/message }; /** * Geometric Recognizer Node * It can be attached to a game scene, and used everywhere in the scene * @see cocos2d::Node */ class GeometricRecognizerNode :public cocos2d::Node { public: /** * Call when Geometric Recognizer Node is initialized, override * @see cocos2d::Node::init * @return true if initialize successfully, false otherwise */ virtual bool init(); /** * Load template as multiply stroke * @param name template name * @param path template path in file system * @param multiStrokeGesture a empty MultiStrokeGesture object * will be fill in template data after call * @return reference to a existing MultiStrokeGesture object */ DollarRecognizer::MultiStrokeGesture& loadTemplate( std::string name, const char* path, DollarRecognizer::MultiStrokeGesture& multiStrokeGesture); /** * Store multiply stroke as template file * @param multiStrokeGesture a reference to existing MultiStrokeGesture object * @param path template path in file system */ void storeAsTemplate( const DollarRecognizer::MultiStrokeGesture& multiStrokeGesture, const char* path); /** * Get GeometricRecognizer object * @return pointer to GeometricRecognizer instance */ inline DollarRecognizer::GeometricRecognizer* getGeometricRecognizer() { return &_geometricRecognizer; } /** * Scan Gesture Samples by specified gesture name * @param gestureName specified gesture name, such as Cycle, Rectangle, etc * @param multiStrokeGesture a empty MultiStrokeGesture object to store data * @param mgestureList sample file detail names, such as Cycle::1, Cycle::2, etc */ void scanGestureSamples( const string& gestureName, DollarRecognizer::MultiStrokeGesture& multiStrokeGesture, vector<string>& mgestureList); /** * Feedback loading template progress * send EVENT_LOADING_TEMPLATE event */ void loadProgressFeedBack(); /** * Feedback when loading progress is active * send EVENT_LOADING_TEMPLATE event */ void loadProgressActiveFeedBack(); /** * Feedback when loading progress is done * send EVENT_LOADED_TEMPLATE event */ void loadProgressDoneFeedBack(); /** * Static factory to create GeometricRecognizerNode object */ CREATE_FUNC(GeometricRecognizerNode); private: DollarRecognizer::GeometricRecognizer _geometricRecognizer; // dollar recognizer instance }; #endif /* __GEOMETRIC_RECOGNIZER_NODE_H__ */
[ "microsmadio@hotmail.com" ]
microsmadio@hotmail.com
eeec16e423dba54c128128d875387601b6b39188
6c78ebd8f7a91957f84e260bf4640e76b8d665e7
/src/threading/WindowsThread.cpp
45dde2fb69e46ff5d3a9573a11d524049d861332
[ "MIT" ]
permissive
TheCoderRaman/nCine
b74728783e34151b4276e2fb303d605602ca78ba
a35f9898cc754a9c1f3c82d8e505160571cb4cf6
refs/heads/master
2023-08-28T14:57:43.613194
2019-05-30T19:16:32
2019-06-14T16:31:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,843
cpp
#include "common_macros.h" #include "Thread.h" namespace ncine { /////////////////////////////////////////////////////////// // PUBLIC FUNCTIONS /////////////////////////////////////////////////////////// void ThreadAffinityMask::zero() { affinityMask_ = 0LL; } void ThreadAffinityMask::set(int cpuNum) { affinityMask_ |= 1LL << cpuNum; } void ThreadAffinityMask::clear(int cpuNum) { affinityMask_ &= ~(1LL << cpuNum); } bool ThreadAffinityMask::isSet(int cpuNum) { return ((affinityMask_ >> cpuNum) & 1LL) != 0; } /////////////////////////////////////////////////////////// // CONSTRUCTORS and DESTRUCTOR /////////////////////////////////////////////////////////// Thread::Thread() : handle_(0) { } Thread::Thread(ThreadFunctionPtr startFunction, void *arg) : handle_(0) { run(startFunction, arg); } /////////////////////////////////////////////////////////// // PUBLIC FUNCTIONS /////////////////////////////////////////////////////////// unsigned int Thread::numProcessors() { unsigned int numProcs = 0; SYSTEM_INFO si; GetSystemInfo(&si); numProcs = si.dwNumberOfProcessors; return numProcs; } void Thread::run(ThreadFunctionPtr startFunction, void *arg) { if (handle_ == 0) { threadInfo_.startFunction = startFunction; threadInfo_.threadArg = arg; handle_ = reinterpret_cast<HANDLE>(_beginthreadex(nullptr, 0, wrapperFunction, &threadInfo_, 0, nullptr)); FATAL_ASSERT_MSG(handle_, "Error in _beginthreadex()"); } else LOGW_X("Thread %u is already running", handle_); } void *Thread::join() { WaitForSingleObject(handle_, INFINITE); return nullptr; } long int Thread::self() { return GetCurrentThreadId(); } void Thread::exit(void *retVal) { _endthreadex(0); *static_cast<unsigned int *>(retVal) = 0; } void Thread::yieldExecution() { Sleep(0); } void Thread::cancel() { TerminateThread(handle_, 0); } ThreadAffinityMask Thread::affinityMask() const { ThreadAffinityMask affinityMask; if (handle_ != 0) { // A neutral value for the temporary mask DWORD_PTR allCpus = ~(allCpus & 0); affinityMask.affinityMask_ = SetThreadAffinityMask(handle_, allCpus); SetThreadAffinityMask(handle_, affinityMask.affinityMask_); } else LOGW("Cannot get the affinity for a thread that has not been created yet"); return affinityMask; } void Thread::setAffinityMask(ThreadAffinityMask affinityMask) { if (handle_ != 0) SetThreadAffinityMask(handle_, affinityMask.affinityMask_); else LOGW("Cannot set the affinity mask for a not yet created thread"); } /////////////////////////////////////////////////////////// // PRIVATE FUNCTIONS /////////////////////////////////////////////////////////// unsigned int Thread::wrapperFunction(void *arg) { ThreadInfo *threadInfo = static_cast<ThreadInfo *>(arg); threadInfo->startFunction(threadInfo->threadArg); return 0; } }
[ "encelo@gmail.com" ]
encelo@gmail.com
6cb5c10f324394fef04691711c46dd16709d5123
c7e65a70caf87041afd27441fe45eac85e8cd1e4
/apps/coreir_examples/conv_bw_valid/pipeline.cpp
d686745a8ab708ae8328047c43e4358c65053328
[ "MIT" ]
permissive
jeffsetter/Halide_CoreIR
adb8d9c4bc91b11d55e07a67e86643a0515e0ee6
f2f5307f423a6040beb25a1f63a8f7ae8a93d108
refs/heads/master
2020-05-23T18:06:27.007413
2018-10-02T22:09:02
2018-10-02T22:09:02
84,777,366
7
1
NOASSERTION
2018-11-05T15:05:11
2017-03-13T02:50:55
C++
UTF-8
C++
false
false
4,233
cpp
#include "Halide.h" #include <string.h> using namespace Halide; using std::string; Var x("x"), y("y"); Var xo("xo"), xi("xi"), yi("yi"), yo("yo"); class MyPipeline { public: ImageParam input; Param<uint16_t> bias; Func kernel; Func clamped; Func conv1; Func output; Func hw_output; std::vector<Argument> args; RDom win; MyPipeline() : input(UInt(8), 2, "input"), bias("bias"), kernel("kernel"), conv1("conv1"), output("output"), hw_output("hw_output"), win(0, 3, 0, 3) { // Define the kernel kernel(x,y) = 0; kernel(0,0) = 11; kernel(0,1) = 12; kernel(0,2) = 13; kernel(1,0) = 14; kernel(1,1) = 0; kernel(1,2) = 16; kernel(2,0) = 17; kernel(2,1) = 18; kernel(2,2) = 19; // define the algorithm clamped(x,y) = input(x,y); conv1(x, y) += clamped(x+win.x, y+win.y) * kernel(win.x, win.y); // unroll the reduction conv1.update(0).unroll(win.x).unroll(win.y); hw_output(x,y) = cast<uint8_t>(conv1(x,y)); output(x, y) = hw_output(x, y); args.push_back(input); args.push_back(bias); } void compile_cpu() { std::cout << "\ncompiling cpu code..." << std::endl; output.tile(x, y, xo, yo, xi, yi, 62,62); output.fuse(xo, yo, xo).parallel(xo); output.vectorize(xi, 8); conv1.compute_at(output, xo).vectorize(x, 8); //output.print_loop_nest(); output.compile_to_lowered_stmt("pipeline_native.ir.html", args, HTML); output.compile_to_header("pipeline_native.h", args, "pipeline_native"); output.compile_to_object("pipeline_native.o", args, "pipeline_native"); } void compile_gpu() { std::cout << "\ncompiling gpu code..." << std::endl; output.compute_root().reorder(x, y).gpu_tile(x, y, 16, 16); conv1.compute_root().reorder(x, y).gpu_tile(x, y, 16, 16); //conv1.compute_at(output, Var::gpu_blocks()).gpu_threads(x, y); //output.print_loop_nest(); Target target = get_target_from_environment(); target.set_feature(Target::CUDA); output.compile_to_lowered_stmt("pipeline_cuda.ir.html", args, HTML, target); output.compile_to_header("pipeline_cuda.h", args, "pipeline_cuda", target); output.compile_to_object("pipeline_cuda.o", args, "pipeline_cuda", target); } void compile_hls() { std::cout << "\ncompiling HLS code..." << std::endl; clamped.compute_root(); // prepare the input for the whole image // HLS schedule: make a hw pipeline producing 'hw_output', taking // inputs of 'clamped', buffering intermediates at (output, xo) loop // level hw_output.compute_root(); //hw_output.tile(x, y, xo, yo, xi, yi, 1920, 1080).reorder(xi, yi, xo, yo); hw_output.tile(x, y, xo, yo, xi, yi, 62,62).reorder(xi, yi, xo, yo); //hw_output.unroll(xi, 2); hw_output.accelerate({clamped}, xi, xo, {}); // define the inputs and the output conv1.linebuffer(); // conv1.unroll(x).unroll(y); output.print_loop_nest(); Target hls_target = get_target_from_environment(); hls_target.set_feature(Target::CPlusPlusMangling); output.compile_to_lowered_stmt("pipeline_hls.ir.html", args, HTML, hls_target); output.compile_to_hls("pipeline_hls.cpp", args, "pipeline_hls", hls_target); output.compile_to_header("pipeline_hls.h", args, "pipeline_hls", hls_target); } void compile_coreir() { std::cout << "\ncompiling CoreIR code..." << std::endl; clamped.compute_root(); hw_output.compute_root(); conv1.linebuffer(); hw_output.tile(x, y, xo, yo, xi, yi, 62,62).reorder(xi,yi,xo,yo); hw_output.accelerate({clamped}, xi, xo, {}); Target coreir_target = get_target_from_environment(); coreir_target.set_feature(Target::CPlusPlusMangling); coreir_target.set_feature(Target::CoreIRValid); output.compile_to_lowered_stmt("pipeline_coreir.ir.html", args, HTML, coreir_target); output.compile_to_coreir("pipeline_coreir.cpp", args, "pipeline_coreir", coreir_target); } }; int main(int argc, char **argv) { MyPipeline p1; p1.compile_cpu(); MyPipeline p2; p2.compile_hls(); MyPipeline p4; p4.compile_coreir(); // MyPipeline p3; //p3.compile_gpu(); return 0; }
[ "setter@stanford.edu" ]
setter@stanford.edu
96e02b98864cd843b05390a05f3981034c584682
3ee0d3519f444e8ac3dd8c4731c9bbe751dd7595
/FrameData/Shader.h
aa051b160fdd17249ad87ae79c6469ba788ef4bf
[ "MIT" ]
permissive
ousttrue/FunnelPipe
77f4941fde22353eea2c1e51a1b891e69cc4572f
380b52a7d41b4128b287ec02280bb703ed6b5d66
refs/heads/master
2023-08-23T08:40:56.895419
2021-09-08T12:57:41
2021-09-08T12:57:41
250,489,380
0
0
null
null
null
null
UTF-8
C++
false
false
2,914
h
#pragma once #include <wrl/client.h> #include <d3dcompiler.h> #include <string> #include <vector> #include <memory> #include <span> #include "ShaderConstantVariable.h" namespace framedata { class Shader { protected: template <typename T> using ComPtr = Microsoft::WRL::ComPtr<T>; Shader(const Shader &) = delete; Shader &operator=(const Shader &) = delete; std::string m_name; ComPtr<ID3DBlob> m_compiled; std::vector<ConstantBuffer> m_cblist; void GetConstants(const ComPtr<ID3D12ShaderReflection> &pReflection, const std::string &source); public: Shader(const std::string &name) : m_name(name) {} const std::string &Name() const { return m_name; } virtual bool Compile(const std::string &source, const std::string &entrypoint, const D3D_SHADER_MACRO *define) = 0; std::tuple<LPVOID, UINT> ByteCode() const { return std::make_pair(m_compiled->GetBufferPointer(), static_cast<UINT>(m_compiled->GetBufferSize())); } // register(b0), register(b1), register(b2)... const ConstantBuffer *CB(int reg) const { for (auto &cb : m_cblist) { if (cb.reg == reg) { return &cb; } } return nullptr; } }; using ShaderPtr = std::shared_ptr<Shader>; class PixelShader : public Shader { public: using Shader::Shader; bool Compile(const std::string &source, const std::string &entrypoint, const D3D_SHADER_MACRO *define) override; }; using PixelShaderPtr = std::shared_ptr<PixelShader>; class VertexShader : public Shader { template <typename T> using ComPtr = Microsoft::WRL::ComPtr<T>; // keep semantic strings enum INPUT_CLASSIFICATION { INPUT_CLASSIFICATION_PER_VERTEX_DATA = 0, INPUT_CLASSIFICATION_PER_INSTANCE_DATA = 1 }; struct InputLayoutElement { LPCSTR SemanticName; UINT SemanticIndex; DXGI_FORMAT Format; UINT InputSlot; UINT AlignedByteOffset; INPUT_CLASSIFICATION InputSlotClass; UINT InstanceDataStepRate; }; std::vector<std::string> m_semantics; std::vector<InputLayoutElement> m_layout; bool InputLayoutFromReflection(const ComPtr<ID3D12ShaderReflection> &reflection); public: using Shader::Shader; bool Compile(const std::string &source, const std::string &entrypoint, const D3D_SHADER_MACRO *define) override; // same with D3D11_INPUT_ELEMENT_DESC or D3D12_INPUT_ELEMENT_DESC std::span<const InputLayoutElement> InputLayout() const { return m_layout; } }; using VertexShaderPtr = std::shared_ptr<VertexShader>; } // namespace framedata
[ "ousttrue@gmail.com" ]
ousttrue@gmail.com
fb7f8a2e574eb401570d5b2ae62bd318d8dbd84a
4f460d4984c9e934978bbc89eb10654fa3b618a8
/WifiWebServer/WifiWebServer.ino
5834dbd2c8baa0ac329b814e0f3292e7afe81bc3
[]
no_license
davidaronson13/PowerBiker
eaea512bc690801d4fbe050bd731eaab8445349d
3757549a823981b980a7817008cee68d5b86b03d
refs/heads/master
2020-03-31T00:57:05.928520
2014-05-27T14:56:22
2014-05-27T14:56:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,119
ino
/* WiFi Web Server A simple web server that shows the value of the analog input pins. using a WiFi shield. This example is written for a network using WPA encryption. For WEP or WPA, change the Wifi.begin() call accordingly. Circuit: * WiFi shield attached * Analog inputs attached to pins A0 through A5 (optional) created 13 July 2010 by dlf (Metodo2 srl) modified 31 May 2012 by Tom Igoe */ #include <SPI.h> #include <WiFi.h> char ssid[] = "bikeMind"; // your network SSID (name) char pass[] = "secretPassword"; // your network password int keyIndex = 0; // your network key Index number (needed only for WEP) int status = WL_IDLE_STATUS; WiFiServer server(80); void setup() { //Initialize serial and wait for port to open: Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for Leonardo only } // check for the presence of the shield: if (WiFi.status() == WL_NO_SHIELD) { Serial.println("WiFi shield not present"); // don't continue: while(true); } // attempt to connect to Wifi network: while ( status != WL_CONNECTED) { Serial.print("Attempting to connect to SSID: "); Serial.println(ssid); // Connect to WPA/WPA2 network. Change this line if using open or WEP network: status = WiFi.begin(ssid); // wait 10 seconds for connection: delay(10000); } server.begin(); // you're connected now, so print out the status: printWifiStatus(); } void loop() { // listen for incoming clients WiFiClient client = server.available(); if (client) { Serial.println("new client"); // an http request ends with a blank line boolean currentLineIsBlank = true; while (client.connected()) { if (client.available()) { char c = client.read(); Serial.write(c); // if you've gotten to the end of the line (received a newline // character) and the line is blank, the http request has ended, // so you can send a reply if (c == '\n' && currentLineIsBlank) { // send a standard http response header client.println("HTTP/1.1 200 OK"); client.println("Content-Type: text/html"); client.println("Connection: close"); client.println(); client.println("<!DOCTYPE HTML>"); client.println("<html>"); // add a meta refresh tag, so the browser pulls again every 5 seconds: client.println("<meta http-equiv=\"refresh\" content=\"5\">"); //add meta for full screen client.println("<meta name=\"apple-mobile-web-app-capable\" content=\"yes\">"); client.println("<body style=\"background-color:#000; font-size:64px;color:#0F0; \">"); // output the value of each analog input pin for (int analogChannel = 0; analogChannel < 6; analogChannel++) { int sensorReading = analogRead(analogChannel); client.print("analog input "); client.print(analogChannel); client.print(" is "); client.print(sensorReading); client.println("<br />"); } client.println("</body></html>"); break; } if (c == '\n') { // you're starting a new line currentLineIsBlank = true; } else if (c != '\r') { // you've gotten a character on the current line currentLineIsBlank = false; } } } // give the web browser time to receive the data delay(1); // close the connection: client.stop(); Serial.println("client disonnected"); } } void printWifiStatus() { // print the SSID of the network you're attached to: Serial.print("SSID: "); Serial.println(WiFi.SSID()); // print your WiFi shield's IP address: IPAddress ip = WiFi.localIP(); Serial.print("IP Address: "); Serial.println(ip); // print the received signal strength: long rssi = WiFi.RSSI(); Serial.print("signal strength (RSSI):"); Serial.print(rssi); Serial.println(" dBm"); }
[ "davidaronson13@gmail.com" ]
davidaronson13@gmail.com
803302ab96bf04ea0b55a8ff90a18dbb73c20a72
8b552e2a83aefe6546a8d492b101cea675c05a63
/assignment9(glut)/parser.h
14724c75ce7bd9a915f78faab22c7dacce22237e
[]
no_license
Dream4Leo/6.837-MIT04Fall-Assignments
4d1c416f452286282b8922b2ee3afdc7176ae72a
68f945b2f0be83d367b053f4c128c7c74d5ffed8
refs/heads/master
2020-06-16T22:07:28.352960
2019-10-05T02:40:49
2019-10-05T02:40:49
195,717,287
1
0
null
null
null
null
UTF-8
C++
false
false
9,279
h
#ifndef _PARSER_H_ #define _PARSER_H_ #include <assert.h> #include "vectors.h" #include "system.h" #include "generator.h" #include "integrator.h" #include "forcefield.h" // ==================================================================== // ==================================================================== #define MAX_PARSER_TOKEN_LENGTH 100 class System; class Generator; class Integrator; class ForceField; // ==================================================================== // ==================================================================== // parse the particle system file class Parser { public: // CONSTRUCTOR & DESTRUCTOR Parser(const char *file); ~Parser(); // ACCESSORS int getNumSystems() { return num_systems; } System* getSystem(int i) { assert (i >= 0 && i < num_systems); return systems[i]; } private: // don't use this constructor Parser() { assert(0); } // HELPER FUNCTIONS System* ParseSystem(); Generator* ParseGenerator(); Integrator* ParseIntegrator(); ForceField* ParseForceField(); // UTILITY FUNCTIONS int getToken(char token[MAX_PARSER_TOKEN_LENGTH]); Vec3f readVec3f(); Vec2f readVec2f(); float readFloat(); int readInt(); // REPRESENTATION int num_systems; System **systems; FILE *file; }; // ==================================================================== // ==================================================================== Parser::Parser(const char *filename) { // open the file for reading assert (filename != NULL); file = fopen(filename,"r"); assert (file != NULL); char token[MAX_PARSER_TOKEN_LENGTH]; // read in the number of particles in this file getToken(token); assert (!strcmp(token,"num_systems")); num_systems = readInt(); systems = new (System*)[num_systems]; // read the systems for (int i = 0; i < num_systems; i++) { System *s = ParseSystem(); assert (s != NULL); systems[i] = s; } fclose(file); } Parser::~Parser() { // cleanup for (int i = 0; i < num_systems; i++) { delete systems[i]; } delete [] systems; } // ==================================================================== System* Parser::ParseSystem() { char token[MAX_PARSER_TOKEN_LENGTH]; getToken(token); assert (!strcmp(token,"system")); Generator *generator = ParseGenerator(); Integrator *integrator = ParseIntegrator(); ForceField *forcefield = ParseForceField(); return new System(generator, integrator, forcefield); } // ==================================================================== // ==================================================================== // ==================================================================== Generator* Parser::ParseGenerator() { // read the generator type char type[MAX_PARSER_TOKEN_LENGTH]; getToken(type); // generator variable defaults Vec3f position = Vec3f(0,0,0); float position_randomness = 0; Vec3f velocity = Vec3f(0,0,0); float velocity_randomness = 0; Vec3f color = Vec3f(1,1,1); Vec3f dead_color = Vec3f(1,1,1); float color_randomness = 0; float mass = 1; float mass_randomness = 0; float lifespan = 10; float lifespan_randomness = 0; int desired_num_particles = 1000; int grid = 10; float ring_velocity = 1; // read the provided values char token[MAX_PARSER_TOKEN_LENGTH]; getToken(token); assert (!strcmp(token,"{")); while (1) { getToken(token); if (!strcmp(token,"position")) { position = readVec3f(); } else if (!strcmp(token,"position_randomness")) { position_randomness = readFloat(); } else if (!strcmp(token,"velocity")) { velocity = readVec3f(); } else if (!strcmp(token,"velocity_randomness")) { velocity_randomness = readFloat(); } else if (!strcmp(token,"color")) { color = readVec3f(); dead_color = color; } else if (!strcmp(token,"dead_color")) { dead_color = readVec3f(); } else if (!strcmp(token,"color_randomness")) { color_randomness = readFloat(); } else if (!strcmp(token,"mass")) { mass = readFloat(); } else if (!strcmp(token,"mass_randomness")) { mass_randomness = readFloat(); } else if (!strcmp(token,"lifespan")) { lifespan = readFloat(); } else if (!strcmp(token,"lifespan_randomness")) { lifespan_randomness = readFloat(); } else if (!strcmp(token,"desired_num_particles")) { desired_num_particles = readInt(); } else if (strcmp(token,"}")) { printf ("ERROR unknown generator token %s\n", token); assert(0); } else { break; } } // create the appropriate generator Generator *answer = NULL; if (!strcmp(type,"hose_generator")) { answer = new HoseGenerator(position,position_randomness, velocity,velocity_randomness); } else if (!strcmp(type,"ring_generator")) { answer = new RingGenerator(position_randomness,velocity,velocity_randomness); } else { printf ("WARNING: unknown generator type '%s'\n", type); printf ("WARNING: unknown generator type '%s'\n", type); } // set the common generator parameters assert (answer != NULL); answer->SetColors(color,dead_color,color_randomness); answer->SetMass(mass,mass_randomness); answer->SetLifespan(lifespan,lifespan_randomness,desired_num_particles); return answer; } // ==================================================================== // ==================================================================== // ==================================================================== Integrator* Parser::ParseIntegrator() { // read the integrator type char type[MAX_PARSER_TOKEN_LENGTH]; getToken(type); // there are no variables char token[MAX_PARSER_TOKEN_LENGTH]; getToken(token); assert(!strcmp(token,"{")); getToken(token); assert(!strcmp(token,"}")); // create the appropriate integrator Integrator *answer = NULL; if (!strcmp(type,"euler_integrator")) { answer = new EulerIntegrator(); } else if (!strcmp(type,"midpoint_integrator")) { answer = new MidpointIntegrator(); } else if (!strcmp(type,"rungekutta_integrator")) { answer = new RungeKuttaIntegrator(); } else { printf ("WARNING: unknown integrator type '%s'\n", type); } assert (answer != NULL); return answer; } // ==================================================================== // ==================================================================== // ==================================================================== ForceField* Parser::ParseForceField() { // read the forcefield type char type[MAX_PARSER_TOKEN_LENGTH]; getToken(type); // forcefield variable defaults Vec3f gravity = Vec3f(0,0,0); Vec3f force = Vec3f(0,0,0); float magnitude = 1; // read the provided values char token[MAX_PARSER_TOKEN_LENGTH]; getToken(token); assert (!strcmp(token,"{")); while (1) { getToken(token); if (!strcmp(token,"gravity")) { gravity = readVec3f(); } else if (!strcmp(token,"force")) { force = readVec3f(); } else if (!strcmp(token,"magnitude")) { magnitude = readFloat(); } else if (strcmp(token,"}")) { printf ("ERROR unknown gravity token %s\n", token); assert(0); } else { break; } } // create the appropriate force field ForceField *answer = NULL; if (!strcmp(type,"gravity_forcefield")) { answer = new GravityForceField(gravity); } else if (!strcmp(type,"constant_forcefield")) { answer = new ConstantForceField(force); } else if (!strcmp(type,"radial_forcefield")) { answer = new RadialForceField(magnitude); } else if (!strcmp(type,"vertical_forcefield")) { answer = new VerticalForceField(magnitude); } else if (!strcmp(type,"wind_forcefield")) { answer = new WindForceField(magnitude); } else { printf ("WARNING: unknown forcefield type '%s'\n", type); } assert (answer != NULL); return answer; } // ==================================================================== // ==================================================================== // HELPER FUNCTIONS int Parser::getToken(char token[MAX_PARSER_TOKEN_LENGTH]) { // for simplicity, tokens must be separated by whitespace assert (file != NULL); int success = fscanf(file,"%s ",token); if (success == EOF) { token[0] = '\0'; return 0; } return 1; } Vec3f Parser::readVec3f() { float x,y,z; int count = fscanf(file,"%f %f %f",&x,&y,&z); if (count != 3) { printf ("Error trying to read 3 floats to make a Vec3f\n"); assert (0); } return Vec3f(x,y,z); } Vec2f Parser::readVec2f() { float u,v; int count = fscanf(file,"%f %f",&u,&v); if (count != 2) { printf ("Error trying to read 2 floats to make a Vec2f\n"); assert (0); } return Vec2f(u,v); } float Parser::readFloat() { float answer; int count = fscanf(file,"%f",&answer); if (count != 1) { printf ("Error trying to read 1 float\n"); assert (0); } return answer; } int Parser::readInt() { int answer; int count = fscanf(file,"%d",&answer); if (count != 1) { printf ("Error trying to read 1 int\n"); assert (0); } return answer; } // ==================================================================== #endif
[ "3180102688@zju.edu.cn" ]
3180102688@zju.edu.cn
e7a5585209c4f2428ca85fc55d59feb8a1c0482b
b844c8d51fac1148363967993fb3299dcb47164d
/Individual.h
5a62f53dfb18aee3e2d92b348acae672317871fa
[]
no_license
patyhaizer/brkga
1470fcbc39187ce0b52a1ed2692c7bcb3a840601
3642fc64dbe72e920461d2929b143ea7df54e05c
refs/heads/master
2021-01-15T17:41:26.636794
2015-08-31T23:39:38
2015-08-31T23:39:38
37,101,820
0
0
null
null
null
null
UTF-8
C++
false
false
371
h
#ifndef INDIVIDUAL_H #define INDIVIDUAL_H class Individual { private: Individual(); Individual(const Individual& other); Individual operator=(const Individual& other); public: explicit Individual(unsigned chromossomeSize); ~Individual(); double * m_chromossome; double m_fitness; unsigned m_chromossomeSize; }; #endif // INDIVIDUAL_H
[ "paty.haizer@gmail.com" ]
paty.haizer@gmail.com
5f3f225665cff48a5ebe83a2e45e807507cf52fe
9b8708ad7ffb5d344eba46451cabc3da8c0b645b
/Moteur/SceneGraph/meshmanager.h
8dac8630f554c425dde04c6aa8c74babb287882d
[]
no_license
VisualPi/GameEngine
8830037305ff2268866f0e2c254e6f74901dd18d
03c60c571ab3a95b8eaf2c560aa3e4c9486a77c3
refs/heads/master
2021-07-08T18:13:28.459930
2017-10-08T12:05:05
2017-10-08T12:05:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
517
h
#pragma once #include <vector> #include "../Transfer/bufferfactory.h" #include "ModelImporter/mesh.h" #include "../Vulkan/buffer.h" #include "drawcommand.h" class MeshManager { public: MeshManager(BufferFactory &bufferFactory); DrawCmd addMesh(const std::vector<Mesh> &meshes); private: BufferFactory &mBufferFactory; // uint32_t Buffer mStagingBuffer; // the uint32_t size means the total offset used std::vector<std::tuple<uint32_t, Buffer>> mIbos; std::vector<std::tuple<uint32_t, Buffer>> mVbos; };
[ "antoine.morrier@outlook.fr" ]
antoine.morrier@outlook.fr
193a0b07ff81166f34390d3d2b2da8da69aba6e0
313e686e0f0aa3b2535bc94c68644ca2ea7b8e61
/src/server/scripts/Outland/CoilfangReservoir/TheUnderbog/instance_the_underbog.cpp
a56c9db1291598f7bf13e38cc2a5fa4a3fdac638
[]
no_license
mysql1/TournamentCore
cf03d44094257a5348bd6c509357d512fb03a338
571238d0ec49078fb13f1965ce7b91c24f2ea262
refs/heads/master
2020-12-03T00:29:21.203000
2015-05-12T07:30:42
2015-05-12T07:30:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,627
cpp
/* * Copyright (C) 2014-2015 TournamentCore * Copyright (C) 2008-2015 TrinityCore <http://www.trinitycore.org/> * * 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, see <http://www.gnu.org/licenses/>. */ /* This placeholder for the instance is needed for dungeon finding to be able to give credit after the boss defined in lastEncounterDungeon is killed. Without it, the party doing random dungeon won't get satchel of spoils and gets instead the deserter debuff. */ #include "ScriptMgr.h" #include "InstanceScript.h" class instance_the_underbog : public InstanceMapScript { public: instance_the_underbog() : InstanceMapScript("instance_the_underbog", 546) { } InstanceScript* GetInstanceScript(InstanceMap* map) const override { return new instance_the_underbog_InstanceMapScript(map); } struct instance_the_underbog_InstanceMapScript : public InstanceScript { instance_the_underbog_InstanceMapScript(Map* map) : InstanceScript(map) { } }; }; void AddSC_instance_the_underbog() { new instance_the_underbog(); }
[ "TournamentCore@gmail.com" ]
TournamentCore@gmail.com
652cede466fa4be421ae6aab8fde796d3599f151
19742122229f417a418158630f279f81c1c503a6
/repo/daemon/identifier_collector.cc
477305ef779a520d6ebdc61ed68e032f14a4713e
[ "BSD-3-Clause" ]
permissive
rosstex/replex
20bbb0829aef4f868fafb34c2a16172d6455ec6f
2a4499ebc81622985c59647839e7f517869f8c14
refs/heads/master
2020-03-17T16:26:10.767096
2018-05-17T02:41:23
2018-05-17T02:41:23
133,748,573
0
0
null
null
null
null
UTF-8
C++
false
false
3,176
cc
// Copyright (c) 2013-2014, Cornell University // 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 HyperDex 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. // STL #include <algorithm> // e #include <e/atomic.h> // HyperDex #include "daemon/identifier_collector.h" using hyperdex::identifier_collector; using hyperdex::region_id; const region_id identifier_collector::defaultri; identifier_collector :: identifier_collector(e::garbage_collector* gc) : m_gc(gc) , m_collectors() { } identifier_collector :: ~identifier_collector() throw () { } void identifier_collector :: bump(const region_id& ri, uint64_t lb) { e::compat::shared_ptr<e::seqno_collector> sc; if (!m_collectors.get(ri, &sc)) { abort(); } sc->collect_up_to(lb); } void identifier_collector :: collect(const region_id& ri, uint64_t seqno) { e::compat::shared_ptr<e::seqno_collector> sc; if (!m_collectors.get(ri, &sc)) { abort(); } sc->collect(seqno); } uint64_t identifier_collector :: lower_bound(const region_id& ri) { e::compat::shared_ptr<e::seqno_collector> sc; if (!m_collectors.get(ri, &sc)) { abort(); } uint64_t lb; sc->lower_bound(&lb); return lb; } void identifier_collector :: adopt(region_id* ris, size_t ris_sz) { collector_map_t new_collectors; for (size_t i = 0; i < ris_sz; ++i) { e::compat::shared_ptr<e::seqno_collector> sc; if (!m_collectors.get(ris[i], &sc)) { sc = e::compat::shared_ptr<e::seqno_collector>(new e::seqno_collector(m_gc)); sc->collect(0); } assert(sc); new_collectors.put(ris[i], sc); } m_collectors.swap(&new_collectors); }
[ "rapt@cs.princeton.edu" ]
rapt@cs.princeton.edu
d4de29e4aee6f69182086c6dbedaa871b2f5fae2
37fd355d5d0b9a60e6c5799b029ef95eac749afe
/src/scheduler/grouper/GreedyGrouper.hpp
e76fc49886d8dd16152ff025f17cddc8cf8382d6
[]
no_license
freiheitsnetz/openwns-library
7a903aff2ad9d120d53195076d900bd020367980
eb98600df8b0baca1d90907b5dd2c80c64ab9ffa
refs/heads/master
2021-01-18T05:07:32.803956
2014-03-26T16:16:19
2014-03-26T16:16:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,983
hpp
/******************************************************************************* * This file is part of openWNS (open Wireless Network Simulator) * _____________________________________________________________________________ * * Copyright (C) 2004-2009 * Chair of Communication Networks (ComNets) * Kopernikusstr. 5, D-52074 Aachen, Germany * phone: ++49-241-80-27910, * fax: ++49-241-80-22242 * email: info@openwns.org * www: http://www.openwns.org * _____________________________________________________________________________ * * openWNS is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License version 2 as published by the * Free Software Foundation; * * openWNS is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************/ #ifndef WNS_SCHEDULER_GROUPER_GREEDYGROUPER_HPP #define WNS_SCHEDULER_GROUPER_GREEDYGROUPER_HPP #include <WNS/scheduler/grouper/AllPossibleGroupsGrouper.hpp> namespace wns { namespace scheduler { namespace grouper { class GreedyGrouper : public AllPossibleGroupsGrouper { public: // inherit everything from AllPossibleGroupsGrouper except for makeGrouping GreedyGrouper(const wns::pyconfig::View& config); ~GreedyGrouper() {}; protected: virtual Partition makeGrouping(int maxBeams, unsigned int noOfStations); private: class BeamCmp { public: bool operator() (const Beams&, const Beams&) const; }; int MonteCarloGreedyProbe; }; }}} // namespace wns::scheduler::grouper #endif // WNS_SCHEDULER_GROUPER_GREEDYGROUPER_HPP
[ "aku@comnets.rwth-aachen.de" ]
aku@comnets.rwth-aachen.de
3fc78a06a548c887ef3d79d551062efae5e49c88
bad319e286793086efef5f1998f9494ff45a3ad8
/Source/SimpleShooter/ShooterPlayerController.h
1569ee56f9f4bd888d1fcb68c3fc28095ec08e8f
[]
no_license
SharkyZg/SimpleShooter
e8b982bc032c94cd07aa7e2c61b15e0d81b57e88
0ae518d2a5b03992ecdc7dd3e94f2dbf66037e64
refs/heads/master
2023-01-20T22:59:14.402966
2020-11-26T16:46:07
2020-11-26T16:46:07
312,320,583
0
0
null
null
null
null
UTF-8
C++
false
false
835
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/PlayerController.h" #include "ShooterPlayerController.generated.h" /** * */ UCLASS() class SIMPLESHOOTER_API AShooterPlayerController : public APlayerController { GENERATED_BODY() public: virtual void GameHasEnded(class AActor *EndGameFocus = nullptr, bool bIsWinner = false) override; private: UPROPERTY(EditAnywhere) TSubclassOf<class UUserWidget> LoseScreenClass; UPROPERTY(EditAnywhere) TSubclassOf<class UUserWidget> WinScreenClass; UPROPERTY(EditAnywhere) TSubclassOf<class UUserWidget> CrossairClass; UPROPERTY(EditAnywhere) float RestartDelay = 5; FTimerHandle RestartTimer; UPROPERTY() UUserWidget *Crossair; protected: virtual void BeginPlay() override; };
[ "marko.sarkanj@gmail.com" ]
marko.sarkanj@gmail.com
77dc64e38297f4a999095ebb5929fc38fbf7b897
7e288ad3bcaca2e00e04113ebd251331b5ea300c
/starviewer/src/core/screen.cpp
ed500cb92125679f69914ef74a8e86dada3d0e72
[]
no_license
idvr/starviewer
b7fb2eb38e8cce6f6cd9b4b10371a071565ae4fc
94bf98803e4face8f81ff68447cf52a686571ad7
refs/heads/master
2020-12-02T17:46:13.018426
2014-12-02T11:29:38
2014-12-02T11:31:28
null
0
0
null
null
null
null
IBM852
C++
false
false
6,161
cpp
#include "screen.h" #include <QString> namespace udg { const int Screen::NullScreenID = -1; const int Screen::MaximumDistanceInBetween = 5; Screen::Screen() { initializeValues(); } Screen::Screen(const QRect &geometry, const QRect &availableGeometry) { initializeValues(); setGeometry(geometry); setAvailableGeometry(availableGeometry); } Screen::~Screen() { } void Screen::setGeometry(const QRect &geometry) { m_geometry = geometry; } QRect Screen::getGeometry() const { return m_geometry; } void Screen::setAvailableGeometry(const QRect &geometry) { m_availableGeometry = geometry; } QRect Screen::getAvailableGeometry() const { return m_availableGeometry; } void Screen::setAsPrimary(bool isPrimary) { m_isPrimary = isPrimary; } bool Screen::isPrimary() const { return m_isPrimary; } void Screen::setID(int ID) { m_ID = ID; } int Screen::getID() const { return m_ID; } QString Screen::toString() const { QString string; string = QString("Is Primary: %1\n").arg(m_isPrimary); string += QString("ID: %1\n").arg(m_ID); string += QString("Geometry: %1, %2, %3, %4\n").arg(m_geometry.x()).arg(m_geometry.y()).arg(m_geometry.width()).arg(m_geometry.height()); string += QString("Available Geometry: %1, %2, %3, %4").arg(m_availableGeometry.x()).arg(m_availableGeometry.y()).arg(m_availableGeometry.width()).arg(m_availableGeometry.height()); return string; } bool Screen::isHigher(const Screen &screen) { if (m_geometry.top() < screen.getGeometry().top()) { return true; } return false; } bool Screen::isLower(const Screen &screen) { if (m_geometry.top() > screen.getGeometry().top()) { return true; } return false; } bool Screen::isMoreToTheLeft(const Screen &screen) { if (m_geometry.left() < screen.getGeometry().left()) { return true; } return false; } bool Screen::isMoreToTheRight(const Screen &screen) { if (m_geometry.right() > screen.getGeometry().right()) { return true; } return false; } bool Screen::isOver(const Screen &screen) const { if (m_geometry.bottom() <= screen.getGeometry().top()) { return true; } return false; } bool Screen::isUnder(const Screen &screen) const { if (m_geometry.top() >= screen.getGeometry().bottom()) { return true; } return false; } bool Screen::isOnLeft(const Screen &screen) const { if (m_geometry.right() <= screen.getGeometry().left()) { return true; } return false; } bool Screen::isOnRight(const Screen &screen) const { if (m_geometry.left() >= screen.getGeometry().right()) { return true; } return false; } bool Screen::isTop(const Screen &screen) const { // Esta posat a sobre if (abs(m_geometry.bottom() - screen.getGeometry().top()) < MaximumDistanceInBetween) { // Te la mateixa alšada int leftPart = abs(m_geometry.left() - screen.getGeometry().left()); int rightPart = abs(m_geometry.right() - screen.getGeometry().right()); if (leftPart + rightPart < MaximumDistanceInBetween) { return true; } } return false; } bool Screen::isBottom(const Screen &screen) const { // Esta posat a sota if (abs(m_geometry.top() - screen.getGeometry().bottom()) < MaximumDistanceInBetween) { // Te la mateixa alšada int leftPart = abs(m_geometry.left() - screen.getGeometry().left()); int rightPart = abs(m_geometry.right() - screen.getGeometry().right()); if (leftPart + rightPart < MaximumDistanceInBetween) { return true; } } return false; } bool Screen::isLeft(const Screen &screen) const { // Esta posat a l'esquerra if (abs(m_geometry.right() - screen.getGeometry().left()) < MaximumDistanceInBetween) { // Te la mateixa alšada int topPart = abs(m_geometry.top() - screen.getGeometry().top()); int bottomPart = abs(m_geometry.bottom() - screen.getGeometry().bottom()); if (topPart + bottomPart < MaximumDistanceInBetween) { return true; } } return false; } bool Screen::isRight(const Screen &screen) const { // Esta posat a l'esquerra if (abs(m_geometry.left() - screen.getGeometry().right()) < MaximumDistanceInBetween) { // Te la mateixa alšada int topPart = abs(m_geometry.top() - screen.getGeometry().top()); int bottomPart = abs(m_geometry.bottom() - screen.getGeometry().bottom()); if (topPart + bottomPart < MaximumDistanceInBetween) { return true; } } return false; } bool Screen::isTopLeft(const Screen &screen) const { QPoint distancePoint = m_geometry.bottomRight() - screen.getGeometry().topLeft(); if (distancePoint.manhattanLength() < MaximumDistanceInBetween) { return true; } return false; } bool Screen::isTopRight(const Screen &screen) const { QPoint distancePoint = m_geometry.bottomLeft() - screen.getGeometry().topRight(); if (distancePoint.manhattanLength() < MaximumDistanceInBetween) { return true; } return false; } bool Screen::isBottomLeft(const Screen &screen) const { QPoint distancePoint = m_geometry.topRight() - screen.getGeometry().bottomLeft(); if (distancePoint.manhattanLength() < MaximumDistanceInBetween) { return true; } return false; } bool Screen::isBottomRight(const Screen &screen) const { QPoint distancePoint = m_geometry.topLeft() - screen.getGeometry().bottomRight(); if (distancePoint.manhattanLength() < MaximumDistanceInBetween) { return true; } return false; } bool Screen::operator==(const Screen &screen) const { return m_isPrimary == screen.m_isPrimary && m_ID == screen.m_ID && m_geometry == screen.m_geometry && m_availableGeometry == screen.m_availableGeometry; } void Screen::initializeValues() { m_isPrimary = false; m_ID = NullScreenID; } } // End namespace udg
[ "jspinola@gmail.com" ]
jspinola@gmail.com
5215a1051ccadd7a8229f481cb7134cf17d68564
525b6ab973b23d8333fad39dcd530c217e14741f
/stop_variables/mt2w.cc
47e35f0e46147889803b3f0efec15535d6ff1933
[]
no_license
mialiu149/AnalysisLoopers2015
2aa4ec86d6bd75a1510231813b7dc5e11acd1bd6
718c8b33243042f330cbc872af1f805106d4143e
refs/heads/master
2020-12-15T04:08:49.690916
2019-01-17T20:45:50
2019-01-17T20:45:50
44,395,757
1
0
null
null
null
null
UTF-8
C++
false
false
8,677
cc
#include "mt2w.h" // //-------------------------------------------------------------------- // original 8 TeV function double calculateMT2w(vector<LorentzVector>& jets, vector<bool>& btag, LorentzVector& lep, float met, float metphi){ // I am asumming that jets is sorted by Pt assert ( jets.size() == btag.size() ); // require at least 2 jets if ( jets.size()<2 ) return -999.; // First we count the number of b-tagged jets, and separate those non b-tagged std::vector<int> bjets; std::vector<int> non_bjets; for( unsigned int i = 0 ; i < jets.size() ; i++ ){ if( btag.at(i) ) { bjets.push_back(i); } else { non_bjets.push_back(i); } } int n_btag = (int) bjets.size(); // cout << "n_btag = " << n_btag << endl; // We do different things depending on the number of b-tagged jets // arXiv:1203.4813 recipe int nMax=-1; if(jets.size()<=3) nMax=non_bjets.size(); else nMax=3; if (n_btag == 0){ // 0 b-tags // If no b-jets select the minimum of the mt2w from all combinations with // the three leading jets float min_mt2w = 9999; for (int i=0; i<nMax; i++) for (int j=0; j<nMax; j++){ if (i == j) continue; float c_mt2w = mt2wWrapper(lep, jets[non_bjets[i]], jets[non_bjets[j]], met, metphi); if (c_mt2w < min_mt2w) min_mt2w = c_mt2w; } return min_mt2w; } else if (n_btag == 1 ){ // 1 b-tags // if only one b-jet choose the three non-b leading jets and choose the smaller float min_mt2w = 9999; for (int i=0; i<nMax; i++){ float c_mt2w = mt2wWrapper(lep, jets[bjets[0]], jets[non_bjets[i]], met, metphi); if (c_mt2w < min_mt2w) min_mt2w = c_mt2w; } for (int i=0; i<nMax; i++){ float c_mt2w = mt2wWrapper(lep, jets[non_bjets[i]], jets[bjets[0]], met, metphi); if (c_mt2w < min_mt2w) min_mt2w = c_mt2w; } return min_mt2w; } else if (n_btag >= 2) { // >=2 b-tags // if 3 or more b-jets the paper says ignore b-tag and do like 0-bjets // but we are going to make the combinations with the b-jets float min_mt2w = 9999; for (int i=0; i<n_btag; i++) for (int j=0; j<n_btag; j++){ if (i == j) continue; float c_mt2w = mt2wWrapper(lep, jets[bjets[i]], jets[bjets[j]], met, metphi); if (c_mt2w < min_mt2w) min_mt2w = c_mt2w; } return min_mt2w; } return -1.; } // This funcion is a wrapper for mt2w_bisect etc that takes LorentzVectors instead of doubles // original 8 TeV function double mt2wWrapper(LorentzVector& lep, LorentzVector& jet_o, LorentzVector& jet_b, float met, float metphi){ // same for all MT2x variables double metx = met * cos( metphi ); double mety = met * sin( metphi ); double pl[4]; // Visible lepton double pb1[4]; // bottom on the same side as the visible lepton double pb2[4]; // other bottom, paired with the invisible W double pmiss[3]; // <unused>, pmx, pmy missing pT int mydigit = 3; pl[0] = JetUtil::round(lep.E(), mydigit); pl[1] = JetUtil::round(lep.Px(), mydigit); pl[2] = JetUtil::round(lep.Py(), mydigit); pl[3] = JetUtil::round(lep.Pz(), mydigit); pb1[1] = JetUtil::round(jet_o.Px(),mydigit); pb1[2] = JetUtil::round(jet_o.Py(),mydigit); pb1[3] = JetUtil::round(jet_o.Pz(),mydigit); pb2[1] = JetUtil::round(jet_b.Px(),mydigit); pb2[2] = JetUtil::round(jet_b.Py(),mydigit); pb2[3] = JetUtil::round(jet_b.Pz(),mydigit); pmiss[0] = JetUtil::round(0., mydigit); pmiss[1] = JetUtil::round(metx, mydigit); pmiss[2] = JetUtil::round(mety, mydigit); pb1[0] = JetUtil::round(jet_o.E(), mydigit); pb2[0] = JetUtil::round(jet_b.E(), mydigit); mt2w_bisect::mt2w mt2w_event; mt2w_event.set_momenta(pl, pb1, pb2, pmiss); return mt2w_event.get_mt2w(); } //new MT2W function (gives btag values, and has additional functionality) // deprecated //allows for non-massive bjets (not tested) //addnjets: if <2 b-jets, add non-bjets up to total addnjets 'b-jets' (default = 3, recommended = 1,2) //addjets: ==1: add additional jets according to highest b-tag discriminant, ==2: add additional jets according to highest jet-pt /*float CalculateMT2w_(vector<LorentzVector> jets, vector<float> btag, float btagdiscr, LorentzVector lep, float met, float metphi, unsigned int addnjets, int addjets){ if(jets.size()!=btag.size()) return -99.; vector<LorentzVector> bjet = JetUtil::BJetSelector(jets,btag,btagdiscr,2,addnjets,addjets); if(bjet.size()<2) return -999.; float min_mt2w = 9999; for (unsigned int i=0; i<bjet.size(); ++i){ for (unsigned int j=0; j<bjet.size(); ++j){ if (i == j) continue; float c_mt2w = mt2wWrapper(lep, bjet[i], bjet[j], met, metphi); if (c_mt2w < min_mt2w) min_mt2w = c_mt2w; } } return min_mt2w; }*/ //new MT2W function (gives btag values, and has additional functionality) // deprecated //see CalculateMT2w_ //uses LorentzVector for MET /*float CalculateMT2w(vector<LorentzVector> jets, vector<float> btag, float btagdiscr, LorentzVector lep, LorentzVector metlv, unsigned int addnjets, int addjets){ float met = metlv.Pt(); float metphi = metlv.Phi(); return CalculateMT2w_(jets,btag,btagdiscr,lep,met,metphi,addnjets,addjets); }*/ //new MT2W function (give directly bjets, and has additional functionality) // deprecated //allows for non-massive bjets (not tested) /*float CalculateMT2W_(vector<LorentzVector> bjet, LorentzVector lep, float met, float metphi){ if(bjet.size()<2) return -999.; float min_mt2w = 9999; for (unsigned int i=0; i<bjet.size(); ++i){ for (unsigned int j=0; j<bjet.size(); ++j){ if (i == j) continue; float c_mt2w = mt2wWrapper(lep, bjet[i], bjet[j], met, metphi); if (c_mt2w < min_mt2w) min_mt2w = c_mt2w; } } return min_mt2w; }*/ //new MT2W function (give directly bjets, and has additional functionality) // deprecated //see CalculateMT2W_ //uses LorentzVector for MET /*float CalculateMT2W(vector<LorentzVector> bjet, LorentzVector lep, LorentzVector metlv){ float met = metlv.Pt(); float metphi = metlv.Phi(); return CalculateMT2W_(bjet,lep,met,metphi); }*/ // 13 TeV implementation - full calculation needs JetUtil CSV ordering, see looper float CalcMT2W(vector<LorentzVector> bjets, vector<LorentzVector> addjets, LorentzVector lep, LorentzVector metlv){ float met = metlv.Pt(); float metphi = metlv.Phi(); return CalcMT2W_(bjets,addjets,lep,met,metphi); } // 13 TeV implementation - full calculation needs JetUtil CSV ordering, see looper float CalcMT2W_(vector<LorentzVector> bjets, vector<LorentzVector> addjets, LorentzVector lep, float met, float metphi){ if((bjets.size()+addjets.size())<2) return -999.; float min_mt2w = 9999; for (unsigned int i=0; i<bjets.size(); ++i){ for (unsigned int j=i+1; j<bjets.size(); ++j){ float c_mt2w = mt2wWrapper(lep, bjets[i], bjets[j], met, metphi); if (c_mt2w < min_mt2w) min_mt2w = c_mt2w; //cout << "MT2W " << c_mt2w << " for b1 " << bjets[i].Pt() << " and b2 " << bjets[j].Pt() << endl; c_mt2w = mt2wWrapper(lep, bjets[j], bjets[i], met, metphi); if (c_mt2w < min_mt2w) min_mt2w = c_mt2w; //cout << "MT2W " << c_mt2w << " for b1 " << bjets[j].Pt() << " and b2 " << bjets[i].Pt() << endl; } for (unsigned int j=0; j<addjets.size(); ++j){ float c_mt2w = mt2wWrapper(lep, bjets[i], addjets[j], met, metphi); if (c_mt2w < min_mt2w) min_mt2w = c_mt2w; //cout << "MT2W " << c_mt2w << " for b1 " << bjets[i].Pt() << " and a2 " << addjets[j].Pt() << endl; c_mt2w = mt2wWrapper(lep, addjets[j], bjets[i], met, metphi); if (c_mt2w < min_mt2w) min_mt2w = c_mt2w; //cout << "MT2W " << c_mt2w << " for a1 " << addjets[j].Pt() << " and b2 " << bjets[i].Pt() << endl; } } if(bjets.size()==0){ for (unsigned int j=1; j<addjets.size(); ++j){ float c_mt2w = mt2wWrapper(lep, addjets[0], addjets[j], met, metphi); if (c_mt2w < min_mt2w) min_mt2w = c_mt2w; c_mt2w = mt2wWrapper(lep, addjets[j], addjets[0], met, metphi); if (c_mt2w < min_mt2w) min_mt2w = c_mt2w; } } return min_mt2w; }
[ "miaoyuan.liu0@gmail.com" ]
miaoyuan.liu0@gmail.com
f002df229d9b91f81d10fa6b6f78a41843ef53d4
e157690a1cbf4ba86a61f873ea8cadcb8dd39f10
/src/matrix.cxx
2b1fc463bf29e7ae3365cb7638bd7fe2c73e4cff
[]
no_license
mollios/clustering
8792920705f958a014143d92e33920bf20a1169e
5af88d45a8465858980f44e6fa7c50913242ae87
refs/heads/master
2021-07-12T15:46:34.810127
2021-04-15T10:39:05
2021-04-15T10:39:05
243,174,558
0
0
null
null
null
null
UTF-8
C++
false
false
9,088
cxx
#include<iostream> #include<cstdlib> #include<cmath> #include"vector.h" #include"matrix.h" Matrix::Matrix(int rows, int cols) try : Rows(rows), Element(new Vector[Rows]){ for(int i=0;i<Rows;i++){ Element[i]=Vector(cols); } } catch(std::bad_alloc){ std::cerr << "Out of Memory" << std::endl; throw; } Matrix::Matrix(int dim, const char *s) try : Rows(dim), Element(new Vector[Rows]){ if(strcmp(s, "I")!=0){ std::cerr << "Invalid string parameter" << std::endl; exit(1); } for(int i=0;i<Rows;i++){ Element[i]=Vector(dim); } for(int i=0;i<Rows;i++){ for(int j=0;j<Rows;j++){ Element[i][j]=0.0; } Element[i][i]=1.0; } } catch(std::bad_alloc){ std::cerr << "Out of Memory" << std::endl; throw; } Matrix::Matrix(const Vector &arg, const char *s) try : Rows(arg.size()), Element(new Vector[Rows]){ if(strcmp(s, "diag")!=0){ std::cerr << "Invalid string parameter" << std::endl; exit(1); } for(int i=0;i<Rows;i++){ Element[i]=Vector(Rows); } for(int i=0;i<Rows;i++){ for(int j=0;j<Rows;j++){ Element[i][j]=0.0; } Element[i][i]=arg[i]; } } catch(std::bad_alloc){ std::cerr << "Out of Memory" << std::endl; throw; } Matrix::~Matrix(void){ delete []Element; } Matrix::Matrix(const Matrix &arg) try : Rows(arg.Rows), Element(new Vector[Rows]){ for(int i=0;i<Rows;i++){ Element[i]=arg.Element[i]; } } catch(std::bad_alloc){ std::cerr << "Out of Memory" << std::endl; throw; } Matrix::Matrix(Matrix &&arg) : Rows(arg.Rows), Element(arg.Element){ arg.Rows=0; arg.Element=nullptr; } Matrix &Matrix::operator=(Matrix &&arg){ if(this==&arg){ return *this; } else{ Rows=arg.Rows; Element=arg.Element; arg.Rows=0; arg.Element=nullptr; return *this; } } Matrix &Matrix::operator=(const Matrix &arg){ if(this==&arg) return *this; //Rows=arg.Rows;ここではRowsを更新してはいけない if(this->Rows != arg.Rows || this->cols() != arg.cols()){ Rows=arg.Rows; delete []Element; try{ Element=new Vector[Rows]; } catch(std::bad_alloc){ std::cerr << "Out of Memory" << std::endl; throw; } } for(int i=0;i<Rows;i++){ Element[i]=arg.Element[i]; } return *this; } int Matrix::rows(void) const{ return Rows; } int Matrix::cols(void) const{ return Element[0].size(); } Vector Matrix::operator[](int index) const{ return Element[index]; } Vector &Matrix::operator[](int index){ return Element[index]; } Matrix Matrix::operator+(void) const{ return *this; } Matrix Matrix::operator-(void) const{ Matrix result=*this; for(int i=0;i<result.Rows;i++){ result[i]=-1.0*result[i]; } return result; } Matrix &Matrix::operator+=(const Matrix &rhs){ if(rhs.Rows==0){ std::cout << "Rows 0" << std::endl; exit(1); } else if(Rows!=rhs.Rows){ std::cout << "Rows Unmatched" << std::endl; exit(1); } else{ for(int i=0;i<Rows;i++){ Element[i]+=rhs[i]; } } return *this; } Matrix &Matrix::operator-=(const Matrix &rhs){ if(rhs.Rows==0){ std::cout << "Rows 0" << std::endl; exit(1); } else if(Rows!=rhs.Rows){ std::cout << "Rows Unmatched" << std::endl; exit(1); } else{ for(int i=0;i<Rows;i++){ Element[i]-=rhs[i]; } } return *this; } Matrix operator+(const Matrix &lhs, const Matrix &rhs){ Matrix result=lhs; return result+=rhs; } Matrix operator-(const Matrix &lhs, const Matrix &rhs){ Matrix result=lhs; return result-=rhs; } Matrix operator*(double lhs, const Matrix &rhs){ if(rhs.rows()==0){ std::cout << "Rows 0" << std::endl; exit(1); } Matrix result=rhs; for(int i=0;i<result.rows();i++){ result[i]=lhs*result[i]; } return result; } Matrix &Matrix::operator/=(double rhs){ for(int i=0;i<Rows;i++){ Element[i]/=rhs; } return *this; } Matrix operator/(const Matrix &lhs, double rhs){ Matrix result(lhs); return result/=rhs; } std::ostream &operator<<(std::ostream &os, const Matrix &rhs){ os << "("; if(rhs.rows()>0){ for(int i=0;;i++){ os << rhs[i]; if(i>=rhs.rows()-1) break; os << "\n"; } } os << ')'; return os; } bool operator==(const Matrix &lhs, const Matrix &rhs){ if(lhs.rows()!=rhs.rows()) return false; for(int i=0;i<lhs.rows();i++){ if(lhs[i]!=rhs[i]) return false; } return true; } double abssum(const Vector &arg){ double result=fabs(arg[0]); for(int i=1;i<arg.size();i++){ result+=fabs(arg[i]); } return result; } double max_norm(const Matrix &arg){ if(arg.rows()<1){ std::cout << "Can't calculate norm for 0-sized vector" << std::endl; exit(1); } double result=abssum(arg[0]); for(int i=1;i<arg.rows();i++){ double tmp=abssum(arg[i]); if(result<tmp) result=tmp; } return result; } double frobenius_norm(const Matrix &arg){ double result=0.0; for(int i=0;i<arg.rows();i++){ for(int j=0;j<arg.cols();j++){ result+=arg[i][j]*arg[i][j]; }} return sqrt(result); } Vector operator*(const Matrix &lhs, const Vector &rhs){ if(lhs.rows()<1 || lhs.cols()<1 || rhs.size()<1 || lhs.cols()!=rhs.size()){ std::cout << "operator*(const Matrix &, const Vector &):"; std::cout << "Can't calculate innerproduct "; std::cout << "for 0-sized vector "; std::cout << "or for different sized vector:"; std::cout << "lhs.Cols=" << lhs.cols() << ", "; std::cout << "lhs.Rows=" << lhs.rows() << ", "; std::cout << "rhs.Size=" << rhs.size(); std::cout << std::endl; exit(1); } Vector result(lhs.rows()); for(int i=0;i<lhs.rows();i++){ result[i]=lhs[i]*rhs; } return result; } Matrix operator*(const Matrix &lhs, const Matrix &rhs){ if(lhs.rows()<1 || rhs.cols()<1 || lhs.cols()!=rhs.rows()){ std::cout << "Can't calculate innerproduct"; std::cout << "for 0-sized vector"; std::cout << "or for different sized vector"; std::cout << std::endl; exit(1); } Matrix result(lhs.rows(), rhs.cols()); for(int i=0;i<result.rows();i++){ for(int j=0;j<result.cols();j++){ result[i][j]=0.0; for(int k=0;k<lhs.cols();k++){ result[i][j]+=lhs[i][k]*rhs[k][j]; } }} return result; } Matrix Matrix::sub(int row_begin, int row_end, int col_begin, int col_end) const{ if(row_end<row_begin || col_end<col_begin){ std::cerr << "Matrix::sub:invalid parameter" << std::endl; std::cerr << "row_begin:" << row_begin << std::endl; std::cerr << "row_end:" << row_end << std::endl; std::cerr << "col_begin:" << col_begin << std::endl; std::cerr << "col_end:" << col_end << std::endl; exit(1); } if(row_end>=this->rows() || col_end>=this->cols()){ std::cerr << "Matrix::sub:invalid parameter" << std::endl; std::cerr << "row_end:" << row_end << std::endl; std::cerr << "Rows:" << this->rows() << std::endl; std::cerr << "col_end:" << col_end << std::endl; std::cerr << "Cols:" << this->cols() << std::endl; exit(1); } if(row_begin<0 || col_begin<0){ std::cerr << "Matrix::sub:invalid parameter" << std::endl; std::cerr << "row_begin:" << row_begin << std::endl; std::cerr << "col_begin:" << col_begin << std::endl; exit(1); } Matrix result(row_end-row_begin+1, col_end-col_begin+1); for(int i=0;i<result.rows();i++){ for(int j=0;j<result.cols();j++){ result[i][j]=Element[i+row_begin][j+col_begin]; }} return result; } void Matrix::set_sub(int row_begin, int row_end, int col_begin, int col_end, const Matrix &arg){ if(row_end<row_begin || col_end<col_begin){ std::cerr << "Matrix::sub:invalid parameter" << std::endl; exit(1); } for(int i=row_begin;i<=row_end;i++){ for(int j=col_begin;j<=col_end;j++){ Element[i][j]=arg[i-row_begin][j-col_begin]; }} return; } Matrix transpose(const Matrix &arg){ Matrix result(arg.cols(), arg.rows()); for(int i=0;i<result.rows();i++){ for(int j=0;j<result.cols();j++){ result[i][j]=arg[j][i]; }} return result; } Vector diag(const Matrix &arg){ if(arg.rows()!=arg.cols()){ std::cerr << "No Diag" << std::endl; exit(1); } Vector result(arg.rows()); for(int i=0;i<result.size();i++){ result[i]=arg[i][i]; } return result; } Matrix pow(const Matrix &arg, double power){ Matrix result(arg); for(int i=0;i<result.rows();i++){ for(int j=0;j<result.cols();j++){ result[i][j]=pow(result[i][j],power); }} return result; } Matrix transpose(const Vector &arg){ Matrix result(1, arg.size()); for(int j=0;j<result.cols();j++){ result[0][j]=arg[j]; } return result; } Matrix operator*(const Vector &lhs, const Matrix &rhs){ if(rhs.rows()!=1){ std::cerr << "Size unmatched for Vector*Matrix:" << rhs.rows() << ":" << rhs.cols() << std::endl; exit(1); } Matrix result(lhs.size(), rhs.cols()); for(int i=0;i<result.rows();i++){ for(int j=0;j<result.cols();j++){ result[i][j]=lhs[i]*rhs[0][j]; }} return result; }
[ "ma20096@shibaura-it.ac.jp" ]
ma20096@shibaura-it.ac.jp
61cdc9adbcaec9e25f91357127d62b47bab6af6a
dd92b8cc9a2bca3a1b3d5ebf36fc00493a39dc2f
/src/tool/hpcrun/sample-sources/blame-shift/blame-map.c
5d8b5767e754302f617a64685f485075f8d4c1cb
[]
no_license
tjovanovic996/hpctoolkit-tracing
effb19b34430eea9df02f19e906b846782b52fa4
f93e17149985cc93a3c6c4654e2a6e472f681189
refs/heads/master
2020-07-09T19:58:55.783806
2019-08-23T21:09:23
2019-08-23T21:09:23
204,068,692
0
1
null
null
null
null
UTF-8
C++
false
false
7,394
c
// -*-Mode: C++;-*- // technically C99 // * BeginRiceCopyright ***************************************************** // // $HeadURL: $ // $Id$ // // -------------------------------------------------------------------------- // Part of HPCToolkit (hpctoolkit.org) // // Information about sources of support for research and development of // HPCToolkit is at 'hpctoolkit.org' and in 'README.Acknowledgments'. // -------------------------------------------------------------------------- // // Copyright ((c)) 2002-2019, Rice University // 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 Rice University (RICE) 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 RICE 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 RICE 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. // // ******************************************************* EndRiceCopyright * // // directed blame shifting for locks, critical sections, ... // /****************************************************************************** * system includes *****************************************************************************/ #include <assert.h> /****************************************************************************** * local includes *****************************************************************************/ #include "blame-map.h" #include <hpcrun/messages/messages.h> #include <lib/prof-lean/stdatomic.h> #include <memory/hpcrun-malloc.h> /****************************************************************************** * macros *****************************************************************************/ #define N (128*1024) #define INDEX_MASK ((N)-1) #define LOSSLESS_BLAME #ifdef BLAME_MAP_LOCKING #define do_lock() \ { \ for(;;) { \ if (fetch_and_store_i64(&thelock, 1) == 0) break; \ while (thelock == 1); \ } \ } #define do_unlock() thelock = 0 #else #define do_lock() #define do_unlock() #endif /****************************************************************************** * data type *****************************************************************************/ typedef struct { uint32_t obj_id; uint32_t blame; } blame_parts_t; typedef union { uint_fast64_t combined; blame_parts_t parts; } blame_all_t; union blame_entry_t { atomic_uint_fast64_t value; }; /*************************************************************************** * private data ***************************************************************************/ static uint64_t volatile thelock; /*************************************************************************** * private operations ***************************************************************************/ uint32_t blame_entry_obj_id(uint_fast64_t value) { blame_all_t entry; entry.combined = value; return entry.parts.obj_id; } uint32_t blame_entry_blame(uint_fast64_t value) { blame_all_t entry; entry.combined = value; return entry.parts.blame; } uint32_t blame_map_obj_id(uint64_t obj) { return ((uint32_t) ((uint64_t)obj) >> 2); } uint32_t blame_map_hash(uint64_t obj) { return ((uint32_t)((blame_map_obj_id(obj)) & INDEX_MASK)); } uint_fast64_t blame_map_entry(uint64_t obj, uint32_t metric_value) { blame_all_t be; be.parts.obj_id = blame_map_obj_id(obj); be.parts.blame = metric_value; return be.combined; } /*************************************************************************** * interface operations ***************************************************************************/ blame_entry_t* blame_map_new(void) { blame_entry_t* rv = hpcrun_malloc(N * sizeof(blame_entry_t)); blame_map_init(rv); return rv; } void blame_map_init(blame_entry_t table[]) { int i; for(i = 0; i < N; i++) { atomic_store(&table[i].value, 0); } } void blame_map_add_blame(blame_entry_t table[], uint64_t obj, uint32_t metric_value) { uint32_t obj_id = blame_map_obj_id(obj); uint32_t index = blame_map_hash(obj); assert(index >= 0 && index < N); do_lock(); uint_fast64_t oldval = atomic_load(&table[index].value); for(;;) { blame_all_t newval; newval.combined = oldval; newval.parts.blame += metric_value; uint32_t obj_at_index = newval.parts.obj_id; if(obj_at_index == obj_id) { #ifdef LOSSLESS_BLAME if (atomic_compare_exchange_strong_explicit(&table[index].value, &oldval, newval.combined, memory_order_relaxed, memory_order_relaxed)) break; #else // the atomicity is not needed here, but it is the easiest way to write this atomic_store(&table[index].value, newval.combined); break; #endif } else { if(newval.parts.obj_id == 0) { newval.combined = blame_map_entry(obj, metric_value); #ifdef LOSSLESS_BLAME if ((atomic_compare_exchange_strong_explicit(&table[index].value, &oldval, newval.combined, memory_order_relaxed, memory_order_relaxed))) break; // otherwise, try again #else // the atomicity is not needed here, but it is the easiest way to write this atomic_store(&table[index].value, newval.combined); break; #endif } else { EMSG("leaked blame %d\n", metric_value); // entry in use for another object's blame // in this case, since it isn't easy to shift // our blame efficiently, we simply drop it. break; } } } do_unlock(); } uint64_t blame_map_get_blame(blame_entry_t table[], uint64_t obj) { static uint64_t zero = 0; uint64_t val = 0; uint32_t obj_id = blame_map_obj_id(obj); uint32_t index = blame_map_hash(obj); assert(index >= 0 && index < N); do_lock(); for(;;) { uint_fast64_t oldval = atomic_load(&table[index].value); uint32_t entry_obj_id = blame_entry_obj_id(oldval); if(entry_obj_id == obj_id) { #ifdef LOSSLESS_BLAME if (!atomic_compare_exchange_strong_explicit(&table[index].value, &oldval, zero, memory_order_relaxed, memory_order_relaxed)) continue; // try again on failure #else table[index].all = 0; #endif val = (uint64_t) blame_entry_blame(oldval); } break; } do_unlock(); return val; }
[ "ax4@gpu.cs.rice.edu" ]
ax4@gpu.cs.rice.edu
ee447d1259521fe5626a8ca0c351c47080340796
dd80a584130ef1a0333429ba76c1cee0eb40df73
/external/chromium_org/chrome/browser/ui/views/apps/chrome_shell_window_delegate_views_win.cc
9ef69f376d2f18bba1c3fe4ba610e119990b680a
[ "BSD-3-Clause", "MIT" ]
permissive
karunmatharu/Android-4.4-Pay-by-Data
466f4e169ede13c5835424c78e8c30ce58f885c1
fcb778e92d4aad525ef7a995660580f948d40bc9
refs/heads/master
2021-03-24T13:33:01.721868
2017-02-18T17:48:49
2017-02-18T17:48:49
81,847,777
0
2
MIT
2020-03-09T00:02:12
2017-02-13T16:47:00
null
UTF-8
C++
false
false
602
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 "chrome/browser/ui/apps/chrome_shell_window_delegate.h" #include "chrome/browser/ui/views/apps/native_app_window_views_win.h" // static apps::NativeAppWindow* ChromeShellWindowDelegate::CreateNativeAppWindowImpl( apps::ShellWindow* shell_window, const apps::ShellWindow::CreateParams& params) { NativeAppWindowViewsWin* window = new NativeAppWindowViewsWin; window->Init(shell_window, params); return window; }
[ "karun.matharu@gmail.com" ]
karun.matharu@gmail.com
2a13231b8e63dc0fca1b03ac00bd3d7017a32ccc
4b5ea843b81b17626fff180dac3b3bec82e8110e
/Plugins/BIPlugin/Source/BIPlugin/Private/PathPredictionEntry.cpp
c738e6cd3cb88bddc0cd82922ef78d8bbc500a10
[]
no_license
TeraNaidja/UE4BlueprintPlugin
75452e0302fcba5e3ff99b5838ea3b8f46ecb1c2
16784cf63b688c2fb451f728ee5f40a8e5d4e9d9
refs/heads/master
2016-09-03T03:49:17.131454
2015-09-22T11:29:19
2015-09-22T11:29:19
33,359,265
1
0
null
null
null
null
UTF-8
C++
false
false
683
cpp
#include "BIPluginPrivatePCH.h" #include "PathPredictionEntry.h" PathPredictionEntry::PathPredictionEntry() : m_NumUses(0) { } PathPredictionEntry::~PathPredictionEntry() { } bool PathPredictionEntry::CompareExcludingUses(const PathPredictionEntry& a_Other) const { return m_AnchorVertex == a_Other.m_AnchorVertex && m_PredictionVertex == a_Other.m_PredictionVertex && m_ContextPath == a_Other.m_ContextPath; } FArchive& operator << (FArchive& a_Archive, PathPredictionEntry& a_Value) { int32 direction = (int32)a_Value.m_Direction; return a_Archive << direction << a_Value.m_PredictionVertex << a_Value.m_AnchorVertex << a_Value.m_ContextPath << a_Value.m_NumUses; }
[ "phildegroot5@gmail.com" ]
phildegroot5@gmail.com
5ebbfce2147b6f43a4a78934618f28350b3a597f
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5639104758808576_0/C++/Biigbang/p1.cpp
172bdebce242acbff444a988777c7cc8929189b9
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
550
cpp
#include <stdio.h> const int maxs = 1001; char shy[maxs]; int T, S; int main() { int c, a; scanf("%d", &T); for(int t = 1; t <= T; ++t) { scanf("%d%s", &S, shy); c = a = 0; for(int i = 0; i <= S; ++i) { if (shy[i] > '0') { if (c >= i) { c += shy[i] - '0'; } else { a += i - c; c += shy[i] - '0' + a; } } } printf("Case #%d: %d\n", t, a); } return 0; }
[ "eewestman@gmail.com" ]
eewestman@gmail.com