blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
6429afb6f0baa6ff10e8724fbfd853c7a0785c7d
374a76b065a133084b6d87c498e0b0ac0fb0e0fc
/tensorflow/compiler/mlir/tools/kernel_gen/transforms/gpu_kernel_to_blob_pass.cc
f995c22f36f259b31281648942c32845a72dd044
[ "Apache-2.0" ]
permissive
yashkarbhari/tensorflow
26e1efa1bc89365cafcee20cc34aa6e2f1d71132
fd20aef919be295ce540aef232a4450ffb5fb521
refs/heads/master
2022-12-25T11:17:06.508453
2020-10-03T05:52:11
2020-10-03T05:59:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,468
cc
/* Copyright 2020 The TensorFlow Authors. 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 "llvm/Transforms/Utils/Cloning.h" #include "mlir/Dialect/StandardOps/IR/Ops.h" // from @llvm-project #include "mlir/Target/NVVMIR.h" // from @llvm-project #include "mlir/Target/ROCDLIR.h" // from @llvm-project #include "mlir/Transforms/DialectConversion.h" // from @llvm-project #include "tensorflow/compiler/mlir/hlo/include/mlir-hlo/Dialect/mhlo/IR/hlo_ops.h" #include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/passes.h" #include "tensorflow/compiler/xla/debug_options_flags.h" #include "tensorflow/compiler/xla/service/gpu/llvm_gpu_backend/gpu_backend_lib.h" #include "tensorflow/compiler/xla/service/gpu/stream_executor_util.h" #include "tensorflow/compiler/xla/service/gpu/target_constants.h" #include "tensorflow/compiler/xla/service/hlo_module_config.h" #include "tensorflow/compiler/xla/status.h" #include "tensorflow/compiler/xla/statusor.h" #include "tensorflow/core/platform/cuda_libdevice_path.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/path.h" #if GOOGLE_CUDA #include "tensorflow/stream_executor/gpu/asm_compiler.h" #elif TENSORFLOW_USE_ROCM #include "tensorflow/core/platform/rocm_rocdl_path.h" #endif namespace mlir { namespace kernel_gen { namespace transforms { namespace { #define GEN_PASS_CLASSES #include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/kernel_gen_passes.h.inc" using xla::InternalError; class GpuKernelToBlobPass : public GpuKernelToBlobPassBase<GpuKernelToBlobPass> { public: GpuKernelToBlobPass(mlir::StringRef blob_annotation, llvm::ArrayRef<uint32_t> architectures, bool generate_fatbin) { blob_annotation_ = blob_annotation.str(); architectures_ = architectures; generate_fatbin_ = generate_fatbin; } void runOnOperation() override { mlir::gpu::GPUModuleOp gpu_module = getOperation(); auto blob_or = GetGpuBinaryBlob(gpu_module); if (blob_or.ok()) { const auto& blob = blob_or.ValueOrDie(); std::string blob_string(blob.begin(), blob.end()); gpu_module.setAttr(blob_annotation_, mlir::StringAttr::get(blob_string, &getContext())); return; } return signalPassFailure(); } xla::StatusOr<std::vector<uint8_t>> GetGpuBinaryBlob( mlir::gpu::GPUModuleOp gpu_module) { if (architectures_.empty()) { return InternalError("Expected at least one GPU architecture."); } if (!generate_fatbin_ && architectures_.size() > 1) { return InternalError( "Can only generate machine code for more than one architecture as a " "fatbin."); } llvm::LLVMContext llvmContext; #if TENSORFLOW_USE_ROCM auto llvmModule = mlir::translateModuleToROCDLIR(gpu_module, llvmContext); if (!llvmModule) { return InternalError("Could not translate MLIR module to ROCDL IR"); } llvmModule->setModuleIdentifier("acme"); xla::HloModuleConfig config; config.set_debug_options(xla::GetDebugOptionsFromFlags()); // TODO(b/169066682): Support fatbin on ROCm. if (generate_fatbin_) { return InternalError("Fatbins are not yet supported for ROCm."); } uint32_t arch = architectures_.front(); std::string libdevice_dir = tensorflow::RocdlRoot(); return xla::gpu::amdgpu::CompileToHsaco(llvmModule.get(), arch, config, libdevice_dir); #elif GOOGLE_CUDA auto llvmModule = mlir::translateModuleToNVVMIR(gpu_module, llvmContext); if (!llvmModule) { return InternalError("Could not translate MLIR module to NVVM"); } llvmModule->setModuleIdentifier("acme"); llvmModule->setDataLayout(xla::gpu::nvptx::kDataLayout); xla::HloModuleConfig config; config.set_debug_options(xla::GetDebugOptionsFromFlags()); auto enable_fusion = [](llvm::TargetMachine* target) { target->Options.AllowFPOpFusion = llvm::FPOpFusion::FPOpFusionMode::Fast; }; // Compile and collect requested cubin and PTX images. std::vector<tensorflow::se::CubinOrPTXImage> images; TF_ASSIGN_OR_RETURN(std::string libdevice_dir, GetLibdeviceDir(config)); auto gpu_asm_opts = xla::gpu::PtxOptsFromConfig(config); for (uint32_t arch : architectures_) { int32_t cc_major = arch / 10; int32_t cc_minor = arch % 10; // Module may be changed by CompileToPtx. auto llvmModuleCopy = llvm::CloneModule(*llvmModule); TF_ASSIGN_OR_RETURN( std::string ptx, xla::gpu::nvptx::CompileToPtx(llvmModuleCopy.get(), std::make_pair(cc_major, cc_minor), config, libdevice_dir, enable_fusion)); // TODO(b/169066682): If compute_XX profile, collect PTX image here. VLOG(1) << ptx; TF_ASSIGN_OR_RETURN(std::vector<uint8_t> gpu_asm, tensorflow::se::CompileGpuAsm( cc_major, cc_minor, ptx.c_str(), gpu_asm_opts)); if (!generate_fatbin_) { // Skip fatbin generation and return the first and only GPU machine // code. return gpu_asm; } // Collect cubin image. images.push_back({absl::StrCat("sm_", arch), std::move(gpu_asm)}); } // TODO(b/169870789): Revisit the use of fatbins. // Bundle cubin and PTX images into a single fatbin. return tensorflow::se::BundleGpuAsm(images, gpu_asm_opts.preferred_cuda_dir); #endif return InternalError( "Neither TENSORFLOW_USE_ROCM nor GOOGLE_CUDA are defined." " Did you specify either --config=rocm or --config=cuda ?"); } private: xla::StatusOr<std::string> GetLibdeviceDir( const xla::HloModuleConfig& hlo_module_config) { for (const std::string& cuda_root : tensorflow::CandidateCudaRoots( hlo_module_config.debug_options().xla_gpu_cuda_data_dir())) { std::string libdevice_dir = tensorflow::io::JoinPath(cuda_root, "nvvm", "libdevice"); VLOG(2) << "Looking for libdevice at " << libdevice_dir; if (tensorflow::Env::Default()->IsDirectory(libdevice_dir).ok()) { VLOG(2) << "Found libdevice dir " << libdevice_dir; return libdevice_dir; } } return InternalError( "Can't find libdevice directory ${CUDA_DIR}/nvvm/libdevice"); } }; } // namespace std::unique_ptr<OperationPass<gpu::GPUModuleOp>> CreateGpuKernelToBlobPass( mlir::StringRef blob_annotation, ArrayRef<uint32_t> architectures, bool generate_fatbin) { return std::make_unique<GpuKernelToBlobPass>(blob_annotation, architectures, generate_fatbin); } } // namespace transforms } // namespace kernel_gen } // namespace mlir
[ "gardener@tensorflow.org" ]
gardener@tensorflow.org
356b733256dcfef125d94b867aa3fba0a2c1390c
a2681499f4334accc7d52bc3902a9790b63031dd
/src/main/medfilt.cc
50025553187fad4d47cc9987d272e41cfcaa1b3a
[ "Apache-2.0" ]
permissive
sp-nitech/SPTK
db9f3c4399b67abb8df3d6379fbd21a33423320f
ab234a5926c10e37d7c62b427a4df804382dd388
refs/heads/master
2023-08-19T08:42:45.858537
2023-08-17T05:54:42
2023-08-17T05:54:42
103,337,202
187
26
Apache-2.0
2023-08-17T05:54:43
2017-09-13T01:15:34
C++
UTF-8
C++
false
false
9,574
cc
// ------------------------------------------------------------------------ // // Copyright 2021 SPTK Working Group // // // // 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 <fstream> // std::ifstream #include <iomanip> // std::setw #include <iostream> // std::cerr, std::cin, std::cout, std::endl, etc. #include <sstream> // std::ostringstream #include <vector> // std::vector #include "GETOPT/ya_getopt.h" #include "SPTK/filter/median_filter.h" #include "SPTK/input/input_source_from_stream.h" #include "SPTK/utils/sptk_utils.h" namespace { enum LongOptions { kMagic = 1000, }; enum WaysToApplyFilter { kEachDimension = 0, kAcrossDimension, kNumWaysToApplyFilter }; const int kDefaultNumInputOrder(0); const int kDefaultNumFilterOrder(2); const WaysToApplyFilter kDefaultWayToApplyFilter(kEachDimension); void PrintUsage(std::ostream* stream) { // clang-format off *stream << std::endl; *stream << " medfilt - median filter" << std::endl; *stream << std::endl; *stream << " usage:" << std::endl; *stream << " medfilt [ options ] [ infile ] > stdout" << std::endl; *stream << " options:" << std::endl; *stream << " -l l : length of vector ( int)[" << std::setw(5) << std::right << kDefaultNumInputOrder + 1 << "][ 1 <= l <= ]" << std::endl; // NOLINT *stream << " -m m : order of vector ( int)[" << std::setw(5) << std::right << "l-1" << "][ 0 <= m <= ]" << std::endl; // NOLINT *stream << " -k k : order of filter ( int)[" << std::setw(5) << std::right << kDefaultNumFilterOrder << "][ 0 <= k <= ]" << std::endl; // NOLINT *stream << " -w w : way to apply filter ( int)[" << std::setw(5) << std::right << kDefaultWayToApplyFilter << "][ 0 <= w <= 1 ]" << std::endl; // NOLINT *stream << " 0 (each dimension)" << std::endl; *stream << " 1 (across dimension)" << std::endl; *stream << " -magic magic : magic number (double)[" << std::setw(5) << std::right << "N/A" << "]" << std::endl; // NOLINT *stream << " -h : print this message" << std::endl; *stream << " infile:" << std::endl; *stream << " data sequence (double)[stdin]" << std::endl; // NOLINT *stream << " stdout:" << std::endl; *stream << " filtered data sequence (double)" << std::endl; // NOLINT *stream << " notice:" << std::endl; *stream << " if w = 0, output size is m+1, otherwise 1" << std::endl; *stream << std::endl; *stream << " SPTK: version " << sptk::kVersion << std::endl; *stream << std::endl; // clang-format on } } // namespace /** * @a medfilt [ @e option ] [ @e infile ] * * - @b -l @e int * - length of vector @f$(1 \le M + 1)@f$ * - @b -m @e int * - order of vector @f$(0 \le M)@f$ * - @b -k @e int * - order of filter @f$(0 \le K)@f$ * - @b -w @e int * - way to apply filter * \arg @c 0 each dimension * \arg @c 1 across dimension * - @b -magic @e double * - magic number * - @b infile @e str * - double-type data sequence * - @b stdout * - double-type filtered data sequence * * @code{.sh} * echo 1 3 5 7 | x2x +ad | medfilt -w 0 -l 1 -k 2 | x2x +da * # 2 3 5 6 * @endcode * * @code{.sh} * echo 1 2 3 4 5 6 7 8 | x2x +ad | medfilt -w 0 -l 2 | x2x +da * # 2 3 3 4 5 6 6 7 * @endcode * * @code{.sh} * echo 1 2 3 4 5 6 7 8 | x2x +ad | medfilt -w 1 -l 2 | x2x +da * # 2.5 3.5 5.5 6.5 * @endcode * * @param[in] argc Number of arguments. * @param[in] argv Argument vector. * @return 0 on success, 1 on failure. */ int main(int argc, char* argv[]) { int num_input_order(kDefaultNumInputOrder); int num_filter_order(kDefaultNumFilterOrder); WaysToApplyFilter way_to_apply_filter(kDefaultWayToApplyFilter); double magic_number(0.0); bool is_magic_number_specified(false); const struct option long_options[] = { {"magic", required_argument, NULL, kMagic}, {0, 0, 0, 0}, }; for (;;) { const int option_char( getopt_long_only(argc, argv, "l:m:k:w:h", long_options, NULL)); if (-1 == option_char) break; switch (option_char) { case 'l': { if (!sptk::ConvertStringToInteger(optarg, &num_input_order) || num_input_order <= 0) { std::ostringstream error_message; error_message << "The argument for the -l option must be a positive integer"; sptk::PrintErrorMessage("medfilt", error_message); return 1; } --num_input_order; break; } case 'm': { if (!sptk::ConvertStringToInteger(optarg, &num_input_order) || num_input_order < 0) { std::ostringstream error_message; error_message << "The argument for the -m option must be a " << "non-negative integer"; sptk::PrintErrorMessage("medfilt", error_message); return 1; } break; } case 'k': { if (!sptk::ConvertStringToInteger(optarg, &num_filter_order) || num_filter_order < 0) { std::ostringstream error_message; error_message << "The argument for the -k option must be a " << "non-negative integer"; sptk::PrintErrorMessage("medfilt", error_message); return 1; } break; } case 'w': { const int min(0); const int max(static_cast<int>(kNumWaysToApplyFilter) - 1); int tmp; if (!sptk::ConvertStringToInteger(optarg, &tmp) || !sptk::IsInRange(tmp, min, max)) { std::ostringstream error_message; error_message << "The argument for the -w option must be an integer " << "in the range of " << min << " to " << max; sptk::PrintErrorMessage("medfilt", error_message); return 1; } way_to_apply_filter = static_cast<WaysToApplyFilter>(tmp); break; } case kMagic: { if (!sptk::ConvertStringToDouble(optarg, &magic_number)) { std::ostringstream error_message; error_message << "The argument for the -magic option must be a number"; sptk::PrintErrorMessage("medfilt", error_message); return 1; } is_magic_number_specified = true; break; } case 'h': { PrintUsage(&std::cout); return 0; } default: { PrintUsage(&std::cerr); return 1; } } } const int num_input_files(argc - optind); if (1 < num_input_files) { std::ostringstream error_message; error_message << "Too many input files"; sptk::PrintErrorMessage("medfilt", error_message); return 1; } const char* input_file(0 == num_input_files ? NULL : argv[optind]); if (!sptk::SetBinaryMode()) { std::ostringstream error_message; error_message << "Cannot set translation mode"; sptk::PrintErrorMessage("medfilt", error_message); return 1; } std::ifstream ifs; if (NULL != input_file) { ifs.open(input_file, std::ios::in | std::ios::binary); if (ifs.fail()) { std::ostringstream error_message; error_message << "Cannot open file " << input_file; sptk::PrintErrorMessage("medfilt", error_message); return 1; } } std::istream& input_stream(ifs.is_open() ? ifs : std::cin); const int input_length(num_input_order + 1); sptk::InputSourceFromStream input_source(false, input_length, &input_stream); sptk::MedianFilter median_filter(num_input_order, num_filter_order, &input_source, kEachDimension == way_to_apply_filter, is_magic_number_specified, magic_number); if (!median_filter.IsValid()) { std::ostringstream error_message; error_message << "Failed to initialize MedianFilter"; sptk::PrintErrorMessage("medfilt", error_message); return 1; } const int output_length(median_filter.GetSize()); std::vector<double> output(output_length); while (median_filter.Get(&output)) { if (!sptk::WriteStream(0, output_length, output, &std::cout, NULL)) { std::ostringstream error_message; error_message << "Failed to write output"; sptk::PrintErrorMessage("medfilt", error_message); return 1; } } return 0; }
[ "takenori.yoshimura24@gmail.com" ]
takenori.yoshimura24@gmail.com
38ad0a524f3f1825636efb6db5d01c7e0dc02884
fae26d601fe2b795fcd9ce40061bfb5db727ebf4
/113 - Power of Cryptography/main.cpp
36b9e6f041ddcc3e80d957fc6d55046c04aca2c1
[]
no_license
phg1024/UVa
5771caf2f9070abfab857b0b32db3a076fce7c3b
e27e4a67c80e716c87f266a68396ac5b5968345d
refs/heads/master
2020-04-11T05:40:30.107452
2014-07-17T07:49:33
2014-07-17T07:49:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
334
cpp
#include <iostream> #include <string> #include <algorithm> #include <functional> #include <vector> #include <cstring> #include <cstdio> #include <cstdlib> #include <cmath> using namespace std; int main() { double n, p; while (scanf("%lf%lf", &n, &p) != EOF) { printf("%.lf\n", pow(p, 1/n)); } return 0; }
[ "peihongguo@gmail.com" ]
peihongguo@gmail.com
27673be22bd2b5fd7f99c5cff6dec34f1e099a68
6525746e3478741d5658406b2a7b1df287b46288
/openFoam/heatTransfer/chtMultiRegionFoam/adjacentSolidFluid/constant/regionProperties
5117a9c318c0ae6fea7958d1fe6e84937e101f3e
[]
no_license
scramjetFoam/cfdCaseSetups
05a91228988a01feeca95676590fd0c3b7a60479
37bf3f07aae6e274133d1c9d289c43ebdd87d741
refs/heads/master
2023-07-06T02:57:54.810381
2020-11-05T15:42:20
2020-11-05T15:42:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
930
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: 5 | | \\ / A nd | Web: www.OpenFOAM.org | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class dictionary; location "constant"; object regionProperties; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // regions ( fluid (fluid) solid (solid) ); // ************************************************************************* //
[ "julian.toumey@uconn.edu" ]
julian.toumey@uconn.edu
1067ddb7df21bded743d2b43174c0de91b11d395
39209a3e9682981c10721480e367da0fc55896a9
/MoltenVK/MoltenVK/Utility/MVKVectorAllocator.h
442e0acac5d6bca33ab70630a21545fdb4c7e97d
[ "Apache-2.0", "LicenseRef-scancode-generic-cla" ]
permissive
DiegoAce/MoltenVK
f18d825659777eb4dd9cb0d0256373dc04905a28
ea0bbe57805b2459d8e15b1010186fa168788fa5
refs/heads/master
2020-04-12T17:40:11.739854
2018-12-21T02:08:54
2018-12-21T02:08:54
155,617,197
0
0
Apache-2.0
2018-10-31T20:10:14
2018-10-31T20:10:14
null
UTF-8
C++
false
false
14,548
h
/* * MVKVectorAllocator.h * * Copyright (c) 2012-2018 Dr. Torsten Hans (hans@ipacs.de) * * 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. */ #pragma once #include <new> #include <type_traits> namespace mvk_memory_allocator { inline char *alloc( const size_t num_bytes ) { return new char[num_bytes]; } inline void free( void *ptr ) { delete[] (char*)ptr; } }; ////////////////////////////////////////////////////////////////////////////////////////// // // mvk_vector_allocator_default -> malloc based allocator for MVKVector // ////////////////////////////////////////////////////////////////////////////////////////// template <typename T> class mvk_vector_allocator_default final { public: T *ptr; size_t num_elements_used; private: size_t num_elements_reserved; public: template<class S, class... Args> typename std::enable_if< !std::is_trivially_constructible<S>::value >::type construct( S *_ptr, Args&&... _args ) { new ( _ptr ) S( std::forward<Args>( _args )... ); } template<class S, class... Args> typename std::enable_if< std::is_trivially_constructible<S>::value >::type construct( S *_ptr, Args&&... _args ) { *_ptr = S( std::forward<Args>( _args )... ); } template<class S> typename std::enable_if< !std::is_trivially_destructible<S>::value >::type destruct( S *_ptr ) { _ptr->~S(); } template<class S> typename std::enable_if< std::is_trivially_destructible<S>::value >::type destruct( S *_ptr ) { } template<class S> typename std::enable_if< !std::is_trivially_destructible<S>::value >::type destruct_all() { for( size_t i = 0; i < num_elements_used; ++i ) { ptr[i].~S(); } num_elements_used = 0; } template<class S> typename std::enable_if< std::is_trivially_destructible<S>::value >::type destruct_all() { num_elements_used = 0; } public: constexpr mvk_vector_allocator_default() : ptr{ nullptr }, num_elements_used{ 0 }, num_elements_reserved{ 0 } { } mvk_vector_allocator_default( mvk_vector_allocator_default &&a ) : ptr{ a.ptr }, num_elements_used{ a.num_elements_used }, num_elements_reserved{ a.num_elements_reserved } { a.ptr = nullptr; a.num_elements_used = 0; a.num_elements_reserved = 0; } ~mvk_vector_allocator_default() { deallocate(); } size_t get_capacity() const { return num_elements_reserved; } void swap( mvk_vector_allocator_default &a ) { const auto copy_ptr = a.ptr; const auto copy_num_elements_used = a.num_elements_used; const auto copy_num_elements_reserved = a.num_elements_reserved; a.ptr = ptr; a.num_elements_used = num_elements_used; a.num_elements_reserved = num_elements_reserved; ptr = copy_ptr; num_elements_used = copy_num_elements_used; num_elements_reserved = copy_num_elements_reserved; } void allocate( const size_t num_elements_to_reserve ) { deallocate(); ptr = reinterpret_cast< T* >( mvk_memory_allocator::alloc( num_elements_to_reserve * sizeof( T ) ) ); num_elements_used = 0; num_elements_reserved = num_elements_to_reserve; } void re_allocate( const size_t num_elements_to_reserve ) { //if constexpr( std::is_trivially_copyable<T>::value ) //{ // ptr = reinterpret_cast< T* >( mvk_memory_allocator::tm_memrealloc( ptr, num_elements_to_reserve * sizeof( T ) ); //} //else { auto *new_ptr = reinterpret_cast< T* >( mvk_memory_allocator::alloc( num_elements_to_reserve * sizeof( T ) ) ); for( size_t i = 0; i < num_elements_used; ++i ) { construct( &new_ptr[i], std::move( ptr[i] ) ); destruct( &ptr[i] ); } //if ( ptr != nullptr ) { mvk_memory_allocator::free( ptr ); } ptr = new_ptr; } num_elements_reserved = num_elements_to_reserve; } void shrink_to_fit() { if( num_elements_used == 0 ) { deallocate(); } else { auto *new_ptr = reinterpret_cast< T* >( mvk_memory_allocator::alloc( num_elements_used * sizeof( T ) ) ); for( size_t i = 0; i < num_elements_used; ++i ) { construct( &new_ptr[i], std::move( ptr[i] ) ); destruct( &ptr[i] ); } mvk_memory_allocator::free( ptr ); ptr = new_ptr; num_elements_reserved = num_elements_used; } } void deallocate() { destruct_all<T>(); mvk_memory_allocator::free( ptr ); ptr = nullptr; num_elements_reserved = 0; } }; ////////////////////////////////////////////////////////////////////////////////////////// // // mvk_vector_allocator_with_stack -> malloc based MVKVector allocator with stack storage // ////////////////////////////////////////////////////////////////////////////////////////// template <typename T, int N> class mvk_vector_allocator_with_stack { public: T *ptr; size_t num_elements_used; private: //size_t num_elements_reserved; // uhh, num_elements_reserved is mapped onto the stack elements, let the fun begin alignas( alignof( T ) ) unsigned char elements_stack[N * sizeof( T )]; static_assert( N * sizeof( T ) >= sizeof( size_t ), "Bummer, nasty optimization doesn't work" ); void set_num_elements_reserved( const size_t num_elements_reserved ) { *reinterpret_cast< size_t* >( &elements_stack[0] ) = num_elements_reserved; } public: // // faster element construction and destruction using type traits // template<class S, class... Args> typename std::enable_if< !std::is_trivially_constructible<S, Args...>::value >::type construct( S *_ptr, Args&&... _args ) { new ( _ptr ) S( std::forward<Args>( _args )... ); } template<class S, class... Args> typename std::enable_if< std::is_trivially_constructible<S, Args...>::value >::type construct( S *_ptr, Args&&... _args ) { *_ptr = S( std::forward<Args>( _args )... ); } template<class S> typename std::enable_if< !std::is_trivially_destructible<S>::value >::type destruct( S *_ptr ) { _ptr->~S(); } template<class S> typename std::enable_if< std::is_trivially_destructible<S>::value >::type destruct( S *_ptr ) { } template<class S> typename std::enable_if< !std::is_trivially_destructible<S>::value >::type destruct_all() { for( size_t i = 0; i < num_elements_used; ++i ) { ptr[i].~S(); } num_elements_used = 0; } template<class S> typename std::enable_if< std::is_trivially_destructible<S>::value >::type destruct_all() { num_elements_used = 0; } template<class S> typename std::enable_if< !std::is_trivially_destructible<S>::value >::type swap_stack( mvk_vector_allocator_with_stack &a ) { T stack_copy[N]; for( size_t i = 0; i < num_elements_used; ++i ) { construct( &stack_copy[i], std::move( ptr[i] ) ); destruct( &ptr[i] ); } for( size_t i = 0; i < a.num_elements_used; ++i ) { construct( &ptr[i], std::move( a.ptr[i] ) ); destruct( &ptr[i] ); } for( size_t i = 0; i < num_elements_used; ++i ) { construct( &a.ptr[i], std::move( stack_copy[i] ) ); destruct( &stack_copy[i] ); } } template<class S> typename std::enable_if< std::is_trivially_destructible<S>::value >::type swap_stack( mvk_vector_allocator_with_stack &a ) { constexpr int STACK_SIZE = N * sizeof( T ); for( int i = 0; i < STACK_SIZE; ++i ) { const auto v = elements_stack[i]; elements_stack[i] = a.elements_stack[i]; a.elements_stack[i] = v; } } public: mvk_vector_allocator_with_stack() : ptr{ reinterpret_cast< T* >( &elements_stack[0] ) }, num_elements_used{ 0 } { } mvk_vector_allocator_with_stack( mvk_vector_allocator_with_stack &&a ) : num_elements_used{ a.num_elements_used } { // is a heap based -> steal ptr from a if( !a.get_data_on_stack() ) { ptr = a.ptr; set_num_elements_reserved( a.get_capacity() ); a.ptr = a.get_default_ptr(); } else { ptr = get_default_ptr(); for( size_t i = 0; i < a.num_elements_used; ++i ) { construct( &ptr[i], std::move( a.ptr[i] ) ); destruct( &a.ptr[i] ); } } a.num_elements_used = 0; } ~mvk_vector_allocator_with_stack() { deallocate(); } size_t get_capacity() const { return get_data_on_stack() ? N : *reinterpret_cast< const size_t* >( &elements_stack[0] ); } constexpr T *get_default_ptr() const { return reinterpret_cast< T* >( const_cast< unsigned char * >( &elements_stack[0] ) ); } bool get_data_on_stack() const { return ptr == get_default_ptr(); } void swap( mvk_vector_allocator_with_stack &a ) { // both allocators on heap -> easy case if( !get_data_on_stack() && !a.get_data_on_stack() ) { auto copy_ptr = ptr; auto copy_num_elements_reserved = get_capacity(); ptr = a.ptr; set_num_elements_reserved( a.get_capacity() ); a.ptr = copy_ptr; a.set_num_elements_reserved( copy_num_elements_reserved ); } // both allocators on stack -> just switch the stack contents else if( get_data_on_stack() && a.get_data_on_stack() ) { swap_stack<T>( a ); } else if( get_data_on_stack() && !a.get_data_on_stack() ) { auto copy_ptr = a.ptr; auto copy_num_elements_reserved = a.get_capacity(); a.ptr = a.get_default_ptr(); for( size_t i = 0; i < num_elements_used; ++i ) { construct( &a.ptr[i], std::move( ptr[i] ) ); destruct( &ptr[i] ); } ptr = copy_ptr; set_num_elements_reserved( copy_num_elements_reserved ); } else if( !get_data_on_stack() && a.get_data_on_stack() ) { auto copy_ptr = ptr; auto copy_num_elements_reserved = get_capacity(); ptr = get_default_ptr(); for( size_t i = 0; i < a.num_elements_used; ++i ) { construct( &ptr[i], std::move( a.ptr[i] ) ); destruct( &a.ptr[i] ); } a.ptr = copy_ptr; a.set_num_elements_reserved( copy_num_elements_reserved ); } auto copy_num_elements_used = num_elements_used; num_elements_used = a.num_elements_used; a.num_elements_used = copy_num_elements_used; } // // allocates rounded up to the defined alignment the number of bytes / if the system cannot allocate the specified amount of memory then a null block is returned // void allocate( const size_t num_elements_to_reserve ) { deallocate(); // check if enough memory on stack space is left if( num_elements_to_reserve <= N ) { return; } ptr = reinterpret_cast< T* >( mvk_memory_allocator::alloc( num_elements_to_reserve * sizeof( T ) ) ); num_elements_used = 0; set_num_elements_reserved( num_elements_to_reserve ); } //template<class S> typename std::enable_if< !std::is_trivially_copyable<S>::value >::type void _re_allocate( const size_t num_elements_to_reserve ) { auto *new_ptr = reinterpret_cast< T* >( mvk_memory_allocator::alloc( num_elements_to_reserve * sizeof( T ) ) ); for( size_t i = 0; i < num_elements_used; ++i ) { construct( &new_ptr[i], std::move( ptr[i] ) ); destruct( &ptr[i] ); } if( ptr != get_default_ptr() ) { mvk_memory_allocator::free( ptr ); } ptr = new_ptr; set_num_elements_reserved( num_elements_to_reserve ); } //template<class S> typename std::enable_if< std::is_trivially_copyable<S>::value >::type // _re_allocate( const size_t num_elements_to_reserve ) //{ // const bool data_is_on_stack = get_data_on_stack(); // // auto *new_ptr = reinterpret_cast< S* >( mvk_memory_allocator::tm_memrealloc( data_is_on_stack ? nullptr : ptr, num_elements_to_reserve * sizeof( S ) ) ); // if( data_is_on_stack ) // { // for( int i = 0; i < N; ++i ) // { // new_ptr[i] = ptr[i]; // } // } // // ptr = new_ptr; // set_num_elements_reserved( num_elements_to_reserve ); //} void re_allocate( const size_t num_elements_to_reserve ) { //TM_ASSERT( num_elements_to_reserve > get_capacity() ); if( num_elements_to_reserve > N ) { _re_allocate( num_elements_to_reserve ); } } void shrink_to_fit() { // nothing to do if data is on stack already if( get_data_on_stack() ) return; // move elements to stack space if( num_elements_used <= N ) { const auto num_elements_reserved = get_capacity(); auto *stack_ptr = get_default_ptr(); for( size_t i = 0; i < num_elements_used; ++i ) { construct( &stack_ptr[i], std::move( ptr[i] ) ); destruct( &ptr[i] ); } mvk_memory_allocator::free( ptr ); ptr = stack_ptr; } else { auto *new_ptr = reinterpret_cast< T* >( mvk_memory_allocator::alloc( ptr, num_elements_used * sizeof( T ) ) ); for( size_t i = 0; i < num_elements_used; ++i ) { construct( &new_ptr[i], std::move( ptr[i] ) ); destruct( &ptr[i] ); } mvk_memory_allocator::free( ptr ); ptr = new_ptr; set_num_elements_reserved( num_elements_used ); } } void deallocate() { destruct_all<T>(); if( !get_data_on_stack() ) { mvk_memory_allocator::free( ptr ); } ptr = get_default_ptr(); num_elements_used = 0; } };
[ "mail@ipacs.de" ]
mail@ipacs.de
179bdeffdcb807053a7afef67fa52e6d55e41f03
27894a9a992b507029228f8e5f096ae5a3ddd6d8
/OpenCLTestReduction/OpenCLTestReduction.cpp
6babab05da961911b50c5c533c6269569586ce9f
[]
no_license
asdlei99/OpenCLTest
09372934e9018ca2010d70d579ce228ad44ac118
89cf005b4108ac3ac8cada470d62fdfba82af64e
refs/heads/master
2020-09-26T12:46:21.984457
2016-12-24T12:09:06
2016-12-24T12:09:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
33,701
cpp
/***************************************************************************** * Copyright (c) 2013-2016 Intel Corporation * All rights reserved. * * WARRANTY DISCLAIMER * * THESE MATERIALS ARE 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 INTEL OR ITS * 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 THESE * MATERIALS, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Intel Corporation is the author of the Materials, and requests that all * problem reports or change requests be submitted to it directly *****************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <tchar.h> #include <memory.h> #include <vector> #include <algorithm> #include "CL\cl.h" #include "utils.h" #include "Template.cl" //for perf. counters #include <Windows.h> // Macros for OpenCL versions #define OPENCL_VERSION_1_2 1.2f #define OPENCL_VERSION_2_0 2.0f #define CLAMP(x, low, high) (((x) > (high))? (high) : ((x) < (low))? (low) : (x)) int ceil_int_div(int i, int div) { return (i + div - 1) / div; } int ceil_int(int i, int div) { return ceil_int_div(i, div) * div; } /* This function helps to create informative messages in * case when OpenCL errors occur. It returns a string * representation for an OpenCL error code. * (E.g. "CL_DEVICE_NOT_FOUND" instead of just -1.) */ const char* TranslateOpenCLError(cl_int errorCode) { switch (errorCode) { case CL_SUCCESS: return "CL_SUCCESS"; case CL_DEVICE_NOT_FOUND: return "CL_DEVICE_NOT_FOUND"; case CL_DEVICE_NOT_AVAILABLE: return "CL_DEVICE_NOT_AVAILABLE"; case CL_COMPILER_NOT_AVAILABLE: return "CL_COMPILER_NOT_AVAILABLE"; case CL_MEM_OBJECT_ALLOCATION_FAILURE: return "CL_MEM_OBJECT_ALLOCATION_FAILURE"; case CL_OUT_OF_RESOURCES: return "CL_OUT_OF_RESOURCES"; case CL_OUT_OF_HOST_MEMORY: return "CL_OUT_OF_HOST_MEMORY"; case CL_PROFILING_INFO_NOT_AVAILABLE: return "CL_PROFILING_INFO_NOT_AVAILABLE"; case CL_MEM_COPY_OVERLAP: return "CL_MEM_COPY_OVERLAP"; case CL_IMAGE_FORMAT_MISMATCH: return "CL_IMAGE_FORMAT_MISMATCH"; case CL_IMAGE_FORMAT_NOT_SUPPORTED: return "CL_IMAGE_FORMAT_NOT_SUPPORTED"; case CL_BUILD_PROGRAM_FAILURE: return "CL_BUILD_PROGRAM_FAILURE"; case CL_MAP_FAILURE: return "CL_MAP_FAILURE"; case CL_MISALIGNED_SUB_BUFFER_OFFSET: return "CL_MISALIGNED_SUB_BUFFER_OFFSET"; //-13 case CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST: return "CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST"; //-14 case CL_COMPILE_PROGRAM_FAILURE: return "CL_COMPILE_PROGRAM_FAILURE"; //-15 case CL_LINKER_NOT_AVAILABLE: return "CL_LINKER_NOT_AVAILABLE"; //-16 case CL_LINK_PROGRAM_FAILURE: return "CL_LINK_PROGRAM_FAILURE"; //-17 case CL_DEVICE_PARTITION_FAILED: return "CL_DEVICE_PARTITION_FAILED"; //-18 case CL_KERNEL_ARG_INFO_NOT_AVAILABLE: return "CL_KERNEL_ARG_INFO_NOT_AVAILABLE"; //-19 case CL_INVALID_VALUE: return "CL_INVALID_VALUE"; case CL_INVALID_DEVICE_TYPE: return "CL_INVALID_DEVICE_TYPE"; case CL_INVALID_PLATFORM: return "CL_INVALID_PLATFORM"; case CL_INVALID_DEVICE: return "CL_INVALID_DEVICE"; case CL_INVALID_CONTEXT: return "CL_INVALID_CONTEXT"; case CL_INVALID_QUEUE_PROPERTIES: return "CL_INVALID_QUEUE_PROPERTIES"; case CL_INVALID_COMMAND_QUEUE: return "CL_INVALID_COMMAND_QUEUE"; case CL_INVALID_HOST_PTR: return "CL_INVALID_HOST_PTR"; case CL_INVALID_MEM_OBJECT: return "CL_INVALID_MEM_OBJECT"; case CL_INVALID_IMAGE_FORMAT_DESCRIPTOR: return "CL_INVALID_IMAGE_FORMAT_DESCRIPTOR"; case CL_INVALID_IMAGE_SIZE: return "CL_INVALID_IMAGE_SIZE"; case CL_INVALID_SAMPLER: return "CL_INVALID_SAMPLER"; case CL_INVALID_BINARY: return "CL_INVALID_BINARY"; case CL_INVALID_BUILD_OPTIONS: return "CL_INVALID_BUILD_OPTIONS"; case CL_INVALID_PROGRAM: return "CL_INVALID_PROGRAM"; case CL_INVALID_PROGRAM_EXECUTABLE: return "CL_INVALID_PROGRAM_EXECUTABLE"; case CL_INVALID_KERNEL_NAME: return "CL_INVALID_KERNEL_NAME"; case CL_INVALID_KERNEL_DEFINITION: return "CL_INVALID_KERNEL_DEFINITION"; case CL_INVALID_KERNEL: return "CL_INVALID_KERNEL"; case CL_INVALID_ARG_INDEX: return "CL_INVALID_ARG_INDEX"; case CL_INVALID_ARG_VALUE: return "CL_INVALID_ARG_VALUE"; case CL_INVALID_ARG_SIZE: return "CL_INVALID_ARG_SIZE"; case CL_INVALID_KERNEL_ARGS: return "CL_INVALID_KERNEL_ARGS"; case CL_INVALID_WORK_DIMENSION: return "CL_INVALID_WORK_DIMENSION"; case CL_INVALID_WORK_GROUP_SIZE: return "CL_INVALID_WORK_GROUP_SIZE"; case CL_INVALID_WORK_ITEM_SIZE: return "CL_INVALID_WORK_ITEM_SIZE"; case CL_INVALID_GLOBAL_OFFSET: return "CL_INVALID_GLOBAL_OFFSET"; case CL_INVALID_EVENT_WAIT_LIST: return "CL_INVALID_EVENT_WAIT_LIST"; case CL_INVALID_EVENT: return "CL_INVALID_EVENT"; case CL_INVALID_OPERATION: return "CL_INVALID_OPERATION"; case CL_INVALID_GL_OBJECT: return "CL_INVALID_GL_OBJECT"; case CL_INVALID_BUFFER_SIZE: return "CL_INVALID_BUFFER_SIZE"; case CL_INVALID_MIP_LEVEL: return "CL_INVALID_MIP_LEVEL"; case CL_INVALID_GLOBAL_WORK_SIZE: return "CL_INVALID_GLOBAL_WORK_SIZE"; //-63 case CL_INVALID_PROPERTY: return "CL_INVALID_PROPERTY"; //-64 case CL_INVALID_IMAGE_DESCRIPTOR: return "CL_INVALID_IMAGE_DESCRIPTOR"; //-65 case CL_INVALID_COMPILER_OPTIONS: return "CL_INVALID_COMPILER_OPTIONS"; //-66 case CL_INVALID_LINKER_OPTIONS: return "CL_INVALID_LINKER_OPTIONS"; //-67 case CL_INVALID_DEVICE_PARTITION_COUNT: return "CL_INVALID_DEVICE_PARTITION_COUNT"; //-68 // case CL_INVALID_PIPE_SIZE: return "CL_INVALID_PIPE_SIZE"; //-69 // case CL_INVALID_DEVICE_QUEUE: return "CL_INVALID_DEVICE_QUEUE"; //-70 default: return "UNKNOWN ERROR CODE"; } } /* Convenient container for all OpenCL specific objects used in the sample * * It consists of two parts: * - regular OpenCL objects which are used in almost each normal OpenCL applications * - several OpenCL objects that are specific for this particular sample * * You collect all these objects in one structure for utility purposes * only, there is no OpenCL specific here: just to avoid global variables * and make passing all these arguments in functions easier. */ struct ocl_args_d_t { ocl_args_d_t(); ~ocl_args_d_t(); // Regular OpenCL objects: cl_context context; // hold the context handler cl_device_id device; // hold the selected device handler cl_command_queue commandQueue; // hold the commands-queue handler cl_program program; // hold the program handler cl_kernel kernel; // hold the kernel handler float platformVersion; // hold the OpenCL platform version (default 1.2) float deviceVersion; // hold the OpenCL device version (default. 1.2) float compilerVersion; // hold the device OpenCL C version (default. 1.2) // Objects that are specific for algorithm implemented in this sample cl_mem srcMem; // hold first source buffer cl_mem dstMem; // hold destination buffer }; ocl_args_d_t::ocl_args_d_t() : context(NULL), device(NULL), commandQueue(NULL), program(NULL), kernel(NULL), platformVersion(OPENCL_VERSION_1_2), deviceVersion(OPENCL_VERSION_1_2), compilerVersion(OPENCL_VERSION_1_2), srcMem(NULL), dstMem(NULL) { } /* * destructor - called only once * Release all OpenCL objects * This is a regular sequence of calls to deallocate all created OpenCL resources in bootstrapOpenCL. * * You may want to call these deallocation procedures in the middle of your application execution * (not at the end) if you don't further need OpenCL runtime. * You may want to do that in order to free some memory, for example, * or recreate OpenCL objects with different parameters. * */ ocl_args_d_t::~ocl_args_d_t() { cl_int err = CL_SUCCESS; if (kernel) { err = clReleaseKernel(kernel); if (CL_SUCCESS != err) { LogError("Error: clReleaseKernel returned '%s'.\n", TranslateOpenCLError(err)); } } if (program) { err = clReleaseProgram(program); if (CL_SUCCESS != err) { LogError("Error: clReleaseProgram returned '%s'.\n", TranslateOpenCLError(err)); } } if (srcMem) { err = clReleaseMemObject(srcMem); if (CL_SUCCESS != err) { LogError("Error: clReleaseMemObject returned '%s'.\n", TranslateOpenCLError(err)); } } if (dstMem) { err = clReleaseMemObject(dstMem); if (CL_SUCCESS != err) { LogError("Error: clReleaseMemObject returned '%s'.\n", TranslateOpenCLError(err)); } } if (commandQueue) { err = clReleaseCommandQueue(commandQueue); if (CL_SUCCESS != err) { LogError("Error: clReleaseCommandQueue returned '%s'.\n", TranslateOpenCLError(err)); } } if (device) { err = clReleaseDevice(device); if (CL_SUCCESS != err) { LogError("Error: clReleaseDevice returned '%s'.\n", TranslateOpenCLError(err)); } } if (context) { err = clReleaseContext(context); if (CL_SUCCESS != err) { LogError("Error: clReleaseContext returned '%s'.\n", TranslateOpenCLError(err)); } } /* * Note there is no procedure to deallocate platform * because it was not created at the startup, * but just queried from OpenCL runtime. */ } /* * Check whether an OpenCL platform is the required platform * (based on the platform's name) */ bool CheckPreferredPlatformMatch(cl_platform_id platform, const char* preferredPlatform) { size_t stringLength = 0; cl_int err = CL_SUCCESS; bool match = false; // In order to read the platform's name, we first read the platform's name string length (param_value is NULL). // The value returned in stringLength err = clGetPlatformInfo(platform, CL_PLATFORM_NAME, 0, NULL, &stringLength); if (CL_SUCCESS != err) { LogError("Error: clGetPlatformInfo() to get CL_PLATFORM_NAME length returned '%s'.\n", TranslateOpenCLError(err)); return false; } // Now, that we know the platform's name string length, we can allocate enough space before read it std::vector<char> platformName(stringLength); // Read the platform's name string // The read value returned in platformName err = clGetPlatformInfo(platform, CL_PLATFORM_NAME, stringLength, &platformName[0], NULL); if (CL_SUCCESS != err) { LogError("Error: clGetplatform_ids() to get CL_PLATFORM_NAME returned %s.\n", TranslateOpenCLError(err)); return false; } // Now check if the platform's name is the required one if (strstr(&platformName[0], preferredPlatform) != 0) { // The checked platform is the one we're looking for match = true; } return match; } /* * Find and return the preferred OpenCL platform * In case that preferredPlatform is NULL, the ID of the first discovered platform will be returned */ cl_platform_id FindOpenCLPlatform(const char* preferredPlatform, cl_device_type deviceType) { cl_uint numPlatforms = 0; cl_int err = CL_SUCCESS; // Get (in numPlatforms) the number of OpenCL platforms available // No platform ID will be return, since platforms is NULL err = clGetPlatformIDs(0, NULL, &numPlatforms); if (CL_SUCCESS != err) { LogError("Error: clGetplatform_ids() to get num platforms returned %s.\n", TranslateOpenCLError(err)); return NULL; } LogInfo("Number of available platforms: %u\n", numPlatforms); if (0 == numPlatforms) { LogError("Error: No platforms found!\n"); return NULL; } std::vector<cl_platform_id> platforms(numPlatforms); // Now, obtains a list of numPlatforms OpenCL platforms available // The list of platforms available will be returned in platforms err = clGetPlatformIDs(numPlatforms, &platforms[0], NULL); if (CL_SUCCESS != err) { LogError("Error: clGetplatform_ids() to get platforms returned %s.\n", TranslateOpenCLError(err)); return NULL; } // Check if one of the available platform matches the preferred requirements for (cl_uint i = 0; i < numPlatforms; i++) { bool match = true; cl_uint numDevices = 0; // If the preferredPlatform is not NULL then check if platforms[i] is the required one // Otherwise, continue the check with platforms[i] if ((NULL != preferredPlatform) && (strlen(preferredPlatform) > 0)) { // In case we're looking for a specific platform match = CheckPreferredPlatformMatch(platforms[i], preferredPlatform); } // match is true if the platform's name is the required one or don't care (NULL) if (match) { // Obtains the number of deviceType devices available on platform // When the function failed we expect numDevices to be zero. // We ignore the function return value since a non-zero error code // could happen if this platform doesn't support the specified device type. err = clGetDeviceIDs(platforms[i], deviceType, 0, NULL, &numDevices); if (CL_SUCCESS != err) { LogError("clGetDeviceIDs() returned %s.\n", TranslateOpenCLError(err)); } if (0 != numDevices) { // There is at list one device that answer the requirements return platforms[i]; } } } return NULL; } /* * This function read the OpenCL platdorm and device versions * (using clGetxxxInfo API) and stores it in the ocl structure. * Later it will enable us to support both OpenCL 1.2 and 2.0 platforms and devices * in the same program. */ int GetPlatformAndDeviceVersion(cl_platform_id platformId, ocl_args_d_t *ocl) { cl_int err = CL_SUCCESS; // Read the platform's version string length (param_value is NULL). // The value returned in stringLength size_t stringLength = 0; err = clGetPlatformInfo(platformId, CL_PLATFORM_VERSION, 0, NULL, &stringLength); if (CL_SUCCESS != err) { LogError("Error: clGetPlatformInfo() to get CL_PLATFORM_VERSION length returned '%s'.\n", TranslateOpenCLError(err)); return err; } // Now, that we know the platform's version string length, we can allocate enough space before read it std::vector<char> platformVersion(stringLength); // Read the platform's version string // The read value returned in platformVersion err = clGetPlatformInfo(platformId, CL_PLATFORM_VERSION, stringLength, &platformVersion[0], NULL); if (CL_SUCCESS != err) { LogError("Error: clGetplatform_ids() to get CL_PLATFORM_VERSION returned %s.\n", TranslateOpenCLError(err)); return err; } if (strstr(&platformVersion[0], "OpenCL 2.0") != NULL) { ocl->platformVersion = OPENCL_VERSION_2_0; } // Read the device's version string length (param_value is NULL). err = clGetDeviceInfo(ocl->device, CL_DEVICE_VERSION, 0, NULL, &stringLength); if (CL_SUCCESS != err) { LogError("Error: clGetDeviceInfo() to get CL_DEVICE_VERSION length returned '%s'.\n", TranslateOpenCLError(err)); return err; } // Now, that we know the device's version string length, we can allocate enough space before read it std::vector<char> deviceVersion(stringLength); // Read the device's version string // The read value returned in deviceVersion err = clGetDeviceInfo(ocl->device, CL_DEVICE_VERSION, stringLength, &deviceVersion[0], NULL); if (CL_SUCCESS != err) { LogError("Error: clGetDeviceInfo() to get CL_DEVICE_VERSION returned %s.\n", TranslateOpenCLError(err)); return err; } if (strstr(&deviceVersion[0], "OpenCL 2.0") != NULL) { ocl->deviceVersion = OPENCL_VERSION_2_0; } // Read the device's OpenCL C version string length (param_value is NULL). err = clGetDeviceInfo(ocl->device, CL_DEVICE_OPENCL_C_VERSION, 0, NULL, &stringLength); if (CL_SUCCESS != err) { LogError("Error: clGetDeviceInfo() to get CL_DEVICE_OPENCL_C_VERSION length returned '%s'.\n", TranslateOpenCLError(err)); return err; } // Now, that we know the device's OpenCL C version string length, we can allocate enough space before read it std::vector<char> compilerVersion(stringLength); // Read the device's OpenCL C version string // The read value returned in compilerVersion err = clGetDeviceInfo(ocl->device, CL_DEVICE_OPENCL_C_VERSION, stringLength, &compilerVersion[0], NULL); if (CL_SUCCESS != err) { LogError("Error: clGetDeviceInfo() to get CL_DEVICE_OPENCL_C_VERSION returned %s.\n", TranslateOpenCLError(err)); return err; } else if (strstr(&compilerVersion[0], "OpenCL C 2.0") != NULL) { ocl->compilerVersion = OPENCL_VERSION_2_0; } return err; } /* * Generate random value for input buffers */ void generateInput(cl_float* inputArray, int nSize) { srand(12345); // random initialization of input for (int i = 0; i < nSize; i++) { inputArray[i] = (float)rand() / RAND_MAX; } } /* * This function picks/creates necessary OpenCL objects which are needed. * The objects are: * OpenCL platform, device, context, and command queue. * * All these steps are needed to be performed once in a regular OpenCL application. * This happens before actual compute kernels calls are performed. * * For convenience, in this application you store all those basic OpenCL objects in structure ocl_args_d_t, * so this function populates fields of this structure, which is passed as parameter ocl. * Please, consider reviewing the fields before going further. * The structure definition is right in the beginning of this file. */ int SetupOpenCL(ocl_args_d_t *ocl, cl_device_type deviceType) { // The following variable stores return codes for all OpenCL calls. cl_int err = CL_SUCCESS; // Query for all available OpenCL platforms on the system // Here you enumerate all platforms and pick one which name has preferredPlatform as a sub-string cl_platform_id platformId = FindOpenCLPlatform("Intel", deviceType); if (NULL == platformId) { LogError("Error: Failed to find OpenCL platform.\n"); return CL_INVALID_VALUE; } // Create context with device of specified type. // Required device type is passed as function argument deviceType. // So you may use this function to create context for any CPU or GPU OpenCL device. // The creation is synchronized (pfn_notify is NULL) and NULL user_data cl_context_properties contextProperties[] = { CL_CONTEXT_PLATFORM, (cl_context_properties)platformId, 0 }; ocl->context = clCreateContextFromType(contextProperties, deviceType, NULL, NULL, &err); if ((CL_SUCCESS != err) || (NULL == ocl->context)) { LogError("Couldn't create a context, clCreateContextFromType() returned '%s'.\n", TranslateOpenCLError(err)); return err; } // Query for OpenCL device which was used for context creation err = clGetContextInfo(ocl->context, CL_CONTEXT_DEVICES, sizeof(cl_device_id), &ocl->device, NULL); if (CL_SUCCESS != err) { LogError("Error: clGetContextInfo() to get list of devices returned %s.\n", TranslateOpenCLError(err)); return err; } // Read the OpenCL platform's version and the device OpenCL and OpenCL C versions GetPlatformAndDeviceVersion(platformId, ocl); // Create command queue. // OpenCL kernels are enqueued for execution to a particular device through special objects called command queues. // Command queue guarantees some ordering between calls and other OpenCL commands. // Here you create a simple in-order OpenCL command queue that doesn't allow execution of two kernels in parallel on a target device. #ifdef CL_VERSION_2_0 if (OPENCL_VERSION_2_0 == ocl->deviceVersion) { const cl_command_queue_properties properties[] ={ CL_QUEUE_PROPERTIES, CL_QUEUE_PROFILING_ENABLE, 0 }; ocl->commandQueue = clCreateCommandQueueWithProperties(ocl->context, ocl->device, properties, &err); } else { // default behavior: OpenCL 1.2 cl_command_queue_properties properties = CL_QUEUE_PROFILING_ENABLE; ocl->commandQueue = clCreateCommandQueue(ocl->context, ocl->device, properties, &err); } #else // default behavior: OpenCL 1.2 cl_command_queue_properties properties = CL_QUEUE_PROFILING_ENABLE; ocl->commandQueue = clCreateCommandQueue(ocl->context, ocl->device, properties, &err); #endif if (CL_SUCCESS != err) { LogError("Error: clCreateCommandQueue() returned %s.\n", TranslateOpenCLError(err)); return err; } return CL_SUCCESS; } /* * Create and build OpenCL program from its source code */ int CreateAndBuildProgram(ocl_args_d_t *ocl) { cl_int err = CL_SUCCESS; HMODULE hmodule = GetModuleHandle(NULL); HRSRC hresource = nullptr; HGLOBAL hresource_data = nullptr; const char *source = nullptr; size_t src_size = 0; if ( nullptr == (hresource = FindResource(hmodule, L"CLDATA", L"KERNEL_DATA")) || nullptr == (hresource_data = LoadResource(hmodule, hresource)) || nullptr == (source = (const char *)LockResource(hresource_data)) || 0 == (src_size = SizeofResource(hmodule, hresource))) { return CL_INVALID_VALUE; } ocl->program = clCreateProgramWithSource(ocl->context, 1, (const char**)&source, &src_size, &err); if (CL_SUCCESS != err) { LogError("Error: clCreateProgramWithSource returned %s.\n", TranslateOpenCLError(err)); return err; } // Build the program // During creation a program is not built. You need to explicitly call build function. // Here you just use create-build sequence, // but there are also other possibilities when program consist of several parts, // some of which are libraries, and you may want to consider using clCompileProgram and clLinkProgram as // alternatives. std::string options = ""; err = clBuildProgram(ocl->program, 1, &ocl->device, options.c_str(), NULL, NULL); if (CL_SUCCESS != err) { LogError("Error: clBuildProgram() for source program returned %s.\n", TranslateOpenCLError(err)); // In case of error print the build log to the standard output // First check the size of the log // Then allocate the memory and obtain the log from the program if (err == CL_BUILD_PROGRAM_FAILURE) { size_t log_size = 0; clGetProgramBuildInfo(ocl->program, ocl->device, CL_PROGRAM_BUILD_LOG, 0, NULL, &log_size); std::vector<char> build_log(log_size); clGetProgramBuildInfo(ocl->program, ocl->device, CL_PROGRAM_BUILD_LOG, log_size, &build_log[0], NULL); LogError("Error happened during the build of OpenCL program.\nBuild log:%s", &build_log[0]); } } return err; } /* * Create OpenCL buffers from host memory * These buffers will be used later by the OpenCL kernel */ int CreateBufferArguments(ocl_args_d_t *ocl, cl_float* input, cl_float* output, int nSize, int nDstSize) { cl_int err = CL_SUCCESS; ocl->srcMem = clCreateBuffer(ocl->context, CL_MEM_READ_ONLY | CL_MEM_USE_HOST_PTR, sizeof(cl_float) * nSize, input, &err); if (CL_SUCCESS != err) { LogError("Error: clCreateBuffer for srcMem returned %s\n", TranslateOpenCLError(err)); return err; } ocl->dstMem = clCreateBuffer(ocl->context, CL_MEM_WRITE_ONLY | CL_MEM_USE_HOST_PTR, sizeof(cl_float) * nDstSize, output, &err); if (CL_SUCCESS != err) { LogError("Error: clCreateBuffer for dstMem returned %s\n", TranslateOpenCLError(err)); return err; } return CL_SUCCESS; } /* * Set kernel arguments */ cl_uint SetKernelArguments(ocl_args_d_t *ocl, int nSize) { cl_int err = CL_SUCCESS; err = clSetKernelArg(ocl->kernel, 0, sizeof(cl_mem), (void *)&ocl->srcMem); if (CL_SUCCESS != err) { LogError("error: Failed to set argument srcMem, returned %s\n", TranslateOpenCLError(err)); return err; } err = clSetKernelArg(ocl->kernel, 1, sizeof(cl_mem), (void *)&ocl->dstMem); if (CL_SUCCESS != err) { LogError("Error: Failed to set argument dstMem, returned %s\n", TranslateOpenCLError(err)); return err; } err = clSetKernelArg(ocl->kernel, 2, sizeof(cl_int), (void *)&nSize); if (CL_SUCCESS != err) { LogError("Error: Failed to set argument arrayWidth, returned %s\n", TranslateOpenCLError(err)); return err; } return err; } /* * Execute the kernel */ cl_uint ExecuteAddKernel(ocl_args_d_t *ocl, int nSize) { cl_int err = CL_SUCCESS; // Define global iteration space for clEnqueueNDRangeKernel. size_t localWorkSize[2] = { GROUP_SIZE, 0 }; size_t globalWorkSize[2] = { ceil_int(nSize, localWorkSize[0]), 0 }; // execute kernel err = clEnqueueNDRangeKernel(ocl->commandQueue, ocl->kernel, 1, NULL, globalWorkSize, localWorkSize, 0, NULL, NULL); if (CL_SUCCESS != err) { LogError("Error: Failed to run kernel, return %s\n", TranslateOpenCLError(err)); return err; } return CL_SUCCESS; } /* * "Read" the result buffer (mapping the buffer to the host memory address) */ bool ReadAndVerify(ocl_args_d_t *ocl, float cpu_sum, int nSize) { cl_int err = CL_SUCCESS; bool result = true; cl_float *ptrMapped = (cl_float *)clEnqueueMapBuffer(ocl->commandQueue, ocl->dstMem, CL_FALSE, CL_MAP_READ, 0, sizeof(cl_float) * nSize, 0, NULL, NULL, &err); if (CL_SUCCESS != err) { LogError("Error: clEnqueueMapBuffer for ocl->dstMem returned %s\n", TranslateOpenCLError(err)); } // Call clFinish to guarantee that output region is updated err = clFinish(ocl->commandQueue); if (CL_SUCCESS != err) { LogError("Error: clFinish returned %s\n", TranslateOpenCLError(err)); } float gpu_sum = 0.0f; for (int i = 0; i < nSize; i++) { gpu_sum += ptrMapped[i]; } if (std::abs((cpu_sum - gpu_sum) / cpu_sum) > 1e-5) { LogError("Verification failed: %e:%e\n", cpu_sum, gpu_sum); result = false; } err = clEnqueueUnmapMemObject(ocl->commandQueue, ocl->dstMem, ptrMapped, 0, NULL, NULL); if (CL_SUCCESS != err) { LogError("Error: clEnqueueUnmapMemObject for ocl->dstMem returned %s\n", TranslateOpenCLError(err)); } err = clFinish(ocl->commandQueue); if (CL_SUCCESS != err) { LogError("Error: clFinish returned %s\n", TranslateOpenCLError(err)); } return result; } /* * main execution routine * Basically it consists of three parts: * - generating the inputs * - running OpenCL kernel * - reading results of processing */ int _tmain(int argc, TCHAR* argv[]) { cl_int err; ocl_args_d_t ocl; cl_device_type deviceType = CL_DEVICE_TYPE_GPU; LARGE_INTEGER perfFrequency; LARGE_INTEGER performanceCountNDRangeStart; LARGE_INTEGER performanceCountNDRangeStop; int nSize = 4 * 1024 * 1024; //initialize Open CL objects (context, queue, etc.) if (CL_SUCCESS != SetupOpenCL(&ocl, deviceType)) { return -1; } // allocate working buffers. cl_float* input = (cl_float*)_aligned_malloc(sizeof(cl_float) * nSize, 4096); cl_float* output = (cl_float*)_aligned_malloc(sizeof(cl_float) * nSize / GROUP_SIZE, 4096); if (NULL == input || NULL == output) { LogError("Error: _aligned_malloc failed to allocate buffers.\n"); return -1; } // Create and build the OpenCL program if (CL_SUCCESS != CreateAndBuildProgram(&ocl)) { return -1; } // Program consists of kernels. // Each kernel can be called (enqueued) from the host part of OpenCL application. // To call the kernel, you need to create it from existing program. ocl.kernel = clCreateKernel(ocl.program, "reduce_add", &err); if (CL_SUCCESS != err) { LogError("Error: clCreateKernel returned %s\n", TranslateOpenCLError(err)); return -1; } // Create OpenCL buffers from host memory // These buffers will be used later by the OpenCL kernel if (CL_SUCCESS != CreateBufferArguments(&ocl, input, output, nSize, nSize / GROUP_SIZE)) { return -1; } //random input cl_float *ptrMapped = (cl_float *)clEnqueueMapBuffer(ocl.commandQueue, ocl.srcMem, CL_FALSE, CL_MAP_WRITE, 0, sizeof(cl_float) * nSize, 0, NULL, NULL, &err); if (CL_SUCCESS != err) { LogError("Error: clEnqueueMapBuffer for ocl->srcMem returned %s\n", TranslateOpenCLError(err)); return -1; } err = clFinish(ocl.commandQueue); generateInput(ptrMapped, nSize); float cpu_sum = 0.0f; for (int i = 0; i < nSize; i++) { cpu_sum += ptrMapped[i]; } err = clEnqueueUnmapMemObject(ocl.commandQueue, ocl.srcMem, ptrMapped, 0, NULL, NULL); if (CL_SUCCESS != err) { LogError("Error: clEnqueueUnmapMemObject for ocl->srcMem returned %s\n", TranslateOpenCLError(err)); return err; } err = clFinish(ocl.commandQueue); if (CL_SUCCESS != err) { LogError("Error: clFinish returned %s\n", TranslateOpenCLError(err)); } bool queueProfilingEnable = true; for (;;) { // Passing arguments into OpenCL kernel. if (CL_SUCCESS != SetKernelArguments(&ocl, nSize)) { return -1; } // Regularly you wish to use OpenCL in your application to achieve greater performance results // that are hard to achieve in other ways. // To understand those performance benefits you may want to measure time your application spent in OpenCL kernel execution. // The recommended way to obtain this time is to measure interval between two moments: // - just before clEnqueueNDRangeKernel is called, and // - just after clFinish is called // clFinish is necessary to measure entire time spending in the kernel, measuring just clEnqueueNDRangeKernel is not enough, // because this call doesn't guarantees that kernel is finished. // clEnqueueNDRangeKernel is just enqueue new command in OpenCL command queue and doesn't wait until it ends. // clFinish waits until all commands in command queue are finished, that suits your need to measure time. if (queueProfilingEnable) QueryPerformanceCounter(&performanceCountNDRangeStart); // Execute (enqueue) the kernel if (CL_SUCCESS != ExecuteAddKernel(&ocl, nSize)) { return -1; } if (queueProfilingEnable) QueryPerformanceCounter(&performanceCountNDRangeStop); nSize /= GROUP_SIZE; if (nSize < GROUP_SIZE) { break; } std::swap(ocl.srcMem, ocl.dstMem); } // The last part of this function: getting processed results back. // use map-unmap sequence to update original memory area with output buffer. ReadAndVerify(&ocl, cpu_sum, nSize); // retrieve performance counter frequency if (queueProfilingEnable) { QueryPerformanceFrequency(&perfFrequency); LogInfo("NDRange performance counter time %f ms.\n", 1000.0f*(float)(performanceCountNDRangeStop.QuadPart - performanceCountNDRangeStart.QuadPart) / (float)perfFrequency.QuadPart); } _aligned_free(input); _aligned_free(output); //情報を収集できるよう待機する Sleep(5000); return 0; }
[ "rigaya34589@live.jp" ]
rigaya34589@live.jp
33dc5e5a5f243645a7ae1db20fa6c1da925034d2
a3ac029ab1930d0d4523cbed51393ea8adfe61ee
/source/xml2md.cpp
7f01af9bcb078798e7af9daaf554052bc0f8d6a9
[]
no_license
shawnpringle/steemedit
96993b5d314c4ac908970ff44a7e304d7b95ae3b
aee13b2c69a1429dcd698bf1386f112858ee26d7
refs/heads/master
2021-01-12T11:08:46.630728
2017-06-10T22:16:48
2017-06-10T22:16:48
72,844,804
0
0
null
null
null
null
UTF-8
C++
false
false
21,321
cpp
#include <wx/mstream.h> #include <iostream> #include "popcorn_wxstring.h" #include <utility> #include <wx/xml/xml.h> #include <string> #include "image_locations.h" #include "xml2md.h" #include <boost/locale.hpp> #include "trash.h" #include "bug_exception.h" #include <signal.h> #include "utf.h" using namespace std; // Should be used for turning text as it is in the XML file into equivalent mark down. // This means the user writes something like *see*, that is exactly what should appear // on the website. wxString md_escape(const wxString& in) { // this is a stub for now. return in; } std::pair<bool, wxString> XMLFile2MDFile(const wxImageTowxStringMap& themap, const wxString XML_filename, const wxString MD_filename) { wxFileInputStream XML_stream(XML_filename); wxFileOutputStream MD_stream(MD_filename); std::pair<bool, wxString> r = XMLFile2MDFile(themap, XML_stream, MD_stream); if (!r.first) { // TO DO: Should delete 'MD_filename' } return r; } static bool time_is_up(false); static const wxString font_weight_name = wxT("fontweight"); static const wxString font_style_name = wxT("fontstyle"); static const wxString font_size_name = #if wxMAJOR_VERSION < 3 wxT("fontsize"); #else wxT("fontpointsize"); #endif struct EggTimer { EggTimer(size_t time) { seassert(time != 0); time_is_up = false; #if !defined(_WIN32) && !defined(NDEBUG) alarm(time); signal(SIGALRM, [](int) { time_is_up = true; }); #endif // _WIN32 } ~EggTimer() { #if !defined(_WIN32) && !defined(NDEBUG) alarm(0); #endif // _WIN32 } }; static long getNumericalProperty(wxXmlNode * node, const wxString name, const long default_p) { wxString out; if (node->GetPropVal(name, &out)) { long temporary; if (out.ToLong(&temporary)) return temporary; } return default_p; } std::bad_alloc bae; /*** * Routine reads the contents of the XML_istream converts it to mark down and writes it to MD_ostream. The inline image data is replaced with URLs found in //themap//. * The XML stream shall be in ASCII encoding^^1^^ * The MD file stream shall be a UTF-8 encoding. Assumption: The file consists of text paragraphs and images only. Assumption: MD_ostream is always writable or it is somehow bad. 1. XML files use an encoding scheme to allow any Unicode character yet it is still in ASCII. Like ASCII HTML pages, arbitrary Unicode characters can be specified using HTML entities (which are expressed in ASCII). ****/ std::pair<bool, wxString> XMLFile2MDFile(const wxImageTowxStringMap& themap, wxInputStream& XML_istream, wxOutputStream& MD_utf8_ostream) { // Because it is convenient to work with 32-bit characters rather than utf-8 byte characters, the string gets // converted to a byte string at the very end of the translation process. wxXmlDocument doc; #if !defined(_WIN32) && !defined(NDEBUG) EggTimer et(5); #endif // WIN32_ try { if (!doc.Load(XML_istream)) { return std::make_pair(false,wxT("stream is not valid XML.")); } // start processing the XML file if (doc.GetRoot()->GetName() != wxT("richtext")) { return std::make_pair<bool, wxString>(false, wxT("richtext tag not found.")); } // XmlNode strings are 32-bit word strings (wxString)s rather than byte strings. wxXmlNode * paragraph_layout = doc.GetRoot()->GetChildren(); if (paragraph_layout == nullptr || paragraph_layout->GetName() != wxT("paragraphlayout")) { return std::make_pair<bool, wxString>(false, wxT("paragraphlayout tag not found.")); } const long normal_font_weight = getNumericalProperty(paragraph_layout, font_weight_name, 0); if (normal_font_weight == 0) { runtime_error e("Missing fontweight property."); throw e; } long * normal_font_style_ptr = nullptr; { long tmp_fs = getNumericalProperty(paragraph_layout, font_style_name, 0); if (tmp_fs != 0) normal_font_style_ptr = new long(tmp_fs); } if (normal_font_style_ptr == nullptr) { runtime_error e("Missing fontstyle property"); throw e; } //long font_style = normal_font_style; const long normal_font_size = getNumericalProperty(paragraph_layout, font_size_name, 0); if (normal_font_size == 0) { runtime_error e("Missing fontsize property."); throw e; } long font_size = normal_font_size; wxStringOutputStream MD_ostream; for (wxXmlNode * paragraph_node = paragraph_layout->GetChildren(); paragraph_node != nullptr && !time_is_up; paragraph_node = paragraph_node->GetNext()) { if (paragraph_node->GetName() != wxT("paragraph")) { return std::make_pair(false, wxT("Illegal tag found :") + paragraph_node->GetName()); } font_size = getNumericalProperty(paragraph_node, font_size_name, normal_font_size); wxXmlNode * paragraph_child = paragraph_node->GetChildren(); wxString name; if (paragraph_child != nullptr && (font_size = getNumericalProperty(paragraph_child, font_size_name, font_size)) != normal_font_size && paragraph_child->GetNodeContent().length() > 0 ) { if (font_size == 125 * normal_font_size / 64) { MD_ostream.PutC('#'); } if (font_size == 25 * normal_font_size / 16) { MD_ostream.PutC('#'); MD_ostream.PutC('#'); } if (font_size == 5 * normal_font_size / 4) { MD_ostream.PutC('#'); MD_ostream.PutC('#'); MD_ostream.PutC('#'); } if (font_size != normal_font_size) { MD_ostream.PutC(' '); } } // true if we must add a space to prevent problems with the interpreters of MD bool must_space(false); for ( ; paragraph_child != nullptr && !time_is_up; paragraph_child = paragraph_child->GetNext()) { // process text enclosed by <tag1></tag1> wxString name = paragraph_child->GetName(), weight_string; if (name == wxT("text")) { wxString * url_ptr; wxString url; if (paragraph_child->GetPropVal(wxT("url"), url_ptr = &url)) { MD_ostream.PutC('['); } else { url_ptr = nullptr; } wxString bare_content = paragraph_child->GetNodeContent(); if (bare_content.length() > 0 && bare_content.at(0) == '\"') { seassert(bare_content.length() > 1); bare_content = bare_content(1,bare_content.length()-2); } //bare_content = bare_content.Right(bare_content.length()-1); //bare_content = bare_content.Left(bare_content.length()-1); const wxString escaped_content = md_escape(bare_content); const bool is_bold = getNumericalProperty(paragraph_child, font_weight_name, normal_font_weight) > normal_font_weight; bool is_italic; if (normal_font_style_ptr != nullptr) is_italic = getNumericalProperty(paragraph_child, font_style_name, *normal_font_style_ptr) != *normal_font_style_ptr; else is_italic = false; // Mark down needs that the following character of these formatting // marks be next to characters that are not spaces. { // ("?)[ \t]*([^ \t].*[^ \t])[ \t]*\1 // ^ ^ ^ ^ // | | | | // after_quote_i; | | // | | | // first_non_whitespace_i; | // | | // last_non_whitespace_i; | // after_last_i; // <--------+ const size_t after_quote_i = 0; const size_t after_last_i = escaped_content.length(); size_t temp = escaped_content.find_first_not_of(wxT(" \t"), after_quote_i, after_last_i - after_quote_i + 1); const size_t first_non_whitespace_i = temp == string::npos ? after_last_i + 1 : temp; const size_t last_non_whitespace_i = escaped_content.find_last_not_of(wxT(" \t")); // first add the white space at the beginning to the stream if (must_space && after_quote_i == first_non_whitespace_i) { // space necessary to prevent confusion with // **** or __ etc... MD_ostream.PutC(' '); } must_space = (is_bold || is_italic); // print the initial whitespace if any. for (size_t i = after_quote_i; i < first_non_whitespace_i; ++i) { MD_ostream.PutC(escaped_content.at(i)); } // write the formatting characters if (last_non_whitespace_i != std::string::npos) { seassert(after_last_i != std::string::npos); if (is_bold) MD_ostream.Write("**", 2); if (is_italic) MD_ostream.PutC('_'); // write the non-whitespace characters for (size_t i = first_non_whitespace_i; i <= last_non_whitespace_i; ++i) { MD_ostream.PutC(escaped_content.at(i)); } // write the formatting characters if (is_italic) MD_ostream.PutC('_'); if (is_bold) MD_ostream.Write("**", 2); // write any whitespace that comes after for (size_t i = last_non_whitespace_i + 1; i < after_last_i; ++i) { MD_ostream.PutC(escaped_content.at(i)); } if (url_ptr != nullptr) { MD_ostream.Write("](", 2); MD_ostream << (*url_ptr); MD_ostream.PutC(')'); } } // if } // if name = text } else if (name == wxT("symbol")) { wchar_t wc_char; long long_char(0); const wxString bare_content = paragraph_child->GetNodeContent(); if (!bare_content.ToLong((long*)&long_char)) { runtime_error e("XML symbol tag has no number content."); throw e; } wc_char = static_cast<wchar_t>(long_char); MD_ostream.Write(&wc_char, sizeof(wxChar)); } else if (name == wxT("image")) { wxString url; if (paragraph_child->GetAttribute(wxT("url"), &url) == false) { unsigned char * raw_string(nullptr); long temp; wxXmlNode * image_child = paragraph_child->GetChildren(); if (image_child->GetName() != wxT("data")) { return std::make_pair(false, wxT("Error: No data member for image.")); } wxString bare_content = image_child->GetNodeContent(); std::cout << "Image byte count is " << (bare_content.Length()/2) << std::endl; raw_string = (unsigned char*)malloc(bare_content.Length()/2+1); if (raw_string == nullptr) { throw bae; } raw_string[bare_content.Length()/2] = '\0'; // Need to parse this hex size_t rawi = 0; size_t hi = 0; while (hi < bare_content.Length() && !time_is_up) { wxString byte_hex = bare_content.Mid(hi, 2); byte_hex.ToLong(&temp, 16); raw_string[rawi] = bare_content[rawi] = temp; hi += 2; rawi += 1; } // this deep copies the string! wxMemoryInputStream image_string_stream(raw_string, bare_content.Length()/2); bare_content = wxEmptyString; // This branch is only used for old sea.zip files. New versions of sea.zip files don't even // have image files std::shared_ptr<wxImage> other_ptr(new wxImage(image_string_stream, wxBITMAP_TYPE_PNG)); // Data gets copied to *other_ptr, we don't need this or image_string_stream any more. free(raw_string); raw_string = nullptr; if (!other_ptr->IsOk()) { return std::make_pair(false, wxT("Invalid image in XML file")); } auto il = themap.find(*other_ptr); if (il == themap.end()) { return std::make_pair(false, wxT("Cannot find the URL of one of the embedded images")); } url = il->second.url; } // TO DO: wxOutputStream::Write may not write all sometimes but still be usable, // for example in the case of a socket. The code would need to call Write repeatedly // in a loop and should probably be done in some background thread. wxString img_url_code = wxT("![](") + url + wxT(")"); for (auto x : img_url_code) { MD_ostream.Write((void*)&x, sizeof(x)); if (MD_ostream.LastWrite() != sizeof(x)) return std::make_pair(false, wxT("Error in writing to stream")); } must_space = false; // if name == image } else { // if name != image return std::make_pair(false, wxT("Unknown tag in XML: \'") + name + wxT("\'")); } } // for MD_ostream.Write(wxT("\n"), sizeof(wxChar)); } // for if (time_is_up) { return std::make_pair(false, wxT("Time ran out.")); } wxString wide_string = MD_ostream.GetString(); // string wide_string is a 32-bit or 16-bit host Endian Unicode string // UTF8_string is a 8-bit UTF-8 string. std::string UTF8_string = ToUTF8(wide_string); MD_utf8_ostream.Write(UTF8_string.c_str(), UTF8_string.length()); MD_utf8_ostream.Close(); } catch (const std::exception& e) { wxString error_message = FromUTF8(e.what()); return std::make_pair(false, error_message); } return std::make_pair(true, wxT("Success")); } void addImageURLs(const wxImageTowxStringMap& themap, wxInputStream& XML_istream, wxOutputStream& XML_ostream) { wxXmlDocument doc; if (!doc.Load(XML_istream)) { runtime_error e("stream is not valid XML."); throw e; } addImageURLs(themap, doc); if (!doc.Save(XML_ostream)) { runtime_error e("unable to write XML"); throw e; } } wxXmlDocument addImageURLs(const wxImageTowxStringMap& themap, wxXmlDocument& doc) { // start processing the XML file if (doc.GetRoot()->GetName() != wxT("richtext")) { runtime_error e("richtext tag not found."); throw e; } // XmlNode strings are 32-bit word strings (wxString)s rather than byte strings. wxXmlNode * paragraph_layout = doc.GetRoot()->GetChildren(); if (paragraph_layout == nullptr || paragraph_layout->GetName() != wxT("paragraphlayout")) { runtime_error e("paragraphlayout tag not found."); throw e; } const long normal_font_weight = getNumericalProperty(paragraph_layout, font_weight_name, 0); if (normal_font_weight == 0) { runtime_error e("Missing fontweight property."); throw e; } long * normal_font_style_ptr = nullptr; { long tmp_fs = getNumericalProperty(paragraph_layout, font_style_name, 0); if (tmp_fs != 0) normal_font_style_ptr = new long(tmp_fs); } if (normal_font_style_ptr == nullptr) { runtime_error e("Missing fontstyle property"); throw e; } //long font_style = normal_font_style; const long normal_font_size = getNumericalProperty(paragraph_layout, font_size_name, 0); if (normal_font_size == 0) { runtime_error e("Missing fontsize property."); throw e; } wxStringOutputStream MD_ostream; for (wxXmlNode * paragraph_node = paragraph_layout->GetChildren(); paragraph_node != nullptr && !time_is_up; paragraph_node = paragraph_node->GetNext()) { if (paragraph_node->GetName() != wxT("paragraph")) { std::runtime_error e("Illegal tag found "); throw e; } for (wxXmlNode * paragraph_child = paragraph_node->GetChildren(); paragraph_child != nullptr && !time_is_up; paragraph_child = paragraph_child->GetNext()) { // process text enclosed by <tag1></tag1> wxString name = paragraph_child->GetName(); if (name == wxT("image")) { wxString url; if (paragraph_child->GetAttribute(wxT("url"), &url) == false) { unsigned char * raw_string(nullptr); long temp; wxXmlNode * image_child = paragraph_child->GetChildren(); if (image_child->GetName() != wxT("data")) { std::runtime_error e("Error: No data member for image."); throw e; } wxString bare_content = image_child->GetNodeContent(); std::cout << "Image byte count is " << (bare_content.Length()/2) << std::endl; raw_string = (unsigned char*)malloc(bare_content.Length()/2+1); if (raw_string == nullptr) { throw bae; } raw_string[bare_content.Length()/2] = '\0'; // Need to parse this hex size_t rawi = 0; size_t hi = 0; while (hi < bare_content.Length() && !time_is_up) { wxString byte_hex = bare_content.Mid(hi, 2); byte_hex.ToLong(&temp, 16); raw_string[rawi] = bare_content[rawi] = temp; hi += 2; rawi += 1; } // this deep copies the string! wxMemoryInputStream image_string_stream(raw_string, bare_content.Length()/2); bare_content = wxEmptyString; // This branch is only used for old sea.zip files. New versions of sea.zip files don't even // have image files std::shared_ptr<wxImage> other_ptr(new wxImage(image_string_stream, wxBITMAP_TYPE_PNG)); // Data gets copied to *other_ptr, we don't need this or image_string_stream any more. free(raw_string); raw_string = nullptr; if (!other_ptr->IsOk()) { throw std::runtime_error("Invalid image in XML file"); } auto il = themap.find(*other_ptr); if (il == themap.end()) { throw std::runtime_error("Cannot find the URL of one of the embedded images"); } url = il->second.url; paragraph_child->AddAttribute(wxT("url"), url); } // if no url attribute set } // if tag type is image } // for } // for return doc; }
[ "shawn.pringle@gmail.com" ]
shawn.pringle@gmail.com
613e4f7052084ff697aec41968d5f1df4d77faa1
4c84d6f2e63244a1d9f7d769a06a6d3d9b694101
/bksafevul/src_bksafevul/bksafevul/Vulfix/HyperTextParser.h
b095abe1b29432759cb9b8528e543caf6ba4c801
[ "Apache-2.0" ]
permissive
liangqidong/Guardian-demo
ad3582c9fc53924d2ce0ca3570bf2e0a909d1391
3bf26f02450a676b2b8f77892a895c328dfb6814
refs/heads/master
2020-03-06T22:37:53.416632
2018-03-28T08:26:10
2018-03-28T08:26:10
127,108,413
0
1
null
null
null
null
UTF-8
C++
false
false
752
h
#pragma once #include <string> #include <map> #include <vector> typedef std::basic_string<TCHAR> tstring; typedef std::map<tstring, tstring> attributes; #ifndef LPCTSTR typedef const TCHAR *LPCTSTR; #endif struct TextPart { TextPart() { } TextPart(LPCTSTR sztag, LPCTSTR szval) { if(sztag) tag = sztag; if(szval) val = szval; } BOOL isText() const { return tag.empty(); } BOOL isLink() const { return !tag.empty() && tag==_T("a"); } BOOL isBold() const { return !tag.empty() && tag==_T("b"); } tstring tag, val; attributes attrs; }; typedef std::vector<TextPart> TextParts; class CHyperTextParser { public: void Parse( LPCTSTR sz, TextParts &parts ); void _ParseAttribute( LPCTSTR pb, LPCTSTR pe, TextPart &tt ); };
[ "18088708700@163.com" ]
18088708700@163.com
6d160200396d6cd8e4e5ba336c4465e0c9066332
06726bb031816046fe2175e483981e5f6e2ece82
/GreenJudge/b017.cpp
f2ebbcab087d17bbb98f6f4d15d422a66370614a
[]
no_license
a37052800/c
2390f07c77131fbe01fc26943cb544edebc1726a
e966460b617dbfdeca324a6b4e845a62c70631bb
refs/heads/master
2023-01-11T11:49:06.463615
2022-12-26T08:14:27
2022-12-26T08:14:27
150,870,651
0
0
null
null
null
null
UTF-8
C++
false
false
655
cpp
#include <iostream> #include <string> #include <sstream> using namespace std; int main() { string a,b; int i=0,j,u=0,x=0; cin>>a>>b; int sa=a.size(),sb=b.size(); int na[sa],nb[sb],n[102]={0}; string c; stringstream s; while(a[i]!='\0') { c=a[i]; s.clear(); s.str(c); s>>na[i]; i++; } i=0; while(b[i]!='\0') { c=b[i]; s.clear(); s.str(c); s>>nb[i]; i++; } for(i=0;i<=sa-1;i++) { for(j=0;j<=sb-1;j++) { n[101-i-j]=na[sa-1-i]*nb[sb-1-j]+n[101-i-j]; while(n[101-i-j]>=10) { n[101-1-i-j]++; n[101-i-j]-=10; } } } for(i=0;i<=101;i++) { if(n[i]>0) x=1; if(x==1) cout<<n[i]; } return 0; }
[ "a37052800@gmail.com" ]
a37052800@gmail.com
f0b60d17ea8de85bfc66494432c8e62979a06284
b367fe5f0c2c50846b002b59472c50453e1629bc
/xbox_leak_may_2020/xbox trunk/xbox/private/test/directx/d3d/conf/mipfilter/maxbias.cpp
23beb918672af8fc4f6e4e8994907b2de51d4b9d
[]
no_license
sgzwiz/xbox_leak_may_2020
11b441502a659c8da8a1aa199f89f6236dd59325
fd00b4b3b2abb1ea6ef9ac64b755419741a3af00
refs/heads/master
2022-12-23T16:14:54.706755
2020-09-27T18:24:48
2020-09-27T18:24:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,673
cpp
//#define D3D_OVERLOADS #include "d3dlocus.h" #include "cd3dtest.h" #include "MipFilter.h" //************************************************************************ // Point_MaxMipLevel Test functions CPoint_MaxMipLevelTest::CPoint_MaxMipLevelTest() { m_szTestName = TEXT("MipFilter Point_MaxMipLevel"); m_szCommandKey = TEXT("Point_MaxMipLevel"); // Inidicate that we are a Max test bMax = true; } CPoint_MaxMipLevelTest::~CPoint_MaxMipLevelTest() { } //************************************************************************ // Linear_MaxMipLevel Test functions CLinear_MaxMipLevelTest::CLinear_MaxMipLevelTest() { m_szTestName = TEXT("MipFilter Linear_MaxMipLevel"); m_szCommandKey = TEXT("Linear_MaxMipLevel"); // Inidicate that we are a MipLinear & Max test bMax = true; bMipLinear = true; } CLinear_MaxMipLevelTest::~CLinear_MaxMipLevelTest() { } //************************************************************************ // Point_LODBias Test functions CPoint_LODBiasTest::CPoint_LODBiasTest() { m_szTestName = TEXT("MipFilter Point_LODBias"); m_szCommandKey = TEXT("Point_LODBias"); // Inidicate that we are a Bias test bBias = true; } CPoint_LODBiasTest::~CPoint_LODBiasTest() { } //************************************************************************ // Linear_LODBias Test functions CLinear_LODBiasTest::CLinear_LODBiasTest() { m_szTestName = TEXT("MipFilter Linear_LODBias"); m_szCommandKey = TEXT("Linear_LODBias"); // Inidicate that we are a MipLinear & Bias test bBias = true; bMipLinear = true; } CLinear_LODBiasTest::~CLinear_LODBiasTest() { }
[ "benjamin.barratt@icloud.com" ]
benjamin.barratt@icloud.com
51e04ecb2bba466792464373eaf509c2181fefe0
bebdef83edff1cc8255785369e140ce84d43350a
/Codes/10172_Gae.cpp
b53e6f7d67d6676f7a781030df193b732b83d186
[]
no_license
SayYoungMan/BaekJoon_OJ_Solutions
027fe9603c533df74633386dc3f7e15d5b465a00
b764ad1a33dc7c522e044eb0406903937fe8e4cc
refs/heads/master
2023-07-05T13:47:43.260574
2021-08-26T11:42:21
2021-08-26T11:42:21
387,247,523
0
0
null
null
null
null
UTF-8
C++
false
false
218
cpp
#include <iostream> int main() { std::cout << "|\\_/|\n"; std::cout << "|q p| /}\n"; std::cout << "( 0 )\"\"\"\\\n"; std::cout << "|\"^\"` |\n"; std::cout << "||_/=\\\\__|\n"; return 0; }
[ "nickte89@gmail.com" ]
nickte89@gmail.com
b1fc4f3dc3c59a5da386940b21a0a069eedba6e2
1fc4ef58830ec6b20a54ce6176b1642d5d98195a
/hodoscopes/hodoEff/hodoeff_calc.cxx
5197b8500285d4a0a2c599d7e63a880961c17e07
[]
no_license
dkleinja/analysis_E1039
abbff459fd2bcdb6067dab47485786fb69bb015a
37e3dd6982b75d843882181fc7b9de277478f423
refs/heads/master
2021-04-19T00:27:20.683036
2017-06-01T21:50:49
2017-06-01T21:50:49
33,490,756
0
0
null
null
null
null
UTF-8
C++
false
false
7,123
cxx
void hodoeff_calc(const int reco = 5, const int roadset = 57, const int ntracks = 1, const int momcut = 20, const int ycut = 3, const int centcut = 90) { gStyle->SetOptStat(0); int hodoID; int elementID; int flag; int matrix1flag; double mom_exp; double y_exp; //get the values Int_t paddleNumber; Double_t x; Double_t Efficiency, Efficiency_low, Efficiency_high; Double_t EffError_low, EffError_high; /* int nElements[8] = {20, 20, 19, 19, 16, 16, 16, 16}; int hodoIDs[8] = {27, 28, 29, 30, 35, 36, 37, 38}; std::string hodoNames[8] = {"H1L", "H1R", "H2L", "H2R", "H4Y1L", "H4Y1R", "H4Y2L", "H4Y2R"}; TFile* dataFile = new TFile("hodoeff_Y.root", "READ"); */ int nElements[8] = {23, 23, 16, 16, 16, 16, 16, 16}; int hodoIDs[8] = {25, 26, 31, 32, 33, 34, 39, 40}; std::string hodoNames[8] = {"H1B", "H1T", "H2B", "H2T", "H3B", "H3T", "H4B", "H4T"}; //TFile* dataFile = new TFile("hodoEff_012525.root", "READ"); //TFile* dataFile = new TFile("hodoEff_012125.root", "READ"); //TTree* dataTree = (TTree*)dataFile->Get("save"); char Fname[128]; TChain *dataTree = new TChain("save"); int chainfirst = 12525; //int chainlast = 12526; int chainlast = 15789; if(roadset==57){ chainfirst = 8412; chainlast = 10415; } //for(int i = chainfirst; i <= chainlast; i++){ for(int i = chainfirst; i <= chainlast; i++){ //if(i > 13799 && i < 14800)continue; sprintf(Fname, "./hodoDSTs/hodoEff_0%d.root", i); //sprintf(Fname, "./hodoDSTs/geotest_0%d.root", i); sprintf(Fname, "./hodoDSTs/kunadvise_0%d.root", i); sprintf(Fname, "./hodoDSTs/momcut%d_ycut3_centcut%d_trighits1_0%d.root", momcut, centcut, i); //sprintf(Fname, "./hodoDSTs/trighits_momcut%d_ycut3_centcut%d_0%d.root", momcut, centcut, i); //sprintf(Fname, "./hodoDSTs/momcut%d_ycut3_centcut%d_0%d.root", momcut, centcut, i); sprintf(Fname, "./hodoDSTs/R00%dfiles_track%d_0%d.root", reco, ntracks, i); //sprintf(Fname, "./hodoDSTs/R00%dfiles_OnlEnable%d_0%d.root", reco, ntracks, i); //cout << "Getting File " << Fname << endl; dataTree -> Add(Fname); } dataTree->SetBranchAddress("hodoID", &hodoID); dataTree->SetBranchAddress("elementID", &elementID); dataTree->SetBranchAddress("flag", &flag); dataTree->SetBranchAddress("matrix1flag", &matrix1flag); dataTree->SetBranchAddress("mom_exp", &mom_exp); dataTree->SetBranchAddress("y_exp", &y_exp); TH1I* hist_all[8]; TH1I* hist_acc[8]; TH1D* hist_eff[8]; TGraphAsymmErrors* graph_eff[8]; char buffer[20]; for(int i = 0; i < 8; ++i) { sprintf(buffer, "%s_all", hodoNames[i].c_str()); hist_all[i] = new TH1I(buffer, buffer, nElements[i], 1, nElements[i]+1); hist_all[i]->Sumw2(); sprintf(buffer, "%s_acc", hodoNames[i].c_str()); hist_acc[i] = new TH1I(buffer, buffer, nElements[i], 1, nElements[i]+1); hist_acc[i]->Sumw2(); sprintf(buffer, "hist_%s_eff", hodoNames[i].c_str()); hist_eff[i] = new TH1D(buffer, buffer, nElements[i], 1, nElements[i]+1); hist_eff[i]->Sumw2(); hist_eff[i]->GetXaxis()->SetTitle("elementID"); hist_eff[i]->GetXaxis()->CenterTitle(); hist_eff[i]->SetMarkerStyle(8); hist_eff[i]->SetMarkerSize(0.4); sprintf(buffer, "%s_eff", hodoNames[i].c_str()); graph_eff[i] = new TGraphAsymmErrors(); graph_eff[i] -> SetName(buffer); graph_eff[i] -> SetTitle(buffer); graph_eff[i]->GetXaxis()->SetTitle("elementID"); graph_eff[i]->GetXaxis()->CenterTitle(); graph_eff[i]->SetMarkerStyle(8); graph_eff[i]->SetMarkerSize(0.4); } cout << "The number of entries is " << dataTree->GetEntries() << endl; for(int i = 0; i < dataTree->GetEntries(); ++i) { dataTree->GetEntry(i); //if(mom_exp < momcut) cout << i << " " << mom_exp << endl; if(mom_exp < momcut)continue; if(fabs(y_exp) < ycut)continue; //if(matrix1flag!=1)continue; int idx = -1; for(int j = 0; j < 8; ++j) { if(hodoIDs[j] == hodoID) { idx = j; break; } } if(idx >= 0 && idx < 8) { hist_all[idx]->Fill(elementID); if(flag == 1) hist_acc[idx]->Fill(elementID); } } //let's create ofstream file ofstream outFile; sprintf(Fname, "./eff/roadset67_R00%d_ntracks%d_momcut%d_ycut%d_centcut90.txt", reco, ntracks, momcut, ycut); //sprintf(Fname, "detectorEff_low.txt", reco, ntracks, momcut, ycut); outFile.open(Fname); outFile << "HodoName" << "\t" << "elementID" << "\t" << "Efficiency" << "\t" << "Error_low" << "\t" << "Error_high" << "\n"; for(int i = 0; i < 8; ++i) { hist_eff[i]->Divide(hist_acc[i], hist_all[i], 1., 1., "B"); //hist_eff[i]->Divide(hist_acc[i], hist_all[i], 1., 1., "cl=0.683 b(1,1) mode"); graph_eff[i]->Divide(hist_acc[i], hist_all[i], "cl=0.683 b(1,1) mode"); graph_eff[i]->GetXaxis()->SetTitle("elementID"); graph_eff[i]->GetXaxis()->CenterTitle(); //here is where we need to write out to file for(int j = 0; j < graph_eff[i]->GetN(); j++){ graph_eff[i] -> GetPoint(j, x, Efficiency); paddleNumber = x; EffError_low = graph_eff[i] -> GetErrorYlow(j); EffError_high = graph_eff[i] -> GetErrorYhigh(j); Efficiency_low = Efficiency - EffError_low; Efficiency_high = Efficiency + EffError_high; outFile << hodoNames[i] << "\t" << paddleNumber << "\t" << Efficiency << "\t" << EffError_low << "\t" << EffError_high << "\n"; //outFile << hodoNames[i] << "\t" << paddleNumber << "\t" << Efficiency << "\t" << 0 << "\n"; //outFile << hodoNames[i] << "\t" << paddleNumber << "\t" << Efficiency_low << "\t" << 0 << "\n"; //outFile << hodoNames[i] << "\t" << paddleNumber << "\t" << Efficiency_high << "\t" << 0 << "\n"; printf("%s : %4i : %1.4f : %1.4f : %1.4f \n", hodoNames[i].c_str(), paddleNumber, Efficiency, EffError_low, EffError_high); } } outFile.close(); TCanvas* c1 = new TCanvas("c1","c1", 2000,1000); c1->Divide(4, 2); c1->SetGridx(); c1->SetGridy(); c1->SetLogx(); c1->SetLogy(); TCanvas* c2 = new TCanvas("c2", "c2", 2000, 1000); c2->Divide(4, 2); c2->SetGridx(); c2->SetGridy(); c2->SetLogx(); c2->SetLogy(); for(int i = 1; i <= 8; ++i) { c1->cd(i)->SetGridx(); c1->cd(i)->SetGridy(); //c1->cd(i)->SetLogy(); //hist_all[i-1]->Draw(); hist_acc[i-1]->Draw("same"); //hist_eff[i-1]->GetYaxis()->SetRangeUser(0.5, 1.1); //hist_eff[i-1]->Draw(); graph_eff[i-1]->GetYaxis()->SetRangeUser(0.5, 1.1); graph_eff[i-1]->GetXaxis()->SetLimits(1, nElements[i-1]+1); graph_eff[i-1]->Draw("ap"); c2->cd(i)->SetGridx(); c2->cd(i)->SetGridy(); c2->cd(i)->SetLogy(); hist_acc[i-1]->Draw(); } c1 -> cd(); sprintf(Fname, "./images/roadset%d_R00%d_ntracks%d_momcut%d_ycut%d_centcut90.gif", roadset, reco, ntracks, momcut, ycut); c1 -> SaveAs(Fname); c2 -> cd(); sprintf(Fname, "./images/roadset%d_yields_R00%d_ntracks%d_momcut%d_ycut%d_centcut90.gif", roadset, reco, ntracks, momcut, ycut); c2 -> SaveAs(Fname); }
[ "kleinjan@lanl.gov" ]
kleinjan@lanl.gov
26786fddedc25072a5ed72aaaf098f1a2f823807
c557dc5688d94ef4c3c0d1cb7afbd7ee8337c02a
/src/UI.cpp
7cf67d7a8023d9a89e6a20fe5b2df4cda00be815
[]
no_license
keithloughnane/PhysicalAnalyticsServer
0ceb110eeda8499cd4f651c3134ff1f67c66e25c
0c0f4f94a1eb17d539e6456d9cd47c0f933e078c
refs/heads/master
2016-09-05T17:48:42.926015
2013-07-31T19:49:39
2013-07-31T19:49:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
153
cpp
#include "UI.h" #include <iostream> using namespace std; UI::UI() { cout << "UI started...\n" ; //ctor } UI::~UI() { //dtor }
[ "keith.loughnane@gmail.com" ]
keith.loughnane@gmail.com
a0e010d546bbfe66e2ee75b28ed30520a4fac1d3
d2fa5da30a2d6237007e5a3b0ff2d1e14205f3a9
/C++/ITstep week 4/zad_6.cpp
437ec18474cc31fe851fcd87a3f660af18e49c90
[]
no_license
Kaloyan-Dimitrov/OLD_coding_projects
ceeedbf3409a7955c208e66385faeff87dc35ae7
66cbcce3f824e256283426e842797e8e08ea397d
refs/heads/master
2022-12-10T09:19:37.286104
2019-10-21T16:36:53
2019-10-21T16:36:53
216,616,380
0
0
null
2022-12-09T00:49:59
2019-10-21T16:37:30
JavaScript
UTF-8
C++
false
false
255
cpp
#include <iostream> using namespace std; bool is(int a, int c){ if(a%10!=c and a>0) is(a/10, c); else if(a==0) return false; else return true; } int main (){ int ch, c; cin>>ch>>c; if(is(ch, c)) cout<<"True."; else cout<<"False."; return 0; } // 3525
[ "47056188+Kaloyan-Dimitrov@users.noreply.github.com" ]
47056188+Kaloyan-Dimitrov@users.noreply.github.com
6c318f766d42f1435712361aa212ebd1b1e8e964
28645f1537ee57a6426b9b9d5bbea08f67d3eaf2
/src/YBehavior/network/network_msvc.cpp
2d585acdc432b5b973673e8348bff30dfdb84453
[]
no_license
wsrlyk/YBehavior
32b1ef02bc6ab1022c444bd2d5cf51e1e724341a
cd7bd4573c190cc6a14db1288958677bb9d32f6c
refs/heads/master
2023-09-01T10:54:01.041700
2023-08-24T08:13:28
2023-08-24T08:13:28
111,627,890
3
0
null
null
null
null
UTF-8
C++
false
false
6,027
cpp
#ifdef YDEBUGGER #include "YBehavior/define.h" #ifdef YB_MSVC #include "YBehavior/network/network.h" #include <windows.h> #include <process.h> // beginthreadex #include "YBehavior/logger.h" #include <winsock.h> #include <assert.h> #pragma comment(lib, "Ws2_32.lib") namespace YBehavior { const size_t kMaxPacketDataSize = 230; const size_t kMaxPacketSize = 256; const size_t kSocketBufferSize = 16384; const size_t kGlobalQueueSize = (1024 * 32); const size_t kLocalQueueSize = (1024 * 8); SOCKET AsWinSocket(Handle h) { return (SOCKET)(h); } namespace Socket { bool InitSockets() { WSADATA wsaData; int ret = WSAStartup(MAKEWORD(2, 2), &wsaData); return (ret == 0); } void ShutdownSockets() { WSACleanup(); } bool TestConnection(Handle h) { SOCKET winSocket = AsWinSocket(h); fd_set readSet; FD_ZERO(&readSet); FD_SET(winSocket, &readSet); timeval timeout = { 0, 17000 }; int res = ::select(0, &readSet, 0, 0, &timeout); if (res > 0) { if (FD_ISSET(winSocket, &readSet)) { return true; } } return false; } void Close(Handle& h) { ::closesocket(AsWinSocket(h)); h = Handle(0); } Handle CreateSocket(bool bBlock) { SOCKET winSocket = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (winSocket == INVALID_SOCKET) { return Handle(0); } Handle r = Handle(winSocket); unsigned long inonBlocking = (bBlock ? 0 : 1); if (ioctlsocket(winSocket, FIONBIO, &inonBlocking) == 0) { return r; } Close(r); return Handle(0); } Handle Accept(Handle listeningSocket, size_t bufferSize) { typedef int socklen_t; sockaddr_in addr; socklen_t len = sizeof(sockaddr_in); memset(&addr, 0, sizeof(sockaddr_in)); SOCKET outSocket = ::accept(AsWinSocket(listeningSocket), (sockaddr*)&addr, &len); if (outSocket != SOCKET_ERROR) { int sizeOfBufSize = sizeof(bufferSize); ::setsockopt(outSocket, SOL_SOCKET, SO_RCVBUF, (const char*)&bufferSize, sizeOfBufSize); ::setsockopt(outSocket, SOL_SOCKET, SO_SNDBUF, (const char*)&bufferSize, sizeOfBufSize); return Handle(outSocket); } return Handle(0); } bool Listen(Handle h, Port port, int maxConnections) { SOCKET winSocket = AsWinSocket(h); sockaddr_in addr = { 0 }; addr.sin_addr.s_addr = INADDR_ANY; addr.sin_family = AF_INET; addr.sin_port = htons(port); memset(addr.sin_zero, 0, sizeof(addr.sin_zero)); int bReuseAddr = 1; ::setsockopt(winSocket, SOL_SOCKET, SO_REUSEADDR, (const char*)&bReuseAddr, sizeof(bReuseAddr)); //int rcvtimeo = 1000; //::setsockopt(winSocket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&rcvtimeo, sizeof(rcvtimeo)); if (::bind(winSocket, reinterpret_cast<const sockaddr*>(&addr), sizeof(addr)) == SOCKET_ERROR) { Close(h); return false; } if (::listen(winSocket, maxConnections) == SOCKET_ERROR) { Close(h); return false; } return true; } static size_t gs_packetsSent = 0; static size_t gs_packetsReceived = 0; bool Write(Handle& h, const void* buffer, size_t bytes, size_t& outBytesWritten) { outBytesWritten = 0; if (bytes == 0 || !h) { return bytes == 0; } int res = ::send(AsWinSocket(h), (const char*)buffer, (int)bytes, 0); if (res == SOCKET_ERROR) { int err = WSAGetLastError(); if (err == WSAECONNRESET || err == WSAECONNABORTED) { Close(h); } } else { outBytesWritten = (size_t)res; gs_packetsSent++; } return outBytesWritten != 0; } size_t Read(Handle& h, const void* buffer, size_t bytesMax) { size_t bytesRead = 0; if (bytesMax == 0 || !h) { return bytesRead; } fd_set readfds; FD_ZERO(&readfds); FD_SET(AsWinSocket(h), &readfds); struct timeval tv; tv.tv_sec = 0; tv.tv_usec = 100000;//0.1s int rv = ::select(2, &readfds, 0, 0, &tv); if (rv == -1) { } else if (rv == 0) { //timeout } else { int res = ::recv(AsWinSocket(h), (char*)buffer, (int)bytesMax, 0); if (res == SOCKET_ERROR) { int err = WSAGetLastError(); if (err == WSAECONNRESET || err == WSAECONNABORTED) { Close(h); } } else if (res == 0) { ///> Client has been closed. Close(h); } else { bytesRead = (size_t)res; gs_packetsReceived++; } return bytesRead; } return 0; } size_t GetPacketsSent() { return gs_packetsSent; } size_t GetPacketsReceived() { return gs_packetsReceived; } } ///////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// namespace Thread { ThreadHandle CreateThread(ThreadFunction* function, void* arg) { const uint32_t creationFlags = 0x0; uintptr_t hThread = ::_beginthreadex(NULL, (unsigned)300, function, arg, creationFlags, NULL); return (ThreadHandle)hThread; } void SleepMilli (int millisec) { Sleep(millisec); } } struct Mutex::MutexImpl { CRITICAL_SECTION _criticalSection; }; ///////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// Mutex::Mutex() { // Be sure that the shadow is large enough assert(sizeof(m_buffer) >= sizeof(MutexImpl)); // Use the shadow as memory space for the platform specific implementation _impl = (MutexImpl*)m_buffer; InitializeCriticalSection(&_impl->_criticalSection); } Mutex::~Mutex() { DeleteCriticalSection(&_impl->_criticalSection); } void Mutex::Lock() { EnterCriticalSection(&_impl->_criticalSection); } void Mutex::Unlock() { LeaveCriticalSection(&_impl->_criticalSection); } } #endif #endif // YDEBUGGER
[ "wsrlyk@gmail.com" ]
wsrlyk@gmail.com
783cbd8bef6570b1ec9673f4c8681d9f34a115a0
775acebaa6559bb12365c930330a62365afb0d98
/source/public/interfaces/layout/IPathSelectionData.h
c7f40e6d6265fe6adb53eb7e0fb284be29b1f592
[]
no_license
Al-ain-Developers/indesing_plugin
3d22c32d3d547fa3a4b1fc469498de57643e9ee3
36a09796b390e28afea25456b5d61597b20de850
refs/heads/main
2023-08-14T13:34:47.867890
2021-10-05T07:57:35
2021-10-05T07:57:35
339,970,603
1
1
null
2021-10-05T07:57:36
2021-02-18T07:33:40
C++
UTF-8
C++
false
false
1,549
h
//======================================================================================== // // $File: //depot/devtech/16.0.x/plugin/source/public/interfaces/layout/IPathSelectionData.h $ // // Owner: Paul Sorrick // // $Author: pmbuilder $ // // $DateTime: 2020/11/06 13:08:29 $ // // $Revision: #2 $ // // $Change: 1088580 $ // // Copyright 1997-2010 Adobe Systems Incorporated. All rights reserved. // // NOTICE: Adobe permits you to use, modify, and distribute this file in accordance // with the terms of the Adobe license agreement accompanying it. If you have received // this file from a source other than Adobe, then your use, modification, or // distribution of it requires the prior written permission of Adobe. // //======================================================================================== #pragma once #ifndef __IPATHSELECTIONDATA__ #define __IPATHSELECTIONDATA__ #include "IPMUnknown.h" #include "PathTypes.h" #include "LayoutUIID.h" /** Data interface for passing/storing a single path point selection. */ class IPathSelectionData : public IPMUnknown { public: enum { kDefaultIID = IID_IPATHSELECTIONDATA } ; /** Set the selected path point */ virtual void Set(const UIDRef& item, const PointSelector& handle) = 0; /** Clear the selection data */ virtual void Clear() = 0; /** Get the item */ virtual const UIDRef& GetItem() const = 0; /** Get the selected path point */ virtual const PointSelector& GetHandle() const = 0; }; #endif // __IPATHSELECTIONDATA__
[ "75730278+Tarekhesham10@users.noreply.github.com" ]
75730278+Tarekhesham10@users.noreply.github.com
1d1451ebe19ee1d23d3edc1f4c60084e05124a48
f3d3d2d1278721035fcf947f42650ed63f478c08
/Source/FirstTesting/FirstTesting_GameModeBase.cpp
e28200cb8e09beb473a059660e0b35a8c8fc6aea
[]
no_license
ericchia97/FirstTesting
e313b6f36c398e22a540d20c5b294aefa0bbc3b9
22b101a4e4088e8fe695f024aea27bc659e16c99
refs/heads/master
2022-09-16T01:42:33.256491
2020-06-01T15:44:15
2020-06-01T15:44:15
268,562,909
0
0
null
null
null
null
UTF-8
C++
false
false
698
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "FirstTesting_GameModeBase.h" #include "SaveManager.h" #include "FirstCharacterBase.h" #include "UObject/ConstructorHelpers.h" AFirstTesting_GameModeBase::AFirstTesting_GameModeBase() { //Set default pawn class to out Blueprinted character static ConstructorHelpers::FClassFinder<APawn> PlayerPawnBPClass(TEXT("/Game/ThirdPersonBP/Blueprints/ThirdPersonCharacter")); if (PlayerPawnBPClass.Class != NULL) { DefaultPawnClass = PlayerPawnBPClass.Class; } } void AFirstTesting_GameModeBase::InitGameState() { USaveManager::QueryAllSaveInterface(); USaveManager::LoadGame(); Super::InitGameState(); }
[ "ericchia508@gmail.com" ]
ericchia508@gmail.com
d6f0b9034a511cbc47644c68a96c8afc93dd5a90
0a6ce712507faa2150733dc8b93ab16d02085ded
/src/Menu.cpp
e880e4e1dde2433a5ebb3b03438310abe363c0e3
[]
no_license
pierre-rebut/Arcade
2464c303d02a70ba2f2da4ccb22f82915d9216a4
87c521f7522567318c8b9968d094f47b9aa886e1
refs/heads/master
2021-01-21T10:00:22.635175
2017-02-27T22:05:36
2017-02-27T22:05:36
83,355,974
0
0
null
null
null
null
UTF-8
C++
false
false
1,259
cpp
// // Menu.cpp for Menu in /home/rebut_p/Programmation/CPP/cpp_arcade/games/menu_src // // Made by Pierre Rebut // Login <rebut_p@epitech.net> // // Started on Mon Mar 21 14:24:28 2016 Pierre Rebut // Last update Sat Apr 2 18:41:04 2016 ganive_v // #include <iostream> #include <iterator> #include "Menu.hpp" #include "Core.hpp" void arcade::Core::initMenu() { _menu._currentGame = 0; for (std::vector<std::pair<std::string, std::string> >::const_iterator it = _lstGame.begin(); it != _lstGame.end(); ++it) _menu._lstGame.push_back((*it).first); for (std::vector<std::pair<std::string, std::string> >::const_iterator it = _lstDisplay.begin(); it != _lstDisplay.end(); ++it) _menu._lstDisplay.push_back((*it).first); } void arcade::Core::printMenu(const arcade::CommandType cmd, bool *menu) { switch (cmd) { case CommandType::GO_UP: _menu._currentGame --; break; case CommandType::GO_DOWN: _menu._currentGame++; break; case CommandType::PLAY: _currentGame = _menu._currentGame; changeGame(_lstGame.at(_menu._currentGame).second); *menu = false; break; default:break; } _menu._currentGame %= _menu._lstGame.size(); _display->drawMenu(_menu); }
[ "pierre.rebut@epitech.eu" ]
pierre.rebut@epitech.eu
fb36701d69ed9e92a7b4673a7a0b20d9eecac241
f0ba9db32f36c5aba864e5978872b2e8ad10aa40
/include/bsl/details/integer_sequence_min.hpp
19c3ecc53310207b81bc5d9629b98a2324c8a31c
[ "MIT" ]
permissive
Bareflank/bsl
fb325084b19cd48e03197f4265049f9c8d008c9f
6509cfff948fa34b98585512d7be33a36e2f9522
refs/heads/master
2021-12-25T11:19:43.743888
2021-10-21T14:47:58
2021-10-21T14:47:58
216,364,945
77
5
NOASSERTION
2021-10-21T02:24:26
2019-10-20T13:18:28
C++
UTF-8
C++
false
false
4,196
hpp
/// @copyright /// Copyright (C) 2020 Assured Information Security, Inc. /// /// @copyright /// 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: /// /// @copyright /// The above copyright notice and this permission notice shall be included in /// all copies or substantial portions of the Software. /// /// @copyright /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, /// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE /// SOFTWARE. #ifndef BSL_INTEGER_SEQUENCE_MIN_HPP #define BSL_INTEGER_SEQUENCE_MIN_HPP namespace bsl::details { namespace details { /// <!-- description --> /// @brief Returns the min of T1 and T2 /// /// <!-- inputs/outputs --> /// @tparam T the type of values being compared /// @param t1 the first integer to compare /// @param t2 the second integer to compare /// @return Returns the min of T1 and T2 /// template<typename T> [[nodiscard]] constexpr auto integer_sequence_min_impl(T const t1, T const t2) noexcept -> T { if (t1 < t2) { return t1; } return t2; } } /// @class bsl::details::integer_sequence_min /// /// <!-- description --> /// @brief Returns the min value given an integer sequence. This is /// used to implement integer_sequence::min(). /// /// <!-- template parameters --> /// @tparam T the type that defines the sequence of integers /// @tparam T1 the first integer in the sequence /// @tparam R the remaining integers in the sequence /// template<typename T, T T1, T... R> struct integer_sequence_min final { /// @brief the max value between T2 to TR static constexpr T t2{integer_sequence_min<T, R...>::value}; /// @brief the max value between T2 to T1 static constexpr T value{details::integer_sequence_min_impl(T1, t2)}; }; /// @class bsl::details::integer_sequence_min /// /// <!-- description --> /// @brief Returns the min value given an integer sequence. This is /// used to implement integer_sequence::min(). Note that this /// provides the case where there are only two integers in the /// sequence. /// /// <!-- template parameters --> /// @tparam T the type that defines the sequence of integers /// @tparam T1 the first integer in the sequence /// @tparam T2 the second integer in the sequence /// template<typename T, T T1, T T2> struct integer_sequence_min<T, T1, T2> final { /// @brief the max value between T2 to T1 static constexpr T value{details::integer_sequence_min_impl(T1, T2)}; }; /// @class bsl::details::integer_sequence_min /// /// <!-- description --> /// @brief Returns the min value given an integer sequence. This is /// used to implement integer_sequence::min(). Note that this /// provides the case where there is only one integer in the /// sequence. /// /// <!-- template parameters --> /// @tparam T the type that defines the sequence of integers /// @tparam T1 the first integer in the sequence /// template<typename T, T T1> struct integer_sequence_min<T, T1> final { /// @brief the value of T1 static constexpr T value{T1}; }; } #endif
[ "rianquinn@gmail.com" ]
rianquinn@gmail.com
820310a4a6645c82dff0239493ad8d5c8b76e2e5
ee9c5d0ca8f5b0884827f808fd74289f5f8fc5f2
/problems/DMOPC/2018/DMOPC18-Bob.cpp
c8672f45e6d5374ab29106a4ba42175d5bdd2386
[]
no_license
caoash/competitive-programming
a1f69a03da5ea6eae463c6ae521a55bf32011752
f98d8d547d25811a26cf28316fbeb76477b6c63f
refs/heads/master
2022-05-26T12:51:37.952057
2021-10-10T22:01:03
2021-10-10T22:01:03
162,861,707
21
1
null
null
null
null
UTF-8
C++
false
false
1,655
cpp
/* * Reduce the problem to pairing LCAs with distance formula, then realize if you choose the centroid you can always pair nodes using the root as LCA. */ #include <bits/stdc++.h> using namespace std; using ll = long long; using vi = vector<int>; using vl = vector<ll>; #define pb push_back #define rsz resize #define all(x) begin(x), end(x) #define sz(x) (int)(x).size() using pi = pair<int,int>; #define f first #define s second #define mp make_pair const int MX = 200005; const int MOD = (int) (1e9 + 7); const ll INF = (ll) 1e18; int n, m; int sz[MX]; vector<pi> adj[MX]; int dist[MX]; void dfs(int v, int p) { for (pi to : adj[v]) { if (to.f != p) { dfs(to.f, v); sz[v] += sz[to.f]; } } } int find(int v, int p) { for (pi to : adj[v]) { if (to.f != p) { if (sz[to.f] >= n / 2) { return find(to.f, v); } } } return v; } void dfs_dist(int v, int p) { for (pi to : adj[v]) { if (to.f != p) { dist[to.f] = dist[v] + to.s; dfs_dist(to.f, v); } } } int main(){ ios::sync_with_stdio(false); cin.tie(0); cin >> n >> m; vi a(n); for (int i = 0; i < n; i++) { cin >> a[i]; a[i]--; sz[a[i]]++; } for (int i = 0; i < m - 1; i++) { int u, v, w; cin >> u >> v >> w; u--, v--; adj[u].pb(mp(v, w)); adj[v].pb(mp(u, w)); } dfs(0, -1); int cent = find(0, -1); dfs_dist(cent, -1); ll ans = 0; for (int i = 0; i < n; i++) { ans += dist[a[i]]; } cout << ans << '\n'; }
[ "caoash@gmail.com" ]
caoash@gmail.com
07c6950a0b30fd381008497b8a6daeb02aa6a393
8af23530c7a2d76cba058d8d7f29b5a43dd43511
/exam10.cpp
6d4d78c37121a13acea26e3af064f3f8a4178189
[]
no_license
ABCorabc/C-Programming
310caf4960e7ce07749e9890be16bab7737248cc
ede6bdf520eb97d8af4c451861bcfb32d826ece7
refs/heads/master
2021-07-05T20:19:09.219111
2017-09-28T23:54:07
2017-09-28T23:54:07
105,117,571
0
0
null
null
null
null
UTF-8
C++
false
false
404
cpp
#include <stdio.h> typedef struct { int high; int low; char isPass; int standard; int sub; }result; void passorfail(result *); int main() { result r; scanf("%d %d %d", &r.high, &r.low, &r.standard); passorfail(&r); printf("%d %c\n", r.sub, r.isPass); } void passorfail(result *rp) { rp->sub = rp->high - rp->low; if (rp->sub <= rp->standard) rp->isPass = 'P'; else rp->isPass = 'F'; }
[ "kangkang1104@naver.com" ]
kangkang1104@naver.com
68d802089ef9db46a8b906e9bced8a3dbc562283
485978672fe6f6aa10e451b650287fba2ecb78b7
/module_qkpack/qkpack/lib/qkpack_metrics/inc/metrics/uniform_sample.h
6088cf5fda302be9fb29ff7a4155a4af0cc421e3
[]
no_license
lidaohang/data-qkpack-ngluaproxy
b20fffb24969a35b79e40cdb0d1d15d6437c5a09
1e6f5488e7e1f6c5c618292dbc0cb1330f7bafdc
refs/heads/master
2021-05-11T13:26:28.417674
2018-12-06T06:03:49
2018-12-06T06:03:49
117,679,187
0
2
null
null
null
null
UTF-8
C++
false
false
1,969
h
#ifndef __UNIFORM_SAMPLE_H__ #define __UNIFORM_SAMPLE_H__ #include <vector> #include <iterator> #include <boost/atomic.hpp> #include <boost/thread/mutex.hpp> #include <boost/thread/lock_guard.hpp> #include <boost/random/mersenne_twister.hpp> #include <boost/random/uniform_int_distribution.hpp> #include "metrics/sample.h" namespace com { namespace youku { namespace data { namespace qkpack { namespace metrics { /** * A random sampling reservoir of a stream of {@code long}s. Uses Vitter's Algorithm R to produce a * statistically representative sample. */ class UniformSample: public Sample { public: /** * Creates a new {@link UniformReservoir}. * @param size the number of samples to keep in the sampling reservoir */ UniformSample(boost::uint32_t reservoirSize = DEFAULT_SAMPLE_SIZE); virtual ~UniformSample(); /** * Clears the values in the sample. */ virtual void Clear(); /** * Returns the number of values recorded. * @return the number of values recorded */ virtual boost::uint64_t Size() const; /** * Adds a new recorded value to the sample. * @param value a new recorded value */ virtual void Update(boost::int64_t value); /** * Returns a snapshot of the sample's values. * @return a snapshot of the sample's values */ virtual SnapshotPtr GetSnapshot() const; /**< The Maximum sample size at any given time. */ static const boost::uint64_t DEFAULT_SAMPLE_SIZE; private: boost::uint64_t GetRandom(boost::uint64_t count) const; const boost::uint64_t reservoir_size_; boost::atomic<boost::uint64_t> count_; typedef std::vector<boost::int64_t> Int64Vector; Int64Vector values_; mutable boost::mt11213b rng_; mutable boost::mutex mutex_; }; } /* namespace metrics */ } /* namespace qkpack */ } /* namespace data */ } /* namespace youku */ } /* namespace com */ #endif /* __UNIFORM_SAMPLE_H__ */
[ "357732053@126.com" ]
357732053@126.com
d5a51fa78a8992391deea674fff07e964268ba68
24f26275ffcd9324998d7570ea9fda82578eeb9e
/net/proxy_resolution/proxy_bypass_rules_unittest.cc
aed0056f8b6b992e32f32f56f134dac918ee4101
[ "BSD-3-Clause" ]
permissive
Vizionnation/chromenohistory
70a51193c8538d7b995000a1b2a654e70603040f
146feeb85985a6835f4b8826ad67be9195455402
refs/heads/master
2022-12-15T07:02:54.461083
2019-10-25T15:07:06
2019-10-25T15:07:06
217,557,501
2
1
BSD-3-Clause
2022-11-19T06:53:07
2019-10-25T14:58:54
null
UTF-8
C++
false
false
19,894
cc
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/proxy_resolution/proxy_bypass_rules.h" #include "base/stl_util.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "build/build_config.h" #include "net/proxy_resolution/proxy_config_service_common_unittest.h" #include "testing/gtest/include/gtest/gtest.h" #if defined(OS_WIN) // On Windows, "loopback" resolves to localhost and is implicitly bypassed to // match WinInet. #define BYPASS_LOOPBACK #endif namespace net { namespace { // Calls |rules.Matches()| for each name in |hosts| (for various URL schemes), // and checks that the result is |bypasses|. If the host is in |inverted_hosts| // then the expectation is reversed. void ExpectRulesMatch(const ProxyBypassRules& rules, const char* hosts[], size_t num_hosts, bool bypasses, const std::set<std::string>& inverted_hosts) { // The scheme of the URL shouldn't matter. const char* kUrlSchemes[] = {"http://", "https://", "ftp://"}; for (auto* scheme : kUrlSchemes) { for (size_t i = 0; i < num_hosts; ++i) { const char* host = hosts[i]; bool expectation = bypasses; if (inverted_hosts.count(std::string(host)) != 0) expectation = !expectation; std::string url = std::string(scheme) + std::string(host); EXPECT_EQ(expectation, rules.Matches(GURL(url))) << url; } } } // Tests calling |rules.Matches()| for localhost URLs returns |bypasses|. void ExpectBypassLocalhost( const ProxyBypassRules& rules, bool bypasses, const std::set<std::string>& inverted_hosts = std::set<std::string>()) { const char* kHosts[] = { "localhost", "localhost.", "foo.localhost", "localhost6", "localhost6.localdomain6", "127.0.0.1", "127.100.0.2", "[::1]", "[::0:FFFF:127.0.0.1]", "[::fFfF:127.100.0.0]", "[0::ffff:7f00:1]", #if defined(BYPASS_LOOPBACK) "loopback", "loopback.", #endif }; ExpectRulesMatch(rules, kHosts, base::size(kHosts), bypasses, inverted_hosts); } // Tests calling |rules.Matches()| for link-local URLs returns |bypasses|. void ExpectBypassLinkLocal(const ProxyBypassRules& rules, bool bypasses) { const char* kHosts[] = { "169.254.3.2", "169.254.100.1", "[FE80::8]", "[fe91::1]", "[::ffff:169.254.3.2]", }; ExpectRulesMatch(rules, kHosts, base::size(kHosts), bypasses, {}); } // Tests calling |rules.Matches()| with miscelaneous URLs that are neither // localhost or link local IPs, returns |bypasses|. void ExpectBypassMisc( const ProxyBypassRules& rules, bool bypasses, const std::set<std::string>& inverted_hosts = std::set<std::string>()) { const char* kHosts[] = { "192.168.0.1", "170.254.0.0", "128.0.0.1", "[::2]", "[FD80::1]", "foo", "www.example3.com", "[::ffff:128.0.0.1]", "[::ffff:126.100.0.0]", "[::ffff::ffff:127.0.0.1]", "[::ffff:0:127.0.0.1]", "[::127.0.0.1]", #if !defined(BYPASS_LOOPBACK) "loopback", "loopback.", #endif }; ExpectRulesMatch(rules, kHosts, base::size(kHosts), bypasses, inverted_hosts); } TEST(ProxyBypassRulesTest, ParseAndMatchBasicHost) { ProxyBypassRules rules; rules.ParseFromString("wWw.gOogle.com"); ASSERT_EQ(1u, rules.rules().size()); // Hostname rules are normalized to lower-case. EXPECT_EQ("www.google.com", rules.rules()[0]->ToString()); // All of these match; port, scheme, and non-hostname components don't // matter. EXPECT_TRUE(rules.Matches(GURL("http://www.google.com"))); EXPECT_TRUE(rules.Matches(GURL("ftp://www.google.com:99"))); EXPECT_TRUE(rules.Matches(GURL("https://www.google.com:81"))); // Must be a strict host match to work. EXPECT_FALSE(rules.Matches(GURL("http://foo.www.google.com"))); EXPECT_FALSE(rules.Matches(GURL("http://xxx.google.com"))); EXPECT_FALSE(rules.Matches(GURL("http://google.com"))); EXPECT_FALSE(rules.Matches(GURL("http://www.google.com.baz.org"))); } TEST(ProxyBypassRulesTest, ParseAndMatchBasicDomain) { ProxyBypassRules rules; rules.ParseFromString(".gOOgle.com"); ASSERT_EQ(1u, rules.rules().size()); // Hostname rules are normalized to lower-case. // Note that we inferred this was an "ends with" test. EXPECT_EQ("*.google.com", rules.rules()[0]->ToString()); // All of these match; port, scheme, and non-hostname components don't // matter. EXPECT_TRUE(rules.Matches(GURL("http://www.google.com"))); EXPECT_TRUE(rules.Matches(GURL("ftp://www.google.com:99"))); EXPECT_TRUE(rules.Matches(GURL("https://a.google.com:81"))); EXPECT_TRUE(rules.Matches(GURL("http://foo.google.com/x/y?q"))); EXPECT_TRUE(rules.Matches(GURL("http://foo:bar@baz.google.com#x"))); // Must be a strict "ends with" to work. EXPECT_FALSE(rules.Matches(GURL("http://google.com"))); EXPECT_FALSE(rules.Matches(GURL("http://foo.google.com.baz.org"))); } TEST(ProxyBypassRulesTest, ParseAndMatchBasicDomainWithPort) { ProxyBypassRules rules; rules.ParseFromString("*.GOOGLE.com:80"); ASSERT_EQ(1u, rules.rules().size()); // Hostname rules are normalized to lower-case. EXPECT_EQ("*.google.com:80", rules.rules()[0]->ToString()); // All of these match; scheme, and non-hostname components don't matter. EXPECT_TRUE(rules.Matches(GURL("http://www.google.com"))); EXPECT_TRUE(rules.Matches(GURL("ftp://www.google.com:80"))); EXPECT_TRUE(rules.Matches(GURL("https://a.google.com:80?x"))); // Must be a strict "ends with" to work. EXPECT_FALSE(rules.Matches(GURL("http://google.com"))); EXPECT_FALSE(rules.Matches(GURL("http://foo.google.com.baz.org"))); // The ports must match. EXPECT_FALSE(rules.Matches(GURL("http://www.google.com:90"))); EXPECT_FALSE(rules.Matches(GURL("https://www.google.com"))); } TEST(ProxyBypassRulesTest, MatchAll) { ProxyBypassRules rules; rules.ParseFromString("*"); ASSERT_EQ(1u, rules.rules().size()); EXPECT_EQ("*", rules.rules()[0]->ToString()); EXPECT_TRUE(rules.Matches(GURL("http://www.google.com"))); EXPECT_TRUE(rules.Matches(GURL("ftp://www.foobar.com:99"))); EXPECT_TRUE(rules.Matches(GURL("https://a.google.com:80?x"))); } TEST(ProxyBypassRulesTest, WildcardAtStart) { ProxyBypassRules rules; rules.ParseFromString("*.org:443"); ASSERT_EQ(1u, rules.rules().size()); EXPECT_EQ("*.org:443", rules.rules()[0]->ToString()); EXPECT_TRUE(rules.Matches(GURL("http://www.google.org:443"))); EXPECT_TRUE(rules.Matches(GURL("https://www.google.org"))); EXPECT_FALSE(rules.Matches(GURL("http://www.google.org"))); EXPECT_FALSE(rules.Matches(GURL("https://www.google.com"))); EXPECT_FALSE(rules.Matches(GURL("https://www.google.org.com"))); } // Tests a codepath that parses hostnamepattern:port, where "port" is invalid // by containing a leading plus. TEST(ProxyBypassRulesTest, ParseInvalidPort) { ProxyBypassRules rules; EXPECT_TRUE(rules.AddRuleFromString("*.org:443")); EXPECT_FALSE(rules.AddRuleFromString("*.com:+443")); EXPECT_FALSE(rules.AddRuleFromString("*.com:-443")); } TEST(ProxyBypassRulesTest, IPV4Address) { ProxyBypassRules rules; rules.ParseFromString("192.168.1.1"); ASSERT_EQ(1u, rules.rules().size()); EXPECT_EQ("192.168.1.1", rules.rules()[0]->ToString()); EXPECT_TRUE(rules.Matches(GURL("http://192.168.1.1"))); EXPECT_TRUE(rules.Matches(GURL("https://192.168.1.1:90"))); EXPECT_FALSE(rules.Matches(GURL("http://www.google.com"))); EXPECT_FALSE(rules.Matches(GURL("http://sup.192.168.1.1"))); } TEST(ProxyBypassRulesTest, IPV4AddressWithPort) { ProxyBypassRules rules; rules.ParseFromString("192.168.1.1:33"); ASSERT_EQ(1u, rules.rules().size()); EXPECT_EQ("192.168.1.1:33", rules.rules()[0]->ToString()); EXPECT_TRUE(rules.Matches(GURL("http://192.168.1.1:33"))); EXPECT_FALSE(rules.Matches(GURL("http://www.google.com"))); EXPECT_FALSE(rules.Matches(GURL("http://192.168.1.1"))); EXPECT_FALSE(rules.Matches(GURL("http://sup.192.168.1.1:33"))); } TEST(ProxyBypassRulesTest, IPV6Address) { ProxyBypassRules rules; rules.ParseFromString("[3ffe:2a00:100:7031:0:0::1]"); ASSERT_EQ(1u, rules.rules().size()); // Note that we canonicalized the IP address. EXPECT_EQ("[3ffe:2a00:100:7031::1]", rules.rules()[0]->ToString()); EXPECT_TRUE(rules.Matches(GURL("http://[3ffe:2a00:100:7031::1]"))); EXPECT_TRUE(rules.Matches(GURL("http://[3ffe:2a00:100:7031::1]:33"))); EXPECT_FALSE(rules.Matches(GURL("http://www.google.com"))); EXPECT_FALSE(rules.Matches(GURL("http://sup.192.168.1.1:33"))); } TEST(ProxyBypassRulesTest, IPV6AddressWithPort) { ProxyBypassRules rules; rules.ParseFromString("[3ffe:2a00:100:7031::1]:33"); ASSERT_EQ(1u, rules.rules().size()); EXPECT_EQ("[3ffe:2a00:100:7031::1]:33", rules.rules()[0]->ToString()); EXPECT_TRUE(rules.Matches(GURL("http://[3ffe:2a00:100:7031::1]:33"))); EXPECT_FALSE(rules.Matches(GURL("http://[3ffe:2a00:100:7031::1]"))); EXPECT_FALSE(rules.Matches(GURL("http://www.google.com"))); } TEST(ProxyBypassRulesTest, HTTPOnly) { ProxyBypassRules rules; rules.ParseFromString("http://www.google.com"); ASSERT_EQ(1u, rules.rules().size()); EXPECT_EQ("http://www.google.com", rules.rules()[0]->ToString()); EXPECT_TRUE(rules.Matches(GURL("http://www.google.com/foo"))); EXPECT_TRUE(rules.Matches(GURL("http://www.google.com:99"))); EXPECT_FALSE(rules.Matches(GURL("https://www.google.com"))); EXPECT_FALSE(rules.Matches(GURL("ftp://www.google.com"))); EXPECT_FALSE(rules.Matches(GURL("http://foo.www.google.com"))); EXPECT_FALSE(rules.Matches(GURL("http://www.google.com.org"))); EXPECT_FALSE(rules.Matches(GURL("https://www.google.com"))); } TEST(ProxyBypassRulesTest, HTTPOnlyWithWildcard) { ProxyBypassRules rules; rules.ParseFromString("http://*www.google.com"); ASSERT_EQ(1u, rules.rules().size()); EXPECT_EQ("http://*www.google.com", rules.rules()[0]->ToString()); EXPECT_TRUE(rules.Matches(GURL("http://www.google.com/foo"))); EXPECT_TRUE(rules.Matches(GURL("http://www.google.com:99"))); EXPECT_TRUE(rules.Matches(GURL("http://foo.www.google.com"))); EXPECT_FALSE(rules.Matches(GURL("https://www.google.com"))); EXPECT_FALSE(rules.Matches(GURL("ftp://www.google.com"))); EXPECT_FALSE(rules.Matches(GURL("http://www.google.com.org"))); EXPECT_FALSE(rules.Matches(GURL("https://www.google.com"))); } TEST(ProxyBypassRulesTest, UseSuffixMatching) { ProxyBypassRules rules; rules.ParseFromString( "foo1.com, .foo2.com, 192.168.1.1, " "*foobar.com:80, *.foo, http://baz, <local>", ProxyBypassRules::ParseFormat::kHostnameSuffixMatching); ASSERT_EQ(7u, rules.rules().size()); EXPECT_EQ("*foo1.com", rules.rules()[0]->ToString()); EXPECT_EQ("*.foo2.com", rules.rules()[1]->ToString()); EXPECT_EQ("192.168.1.1", rules.rules()[2]->ToString()); EXPECT_EQ("*foobar.com:80", rules.rules()[3]->ToString()); EXPECT_EQ("*.foo", rules.rules()[4]->ToString()); EXPECT_EQ("http://*baz", rules.rules()[5]->ToString()); EXPECT_EQ("<local>", rules.rules()[6]->ToString()); EXPECT_TRUE(rules.Matches(GURL("http://foo1.com"))); EXPECT_TRUE(rules.Matches(GURL("http://aaafoo1.com"))); EXPECT_FALSE(rules.Matches(GURL("http://aaafoo1.com.net"))); } TEST(ProxyBypassRulesTest, MultipleRules) { ProxyBypassRules rules; rules.ParseFromString(".google.com , .foobar.com:30"); ASSERT_EQ(2u, rules.rules().size()); EXPECT_TRUE(rules.Matches(GURL("http://baz.google.com:40"))); EXPECT_FALSE(rules.Matches(GURL("http://google.com:40"))); EXPECT_TRUE(rules.Matches(GURL("http://bar.foobar.com:30"))); EXPECT_FALSE(rules.Matches(GURL("http://bar.foobar.com"))); EXPECT_FALSE(rules.Matches(GURL("http://bar.foobar.com:33"))); } TEST(ProxyBypassRulesTest, BadInputs) { ProxyBypassRules rules; EXPECT_FALSE(rules.AddRuleFromString("://")); EXPECT_FALSE(rules.AddRuleFromString(" ")); EXPECT_FALSE(rules.AddRuleFromString("http://")); EXPECT_FALSE(rules.AddRuleFromString("*.foo.com:-34")); EXPECT_EQ(0u, rules.rules().size()); } TEST(ProxyBypassRulesTest, Equals) { ProxyBypassRules rules1; ProxyBypassRules rules2; rules1.ParseFromString("foo1.com, .foo2.com"); rules2.ParseFromString("foo1.com,.FOo2.com"); EXPECT_EQ(rules1, rules2); EXPECT_EQ(rules2, rules1); rules1.ParseFromString(".foo2.com"); rules2.ParseFromString("foo1.com,.FOo2.com"); EXPECT_FALSE(rules1 == rules2); EXPECT_FALSE(rules2 == rules1); } TEST(ProxyBypassRulesTest, BypassSimpleHostnames) { // Test the simple hostnames rule in isolation, by first removing the // implicit rules. ProxyBypassRules rules; rules.ParseFromString("<-loopback>; <local>"); ASSERT_EQ(2u, rules.rules().size()); EXPECT_EQ("<-loopback>", rules.rules()[0]->ToString()); EXPECT_EQ("<local>", rules.rules()[1]->ToString()); EXPECT_TRUE(rules.Matches(GURL("http://example/"))); EXPECT_FALSE(rules.Matches(GURL("http://example./"))); EXPECT_FALSE(rules.Matches(GURL("http://example.com/"))); EXPECT_FALSE(rules.Matches(GURL("http://[dead::beef]/"))); EXPECT_FALSE(rules.Matches(GURL("http://192.168.1.1/"))); // Confusingly, <local> rule is NOT about localhost names. There is however // overlap on "localhost6?" as it is both a simple hostname and a localhost // name ExpectBypassLocalhost(rules, false, {"localhost", "localhost6", "loopback"}); // Should NOT bypass link-local addresses. ExpectBypassLinkLocal(rules, false); // Should not bypass other names either (except for the ones with no dot). ExpectBypassMisc(rules, false, {"foo", "loopback"}); } TEST(ProxyBypassRulesTest, ParseAndMatchCIDR_IPv4) { ProxyBypassRules rules; rules.ParseFromString("192.168.1.1/16"); ASSERT_EQ(1u, rules.rules().size()); EXPECT_EQ("192.168.1.1/16", rules.rules()[0]->ToString()); EXPECT_TRUE(rules.Matches(GURL("http://192.168.1.1"))); EXPECT_TRUE(rules.Matches(GURL("ftp://192.168.4.4"))); EXPECT_TRUE(rules.Matches(GURL("https://192.168.0.0:81"))); // Test that an IPv4 mapped IPv6 literal matches an IPv4 CIDR rule. EXPECT_TRUE(rules.Matches(GURL("http://[::ffff:192.168.11.11]"))); EXPECT_FALSE(rules.Matches(GURL("http://foobar.com"))); EXPECT_FALSE(rules.Matches(GURL("http://192.169.1.1"))); EXPECT_FALSE(rules.Matches(GURL("http://xxx.192.168.1.1"))); EXPECT_FALSE(rules.Matches(GURL("http://192.168.1.1.xx"))); } TEST(ProxyBypassRulesTest, ParseAndMatchCIDR_IPv6) { ProxyBypassRules rules; rules.ParseFromString("a:b:c:d::/48"); ASSERT_EQ(1u, rules.rules().size()); EXPECT_EQ("a:b:c:d::/48", rules.rules()[0]->ToString()); EXPECT_TRUE(rules.Matches(GURL("http://[A:b:C:9::]"))); EXPECT_FALSE(rules.Matches(GURL("http://foobar.com"))); EXPECT_FALSE(rules.Matches(GURL("http://192.169.1.1"))); // Test that an IPv4 literal matches an IPv4 mapped IPv6 CIDR rule. // This is the IPv4 mapped equivalent to 192.168.1.1/16. rules.ParseFromString("::ffff:192.168.1.1/112"); EXPECT_TRUE(rules.Matches(GURL("http://[::ffff:192.168.1.3]"))); EXPECT_TRUE(rules.Matches(GURL("http://192.168.11.11"))); EXPECT_FALSE(rules.Matches(GURL("http://10.10.1.1"))); // Test using an IP range that is close to IPv4 mapped, but not // quite. Should not result in matches. rules.ParseFromString("::fffe:192.168.1.1/112"); EXPECT_TRUE(rules.Matches(GURL("http://[::fffe:192.168.1.3]"))); EXPECT_FALSE(rules.Matches(GURL("http://[::ffff:192.168.1.3]"))); EXPECT_FALSE(rules.Matches(GURL("http://192.168.11.11"))); EXPECT_FALSE(rules.Matches(GURL("http://10.10.1.1"))); } // Test that parsing an IPv6 range given a bracketed literal is not supported. // Whether IPv6 literals need to be bracketed or not is pretty much a coin toss // depending on the context, and here it is expected to be unbracketed to match // macOS. It would be fine to support bracketed too, however none of the // grammars we parse need that. TEST(ProxyBypassRulesTest, ParseBracketedIPv6Range) { ProxyBypassRules rules; rules.ParseFromString("[a:b:c:d::]/48"); ASSERT_EQ(0u, rules.rules().size()); } // Check which URLs an empty ProxyBypassRules matches. TEST(ProxyBypassRulesTest, DefaultImplicitRules) { ProxyBypassRules rules; EXPECT_EQ("", rules.ToString()); // Should bypass all localhost and loopback names. ExpectBypassLocalhost(rules, true); // Should bypass all link-local addresses. ExpectBypassLinkLocal(rules, true); // Should not bypass other names. ExpectBypassMisc(rules, false); } // Test use of the <-loopback> bypass rule. TEST(ProxyBypassRulesTest, NegativeWinLoopback) { ProxyBypassRules rules; rules.ParseFromString("www.example.com;<-loopback>"); ASSERT_EQ(2u, rules.rules().size()); EXPECT_EQ("www.example.com", rules.rules()[0]->ToString()); EXPECT_EQ("<-loopback>", rules.rules()[1]->ToString()); // Should NOT bypass localhost and loopback names. ExpectBypassLocalhost(rules, false); // Should NOT bypass link-local addresses. ExpectBypassLinkLocal(rules, false); // Should not bypass other names either. ExpectBypassMisc(rules, false); // Only www.example.com should be bypassed. EXPECT_TRUE(rules.Matches(GURL("http://www.example.com/"))); } // Verifies the evaluation order of mixing negative and positive rules. This // expectation comes from WinInet (which is where <-loopback> comes from). TEST(ProxyBypassRulesTest, RemoveImplicitAndAddLocalhost) { ProxyBypassRules rules; rules.ParseFromString("<-loopback>; localhost"); ASSERT_EQ(2u, rules.rules().size()); EXPECT_EQ("<-loopback>", rules.rules()[0]->ToString()); EXPECT_EQ("localhost", rules.rules()[1]->ToString()); // Should not bypass localhost names because of <-loopback>. Except for // "localhost" which was added at the end. ExpectBypassLocalhost(rules, false, {"localhost"}); // Should NOT bypass link-local addresses. ExpectBypassLinkLocal(rules, false); // Should not bypass other names either. ExpectBypassMisc(rules, false); } // Verifies the evaluation order of mixing negative and positive rules. This // expectation comes from WinInet (which is where <-loopback> comes from). TEST(ProxyBypassRulesTest, AddLocalhostThenRemoveImplicit) { ProxyBypassRules rules; rules.ParseFromString("localhost; <-loopback>"); ASSERT_EQ(2u, rules.rules().size()); EXPECT_EQ("localhost", rules.rules()[0]->ToString()); EXPECT_EQ("<-loopback>", rules.rules()[1]->ToString()); // Because of the ordering, localhost is not bypassed, because <-loopback> // "unbypasses" it. ExpectBypassLocalhost(rules, false); // Should NOT bypass link-local addresses. ExpectBypassLinkLocal(rules, false); // Should not bypass other names either. ExpectBypassMisc(rules, false); } TEST(ProxyBypassRulesTest, AddRulesToSubtractImplicit) { ProxyBypassRules rules; rules.ParseFromString("foo"); rules.AddRulesToSubtractImplicit(); ASSERT_EQ(2u, rules.rules().size()); EXPECT_EQ("foo", rules.rules()[0]->ToString()); EXPECT_EQ("<-loopback>", rules.rules()[1]->ToString()); } TEST(ProxyBypassRulesTest, GetRulesToSubtractImplicit) { EXPECT_EQ("<-loopback>;", ProxyBypassRules::GetRulesToSubtractImplicit()); } // Verifies that the <local> and <-loopback> rules can be specified in any // case. This matches how WinInet's parses them. TEST(ProxyBypassRulesTest, LoopbackAndLocalCaseInsensitive) { ProxyBypassRules rules; rules.ParseFromString("<Local>; <-LoopBacK>; <LoCaL>; <-LoOpBack>"); ASSERT_EQ(4u, rules.rules().size()); EXPECT_EQ("<local>", rules.rules()[0]->ToString()); EXPECT_EQ("<-loopback>", rules.rules()[1]->ToString()); EXPECT_EQ("<local>", rules.rules()[2]->ToString()); EXPECT_EQ("<-loopback>", rules.rules()[3]->ToString()); } } // namespace } // namespace net
[ "rjkroege@chromium.org" ]
rjkroege@chromium.org
86679a778151afc85860b87f3dbb0c4d733a5633
ece46d54db148fcd1717ae33e9c277e156067155
/SDK/arxsdk2013/utils/Atil/Inc/format_codecs/ccitt.h
40d00d305abf342852ce997e5aa7ee8af22ff0ec
[]
no_license
15831944/ObjectArx
ffb3675875681b1478930aeac596cff6f4187ffd
8c15611148264593730ff5b6213214cebd647d23
refs/heads/main
2023-06-16T07:36:01.588122
2021-07-09T10:17:27
2021-07-09T10:17:27
384,473,453
0
1
null
2021-07-09T15:08:56
2021-07-09T15:08:56
null
UTF-8
C++
false
false
8,357
h
/////////////////////////////////////////////////////////////////////////////// // // (C) Autodesk, Inc. 2007-2011. All rights reserved. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // /////////////////////////////////////////////////////////////////////////////// #ifndef ATILDEFS_H #include "AtilDefs.h" #endif #ifndef CCITT_H #define CCITT_H #if __GNUC__ >= 4 #pragma GCC visibility push(default) #endif /// <summary> /// This holds the enums used by the CCITT decoder/encoder. /// </summary> struct CCITT { /// <summary> Describes the fill order of the bytes in the data.</summary> enum FillOrder { /// <summary> Intel least significant first.</summary> kLsb2Msb, /// <summary> Motorola most significant first.</summary> kMsb2Lsb }; /// <summary> Specifies different encoding systems within the CCITT specification.</summary> enum EncodeMethod { /// <summary> Use the Group3 tables along the row only (one dimensional) with RLE encoding.</summary> kG3_RLE, /// <summary> Use the Group3 tables along the row only (one dimensional).</summary> kG3_1D, /// <summary> Use the Group3 tables with two dimensional references.</summary> kG3_2d, /// <summary> Use the Group4 tables which are two dimensional.</summary> kG4 }; /// <summary> This declares flags that effect the encoding of the data i.e. line terminators. </summary> enum EncodeFlags { /// <summary> Flag indicating no directives over the CCITT specification. </summary> kNone = 0, /// <summary> Flag indicating that bits unused in the last byte of line are filled. </summary> kEOLFillBits = 0x0001, /// <summary> Flag indicating that each row is byte aligned. </summary> kFaxModeByteAlign = 0x0010, /// <summary> Flag indicating that each row is word aligned. </summary> kFaxModeWordAlign = 0x0110, /// <summary> Flag used for compatibility with some fax formats. </summary> kFaxModeNORTC = 0x0100, /// <summary> Flag used to disable the end of line flags. </summary> kFaxModeNoEOL = 0x1000 }; }; /// <summary> forward declaration of the Atil::DataStreamInterface. </summary> namespace Atil {class DataStreamInterface;} /// <summary> /// CCITTDecoder is a class which is used to decode data in CCITT group 3 /// or group 4 format.</summary> class CCITTDecoder { public: /// <summary> /// A static method used to construct an instance of a CCITTTDecoder.</summary> static CCITTDecoder* construct(); public: /// <summary> The destructor. </summary> virtual ~CCITTDecoder(); /// <summary> /// Sets up the decoder with the encoding method, the bit order, and the width of /// a row of decoded data.</summary> /// <param name="encoding">The encoding method the data is stored in.</param> /// <param name="bitOrder">Whether the data is stored little-endian or big-endian</param> /// <param name="nEndodeFlags">Any encoding flags that are needed. (CCITT::EncodeFlags)</param> /// <param name="nRowWidth">Width of a row in bytes</param> virtual void setupDecoder( CCITT::EncodeMethod encoding, CCITT::FillOrder bitOrder, unsigned int nEncodeFlags, int nRowWidth ) = 0; /// <summary> /// Decodes a block of data known to contain complete rows of compressed data. </summary> /// <param name="pIn">Pointer to block of compressed data.</param> /// <param name="nInBytes">Number of bytes of compressed data.</param> /// <param name="pOut">Pointer to buffer to receive decoded data.</param> /// <param name="nOutBytes">Number of bytes to be decoded. The output buffer must /// be at least that large.</param> virtual void decodeBlock(unsigned char* pIn, int nInBytes, unsigned char* pOut, int nOutBytes) = 0; /// <summary> /// Feeds the decoder the data stream from which the encoded data will be pulled. /// The data stream must be open for read. </summary> /// <param name="pStream">Pointer to an open (for read) data stream from which /// the decoder pulls encoded data. </param> virtual void decodeByRow(Atil::DataStreamInterface* pStream ) = 0; /// <summary> /// Decodes row(s) of data from the input stream specified in decodeByRow</summary> /// <param name="pRow">Pointer to a buffer to hold the decoded data.</param> /// <param name="nRowBytes">Number of bytes to be decoded. The output buffer must be /// at least that large.</param> /// <returns>Returns "true" if the requested number of bytes was decoded.</returns> virtual bool decodeRow(unsigned char * pRow, int nRowBytes ) = 0; }; class CCITTEncoder { public: /// <summary> /// A static method used to construct an instance of a CCITTTEncoder.</summary> static CCITTEncoder* construct (); public: /// <summary> The destructor. </summary> virtual ~CCITTEncoder (); /// <summary> /// Sets up the Encoder with the encoding method, the bit order, and the width of /// a row of data.</summary> /// <param name="encoding">The encoding method the data is stored in.</param> /// <param name="bitOrder">Whether the data is stored little-endian or big-endian</param> /// <param name="options">The options from <c>EncodingFlags</c> to use in encoding.</param> /// <param name="nRowWidth">Width of a row in bytes</param> virtual void setupEncoder ( CCITT::EncodeMethod encoding, CCITT::FillOrder bitOrder, CCITT::EncodeFlags options, int nRowWidth ) = 0; /// <summary> /// Encodes a block of data known to contain complete rows of data. </summary> /// <param name="pIn">Pointer to block of data.</param> /// <param name="nInBytes">Number of bytes of data.</param> /// <param name="pOut">Pointer to buffer to receive Encoded data.</param> /// <param name="nEncodedBytes">A reference to the number of bytes to be used in encoding.</param> virtual bool encodeBlock ( unsigned char* pIn, int nInBytes, unsigned char* pOut, int nOutBytes, int& nEncodedBytes ) = 0; /// <summary>Sets the output buffer for encoded rows of data.</summary> /// <param name="pOut">Pointer to the buffer to receive encoded data.</param> /// <param name="nOutBytes">The number of bytes in the <c>pOut</c> buffer.</param> virtual void encodeByRow ( unsigned char* pOut, int nOutBytes ) = 0; /// <summary>Sets the pointer to the start of the output buffer. This states that /// the buffer is prepared to receive data again. </summary> virtual void resetOutputPointer ( ) = 0; /// <summary> /// Encodes a row of data sending encoded data to the set output buffer.</summary> /// <param name="pRow">Pointer to a buffer holding the data.</param> /// <param name="nRowBytes">Number of bytes to be encoded.</param> /// <param name="nEncodedBytes">A reference to the number of bytes used in the output /// for encoding.</param> /// <returns>Returns "true" if successful encoding.</returns> virtual bool encodeRow ( unsigned char * pRow, int nRowBytes, int& nEncodedBytes ) = 0; /// <summary>This signals that there are no more rows to be encoded.</summary> /// <param name="nEncodedBytes">A reference to the number of bytes used in the output /// for encoding.</param> virtual void endEncodingRows ( int& nEncodedBytes ) = 0; }; #if __GNUC__ >= 4 #pragma GCC visibility pop #endif #endif
[ "zhangsensen@zwcad.com" ]
zhangsensen@zwcad.com
0e99106819deaaf2043eca28993dbaeaababc984
9bba90bad4f312c949c0704a6b3a3d94cdca4671
/test.code/google_libs/sparsehash.cpp
3b25983128f7be6402dda7808958a262ef77a738
[ "Apache-2.0" ]
permissive
P79N6A/workspace
036072fc3788ec50a95744b512e1566c3b16f082
2f1b4977ef51e77fcaf7e3c120714138099ce096
refs/heads/master
2020-04-23T10:04:37.302251
2019-02-17T06:57:18
2019-02-17T06:57:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,269
cpp
#include <google/dense_hash_map> #include <iostream> #include <string> #include <map> using namespace std; using google::dense_hash_map; // namespace where class lives by default struct eqstr { bool operator()(const char* s1, const char* s2) const { if (s1 && s2) return strcmp(s1, s2) <= 0; else if (s1) return 0; else return 1; } }; int main() { dense_hash_map<const char*, int, SPARSEHASH_HASH<const char*> > months; //dense_hash_map<const char*, int, SPARSEHASH_HASH<const char*>, eqstr > months; // must set empty key months.set_empty_key(NULL); months["january"] = 31; months["february"] = 28; months["december"] = 31; // 且不能使用empty key // months[NULL] = 32; cout << (months.find("september") == months.end()) << endl; cout << "september -> " << months["september"] << endl; cout << (months.find("september") == months.end()) << endl; cout << "april -> " << months["april"] << endl; cout << "june -> " << months["june"] << endl; cout << "november -> " << months["november"] << endl; std::string v = "\"\'<>&"; cout << v << endl; char* p; if (p = strpbrk(v.data(), "\"\'<>&")) { cout << p << " hit" << endl; } std::map<int , int> imap; imap[5] = 10; return 0; }
[ "lianjiang.yulj@alibaba-inc.com" ]
lianjiang.yulj@alibaba-inc.com
69498aeb12ee67e0ec9abbd3e43a3804b817331a
514b6f62afef72026cb47366224a33e6f56b48ca
/include/gameobject.h
beabc24b657ee65af0752a13d149e715b39d2c0f
[]
no_license
ghedger/glhplane
0cf8b849787f9de34caed222dcbe345e96bca1b4
05a188820cf196d0b636fcdb2e960886334ec19f
refs/heads/master
2021-08-23T19:06:43.462856
2017-12-06T04:52:53
2017-12-06T04:52:53
112,535,510
0
0
null
null
null
null
UTF-8
C++
false
false
228
h
// gameObject // Declaration for gameObject, a common ancestor #pragma once class GameObject { public: GameObject(); virtual ~GameObject(); virtual bool init() = 0; virtual void draw() = 0; protected: };
[ "greg@hedgersoftware.com" ]
greg@hedgersoftware.com
0de05fc8ed673d8db17ca162991f84548e804aec
a3ef275aee6c72acde34dcff9c291a6983b56937
/src/dense_hodlr/HODLR_Matrix.hpp
591483d59ed8ec61dded66ea9261990a7f0257fd
[]
no_license
stnava/RHODLR
6d872b8a3c8276a5216f0e7e665775d64463d5ec
81d8d712b5a9bba651ec16c0163e65f85c099557
refs/heads/master
2021-01-25T05:21:23.393150
2014-12-19T14:18:49
2014-12-19T14:18:49
27,038,381
1
0
null
null
null
null
UTF-8
C++
false
false
21,001
hpp
#ifndef HODLR_MATRIX_HPP #define HODLR_MATRIX_HPP //Standard C++ #include <cmath> #include <complex> #include <cstdlib> #include <ctime> #include <iostream> #include <memory> #include <string> #include <vector> //External Dependencies #include <Eigen/Dense> #include <Eigen/Sparse> //Custom Dependencies #include "helperFunctions.hpp" #include "HODLR_Tree.hpp" #include "kernel.hpp" #include "lowRank.hpp" #include "matrixIO.hpp" #include "perturbI.hpp" #include "user_IndexTree.hpp" #include "recLU_FactorTree.hpp" /** * \author Amirhossein Aminfar */ class HODLR_Matrix{ public: bool printLevelRankInfo; bool printLevelAccuracy; bool printLevelInfo; bool printResultInfo; /** * \defgroup Constructors * The HODLR matrix class provides a variety of options for initialization. * I'm planning to merge some of these constructors into a single constructor. However, some constructors may become depreciated in the feature. * @{ */ /** * \defgroup defConstruct Default Constructor * @{ */ HODLR_Matrix(); /** @} */ /** * \defgroup denseConstruct Dense Matrix Constructors * \brief Thse constructors build an HODLR matrix from a preallocated dense matrix. * \note Currently, the dense matrix is being passed by a non const reference variable. So if you want your original matrix, copy it elsewhere befor passing it to the constructor. * \note Only use the partial pivoting ACA ("partialPiv_ACA"), full pivoting ACA ("fullPiv_ACA"), singualr value Decomposition ("SVD"), pseudo skeleton with Chebyshev point selection ("PS_Cheby") or BDLR ("PS_Boundary") as the low-rank approximation schemes for dense matrices. * @{ */ /** * \param[in] inputMatrix : Preallocated dense matrix as Eigen::MatrixXd matrix class. * \param[in] inputSizeThreshold : Leaf size threshold. If no value is provided, it will set the leaf size to the default value of 30. * \param[in] LR_Method : Low-rank approximation scheme to be used in calculating the off-diagonal low-rank approximations. If no value is provided, it will set the LR_Method parameter to "partialPiv_ACA". * \brief This constructor initializes the class with a dense matrix and an optional leaf size threshold. */ HODLR_Matrix(Eigen::MatrixXd &inputMatrix,int inputSizeThreshold = 30, std::string LR_Method = "partialPiv_ACA"); /** * \param[in] inputMatrix : Preallocated dense matrix as Eigen::MatrixXd matrix class. * \param[in] inputSizeThreshold : Leaf size threshold. * \param[in] input_IndexTree : User defined splitting scheme stored as a user_IndexTree class. * \brief This constructor initializes the class with a dense matrix and a user specified indexing scheme which will be used to create the HODLR index tree. * This constructor initializes the class with a dense matrix. */ HODLR_Matrix(Eigen::MatrixXd &inputMatrix,int inputSizeThreshold,user_IndexTree &input_IndexTree); /** * \param[in] inputMatrix : Preallocated dense matrix as Eigen::MatrixXd matrix class. * \param[in] inputGraph : Preallocated sparse matrix. This sparse matrix will be used as the interaction graph in the BDLR low-rank approximation scheme. * \param[in] inputSizeThreshold : Leaf size threshold. If no value is provided, it will set the leaf size to the default value of 30. * \brief This constructor initializes the class with a dense matrix and an interaction graph (sparse matrix). The grpah is going to be used primarily as the interaction graph in the BDLR scheme. */ HODLR_Matrix(Eigen::MatrixXd &inputMatrix,Eigen::SparseMatrix<double> &inputGraph,int inputSizeThreshold = 30); /** * \param[in] inputMatrix : Preallocated dense matrix as Eigen::MatrixXd matrix class. * \param[in] inputGraph : Preallocated sparse matrix. This sparse matrix will be used as the interaction graph in the BDLR low-rank approximation scheme. * \param[in] inputSizeThreshold : Leaf size threshold. * \param[in] input_IndexTree : User defined splitting scheme stored as a user_IndexTree class. * \brief This constructor initializes the class with a dense matrix and an interaction graph (sparse matrix) and a user defined indexing schemes. The grpah is going to be used primarily as the interaction graph in the BDLR scheme. The user defined indexing scheme will be used to create the HODLR index tree. */ HODLR_Matrix(Eigen::MatrixXd &inputMatrix,Eigen::SparseMatrix<double> &inputGraph,int inputSizeThreshold,user_IndexTree &input_IndexTree); /** @} */ /** * \defgroup sparseConstruct Sparse Matrix Constructors * \brief Thse constructors build an HODLR matrix from a preallocated sparse matrix. * \note Currently, the sparse matrix is being passed by a non const reference variable. So if you want your original matrix, copy it elsewhere befor passing it to the constructor. * \note Only use "PS_Sparse" or "identifyBoundary" as low-rank approximation methods when initializing the class with a sparse matrix. * @{ */ /** * \param[in] inputMatrix : Preallocated Sparse Matrix. * \param[in] inputSizeThreshold : Leaf size threshold. If no value is provided, it will set the leaf size to the default value of 30. * \param[in] LR_Method : Low-rank approximation scheme to be used in calculating the off-diagonal low-rank approximations. If no value is provided, it will set the LR_Method parameter to "PS_Sparse". * \brief This constructor initializes the class with a sparse matrix and optional leaf size and low-rank approximation method parameters. */ HODLR_Matrix(Eigen::SparseMatrix<double> &inputMatrix,int inputSizeThreshold = 30,std::string LR_Method = "PS_Sparse"); /** * \param[in] inputMatrix : Preallocated Sparse Matrix. * \param[in] inputSizeThreshold : Leaf size threshold. If no value is provided, it will set the leaf size to the default value of 30. * \param[in] input_IndexTree : User defined splitting scheme stored as a user_IndexTree class. * \param[in] LR_Method : Low-rank approximation scheme to be used in calculating the off-diagonal low-rank approximations. If no value is provided, it will set the LR_Method parameter to "PS_Sparse". * \brief This constructor initializes the class with a sparse matrix and a user defined indexing scheme used to create the HODLR indexing tree. */ HODLR_Matrix(Eigen::SparseMatrix<double> &inputMatrix,int inputSizeThreshold,user_IndexTree &input_IndexTree,std::string LR_Method = "PS_Sparse"); /** * \param[in] inputMatrix : Preallocated Sparse Matrix. * \param[in] inputGraph : Preallocated sparse matrix. This sparse matrix will be used as the interaction graph in the BDLR low-rank approximation scheme. * \param[in] inputSizeThreshold : Leaf size threshold. If no value is provided, it will set the leaf size to the default value of 30. * \param[in] input_IndexTree : User defined splitting scheme stored as a user_IndexTree class. * \param[in] LR_Method : Low-rank approximation scheme to be used in calculating the off-diagonal low-rank approximations. If no value is provided, it will set the LR_Method parameter to "PS_Sparse". * \brief This constructor initializes the class with a sparse matrix and an interaction graph (sparse matrix) and a user defined indexing schemes. The grpah is going to be used primarily as the interaction graph in the BDLR scheme. The user defined indexing scheme will be used to create the HODLR index tree. */ HODLR_Matrix(Eigen::SparseMatrix<double> &inputMatrix,Eigen::SparseMatrix<double> &inputGraph,int inputSizeThreshold,user_IndexTree &input_IndexTree,std::string LR_Method = "PS_Sparse"); /** @} */ /** * \defgroup kernelConstruct Kernel Matrix Constructors * \brief These constructors build an HODLR matrix from a kernel function. * @{ */ /** * \param[in] numRows : Number of rows of the dense matrix. * \param[in] numCols : Number of columns of the dense matrix. * \param[in] inputKernel: Kernel function defining the matrix. * \param[in] inputKernelData: Additional information needed by the kernel function in excess of the row and column index of the entry. * \param[in] inputSizeThreshold: Leaf size threshold. If no value is provided, it will set the leaf size to the default value of 30. * \brief This constructor initializes the class with a kernel function and a size threshold. */ HODLR_Matrix(int numRows, int numCols,double (*inputKernel)(int i,int j,void* inputKernelData),void* inputKernelData,int inputSizeThreshold = 30); /** * \param[in] numRows : Number of rows of the dense matrix. * \param[in] numCols : Number of columns of the dense matrix. * \param[in] inputKernel: Kernel function defining the matrix. * \param[in] inputKernelData: Additional information needed by the kernel function in excess of the row and column index of the entry. * \param[in] inputGraph : Preallocated sparse matrix. This sparse matrix will be used as the interaction graph in the BDLR low-rank approximation scheme. * \param[in] inputSizeThreshold: Leaf size threshold. If no value is provided, it will set the leaf size to the default value of 30. * \brief This constructor initializes the class with a kernel function, a size threshold and an interaction graph. The grpah is going to be used primarily as the interaction graph in the BDLR scheme. */ HODLR_Matrix(int numRows, int numCols,double (*inputKernel)(int i,int j,void* inputKernelData),void* inputKernelData,Eigen::SparseMatrix<double> &inputGraph,int inputSizeThreshold = 30); /** * \param[in] numRows : Number of rows of the dense matrix. * \param[in] numCols : Number of columns of the dense matrix. * \param[in] inputKernel: Kernel function defining the matrix. * \param[in] inputKernelData: Additional information needed by the kernel function in excess of the row and column index of the entry. * \param[in] inputSizeThreshold: Leaf size threshold. * \param[in] input_IndexTree : User defined splitting scheme stored as a user_IndexTree class. * \brief This constructor initializes the class with a kernel function a user defined indexing scheme used to create the HODLR indexing tree. */ HODLR_Matrix(int numRows, int numCols,double (*inputKernel)(int i,int j,void* inputKernelData),void* inputKernelData,int inputSizeThreshold,user_IndexTree &input_IndexTree); /** * \param[in] numRows : Number of rows of the dense matrix. * \param[in] numCols : Number of columns of the dense matrix. * \param[in] inputKernel: Kernel function defining the matrix. * \param[in] inputKernelData: Additional information needed by the kernel function in excess of the row and column index of the entry. * \param[in] inputGraph : Preallocated sparse matrix. This sparse matrix will be used as the interaction graph in the BDLR low-rank approximation scheme. * \param[in] inputSizeThreshold: Leaf size threshold. * \param[in] input_IndexTree : User defined splitting scheme stored as a user_IndexTree class. * \brief This constructor initializes the class with a kernel function and an interaction graph (sparse matrix) and a user defined indexing schemes. The grpah is going to be used primarily as the interaction graph in the BDLR scheme. The user defined indexing scheme will be used to create the HODLR index tree. */ HODLR_Matrix(int numRows, int numCols,double (*inputKernel)(int i,int j,void* inputKernelData),void* inputKernelData, Eigen::SparseMatrix<double> &inputGraph, int inputSizeThreshold, user_IndexTree &input_IndexTree); /** @} */ /** * \param[in] inputMatrix * This constructor initializes the class with a dense matrix. */ HODLR_Matrix(const HODLR_Matrix & rhs); //Copy Constructor /** @} */ ~HODLR_Matrix(); /************************************* Create HODLR Structure ***************************************/ void storeLRinTree(); /************************************* Solve Methods **********************************/ Eigen::MatrixXd recLU_Solve(const Eigen::MatrixXd & input_RHS); Eigen::MatrixXd recSM_Solve(const Eigen::MatrixXd & input_RHS); void recLU_Compute(); Eigen::MatrixXd extendedSp_Solve(const Eigen::MatrixXd & input_RHS); Eigen::MatrixXd iterative_Solve(const Eigen::MatrixXd & input_RHS, const int maxIterations, const double stop_tolerance,const double init_LRTolerance,const std::string input_LR_Method, const std::string directSolve_Method); /************************************* Attribute Modification **********************************/ void set_LRTolerance(double tolerance); void set_minPivot(double minPivot); void set_pastix_MinPivot(double minPivot); void set_LRMethod(std::string input_LRMethod); void set_FreeMatrixMemory(bool inputVal); void set_BoundaryDepth(int inputBoundaryDepth); void set_recLUFactorizedFlag(bool factorized); void set_numSel(int numSel_); void set_LeafConst(); void saveExtendedSp(std::string savePath); /************************************ Accessing Attributes ************************************/ double get_recLU_FactorizationTime() const; double get_recLU_SolveTime() const; double get_recLU_TotalTime() const; double get_extendedSp_AssemblyTime() const; double get_extendedSp_FactorizationTime() const; double get_extendedSp_SolveTime() const; double get_extendedSp_TotalTime() const; double get_LR_ComputationTime() const; double get_totalIter_SolveTime() const; double get_MatrixSize() const; int rows() const; int cols() const; double norm(); double determinant(); double logAbsDeterminant(); /************************************ Acessing HODLR Entries *******************************/ Eigen::MatrixXd block(int min_i,int min_j,int numRows,int numCols); Eigen::MatrixXd row(int row); Eigen::MatrixXd col(int col); HODLR_Matrix topDiag(); HODLR_Matrix bottDiag(); void keepTopDiag(); void keepBottDiag(); friend void splitAtTop(HODLR_Matrix& self,HODLR_Matrix& topHODLR, HODLR_Matrix& bottHODLR); Eigen::MatrixXd& returnTopOffDiagU(); Eigen::MatrixXd& returnTopOffDiagV(); Eigen::MatrixXd& returnTopOffDiagK(); Eigen::MatrixXd& returnBottOffDiagU(); Eigen::MatrixXd& returnBottOffDiagV(); Eigen::MatrixXd& returnBottOffDiagK(); /******************************** Check ******************************************************/ void check_Structure(); double calcAbsDiff(); Eigen::MatrixXd createExactHODLR(const int rank,int input_MatrixSize,const int inpt_SizeThreshold); void saveSolverInfo(const std::string outputFileName); void freeMatrixData(); void destroyAllData(); void recalculateSize(); void correctIndices(); void initInfoVectors(); private: int sizeThreshold; int extendedSp_Size; int matrixSize; int matrixNumRows; int matrixNumCols; int constLeafSize; double recLU_FactorizationTime; double recLU_SolveTime; double recLU_TotalTime; double recSM_FactorizationTime; double recSM_SolveTime; double recSM_TotalTime; double LR_ComputationTime; double extendedSp_AssemblyTime; double extendedSp_FactorizationTime; double extendedSp_SolveTime; double extendedSp_TotalTime; double totalIter_SolveTime; double determinant_; double logAbsDeterminant_; std::vector<double> LR_ComputationLevelTimeVec; std::vector<double> recLU_FactorLevelTimeVec; std::vector<double> recLU_SolveLevelTimeVec; std::vector<double> iter_IterTimeVec; std::vector<double> iter_IterAccuracyVec; std::vector<double> levelRankAverageVec; std::vector<double> levelRankAverageVecCnt; bool LRStoredInTree; bool recLU_Factorized; bool recSM_Factorized; bool assembled_ExtendedSp; bool saveExtendedSp_Matrix; bool freeMatrixMemory; bool freeMatrixMemory_Sp; bool freeGraphMemmory; bool matrixDataAvail; bool matrixDataAvail_Sp; bool graphDataAvail; bool kernelDataAvail; bool isSquareMatrix; bool isLeafConst; bool constLeafSet; bool constLeafFactorized; bool calculatedDet; double LR_Tolerance; double minPivot; double pastix_MinPivot; int boundaryDepth; int numSel; HODLR_Tree indexTree; recLU_FactorTree recLUfactorTree; Eigen::MatrixXd matrixData; Eigen::SparseMatrix<double> matrixData_Sp; Eigen::SparseMatrix<double> graphData; Eigen::SparseLU<Eigen::SparseMatrix<double> > extendedSp_Solver; Eigen::MatrixXd constLeaf; Eigen::PartialPivLU<Eigen::MatrixXd> constLeafLU; kernelMatrix kernelMatrixData; std::string extendedSp_SavePath; void setDefaultValues(); void initialize(Eigen::MatrixXd& inputMatrix); void initialize(Eigen::SparseMatrix<double>& inputMatrix); void initialize(int numRows, int numCols,double (*inputKernel)(int i,int j,void* kernelData),void* inputKernelData); void reset_attributes(); void initializeInfoVecotrs(int numLevels); /****************************recLU Solver Functions*******************************/ void storeLRinTree(HODLR_Tree::node* HODLR_Root); void recLU_Factorize(); void recSM_Factorize(); Eigen::MatrixXd recLU_Factorize(const Eigen::MatrixXd & input_RHS,const HODLR_Tree::node* HODLR_Root, recLU_FactorTree::node* factorRoot); void recSM_Factorize(HODLR_Tree::node* HODLR_Root,std::vector<HODLR_Tree::node*> &leftChildren, std::vector<HODLR_Tree::node*> &rightChildren,int desLevel); Eigen::MatrixXd recLU_Solve(const Eigen::MatrixXd & input_RHS,const HODLR_Tree::node* HODLR_Root, const recLU_FactorTree::node* factorRoot); void recSM_Solve(HODLR_Tree::node* HODLR_Root,Eigen::MatrixXd &RHS); /**************************extendedSp Solver Functions***************************/ void findNodesAtLevel(HODLR_Tree::node* HODLR_Root, const int level, std::vector<HODLR_Tree::node*> & outputVector); void findLeafNodes(HODLR_Tree::node* HODLR_Root, std::vector<HODLR_Tree::node*>& outputVector); void insertDenseBlockIntoSpMatrix(std::vector<Eigen::Triplet<double,int> > & Sp_TripletVec, const Eigen::MatrixXd & denseMatrix, const int start_i, const int start_j); void insertIdentityIntoSpMatrix(std::vector<Eigen::Triplet<double,int> > & Sp_TripletVec, const int startIndex_i,const int startIndex_j, const int matrixSize, const int constant); int sumRanks(HODLR_Tree::node* HODLR_Root); Eigen::SparseMatrix<double> assembleExtendedSPMatrix(); /***************************Iterative Solver Functions****************************/ Eigen::MatrixXd oneStep_Iterate(const Eigen::MatrixXd & prevStep_result,const Eigen::MatrixXd & RHS,const Eigen::MatrixXd & initSolveGuess,Eigen::MatrixXd & prevStep_Product,const std::string directSolve_Method); /**********************************Accessing Matrix Entries***************************/ void fill_Block(Eigen::MatrixXd & blkMatrix,HODLR_Tree::node* root,int min_i,int min_j,int max_i,int max_j); void fill_BlockWithLRProduct(Eigen::MatrixXd & blkMatrix,int LR_Min_i,int LR_Min_j, int LR_numRows, int LR_numCols,Eigen::MatrixXd & LR_U,Eigen::MatrixXd & LR_V,int blk_Min_i,int blk_Min_j); /******************************Memory Management Functions***********************************/ void freeDenseMatMem(); void freeSparseMatMem(); /******************************** Check ******************************************************/ void check_Structure(HODLR_Tree::node* HODLR_Root); void createExactHODLR(HODLR_Tree::node* HODLR_Root,const int rank,Eigen::MatrixXd & result); /******************************** Determinant ************************************************/ void calcDeterminant(); void calcDeterminant(HODLR_Tree::node* HODLR_Root); /******************************** Friend Functions *******************************************/ friend void extendAddUpdate(HODLR_Matrix & parentHODLR, std::vector<Eigen::MatrixXd*> D_Array,std::vector<HODLR_Matrix*> D_HODLR_Array,std::vector<Eigen::MatrixXd*> U_Array,std::vector<Eigen::MatrixXd*> V_Array,std::vector<std::vector<int> > & updateIdxVec_Array_D,std::vector<std::vector<int> > & updateIdxVec_Array_D_HODLR,double tol,std::string mode); friend void extendAddUpdate(HODLR_Matrix & parentHODLR,HODLR_Matrix & D_HODLR,std::vector<int> & updateIdxVec,double tol,std::string mode); friend void extendAddUpdate(HODLR_Matrix & parentHODLR,Eigen::MatrixXd & U,Eigen::MatrixXd & V,std::vector<int>& updateIdxVec,double tol,std::string mode); friend HODLR_Matrix extend(std::vector<int> & extendIdxVec, int parentSize, HODLR_Matrix & childHODLR); friend void extendAddUpdate(HODLR_Matrix & parentHODLR,Eigen::MatrixXd & D,std::vector<int> & updateIdxVec,double tol,std::string mode); }; /** \class HODLR_Matrix HODLR_Matrix.hpp * \brief This is the main HODLR class that includes all the fast HODLR solvers. * * This class can be used as a sibling of the Eigen::MatrixXd class in cases where access to matrix entries is required. */ #endif
[ "stnava@gmail.com" ]
stnava@gmail.com
543475840371617acc7231ea61f8475283755ceb
21f7639aa6bbfc421fed3e28f94c47b5f6dfa39c
/src/unisinsight/webSocket/src/example/asyncServer.cpp
6c6acee963a349d504a9477288989782b5f43436
[]
no_license
hthappiness/codebase
06d3fe41ed97b791fc53ca1e734fca1234cd82e0
fb2af5f250d0ac69ba3dc324cbf65c34db39fd5c
refs/heads/master
2021-07-23T04:09:36.361718
2021-07-11T13:41:40
2021-07-11T13:41:40
233,802,062
0
0
null
null
null
null
UTF-8
C++
false
false
2,202
cpp
namespace { typedef boost::asio::io_service IoService; typedef boost::asio::ip::tcp TCP; std::string make_daytime_string() { using namespace std; time_t now = std::time(NULL); return ctime(&now); } class tcp_connection : public boost::enable_shared_from_this<tcp_connection> { public: typedef boost::shared_ptr<tcp_connection> pointer; static pointer create(IoService& io_service) { return pointer(new tcp_connection(io_service)); } TCP::socket& socket() { return socket_; } void start() { message_ = make_daytime_string(); boost::asio::async_write( socket_, boost::asio::buffer(message_), boost::bind(&tcp_connection::handle_write, shared_from_this()); //boost::asio::placeholders::error, //boost::asio::placeholders::bytes_transferred)); } private: tcp_connection(IoService& io_service) : socket_(io_service) { } void handle_write(const boost::system::error_code& /*error*/, size_t /*bytes_transferred*/) { PRINT_DEBUG("write data!!!"); } TCP::socket socket_; std::string message_; }; class tcp_server { public: tcp_server(IoService& io_service) : acceptor_(io_service, TCP::endpoint(TCP::v4(), 10000)) { start_accept(); } private: void start_accept() { tcp_connection::pointer new_connection = tcp_connection::create(acceptor_.get_io_service()); acceptor_.async_accept( new_connection->socket(), boost::bind(&tcp_server::handle_accept, this, new_connection )); } void handle_accept(tcp_connection::pointer new_connection, const boost::system::error_code& error) { if (!error) { new_connection->start(); start_accept(); } } TCP::acceptor acceptor_; }; } // tcp_connection与tcp_server封装后 void test_asio_asynserver() { try { IoService io_service; tcp_server server(io_service); // 只有io_service类的run()方法运行之后回调对象才会被调用 io_service.run(); } catch (std::exception& e) { std::cerr << e.what() << std::endl; } }
[ "329295821@qq.com" ]
329295821@qq.com
4205ba6ea8b4fb926ead40b767c4a56b2e9374a2
b19f30140cef064cbf4b18e749c9d8ebdd8bf27f
/D3DGame_180914_032_1_ModelScale_Inside_Shader/Objects/GameModel.h
42faa2a17f2f5003d2210be5f968d38c931ff140
[]
no_license
evehour/SGADHLee
675580e199991916cf3134e7c61749b0a0bfa070
0ebbedf5d0692b782e2e5f9a372911c65f98ddc4
refs/heads/master
2020-03-25T13:22:42.597811
2019-01-03T07:05:54
2019-01-03T07:05:54
143,822,128
0
0
null
null
null
null
UTF-8
C++
false
false
2,829
h
#pragma once #include "GameRender.h" class GameModel : public GameRender { public: GameModel ( wstring matFolder, wstring matFile , wstring meshFolder, wstring meshFile ); virtual ~GameModel(); void Velocity(D3DXVECTOR3& vec); D3DXVECTOR3 Velocity(); void Scale(float x, float y, float z); void Scale(D3DXVECTOR3 vec); virtual void Update(); virtual void Render(); Model* GetModel() { return model; } void SetShader(Shader* shader); void SetDiffuse(float r, float g, float b, float a = 1.0f); void SetDiffuse(D3DXCOLOR& color); void SetDiffuseMap(wstring file); void SetSpecular(float r, float g, float b, float a = 1.0f); void SetSpecular(D3DXCOLOR& color); void SetSpecularMap(wstring file); void SetNormalMap(wstring file); void SetDetailMap(wstring file); void SetShininess(float val); protected: void CalcPosition(); protected: Model* model; Shader* shader; D3DXVECTOR3 velocity; vector<D3DXMATRIX> boneTransforms; private: class RenderBuffer : public ShaderBuffer { public: RenderBuffer() : ShaderBuffer(&Data, sizeof(Data)) { Data.Index = 0; } struct Struct { int Index; float Padding[3]; } Data; }; RenderBuffer* renderBuffer; public: bool IsPick(D3DXVECTOR3 & origin, D3DXVECTOR3 & direction, OUT D3DXVECTOR3 & position); public: enum Bound_Type { BOUND_TYPE_SPHERE = 0, BOUND_TYPE_BOX, BOUND_TYPE_MAX }; void Center(D3DXVECTOR3& val) { val = center; } void BoundSize(D3DXVECTOR3& val) { val = boundSize; } void Radius(float& val) { val = radius; } void BoundType(Bound_Type& val) { boundType = val; } int BoundType() { return (int)boundType; } //0,2,4,6 - bottom void GetBoundSpace(std::vector<D3DXVECTOR3>& boundBox) { boundBox.assign(boundSpace.begin(), boundSpace.end()); } void GetBoundSpaceTries(std::vector<D3DXVECTOR3>& boundBoxTries) { boundBoxTries.assign(this->boundSpaceTries.begin(), this->boundSpaceTries.end()); } void GetAAABB(std::vector<D3DXVECTOR3>& aabbBox); D3DXVECTOR3 GetMinVertice() { return vecMin; } D3DXVECTOR3 GetMaxVertice() { return vecMax; } //bool IsPick(D3DXVECTOR3& origin, D3DXVECTOR3& direction, OUT D3DXVECTOR3& position); bool IsPickPart(D3DXVECTOR3& origin, D3DXVECTOR3& direction, OUT int& partIdx, OUT D3DXVECTOR3* position); void SetBoneMatrixByIdx(const int& boneIdx, const D3DXMATRIX& matrix); string GetBoneNameByIdx(const int& boneIdx); D3DXMATRIX GetBoneLocalMatrixByIdx(const int& boneIdx); protected: class LineMake* box; class LineMake* boxAABB; std::vector<D3DXVECTOR3> boundSpace; std::vector<D3DXVECTOR3> boundSpaceTries; std::vector<pair<int, pair<class ModelBone *, D3DXMATRIX>>> boneList; Bound_Type boundType; D3DXVECTOR3 center; D3DXVECTOR3 boundSize; D3DXVECTOR3 vecMin, vecMax; float radius; void SetBoundSpace(); void SetBoneList(); };
[ "evehour@naver.com" ]
evehour@naver.com
6b555fdeebb3e34933d285b3fff7b4c4ff5af63a
f5a8866ca08727fa99e8dce3c7d4eb413191e035
/dumux/porousmediumflow/richardsCylindrical1d/localresidual.hh
f9c020b1f82f9cb362dd1c817036f18f78a6433b
[]
no_license
Plant-Root-Soil-Interactions-Modelling/dumux-rosi
fecb3f48963e102a0257fbf5939b0e2973a6336c
cf6a6e5fa450b306e1ae134284419b1558c9349e
refs/heads/master
2023-08-16T22:19:14.152346
2023-08-02T08:16:51
2023-08-02T08:16:51
80,874,606
6
3
null
2023-08-31T11:10:28
2017-02-03T22:24:47
Jupyter Notebook
UTF-8
C++
false
false
7,886
hh
// -*- mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- // vi: set et ts=4 sw=4 sts=4: /***************************************************************************** * See the file COPYING for full copying permissions. * * * * 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/>. * *****************************************************************************/ /*! * \file * \ingroup RichardsModel * \brief Element-wise calculation of the Jacobian matrix for problems * using the Richards fully implicit models. */ #ifndef DUMUX_RICHARDS_CYL_LOCAL_RESIDUAL_HH #define DUMUX_RICHARDS_CYL_LOCAL_RESIDUAL_HH #include <dumux/common/properties.hh> namespace Dumux { /*! * \ingroup RichardsModel * \brief Element-wise calculation of the Jacobian matrix for problems * using the Richards fully implicit models. */ template<class TypeTag> class RichardsLocalResidual : public GetPropType<TypeTag, Properties::BaseLocalResidual> { using Implementation = GetPropType<TypeTag, Properties::LocalResidual>; using ParentType = GetPropType<TypeTag, Properties::BaseLocalResidual>; using Scalar = GetPropType<TypeTag, Properties::Scalar>; using Problem = GetPropType<TypeTag, Properties::Problem>; using NumEqVector = GetPropType<TypeTag, Properties::NumEqVector>; using VolumeVariables = GetPropType<TypeTag, Properties::VolumeVariables>; using ElementVolumeVariables = typename GetPropType<TypeTag, Properties::GridVolumeVariables>::LocalView; using FluxVariables = GetPropType<TypeTag, Properties::FluxVariables>; using ElementFluxVariablesCache = typename GetPropType<TypeTag, Properties::GridFluxVariablesCache>::LocalView; using FVElementGeometry = typename GetPropType<TypeTag, Properties::FVGridGeometry>::LocalView; using SubControlVolume = typename FVElementGeometry::SubControlVolume; using SubControlVolumeFace = typename FVElementGeometry::SubControlVolumeFace; using GridView = GetPropType<TypeTag, Properties::GridView>; using Element = typename GridView::template Codim<0>::Entity; using EnergyLocalResidual = GetPropType<TypeTag, Properties::EnergyLocalResidual>; using FluidSystem = GetPropType<TypeTag, Properties::FluidSystem>; using Indices = typename GetPropType<TypeTag, Properties::ModelTraits>::Indices; enum { conti0EqIdx = Indices::conti0EqIdx }; // first index for the mass balance enum { // phase indices liquidPhaseIdx = FluidSystem::liquidPhaseIdx, gasPhaseIdx = FluidSystem::gasPhaseIdx, liquidCompIdx = FluidSystem::liquidCompIdx }; static constexpr bool enableWaterDiffusionInAir = false; // getPropValue<TypeTag, Properties::EnableWaterDiffusionInAir>(); public: using ParentType::ParentType; /*! * \brief Evaluates the rate of change of all conservation * quantites (e.g. phase mass) within a sub-control * volume of a finite volume element for the immiscible models. * \param problem The problem * \param scv The sub control volume * \param volVars The current or previous volVars * \note This function should not include the source and sink terms. * \note The volVars can be different to allow computing * the implicit euler time derivative here */ NumEqVector computeStorage(const Problem& problem, const SubControlVolume& scv, const VolumeVariables& volVars) const { // partial time derivative of the phase mass NumEqVector storage(0.0); storage[conti0EqIdx] = volVars.porosity() * volVars.density(liquidPhaseIdx) * volVars.saturation(liquidPhaseIdx)*scv.center()[0]; // for extended Richards we consider water in air // todo ignored for now if (enableWaterDiffusionInAir) storage[conti0EqIdx] += volVars.porosity() * volVars.molarDensity(gasPhaseIdx) * volVars.moleFraction(gasPhaseIdx, liquidCompIdx) * FluidSystem::molarMass(liquidCompIdx) * volVars.saturation(gasPhaseIdx); //! The energy storage in the water, air and solid phase EnergyLocalResidual::fluidPhaseStorage(storage, scv, volVars, liquidPhaseIdx); EnergyLocalResidual::fluidPhaseStorage(storage, scv, volVars, gasPhaseIdx); EnergyLocalResidual::solidPhaseStorage(storage, scv, volVars); return storage; } /*! * \brief Evaluates the mass flux over a face of a sub control volume. * * \param problem The problem * \param element The current element. * \param fvGeometry The finite-volume geometry * \param elemVolVars The volume variables of the current element * \param scvf The sub control volume face to compute the flux on * \param elemFluxVarsCache The cache related to flux compuation */ NumEqVector computeFlux(const Problem& problem, const Element& element, const FVElementGeometry& fvGeometry, const ElementVolumeVariables& elemVolVars, const SubControlVolumeFace& scvf, const ElementFluxVariablesCache& elemFluxVarsCache) const { FluxVariables fluxVars; fluxVars.init(problem, element, fvGeometry, elemVolVars, scvf, elemFluxVarsCache); NumEqVector flux(0.0); // the physical quantities for which we perform upwinding auto upwindTerm = [](const auto& volVars) { return volVars.density(liquidPhaseIdx)*volVars.mobility(liquidPhaseIdx); }; flux[conti0EqIdx] = fluxVars.advectiveFlux(liquidPhaseIdx, upwindTerm)*scvf.center()[0]; // for extended Richards we consider water vapor diffusion in air // todo ignored for now if (enableWaterDiffusionInAir) flux[conti0EqIdx] += fluxVars.molecularDiffusionFlux(gasPhaseIdx)[liquidCompIdx]*FluidSystem::molarMass(liquidCompIdx); //! Add advective phase energy fluxes for the water phase only. For isothermal model the contribution is zero. EnergyLocalResidual::heatConvectionFlux(flux, fluxVars, liquidPhaseIdx); //! Add diffusive energy fluxes. For isothermal model the contribution is zero. //! The effective lambda is averaged over both fluid phases and the solid phase EnergyLocalResidual::heatConductionFlux(flux, fluxVars); return flux; } private: Implementation *asImp_() { return static_cast<Implementation *> (this); } const Implementation *asImp_() const { return static_cast<const Implementation *> (this); } }; } // end namespace Dumux #endif
[ "m.giraud@fz-juelich.de" ]
m.giraud@fz-juelich.de
c77463f5788b0e2da5f027a65a00b55e4eabf355
de7afdfbf77908253ef4b497617d0a69822bbd4b
/cf_539/b.cpp
4bec8efc9cde11d64f42843264e32f0b78c6b035
[]
no_license
joaoandreotti/competitive_programming
1ee6abdd589971a1194b059dff6b3b987dc698f3
75c8bce751f09ca76845033893f3a3fa0078753e
refs/heads/master
2020-09-15T11:52:45.554130
2020-02-18T13:38:52
2020-02-18T13:38:52
223,436,524
0
0
null
null
null
null
UTF-8
C++
false
false
815
cpp
#include <bits/stdc++.h> const int MAXN = 5e4 + 1; int n; int arr [MAXN]; int maxd = 1, px = 0, py = 0; int msq; long long bfr = 0, ans = INT_MAX; long long f (int i, int j) { long long r = arr [j] - (arr [j] / i); long long r1 = (arr [0] * i) - arr [0]; //printf ("r1: %lld, r: %lld\n", r1, r); long long aux = bfr + (r1-r); return aux; } int main () { scanf ("%d", &n); for (int i = 0; i < n; i++) { scanf ("%d", arr + i); bfr += arr [i]; } std::sort (arr, arr + n); for (int i = 2; i <= 100; i++) for (int j = 1; j < n; j++) if (!(arr [j] % i)) { ans = std::min (ans, f (i, j)); //printf ("ans: %d, i: %d, j: %d\n", ans, i, j); } //printf ("maxd: %d, px: %d, py: %d\n", maxd, px, py); printf ("%lld\n", std::min (ans, bfr)); return 0; }
[ "joao.andreotti@hotmail.com" ]
joao.andreotti@hotmail.com
9aaa73329f1703281351093c750963365fd3a29b
7023df22c3b788b897ab1d60c413501bf025db4e
/src/main.h
dae82f1a160f530f0495cb9ef41d44e85f3849e0
[ "MIT" ]
permissive
forkee/masterdoge
e667d1d47f5eb3419f37d291cf4ccf2eba8f4efa
a1f272a205820e3d18bc7823eede47f140a8297c
refs/heads/master
2021-05-13T21:54:15.861397
2015-07-22T17:32:24
2015-07-22T17:32:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
42,648
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_MAIN_H #define BITCOIN_MAIN_H #include "core.h" #include "bignum.h" #include "sync.h" #include "txmempool.h" #include "net.h" #include "script.h" #include "scrypt.h" #include <list> class CValidationState; #define START_MASTERNODE_PAYMENTS_TESTNET 1428034047 //Fri, 09 Jan 2015 21:05:58 GMT #define START_MASTERNODE_PAYMENTS 1428537599 //Wed, 8 April 2015 23:59:59 GMT static const int64_t DARKSEND_COLLATERAL = (20000*COIN); static const int64_t DARKSEND_FEE = (0.999*COIN); static const int64_t DARKSEND_POOL_MAX = (19999.9*COIN); /* At 15 signatures, 1/2 of the masternode network can be owned by one party without comprimising the security of InstantX (1000/2150.0)**15 = 1.031e-05 */ #define INSTANTX_SIGNATURES_REQUIRED 20 #define INSTANTX_SIGNATURES_TOTAL 30 #define MASTERNODE_NOT_PROCESSED 0 // initial state #define MASTERNODE_IS_CAPABLE 1 #define MASTERNODE_NOT_CAPABLE 2 #define MASTERNODE_STOPPED 3 #define MASTERNODE_INPUT_TOO_NEW 4 #define MASTERNODE_PORT_NOT_OPEN 6 #define MASTERNODE_PORT_OPEN 7 #define MASTERNODE_SYNC_IN_PROCESS 8 #define MASTERNODE_REMOTELY_ENABLED 9 #define MASTERNODE_MIN_CONFIRMATIONS 15 #define MASTERNODE_MIN_DSEEP_SECONDS (30*60) #define MASTERNODE_MIN_DSEE_SECONDS (5*60) #define MASTERNODE_PING_SECONDS (1*60) #define MASTERNODE_EXPIRATION_SECONDS (65*60) #define MASTERNODE_REMOVAL_SECONDS (70*60) class CBlock; class CBlockIndex; class CInv; class CKeyItem; class CNode; class CReserveKey; class CWallet; /** The maximum allowed size for a serialized block, in bytes (network rule) */ static const unsigned int MAX_BLOCK_SIZE = 40000000; /** The maximum size for mined blocks */ static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2; /** The maximum size for transactions we're willing to relay/mine **/ static const unsigned int MAX_STANDARD_TX_SIZE = MAX_BLOCK_SIZE_GEN/5; /** The maximum allowed number of signature check operations in a block (network rule) */ static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50; /** Maxiumum number of signature check operations in an IsStandard() P2SH script */ static const unsigned int MAX_P2SH_SIGOPS = 15; /** The maximum number of sigops we're willing to relay/mine in a single tx */ static const unsigned int MAX_TX_SIGOPS = MAX_BLOCK_SIGOPS/5; /** The maximum number of orphan transactions kept in memory */ static const unsigned int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100; /** Default for -maxorphanblocks, maximum number of orphan blocks kept in memory */ static const unsigned int DEFAULT_MAX_ORPHAN_BLOCKS = 750; /** The maximum number of entries in an 'inv' protocol message */ static const unsigned int MAX_INV_SZ = 50000; /** Fees smaller than this (in satoshi) are considered zero fee (for transaction creation) */ static const int64_t MIN_TX_FEE = 1000; /** Fees smaller than this (in satoshi) are considered zero fee (for relaying) */ static const int64_t MIN_RELAY_TX_FEE = MIN_TX_FEE; /** No amount larger than this (in satoshi) is valid */ static const int64_t MAX_MONEY = 10000000000 * COIN; // 1M PoW coins inline bool MoneyRange(int64_t nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); } /** Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp. */ static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC inline int64_t FutureDrift(int64_t nTime) { return nTime + 120; } inline unsigned int GetTargetSpacing(int nHeight) { return 64; } extern CScript COINBASE_FLAGS; extern CCriticalSection cs_main; extern CTxMemPool mempool; extern std::map<uint256, CBlockIndex*> mapBlockIndex; extern std::set<std::pair<COutPoint, unsigned int> > setStakeSeen; extern CBlockIndex* pindexGenesisBlock; extern unsigned int nStakeMinAge; extern unsigned int nNodeLifespan; extern int nBestHeight; extern uint256 nBestChainTrust; extern uint256 nBestInvalidTrust; extern uint256 hashBestChain; extern CBlockIndex* pindexBest; extern uint64_t nLastBlockTx; extern uint64_t nLastBlockSize; extern int64_t nLastCoinStakeSearchInterval; extern const std::string strMessageMagic; extern int64_t nTimeBestReceived; extern bool fImporting; extern bool fReindex; struct COrphanBlock; extern std::map<uint256, COrphanBlock*> mapOrphanBlocks; extern bool fHaveGUI; // Settings extern bool fUseFastIndex; extern unsigned int nDerivationMethodIndex; extern bool fMinimizeCoinAge; // Minimum disk space required - used in CheckDiskSpace() static const uint64_t nMinDiskSpace = 52428800; class CReserveKey; class CTxDB; class CTxIndex; class CWalletInterface; /** Register a wallet to receive updates from core */ void RegisterWallet(CWalletInterface* pwalletIn); /** Unregister a wallet from core */ void UnregisterWallet(CWalletInterface* pwalletIn); /** Unregister all wallets from core */ void UnregisterAllWallets(); /** Push an updated transaction to all registered wallets */ void SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fConnect = true); /** Ask wallets to resend their transactions */ void ResendWalletTransactions(bool fForce = false); /** Register with a network node to receive its signals */ void RegisterNodeSignals(CNodeSignals& nodeSignals); /** Unregister a network node */ void UnregisterNodeSignals(CNodeSignals& nodeSignals); void PushGetBlocks(CNode* pnode, CBlockIndex* pindexBegin, uint256 hashEnd); bool ProcessBlock(CNode* pfrom, CBlock* pblock); bool CheckDiskSpace(uint64_t nAdditionalBytes=0); FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb"); FILE* AppendBlockFile(unsigned int& nFileRet); bool LoadBlockIndex(bool fAllowNew=true); void PrintBlockTree(); CBlockIndex* FindBlockByHeight(int nHeight); bool ProcessMessages(CNode* pfrom); bool SendMessages(CNode* pto, bool fSendTrickle); void ThreadImport(std::vector<boost::filesystem::path> vImportFiles); bool CheckProofOfWork(uint256 hash, unsigned int nBits); unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake); int64_t GetProofOfWorkReward(int64_t nHeight, int64_t nFees); int64_t GetProofOfStakeReward(int64_t nCoinAge, int64_t nFees, bool fMasternodePayment); unsigned int ComputeMinWork(unsigned int nBase, int64_t nTime); unsigned int ComputeMinStake(unsigned int nBase, int64_t nTime, unsigned int nBlockTime); bool IsInitialBlockDownload(); std::string GetWarnings(std::string strFor); bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock); uint256 WantedByOrphan(const COrphanBlock* pblockOrphan); const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake); void ThreadStakeMiner(CWallet *pwallet); /** (try to) add transaction to memory pool **/ bool AcceptToMemoryPool(CTxMemPool& pool, CTransaction &tx, bool fLimitFree, bool* pfMissingInputs); bool AcceptableInputs(CTxMemPool& pool, const CTransaction &txo, bool fLimitFree, bool* pfMissingInputs); bool FindTransactionsByDestination(const CTxDestination &dest, std::vector<uint256> &vtxhash); int GetInputAge(CTxIn& vin); /** Abort with a message */ bool AbortNode(const std::string &msg, const std::string &userMessage=""); /** Increase a node's misbehavior score. */ void Misbehaving(NodeId nodeid, int howmuch); int64_t GetMasternodePayment(int nHeight, int64_t blockValue); /** Position on disk for a particular transaction. */ class CDiskTxPos { public: unsigned int nFile; unsigned int nBlockPos; unsigned int nTxPos; CDiskTxPos() { SetNull(); } CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn) { nFile = nFileIn; nBlockPos = nBlockPosIn; nTxPos = nTxPosIn; } IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); ) void SetNull() { nFile = (unsigned int) -1; nBlockPos = 0; nTxPos = 0; } bool IsNull() const { return (nFile == (unsigned int) -1); } friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b) { return (a.nFile == b.nFile && a.nBlockPos == b.nBlockPos && a.nTxPos == b.nTxPos); } friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b) { return !(a == b); } std::string ToString() const { if (IsNull()) return "null"; else return strprintf("(nFile=%u, nBlockPos=%u, nTxPos=%u)", nFile, nBlockPos, nTxPos); } }; enum GetMinFee_mode { GMF_BLOCK, GMF_RELAY, GMF_SEND, }; typedef std::map<uint256, std::pair<CTxIndex, CTransaction> > MapPrevTx; int64_t GetMinFee(const CTransaction& tx, unsigned int nBlockSize = 1, enum GetMinFee_mode mode = GMF_BLOCK, unsigned int nBytes = 0); /** The basic transaction that is broadcasted on the network and contained in * blocks. A transaction can contain multiple inputs and outputs. */ class CTransaction { public: static const int CURRENT_VERSION=1; int nVersion; unsigned int nTime; std::vector<CTxIn> vin; std::vector<CTxOut> vout; unsigned int nLockTime; // Denial-of-service detection: mutable int nDoS; bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; } CTransaction() { SetNull(); } IMPLEMENT_SERIALIZE ( READWRITE(this->nVersion); nVersion = this->nVersion; READWRITE(nTime); READWRITE(vin); READWRITE(vout); READWRITE(nLockTime); ) void SetNull() { nVersion = CTransaction::CURRENT_VERSION; nTime = GetAdjustedTime(); vin.clear(); vout.clear(); nLockTime = 0; nDoS = 0; // Denial-of-service prevention } bool IsNull() const { return (vin.empty() && vout.empty()); } uint256 GetHash() const { return SerializeHash(*this); } bool IsCoinBase() const { return (vin.size() == 1 && vin[0].prevout.IsNull() && vout.size() >= 1); } bool IsCoinStake() const { // ppcoin: the coin stake transaction is marked with the first output empty return (vin.size() > 0 && (!vin[0].prevout.IsNull()) && vout.size() >= 2 && vout[0].IsEmpty()); } /** Amount of bitcoins spent by this transaction. @return sum of all outputs (note: does not include fees) */ int64_t GetValueOut() const { int64_t nValueOut = 0; BOOST_FOREACH(const CTxOut& txout, vout) { nValueOut += txout.nValue; if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut)) throw std::runtime_error("CTransaction::GetValueOut() : value out of range"); } return nValueOut; } /** Amount of bitcoins coming in to this transaction Note that lightweight clients may not know anything besides the hash of previous transactions, so may not be able to calculate this. @param[in] mapInputs Map of previous transactions that have outputs we're spending @return Sum of value of all inputs (scriptSigs) @see CTransaction::FetchInputs */ int64_t GetValueIn(const MapPrevTx& mapInputs) const; bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL) { CAutoFile filein = CAutoFile(OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb"), SER_DISK, CLIENT_VERSION); if (!filein) return error("CTransaction::ReadFromDisk() : OpenBlockFile failed"); // Read transaction if (fseek(filein, pos.nTxPos, SEEK_SET) != 0) return error("CTransaction::ReadFromDisk() : fseek failed"); try { filein >> *this; } catch (std::exception &e) { return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__); } // Return file pointer if (pfileRet) { if (fseek(filein, pos.nTxPos, SEEK_SET) != 0) return error("CTransaction::ReadFromDisk() : second fseek failed"); *pfileRet = filein.release(); } return true; } friend bool operator==(const CTransaction& a, const CTransaction& b) { return (a.nVersion == b.nVersion && a.nTime == b.nTime && a.vin == b.vin && a.vout == b.vout && a.nLockTime == b.nLockTime); } friend bool operator!=(const CTransaction& a, const CTransaction& b) { return !(a == b); } std::string ToString() const { std::string str; str += IsCoinBase()? "Coinbase" : (IsCoinStake()? "Coinstake" : "CTransaction"); str += strprintf("(hash=%s, nTime=%d, ver=%d, vin.size=%u, vout.size=%u, nLockTime=%d)\n", GetHash().ToString(), nTime, nVersion, vin.size(), vout.size(), nLockTime); for (unsigned int i = 0; i < vin.size(); i++) str += " " + vin[i].ToString() + "\n"; for (unsigned int i = 0; i < vout.size(); i++) str += " " + vout[i].ToString() + "\n"; return str; } bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet); bool ReadFromDisk(CTxDB& txdb, COutPoint prevout); bool ReadFromDisk(COutPoint prevout); bool DisconnectInputs(CTxDB& txdb); /** Fetch from memory and/or disk. inputsRet keys are transaction hashes. @param[in] txdb Transaction database @param[in] mapTestPool List of pending changes to the transaction index database @param[in] fBlock True if being called to add a new best-block to the chain @param[in] fMiner True if being called by CreateNewBlock @param[out] inputsRet Pointers to this transaction's inputs @param[out] fInvalid returns true if transaction is invalid @return Returns true if all inputs are in txdb or mapTestPool */ bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool, bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid); /** Sanity check previous transactions, then, if all checks succeed, mark them as spent by this transaction. @param[in] inputs Previous transactions (from FetchInputs) @param[out] mapTestPool Keeps track of inputs that need to be updated on disk @param[in] posThisTx Position of this transaction on disk @param[in] pindexBlock @param[in] fBlock true if called from ConnectBlock @param[in] fMiner true if called from CreateNewBlock @return Returns true if all checks succeed */ bool ConnectInputs(CTxDB& txdb, MapPrevTx inputs, std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx, const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, unsigned int flags = STANDARD_SCRIPT_VERIFY_FLAGS, bool fValidateSig = true); bool CheckTransaction() const; bool GetCoinAge(CTxDB& txdb, uint64_t& nCoinAge) const; // ppcoin: get transaction coin age const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const; }; /** wrapper for CTxOut that provides a more compact serialization */ class CTxOutCompressor { private: CTxOut &txout; public: CTxOutCompressor(CTxOut &txoutIn) : txout(txoutIn) { } IMPLEMENT_SERIALIZE( READWRITE(VARINT(txout.nValue)); CScriptCompressor cscript(REF(txout.scriptPubKey)); READWRITE(cscript); ) }; /** Check for standard transaction types @param[in] mapInputs Map of previous transactions that have outputs we're spending @return True if all inputs (scriptSigs) use only standard transaction forms @see CTransaction::FetchInputs */ bool AreInputsStandard(const CTransaction& tx, const MapPrevTx& mapInputs); /** Count ECDSA signature operations the old-fashioned (pre-0.6) way @return number of sigops this transaction's outputs will produce when spent @see CTransaction::FetchInputs */ unsigned int GetLegacySigOpCount(const CTransaction& tx); /** Count ECDSA signature operations in pay-to-script-hash inputs. @param[in] mapInputs Map of previous transactions that have outputs we're spending @return maximum number of sigops required to validate this transaction's inputs @see CTransaction::FetchInputs */ unsigned int GetP2SHSigOpCount(const CTransaction& tx, const MapPrevTx& mapInputs); /** Check for standard transaction types @return True if all outputs (scriptPubKeys) use only standard transaction forms */ bool IsStandardTx(const CTransaction& tx, std::string& reason); bool IsFinalTx(const CTransaction &tx, int nBlockHeight = 0, int64_t nBlockTime = 0); /** A transaction with a merkle branch linking it to the block chain. */ class CMerkleTx : public CTransaction { private: int GetDepthInMainChainINTERNAL(CBlockIndex* &pindexRet) const; public: uint256 hashBlock; std::vector<uint256> vMerkleBranch; int nIndex; // memory only mutable bool fMerkleVerified; CMerkleTx() { Init(); } CMerkleTx(const CTransaction& txIn) : CTransaction(txIn) { Init(); } void Init() { hashBlock = 0; nIndex = -1; fMerkleVerified = false; } IMPLEMENT_SERIALIZE ( nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action); nVersion = this->nVersion; READWRITE(hashBlock); READWRITE(vMerkleBranch); READWRITE(nIndex); ) int SetMerkleBranch(const CBlock* pblock=NULL); // Return depth of transaction in blockchain: // -1 : not in blockchain, and not in memory pool (conflicted transaction) // 0 : in memory pool, waiting to be included in a block // >=1 : this many blocks deep in the main chain int GetDepthInMainChain(CBlockIndex* &pindexRet) const; int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); } bool IsInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChainINTERNAL(pindexRet) > 0; } int GetBlocksToMaturity() const; bool AcceptToMemoryPool(bool fLimitFree=true); int GetTransactionLockSignatures() const; bool IsTransactionLockTimedOut() const; }; /** A txdb record that contains the disk location of a transaction and the * locations of transactions that spend its outputs. vSpent is really only * used as a flag, but having the location is very helpful for debugging. */ class CTxIndex { public: CDiskTxPos pos; std::vector<CDiskTxPos> vSpent; CTxIndex() { SetNull(); } CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs) { pos = posIn; vSpent.resize(nOutputs); } IMPLEMENT_SERIALIZE ( if (!(nType & SER_GETHASH)) READWRITE(nVersion); READWRITE(pos); READWRITE(vSpent); ) void SetNull() { pos.SetNull(); vSpent.clear(); } bool IsNull() { return pos.IsNull(); } friend bool operator==(const CTxIndex& a, const CTxIndex& b) { return (a.pos == b.pos && a.vSpent == b.vSpent); } friend bool operator!=(const CTxIndex& a, const CTxIndex& b) { return !(a == b); } int GetDepthInMainChain() const; }; /** Nodes collect new transactions into a block, hash them into a hash tree, * and scan through nonce values to make the block's hash satisfy proof-of-work * requirements. When they solve the proof-of-work, they broadcast the block * to everyone and the block is added to the block chain. The first transaction * in the block is a special one that creates a new coin owned by the creator * of the block. * * Blocks are appended to blk0001.dat files on disk. Their location on disk * is indexed by CBlockIndex objects in memory. */ class CBlock { public: // header static const int CURRENT_VERSION = 7; int nVersion; uint256 hashPrevBlock; uint256 hashMerkleRoot; unsigned int nTime; unsigned int nBits; unsigned int nNonce; // network and disk std::vector<CTransaction> vtx; // ppcoin: block signature - signed by one of the coin base txout[N]'s owner std::vector<unsigned char> vchBlockSig; // memory only mutable std::vector<uint256> vMerkleTree; // Denial-of-service detection: mutable int nDoS; bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; } CBlock() { SetNull(); } IMPLEMENT_SERIALIZE ( READWRITE(this->nVersion); nVersion = this->nVersion; READWRITE(hashPrevBlock); READWRITE(hashMerkleRoot); READWRITE(nTime); READWRITE(nBits); READWRITE(nNonce); // ConnectBlock depends on vtx following header to generate CDiskTxPos if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY))) { READWRITE(vtx); READWRITE(vchBlockSig); } else if (fRead) { const_cast<CBlock*>(this)->vtx.clear(); const_cast<CBlock*>(this)->vchBlockSig.clear(); } ) void SetNull() { nVersion = CBlock::CURRENT_VERSION; hashPrevBlock = 0; hashMerkleRoot = 0; nTime = 0; nBits = 0; nNonce = 0; vtx.clear(); vchBlockSig.clear(); vMerkleTree.clear(); nDoS = 0; } bool IsNull() const { return (nBits == 0); } uint256 GetHash() const { if (nVersion > 6) return Hash(BEGIN(nVersion), END(nNonce)); else return GetPoWHash(); } uint256 GetPoWHash() const { return scrypt_blockhash(CVOIDBEGIN(nVersion)); } int64_t GetBlockTime() const { return (int64_t)nTime; } void UpdateTime(const CBlockIndex* pindexPrev); // entropy bit for stake modifier if chosen by modifier unsigned int GetStakeEntropyBit() const { // Take last bit of block hash as entropy bit unsigned int nEntropyBit = ((GetHash().Get64()) & 1llu); LogPrint("stakemodifier", "GetStakeEntropyBit: hashBlock=%s nEntropyBit=%u\n", GetHash().ToString(), nEntropyBit); return nEntropyBit; } // ppcoin: two types of block: proof-of-work or proof-of-stake bool IsProofOfStake() const { return (vtx.size() > 1 && vtx[1].IsCoinStake()); } bool IsProofOfWork() const { return !IsProofOfStake(); } std::pair<COutPoint, unsigned int> GetProofOfStake() const { return IsProofOfStake()? std::make_pair(vtx[1].vin[0].prevout, vtx[1].nTime) : std::make_pair(COutPoint(), (unsigned int)0); } // ppcoin: get max transaction timestamp int64_t GetMaxTransactionTime() const { int64_t maxTransactionTime = 0; BOOST_FOREACH(const CTransaction& tx, vtx) maxTransactionTime = std::max(maxTransactionTime, (int64_t)tx.nTime); return maxTransactionTime; } uint256 BuildMerkleTree() const { vMerkleTree.clear(); BOOST_FOREACH(const CTransaction& tx, vtx) vMerkleTree.push_back(tx.GetHash()); int j = 0; for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2) { for (int i = 0; i < nSize; i += 2) { int i2 = std::min(i+1, nSize-1); vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]), BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2]))); } j += nSize; } return (vMerkleTree.empty() ? 0 : vMerkleTree.back()); } std::vector<uint256> GetMerkleBranch(int nIndex) const { if (vMerkleTree.empty()) BuildMerkleTree(); std::vector<uint256> vMerkleBranch; int j = 0; for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2) { int i = std::min(nIndex^1, nSize-1); vMerkleBranch.push_back(vMerkleTree[j+i]); nIndex >>= 1; j += nSize; } return vMerkleBranch; } static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex) { if (nIndex == -1) return 0; BOOST_FOREACH(const uint256& otherside, vMerkleBranch) { if (nIndex & 1) hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash)); else hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside)); nIndex >>= 1; } return hash; } bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet) { // Open history file to append CAutoFile fileout = CAutoFile(AppendBlockFile(nFileRet), SER_DISK, CLIENT_VERSION); if (!fileout) return error("CBlock::WriteToDisk() : AppendBlockFile failed"); // Write index header unsigned int nSize = fileout.GetSerializeSize(*this); fileout << FLATDATA(Params().MessageStart()) << nSize; // Write block long fileOutPos = ftell(fileout); if (fileOutPos < 0) return error("CBlock::WriteToDisk() : ftell failed"); nBlockPosRet = fileOutPos; fileout << *this; // Flush stdio buffers and commit to disk before returning fflush(fileout); if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0) FileCommit(fileout); return true; } bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true) { SetNull(); // Open history file to read CAutoFile filein = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb"), SER_DISK, CLIENT_VERSION); if (!filein) return error("CBlock::ReadFromDisk() : OpenBlockFile failed"); if (!fReadTransactions) filein.nType |= SER_BLOCKHEADERONLY; // Read block try { filein >> *this; } catch (std::exception &e) { return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__); } // Check the header if (fReadTransactions && IsProofOfWork() && !CheckProofOfWork(GetPoWHash(), nBits)) return error("CBlock::ReadFromDisk() : errors in block header"); return true; } std::string ToString() const { std::stringstream s; s << strprintf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%u, vchBlockSig=%s)\n", GetHash().ToString(), nVersion, hashPrevBlock.ToString(), hashMerkleRoot.ToString(), nTime, nBits, nNonce, vtx.size(), HexStr(vchBlockSig.begin(), vchBlockSig.end())); for (unsigned int i = 0; i < vtx.size(); i++) { s << " " << vtx[i].ToString() << "\n"; } s << " vMerkleTree: "; for (unsigned int i = 0; i < vMerkleTree.size(); i++) s << " " << vMerkleTree[i].ToString(); s << "\n"; return s.str(); } bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex); bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck=false); bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true); bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew); bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos, const uint256& hashProof); bool CheckBlock(bool fCheckPOW=true, bool fCheckMerkleRoot=true, bool fCheckSig=true) const; bool AcceptBlock(); bool HasMasternodePayment(); bool SignBlock(CWallet& keystore, int64_t nFees); bool CheckBlockSignature() const; void RebuildAddressIndex(CTxDB& txdb); private: bool SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew); }; /** The block chain is a tree shaped structure starting with the * genesis block at the root, with each block potentially having multiple * candidates to be the next block. pprev and pnext link a path through the * main/longest chain. A blockindex may have multiple pprev pointing back * to it, but pnext will only point forward to the longest branch, or will * be null if the block is not part of the longest chain. */ class CBlockIndex { public: const uint256* phashBlock; CBlockIndex* pprev; CBlockIndex* pnext; unsigned int nFile; unsigned int nBlockPos; uint256 nChainTrust; // ppcoin: trust score of block chain int nHeight; int64_t nMint; int64_t nMoneySupply; unsigned int nFlags; // ppcoin: block index flags enum { BLOCK_PROOF_OF_STAKE = (1 << 0), // is proof-of-stake block BLOCK_STAKE_ENTROPY = (1 << 1), // entropy bit for stake modifier BLOCK_STAKE_MODIFIER = (1 << 2), // regenerated stake modifier }; uint64_t nStakeModifier; // hash modifier for proof-of-stake // proof-of-stake specific fields COutPoint prevoutStake; unsigned int nStakeTime; uint256 hashProof; // block header int nVersion; uint256 hashMerkleRoot; unsigned int nTime; unsigned int nBits; unsigned int nNonce; CBlockIndex() { phashBlock = NULL; pprev = NULL; pnext = NULL; nFile = 0; nBlockPos = 0; nHeight = 0; nChainTrust = 0; nMint = 0; nMoneySupply = 0; nFlags = 0; nStakeModifier = 0; hashProof = 0; prevoutStake.SetNull(); nStakeTime = 0; nVersion = 0; hashMerkleRoot = 0; nTime = 0; nBits = 0; nNonce = 0; } CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block) { phashBlock = NULL; pprev = NULL; pnext = NULL; nFile = nFileIn; nBlockPos = nBlockPosIn; nHeight = 0; nChainTrust = 0; nMint = 0; nMoneySupply = 0; nFlags = 0; nStakeModifier = 0; hashProof = 0; if (block.IsProofOfStake()) { SetProofOfStake(); prevoutStake = block.vtx[1].vin[0].prevout; nStakeTime = block.vtx[1].nTime; } else { prevoutStake.SetNull(); nStakeTime = 0; } nVersion = block.nVersion; hashMerkleRoot = block.hashMerkleRoot; nTime = block.nTime; nBits = block.nBits; nNonce = block.nNonce; } CBlock GetBlockHeader() const { CBlock block; block.nVersion = nVersion; if (pprev) block.hashPrevBlock = pprev->GetBlockHash(); block.hashMerkleRoot = hashMerkleRoot; block.nTime = nTime; block.nBits = nBits; block.nNonce = nNonce; return block; } uint256 GetBlockHash() const { return *phashBlock; } int64_t GetBlockTime() const { return (int64_t)nTime; } uint256 GetBlockTrust() const; bool IsInMainChain() const { return (pnext || this == pindexBest); } bool CheckIndex() const { return true; } int64_t GetPastTimeLimit() const { return GetBlockTime() - 120; } enum { nMedianTimeSpan=11 }; int64_t GetMedianTimePast() const { int64_t pmedian[nMedianTimeSpan]; int64_t* pbegin = &pmedian[nMedianTimeSpan]; int64_t* pend = &pmedian[nMedianTimeSpan]; const CBlockIndex* pindex = this; for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev) *(--pbegin) = pindex->GetBlockTime(); std::sort(pbegin, pend); return pbegin[(pend - pbegin)/2]; } /** * Returns true if there are nRequired or more blocks of minVersion or above * in the last nToCheck blocks, starting at pstart and going backwards. */ static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck); bool IsProofOfWork() const { return !(nFlags & BLOCK_PROOF_OF_STAKE); } bool IsProofOfStake() const { return (nFlags & BLOCK_PROOF_OF_STAKE); } void SetProofOfStake() { nFlags |= BLOCK_PROOF_OF_STAKE; } unsigned int GetStakeEntropyBit() const { return ((nFlags & BLOCK_STAKE_ENTROPY) >> 1); } bool SetStakeEntropyBit(unsigned int nEntropyBit) { if (nEntropyBit > 1) return false; nFlags |= (nEntropyBit? BLOCK_STAKE_ENTROPY : 0); return true; } bool GeneratedStakeModifier() const { return (nFlags & BLOCK_STAKE_MODIFIER); } void SetStakeModifier(uint64_t nModifier, bool fGeneratedStakeModifier) { nStakeModifier = nModifier; if (fGeneratedStakeModifier) nFlags |= BLOCK_STAKE_MODIFIER; } std::string ToString() const { return strprintf("CBlockIndex(nprev=%p, pnext=%p, nFile=%u, nBlockPos=%-6d nHeight=%d, nMint=%s, nMoneySupply=%s, nFlags=(%s)(%d)(%s), nStakeModifier=%016x, hashProof=%s, prevoutStake=(%s), nStakeTime=%d merkle=%s, hashBlock=%s)", pprev, pnext, nFile, nBlockPos, nHeight, FormatMoney(nMint), FormatMoney(nMoneySupply), GeneratedStakeModifier() ? "MOD" : "-", GetStakeEntropyBit(), IsProofOfStake()? "PoS" : "PoW", nStakeModifier, hashProof.ToString(), prevoutStake.ToString(), nStakeTime, hashMerkleRoot.ToString(), GetBlockHash().ToString()); } }; /** Used to marshal pointers into hashes for db storage. */ class CDiskBlockIndex : public CBlockIndex { private: uint256 blockHash; public: uint256 hashPrev; uint256 hashNext; CDiskBlockIndex() { hashPrev = 0; hashNext = 0; blockHash = 0; } explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex) { hashPrev = (pprev ? pprev->GetBlockHash() : 0); hashNext = (pnext ? pnext->GetBlockHash() : 0); } IMPLEMENT_SERIALIZE ( if (!(nType & SER_GETHASH)) READWRITE(nVersion); READWRITE(hashNext); READWRITE(nFile); READWRITE(nBlockPos); READWRITE(nHeight); READWRITE(nMint); READWRITE(nMoneySupply); READWRITE(nFlags); READWRITE(nStakeModifier); if (IsProofOfStake()) { READWRITE(prevoutStake); READWRITE(nStakeTime); } else if (fRead) { const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull(); const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0; } READWRITE(hashProof); // block header READWRITE(this->nVersion); READWRITE(hashPrev); READWRITE(hashMerkleRoot); READWRITE(nTime); READWRITE(nBits); READWRITE(nNonce); READWRITE(blockHash); ) uint256 GetBlockHash() const { if (fUseFastIndex && (nTime < GetAdjustedTime() - 24 * 60 * 60) && blockHash != 0) return blockHash; CBlock block; block.nVersion = nVersion; block.hashPrevBlock = hashPrev; block.hashMerkleRoot = hashMerkleRoot; block.nTime = nTime; block.nBits = nBits; block.nNonce = nNonce; const_cast<CDiskBlockIndex*>(this)->blockHash = block.GetHash(); return blockHash; } std::string ToString() const { std::string str = "CDiskBlockIndex("; str += CBlockIndex::ToString(); str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)", GetBlockHash().ToString(), hashPrev.ToString(), hashNext.ToString()); return str; } }; /** Describes a place in the block chain to another node such that if the * other node doesn't have the same branch, it can find a recent common trunk. * The further back it is, the further before the fork it may be. */ class CBlockLocator { protected: std::vector<uint256> vHave; public: CBlockLocator() { } explicit CBlockLocator(const CBlockIndex* pindex) { Set(pindex); } explicit CBlockLocator(uint256 hashBlock) { std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock); if (mi != mapBlockIndex.end()) Set((*mi).second); } CBlockLocator(const std::vector<uint256>& vHaveIn) { vHave = vHaveIn; } IMPLEMENT_SERIALIZE ( if (!(nType & SER_GETHASH)) READWRITE(nVersion); READWRITE(vHave); ) void SetNull() { vHave.clear(); } bool IsNull() { return vHave.empty(); } void Set(const CBlockIndex* pindex) { vHave.clear(); int nStep = 1; while (pindex) { vHave.push_back(pindex->GetBlockHash()); // Exponentially larger steps back for (int i = 0; pindex && i < nStep; i++) pindex = pindex->pprev; if (vHave.size() > 10) nStep *= 2; } vHave.push_back(Params().HashGenesisBlock()); } int GetDistanceBack() { // Retrace how far back it was in the sender's branch int nDistance = 0; int nStep = 1; BOOST_FOREACH(const uint256& hash, vHave) { std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash); if (mi != mapBlockIndex.end()) { CBlockIndex* pindex = (*mi).second; if (pindex->IsInMainChain()) return nDistance; } nDistance += nStep; if (nDistance > 10) nStep *= 2; } return nDistance; } CBlockIndex* GetBlockIndex() { // Find the first block the caller has in the main chain BOOST_FOREACH(const uint256& hash, vHave) { std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash); if (mi != mapBlockIndex.end()) { CBlockIndex* pindex = (*mi).second; if (pindex->IsInMainChain()) return pindex; } } return pindexGenesisBlock; } uint256 GetBlockHash() { // Find the first block the caller has in the main chain BOOST_FOREACH(const uint256& hash, vHave) { std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash); if (mi != mapBlockIndex.end()) { CBlockIndex* pindex = (*mi).second; if (pindex->IsInMainChain()) return hash; } } return Params().HashGenesisBlock(); } int GetHeight() { CBlockIndex* pindex = GetBlockIndex(); if (!pindex) return 0; return pindex->nHeight; } }; /** Capture information about block/transaction validation */ class CValidationState { private: enum mode_state { MODE_VALID, //! everything ok MODE_INVALID, //! network rule violation (DoS value may be set) MODE_ERROR, //! run-time error } mode; int nDoS; std::string strRejectReason; unsigned char chRejectCode; bool corruptionPossible; public: CValidationState() : mode(MODE_VALID), nDoS(0), chRejectCode(0), corruptionPossible(false) {} bool DoS(int level, bool ret = false, unsigned char chRejectCodeIn=0, std::string strRejectReasonIn="", bool corruptionIn=false) { chRejectCode = chRejectCodeIn; strRejectReason = strRejectReasonIn; corruptionPossible = corruptionIn; if (mode == MODE_ERROR) return ret; nDoS += level; mode = MODE_INVALID; return ret; } bool Invalid(bool ret = false, unsigned char _chRejectCode=0, std::string _strRejectReason="") { return DoS(0, ret, _chRejectCode, _strRejectReason); } bool Error(std::string strRejectReasonIn="") { if (mode == MODE_VALID) strRejectReason = strRejectReasonIn; mode = MODE_ERROR; return false; } bool Abort(const std::string &msg) { AbortNode(msg); return Error(msg); } bool IsValid() const { return mode == MODE_VALID; } bool IsInvalid() const { return mode == MODE_INVALID; } bool IsError() const { return mode == MODE_ERROR; } bool IsInvalid(int &nDoSOut) const { if (IsInvalid()) { nDoSOut = nDoS; return true; } return false; } bool CorruptionPossible() const { return corruptionPossible; } unsigned char GetRejectCode() const { return chRejectCode; } std::string GetRejectReason() const { return strRejectReason; } }; class CWalletInterface { protected: virtual void SyncTransaction(const CTransaction &tx, const CBlock *pblock, bool fConnect) =0; virtual void EraseFromWallet(const uint256 &hash) =0; virtual void SetBestChain(const CBlockLocator &locator) =0; virtual void UpdatedTransaction(const uint256 &hash) =0; virtual void Inventory(const uint256 &hash) =0; virtual void ResendWalletTransactions(bool fForce) =0; friend void ::RegisterWallet(CWalletInterface*); friend void ::UnregisterWallet(CWalletInterface*); friend void ::UnregisterAllWallets(); }; #endif
[ "MasterDoge-dev@users.noreply.github.com" ]
MasterDoge-dev@users.noreply.github.com
4f2ad139b376b198ed84f0656c9fa0c75274146e
c96c2f55ee053df41cf84491b7ab6586b94bef55
/Bloco.cpp
0c03c24ae1bb852ee48da4b7b7f26a320e8bd46a
[]
no_license
Bcortizo/CloneOUT
ccdba01b552a68deeb177f4a93e8ddd64cf0306d
3153bcc56f50edd4dde5146177edb2058ebcc853
refs/heads/master
2020-06-29T18:50:30.062325
2016-11-22T11:09:11
2016-11-22T11:09:11
74,416,782
0
0
null
null
null
null
MacCentralEurope
C++
false
false
623
cpp
#include "Bloco.h" Bloco::Bloco() { ID = 0; } Bloco::~Bloco() { } void Bloco::inicializar(int id, string nomeBloco) { ID = id; // seta o sprite "nomeBloco" jŠ com o caminho de arquivo certo if (!gRecursos.carregouSpriteSheet(nomeBloco)) { gRecursos.carregarSpriteSheet(nomeBloco, "imagens/" + nomeBloco + ".png"); } sprite.setSpriteSheet(nomeBloco); } void Bloco::desenhar(float x, float y) { if (ID != 0) { sprite.desenhar(x, y); } } float Bloco::getLargura() { return sprite.getLargura(); } float Bloco::getAltura() { return sprite.getAltura(); }
[ "noreply@github.com" ]
Bcortizo.noreply@github.com
63054c14f8a16eeeb2d0ab609bb2cee4e6286b06
e8dec4ca444ebc02d27c91960f16fa8a8152eb98
/c project/sample31.cpp
59af2cacf1ce41138eab6c21133d43f1005167bd
[]
no_license
cyberteknik/c-projects
2192df3b263fde65054c9ac0df41ac4df938b1ee
12a2c1c19f3727b53b0a2f3e1bb0fcb550ca0ef4
refs/heads/main
2023-03-30T10:24:25.568771
2021-04-04T14:39:48
2021-04-04T14:39:48
354,554,350
0
0
null
null
null
null
ISO-8859-9
C++
false
false
880
cpp
#include <stdio.h> #include <stdlib.h> /*Aybars ARSLAN Bilgisayar Mühendisliği İngilizce 2.öğretim*/ /*10 elemanlı dizi tanımlayın bu 10 elemanlı dizinin en büyük ve en kucuk sayilari veren program*/ int main(void) { int i,gecici,tut; int sayi[10]={12,213,334,425,563,67,78,839,11,10}; printf("Elimizdeki sayilar : 12,213,334,425,563,67,78,839,11,10"); for(gecici=1;gecici<10;gecici++) { for (i=0;i<10 - 1;i++) { if (sayi[i]>sayi[i+1]) { tut=sayi[i]; sayi[i]=sayi[i+1]; sayi[i+1]=tut; } } } printf("\n\nKucukten buyuge siralamasi :"); for (i=0;i<10;i++) { printf("\n%d\t",sayi[i]); } printf("\n\nCikmak icin enter tusuna basiniz."); return 0; }
[ "noreply@github.com" ]
cyberteknik.noreply@github.com
7e71dc979deffdaa5f10f89a53063edc2a7e3550
23866116bb245ec5c4704f0b4336e91fc85e0506
/Solution/PhoenixEngine/Source/Rendering/GL/GLTypes.cpp
daf47bf5af34faac57926cdba504944ab1279e2b
[ "MIT" ]
permissive
rohunb/PhoenixEngine
6ce19c45b4acf1fc78d49d68da21c8d80e5fbe2f
4d21f9000c2e0c553c398785e8cebff1bc190a8c
refs/heads/master
2021-05-07T00:33:53.239503
2017-11-09T19:51:43
2017-11-09T19:51:43
110,158,005
2
0
null
null
null
null
UTF-8
C++
false
false
3,164
cpp
#include "Stdafx.h" #include "Rendering/GL/GLTypes.h" #include "Utility/Debug/Assert.h" namespace Phoenix { namespace GL { const FChar* EError::ToString(const EError::Type GLError) { switch (GLError) { case EError::None: return "GL_NO_ERROR"; case EError::InvalidEnum: return "GL_INVALID_ENUM"; case EError::InvalidValue: return "GL_INVALID_VALUE"; case EError::InvalidOperation: return "GL_INVALID_OPERATION"; case EError::InvalidFrameBufferOperation: return "GL_INVALID_FRAMEBUFFER_OPERATION"; case EError::OutOfMemory: return "GL_OUT_OF_MEMORY"; case EError::StackUnderflow: return "GL_STACK_UNDERFLOW"; case EError::StackOverflow: return "GL_STACK_OVERFLOW"; default: F_Assert(false, "Invalid error ID."); break; } F_Assert(false, "Invalid error handling."); return nullptr; } const FChar* EError::ToDescription(const EError::Type GLError) { switch (GLError) { case EError::None: return "No error has been recorded."; case EError::InvalidEnum: return "An unacceptable value is specified for an enumerated argument."; case EError::InvalidValue: return "A numeric argument is out of range."; case EError::InvalidOperation: return "The specified operation is not allowed in the current state."; case EError::InvalidFrameBufferOperation: return "The framebuffer object is not complete."; case EError::OutOfMemory: return "There is not enough memory left to execute the command."; case EError::StackUnderflow: return "An attempt has been made to perform an operation that would cause an internal stack to underflow."; case EError::StackOverflow: return "An attempt has been made to perform an operation that would cause an internal stack to overflow."; default: F_Assert(false, "Invalid error ID."); break; } F_Assert(false, "Invalid error handling."); return nullptr; } const FChar* EGBufferStatus::ToString(const EGBufferStatus::Type GBufferStatus) { switch (GBufferStatus) { case EGBufferStatus::Complete: return "GL_FRAMEBUFFER_COMPLETE"; case EGBufferStatus::Undefined: return "GL_FRAMEBUFFER_UNDEFINED"; case EGBufferStatus::IncompleteAttachment: return "GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT"; case EGBufferStatus::IncompleteMissingAttachment: return "GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT"; case EGBufferStatus::IncompleteDrawBuffer: return "GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER"; case EGBufferStatus::IncompleteReadBuffer: return "GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER"; case EGBufferStatus::Unsupported: return "GL_FRAMEBUFFER_UNSUPPORTED"; case EGBufferStatus::IncompleteMultiSample: return "GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE"; case EGBufferStatus::IncompleteLayerTargets: return "GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS"; case EGBufferStatus::Error: return "ERROR"; default: F_Assert(false, "Invalid GBufferStatus."); break; } F_Assert(false, "Invalid error handling."); return nullptr; } } }
[ "rohunb@gmail.com" ]
rohunb@gmail.com
4fadd1ec3e07d89b5517da34d1deab48bf136b28
7ad3de59e656b0f942aad539c6e5c16c7cdf9bdd
/lab_debug/cs225/HSLAPixel.cpp
879c1db92c7a3d88de6f8c5a14b4a79200d806d8
[]
no_license
wenqian-ye/Data_Structure
d22b3792d70e3772af2199ff7330fd2a12a3c805
44126a1cb43f05bb85ebffca2e075b1951939d1c
refs/heads/master
2022-01-31T19:10:49.373888
2019-08-13T15:49:25
2019-08-13T15:49:25
202,177,041
1
0
null
null
null
null
UTF-8
C++
false
false
2,276
cpp
/** * @file HSLAPixel.cpp * Implementation of the HSLAPixel class for use in with the PNG library. * * @author CS 225: Data Structures * @version 2018r1 */ #include "HSLAPixel.h" #include <cmath> #include <iostream> using namespace std; namespace cs225 { HSLAPixel::HSLAPixel() { h = 0; s = 0; l = 1.0; a = 1.0; } HSLAPixel::HSLAPixel(double hue, double saturation, double luminance) { h = hue; s = saturation; l = luminance; a = 1.0; } HSLAPixel::HSLAPixel(double hue, double saturation, double luminance, double alpha) { h = hue; s = saturation; l = luminance; a = alpha; } HSLAPixel & HSLAPixel::operator=(HSLAPixel const & other) { this->h = other.h; this->s = other.s; this->l = other.l; this->a = other.a; return *this; } bool HSLAPixel::operator== (HSLAPixel const & other) const { // thank/blame Wade for the following function if (fabs(a - other.a) > 0.01) { return false; } if ( a == 0 ) { return true; } if (fabs(l - other.l) > 0.01) { return false; } if (l == 0 || l == 1) { return true; } if (fabs(s - other.s) > 0.01) { return false; } if (s == 0) { return true; } if (fabs(h - other.h) < 0.5 || fabs(h - other.h) > 359.5 ) { return true; } else { return false; } } bool HSLAPixel::operator!= (HSLAPixel const & other) const { return !(*this == other); } bool HSLAPixel::operator< (HSLAPixel const & other) const { if (*this == other) { return false; } if (l < other.l) return true; else if (l > other.l) return false; // == lumininance if (s < other.s) return true; else if (s > other.s) return false; // == saturation if (h < other.h) return true; else if (h > other.h) return false; // == hue if (a < other.a) return true; else if (a > other.a) return false; // == alpha // same pixel return false; } std::ostream & operator<<(std::ostream & out, HSLAPixel const & pixel) { out << "(" << pixel.h << ", " << pixel.s << ", " << pixel.l << (pixel.a != 1 ? ", " + std::to_string(pixel.a) : "") << ")"; return out; } }
[ "wenqian3@illinois.edu" ]
wenqian3@illinois.edu
a5dce251a82eb39255578fea1e6cb9940a124aac
3d4f69dba44f5e285c19c6762494073148011bbe
/solution/332. Reconstruct Itinerary/332_02.cpp
d6a92ad2bc4c69df1f7b49a7a9807fb85f559736
[]
no_license
cmeslo/leetcode
a0fd9826aaf77380c6cfb6bd24f26024345077be
9b304046c2727364a3c9e5c513cb312fabdc729e
refs/heads/master
2023-08-31T02:34:56.962597
2023-08-30T17:06:07
2023-08-30T17:06:07
96,622,859
0
0
null
null
null
null
UTF-8
C++
false
false
832
cpp
class Solution { public: vector<string> findItinerary(vector<vector<string>>& tickets) { for (const vector<string>& t : tickets) { _trips[t[0]].push_back(t[1]); } for (auto& it : _trips) { auto& dests = it.second; std::sort(dests.begin(), dests.end()); } postOrderTraversal("JFK"); return vector<string>(_route.rbegin(), _route.rend()); } private: unordered_map<string, deque<string>> _trips; vector<string> _route; void postOrderTraversal(string root) { auto& dests = _trips[root]; while (!dests.empty()) { const string dest = dests.front(); dests.pop_front(); postOrderTraversal(dest); } _route.push_back(root); } };
[ "noreply@github.com" ]
cmeslo.noreply@github.com
1f03a6316db7c3882ca69c4da29f442463e200a5
ed51b0a0514d160658c7e8d66a53427122bfb3d5
/mips-processor-simulation-master/main.cpp
7b6adc7f296f052828d8c9978ba97244d61512c2
[ "MIT" ]
permissive
OliverCho18/NonPipelined-Processor
e83d82d5a72f483ba50fb49dee90125d2817ce21
2cf13ae4bad83f73a7d6d7082c6bedfe07e9021d
refs/heads/main
2022-12-19T12:59:31.769892
2020-09-13T23:52:13
2020-09-13T23:52:13
294,861,458
0
0
null
null
null
null
UTF-8
C++
false
false
254
cpp
#include "Processor.h" using namespace std; int main(int argc, char** argv) { if(argc != 2) { cout << "Usage: " << "./simExec [config file]" << endl; return 0; } string configFile = argv[1]; Processor sim(configFile); sim.run(); return 0; }
[ "olivercho@Olivers-MacBook-Pro.local" ]
olivercho@Olivers-MacBook-Pro.local
b850911e5872ac68a6883a96d24b8da585b5e2c2
b57193090bbfa5838f1e673f37ac82ad26286b54
/src/http/PList.cxx
f6a3b785bde52f725f8525451b63a639d4643e6b
[]
no_license
luckydonald-backup/beng-proxy
8021e4fe7bb06e24b6f7d2a5464fc6051a8df25f
34ef0a94c7005bde20390c3b60a6439cc6770573
refs/heads/master
2020-05-24T20:56:31.428664
2019-05-16T08:40:44
2019-05-16T09:14:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,507
cxx
/* * Copyright 2007-2019 Content Management AG * All rights reserved. * * author: Max Kellermann <mk@cm4all.com> * * 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. * * 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 * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "PList.hxx" #include "pool/pool.hxx" #include "util/StringStrip.hxx" #include "util/StringView.hxx" #include <string.h> char ** http_list_split(struct pool &pool, const char *p) noexcept { constexpr size_t MAX_ITEMS = 64; char *tmp[MAX_ITEMS + 1]; /* XXX dynamic allocation */ size_t num = 0; do { const char *comma, *end; /* skip whitespace */ p = StripLeft(p); if (*p == 0) break; /* find the next delimiter */ end = comma = strchr(p, ','); if (end == nullptr) /* last element */ end = p + strlen(p); /* delete trailing whitespace */ end = StripRight(p, end); /* append new list item */ tmp[num++] = p_strdup_lower(pool, StringView(p, end)); if (comma == nullptr) /* this was the last element */ break; /* continue after the comma */ p = comma + 1; } while (num < MAX_ITEMS); tmp[num++] = nullptr; return (char**)p_memdup(&pool, tmp, num * sizeof(tmp[0])); }
[ "mk@cm4all.com" ]
mk@cm4all.com
4754818e992bd1c54ae10b7c4f5fb9ee09a60fe1
a2a3d4b43577559df50f56076391d2f0df60a7aa
/diagram/ggate.h
c529e56883f3f0995b8d15392dbc450317e461fb
[ "MIT" ]
permissive
juanmacaaz/LogicSimulator
5bab2563b81ab1101aa7c7de2f787a8948978cde
27f402b4345bc992b6331ad4ed027c8b7ae8f742
refs/heads/master
2022-11-09T03:09:16.074008
2020-06-26T08:56:08
2020-06-26T08:56:08
250,613,012
1
0
null
null
null
null
UTF-8
C++
false
false
825
h
#ifndef ANDITEM_H #define ANDITEM_H #include <QGraphicsPixmapItem> #include <QDir> #include <typeinfo> #include "diagram/gvertex.h" class GGate : public QObject, public QGraphicsPixmapItem { Q_OBJECT public: enum Element { XOR, AND, OR, INV , INPUT, OUTPUT}; GGate(int x, int y, long id); ~GGate(); GVertex* getVertexA() const {return m_vertexA;}; GVertex* getVertexB() const {return m_vertexB;}; void mouseMoveEvent(QGraphicsSceneMouseEvent *event); void mousePressEvent(QGraphicsSceneMouseEvent *event); bool isEqual(GGate* gate); long getId() const { return m_id;} void disActiveVertex(); protected: void moveVertexs(int x, int y); private: GVertex *m_vertexA; GVertex *m_vertexB; long m_id; signals: void gateClicked(GGate* gate); }; #endif // ANDITEM_H
[ "juanma.caaz@gmai.com" ]
juanma.caaz@gmai.com
27a3b7328dc0c9c3cfe283f88f463984ff84f11a
f9185f58ac3d826bad491b7c6a943c65618f48e9
/object_pointor.cpp
d9773c756e0a627624ab0aea4bbee6c77d459e63
[]
no_license
ashwani471/c-_opps
315e4accef5309c15af04b0fb882a97a83c7c263
53dd065a2391c2c92864db5901362e5f030dd054
refs/heads/master
2023-08-23T11:20:07.859248
2021-10-18T10:10:19
2021-10-18T10:10:19
401,703,269
0
0
null
null
null
null
UTF-8
C++
false
false
392
cpp
#include<iostream> using namespace std; class Box{ private: int l,b,h; public: void setData(int x,int y,int z){ l=x; b=y; h=z; } void showData(){ cout<<"l="<<l<<" b="<<b<<" h="<<h<<endl; } }; int main(){ Box b; Box *p; p=&b; // b.setData(2 , 3,4); // b.showData(); p->setData(3,4,5); p->showData(); }
[ "ashwanikumar351999@gmail.com" ]
ashwanikumar351999@gmail.com
7ab94d49d0a3593524a7555cb7638a4ef4d3c8b0
fb20c87ddf78f76a29fc6c7a6204f0ea825f59b2
/cpptest_yagarto/library/usb/message.h
2794478c20f0c840564d4b5d8f4da419fbf6e34b
[]
no_license
ChenMH1989/uhs20_stm32
17ab108e31d083090a600a3b7bc3b22820007fd0
2975e7b4791fee444758dfbf3506f1af008ef28b
refs/heads/master
2021-04-26T11:46:19.494900
2013-11-29T14:37:45
2013-11-29T14:37:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,645
h
/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. This software may be distributed and modified under the terms of the GNU General Public License version 2 (GPL2) as published by the Free Software Foundation and appearing in the file GPL2.TXT included in the packaging of this file. Please note that GPL2 Section 2[b] requires that all works based on this software must also be made publicly available under the terms of the GPL2 ("Copyleft"). Contact information ------------------- Circuits At Home, LTD Web : http://www.circuitsathome.com e-mail : support@circuitsathome.com */ #if !defined(__MESSAGE_H__) #define __MESSAGE_H__ // uncomment to activate //#define DEBUG_USB_HOST #define PSTR(x) x //hzx reserved #include <inttypes.h> //#include <avr/pgmspace.h> extern int UsbDEBUGlvl; #include "printhex.h" void E_Notify(char const * msg, int lvl); void E_Notify(uint8_t b, int lvl); void E_NotifyStr(char const * msg, int lvl); void E_Notifyc(char c, int lvl); #ifdef DEBUG_USB_HOST #define Notify E_Notify #define NotifyStr E_NotifyStr #define Notifyc E_Notifyc void NotifyFailGetDevDescr(uint8_t reason); void NotifyFailSetDevTblEntry(uint8_t reason); void NotifyFailGetConfDescr(uint8_t reason); void NotifyFailGetDevDescr(void); void NotifyFailSetDevTblEntry(void); void NotifyFailGetConfDescr(void); void NotifyFailSetConfDescr(void); void NotifyFailUnknownDevice(uint16_t VID, uint16_t PID); void NotifyFail(uint8_t rcode); #else //#define Notify(...) ((void)0) #define Notify E_Notify #define NotifyStr E_NotifyStr //#define NotifyStr(...) ((void)0) #define Notifyc(...) ((void)0) #define NotifyFailGetDevDescr(...) ((void)0) #define NotifyFailSetDevTblEntry(...) ((void)0) #define NotifyFailGetConfDescr(...) ((void)0) #define NotifyFailGetDevDescr(...) ((void)0) #define NotifyFailSetDevTblEntry(...) ((void)0) #define NotifyFailGetConfDescr(...) ((void)0) #define NotifyFailSetConfDescr(...) ((void)0) #define NotifyFailUnknownDevice(...) ((void)0) #define NotifyFail(...) ((void)0) #endif template <class ERROR_TYPE> void ErrorMessage(uint8_t level, char const * msg, ERROR_TYPE rcode = 0) { #if 1 //def DEBUG_USB_HOST Notify(msg, level); Notify(PSTR(": "), level); D_PrintHex<ERROR_TYPE > (rcode, level); Notify(PSTR("\r\n"), level); #endif } template <class ERROR_TYPE> void ErrorMessage(char const * msg, ERROR_TYPE rcode = 0) { #if 1 //def DEBUG_USB_HOST Notify(msg, 0x90); Notify(PSTR(": "), 0x90); D_PrintHex<ERROR_TYPE > (rcode, 0x90); Notify(PSTR("\r\n"), 0x90); #endif } //#include "hexdump.h" #endif // __MESSAGE_H__
[ "hozenshi@gmail.com" ]
hozenshi@gmail.com
d72f0abe91bd4165ac51c46509e87019e853a6bb
ad5b72656f0da99443003984c1e646cb6b3e67ea
/src/plugins/intel_gna/tests/unit/transformations/gna_reorder_activation_and_pooling.cpp
7bacd1ea4e5885b41933283994f8a36ddfabbb6c
[ "Apache-2.0" ]
permissive
novakale/openvino
9dfc89f2bc7ee0c9b4d899b4086d262f9205c4ae
544c1acd2be086c35e9f84a7b4359439515a0892
refs/heads/master
2022-12-31T08:04:48.124183
2022-12-16T09:05:34
2022-12-16T09:05:34
569,671,261
0
0
null
null
null
null
UTF-8
C++
false
false
23,617
cpp
// Copyright (C) 2018-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <gtest/gtest.h> #include "transformations/reorder_activation_and_pooling.hpp" #include "common_test_utils/ngraph_test_utils.hpp" #include <ngraph/function.hpp> #include <ngraph/opsets/opset7.hpp> #include <ngraph/pass/manager.hpp> #include <transformations/init_node_info.hpp> namespace testing { namespace { class IActivationNodeFactory { public: virtual ~IActivationNodeFactory() = default; virtual std::shared_ptr<ngraph::Node> createNode(const ngraph::Output<ngraph::Node>& in) = 0; }; template <typename ActivationT> class ActivationNodeFactory : public IActivationNodeFactory { public: ActivationNodeFactory() = default; std::shared_ptr<ngraph::Node> createNode(const ngraph::Output<ngraph::Node>& operation_before) override { return std::make_shared<ActivationT>(operation_before); } private: ActivationNodeFactory(const ActivationNodeFactory&) = delete; ActivationNodeFactory& operator=(const ActivationNodeFactory& ) = delete; }; template <> class ActivationNodeFactory <ngraph::opset7::Clamp> : public IActivationNodeFactory { public: ActivationNodeFactory(const double min, const double max) : min_(min), max_(max) {} std::shared_ptr<ngraph::Node> createNode(const ngraph::Output<ngraph::Node>& operation_before) override { return std::make_shared<ngraph::opset7::Clamp>(operation_before, min_, max_); } private: ActivationNodeFactory(const ActivationNodeFactory&) = delete; ActivationNodeFactory& operator=(const ActivationNodeFactory& ) = delete; private: const double min_; const double max_; }; using ActivationFactoryPtr = std::shared_ptr<IActivationNodeFactory>; template <typename ActivationT, typename ... Args> ActivationFactoryPtr createActivationFactory(Args&& ... args) { return std::make_shared<ActivationNodeFactory<ActivationT>>(std::forward<Args>(args) ...); } // ---------------------------------------------------------------------------------------------------------------------- /* Variants: Convolution -> Add -> Activation -> MaxPool Convolution -> Activation -> MaxPool */ typedef std::tuple< ActivationFactoryPtr, // activation Node factory bool // do we need to create ngraph::opset7::Add Node or not > ConvolutionActivationPoolTestOptions; class ConvolutionActivationPoolTestFixture : public CommonTestUtils::TestsCommon, public testing::WithParamInterface<ConvolutionActivationPoolTestOptions> { public: void SetUp() override; std::shared_ptr<ngraph::Function> get_initial_function(ActivationFactoryPtr activation_factory, bool isAddNodeNeeded); std::shared_ptr<ngraph::Function> get_reference(ActivationFactoryPtr activation_factory, bool isAddNodeNeeded); public: std::shared_ptr<ngraph::Function> function, reference_function; }; void ConvolutionActivationPoolTestFixture::SetUp() { ActivationFactoryPtr activation_factory; bool isAddNodeNeeded = false; std::tie(activation_factory, isAddNodeNeeded) = GetParam(); function = get_initial_function(activation_factory, isAddNodeNeeded); reference_function = get_reference(activation_factory, isAddNodeNeeded); } std::shared_ptr<ngraph::Function> ConvolutionActivationPoolTestFixture::get_initial_function(ActivationFactoryPtr activation_factory, bool isAddNodeNeeded) { auto input_params_convolution = std::make_shared<ngraph::opset7::Parameter>(ngraph::element::f32, ngraph::Shape{1, 3, 64, 64}); auto input_params_add = std::make_shared<ngraph::opset7::Parameter>(ngraph::element::f32, ngraph::Shape{1, 3, 64, 64}); auto weights = ngraph::opset7::Constant::create(ngraph::element::f32, ngraph::Shape{3, 3, 1, 1}, {1}); auto bias = ngraph::opset7::Constant::create(ngraph::element::f32, ngraph::Shape{3, 1, 1}, {1}); auto convolution_operation = std::make_shared<ngraph::opset7::Convolution>(input_params_convolution, weights, ngraph::Strides{1, 1}, ngraph::CoordinateDiff{0, 0}, ngraph::CoordinateDiff{0, 0}, ngraph::Strides{1, 1}); std::shared_ptr<ngraph::op::Op> last_operation = convolution_operation; if (isAddNodeNeeded) { auto add_operation = std::make_shared<ngraph::opset7::Add>(convolution_operation, input_params_add); last_operation = add_operation; } auto activation = activation_factory->createNode(last_operation); auto max_pool_operation = std::make_shared<ngraph::opset7::MaxPool>(activation, ngraph::Strides{1, 1}, ngraph::Shape{1, 1}, ngraph::Shape{1, 1}, ngraph::Shape{1, 1}); auto result = std::make_shared<ngraph::opset7::Result>(max_pool_operation); return std::make_shared<ngraph::Function>(ngraph::ResultVector{result}, ngraph::ParameterVector{input_params_convolution, input_params_add}); } std::shared_ptr<ngraph::Function> ConvolutionActivationPoolTestFixture::get_reference(ActivationFactoryPtr activation_factory, bool isAddNodeNeeded) { auto input_params_convolution = std::make_shared<ngraph::opset7::Parameter>(ngraph::element::f32, ngraph::Shape{1, 3, 64, 64}); auto input_params_add = std::make_shared<ngraph::opset7::Parameter>(ngraph::element::f32, ngraph::Shape{1, 3, 64, 64}); auto weights = ngraph::opset7::Constant::create(ngraph::element::f32, ngraph::Shape{3, 3, 1, 1}, {1}); auto bias = ngraph::opset7::Constant::create(ngraph::element::f32, ngraph::Shape{3, 1, 1}, {1}); auto convolution_operation = std::make_shared<ngraph::opset7::Convolution>(input_params_convolution, weights, ngraph::Strides{1, 1}, ngraph::CoordinateDiff{0, 0}, ngraph::CoordinateDiff{0, 0}, ngraph::Strides{1, 1}); std::shared_ptr<ngraph::op::Op> last_operation = convolution_operation; if (isAddNodeNeeded) { auto add_operation = std::make_shared<ngraph::opset7::Add>(convolution_operation, input_params_convolution); last_operation = add_operation; } auto max_pool_operation = std::make_shared<ngraph::opset7::MaxPool>(last_operation, ngraph::Strides{1, 1}, ngraph::Shape{1, 1}, ngraph::Shape{1, 1}, ngraph::Shape{1, 1}); auto activation = activation_factory->createNode(max_pool_operation); auto result = std::make_shared<ngraph::opset7::Result>(activation); return std::make_shared<ngraph::Function>(ngraph::ResultVector{result}, ngraph::ParameterVector{input_params_convolution, input_params_add}); } void execute_test(std::shared_ptr<ngraph::Function> function, std::shared_ptr<ngraph::Function> reference_function) { ngraph::pass::Manager manager; manager.register_pass<ngraph::pass::InitNodeInfo>(); manager.register_pass<ov::intel_gna::pass::ReorderActivationAndPooling>(); manager.run_passes(function); const FunctionsComparator func_comparator = FunctionsComparator::with_default().enable(FunctionsComparator::ATTRIBUTES); const FunctionsComparator::Result result = func_comparator(function, reference_function); ASSERT_TRUE(result.valid); } TEST_P(ConvolutionActivationPoolTestFixture, CompareFunctions) { execute_test(function, reference_function); } const std::vector<ActivationFactoryPtr> activationFactories = { createActivationFactory<ngraph::opset7::Relu>(), createActivationFactory<ngraph::opset7::Sigmoid>(), createActivationFactory<ngraph::opset7::Tanh>(), createActivationFactory<ngraph::opset7::Abs>(), createActivationFactory<ngraph::opset7::Log>(), createActivationFactory<ngraph::opset7::Exp>(), createActivationFactory<ngraph::opset7::Sign>(), createActivationFactory<ngraph::opset7::Clamp>(0.1, 0.2) }; INSTANTIATE_TEST_SUITE_P(ConvolutionActivationPoolTestSuite, ConvolutionActivationPoolTestFixture, ::testing::Combine(::testing::ValuesIn(activationFactories), ::testing::ValuesIn(std::vector<bool>{true, false}))); //----------------------------------------------------------------------------------------------------------- // Variant Convolution -> FakeQuantize -> MaxPool : ConvFqMp TEST(TransformationTests, ReorderActivationAndPoolingTestConvFqMp) { std::shared_ptr<ngraph::Function> func(nullptr), reference_func(nullptr); { auto input_params_convolution = std::make_shared<ngraph::opset7::Parameter>(ngraph::element::f32, ngraph::Shape{1, 3, 64, 64}); auto weights = ngraph::opset7::Constant::create(ngraph::element::f32, ngraph::Shape{3, 3, 1, 1}, {1}); auto bias = ngraph::opset7::Constant::create(ngraph::element::f32, ngraph::Shape{3, 1, 1}, {1}); auto convolution_operation = std::make_shared<ngraph::opset7::Convolution>(input_params_convolution, weights, ngraph::Strides{1, 1}, ngraph::CoordinateDiff{0, 0}, ngraph::CoordinateDiff{0, 0}, ngraph::Strides{1, 1}); auto input_low = ngraph::opset7::Constant::create(ngraph::element::f32, ngraph::Shape{1}, {1}); auto input_high = ngraph::opset7::Constant::create(ngraph::element::f32, ngraph::Shape{1}, {20}); auto output_low = ngraph::opset7::Constant::create(ngraph::element::f32, ngraph::Shape{1}, {0}); auto output_high = ngraph::opset7::Constant::create(ngraph::element::f32, ngraph::Shape{1}, {10}); auto fake_quantize_op = std::make_shared<ngraph::opset7::FakeQuantize>(convolution_operation, input_low, input_high, output_low, output_high, 11); auto max_pool_operation = std::make_shared<ngraph::opset7::MaxPool>(fake_quantize_op, ngraph::Strides{1, 1}, ngraph::Shape{1, 1}, ngraph::Shape{1, 1}, ngraph::Shape{1, 1}); auto result = std::make_shared<ngraph::opset7::Result>(max_pool_operation); func = std::make_shared<ngraph::Function>(ngraph::ResultVector{result}, ngraph::ParameterVector{input_params_convolution}); ngraph::pass::Manager m; m.register_pass<ngraph::pass::InitNodeInfo>(); m.register_pass<ov::intel_gna::pass::ReorderActivationAndPooling>(); m.run_passes(func); ASSERT_NO_THROW(check_rt_info(func)); } { auto input_params_convolution = std::make_shared<ngraph::opset7::Parameter>(ngraph::element::f32, ngraph::Shape{1, 3, 64, 64}); auto weights = ngraph::opset7::Constant::create(ngraph::element::f32, ngraph::Shape{3, 3, 1, 1}, {1}); auto bias = ngraph::opset7::Constant::create(ngraph::element::f32, ngraph::Shape{3, 1, 1}, {1}); auto convolution_operation = std::make_shared<ngraph::opset7::Convolution>(input_params_convolution, weights, ngraph::Strides{1, 1}, ngraph::CoordinateDiff{0, 0}, ngraph::CoordinateDiff{0, 0}, ngraph::Strides{1, 1}); auto max_pool_operation = std::make_shared<ngraph::opset7::MaxPool>(convolution_operation, ngraph::Strides{1, 1}, ngraph::Shape{1, 1}, ngraph::Shape{1, 1}, ngraph::Shape{1, 1}); auto input_low = ngraph::opset7::Constant::create(ngraph::element::f32, ngraph::Shape{1}, {1}); auto input_high = ngraph::opset7::Constant::create(ngraph::element::f32, ngraph::Shape{1}, {20}); auto output_low = ngraph::opset7::Constant::create(ngraph::element::f32, ngraph::Shape{1}, {0}); auto output_high = ngraph::opset7::Constant::create(ngraph::element::f32, ngraph::Shape{1}, {10}); auto fake_quantize_op = std::make_shared<ngraph::opset7::FakeQuantize>(max_pool_operation, input_low, input_high, output_low, output_high, 11); auto result = std::make_shared<ngraph::opset7::Result>(fake_quantize_op); reference_func = std::make_shared<ngraph::Function>(ngraph::ResultVector{result}, ngraph::ParameterVector{input_params_convolution}); } const FunctionsComparator func_comparator = FunctionsComparator::with_default().enable(FunctionsComparator::ATTRIBUTES); const FunctionsComparator::Result result = func_comparator(func, reference_func); ASSERT_TRUE(result.valid); } // Variant Convolution -> Add -> FakeQuantize -> MaxPool : ConvAddFqMp TEST(TransformationTests, ReorderActivationAndPoolingTestConvAddFqMp) { std::shared_ptr<ngraph::Function> func(nullptr), reference_func(nullptr); { auto input_params_convolution = std::make_shared<ngraph::opset7::Parameter>(ngraph::element::f32, ngraph::Shape{1, 3, 64, 64}); auto input_params_add = std::make_shared<ngraph::opset7::Parameter>(ngraph::element::f32, ngraph::Shape{1, 3, 64, 64}); auto weights = ngraph::opset7::Constant::create(ngraph::element::f32, ngraph::Shape{3, 3, 1, 1}, {1}); auto bias = ngraph::opset7::Constant::create(ngraph::element::f32, ngraph::Shape{3, 1, 1}, {1}); auto convolution_operation = std::make_shared<ngraph::opset7::Convolution>(input_params_convolution, weights, ngraph::Strides{1, 1}, ngraph::CoordinateDiff{0, 0}, ngraph::CoordinateDiff{0, 0}, ngraph::Strides{1, 1}); auto add_operation = std::make_shared<ngraph::opset7::Add>(convolution_operation, input_params_add); auto input_low = ngraph::opset7::Constant::create(ngraph::element::f32, ngraph::Shape{1}, {1}); auto input_high = ngraph::opset7::Constant::create(ngraph::element::f32, ngraph::Shape{1}, {20}); auto output_low = ngraph::opset7::Constant::create(ngraph::element::f32, ngraph::Shape{1}, {0}); auto output_high = ngraph::opset7::Constant::create(ngraph::element::f32, ngraph::Shape{1}, {10}); auto fake_quantize_op = std::make_shared<ngraph::opset7::FakeQuantize>(add_operation, input_low, input_high, output_low, output_high, 11); auto max_pool_operation = std::make_shared<ngraph::opset7::MaxPool>(fake_quantize_op, ngraph::Strides{1, 1}, ngraph::Shape{1, 1}, ngraph::Shape{1, 1}, ngraph::Shape{1, 1}); auto result = std::make_shared<ngraph::opset7::Result>(max_pool_operation); func = std::make_shared<ngraph::Function>(ngraph::ResultVector{result}, ngraph::ParameterVector{input_params_convolution, input_params_add}); ngraph::pass::Manager m; m.register_pass<ngraph::pass::InitNodeInfo>(); m.register_pass<ov::intel_gna::pass::ReorderActivationAndPooling>(); m.run_passes(func); ASSERT_NO_THROW(check_rt_info(func)); } { auto input_params_convolution = std::make_shared<ngraph::opset7::Parameter>(ngraph::element::f32, ngraph::Shape{1, 3, 64, 64}); auto input_params_add = std::make_shared<ngraph::opset7::Parameter>(ngraph::element::f32, ngraph::Shape{1, 3, 64, 64}); auto weights = ngraph::opset7::Constant::create(ngraph::element::f32, ngraph::Shape{3, 3, 1, 1}, {1}); auto bias = ngraph::opset7::Constant::create(ngraph::element::f32, ngraph::Shape{3, 1, 1}, {1}); auto convolution_operation = std::make_shared<ngraph::opset7::Convolution>(input_params_convolution, weights, ngraph::Strides{1, 1}, ngraph::CoordinateDiff{0, 0}, ngraph::CoordinateDiff{0, 0}, ngraph::Strides{1, 1}); auto add_operation = std::make_shared<ngraph::opset7::Add>(convolution_operation, input_params_add); auto max_pool_operation = std::make_shared<ngraph::opset7::MaxPool>(add_operation, ngraph::Strides{1, 1}, ngraph::Shape{1, 1}, ngraph::Shape{1, 1}, ngraph::Shape{1, 1}); auto input_low = ngraph::opset7::Constant::create(ngraph::element::f32, ngraph::Shape{1}, {1}); auto input_high = ngraph::opset7::Constant::create(ngraph::element::f32, ngraph::Shape{1}, {20}); auto output_low = ngraph::opset7::Constant::create(ngraph::element::f32, ngraph::Shape{1}, {0}); auto output_high = ngraph::opset7::Constant::create(ngraph::element::f32, ngraph::Shape{1}, {10}); auto fake_quantize_op = std::make_shared<ngraph::opset7::FakeQuantize>(max_pool_operation, input_low, input_high, output_low, output_high, 11); auto result = std::make_shared<ngraph::opset7::Result>(fake_quantize_op); reference_func = std::make_shared<ngraph::Function>(ngraph::ResultVector{result}, ngraph::ParameterVector{input_params_convolution, input_params_add}); } const FunctionsComparator func_comparator = FunctionsComparator::with_default().enable(FunctionsComparator::ATTRIBUTES); const FunctionsComparator::Result result = func_comparator(func, reference_func); ASSERT_TRUE(result.valid); } } // namespace } // namespace testing
[ "noreply@github.com" ]
novakale.noreply@github.com
aed9fb6a238da57b62833c6ea99af33b13532c9b
d50ed351970ec2e0b64405aeba50e66657d6ccce
/arduino/include/filters/savitzky_golay.h
59c828799f376f59d135e1ac31767365d6e40511
[]
no_license
tszabo-ro/balancer
b412b794f31fb9764ea0185084e0816a93338e84
3e1883297821f0417405040a6fab747f3c2f3a40
refs/heads/master
2022-04-12T13:59:14.254580
2020-04-05T19:29:30
2020-04-05T19:29:30
248,745,608
0
0
null
null
null
null
UTF-8
C++
false
false
2,324
h
#ifndef SavitzkyGolay_H #define SavitzkyGolay_H #include "../primitives/array.h" #include "../primitives/ring_buffer.h" #include <stdio.h> // Implementation based on http://www.personal.psu.edu/users/m/r/mrh318/Gorry-AC-1990.pdf namespace { double gramPoly(int i, int m, int k, int s) { if (k > 0) { return (4. * k - 2.) / (k * (2. * m - k + 1.)) * (i * gramPoly(i, m, k - 1, s) + s * gramPoly(i, m, k - 1, s - 1)) - ((k - 1.) * (2. * m + k)) / (k * (2. * m - k + 1.)) * gramPoly(i, m, k - 2, s); } else { if (k == 0 && s == 0) return 1.; else return 0.; } } double generalizedFactorial(int a, int b) { double gf = 1.; for (int j = (a - b) + 1; j <= a; j++) { gf *= j; } return gf; } double computeWeight(int i, int t, int m, int n, int s) { double w = 0; for (int k = 0; k <= n; ++k) { w = w + (2 * k + 1) * (generalizedFactorial(2 * m, k) / generalizedFactorial(2 * m + k + 1, k + 1)) * gramPoly(i, m, k, 0) * gramPoly(t, m, k, s); } return w; } template<unsigned long m> static Array<double, (2*m+1)> computeWeights(const int t, const int n, const int s) { Array<double, (2*m+1)> weights; for (unsigned long i = 0; i < 2 * m + 1; ++i) { weights[i] = computeWeight(i - m, t, m, n, s); } return weights; } } template<typename T, unsigned int m_elements, unsigned int n_order, int t_th_pos> class SavitzkyGolayFilter { public: SavitzkyGolayFilter(double dt): dt(dt) { // Compute weights for the time window 2*m+1, for the t'th least-square point for (unsigned int s = 0; s < n_order; ++s) // of the s'th derivative { coefficients[s] = computeWeights<m_elements>(t_th_pos, n_order, s); } } void push(T val) { data.push_back(val); } T filter(unsigned int diff_order = 0) { T result = 0; Array<double, 2*m_elements + 1>& coeff = coefficients[diff_order]; for (unsigned long i = 0; i < data.size(); ++i) { result += coeff[i] * data[i]; } return result / pow(dt, diff_order); } private: const double dt; Array<Array<double, 2*m_elements + 1>, n_order - 1> coefficients; RingBuffer<2*m_elements+1, T> data; }; #endif
[ "tamas@tszabo.ro" ]
tamas@tszabo.ro
03b1c644a77541a426972b9a52d3b5ae82b77356
4b8296335e4fa1a38264fef02f430d3b57884cce
/components/autofill/core/common/mojom/autofill_types_mojom_traits.h
6ec777c3a3b301e53bbd3edd052d8a434c7420b9
[ "BSD-3-Clause" ]
permissive
coxchris502/chromium
07ad6d930123bbf6e1754fe1820505f21d719fcd
f786352782a89d148a10d7bdd8ef3d0a86497926
refs/heads/master
2022-11-06T23:54:53.001812
2020-07-03T14:54:27
2020-07-03T14:54:27
276,935,925
1
0
BSD-3-Clause
2020-07-03T15:49:58
2020-07-03T15:49:57
null
UTF-8
C++
false
false
19,973
h
// 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. #ifndef COMPONENTS_AUTOFILL_CORE_COMMON_MOJOM_AUTOFILL_TYPES_MOJOM_TRAITS_H_ #define COMPONENTS_AUTOFILL_CORE_COMMON_MOJOM_AUTOFILL_TYPES_MOJOM_TRAITS_H_ #include <map> #include <string> #include <utility> #include <vector> #include "base/i18n/rtl.h" #include "base/strings/string16.h" #include "components/autofill/core/common/form_data.h" #include "components/autofill/core/common/form_data_predictions.h" #include "components/autofill/core/common/form_field_data.h" #include "components/autofill/core/common/form_field_data_predictions.h" #include "components/autofill/core/common/mojom/autofill_types.mojom.h" #include "components/autofill/core/common/password_form.h" #include "components/autofill/core/common/password_form_fill_data.h" #include "components/autofill/core/common/password_form_generation_data.h" #include "components/autofill/core/common/password_generation_util.h" #include "components/autofill/core/common/renderer_id.h" #include "mojo/public/cpp/base/text_direction_mojom_traits.h" #include "mojo/public/cpp/bindings/struct_traits.h" #include "ui/gfx/geometry/rect_f.h" #include "url/origin.h" namespace mojo { template <> struct StructTraits<autofill::mojom::FormRendererIdDataView, autofill::FormRendererId> { static uint32_t id(autofill::FormRendererId r) { return r.value(); } static bool Read(autofill::mojom::FormRendererIdDataView data, autofill::FormRendererId* out); }; template <> struct StructTraits<autofill::mojom::FieldRendererIdDataView, autofill::FieldRendererId> { static uint32_t id(autofill::FieldRendererId r) { return r.value(); } static bool Read(autofill::mojom::FieldRendererIdDataView data, autofill::FieldRendererId* out); }; template <> struct StructTraits<autofill::mojom::FormFieldDataDataView, autofill::FormFieldData> { static const base::string16& label(const autofill::FormFieldData& r) { return r.label; } static const base::string16& name(const autofill::FormFieldData& r) { return r.name; } static const base::string16& id_attribute(const autofill::FormFieldData& r) { return r.id_attribute; } static const base::string16& name_attribute( const autofill::FormFieldData& r) { return r.name_attribute; } static const base::string16& value(const autofill::FormFieldData& r) { return r.value; } static const std::string& form_control_type( const autofill::FormFieldData& r) { return r.form_control_type; } static const std::string& autocomplete_attribute( const autofill::FormFieldData& r) { return r.autocomplete_attribute; } static const base::string16& placeholder(const autofill::FormFieldData& r) { return r.placeholder; } static const base::string16& css_classes(const autofill::FormFieldData& r) { return r.css_classes; } static const base::string16& aria_label(const autofill::FormFieldData& r) { return r.aria_label; } static const base::string16& aria_description( const autofill::FormFieldData& r) { return r.aria_description; } static autofill::FieldRendererId unique_renderer_id( const autofill::FormFieldData& r) { return r.unique_renderer_id; } static uint32_t properties_mask(const autofill::FormFieldData& r) { return r.properties_mask; } static int32_t form_control_ax_id(const autofill::FormFieldData& r) { return r.form_control_ax_id; } static uint64_t max_length(const autofill::FormFieldData& r) { return r.max_length; } static bool is_autofilled(const autofill::FormFieldData& r) { return r.is_autofilled; } static const std::string& section(const autofill::FormFieldData& r) { return r.section; } static autofill::FormFieldData::CheckStatus check_status( const autofill::FormFieldData& r) { return r.check_status; } static bool is_focusable(const autofill::FormFieldData& r) { return r.is_focusable; } static bool should_autocomplete(const autofill::FormFieldData& r) { return r.should_autocomplete; } static autofill::FormFieldData::RoleAttribute role( const autofill::FormFieldData& r) { return r.role; } static base::i18n::TextDirection text_direction( const autofill::FormFieldData& r) { return r.text_direction; } static bool is_enabled(const autofill::FormFieldData& r) { return r.is_enabled; } static bool is_readonly(const autofill::FormFieldData& r) { return r.is_readonly; } static const base::string16& typed_value(const autofill::FormFieldData& r) { return r.typed_value; } static const std::vector<base::string16>& option_values( const autofill::FormFieldData& r) { return r.option_values; } static const std::vector<base::string16>& option_contents( const autofill::FormFieldData& r) { return r.option_contents; } static autofill::FormFieldData::LabelSource label_source( const autofill::FormFieldData& r) { return r.label_source; } static gfx::RectF bounds(const autofill::FormFieldData& r) { return r.bounds; } static const std::vector<base::string16>& datalist_values( const autofill::FormFieldData& r) { return r.datalist_values; } static const std::vector<base::string16>& datalist_labels( const autofill::FormFieldData& r) { return r.datalist_labels; } static bool Read(autofill::mojom::FormFieldDataDataView data, autofill::FormFieldData* out); }; template <> struct StructTraits<autofill::mojom::ButtonTitleInfoDataView, autofill::ButtonTitleInfo> { static const base::string16& title(const autofill::ButtonTitleInfo& r) { return r.first; } static autofill::mojom::ButtonTitleType type( const autofill::ButtonTitleInfo& r) { return r.second; } static bool Read(autofill::mojom::ButtonTitleInfoDataView data, autofill::ButtonTitleInfo* out); }; template <> struct StructTraits<autofill::mojom::FormDataDataView, autofill::FormData> { static const base::string16& id_attribute(const autofill::FormData& r) { return r.id_attribute; } static const base::string16& name_attribute(const autofill::FormData& r) { return r.name_attribute; } static const base::string16& name(const autofill::FormData& r) { return r.name; } static const autofill::ButtonTitleList& button_titles( const autofill::FormData& r) { return r.button_titles; } static const GURL& url(const autofill::FormData& r) { return r.url; } static const GURL& full_url(const autofill::FormData& r) { return r.full_url; } static const GURL& action(const autofill::FormData& r) { return r.action; } static bool is_action_empty(const autofill::FormData& r) { return r.is_action_empty; } static const url::Origin& main_frame_origin(const autofill::FormData& r) { return r.main_frame_origin; } static bool is_form_tag(const autofill::FormData& r) { return r.is_form_tag; } static bool is_formless_checkout(const autofill::FormData& r) { return r.is_formless_checkout; } static autofill::FormRendererId unique_renderer_id( const autofill::FormData& r) { return r.unique_renderer_id; } static autofill::mojom::SubmissionIndicatorEvent submission_event( const autofill::FormData& r) { return r.submission_event; } static const std::vector<autofill::FormFieldData>& fields( const autofill::FormData& r) { return r.fields; } static const std::vector<autofill::FieldRendererId> username_predictions( const autofill::FormData& r) { return r.username_predictions; } static bool is_gaia_with_skip_save_password_form( const autofill::FormData& d) { return d.is_gaia_with_skip_save_password_form; } static bool Read(autofill::mojom::FormDataDataView data, autofill::FormData* out); }; template <> struct StructTraits<autofill::mojom::FormFieldDataPredictionsDataView, autofill::FormFieldDataPredictions> { static const autofill::FormFieldData& field( const autofill::FormFieldDataPredictions& r) { return r.field; } static const std::string& signature( const autofill::FormFieldDataPredictions& r) { return r.signature; } static const std::string& heuristic_type( const autofill::FormFieldDataPredictions& r) { return r.heuristic_type; } static const std::string& server_type( const autofill::FormFieldDataPredictions& r) { return r.server_type; } static const std::string& overall_type( const autofill::FormFieldDataPredictions& r) { return r.overall_type; } static const std::string& parseable_name( const autofill::FormFieldDataPredictions& r) { return r.parseable_name; } static const std::string& section( const autofill::FormFieldDataPredictions& r) { return r.section; } static bool Read(autofill::mojom::FormFieldDataPredictionsDataView data, autofill::FormFieldDataPredictions* out); }; template <> struct StructTraits<autofill::mojom::FormDataPredictionsDataView, autofill::FormDataPredictions> { static const autofill::FormData& data( const autofill::FormDataPredictions& r) { return r.data; } static const std::string& signature(const autofill::FormDataPredictions& r) { return r.signature; } static const std::vector<autofill::FormFieldDataPredictions>& fields( const autofill::FormDataPredictions& r) { return r.fields; } static bool Read(autofill::mojom::FormDataPredictionsDataView data, autofill::FormDataPredictions* out); }; template <> struct StructTraits<autofill::mojom::PasswordAndMetadataDataView, autofill::PasswordAndMetadata> { static const base::string16& username( const autofill::PasswordAndMetadata& r) { return r.username; } static const base::string16& password( const autofill::PasswordAndMetadata& r) { return r.password; } static const std::string& realm(const autofill::PasswordAndMetadata& r) { return r.realm; } static bool uses_account_store(const autofill::PasswordAndMetadata& r) { return r.uses_account_store; } static bool Read(autofill::mojom::PasswordAndMetadataDataView data, autofill::PasswordAndMetadata* out); }; template <> struct StructTraits<autofill::mojom::PasswordFormFillDataDataView, autofill::PasswordFormFillData> { static autofill::FormRendererId form_renderer_id( const autofill::PasswordFormFillData& r) { return r.form_renderer_id; } static const GURL& url(const autofill::PasswordFormFillData& r) { return r.url; } static const GURL& action(const autofill::PasswordFormFillData& r) { return r.action; } static const autofill::FormFieldData& username_field( const autofill::PasswordFormFillData& r) { return r.username_field; } static const autofill::FormFieldData& password_field( const autofill::PasswordFormFillData& r) { return r.password_field; } static bool username_may_use_prefilled_placeholder( const autofill::PasswordFormFillData& r) { return r.username_may_use_prefilled_placeholder; } static const std::string& preferred_realm( const autofill::PasswordFormFillData& r) { return r.preferred_realm; } static bool uses_account_store(const autofill::PasswordFormFillData& r) { return r.uses_account_store; } static const autofill::PasswordFormFillData::LoginCollection& additional_logins(const autofill::PasswordFormFillData& r) { return r.additional_logins; } static bool wait_for_username(const autofill::PasswordFormFillData& r) { return r.wait_for_username; } static bool has_renderer_ids(const autofill::PasswordFormFillData& r) { return r.has_renderer_ids; } static bool Read(autofill::mojom::PasswordFormFillDataDataView data, autofill::PasswordFormFillData* out); }; template <> struct StructTraits<autofill::mojom::PasswordFormGenerationDataDataView, autofill::PasswordFormGenerationData> { static autofill::FieldRendererId new_password_renderer_id( const autofill::PasswordFormGenerationData& r) { return r.new_password_renderer_id; } static autofill::FieldRendererId confirmation_password_renderer_id( const autofill::PasswordFormGenerationData& r) { return r.confirmation_password_renderer_id; } static bool Read(autofill::mojom::PasswordFormGenerationDataDataView data, autofill::PasswordFormGenerationData* out); }; template <> struct StructTraits<autofill::mojom::PasswordGenerationUIDataDataView, autofill::password_generation::PasswordGenerationUIData> { static const gfx::RectF& bounds( const autofill::password_generation::PasswordGenerationUIData& r) { return r.bounds; } static int max_length( const autofill::password_generation::PasswordGenerationUIData& r) { return r.max_length; } static const base::string16& generation_element( const autofill::password_generation::PasswordGenerationUIData& r) { return r.generation_element; } static autofill::FieldRendererId generation_element_id( const autofill::password_generation::PasswordGenerationUIData& r) { return r.generation_element_id; } static bool is_generation_element_password_type( const autofill::password_generation::PasswordGenerationUIData& r) { return r.is_generation_element_password_type; } static base::i18n::TextDirection text_direction( const autofill::password_generation::PasswordGenerationUIData& r) { return r.text_direction; } static const autofill::FormData& form_data( const autofill::password_generation::PasswordGenerationUIData& r) { return r.form_data; } static bool Read( autofill::mojom::PasswordGenerationUIDataDataView data, autofill::password_generation::PasswordGenerationUIData* out); }; template <> struct StructTraits<autofill::mojom::PasswordFormDataView, autofill::PasswordForm> { static autofill::PasswordForm::Scheme scheme( const autofill::PasswordForm& r) { return r.scheme; } static const std::string& signon_realm(const autofill::PasswordForm& r) { return r.signon_realm; } static const GURL& url(const autofill::PasswordForm& r) { return r.url; } static const GURL& action(const autofill::PasswordForm& r) { return r.action; } static const std::string& affiliated_web_realm( const autofill::PasswordForm& r) { return r.affiliated_web_realm; } static const base::string16& submit_element(const autofill::PasswordForm& r) { return r.submit_element; } static const base::string16& username_element( const autofill::PasswordForm& r) { return r.username_element; } static bool username_marked_by_site(const autofill::PasswordForm& r) { return r.username_marked_by_site; } static const base::string16& username_value(const autofill::PasswordForm& r) { return r.username_value; } static const std::vector<autofill::ValueElementPair>& all_possible_usernames( const autofill::PasswordForm& r) { return r.all_possible_usernames; } static const std::vector<autofill::ValueElementPair>& all_possible_passwords( const autofill::PasswordForm& r) { return r.all_possible_passwords; } static bool form_has_autofilled_value(const autofill::PasswordForm& r) { return r.form_has_autofilled_value; } static const base::string16& password_element( const autofill::PasswordForm& r) { return r.password_element; } static const base::string16& password_value(const autofill::PasswordForm& r) { return r.password_value; } static const base::string16& new_password_element( const autofill::PasswordForm& r) { return r.new_password_element; } static const base::string16& new_password_value( const autofill::PasswordForm& r) { return r.new_password_value; } static bool new_password_marked_by_site(const autofill::PasswordForm& r) { return r.new_password_marked_by_site; } static const base::string16& confirmation_password_element( const autofill::PasswordForm& r) { return r.confirmation_password_element; } static const base::Time& date_created(const autofill::PasswordForm& r) { return r.date_created; } static const base::Time& date_synced(const autofill::PasswordForm& r) { return r.date_synced; } static bool blocked_by_user(const autofill::PasswordForm& r) { return r.blocked_by_user; } static autofill::PasswordForm::Type type(const autofill::PasswordForm& r) { return r.type; } static int32_t times_used(const autofill::PasswordForm& r) { return r.times_used; } static const autofill::FormData& form_data(const autofill::PasswordForm& r) { return r.form_data; } static autofill::PasswordForm::GenerationUploadStatus generation_upload_status(const autofill::PasswordForm& r) { return r.generation_upload_status; } static const base::string16& display_name(const autofill::PasswordForm& r) { return r.display_name; } static const GURL& icon_url(const autofill::PasswordForm& r) { return r.icon_url; } static const url::Origin& federation_origin(const autofill::PasswordForm& r) { return r.federation_origin; } static bool skip_zero_click(const autofill::PasswordForm& r) { return r.skip_zero_click; } static bool was_parsed_using_autofill_predictions( const autofill::PasswordForm& r) { return r.was_parsed_using_autofill_predictions; } static bool is_public_suffix_match(const autofill::PasswordForm& r) { return r.is_public_suffix_match; } static bool is_affiliation_based_match(const autofill::PasswordForm& r) { return r.is_affiliation_based_match; } static autofill::mojom::SubmissionIndicatorEvent submission_event( const autofill::PasswordForm& r) { return r.submission_event; } static bool only_for_fallback(const autofill::PasswordForm& r) { return r.only_for_fallback; } static bool Read(autofill::mojom::PasswordFormDataView data, autofill::PasswordForm* out); }; template <> struct StructTraits<autofill::mojom::ValueElementPairDataView, autofill::ValueElementPair> { static base::string16 value(const autofill::ValueElementPair& r) { return r.first; } static base::string16 field_name(const autofill::ValueElementPair& r) { return r.second; } static bool Read(autofill::mojom::ValueElementPairDataView data, autofill::ValueElementPair* out); }; template <> struct StructTraits<autofill::mojom::ParsingResultDataView, autofill::ParsingResult> { static autofill::FieldRendererId username_renderer_id( const autofill::ParsingResult& r) { return r.username_renderer_id; } static autofill::FieldRendererId password_renderer_id( const autofill::ParsingResult& r) { return r.password_renderer_id; } static autofill::FieldRendererId new_password_renderer_id( const autofill::ParsingResult& r) { return r.new_password_renderer_id; } static autofill::FieldRendererId confirm_password_renderer_id( const autofill::ParsingResult& r) { return r.confirm_password_renderer_id; } static bool Read(autofill::mojom::ParsingResultDataView data, autofill::ParsingResult* out); }; } // namespace mojo #endif // COMPONENTS_AUTOFILL_CORE_COMMON_MOJOM_AUTOFILL_TYPES_MOJOM_TRAITS_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
7a9d74cd4b8e4e856d4f46d4e465e3b3cbdcbcbb
2c4f360dc9bbfd5892e29341245e3374125d6b60
/include/public/ScenarioUtils.h
09dcb9f1d0b646d6ba0767454ac94df8502cbf79
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
mitre/FMACM
d5549ed4b0e26e72d8186afc77a57e4f3833d864
a9fb00aef7561d2cb35af1163b44dda55a48c85f
refs/heads/master
2023-09-03T01:13:05.401619
2023-08-16T20:48:59
2023-08-16T20:48:59
35,225,860
11
4
Apache-2.0
2018-06-27T18:07:04
2015-05-07T14:49:02
C++
UTF-8
C++
false
false
3,016
h
// **************************************************************************** // NOTICE // // This work was produced for the U.S. Government under Contract 693KA8-22-C-00001 // and is subject to Federal Aviation Administration Acquisition Management System // Clause 3.5-13, Rights In Data-General, Alt. III and Alt. IV (Oct. 1996). // // The contents of this document reflect the views of the author and The MITRE // Corporation and do not necessarily reflect the views of the Federal Aviation // Administration (FAA) or the Department of Transportation (DOT). Neither the FAA // nor the DOT makes any warranty or guarantee, expressed or implied, concerning // the content or accuracy of these views. // // For further information, please contact The MITRE Corporation, Contracts Management // Office, 7515 Colshire Drive, McLean, VA 22102-7539, (703) 983-6000. // // 2023 The MITRE Corporation. All Rights Reserved. // **************************************************************************** #pragma once #include <string> #include <map> #include "public/RandomGenerator.h" namespace aaesim::open_source { class ScenarioUtils { public: ~ScenarioUtils() = default; static RandomGenerator RANDOM_NUMBER_GENERATOR; static const int AIRCRAFT_ID_NOT_IN_MAP; static void ClearAircraftIdMap() { m_aircraft_string_int_map.clear(); } static std::string GetAircraftIdForUniqueId(const int unique_id) { for (const auto &element : m_aircraft_string_int_map) { if (element.second == unique_id) return element.first; } return ""; } static int GetUniqueIdForAircraftId(const std::string aircraft_id) { bool is_in_map = m_aircraft_string_int_map.find(aircraft_id) != m_aircraft_string_int_map.end(); if (is_in_map) { return m_aircraft_string_int_map[aircraft_id]; } return AIRCRAFT_ID_NOT_IN_MAP; } static int GenerateNewUniqueIdForAircraftId(const std::string aircraft_id) { int old_id = GetUniqueIdForAircraftId(aircraft_id); if (old_id == AIRCRAFT_ID_NOT_IN_MAP) { int new_id = m_aircraft_string_int_map.size(); m_aircraft_string_int_map[aircraft_id] = new_id; return new_id; } else { return old_id; } } static std::string ResolveScenarioRootName(const std::string &full_scenario_filename) { std::string local_scenario_name{full_scenario_filename}; // remove the leading directory structure if present (search for last instance of "/" or "\\") auto index = local_scenario_name.find_last_of("/\\"); if (index != std::string::npos) { local_scenario_name = local_scenario_name.substr(index + 1); } index = local_scenario_name.find(".txt"); if (index != std::string::npos) { local_scenario_name.erase(index, 4); } return local_scenario_name; } private: static std::map<std::string, int> m_aircraft_string_int_map; ScenarioUtils() = default; }; } // namespace aaesim::open_source
[ "sbowman@mitre.org" ]
sbowman@mitre.org
af36e1c192fe5d8c890ad85b0c2cf61f3fdacbb9
ea7ea367180ebf57bee22fdeb3a597c2e4c5eb2d
/Mordhack/SDK/Mordhau_BP_MainMenu_classes.hpp
ff507fda7cc5d3a34a4948062da2db34b58c9215
[]
no_license
tho2shem/mordhau-basehack
5105c588544e33e8a7432ed6cb65d1fa41873f62
bc4fbd41417c8a05bfa1620c842b0e0255728237
refs/heads/master
2022-02-15T07:00:11.290882
2019-08-16T04:22:46
2019-08-16T04:22:46
202,657,567
0
0
null
null
null
null
UTF-8
C++
false
false
43,203
hpp
#pragma once // Mordhau (Dumped by Hinnie) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace SDK { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // WidgetBlueprintGeneratedClass BP_MainMenu.BP_MainMenu_C // 0x0230 (0x0438 - 0x0208) class UBP_MainMenu_C : public UUserWidget { public: struct FPointerToUberGraphFrame UberGraphFrame; // 0x0208(0x0008) (Transient, DuplicateTransient) class UWidgetAnimation* MainNavReveal; // 0x0210(0x0008) (BlueprintVisible, ExportObject, BlueprintReadOnly, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UBP_NavButton_C* ArmoryButton; // 0x0218(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UOverlay* ArmorySubNav; // 0x0220(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UBP_SubNavButton_C* AudioButton; // 0x0228(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UBP_AudioSettings_C* BP_AudioSettings; // 0x0230(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UBP_ControlsSettings_C* BP_ControlsSettings; // 0x0238(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UBP_Credits_C* BP_Credits; // 0x0240(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UBP_GameSettings_C* BP_GameSettings; // 0x0248(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UBP_HomeScreen_C* BP_HomeScreen; // 0x0250(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UBP_KeyBindingsSettings_C* BP_KeyBindingsSettings; // 0x0258(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UBP_LocalPlay_C* BP_LocalPlay; // 0x0260(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UBP_MatchmakingScreen_C* BP_MatchmakingScreen; // 0x0268(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UBP_MatchmakingSearchWidget_C* BP_MatchmakingSearchWidget; // 0x0270(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UBP_ProfileCustomization_C* BP_MordhauProfileCustomization; // 0x0278(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UBP_ServerBrowser_C* BP_MordhauServerBrowser; // 0x0280(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UBP_PlayerMenu_C* BP_PlayerMenu; // 0x0288(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UBP_PlayerStatsMenu_C* BP_PlayerStatsMenu; // 0x0290(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UBP_SocialMediaMenu_C* BP_SocialMediaMenu; // 0x0298(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UBP_TrainingMenu_C* BP_TrainingMenu; // 0x02A0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UBP_VideoSettings_C* BP_VideoSettings; // 0x02A8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UWidgetSwitcher* ContentSwitcher; // 0x02B0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UBP_SubNavButton_C* ControlsButton; // 0x02B8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UBP_SubNavButton_C* CreditsButton; // 0x02C0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UBP_SubNavButton_C* GameButton; // 0x02C8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UBP_NavButton_C* HomeButton; // 0x02D0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UOverlay* HomeSubNav; // 0x02D8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UBP_SubNavButton_C* HordeBRButton; // 0x02E0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UImage* Image_1; // 0x02E8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UImage* Image_2; // 0x02F0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UImage* Image_5; // 0x02F8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UBP_SubNavButton_C* KeyBindingsButton; // 0x0300(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UCircularThrobber* Loading; // 0x0308(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UBackgroundBlur* LoadingBlur; // 0x0310(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UBP_SubNavButton_C* LoadoutsButton; // 0x0318(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UBP_SubNavButton_C* LocalMatchButton; // 0x0320(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UOverlay* MainNav; // 0x0328(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UBP_SubNavButton_C* MatchmakingButton; // 0x0330(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UBP_NavButton_C* MiscButton; // 0x0338(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UOverlay* MiscSubNav; // 0x0340(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UBP_NavButton_C* PlayButton; // 0x0348(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UBP_NavButton_C* PlayerButton; // 0x0350(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UOverlay* PlayerMenuSubNav; // 0x0358(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UOverlay* PlaySubNav; // 0x0360(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UBP_SubNavButton_C* ProgressButton; // 0x0368(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UBP_SubNavButton_C* QuickJoinButton; // 0x0370(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UBP_NavButton_C* QuitButton; // 0x0378(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UOverlay* QuitSubNav; // 0x0380(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UBP_SubNavButton_C* ServerBrowserButton; // 0x0388(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UBP_NavButton_C* SettingsButton; // 0x0390(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UOverlay* SettingsSubNav; // 0x0398(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UBP_SubNavButton_C* SocialButton; // 0x03A0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UBP_SubNavButton_C* StatsButton; // 0x03A8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UWidgetSwitcher* SubNavSwitcher; // 0x03B0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UTextBlock* TextBlock_1; // 0x03B8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UBP_SubNavButton_C* TrainingButton; // 0x03C0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UBP_SubNavButton_C* VideoButton; // 0x03C8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) TArray<class UBP_NavButton_C*> NavButtons; // 0x03D0(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance) TArray<class UBP_SubNavButton_C*> SubNavButtons; // 0x03E0(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance) class UBP_ChoiceDialog_C* QuitGameDialog; // 0x03F0(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, InstancedReference, IsPlainOldData) class UBP_ChoiceDialog_C* AgreementDialog; // 0x03F8(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, InstancedReference, IsPlainOldData) class UBP_ChoiceDialog_C* QuitMatchDialog; // 0x0400(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, InstancedReference, IsPlainOldData) class UBP_InformationDialog_C* QuickJoinDialog; // 0x0408(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, InstancedReference, IsPlainOldData) struct FTimerHandle QuickJoinDelayTimer; // 0x0410(0x0008) (Edit, BlueprintVisible, DisableEditOnInstance) float QuickJoinDelay; // 0x0418(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) unsigned char UnknownData00[0x4]; // 0x041C(0x0004) MISSED OFFSET class UBP_MordhauGameInstance_C* GameInstance; // 0x0420(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) int MainNavIndex; // 0x0428(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) unsigned char UnknownData01[0x4]; // 0x042C(0x0004) MISSED OFFSET class UBP_NavButton_C* SelectedNavButton; // 0x0430(0x0008) (Edit, BlueprintVisible, ZeroConstructor, InstancedReference, IsPlainOldData) static UClass* StaticClass() { static auto ptr = UObject::FindClass("WidgetBlueprintGeneratedClass BP_MainMenu.BP_MainMenu_C"); return ptr; } void Request_Main_Navigation_Right(); void Request_Main_Navigation_Left(); struct FEventReply OnKeyDown(struct FGeometry* MyGeometry, struct FKeyEvent* InKeyEvent); ESlateVisibility Get_ArmorySubNav_Visibility_1(); void AskHUDToHideUs(); void HideQuickJoinDialog(); void ShowQuickJoinDialog(); void CreateQuickJoinDialog(); void HideQuitMatchDialog(); void ShowQuitMatchDialog(); void CreateQuitMatchDialog(); ESlateVisibility GetCloseButtonVisibility(); ESlateVisibility GetHomeButtonVisibility(); void QuitGame(); void HideQuitGameDialog(); void ShowQuitGameDialog(); void CreateQuitGameDialog(); struct FEventReply OnPreviewKeyDown(struct FGeometry* MyGeometry, struct FKeyEvent* InKeyEvent); void SetContentWidget(class UBP_MenuContentWidget_C* NewWidget); void UpdateNavAndSubNavButtons(); void CleanUpCustomization(); void Show(TEnumAsByte<E_ArmoryStates> Armory_State); void Hide(); void OnFailure_374B66EC4085986CEE5E52B4E6840193(TArray<struct FServerSearchResult> Results); void OnSuccess_374B66EC4085986CEE5E52B4E6840193(TArray<struct FServerSearchResult> Results); void OnFailure_B1DA11084BE01BCE48C8FBAB6D55A992(); void OnSuccess_B1DA11084BE01BCE48C8FBAB6D55A992(); void OnFailure_D1B5C5904AD6F30CA08466876916931A(); void OnSuccess_D1B5C5904AD6F30CA08466876916931A(); void OnFailure_03195FFE4CF4F9BC52C6D0A8D1D5E5E7(); void OnSuccess_03195FFE4CF4F9BC52C6D0A8D1D5E5E7(); void OnShow(TEnumAsByte<E_ArmoryStates> Armory_State); void Construct(); void BndEvt__SettingsButton_K2Node_ComponentBoundEvent_821_OnClick__DelegateSignature(); void BndEvt__ArmoryButton_K2Node_ComponentBoundEvent_833_OnClick__DelegateSignature(); void BndEvt__QuitButton_K2Node_ComponentBoundEvent_845_OnClick__DelegateSignature(); void BndEvt__GameButton_K2Node_ComponentBoundEvent_857_OnClick__DelegateSignature(); void BndEvt__ControlsButton_K2Node_ComponentBoundEvent_879_OnClick__DelegateSignature(); void BndEvt__PlayButton_K2Node_ComponentBoundEvent_17_OnClick__DelegateSignature(); void BndEvt__ServerBrowserButton_K2Node_ComponentBoundEvent_116_OnClick__DelegateSignature(); void BndEvt__VideoButton_K2Node_ComponentBoundEvent_74_OnClick__DelegateSignature(); void BndEvt__AudioButton_K2Node_ComponentBoundEvent_55_OnClick__DelegateSignature(); void BndEvt__HomeButton_K2Node_ComponentBoundEvent_425_OnClick__DelegateSignature(); void BndEvt__LocalGameButton_K2Node_ComponentBoundEvent_124_OnClick__DelegateSignature(); void BndEvt__QuickJoinButton_K2Node_ComponentBoundEvent_81_OnClick__DelegateSignature(); void QuickJoin(); void BndEvt__KeyBindingsButton_K2Node_ComponentBoundEvent_111_OnClick__DelegateSignature(); void QuitMatch(); void BndEvt__PlayerButton_K2Node_ComponentBoundEvent_0_OnClick__DelegateSignature(); void BndEvt__ProgressButton_K2Node_ComponentBoundEvent_1_OnClick__DelegateSignature(); void BndEvt__StatsButton_K2Node_ComponentBoundEvent_2_OnClick__DelegateSignature(); void BndEvt__CreditsButton_K2Node_ComponentBoundEvent_3_OnClick__DelegateSignature(); void BndEvt__MiscButton_K2Node_ComponentBoundEvent_4_OnClick__DelegateSignature(); void BndEvt__SocialButton_K2Node_ComponentBoundEvent_5_OnClick__DelegateSignature(); void BndEvt__MatchmakingButton_K2Node_ComponentBoundEvent_6_OnClick__DelegateSignature(); void BndEvt__LoadoutsButton_K2Node_ComponentBoundEvent_7_OnClick__DelegateSignature(); void BndEvt__HordeBRButton_K2Node_ComponentBoundEvent_8_OnClick__DelegateSignature(); void Tick(struct FGeometry* MyGeometry, float* InDeltaTime); void GoToMatchMaking(); void BndEvt__TrainingButton_K2Node_ComponentBoundEvent_9_OnClick__DelegateSignature(); void ExecuteUbergraph_BP_MainMenu(int EntryPoint); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "tho2shem@fastmail.com" ]
tho2shem@fastmail.com
c7416823a15bcf030a520afd55dd3982d3429dae
4032ea33407e3016afe562efaed77b2bdd011dfe
/main.cpp
ed6da5234b2ddec6c48624c71eb31e658f8b7af8
[ "Apache-2.0" ]
permissive
Ali-Kazzazi/qt-dark-theme
a3b5465da84bcf4d5df97dfba1a99e13d91ea6b7
b9cb0925ed970920965e4292ae178c1f8d9db479
refs/heads/master
2022-04-06T18:33:34.593496
2016-02-02T00:44:54
2016-02-02T00:44:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
584
cpp
#include "mainwindow.h" #include <QApplication> #include <QFile> #include <QDebug> int main(int argc, char *argv[]) { QApplication a(argc, argv); a.setStyle("plastique"); QFile styleSheet("dark-theme.qss"); if(!styleSheet.open(QIODevice::ReadOnly | QIODevice::Text)){ qDebug() << "Failed to read stylesheet file."; }else{ QTextStream in(&styleSheet); QString css; while(!in.atEnd()){ css.append(in.readLine()); } a.setStyleSheet(css); } MainWindow w; w.show(); return a.exec(); }
[ "vitor.shade@gmail.com" ]
vitor.shade@gmail.com
c7e5b3634289cb39a8163340daf9b32bd148f22d
f651a2be6a9a4fc77d05bdd85f4a59cf4d8502aa
/AutoSQL.cpp
c15748f66cdb38a4206e2a619814528627cbbd82
[]
no_license
hegangmas/MySourceLib
a94582c961af6d82185398bc41cbabbd81de99c6
bb4706cd411ab1861215ce91577e3ecec2273ad6
refs/heads/master
2020-12-25T03:00:34.088806
2012-10-17T06:36:56
2012-10-17T06:36:56
null
0
0
null
null
null
null
GB18030
C++
false
false
11,326
cpp
#include "StdAfx.h" #include "AutoSQL.h" #include "StringTool.h" AutoSQL::AutoSQL() { InitVar(); } AutoSQL::~AutoSQL() { } void AutoSQL::Trim(CString & sSrc) { sSrc.TrimLeft(); sSrc.TrimRight(); } bool AutoSQL::IsEqualNoCase(const CString & sSrc1,LPCSTR lpSrc2) { return sSrc1.CompareNoCase(lpSrc2)==0 ? true:false; } bool AutoSQL::IsKeyNoCase(const CString & sSrc1) { return (IsEqualNoCase(m_sTempWord,"from")|| IsEqualNoCase(m_sTempWord,"where")|| IsEqualNoCase(m_sTempWord,"group")|| IsEqualNoCase(m_sTempWord,"having")|| IsEqualNoCase(m_sTempWord,"order")); } bool AutoSQL::IsWhiteSpace(char cSrc) { if (cSrc>32) return false; if ((cSrc>=8)&&(cSrc<=13)) return true; if (cSrc==32) return true; /* 8 BackSpae */ /* 9 Tab */ /* 10 NewLine */ /* 11 Vertical Tab */ /* 12 Form Feed */ /* 13 Carriage Return */ /* 32 Space */ //Character is a WhiteSpace. return false; } void AutoSQL::Parse(const CString &sOriginSQL, int & nBegin, int & nEnd, LPCSTR lpSeparater, LPCSTR lpKeyWord, CStringArray &CArrReturn) { bool bIsNewWord=TRUE,bIsNewSentence=TRUE,bSetEndWord=false; m_sTempWord=GetOneWord(sOriginSQL,nBegin,nEnd); if (!IsEqualNoCase(m_sBeginWord,lpKeyWord)) { if (IsKeyNoCase(m_sTempWord)) { m_sBeginWord=m_sTempWord; KeyWordBackWard(sOriginSQL,nBegin); } return; } else { m_sTempWord=GetOneWord(sOriginSQL,nBegin,nEnd); if (IsEqualNoCase(lpKeyWord,"group")||IsEqualNoCase(lpKeyWord,"order")) { m_sTempWord=GetOneWord(sOriginSQL,nBegin,nEnd); } } while(m_sTempWord.GetLength()>0) { if (IsKeyNoCase(m_sTempWord)) { m_sBeginWord=m_sTempWord; //字符倒退一个 KeyWordBackWard(sOriginSQL,nBegin); break; } /* if (IsEqualNoCase(m_sTempWord,"by")) { m_sTempWord=GetOneWord(sOriginSQL,nBegin,nEnd); } */ if (bIsNewWord) { CArrReturn.Add(m_sTempWord); } else { CArrReturn[CArrReturn.GetSize()-1]+=" "+m_sTempWord; } bIsNewWord=false; if (lpSeparater==",") { if (nBegin<sOriginSQL.GetLength()&&sOriginSQL[nBegin]==',') { bIsNewWord=true; } m_sTempWord=GetOneWord(sOriginSQL,nBegin,nEnd); continue; } m_sTempWord=GetOneWord(sOriginSQL,nBegin,nEnd); if (IsEqualNoCase(lpSeparater,"and")&&IsEqualNoCase(m_sTempWord,"and")) { bIsNewWord=true; m_sTempWord=GetOneWord(sOriginSQL,nBegin,nEnd); } } } CString AutoSQL::GetOneWord(const CString &sOrigin,int & nBegin,int & nEnd) { CString sOneWord=""; if (nBegin>=sOrigin.GetLength()) { return sOneWord; } /* select a,b, 9 as c , d from e */ //先把空白字符和逗号跳过 这里主要是要定位到一个有效列的第一个字符 while((nBegin<sOrigin.GetLength())&&(IsWhiteSpace(sOrigin[nBegin])||sOrigin[nBegin]==',')) { nBegin++; } nEnd=nBegin; while(nEnd<sOrigin.GetLength()) { //有括号的是子语句 m_iBracketNum=0; if (sOrigin[nEnd]=='(') { m_iBracketNum++; while(m_iBracketNum>0) { nEnd++; if (sOrigin[nEnd]=='(') { m_iBracketNum++; } if (sOrigin[nEnd]==')') { m_iBracketNum--; } } //带括号的子句取完了 } //空白字符或者逗号,结束 if (IsWhiteSpace(sOrigin[nEnd])||sOrigin[nEnd]==',') { break; } nEnd++; } sOneWord=sOrigin.Mid(nBegin,nEnd-nBegin); /* select a,b, 9 as c , d from e */ //再次把空白字符过 这里主要是定位到逗号或者下一个字符,如果不是逗号,则下一个字符不是新列 nBegin=nEnd; while(nBegin<sOrigin.GetLength()&&IsWhiteSpace(sOrigin[nBegin])) { nBegin++; } return sOneWord; } void AutoSQL::KeyWordBackWard(const CString &sOrigin,int & nBegin) { //pos倒退到上一个字符 //GetOneWord 将begin 定位到逗号或者新字符的开始 //尾倒退 //倒推的时候nBegin<=0的情况是不应该存在的 ASSERT(nBegin>0); nBegin--; //定位到上一个字符的尾 while(nBegin>=0&&(IsWhiteSpace(sOrigin[nBegin])||sOrigin[nBegin]==',')) { nBegin--; } if (nBegin<=0) { return; } while(nBegin>=0&&isalpha(sOrigin[nBegin])) { nBegin--; } nBegin++; } void AutoSQL::ParseSelect(const CString &sOriginSQL,int & nBegin,int & nEnd,CStringArray &CArrReturn) { Parse(sOriginSQL,nBegin,nEnd,",","select",CArrReturn); } void AutoSQL::ParseFrom(const CString &sOriginSQL,int & nBegin,int & nEnd,CStringArray &CArrReturn) { Parse(sOriginSQL,nBegin,nEnd,",","from",CArrReturn); } void AutoSQL::ParseWhere(const CString &sOriginSQL,int & nBegin,int & nEnd,CStringArray &CArrReturn) { Parse(sOriginSQL,nBegin,nEnd,"and","where",CArrReturn); } void AutoSQL::ParseGroupBy(const CString &sOriginSQL,int & nBegin,int & nEnd,CStringArray &CArrReturn) { Parse(sOriginSQL,nBegin,nEnd,",","group",CArrReturn); } void AutoSQL::ParseHaving(const CString &sOriginSQL,int & nBegin,int & nEnd,CStringArray &CArrReturn) { Parse(sOriginSQL,nBegin,nEnd,"and","having",CArrReturn); } void AutoSQL::ParseOrderBy(const CString &sOriginSQL,int & nBegin,int & nEnd,CStringArray &CArrReturn) { Parse(sOriginSQL,nBegin,nEnd,",","order",CArrReturn); } void AutoSQL::InitVar() { m_sArrColumns.RemoveAll(); //列名的数组 m_sArrTables.RemoveAll(); //表名的数组 m_sArrWheres.RemoveAll(); //where后面的条件 m_sArrGroupBy.RemoveAll(); //group by 的内容 m_sArrHaving.RemoveAll(); //having 的内容 m_sArrOrderBy.RemoveAll(); //order by 的内容 m_CArrCondition.RemoveAll(); m_bAutoGroupBy=false; //加的列里面有sum()需要把列都group by m_sOriginSQL=""; //初始的SQL m_sTempWord=""; m_lSQLLength=0; //原始语句的长度 m_nTempWordBegin=0; //分解的一段的起点 m_nTempWordEnd=0; //分解的一段的终点 } int AutoSQL::SetOriginSQL(CString &sSQL) { //先去掉头尾的空格 Trim(sSQL); m_lSQLLength=sSQL.GetLength(); if (m_lSQLLength<=6) { //select 长度就已经是6了 return -1; } InitVar(); m_sOriginSQL=sSQL; //先分解原始的SQL ParseSQL(m_sOriginSQL); return 1; } void AutoSQL::ParseSQL(const CString & sSql) { //分解m_sOriginSQL; //先取select; m_sTempWord=sSql.Mid(0,6); if (!IsEqualNoCase(m_sTempWord,"select"))//不是select 开头的 { return; } /* 样板 select bh,sum(sno) from soeevent as b left join ccc on b.xx=ccc.x where pno>10 and bh>1 group by bh,xxx,xxx having sum(sno)>1 and bh>1000 order by bh,xxx,xxx */ //定位到0 m_nTempWordBegin=0; m_sBeginWord="select"; m_nTempWordEnd=m_nTempWordBegin; //开始分解select后面的列,分解到m_sArrColumns ParseSelect(sSql,m_nTempWordBegin,m_nTempWordEnd,m_sArrColumns); //开始分解from后面的表名 ParseFrom(sSql,m_nTempWordBegin,m_nTempWordEnd,m_sArrTables); //开始分解where ParseWhere(sSql,m_nTempWordBegin,m_nTempWordEnd,m_sArrWheres); //开始分解group by ParseGroupBy(sSql,m_nTempWordBegin,m_nTempWordEnd,m_sArrGroupBy); //开始分解 having ParseHaving(sSql,m_nTempWordBegin,m_nTempWordEnd,m_sArrHaving); //开始分解 order by ParseOrderBy(sSql,m_nTempWordBegin,m_nTempWordEnd,m_sArrOrderBy); } CString AutoSQL::GetDealedSQL() { //组合 CString sReturn=""; AddWords(sReturn,m_sArrColumns,"select",","); AddWords(sReturn,m_sArrTables,"from",","); AddWords(sReturn,m_sArrWheres,m_CArrCondition,"where","and"); AddWords(sReturn,m_sArrGroupBy,"group by",","); AddWords(sReturn,m_sArrHaving,"having","and"); AddWords(sReturn,m_sArrOrderBy,"order by",","); return sReturn; } int AutoSQL::AddWords(CString &Return, const CStringArray &CArrSrc, LPCSTR lpHead, LPCSTR lpSeparator) { int nPos,nSize; nSize=CArrSrc.GetSize(); if (nSize<=0) { return 0; } Return+=lpHead; Return+=" "+CArrSrc[0]; for (nPos=1;nPos<nSize;nPos++) { Return+=" "; Return+=lpSeparator; Return+=" "+CArrSrc[nPos]; } Return+=" "; return 1; } int AutoSQL::AddWords(CString &Return, const CStringArray &CArrSrc, const CArray<struct_Condition,struct_Condition &> &CArrAppend, LPCSTR lpHead, LPCSTR lpSeparator) { int nPos,nSize,nSizeAppend; bool bHaveDealFrist=false; nSize=CArrSrc.GetSize(); nSizeAppend=CArrAppend.GetSize(); if (nSize==0&&nSizeAppend==0) { return 0; } Return+=lpHead; Return+=" "; for (nPos=0;nPos<nSize;nPos++) { if (bHaveDealFrist) { Return+=lpSeparator; Return+=" "+CArrSrc[nPos]; Return+=" "; } else { Return+=CArrSrc[nPos]+" "; bHaveDealFrist=true; } } for (nPos=0;nPos<nSizeAppend&&CArrAppend[nPos].m_bCanUse;nPos++) { if (bHaveDealFrist) { Return+=lpSeparator; Return+=" ("+CArrAppend[nPos].m_sConditionSQL; Return+=") "; } else { Return+="("; Return+=CArrAppend[nPos].m_sConditionSQL+") "; bHaveDealFrist=true; } } return 1; } int AutoSQL::AddCondition(CString sConditionname,CString sConditionSQL) { if (sConditionname.GetLength()<=0||sConditionSQL.GetLength()<=0) { return 0; } sConditionname.MakeLower(); Trim(sConditionname); sConditionSQL.MakeLower(); Trim(sConditionSQL); m_CArrCondition.SetSize(m_CArrCondition.GetSize()+1); m_CArrCondition[m_CArrCondition.GetSize()-1].m_bCanUse=true; m_CArrCondition[m_CArrCondition.GetSize()-1].m_sConditionName=sConditionname; m_CArrCondition[m_CArrCondition.GetSize()-1].m_sConditionSQL=sConditionSQL; return 1; } int AutoSQL::AddCondition(string & sConditionname,string & sConditionSQL) { if (sConditionname.length()<=0||sConditionSQL.length()<=0) { return 0; } CStringTool::trim(sConditionname); CStringTool::MakeUpper(sConditionname); CStringTool::trim(sConditionSQL); CStringTool::MakeUpper(sConditionSQL); m_CArrCondition.SetSize(m_CArrCondition.GetSize()+1); m_CArrCondition[m_CArrCondition.GetSize()-1].m_bCanUse=true; m_CArrCondition[m_CArrCondition.GetSize()-1].m_sConditionName=sConditionname.c_str(); m_CArrCondition[m_CArrCondition.GetSize()-1].m_sConditionSQL=sConditionSQL.c_str(); return 1; } int AutoSQL::AddOrderBy(CString sOrderbySQL) { m_sArrOrderBy.Add(sOrderbySQL); return 1; } int AutoSQL::AddOrderBy(const string & sOrderbySQL) { m_sArrOrderBy.Add(sOrderbySQL.c_str()); return 1; } int AutoSQL::AddColumn(CString strColumn) { m_sArrColumns.Add(strColumn); return 1; } int AutoSQL::DelCondition(CString sConditionname) { if (sConditionname.GetLength()<=0) { return 0; } sConditionname.MakeLower(); Trim(sConditionname); int pos=0; for (pos=0;pos<m_CArrCondition.GetSize();pos++) { if (m_CArrCondition[pos].m_sConditionName==sConditionname) { m_CArrCondition.RemoveAt(pos); break; } } return 1; } int AutoSQL::RemoveCondition() { m_CArrCondition.RemoveAll(); return 1; }
[ "changjixiong@gmail.com" ]
changjixiong@gmail.com
0d7da076c7a7d63b59d742c9fb52a5ea7c1a3fcb
af211ceb6001c13571426445cedaaaa2258f2667
/example_2/RedisConfig.cpp
4198245f90b389d7d92fbbb15c85431f363d0921
[]
no_license
xuqnqn/redis-app
b6cc5103da105985b7054466b78f8708ef9c0059
75918cdaf1fdff366f72438eb8e7d4bf8ec1feb5
refs/heads/master
2020-07-22T19:22:16.459708
2019-09-09T12:29:45
2019-09-09T12:29:45
207,302,983
1
0
null
null
null
null
UTF-8
C++
false
false
529
cpp
/************************************************************************* > File Name: RedisConfig.cpp > Author: Xu Qingqing > Mail: xuqnqn@qq.com > Created Time: 2019年09月09日 星期一 19时29分26秒 ************************************************************************/ #include "RedisConfig.h" #include <sstream> RedisConfig::RedisConfig() { } std::string RedisConfig::getRedisIP() { return "127.0.0.1";//设置为本机ip } int RedisConfig::getRedisPort() { return 6379; }
[ "xuqnqn@qq.com" ]
xuqnqn@qq.com
1848020ba49e6d9c28388568d4a85e18dee76002
fa9cba14545c624dffa35dcae860010c46b722cc
/Behavior/CreturesExample/AfraidCreatures.cpp
9311bb881f36283c43a79402c46e341a868cb9c2
[]
no_license
Vinnichenko-Ivan/LifeSimulator
601c817bb50d3da4eb71e7054b160aa245914d2c
457353140d6aa75df84eb042df271f5cd4a02f97
refs/heads/master
2022-12-29T20:11:55.777168
2020-10-15T04:08:06
2020-10-15T04:08:06
284,656,373
1
0
null
2020-09-03T07:32:55
2020-08-03T09:20:47
C++
UTF-8
C++
false
false
30
cpp
#include "AfraidCreatures.h"
[ "fox4080@gmail.com" ]
fox4080@gmail.com
5d7be4d3f80bb05da49e5b7879b7ec78c985faaa
feddb42d6659f59edce34b7e7dc6d160bfff3eae
/src/CAENVMEenvironment/CAENVMEenvironment.cpp
11b5dfa0e3cca7c3d151cc737db6f8bcf07c0408
[]
no_license
cmsromadaq/MPPC-Setup
1b2ae5f3c145d3267f12ceb4fa6283e3d2e1f199
c8b96376de34669e3818bc9ae69440b0e5664816
refs/heads/master
2021-01-17T09:05:25.000281
2016-04-07T14:11:37
2016-04-07T14:11:37
16,640,626
0
0
null
null
null
null
UTF-8
C++
false
false
9,572
cpp
// QDCDataAqcisitionv1.0 // // Developer: Pedro F. Toledo // <pedrotoledocorrea@gmail.com> // // CAENVMEenvironment.cpp // // Description: This file contains the class methodes required for the QDCDataAcqui // sition program, been designed for the version 1.0 // // Libraries----------------------------------------------------------------------- //nclude <stdio.h> //nclude <stdarg.h> //#include <stdint.h> //#include "CAENVMElib.h" //#include <stdlib.h> //#include <string.h> #include "CAENVMEenvironment.h" //Custom Environment #include <fstream> #include <iostream> unsigned int QDCConnection::num = 0; int32_t QDCConnection::BHandle = 0; QDCConnection::QDCConnection(int QDCAddressToConnect){ int Data,result; this->debug = false; if(this->num == 0){ this->BHandle = 0; short Device = atoi("USB"); result = CAENVME_Init(cvV1718, 0, Device, &BHandle); if(result != cvSuccess ){ std::cerr << "\e[0;31mERROR:\e[0m "; switch(result){ case -1: std::cerr << "VME bus error during the cycle"; break; case -2: std::cerr << "Communication error"; break; case -3: std::cerr << "Unspecified error"; break; case -4: std::cerr << "Invalid parameter"; break; case -5: std::cerr << "Timeout error"; break; } std::cerr << ", opening the USB Link to V1718 device" << std::endl; //if(CAENVME_Init(cvV1718, 0, Device, &BHandle) != cvSuccess ){ //std::cout << "initializing device in: 0x" << std::hex << QDCAddressToConnect << std::dec << " with error " << result << std::endl; exit(1); } if(this->Debug()) std::cout << "Connection with CAEN-V1718 Established through USB" << std::endl; } this->QDCAddress = QDCAddressToConnect; if(QDCAddress%0x10000 != 0){ std::cerr << "\e[0;31mERROR:\e[0m Invalid QDC address" << std::endl; exit(7); }else{ if(CAENVME_ReadCycle(QDCConnection::BHandle, this->QDCAddress + 0x1000, &Data, cvA24_U_DATA, cvD16) != cvSuccess){ std::cerr << "\e[0;31mERROR:\e[0m opening the QDC link on address " << std::hex << this->QDCAddress << std::dec << std::endl; exit(7) ; } } if(this->Debug()){ std::cout << "QDC Connected at VME Address " << std::hex << this->QDCAddress; std::cout << ": Firmware v" << std::dec << ((Data&0xF000)>>12)*10+((Data&0xF00)>>8); std::cout << "." << ((Data&0xF0)>>4); std::cout << (Data&0xF) << std::endl; //printf("QDC Connected at VME Address %08X: Firmware v%d.%d%d\n",this->QDCAddress,((Data&0xF000)>>12)*10+((Data&0xF00)>>8),(Data&0xF0)>>4,Data&0xF) ; } this->num++; } QDCConnection::~QDCConnection(){ this->num--; if(this->num==0) CAENVME_End(this->BHandle); } void QDCConnection::QDCWrite(int Address, int Value){ if( Address%2 == 0 and Address >= 0x1002 and Address <= 0x10BF and Address != 0x100E and Address != 0x1022 and Address != 0x1024 and Address != 0x1026 and Address != 0x1070 and Address != 0x1072 and !(Address < 0x1000 and Address > 0x07FC)){ if(CAENVME_WriteCycle(this->BHandle, this->QDCAddress + Address, &Value, cvA24_U_DATA, cvD16)!=cvSuccess){ std::cerr << "\e[0;31mERROR:\e[0m writing QDC at address 0x" << std::hex << QDCAddress << std::dec << std::endl; exit(2); } }else{ std::cerr << "\e[0;31mERROR:\e[0m Invalid Writing QDC Address" << std::endl; exit(2) ; } } void QDCConnection::QDCRead(int Address, int *Value){ unsigned int Data = 0 ; if( Address%2 == 0 and Address >= 0 and Address <= 0x10BF and Address != 0x1016 and Address != 0x1028 and Address != 0x102A and Address != 0x1034 and Address != 0x1036 and Address != 0x1038 and Address != 0x103A and Address != 0x103E and Address != 0x1040 and Address != 0x1064 and Address != 0x1068 and !(Address < 0x1000 and Address > 0x07FC)){ if(Address <= 0x07FC){ if(CAENVME_ReadCycle(this->BHandle, this->QDCAddress + Address, &Data, cvA24_U_DATA, cvD32) != cvSuccess){ std::cerr << "\e[0;31mERROR:\e[0m reading QDC at address 0x" << std::hex << QDCAddress << std::dec << std::endl; exit(3); } }else{ if(CAENVME_ReadCycle(this->BHandle, this->QDCAddress + Address, &Data, cvA24_U_DATA, cvD16) != cvSuccess){ std::cerr << "\e[0;31mERROR:\e[0m reading QDC at address 0x" << std::hex << this->QDCAddress << std::endl; exit(3); } } *Value = Data; }else{ std::cerr << "\e[0;31mERROR:\e[0m Invalid Reading QDC Address" << std::endl; exit(3) ; } } int QDCConnection::QDCReadBLT(int Size, int *Data){ int Total; unsigned char *Datai; if(Size <= 4096 and Size > 0){ Datai = (unsigned char*)malloc(Size*sizeof(unsigned char)*4) ; CAENVME_BLTReadCycle(this->BHandle, this->QDCAddress, Datai, 4*4096, cvA24_U_DATA, cvD32, &Total) ; for(int i=0;i<Size;i++){ if(i<Total/4){ Data[i] =(Datai[i*4+3]<<24)+(Datai[i*4+2]<<16)+(Datai[i*4+1]<<8)+Datai[i*4+0] ; }else{ Data[i] = -1; } } return Total/4; }else{ std::cerr << "\e[0;31mERROR:\e[0m Invalid BLT Reading Length" << std::endl; exit(4) ; } return 0; } void QDCConnection::EnableChannel(int i){ this->QDCWrite(0x1080+i*2,1); } void QDCConnection::DisableChannel(int i){ this->QDCWrite(0x1080+i*2,0x1F0); } int QDCConnection::ReadThresholdValue(int i){ int Value; this->QDCRead(0x1080+i*2,&Value); return Value; } void QDCConnection::Reset(){ this->QDCWrite(0x1016,1); } /* This method change how the Event Counter count. There are two modes setted by mode. The modes are: Mode A (ALL TRG = 1): it counts all events (default); Mode B (ALL TRG = 0): it counts only the accepted events In the mode B, the Event Counter count only if VETO, FCLR and BUSY are not active*/ int QDCConnection::GetBitSet2Register(){ int Value; this->QDCRead(0x1032, &Value); return Value; } void QDCConnection::SetEventCounterMode(int mode){ if(mode!=1 && mode!=0){ std::cerr << "\e[0;31mERROR:\e[0m QDCConnection::SetEventCounterMode: writing in the port." << std::endl; exit(1); } int mask; int Value = this->GetBitSet2Register(); std::cout << "Data: 0x" << std::hex << Value << std::endl; mask = (~(1<<14)) & 0x7FFF; std::cout << "Mask: 0x" << std::hex << mask << std::endl; Value &= mask; Value |= (mode << 14); std::cout << "Value: 0x" << std::hex << Value << std::endl; this->QDCWrite(0x1032,Value); /*std::cout << "Value of Bit Set 2 Register is: 0x" << std::hex << Value << std::endl; return Value;*/ } bool QDCConnection::Debug(){ return this->debug; } void QDCConnection::Debug(bool debug){ this->debug = debug; } int QDCConnection::IpedRegister(){ int Value; this->QDCRead(0x1060, &Value); return Value; } void QDCConnection::SetIpedRegister(int Value){ this->QDCWrite(0x1060,Value); } int QDCConnection::StepThreshold(){ int Value; this->QDCRead(0x1032, &Value); return Value&0x100; } // Methodes QDCTools--------------------------------------------------------------- /*void QDCDataInterpreter(int Size, int *Data, int *Valid, int Hits[][3]){ int InHeader=0; int i, j; int Channel; int GateCounter=-1; int dataKind; //Cleaning Memory for(i=0;i<Size;i++){ Hits[i][0] = -1; Hits[i][1] = -1; } //Completing Result Array i=0; j=0; while(i<Size){ //std::cout << "********* in i:" << i << std::endl; //Cheking for the information Header if(Data[i]==-1){ *Valid=j; return; } dataKind = Data[i]&0x07000000; if(InHeader==0 && dataKind == 0x02000000){ //std::cout << "Header detected in i:" << i << std::endl; //Header read and expected InHeader = 1; i++; GateCounter++; }else if(InHeader==0 && dataKind !=0x02000000){ i=4096; continue; }else if(InHeader==1 && dataKind == 0x02000000){ //Unexpected Header //fprintf(stderr,"\nERROR: Unexpected header %d %d\n",i,InHeader); i++; continue; //exit(6) ; }else if(InHeader==1 && dataKind == 0x04000000){ //Section End InHeader=0; i++; } //When Im inside a valid information section if(InHeader==1){ //std::cout << "Data detected in i:" << i << std::endl; if((Data[i]&0x07000000) != 0x0){ //Other than event detected //fprintf(stderr,"\nERROR: Other than event detected\n"); i++; continue; //exit(6) ; }else{ //Obtaining the channel Channel = (Data[i]&0x001f0000)>>16; //Checking for overflow or underthreshold condition if(Data[i]&0x3000){ //For invalid data i++; }else{ //without overflow or underthreshold Hits[j][0] = Channel; Hits[j][2] = GateCounter; Hits[j][1] = Data[i]&0xFFF; j++; i++; } } } } *Valid = j; }*/
[ "alam.toro@gmail.com" ]
alam.toro@gmail.com
0a7c20773205fc15b7eed5f37942cd0cd8d6fdc2
2c97d16208158f562b19cdbfd8d603ed0abf82f8
/FaceDetector.h
5bb1f9012ac0262e176aba0ad9b528b1d0dbd25b
[]
no_license
Lieto/jc_pilot
e32bc9eb7f85fad7c4c237ea33998ae0ad58e35b
2ca46210df695742f4797c9bc90e31ccd4745805
refs/heads/master
2020-04-17T12:58:17.254270
2016-08-25T15:35:20
2016-08-25T15:35:20
66,282,319
0
0
null
null
null
null
UTF-8
C++
false
false
664
h
// // Created by kuoppves on 21.8.2016. // #ifndef JC_PILOT_FACEDETECTOR_H #define JC_PILOT_FACEDETECTOR_H #include <crowdsight.h> #include "Parameters.h" #include "DetectedPerson.h" class FaceDetector { public: time_t frameTimestamp; CrowdSight *crowdSight; std::map<long, DetectedPerson> detectedPersonMap; bool isCloserTo(cv::Point origPoint, cv::Point comparePoint, cv::Point adPoint); FaceDetector(Parameters& parameters); FaceDetector(string datadir, string license, int dev); bool Process(cv::Mat frame, Parameters& paras, int frameNo, bool fileSource); void ShowSettings(); }; #endif //JC_PILOT_FACEDETECTOR_H
[ "vesa.kuoppala@affecto.com" ]
vesa.kuoppala@affecto.com
77120d5484a87285e35879ea0a6387e6284c76e3
7bc74c12d85d5298f437d043fdc48943ccfdeda7
/001_Project/101_baseline_MS2016/00_zchCode/Foundation/src/math/CRectangle.cpp
b567da5274cf086f4308cd0ac0649992378b0864
[]
no_license
BobDeng1974/cameraframework-github
364dd6e9c3d09a06384bb4772a24ed38b49cbc30
86efc7356d94f4957998e6e0ae718bd9ed4a4ba0
refs/heads/master
2020-08-29T16:14:02.898866
2017-12-15T14:55:25
2017-12-15T14:55:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,144
cpp
#include "CRectangle.h" CRectangle::CRectangle() : m_iX(0) , m_iY(0) , m_uiWidth(0) , m_uiHeight(0) { ; } CRectangle::CRectangle(const CRectangle &src) : m_iX(src.m_iX) , m_iY(src.m_iY) , m_uiWidth(src.m_uiWidth) , m_uiHeight(src.m_uiHeight) { ; } CRectangle::CRectangle(Int32 iX, Int32 iY, UInt32 uiWidth, UInt32 uiHeight) : m_iX(iX) , m_iY(iY) , m_uiWidth(uiWidth) , m_uiHeight(uiHeight) { ; } CRectangle::~CRectangle() { ; } void CRectangle::offset(Int32 iX, Int32 iY) { m_iX += iX; m_iY += iY; } BOOLEAN CRectangle::rectInRect(const CRectangle &rc) const { if (m_iX <= rc.m_iX && rc.m_iX + (Int32)rc.m_uiWidth <= m_iX + (Int32)m_uiWidth) { if (m_iY <= rc.m_iY && rc.m_iY + (Int32)rc.m_uiHeight <= m_iY + (Int32)m_uiHeight) { return TRUE; } } return FALSE; } CRectangle CRectangle::intersect(const CRectangle &rc) const { CRectangle rcTemp(0, 0, 0, 0); // check for total exclusion if ((getRight() >= rc.m_iX) && (m_iX <= rc.getRight()) && (getBottom() >= rc.m_iY) && (m_iY <= rc.getBottom())) { Int32 iTemp; // fill in rcTemp with the intersection rcTemp.m_iX = (m_iX > rc.m_iX) ? m_iX : rc.m_iX; iTemp = (getRight() < rc.getRight()) ? getRight() : rc.getRight(); rcTemp.m_uiWidth = iTemp - rcTemp.m_iX + 1; rcTemp.m_iY = (m_iY > rc.m_iY) ? m_iY : rc.m_iY; iTemp = (getBottom() < rc.getBottom()) ? getBottom() : rc.getBottom(); rcTemp.m_uiHeight = iTemp - rcTemp.m_iY + 1; } return rcTemp; } BOOLEAN CRectangle::isIntersect(const CRectangle &rc) const { Int32 iRight = getRight(); Int32 iBottom = getBottom(); Int32 iRCRight = rc.getRight(); Int32 iRCBottom = rc.getBottom(); if ( ( iRight < rc.m_iX) || ( iRCRight < m_iX ) || ( iBottom < rc.m_iY) || ( iRCBottom < m_iY ) ) { return FALSE; } return TRUE; } void CRectangle::clear() { m_iX = 0; m_iY = 0; m_uiWidth = 0; m_uiHeight = 0; } void CRectangle::add(const CRectangle &rc) { if( isEmpty() ) { m_iX = rc.m_iX; m_iY = rc.m_iY; m_uiWidth = rc.m_uiWidth; m_uiHeight = rc.m_uiHeight; } else { Int32 iRight = getRight(); Int32 iBottom = getBottom(); Int32 iRCRight = rc.getRight(); Int32 iRCBottom = rc.getBottom(); if( m_iX > rc.m_iX ) { m_iX = rc.m_iX; } if( m_iY > rc.m_iY ) { m_iY = rc.m_iY; } m_uiWidth = (iRight < iRCRight) ? (iRCRight - m_iX) : (iRight - m_iX); m_uiWidth += 1; m_uiHeight = (iBottom < iRCBottom) ? (iRCBottom - m_iY) : (iBottom - m_iY); m_uiHeight += 1; } } CRectangle& CRectangle::operator =(const CRectangle &src) { m_iX = src.m_iX; m_iY = src.m_iY; m_uiWidth = src.m_uiWidth; m_uiHeight = src.m_uiHeight; return *this; } BOOLEAN CRectangle::operator ==(const CRectangle &src) const { return m_iX == src.m_iX && m_iY == src.m_iY && m_uiWidth == src.m_uiWidth && m_uiHeight == src.m_uiHeight; } BOOLEAN CRectangle::operator !=(const CRectangle &src) const { return m_iX != src.m_iX || m_iY != src.m_iY || m_uiWidth != src.m_uiWidth || m_uiHeight != src.m_uiHeight; }
[ "guofeng.lu@harman.com" ]
guofeng.lu@harman.com
b49b7e580088e91171cfe8a422de323c96d1f9f1
c3045469a160c69776042fed2762cd7a5d3055c9
/include/INotifier.h
70f366a8ebb1045b1cb5be78917b1ca6678e9f7d
[]
no_license
Htallon/PureMVC
9b47ce187ba3391df3b69e6a1ce8ae460cc3deb2
444ad49fe8d51174b92bb697a37ac1b8baf10dd8
refs/heads/master
2020-12-25T08:50:25.963454
2013-12-12T04:46:09
2013-12-12T04:46:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
433
h
#ifndef _INOTIFIER #define _INOTIFIER #include "MvcType.h" namespace Mvc { namespace Interface { class INotifier { public: virtual ~INotifier() {} virtual void SendNotification(NOTIFICATION_NAME_TYPE notificationName) = 0; virtual void SendNotification(NOTIFICATION_NAME_TYPE notificationName, void* body) = 0; }; } } #endif
[ "irons.du@gmail.com" ]
irons.du@gmail.com
c128b4a195c3f45931ca1783bed0e9e99a50ed80
fe292ad50323a1081bc47a71edfdfcb7489b13c7
/Stacks/PoisnousPlants.cpp
d8843f10164fd0c07e1ed1675dd7db753b0ed5e7
[]
no_license
aasthanarang/HackerRank-ProblemSolving
95d737c7bcfdb23294814f7a0f6ef200ba283309
44514d05216c7bb79ad1253edcd8c9bbbcd4d668
refs/heads/master
2022-12-31T03:36:28.659385
2020-10-21T18:32:34
2020-10-21T18:32:34
304,643,901
0
0
null
null
null
null
UTF-8
C++
false
false
798
cpp
#include<bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector<int> v; for(int i=1; i<=n; i++){ int d; cin>>d; v.push_back(d); } stack<pair<int,int>> s; s.push({v[0],0}); int maxall=0; for(int i=1; i<n; i++){ if(v[i]>s.top().first){ s.push({v[i],1}); } else{ int maxday=0; while(!s.empty() && (s.top()).first>=v[i]){ int day= (s.top()).second; maxday= max(maxday,day); s.pop(); } if(!s.empty()){ s.push({v[i],maxday+1}); } else{ s.push({v[i],0}); } } maxall=max(maxall,(s.top()).second); } cout<<maxall; }
[ "aasthanarang23@gmail.com" ]
aasthanarang23@gmail.com
a11d79f8c4494f0d5ae9648d278bb3c5c8ac348c
268e0671d916f9ce41937c93152a93dba3f95c2d
/Project/ZSort/OpenglProject/OpenglOrpject/game/shader.cpp
cc90221bb5c455a6e8cdbd8391c242e9686f8dac
[]
no_license
HarukaGame/HarukaGit
f4df1a4b74d298dede80e52e67cf7d75b935b442
0afacbaa233c433316439204865f2db7deeb4653
refs/heads/master
2023-01-21T07:06:16.057907
2020-11-29T14:23:01
2020-11-29T14:23:01
266,292,930
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
5,528
cpp
#include "shader.h" #include "GL/glew.h" #include "debug_print.h" bool CShader::SetUpUniform(int _programID) { m_programID = _programID; glUseProgram(m_programID); //---------------------------------------------------------- //uniform設定 //---------------------------------------------------------- m_uniformList[SHADER_UNIFORM_COLOR] = -1; m_uniformList[SHADER_UNIFORM_COLOR] = glGetUniformLocation(m_programID, "color"); if (m_uniformList[SHADER_UNIFORM_COLOR] == -1) { PRINT("color uniformの取得に失敗しました"); } m_uniformList[SHADER_UNIFORM_LIGHT] = -1; m_uniformList[SHADER_UNIFORM_LIGHT] = glGetUniformLocation(m_programID, "light"); if (m_uniformList[SHADER_UNIFORM_LIGHT] == -1) { printf("light uniformの取得に失敗しました"); } m_uniformList[SHADER_UNIFORM_MVP] = -1; m_uniformList[SHADER_UNIFORM_MVP] = glGetUniformLocation(m_programID, "MVP"); if (m_uniformList[SHADER_UNIFORM_MVP] == -1) { printf("MVP uniformの取得に失敗しました"); } //---------------------------------------------------------- //attribute設定 //---------------------------------------------------------- m_attributeList[SHADER_ATTRIBUTE_POSITION] = glGetAttribLocation(m_programID, "position"); if (m_attributeList[SHADER_ATTRIBUTE_POSITION] == -1) { PRINT("position attributeの取得に失敗しました\n"); } m_attributeList[SHADER_ATTRIBUTE_NORMAL] = glGetAttribLocation(m_programID, "normals"); if (m_attributeList[SHADER_ATTRIBUTE_NORMAL] == -1) { PRINT("normal attributeの取得に失敗しました\n"); } return true; } bool CShader::SetUpUniform() { glUseProgram(m_programID); //---------------------------------------------------------- //uniform設定 //---------------------------------------------------------- m_uniformList[SHADER_UNIFORM_COLOR] = -1; m_uniformList[SHADER_UNIFORM_COLOR] = glGetUniformLocation(m_programID, "color"); if (m_uniformList[SHADER_UNIFORM_COLOR] == -1) { PRINT("color uniformの取得に失敗しました"); } m_uniformList[SHADER_UNIFORM_LIGHT] = -1; m_uniformList[SHADER_UNIFORM_LIGHT] = glGetUniformLocation(m_programID, "light"); if (m_uniformList[SHADER_UNIFORM_LIGHT] == -1) { printf("light uniformの取得に失敗しました"); } m_uniformList[SHADER_UNIFORM_MVP] = -1; m_uniformList[SHADER_UNIFORM_MVP] = glGetUniformLocation(m_programID, "MVP"); if (m_uniformList[SHADER_UNIFORM_MVP] == -1) { printf("MVP uniformの取得に失敗しました"); } //---------------------------------------------------------- //attribute設定 //---------------------------------------------------------- m_attributeList[SHADER_ATTRIBUTE_POSITION] = glGetAttribLocation(m_programID, "position"); if (m_attributeList[SHADER_ATTRIBUTE_POSITION] == -1) { PRINT("position attributeの取得に失敗しました\n"); } m_attributeList[SHADER_ATTRIBUTE_NORMAL] = glGetAttribLocation(m_programID, "normals"); if (m_attributeList[SHADER_ATTRIBUTE_NORMAL] == -1) { PRINT("normal attributeの取得に失敗しました\n"); } return true; } int CShader::GetProgramID()const { return m_programID; } int CShader::GetUniform(SHADER_UNIFORM _uniform) const { return m_uniformList[_uniform]; } int CShader::GetAttribute(SHADER_ATTRIBUTE _attribute) const { return m_attributeList[_attribute]; } void CShader::CreateShaderProgram(const char* _vertSource, int _vertLength, const char* _fragSource,int _fragLength) { //バーテックスシェーダーコンパイル GLuint vertShaderID = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertShaderID, 1, &_vertSource, &_vertLength); glCompileShader(vertShaderID); GLint success = 0; glGetShaderiv(vertShaderID, GL_COMPILE_STATUS, &success); if (success == GL_FALSE) { PRINT("バーテックスシェーダーのコンパイルに失敗しました"); } //フラグメントシェーダーのコンパイル GLuint fragShaderID = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragShaderID, 1, &_fragSource, &_fragLength); glCompileShader(fragShaderID); glGetShaderiv(fragShaderID, GL_COMPILE_STATUS, &_fragLength); if (success == GL_FALSE) { PRINT("フラグメントシェーダーのコンパイルに失敗しました"); } //プログラムオブジェクトの作成 m_programID = glCreateProgram(); if (m_programID == 0) { PRINT("プログラムオブジェクトの生成に失敗しました"); } glAttachShader(m_programID, vertShaderID); glAttachShader(m_programID, fragShaderID); GLint attached; glGetProgramiv(m_programID, GL_ATTACHED_SHADERS, &attached); if (attached == GL_FALSE) { PRINT("シェーダーのアタッチに失敗しました"); } //リンク GLint linked; glLinkProgram(m_programID); glGetProgramiv(m_programID, GL_LINK_STATUS, &linked); if (linked == GL_FALSE) { PRINT("シェーダーのリンクに失敗しました"); } if (SetUpUniform() == false) { PRINT("ユニフォームセットアップに失敗しました"); } } void CShader::SetTransparent(const bool _value) { m_transparent = _value; } bool CShader::GetTransparent() const { return m_transparent; }
[ "harukagamecreate@gmail.com" ]
harukagamecreate@gmail.com
f31207c4ec2631f7b26e57ebbc65368d44a3c3df
a68821f672dab6ee928960f9f522a090e254b4f7
/include/quadrule.hpp
697e5693fa0f485276145e3fcf4bd63487eccadf
[]
no_license
mdh266/PECS-1D
fa972c23156a02ee30bc9e28338b7b00a5a2c1f7
c41df003104ed733c8029a49fa6452d0524a90c6
refs/heads/master
2021-06-27T09:11:42.471458
2017-09-12T16:57:46
2017-09-12T16:57:46
71,588,950
6
1
null
null
null
null
UTF-8
C++
false
false
8,090
hpp
void bashforth_set ( int n, double x[], double weight[] ); void bdf_set ( int n, double alpha[], double *beta, double *gamma ); void bdfc_set ( int n, double x[], double w[] ); void bdfp_set ( int order, double xtab[], double weight[] ); double bdf_sum ( double func ( double x ), int order, double xtab[], double weight[] ); char ch_cap ( char ch ); void cheb_set ( int order, double xtab[], double weight[] ); void chebyshev1_compute ( int order, double xtab[], double weight[] ); double chebyshev1_integral ( int expon ); void chebyshev2_compute ( int order, double xtab[], double weight[] ); double chebyshev2_integral ( int expon ); void chebyshev3_compute ( int order, double xtab[], double weight[] ); void clenshaw_curtis_compute ( int n, double x[], double w[] ); void clenshaw_curtis_set ( int order, double xtab[], double weight[] ); void fejer1_compute ( int n, double x[], double w[] ); void fejer1_set ( int order, double xtab[], double weight[] ); void fejer2_compute ( int n, double x[], double w[] ); void fejer2_set ( int order, double xtab[], double weight[] ); void gegenbauer_compute ( int order, double alpha, double xtab[], double weight[] ); double gegenbauer_integral ( int expon, double alpha ); void gegenbauer_recur ( double *p2, double *dp2, double *p1, double x, int order, double alpha, double c[] ); void gegenbauer_root ( double *x, int order, double alpha, double *dp2, double *p1, double c[] ); void gen_hermite_dr_compute ( int order, double alpha, double x[], double w[] ); void gen_hermite_ek_compute ( int order, double alpha, double x[], double w[] ); double gen_hermite_integral ( int expon, double alpha ); void gen_laguerre_ek_compute ( int order, double alpha, double xtab[], double weight[] ); double gen_laguerre_integral ( int expon, double alpha ); void gen_laguerre_ss_compute ( int order, double alpha, double xtab[], double weight[] ); void gen_laguerre_ss_recur ( double *p2, double *dp2, double *p1, double x, int order, double alpha, double b[], double c[] ); void gen_laguerre_ss_root ( double *x, int order, double alpha, double *dp2, double *p1, double b[], double c[] ); void hermite_ek_compute ( int n, double x[], double w[] ); void hermite_gk16_set ( int n, double x[], double w[] ); void hermite_gk18_set ( int n, double x[], double w[] ); void hermite_gk22_set ( int n, double x[], double w[] ); void hermite_gk24_set ( int n, double x[], double w[] ); double hermite_integral ( int n ); double hermite_integral2 ( double a ); void hermite_set ( int order, double xtab[], double weight[] ); void hermite_ss_compute ( int order, double xtab[], double weight[] ); void hermite_ss_recur ( double *p2, double *dp2, double *p1, double x, int order ); void hermite_ss_root ( double *x, int order, double *dp2, double *p1 ); int i4_factorial2 ( int n ); int i4_min ( int i1, int i2 ); int i4_power ( int i, int j ); void imtqlx ( int n, double d[], double e[], double z[] ); void jacobi_ek_compute ( int order, double alpha, double beta, double xtab[], double weight[] ); double jacobi_integral ( int expon, double alpha, double beta ); void jacobi_ss_compute ( int order, double alpha, double beta, double xtab[], double weight[] ); void jacobi_ss_root ( double *x, int order, double alpha, double beta, double *dp2, double *p1, double b[], double c[] ); void jacobi_ss_recur ( double *p2, double *dp2, double *p1, double x, int order, double alpha, double beta, double b[], double c[] ); void kronrod_set ( int order, double xtab[], double weight[] ); void laguerre_ek_compute ( int order, double xtab[], double weight[] ); double laguerre_integral ( int expon ); void laguerre_set ( int order, double xtab[], double weight[] ); void laguerre_ss_compute ( int order, double xtab[], double weight[] ); void laguerre_ss_recur ( double *p2, double *dp2, double *p1, double x, int order, double b[], double c[] ); void laguerre_ss_root ( double *x, int order, double *dp2, double *p1, double b[], double c[] ); double laguerre_sum ( double func ( double x ), double a, int order, double xtab[], double weight[] ); void legendre_dr_compute ( int order, double xtab[], double weight[] ); void legendre_ek_compute ( int n, double x[], double w[] ); double legendre_integral ( int expon ); void legendre_recur ( double *p2, double *dp2, double *p1, double x, int order ); void legendre_set ( int order, double xtab[], double weight[] ); void legendre_set_cos ( int order, double xtab[], double weight[] ); void legendre_set_cos2 ( int order, double xtab[], double weight[] ); void legendre_set_log ( int order, double xtab[], double weight[] ); void legendre_set_sqrtx_01 ( int order, double xtab[], double weight[] ); void legendre_set_sqrtx2_01 ( int order, double xtab[], double weight[] ); void legendre_set_x0_01 ( int order, double xtab[], double weight[] ); void legendre_set_x1 ( int order, double xtab[], double weight[] ); void legendre_set_x1_01 ( int order, double xtab[], double weight[] ); void legendre_set_x2 ( int order, double xtab[], double weight[] ); void legendre_set_x2_01 ( int order, double xtab[], double weight[] ); void lobatto_compute ( int n, double x[], double w[] ); void lobatto_set ( int order, double xtab[], double weight[] ); void moulton_set ( int order, double xtab[], double weight[] ); void nc_compute ( int order, double a, double b, double xtab[], double weight[] ); void ncc_compute ( int order, double xtab[], double weight[] ); void ncc_compute_points ( int n, double x[] ); void ncc_compute_weights ( int n, double w[] ); void ncc_set ( int order, double xtab[], double weight[] ); void nco_compute ( int n, double x[], double w[] ); void nco_compute_points ( int n, double x[] ); void nco_compute_weights ( int n, double w[] ); void nco_set ( int order, double xtab[], double weight[] ); void ncoh_compute ( int n, double x[], double w[] ); void ncoh_compute_points ( int n, double x[] ); void ncoh_compute_weights ( int n, double w[] ); void ncoh_set ( int order, double xtab[], double weight[] ); void patterson_set ( int order, double xtab[], double weight[] ); double r8_abs ( double x ); double r8_epsilon ( ); double r8_factorial ( int n ); double r8_factorial2 ( int n ); double r8_gamma ( double x ); double r8_gamma_log ( double x ); double r8_huge ( ); double r8_hyper_2f1 ( double a, double b, double c, double x ); double r8_max ( double x, double y ); double r8_psi ( double xx ); double r8_sign ( double x ); void r8vec_copy ( int n, double a1[], double a2[] ); double r8vec_dot_product ( int n, double a1[], double a2[] ); void r8vec_reverse ( int n, double x[] ); void radau_compute ( int n, double x[], double w[] ); void radau_set ( int order, double xtab[], double weight[] ); void rule_adjust ( double a, double b, double c, double d, int order, double x[], double w[] ); //bool s_eqi ( string s1, string s2 ); double sum_sub ( double func ( double x ), double a, double b, int nsub, int order, double xlo, double xhi, double xtab[], double weight[] ); double summer ( double func ( double x ), int order, double xtab[], double weight[] ); void summer_gk ( double func ( double x ), int orderg, double weightg[], double *resultg, int orderk, double xtabk[], double weightk[], double *resultk ); void sum_sub_gk ( double func ( double x ), double a, double b, int nsub, int orderg, double weightg[], double *resultg, int orderk, double xtabk[], double weightk[], double *resultk, double *error ); void timestamp ( );
[ "mdh266@gmail.com" ]
mdh266@gmail.com
ad0c87c99eefae924165dbbfc1374a8a63893ad6
b67fa0df1fbb1fdbae55764ebead075ce1a6a12c
/C++/mang/chuyen chu hoa thanh thuwong va chu hoa chu cai dau.cpp
c3628b8fbddd169985da4a734845c1f0808e0c64
[]
no_license
dphuoc432000/DuyTan_1st
056e39f6b2013da4f1da38ca92fb5edb8ac66b89
7c50359b771724b6e31cd867fe00a66af63ba290
refs/heads/master
2023-05-30T04:25:18.161308
2021-06-24T03:37:14
2021-06-24T03:37:14
379,792,321
0
0
null
null
null
null
UTF-8
C++
false
false
819
cpp
#include <iostream> #include <cstring> using namespace std; char thuongThanhHoa(char c) { int x = (int) c; if(x >= 97 && x <= 122) {// Nghia la x nam trong trong a -> z x = x - 32; return (char) x; } return c; } int chuyenChuThanhSo(char c) { int x = (int) c; if(x >= 48 && x <= 57) { return x - 48; } return -1; } char hoaThanhThuong(char c) { int x = (int) c; if(x >= 65 && x <= 90) {// Nghia la x nam trong trong A -> Z x = x + 32; return (char) x; } return c; } void xuatChuoi(char A[]) { for(int i = 0; i < strlen(A); i++) { cout << A[i]; } cout << endl; } void run() { int tong = 0; char A[255]; cin.getline(A, 255); for(int i = 0; i < strlen(A); i++) { if(chuyenChuThanhSo(A[i]) >= 0) { tong = tong + chuyenChuThanhSo(A[i]); } } cout << tong; } main() { run(); }
[ "dphuoc432000@gmail.com" ]
dphuoc432000@gmail.com
d4753520ab341e7c83335c1e414b216dec31c964
c69d4e212ec23964703a9e3f679da6f8bcfd308d
/C++/fun.cpp
35ad9f74ce39df8f41bddf0fc77ce9aa77c8b2fa
[]
no_license
AtulCoder01/Programming-Notes
94740b32b19c257dca974fe8c377a4144774b461
66c30e765312a6c2216ad329fcf75f5d17a57848
refs/heads/master
2022-07-07T21:33:28.419544
2018-01-31T12:27:37
2018-01-31T12:27:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
136
cpp
#include<iostream> using namespace std; void disp(); int main() { disp(); return 0; } void disp() { cout<<"My Name is Atul Kumar\n"; }
[ "roboatul786@gmail.com" ]
roboatul786@gmail.com
e435554be3fe0b7e3c51b70956282d33d77f091f
2f8bb9591e123fab6c1512814bbe6b71d2fef321
/src/gallium/drivers/r600/sfn/sfn_emitaluinstruction.cpp
bb7e2908db2fa3451f5450ab483b25192a76a193
[]
no_license
zhuyonguniontech/mesa
3fdeced3dccb19024bfbe700347028557e833d69
e435f75dd6fc3caf00cfefe321c281cc9f7f0c4b
refs/heads/master
2022-12-18T17:48:38.074478
2020-09-23T02:37:01
2020-09-23T04:19:45
297,839,199
0
0
null
2020-09-23T03:17:17
2020-09-23T03:17:17
null
UTF-8
C++
false
false
48,031
cpp
/* -*- mesa-c++ -*- * * Copyright (c) 2018 Collabora LTD * * Author: Gert Wollny <gert.wollny@collabora.com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * on the rights to use, copy, modify, merge, publish, distribute, sub * license, 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 (including the next * paragraph) 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 NON-INFRINGEMENT. IN NO EVENT SHALL * THE AUTHOR(S) AND/OR THEIR SUPPLIERS 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 "sfn_emitaluinstruction.h" #include "sfn_debug.h" #include "gallium/drivers/r600/r600_shader.h" namespace r600 { using std::vector; EmitAluInstruction::EmitAluInstruction(ShaderFromNirProcessor& processor): EmitInstruction (processor) { } bool EmitAluInstruction::do_emit(nir_instr* ir) { const nir_alu_instr& instr = *nir_instr_as_alu(ir); r600::sfn_log << SfnLog::instr << "emit '" << *ir << " bitsize: " << static_cast<int>(instr.dest.dest.ssa.bit_size) << "' (" << __func__ << ")\n"; preload_src(instr); switch (instr.op) { case nir_op_b2f32: return emit_alu_b2f(instr); case nir_op_i2b1: return emit_alu_i2orf2_b1(instr, op2_setne_int); case nir_op_f2b1: return emit_alu_i2orf2_b1(instr, op2_setne_dx10); case nir_op_b2b1: case nir_op_mov:return emit_mov(instr); case nir_op_ftrunc: return emit_alu_op1(instr, op1_trunc); case nir_op_fabs: return emit_alu_op1(instr, op1_mov, {1 << alu_src0_abs}); case nir_op_fneg: return emit_alu_op1(instr, op1_mov, {1 << alu_src0_neg}); case nir_op_fsat: return emit_alu_op1(instr, op1_mov, {1 << alu_dst_clamp}); case nir_op_frcp: return emit_alu_trans_op1(instr, op1_recip_ieee); case nir_op_frsq: return emit_alu_trans_op1(instr, op1_recipsqrt_ieee1); case nir_op_fsin: return emit_alu_trig_op1(instr, op1_sin); case nir_op_fcos: return emit_alu_trig_op1(instr, op1_cos); case nir_op_fexp2: return emit_alu_trans_op1(instr, op1_exp_ieee); case nir_op_flog2: return emit_alu_trans_op1(instr, op1_log_clamped); case nir_op_fround_even: return emit_alu_op1(instr, op1_rndne); case nir_op_fsqrt: return emit_alu_trans_op1(instr, op1_sqrt_ieee); case nir_op_i2f32: return emit_alu_trans_op1(instr, op1_int_to_flt); case nir_op_u2f32: return emit_alu_trans_op1(instr, op1_uint_to_flt); case nir_op_f2i32: return emit_alu_f2i32_or_u32(instr, op1_flt_to_int); case nir_op_f2u32: return emit_alu_f2i32_or_u32(instr, op1_flt_to_uint); case nir_op_fceil: return emit_alu_op1(instr, op1_ceil); case nir_op_ffract: return emit_alu_op1(instr, op1_fract); case nir_op_ffloor: return emit_alu_op1(instr, op1_floor); case nir_op_fsign: return emit_fsign(instr); case nir_op_fdph: return emit_fdph(instr); case nir_op_ibitfield_extract: return emit_bitfield_extract(instr, op3_bfe_int); case nir_op_ubitfield_extract: return emit_bitfield_extract(instr, op3_bfe_uint); case nir_op_bitfield_insert: return emit_bitfield_insert(instr); case nir_op_bit_count: return emit_alu_op1(instr, op1_bcnt_int); case nir_op_bitfield_reverse: return emit_alu_op1(instr, op1_bfrev_int); case nir_op_ieq: return emit_alu_op2_int(instr, op2_sete_int); case nir_op_ine: return emit_alu_op2_int(instr, op2_setne_int); case nir_op_ige: return emit_alu_op2_int(instr, op2_setge_int); case nir_op_ishl: return emit_alu_op2_int(instr, op2_lshl_int); case nir_op_ishr: return emit_alu_op2_int(instr, op2_ashr_int); case nir_op_ilt: return emit_alu_op2_int(instr, op2_setgt_int, op2_opt_reverse); case nir_op_iand: return emit_alu_op2_int(instr, op2_and_int); case nir_op_ixor: return emit_alu_op2_int(instr, op2_xor_int); case nir_op_imin: return emit_alu_op2_int(instr, op2_min_int); case nir_op_imax: return emit_alu_op2_int(instr, op2_max_int); case nir_op_imul_high: return emit_alu_trans_op2(instr, op2_mulhi_int); case nir_op_umul_high: return emit_alu_trans_op2(instr, op2_mulhi_uint); case nir_op_umax: return emit_alu_op2_int(instr, op2_max_uint); case nir_op_umin: return emit_alu_op2_int(instr, op2_min_uint); case nir_op_ior: return emit_alu_op2_int(instr, op2_or_int); case nir_op_inot: return emit_alu_op1(instr, op1_not_int); case nir_op_iabs: return emit_alu_iabs(instr); case nir_op_ineg: return emit_alu_ineg(instr); case nir_op_idiv: return emit_alu_div_int(instr, true, false); case nir_op_udiv: return emit_alu_div_int(instr, false, false); case nir_op_umod: return emit_alu_div_int(instr, false, true); case nir_op_isign: return emit_alu_isign(instr); case nir_op_uge: return emit_alu_op2_int(instr, op2_setge_uint); case nir_op_ult: return emit_alu_op2_int(instr, op2_setgt_uint, op2_opt_reverse); case nir_op_ushr: return emit_alu_op2_int(instr, op2_lshr_int); case nir_op_flt: return emit_alu_op2(instr, op2_setgt_dx10, op2_opt_reverse); case nir_op_fge: return emit_alu_op2(instr, op2_setge_dx10); case nir_op_fneu: return emit_alu_op2(instr, op2_setne_dx10); case nir_op_feq: return emit_alu_op2(instr, op2_sete_dx10); case nir_op_fmin: return emit_alu_op2(instr, op2_min_dx10); case nir_op_fmax: return emit_alu_op2(instr, op2_max_dx10); case nir_op_fmul: return emit_alu_op2(instr, op2_mul_ieee); case nir_op_imul: return emit_alu_trans_op2(instr, op2_mullo_int); case nir_op_fadd: return emit_alu_op2(instr, op2_add); case nir_op_fsub: return emit_alu_op2(instr, op2_add, op2_opt_neg_src1); case nir_op_iadd: return emit_alu_op2_int(instr, op2_add_int); case nir_op_isub: return emit_alu_op2_int(instr, op2_sub_int); case nir_op_fdot2: return emit_dot(instr, 2); case nir_op_fdot3: return emit_dot(instr, 3); case nir_op_fdot4: return emit_dot(instr, 4); case nir_op_bany_inequal2: return emit_any_all_icomp(instr, op2_setne_int, 2, false); case nir_op_bany_inequal3: return emit_any_all_icomp(instr, op2_setne_int, 3, false); case nir_op_bany_inequal4: return emit_any_all_icomp(instr, op2_setne_int, 4, false); case nir_op_ball_iequal2: return emit_any_all_icomp(instr, op2_sete_int, 2, true); case nir_op_ball_iequal3: return emit_any_all_icomp(instr, op2_sete_int, 3, true); case nir_op_ball_iequal4: return emit_any_all_icomp(instr, op2_sete_int, 4, true); case nir_op_bany_fnequal2: return emit_any_all_fcomp2(instr, op2_setne_dx10, false); case nir_op_bany_fnequal3: return emit_any_all_fcomp(instr, op2_setne, 3, false); case nir_op_bany_fnequal4: return emit_any_all_fcomp(instr, op2_setne, 4, false); case nir_op_ball_fequal2: return emit_any_all_fcomp2(instr, op2_sete_dx10, true); case nir_op_ball_fequal3: return emit_any_all_fcomp(instr, op2_sete, 3, true); case nir_op_ball_fequal4: return emit_any_all_fcomp(instr, op2_sete, 4, true); case nir_op_ffma: return emit_alu_op3(instr, op3_muladd_ieee); case nir_op_bcsel: return emit_alu_op3(instr, op3_cnde, {0, 2, 1}); case nir_op_vec2: return emit_create_vec(instr, 2); case nir_op_vec3: return emit_create_vec(instr, 3); case nir_op_vec4: return emit_create_vec(instr, 4); case nir_op_find_lsb: return emit_alu_op1(instr, op1_ffbl_int); case nir_op_ufind_msb: return emit_find_msb(instr, false); case nir_op_ifind_msb: return emit_find_msb(instr, true); case nir_op_b2i32: return emit_b2i32(instr); case nir_op_pack_64_2x32_split: return emit_pack_64_2x32_split(instr); case nir_op_unpack_64_2x32_split_x: return emit_unpack_64_2x32_split(instr, 0); case nir_op_unpack_64_2x32_split_y: return emit_unpack_64_2x32_split(instr, 1); case nir_op_unpack_half_2x16_split_x: return emit_unpack_32_2x16_split_x(instr); case nir_op_unpack_half_2x16_split_y: return emit_unpack_32_2x16_split_y(instr); case nir_op_pack_half_2x16_split: return emit_pack_32_2x16_split(instr); /* These are in the ALU instruction list, but they should be texture instructions */ case nir_op_fddx_fine: return emit_tex_fdd(instr, TexInstruction::get_gradient_h, true); case nir_op_fddx_coarse: case nir_op_fddx: return emit_tex_fdd(instr, TexInstruction::get_gradient_h, false); case nir_op_fddy_fine: return emit_tex_fdd(instr, TexInstruction::get_gradient_v, true); case nir_op_fddy_coarse: case nir_op_fddy: return emit_tex_fdd(instr,TexInstruction::get_gradient_v, false); case nir_op_umad24: return emit_alu_op3(instr, op3_muladd_uint24, {0, 1, 2}); case nir_op_umul24: return emit_alu_op2(instr, op2_mul_uint24); default: return false; } } void EmitAluInstruction::preload_src(const nir_alu_instr& instr) { const nir_op_info *op_info = &nir_op_infos[instr.op]; assert(op_info->num_inputs <= 4); unsigned nsrc_comp = num_src_comp(instr); sfn_log << SfnLog::reg << "Preload:\n"; for (unsigned i = 0; i < op_info->num_inputs; ++i) { for (unsigned c = 0; c < nsrc_comp; ++c) { m_src[i][c] = from_nir(instr.src[i], c); sfn_log << SfnLog::reg << " " << *m_src[i][c]; } sfn_log << SfnLog::reg << "\n"; } if (instr.op == nir_op_fdph) { m_src[1][3] = from_nir(instr.src[1], 3); sfn_log << SfnLog::reg << " extra:" << *m_src[1][3] << "\n"; } split_constants(instr, nsrc_comp); } unsigned EmitAluInstruction::num_src_comp(const nir_alu_instr& instr) { switch (instr.op) { case nir_op_fdot2: case nir_op_bany_inequal2: case nir_op_ball_iequal2: case nir_op_bany_fnequal2: case nir_op_ball_fequal2: return 2; case nir_op_fdot3: case nir_op_bany_inequal3: case nir_op_ball_iequal3: case nir_op_bany_fnequal3: case nir_op_ball_fequal3: return 3; case nir_op_fdot4: case nir_op_fdph: case nir_op_bany_inequal4: case nir_op_ball_iequal4: case nir_op_bany_fnequal4: case nir_op_ball_fequal4: return 4; case nir_op_vec2: case nir_op_vec3: case nir_op_vec4: return 1; default: return nir_dest_num_components(instr.dest.dest); } } void EmitAluInstruction::split_constants(const nir_alu_instr& instr, unsigned nsrc_comp) { const nir_op_info *op_info = &nir_op_infos[instr.op]; if (op_info->num_inputs < 2) return; int nconst = 0; std::array<const UniformValue *,4> c; std::array<int,4> idx; for (unsigned i = 0; i < op_info->num_inputs; ++i) { PValue& src = m_src[i][0]; assert(src); sfn_log << SfnLog::reg << "Split test " << *src; if (src->type() == Value::kconst) { c[nconst] = static_cast<const UniformValue *>(src.get()); idx[nconst++] = i; sfn_log << SfnLog::reg << "is constant " << i; } sfn_log << SfnLog::reg << "\n"; } if (nconst < 2) return; unsigned sel = c[0]->sel(); unsigned kcache = c[0]->kcache_bank(); sfn_log << SfnLog::reg << "split " << nconst << " constants, sel[0] = " << sel; ; for (int i = 1; i < nconst; ++i) { sfn_log << "sel[" << i << "] = " << c[i]->sel() << "\n"; if (c[i]->sel() != sel || c[i]->kcache_bank() != kcache) { AluInstruction *ir = nullptr; auto v = get_temp_vec4(); for (unsigned k = 0; k < nsrc_comp; ++k) { ir = new AluInstruction(op1_mov, v[k], m_src[idx[i]][k], {write}); emit_instruction(ir); m_src[idx[i]][k] = v[k]; } make_last(ir); } } } bool EmitAluInstruction::emit_alu_inot(const nir_alu_instr& instr) { if (instr.src[0].negate || instr.src[0].abs) { std::cerr << "source modifiers not supported with int ops\n"; return false; } AluInstruction *ir = nullptr; for (int i = 0; i < 4 ; ++i) { if (instr.dest.write_mask & (1 << i)){ ir = new AluInstruction(op1_not_int, from_nir(instr.dest, i), m_src[0][i], write); emit_instruction(ir); } } make_last(ir); return true; } bool EmitAluInstruction::emit_alu_op1(const nir_alu_instr& instr, EAluOp opcode, const AluOpFlags& flags) { AluInstruction *ir = nullptr; for (int i = 0; i < 4 ; ++i) { if (instr.dest.write_mask & (1 << i)){ ir = new AluInstruction(opcode, from_nir(instr.dest, i), m_src[0][i], write); if (flags.test(alu_src0_abs) || instr.src[0].abs) ir->set_flag(alu_src0_abs); if (instr.src[0].negate ^ flags.test(alu_src0_neg)) ir->set_flag(alu_src0_neg); if (flags.test(alu_dst_clamp) || instr.dest.saturate) ir->set_flag(alu_dst_clamp); emit_instruction(ir); } } make_last(ir); return true; } bool EmitAluInstruction::emit_mov(const nir_alu_instr& instr) { /* If the op is a plain move beween SSA values we can just forward * the register reference to the original register */ if (instr.dest.dest.is_ssa && instr.src[0].src.is_ssa && !instr.src[0].abs && !instr.src[0].negate && !instr.dest.saturate) { bool result = true; for (int i = 0; i < 4 ; ++i) { if (instr.dest.write_mask & (1 << i)){ result &= inject_register(instr.dest.dest.ssa.index, i, m_src[0][i], true); } } return result; } else { return emit_alu_op1(instr, op1_mov); } } bool EmitAluInstruction::emit_alu_trig_op1(const nir_alu_instr& instr, EAluOp opcode) { // normalize by dividing by 2*PI, shift by 0.5, take fraction, and // then shift back const float inv_2_pi = 0.15915494f; PValue v[4]; // this might need some additional temp register creation for (unsigned i = 0; i < 4 ; ++i) v[i] = from_nir(instr.dest, i); PValue inv_pihalf = PValue(new LiteralValue(inv_2_pi, 0)); AluInstruction *ir = nullptr; for (unsigned i = 0; i < 4 ; ++i) { if (!(instr.dest.write_mask & (1 << i))) continue; ir = new AluInstruction(op3_muladd_ieee, v[i], {m_src[0][i], inv_pihalf, Value::zero_dot_5}, {alu_write}); if (instr.src[0].negate) ir->set_flag(alu_src0_neg); emit_instruction(ir); } make_last(ir); for (unsigned i = 0; i < 4 ; ++i) { if (!(instr.dest.write_mask & (1 << i))) continue; ir = new AluInstruction(op1_fract, v[i], v[i], {alu_write}); emit_instruction(ir); } make_last(ir); for (unsigned i = 0; i < 4 ; ++i) { if (!(instr.dest.write_mask & (1 << i))) continue; ir = new AluInstruction(op2_add, v[i], v[i], Value::zero_dot_5, write); ir->set_flag(alu_src1_neg); emit_instruction(ir); } make_last(ir); for (unsigned i = 0; i < 4 ; ++i) { if (!(instr.dest.write_mask & (1 << i))) continue; ir = new AluInstruction(opcode, v[i], v[i], last_write); emit_instruction(ir); } return true; } bool EmitAluInstruction::emit_alu_trans_op1(const nir_alu_instr& instr, EAluOp opcode, bool absolute) { AluInstruction *ir = nullptr; std::set<int> src_idx; if (get_chip_class() == CAYMAN) { int last_slot = (instr.dest.write_mask & 0x8) ? 4 : 3; for (int i = 0; i < last_slot; ++i) { ir = new AluInstruction(opcode, from_nir(instr.dest, i), m_src[0][0], instr.dest.write_mask & (1 << i) ? write : empty); if (absolute || instr.src[0].abs) ir->set_flag(alu_src0_abs); if (instr.src[0].negate) ir->set_flag(alu_src0_neg); if (instr.dest.saturate) ir->set_flag(alu_dst_clamp); if (i == (last_slot - 1)) ir->set_flag(alu_last_instr); emit_instruction(ir); } } else { for (int i = 0; i < 4 ; ++i) { if (instr.dest.write_mask & (1 << i)){ ir = new AluInstruction(opcode, from_nir(instr.dest, i), m_src[0][i], last_write); if (absolute || instr.src[0].abs) ir->set_flag(alu_src0_abs); if (instr.src[0].negate) ir->set_flag(alu_src0_neg); if (instr.dest.saturate) ir->set_flag(alu_dst_clamp); emit_instruction(ir); } } } return true; } bool EmitAluInstruction::emit_alu_f2i32_or_u32(const nir_alu_instr& instr, EAluOp op) { AluInstruction *ir = nullptr; std::array<PValue, 4> v; for (int i = 0; i < 4; ++i) { if (!(instr.dest.write_mask & (1 << i))) continue; v[i] = from_nir(instr.dest, i); ir = new AluInstruction(op1_trunc, v[i], m_src[0][i], {alu_write}); if (instr.src[0].abs) ir->set_flag(alu_src0_abs); if (instr.src[0].negate) ir->set_flag(alu_src0_neg); emit_instruction(ir); } make_last(ir); for (int i = 0; i < 4; ++i) { if (!(instr.dest.write_mask & (1 << i))) continue; ir = new AluInstruction(op, v[i], v[i], {alu_write}); emit_instruction(ir); if (op == op1_flt_to_uint) make_last(ir); } make_last(ir); return true; } bool EmitAluInstruction::emit_find_msb(const nir_alu_instr& instr, bool sgn) { int sel_tmp = allocate_temp_register(); int sel_tmp2 = allocate_temp_register(); GPRVector tmp(sel_tmp, {0,1,2,3}); GPRVector tmp2(sel_tmp2, {0,1,2,3}); AluInstruction *ir = nullptr; EAluOp opcode = sgn ? op1_ffbh_int : op1_ffbh_uint; for (int i = 0; i < 4; ++i) { if (!(instr.dest.write_mask & (1 << i))) continue; ir = new AluInstruction(opcode, tmp.reg_i(i), m_src[0][i], write); emit_instruction(ir); } make_last(ir); for (int i = 0; i < 4 ; ++i) { if (!(instr.dest.write_mask & (1 << i))) continue; ir = new AluInstruction(op2_sub_int, tmp2.reg_i(i), PValue(new LiteralValue(31u, 0)), tmp.reg_i(i), write); emit_instruction(ir); } make_last(ir); for (int i = 0; i < 4 ; ++i) { if (!(instr.dest.write_mask & (1 << i))) continue; ir = new AluInstruction(op3_cndge_int, from_nir(instr.dest, i), tmp.reg_i(i), tmp2.reg_i(i), tmp.reg_i(i), write); emit_instruction(ir); } make_last(ir); return true; } bool EmitAluInstruction::emit_b2i32(const nir_alu_instr& instr) { AluInstruction *ir = nullptr; for (int i = 0; i < 4 ; ++i) { if (!(instr.dest.write_mask & (1 << i))) continue; ir = new AluInstruction(op2_and_int, from_nir(instr.dest, i), m_src[0][i], Value::one_i, write); emit_instruction(ir); } make_last(ir); return true; } bool EmitAluInstruction::emit_pack_64_2x32_split(const nir_alu_instr& instr) { AluInstruction *ir = nullptr; for (unsigned i = 0; i < 2; ++i) { if (!(instr.dest.write_mask & (1 << i))) continue; ir = new AluInstruction(op1_mov, from_nir(instr.dest, i), m_src[0][i], write); emit_instruction(ir); } ir->set_flag(alu_last_instr); return true; } bool EmitAluInstruction::emit_unpack_64_2x32_split(const nir_alu_instr& instr, unsigned comp) { emit_instruction(new AluInstruction(op1_mov, from_nir(instr.dest, 0), m_src[0][comp], last_write)); return true; } bool EmitAluInstruction::emit_create_vec(const nir_alu_instr& instr, unsigned nc) { AluInstruction *ir = nullptr; std::set<int> src_slot; for(unsigned i = 0; i < nc; ++i) { if (instr.dest.write_mask & (1 << i)){ auto src = m_src[i][0]; ir = new AluInstruction(op1_mov, from_nir(instr.dest, i), src, write); if (instr.dest.saturate) ir->set_flag(alu_dst_clamp); // FIXME: This is a rather crude approach to fix the problem that // r600 can't read from four different slots of the same component // here we check only for the register index if (src->type() == Value::gpr) src_slot.insert(src->sel()); if (src_slot.size() >= 3) { src_slot.clear(); ir->set_flag(alu_last_instr); } emit_instruction(ir); } } if (ir) ir->set_flag(alu_last_instr); return true; } bool EmitAluInstruction::emit_dot(const nir_alu_instr& instr, int n) { const nir_alu_src& src0 = instr.src[0]; const nir_alu_src& src1 = instr.src[1]; AluInstruction *ir = nullptr; for (int i = 0; i < n ; ++i) { ir = new AluInstruction(op2_dot4_ieee, from_nir(instr.dest, i), m_src[0][i], m_src[1][i], instr.dest.write_mask & (1 << i) ? write : empty); if (src0.negate) ir->set_flag(alu_src0_neg); if (src0.abs) ir->set_flag(alu_src0_abs); if (src1.negate) ir->set_flag(alu_src1_neg); if (src1.abs) ir->set_flag(alu_src1_abs); if (instr.dest.saturate) ir->set_flag(alu_dst_clamp); emit_instruction(ir); } for (int i = n; i < 4 ; ++i) { ir = new AluInstruction(op2_dot4_ieee, from_nir(instr.dest, i), Value::zero, Value::zero, instr.dest.write_mask & (1 << i) ? write : empty); emit_instruction(ir); } if (ir) ir->set_flag(alu_last_instr); return true; } bool EmitAluInstruction::emit_fdph(const nir_alu_instr& instr) { const nir_alu_src& src0 = instr.src[0]; const nir_alu_src& src1 = instr.src[1]; AluInstruction *ir = nullptr; for (int i = 0; i < 3 ; ++i) { ir = new AluInstruction(op2_dot4_ieee, from_nir(instr.dest, i), m_src[0][i], m_src[1][i], instr.dest.write_mask & (1 << i) ? write : empty); if (src0.negate) ir->set_flag(alu_src0_neg); if (src0.abs) ir->set_flag(alu_src0_abs); if (src1.negate) ir->set_flag(alu_src1_neg); if (src1.abs) ir->set_flag(alu_src1_abs); if (instr.dest.saturate) ir->set_flag(alu_dst_clamp); emit_instruction(ir); } ir = new AluInstruction(op2_dot4_ieee, from_nir(instr.dest, 3), Value::one_f, m_src[1][3], (instr.dest.write_mask) & (1 << 3) ? write : empty); if (src1.negate) ir->set_flag(alu_src1_neg); if (src1.abs) ir->set_flag(alu_src1_abs); emit_instruction(ir); ir->set_flag(alu_last_instr); return true; } bool EmitAluInstruction::emit_alu_i2orf2_b1(const nir_alu_instr& instr, EAluOp op) { AluInstruction *ir = nullptr; for (int i = 0; i < 4 ; ++i) { if (instr.dest.write_mask & (1 << i)) { ir = new AluInstruction(op, from_nir(instr.dest, i), m_src[0][i], Value::zero, write); emit_instruction(ir); } } if (ir) ir->set_flag(alu_last_instr); return true; } bool EmitAluInstruction::emit_alu_b2f(const nir_alu_instr& instr) { AluInstruction *ir = nullptr; for (int i = 0; i < 4 ; ++i) { if (instr.dest.write_mask & (1 << i)){ ir = new AluInstruction(op2_and_int, from_nir(instr.dest, i), m_src[0][i], Value::one_f, write); if (instr.src[0].negate) ir->set_flag(alu_src0_neg); if (instr.src[0].abs) ir->set_flag(alu_src0_abs); if (instr.dest.saturate) ir->set_flag(alu_dst_clamp); emit_instruction(ir); } } if (ir) ir->set_flag(alu_last_instr); return true; } bool EmitAluInstruction::emit_any_all_icomp(const nir_alu_instr& instr, EAluOp op, unsigned nc, bool all) { AluInstruction *ir = nullptr; PValue v[4]; // this might need some additional temp register creation for (unsigned i = 0; i < 4 ; ++i) v[i] = from_nir(instr.dest, i); EAluOp combine = all ? op2_and_int : op2_or_int; /* For integers we can not use the modifiers, so this needs some emulation */ /* Should actually be lowered with NIR */ if (instr.src[0].negate == instr.src[1].negate && instr.src[0].abs == instr.src[1].abs) { for (unsigned i = 0; i < nc ; ++i) { ir = new AluInstruction(op, v[i], m_src[0][i], m_src[1][i], write); emit_instruction(ir); } if (ir) ir->set_flag(alu_last_instr); } else { std::cerr << "Negate in iequal/inequal not (yet) supported\n"; return false; } for (unsigned i = 0; i < nc/2 ; ++i) { ir = new AluInstruction(combine, v[2 * i], v[2 * i], v[2 * i + 1], write); emit_instruction(ir); } if (ir) ir->set_flag(alu_last_instr); if (nc > 2) { ir = new AluInstruction(combine, v[0], v[0], v[2], last_write); emit_instruction(ir); } return true; } bool EmitAluInstruction::emit_any_all_fcomp(const nir_alu_instr& instr, EAluOp op, unsigned nc, bool all) { AluInstruction *ir = nullptr; PValue v[4]; // this might need some additional temp register creation for (unsigned i = 0; i < 4 ; ++i) v[i] = from_nir(instr.dest, i); for (unsigned i = 0; i < nc ; ++i) { ir = new AluInstruction(op, v[i], m_src[0][i], m_src[1][i], write); if (instr.src[0].abs) ir->set_flag(alu_src0_abs); if (instr.src[0].negate) ir->set_flag(alu_src0_neg); if (instr.src[1].abs) ir->set_flag(alu_src1_abs); if (instr.src[1].negate) ir->set_flag(alu_src1_neg); emit_instruction(ir); } if (ir) ir->set_flag(alu_last_instr); for (unsigned i = 0; i < nc ; ++i) { ir = new AluInstruction(op1_max4, v[i], v[i], write); if (all) ir->set_flag(alu_src0_neg); emit_instruction(ir); } for (unsigned i = nc; i < 4 ; ++i) { ir = new AluInstruction(op1_max4, v[i], all ? Value::one_f : Value::zero, write); if (all) ir->set_flag(alu_src0_neg); emit_instruction(ir); } ir->set_flag(alu_last_instr); if (all) op = (op == op2_sete) ? op2_sete_dx10: op2_setne_dx10; else op = (op == op2_sete) ? op2_setne_dx10: op2_sete_dx10; ir = new AluInstruction(op, v[0], v[0], Value::one_f, last_write); if (all) ir->set_flag(alu_src1_neg); emit_instruction(ir); return true; } bool EmitAluInstruction::emit_any_all_fcomp2(const nir_alu_instr& instr, EAluOp op, bool all) { AluInstruction *ir = nullptr; PValue v[4]; // this might need some additional temp register creation for (unsigned i = 0; i < 4 ; ++i) v[i] = from_nir(instr.dest, i); for (unsigned i = 0; i < 2 ; ++i) { ir = new AluInstruction(op, v[i], m_src[0][i], m_src[1][i], write); if (instr.src[0].abs) ir->set_flag(alu_src0_abs); if (instr.src[0].negate) ir->set_flag(alu_src0_neg); if (instr.src[1].abs) ir->set_flag(alu_src1_abs); if (instr.src[1].negate) ir->set_flag(alu_src1_neg); emit_instruction(ir); } if (ir) ir->set_flag(alu_last_instr); op = (op == op2_setne_dx10) ? op2_or_int: op2_and_int; ir = new AluInstruction(op, v[0], v[0], v[1], last_write); emit_instruction(ir); return true; } bool EmitAluInstruction::emit_alu_trans_op2(const nir_alu_instr& instr, EAluOp opcode) { const nir_alu_src& src0 = instr.src[0]; const nir_alu_src& src1 = instr.src[1]; AluInstruction *ir = nullptr; if (get_chip_class() == CAYMAN) { int lasti = util_last_bit(instr.dest.write_mask); for (int k = 0; k < lasti ; ++k) { if (instr.dest.write_mask & (1 << k)) { for (int i = 0; i < 4; i++) { ir = new AluInstruction(opcode, from_nir(instr.dest, i), m_src[0][k], m_src[0][k], (i == k) ? write : empty); if (src0.negate) ir->set_flag(alu_src0_neg); if (src0.abs) ir->set_flag(alu_src0_abs); if (src1.negate) ir->set_flag(alu_src1_neg); if (src1.abs) ir->set_flag(alu_src1_abs); if (instr.dest.saturate) ir->set_flag(alu_dst_clamp); if (i == 3) ir->set_flag(alu_last_instr); emit_instruction(ir); } } } } else { for (int i = 0; i < 4 ; ++i) { if (instr.dest.write_mask & (1 << i)){ ir = new AluInstruction(opcode, from_nir(instr.dest, i), m_src[0][i], m_src[1][i], last_write); if (src0.negate) ir->set_flag(alu_src0_neg); if (src0.abs) ir->set_flag(alu_src0_abs); if (src1.negate) ir->set_flag(alu_src1_neg); if (src1.abs) ir->set_flag(alu_src1_abs); if (instr.dest.saturate) ir->set_flag(alu_dst_clamp); emit_instruction(ir); } } } return true; } bool EmitAluInstruction::emit_alu_op2_int(const nir_alu_instr& instr, EAluOp opcode, AluOp2Opts opts) { const nir_alu_src& src0 = instr.src[0]; const nir_alu_src& src1 = instr.src[1]; if (src0.negate || src1.negate || src0.abs || src1.abs) { std::cerr << "R600: don't support modifiers with integer operations"; return false; } return emit_alu_op2(instr, opcode, opts); } bool EmitAluInstruction::emit_alu_op2(const nir_alu_instr& instr, EAluOp opcode, AluOp2Opts ops) { const nir_alu_src *src0 = &instr.src[0]; const nir_alu_src *src1 = &instr.src[1]; int idx0 = 0; int idx1 = 1; if (ops & op2_opt_reverse) { std::swap(src0, src1); std::swap(idx0, idx1); } bool src1_negate = (ops & op2_opt_neg_src1) ^ src1->negate; AluInstruction *ir = nullptr; for (int i = 0; i < 4 ; ++i) { if (instr.dest.write_mask & (1 << i)){ ir = new AluInstruction(opcode, from_nir(instr.dest, i), m_src[idx0][i], m_src[idx1][i], write); if (src0->negate) ir->set_flag(alu_src0_neg); if (src0->abs) ir->set_flag(alu_src0_abs); if (src1_negate) ir->set_flag(alu_src1_neg); if (src1->abs) ir->set_flag(alu_src1_abs); if (instr.dest.saturate) ir->set_flag(alu_dst_clamp); emit_instruction(ir); } } if (ir) ir->set_flag(alu_last_instr); return true; } bool EmitAluInstruction::emit_alu_op2_split_src_mods(const nir_alu_instr& instr, EAluOp opcode, AluOp2Opts ops) { const nir_alu_src *src0 = &instr.src[0]; const nir_alu_src *src1 = &instr.src[1]; if (ops & op2_opt_reverse) std::swap(src0, src1); GPRVector::Values v0; for (int i = 0; i < 4 ; ++i) v0[i] = m_src[0][i]; GPRVector::Values v1; for (int i = 0; i < 4 ; ++i) v1[i] = m_src[1][i]; if (src0->abs || src0->negate) { int src0_tmp = allocate_temp_register(); GPRVector::Values v0_temp; AluInstruction *ir = nullptr; for (int i = 0; i < 4 ; ++i) { if (instr.dest.write_mask & (1 << i)) { v0_temp[i] = PValue(new GPRValue(src0_tmp, i)); ir = new AluInstruction(op1_mov, v0_temp[i], v0[i], write); if (src0->abs) ir->set_flag(alu_src0_abs); if (src0->negate) ir->set_flag(alu_src0_neg); emit_instruction(ir); v0[i] = v0_temp[i]; } } if (ir) ir->set_flag(alu_last_instr); } if (src1->abs || src1->negate) { int src1_tmp = allocate_temp_register(); GPRVector::Values v1_temp; AluInstruction *ir = nullptr; for (int i = 0; i < 4 ; ++i) { if (instr.dest.write_mask & (1 << i)) { v1_temp[i] = PValue(new GPRValue(src1_tmp, i)); ir = new AluInstruction(op1_mov, v1_temp[i], v1[i], {alu_write}); if (src1->abs) ir->set_flag(alu_src0_abs); if (src1->negate) ir->set_flag(alu_src0_neg); emit_instruction(ir); v1[i] = v1_temp[i]; } } if (ir) ir->set_flag(alu_last_instr); } AluInstruction *ir = nullptr; for (int i = 0; i < 4 ; ++i) { if (instr.dest.write_mask & (1 << i)){ ir = new AluInstruction(opcode, from_nir(instr.dest, i), {v0[i], v1[i]}, {alu_write}); emit_instruction(ir); } } if (ir) ir->set_flag(alu_last_instr); return true; } bool EmitAluInstruction::emit_alu_isign(const nir_alu_instr& instr) { int sel_tmp = allocate_temp_register(); GPRVector tmp(sel_tmp, {0,1,2,3}); AluInstruction *ir = nullptr; PValue help[4]; for (int i = 0; i < 4 ; ++i) { if (instr.dest.write_mask & (1 << i)){ help[i] = from_nir(instr.dest, i); auto s = m_src[0][i]; ir = new AluInstruction(op3_cndgt_int, help[i], s, Value::one_i, s, write); emit_instruction(ir); } } if (ir) ir->set_flag(alu_last_instr); for (int i = 0; i < 4 ; ++i) { if (instr.dest.write_mask & (1 << i)){ ir = new AluInstruction(op2_sub_int, tmp.reg_i(i), Value::zero, help[i], write); emit_instruction(ir); } } if (ir) ir->set_flag(alu_last_instr); for (int i = 0; i < 4 ; ++i) { if (instr.dest.write_mask & (1 << i)){ ir = new AluInstruction(op3_cndgt_int, help[i], tmp.reg_i(i), PValue(new LiteralValue(-1,0)), help[i], write); emit_instruction(ir); } } if (ir) ir->set_flag(alu_last_instr); return true; } bool EmitAluInstruction::emit_fsign(const nir_alu_instr& instr) { PValue help[4]; PValue src[4]; AluInstruction *ir = nullptr; for (int i = 0; i < 4 ; ++i) { help[i] = from_nir(instr.dest, i); src[i] = m_src[0][i]; } if (instr.src[0].abs) { for (int i = 0; i < 4 ; ++i) { if (instr.dest.write_mask & (1 << i)){ ir = new AluInstruction(op2_setgt, help[i], src[i], Value::zero, write); ir->set_flag(alu_src0_abs); emit_instruction(ir); } } if (ir) ir->set_flag(alu_last_instr); if (instr.src[0].negate) { for (int i = 0; i < 4 ; ++i) { if (instr.dest.write_mask & (1 << i)){ ir = new AluInstruction(op1_mov, help[i], help[i], write); ir->set_flag(alu_src0_neg); emit_instruction(ir); } } if (ir) ir->set_flag(alu_last_instr); } return true; } for (int i = 0; i < 4 ; ++i) { if (instr.dest.write_mask & (1 << i)){ ir = new AluInstruction(op3_cndgt, help[i], src[i], Value::one_f, src[i], write); if (instr.src[0].negate) { ir->set_flag(alu_src0_neg); ir->set_flag(alu_src2_neg); } emit_instruction(ir); } } if (ir) ir->set_flag(alu_last_instr); for (int i = 0; i < 4 ; ++i) { if (instr.dest.write_mask & (1 << i)){ ir = new AluInstruction(op3_cndgt, help[i], help[i], Value::one_f, help[i], write); ir->set_flag(alu_src0_neg); ir->set_flag(alu_src1_neg); emit_instruction(ir); } } if (ir) ir->set_flag(alu_last_instr); return true; } bool EmitAluInstruction::emit_alu_op3(const nir_alu_instr& instr, EAluOp opcode, std::array<uint8_t, 3> reorder) { const nir_alu_src *src[3]; src[0] = &instr.src[reorder[0]]; src[1] = &instr.src[reorder[1]]; src[2] = &instr.src[reorder[2]]; AluInstruction *ir = nullptr; for (int i = 0; i < 4 ; ++i) { if (instr.dest.write_mask & (1 << i)){ ir = new AluInstruction(opcode, from_nir(instr.dest, i), m_src[reorder[0]][i], m_src[reorder[1]][i], m_src[reorder[2]][i], write); if (src[0]->negate) ir->set_flag(alu_src0_neg); if (src[1]->negate) ir->set_flag(alu_src1_neg); if (src[2]->negate) ir->set_flag(alu_src2_neg); if (instr.dest.saturate) ir->set_flag(alu_dst_clamp); ir->set_flag(alu_write); emit_instruction(ir); } } make_last(ir); return true; } bool EmitAluInstruction::emit_alu_ineg(const nir_alu_instr& instr) { AluInstruction *ir = nullptr; for (int i = 0; i < 4 ; ++i) { if (instr.dest.write_mask & (1 << i)){ ir = new AluInstruction(op2_sub_int, from_nir(instr.dest, i), Value::zero, m_src[0][i], write); emit_instruction(ir); } } if (ir) ir->set_flag(alu_last_instr); return true; } static const char swz[] = "xyzw01?_"; bool EmitAluInstruction::emit_alu_iabs(const nir_alu_instr& instr) { int sel_tmp = allocate_temp_register(); GPRVector tmp(sel_tmp, {0,1,2,3}); std::array<PValue,4> src; AluInstruction *ir = nullptr; for (int i = 0; i < 4 ; ++i) { if (instr.dest.write_mask & (1 << i)){ ir = new AluInstruction(op2_sub_int, tmp.reg_i(i), Value::zero, m_src[0][i], write); emit_instruction(ir); } } make_last(ir); for (int i = 0; i < 4 ; ++i) { if (instr.dest.write_mask & (1 << i)){ ir = new AluInstruction(op3_cndge_int, from_nir(instr.dest, i), m_src[0][i], m_src[0][i], tmp.reg_i(i), write); emit_instruction(ir); } } make_last(ir); return true; } bool EmitAluInstruction::emit_alu_div_int(const nir_alu_instr& instr, bool use_signed, bool mod) { int sel_tmp = allocate_temp_register(); int sel_tmp0 = allocate_temp_register(); int sel_tmp1 = allocate_temp_register(); PValue asrc1(new GPRValue(sel_tmp, 0)); PValue asrc2(new GPRValue(sel_tmp, 1)); PValue rsign(new GPRValue(sel_tmp, 2)); PValue err(new GPRValue(sel_tmp, 3)); GPRVector tmp0(sel_tmp0, {0,1,2,3}); GPRVector tmp1(sel_tmp1, {0,1,2,3}); std::array<PValue, 4> src0; std::array<PValue, 4> src1; for (int i = 0; i < 4 ; ++i) { if (instr.dest.write_mask & (1 << i)) { src0[i] = m_src[0][i]; src1[i] = m_src[1][i]; } } for (int i = 3; i >= 0 ; --i) { if (!(instr.dest.write_mask & (1 << i))) continue; if (use_signed) { emit_instruction(op2_sub_int, asrc1, {Value::zero, src0[i]}, {alu_write}); emit_instruction(op2_sub_int, asrc2, {Value::zero, src1[i]}, {alu_write}); emit_instruction(op2_xor_int, rsign, {src0[i], src1[i]}, {alu_write, alu_last_instr}); emit_instruction(op3_cndge_int, asrc1, {src0[i], src0[i], asrc1}, {alu_write}); emit_instruction(op3_cndge_int, asrc2, {src1[i], src1[i], asrc2}, {alu_write, alu_last_instr}); } else { asrc1 = src0[i]; asrc2 = src1[i]; } emit_instruction(op1_recip_uint, tmp0.x(), {asrc2}, {alu_write, alu_last_instr}); emit_instruction(op2_mullo_uint, tmp0.z(), {tmp0.x(), asrc2}, {alu_write, alu_last_instr}); emit_instruction(op2_sub_int, tmp0.w(), {Value::zero, tmp0.z()}, {alu_write}); emit_instruction(op2_mulhi_uint, tmp0.y(), {tmp0.x(), asrc2 }, {alu_write, alu_last_instr}); emit_instruction(op3_cnde_int, tmp0.z(), {tmp0.y(), tmp0.w(), tmp0.z()}, {alu_write, alu_last_instr}); emit_instruction(op2_mulhi_uint, err, {tmp0.z(), tmp0.x()}, {alu_write, alu_last_instr}); emit_instruction(op2_sub_int, tmp1.x(), {tmp0.x(), err}, {alu_write}); emit_instruction(op2_add_int, tmp1.y(), {tmp0.x(), err}, {alu_write, alu_last_instr}); emit_instruction(op3_cnde_int, tmp0.x(), {tmp0.y(), tmp1.y(), tmp1.x()}, {alu_write, alu_last_instr}); emit_instruction(op2_mulhi_uint, tmp0.z(), {tmp0.x(), asrc1 }, {alu_write, alu_last_instr}); emit_instruction(op2_mullo_uint, tmp0.y(), {tmp0.z(), asrc2 }, {alu_write, alu_last_instr}); emit_instruction(op2_sub_int, tmp0.w(), {asrc1, tmp0.y()}, {alu_write, alu_last_instr}); emit_instruction(op2_setge_uint, tmp1.x(), {tmp0.w(), asrc2}, {alu_write}); emit_instruction(op2_setge_uint, tmp1.y(), {asrc1, tmp0.y()}, {alu_write}); if (mod) { emit_instruction(op2_sub_int, tmp1.z(), {tmp0.w(), asrc2}, {alu_write}); emit_instruction(op2_add_int, tmp1.w(), {tmp0.w(), asrc2}, {alu_write, alu_last_instr}); } else { emit_instruction(op2_add_int, tmp1.z(), {tmp0.z(), Value::one_i}, {alu_write}); emit_instruction(op2_sub_int, tmp1.w(), {tmp0.z(), Value::one_i}, {alu_write, alu_last_instr}); } emit_instruction(op2_and_int, tmp1.x(), {tmp1.x(), tmp1.y()}, {alu_write, alu_last_instr}); if (mod) emit_instruction(op3_cnde_int, tmp0.z(), {tmp1.x(), tmp0.w(), tmp1.z()}, {alu_write, alu_last_instr}); else emit_instruction(op3_cnde_int, tmp0.z(), {tmp1.x(), tmp0.z(), tmp1.z()}, {alu_write, alu_last_instr}); if (use_signed) { emit_instruction(op3_cnde_int, tmp0.z(), {tmp1.y(), tmp1.w(), tmp0.z()}, {alu_write, alu_last_instr}); emit_instruction(op2_sub_int, tmp0.y(), {Value::zero, tmp0.z()}, {alu_write, alu_last_instr}); if (mod) emit_instruction(op3_cndge_int, from_nir(instr.dest, i), {src0[i], tmp0.z(), tmp0.y()}, {alu_write, alu_last_instr}); else emit_instruction(op3_cndge_int, from_nir(instr.dest, i), {rsign, tmp0.z(), tmp0.y()}, {alu_write, alu_last_instr}); } else { emit_instruction(op3_cnde_int, from_nir(instr.dest, i), {tmp1.y(), tmp1.w(), tmp0.z()}, {alu_write, alu_last_instr}); } } return true; } void EmitAluInstruction::split_alu_modifiers(const nir_alu_src& src, const GPRVector::Values& v, GPRVector::Values& out, int ncomp) { AluInstruction *alu = nullptr; for (int i = 0; i < ncomp; ++i) { alu = new AluInstruction(op1_mov, out[i], v[i], {alu_write}); if (src.abs) alu->set_flag(alu_src0_abs); if (src.negate) alu->set_flag(alu_src0_neg); emit_instruction(alu); } make_last(alu); } bool EmitAluInstruction::emit_tex_fdd(const nir_alu_instr& instr, TexInstruction::Opcode op, bool fine) { GPRVector::Values v; std::array<int, 4> writemask = {0,1,2,3}; int ncomp = nir_src_num_components(instr.src[0].src); GPRVector::Swizzle src_swz; for (auto i = 0; i < 4; ++i) { src_swz[i] = instr.src[0].swizzle[i]; } auto src = vec_from_nir_with_fetch_constant(instr.src[0].src, (1 << ncomp) - 1, src_swz); if (instr.src[0].abs || instr.src[0].negate) { GPRVector tmp = get_temp_vec4(); split_alu_modifiers(instr.src[0], src.values(), tmp.values(), ncomp); src = tmp; } for (int i = 0; i < 4; ++i) { writemask[i] = (instr.dest.write_mask & (1 << i)) ? i : 7; v[i] = from_nir(instr.dest, (i < ncomp) ? i : 0); } /* This is querying the dreivatives of the output fb, so we would either need * access to the neighboring pixels or to the framebuffer. Neither is currently * implemented */ GPRVector dst(v); auto tex = new TexInstruction(op, dst, src, 0, R600_MAX_CONST_BUFFERS, PValue()); tex->set_dest_swizzle(writemask); if (fine) { std::cerr << "Sewt fine flag\n"; tex->set_flag(TexInstruction::grad_fine); } emit_instruction(tex); return true; } bool EmitAluInstruction::emit_bitfield_extract(const nir_alu_instr& instr, EAluOp opcode) { int itmp = allocate_temp_register(); std::array<PValue, 4> tmp; std::array<PValue, 4> dst; std::array<PValue, 4> src0; std::array<PValue, 4> shift; PValue l32(new LiteralValue(32)); unsigned write_mask = instr.dest.write_mask; AluInstruction *ir = nullptr; for (int i = 0; i < 4; i++) { if (!(write_mask & (1<<i))) continue; dst[i] = from_nir(instr.dest, i); src0[i] = m_src[0][i]; shift[i] = m_src[2][i]; ir = new AluInstruction(opcode, dst[i], {src0[i], m_src[1][i], shift[i]}, {alu_write}); emit_instruction(ir); } make_last(ir); for (int i = 0; i < 4; i++) { if (!(write_mask & (1<<i))) continue; tmp[i] = PValue(new GPRValue(itmp, i)); ir = new AluInstruction(op2_setge_int, tmp[i], {shift[i], l32}, {alu_write}); emit_instruction(ir); } make_last(ir); for (int i = 0; i < 4; i++) { if (!(write_mask & (1<<i))) continue; ir = new AluInstruction(op3_cnde_int, dst[i], {tmp[i], dst[i], src0[i]}, {alu_write}); emit_instruction(ir); } make_last(ir); return true; } bool EmitAluInstruction::emit_bitfield_insert(const nir_alu_instr& instr) { auto t0 = get_temp_vec4(); auto t1 = get_temp_vec4(); auto t2 = get_temp_vec4(); auto t3 = get_temp_vec4(); PValue l32(new LiteralValue(32)); unsigned write_mask = instr.dest.write_mask; if (!write_mask) return true; AluInstruction *ir = nullptr; for (int i = 0; i < 4; i++) { if (!(write_mask & (1<<i))) continue; ir = new AluInstruction(op2_setge_int, t0[i], {m_src[3][i], l32}, {alu_write}); emit_instruction(ir); } make_last(ir); for (int i = 0; i < 4; i++) { if (!(write_mask & (1<<i))) continue; ir = new AluInstruction(op2_bfm_int, t1[i], {m_src[3][i], m_src[2][i]}, {alu_write}); emit_instruction(ir); } make_last(ir); for (int i = 0; i < 4; i++) { if (!(write_mask & (1<<i))) continue; ir = new AluInstruction(op2_lshl_int, t2[i], {m_src[1][i], m_src[2][i]}, {alu_write}); emit_instruction(ir); } make_last(ir); for (int i = 0; i < 4; i++) { if (!(write_mask & (1<<i))) continue; ir = new AluInstruction(op3_bfi_int, t3[i], {t1[i], t2[i], m_src[0][i]}, {alu_write}); emit_instruction(ir); } make_last(ir); for (int i = 0; i < 4; i++) { if (!(write_mask & (1<<i))) continue; ir = new AluInstruction(op3_cnde_int, from_nir(instr.dest, i), {t0[i], t3[i], m_src[1][i]}, {alu_write}); emit_instruction(ir); } make_last(ir); return true; } bool EmitAluInstruction::emit_unpack_32_2x16_split_y(const nir_alu_instr& instr) { auto tmp = get_temp_register(); emit_instruction(op2_lshr_int, tmp, {m_src[0][0], PValue(new LiteralValue(16))}, {alu_write, alu_last_instr}); emit_instruction(op1_flt16_to_flt32, from_nir(instr.dest, 0), {tmp}, {alu_write, alu_last_instr}); return true; } bool EmitAluInstruction::emit_unpack_32_2x16_split_x(const nir_alu_instr& instr) { emit_instruction(op1_flt16_to_flt32, from_nir(instr.dest, 0), {m_src[0][0]},{alu_write, alu_last_instr}); return true; } bool EmitAluInstruction::emit_pack_32_2x16_split(const nir_alu_instr& instr) { PValue x = get_temp_register(); PValue y = get_temp_register(); emit_instruction(op1_flt32_to_flt16, x,{m_src[0][0]},{alu_write}); emit_instruction(op1_flt32_to_flt16, y,{m_src[1][0]},{alu_write, alu_last_instr}); emit_instruction(op2_lshl_int, y, {y, PValue(new LiteralValue(16))},{alu_write, alu_last_instr}); emit_instruction(op2_or_int, {from_nir(instr.dest, 0)} , {x, y},{alu_write, alu_last_instr}); return true; } }
[ "eric+marge@anholt.net" ]
eric+marge@anholt.net
129a365f6675c06ccb8deac0adbb89fc459e380f
dec1aaef08be491c7ee1434e408a2537e5d9cec8
/tests/inc/test-linspace.h
1e75c4b0ff4e974708a84f7afbb754eec971c6c7
[]
no_license
JHopeCollins/ellipticSolvers
615dbe31f4cc3ffbd1380c45d1a0e4ed04898cb3
97208da821fb43276900d6d89701ea44372e2237
refs/heads/master
2022-02-03T04:20:59.747069
2019-07-18T16:07:16
2019-07-18T16:07:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
921
h
# ifndef TEST_LINSPACE_H # define TEST_LINSPACE_H #include "cppunit/TestFixture.h" #include "cppunit/extensions/HelperMacros.h" #include "linspace.h" /* Tests for linspace function */ class Test_linspace : public CppUnit::TestFixture { private: CPPUNIT_TEST_SUITE( Test_linspace ); CPPUNIT_TEST( test_n_is_1_returns_lowerLimit ); CPPUNIT_TEST( test_0to1_spacing ); CPPUNIT_TEST( test_integer_spacing ); CPPUNIT_TEST( test_0to0_returns0 ); CPPUNIT_TEST( test_1to0_reverse_spacing ); CPPUNIT_TEST_SUITE_END(); float floatError=10e-6; public: void setUp(); void tearDown(); void test_n_is_1_returns_lowerLimit(); void test_0to1_spacing(); void test_integer_spacing(); void test_0to0_returns0(); void test_1to0_reverse_spacing(); }; CPPUNIT_TEST_SUITE_REGISTRATION( Test_linspace ); # endif
[ "joshua.hope-collins@eng.ox.ac.uk" ]
joshua.hope-collins@eng.ox.ac.uk
fb9060ea573d5efab83d5c9e968a100c4a9ff17c
0cb85cd0c88a9b9f0cca4472742c2bf9febef2d8
/PPP/GUI/TaskView.h
1a70a2e7cf65079ece2fb921bb515494d65470ff
[]
no_license
seth1002/antivirus-1
9dfbadc68e16e51f141ac8b3bb283c1d25792572
3752a3b20e1a8390f0889f6192ee6b851e99e8a4
refs/heads/master
2020-07-15T00:30:19.131934
2016-07-21T13:59:11
2016-07-21T13:59:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,917
h
// TaskView.h: interface for the CTaskView class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_TASKVIEW_H__C7D32A70_AE04_4467_88A7_23A2912BE79C__INCLUDED_) #define AFX_TASKVIEW_H__C7D32A70_AE04_4467_88A7_23A2912BE79C__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "TaskProfile.h" #include "ListsView.h" #include <plugin/p_reportdb.h> #define EVENTID_SETTINGS_UPDATE 0x51648943 #define EVENTID_SETTINGS_LOADED 0x0a222235 #define IS_TASK_IN_PROGRESS( _state ) ((_state) & STATE_FLAG_ACTIVE ) class CProfile; ////////////////////////////////////////////////////////////////////// // CSettingsDlg class CSettingsDlg : public CDialogBindingT<cSerializable> { protected: typedef CDialogBindingT<cSerializable> TBase; using TBase::m_nActionsMask; using TBase::m_ser; using TBase::m_pStruct; public: CSettingsDlg(CSinkCreateCtx * pCtx); ~CSettingsDlg(); void SetDirty() { m_bModified = 2; } protected: bool OnOk(); bool OnClose(tDWORD& nResult); CItemBase * m_pContextItem; unsigned m_bContextIsList : 1; unsigned m_bModified : 2; }; ////////////////////////////////////////////////////////////////////// // CTaskProfileView class CTaskProfileView : public CDialogSink { public: enum eFlags {fStat = 0x01, fEdit = 0x02}; CTaskProfileView(tDWORD nFlags, CSinkCreateCtx * pCtx); CTaskProfileView(CProfile * pParentProfiles, tDWORD nFlags = 0, LPCSTR strDefProfile = NULL); tERROR SaveSettings(); void RefreshStatistics(bool bFresh = true); static LPCSTR GetProfileName(tString &strProfileName, CSinkCreateCtx * pCtx, size_t nParamNum); static bool AddProfileSource(bool bStat, CFieldsBinder * pBinding, CProfile * pProfile, LPCTSTR strSect = NULL); virtual void OnCustomizeData(cSerializable * pData, bool bIn); protected: void OnCreate(); void OnInit(); void OnInitProps(CItemProps& pProps); void OnTimerRefresh(tDWORD nTimerSpin); void OnEvent(tDWORD nEventId, cSerializable* pData); void OnChangedData(CItemBase * pItem); bool OnAddDataSection(LPCTSTR strSect); bool OnApply(); protected: SINK_MAP_BEGIN() SINK_DYNAMIC("taskreport", CReportSink(pItem, m_pProfile)) SINK_MAP_END(CDialogSink) cNode * CreateOperator(const char *name, cNode **args, cAlloc *al); class _Data : public CProfile { public: CProfile * GetProfile(LPCSTR strProfile); tERROR SaveSettings(); }; friend class _Data; struct CReportSink : public CListItemSink { CReportSink(CItemBase* pList, CProfile * pProfile); bool GetInfo(cDataInfo& info); cSerializable* GetRowData(tIdx nItem); private: cAutoObj<cReport> m_pReport; cSerializableObj m_Data; }; CProfile * m_pProfile; CProfile * m_pParentProfiles; tDWORD m_nFlags; CItemBase * m_pContextItem; _Data m_data; MEMBER_NODE(cNodeSaveSettings) m_nodeSaveSettings; unsigned m_saveSettingsUsed : 1; }; ////////////////////////////////////////////////////////////////////// // CReportDbView #define CACHE_EVENTS_SIZE 1024 class CReportDbView : public CListSinkMaster { public: CReportDbView(tDWORD nSerId, tDWORD nDataSize); ~CReportDbView(); tDWORD OnBindingFlags() { return ITEMBIND_F_VALUE; } tTYPE_ID OnGetType() { return tTYPE_ID(m_Data ? m_Data->getIID() : cSer::eIID); } void OnInitProps(CItemProps& pProps); void OnChangedData(CItemBase * pItem) { CListItemSink::OnChangedData(pItem); } bool GetInfo(cDataInfo& info); cSerializable* GetRowData(tIdx nItem); void PrepareRows(tIdx nFrom, tDWORD nCount); virtual void OnCustomizeData(cSer * dst, tBYTE * src) = 0; protected: cReportDB* m_pReport; tDWORD m_eDbType; cSerializableObj m_Data; tDWORD m_nDataSize; cVector<tBYTE> m_Cache; tIdx m_Idx[CACHE_EVENTS_SIZE]; tDWORD m_nCurPos; }; ////////////////////////////////////////////////////////////////////// // CThreatsList class CThreatsList : public CListItemSink { public: CThreatsList(); ~CThreatsList(); void DiscardItems(bool bAll); void TreatItems(bool bAll, bool bDelete); void CollectSelected(cDwordVector &aScanRecords); void RestoreItems(bool bAll); void AddToQuarantine(); protected: void OnInitProps(CItemProps& pProps); cNode * CreateOperator(const char *name, cNode **args, cAlloc *al); bool GetInfo(cDataInfo& info); cSerializable* GetRowData(tIdx nItem); private: cAVSTreats * m_pTreats; cInfectedObjectInfo m_cache; }; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// #endif // !defined(AFX_TASKVIEW_H__C7D32A70_AE04_4467_88A7_23A2912BE79C__INCLUDED_)
[ "idrez.mochamad@gmail.com" ]
idrez.mochamad@gmail.com
7faabeac5c4359e9f90390290984b7138a9a5446
8fdd170d3e39fd4eeffea5ec2d61bd0c06eab16f
/1_Manager/xPLduino-Manager/bin/Debug/Firmware/xplduino_controller_RF/water_counter_xpl.cpp
636683c14e98c01517a1768a4b59529933e05e98
[]
no_license
TheGrumpy/xPLduinoProject
6fc07b3cc1ecaa726f07ec7b72eb0c9ef35c1885
35a4fa354d9052a79b4f9d2baebe2ea536b890bd
refs/heads/master
2020-05-30T11:00:21.467230
2015-06-30T13:02:03
2015-06-30T13:02:03
24,757,977
3
0
null
null
null
null
UTF-8
C++
false
false
5,026
cpp
#include "water_counter_xpl.h" #include "water_counter_core.h" #include <avr/pgmspace.h> #define WATER_COUNTER_XPL_VERSION 0 extern char vendor_id[]; // vendor id extern char device_id[]; // device id extern char instance_id[]; // instance id extern xPL xpl; extern water_counter *WATER_COUNTER; extern int NumberOfWaterCounter; // number of instances declared #define DEVICE 1 #define COMMAND 6 int water_counter_status(water_counter *_water_counter, byte _type){ char _current[10+1]="\0"; sprintf(_current, "%s%d", _current, _water_counter -> getValue()); #ifdef DEBUG_WATER_COUNTER_XPL if(_type==T_TRIG){ Serial.print(F("trigger of ")); } else if(_type==T_STAT){ Serial.print(F("stat of ")); } else{ Serial.print(F("unknown type of ")); } Serial.print(_water_counter -> getName()); Serial.print(F(": ")); Serial.print(_water_counter -> getValue()); Serial.println(F(" L")); #endif xPL_Message msg; msg.hop = 1; /* construction du message */ if(_type == XPL_TRIG){ msg.type = XPL_TRIG; }else{ msg.type = XPL_STAT; } msg.SetSource("xplduino","water",instance_id); msg.SetTarget_P(PSTR("*")); msg.SetSchema_P(PSTR("sensor"), PSTR("basic")); msg.AddCommand("type","water"); msg.AddCommand("device", _water_counter -> getName()); msg.AddCommand("current", _current); /* envoi du message */ xpl.SendMessage(msg.toString()); #ifdef DEBUG_WATER_COUNTER_XPL Serial.println(F("------------ Water Counter xPL ------------")); Serial.println(msg.toString()); #endif return 1; } // recherche le device dans la liste et renvoie son etat si trouvee int water_counter_request(xPL_Message * message){ #define REQUEST 0 int8_t cmnd=0; //donnees temporaire pour la recherche des commandes char temp[4+1]="\0"; // level ou fade-rate au format char pour conversion en int int16_t i=0; int16_t nbre= message -> command_count; // memorise le numero de la commande byte id_request=0; byte id_device=0; #ifdef DEBUG_WATER_COUNTER_XPL Serial.print(F("- analyse de ")); Serial.print(nbre); Serial.println(F(" commandes -")); #endif for(i=0; i < nbre; i++){ #ifdef DEBUG_WATER_COUNTER_XPL Serial.print(F(" cherche ")); Serial.println(message -> command[i].name); #endif if(!strcmp(message -> command[i].name,"request")){ if(!bitRead(cmnd,REQUEST)){ bitSet(cmnd,REQUEST); id_request=i; #ifdef DEBUG_WATER_COUNTER_XPL Serial.println(F(" => ok")); #endif }else{ // doublon return 1; } }else if(!(strcmp(message -> command[i].name,"device"))){ if(!bitRead(cmnd,DEVICE)){ bitSet(cmnd,DEVICE); id_device=i; #ifdef DEBUG_WATER_COUNTER_XPL Serial.println(F(" => ok")); #endif }else{ // doublon return 1; } } } //verification que commande goto, device et level sont present. Fade-rate est en option. if(bitRead(cmnd,REQUEST) && bitRead(cmnd,DEVICE)){ //recherche du device water_counter int position=water_counter_find(message -> command[id_device].value, 0); if(position>=0) { int setpoint=0; if(!strcmp(message -> command[id_request].value,"devstate")){ water_counter_status(&WATER_COUNTER[i], T_STAT); //TRIG } }else{ Serial.print(F(" => command unknown: ")); Serial.print(message -> command[id_request].value); } } } // recherche le device dans la liste et modifie ses parametres suite a un message CONFIG.RESPONSE int water_counter_find(char *_name, int first){ extern water_counter *water_counter; // on parcourt la liste des device water_counter en commencant par la ligne "first" for(int i=first; i < NumberOfWaterCounter; i++){ #ifdef DEBUG_WATER_COUNTER_XPL Serial.print(F(" id ")); Serial.print(i); Serial.print(F(" device ")); Serial.print(_name); Serial.print(F(" compare to '")); Serial.println(water_counter[i].getName()); #endif if(!strcmp(_name, water_counter[i].getName())) // si device trouve alors on retourne le numero { #ifdef DEBUG_WATER_COUNTER_XPL Serial.print(F(" => device '")); Serial.print(_name); Serial.print(F(" ' has been found at position ")); Serial.println(i); #endif return i; } } return -1; // si device pas trouve alors on retourne -1 } byte aboutWaterCounterXplVersion(){ return WATER_COUNTER_XPL_VERSION; }
[ "braveheart87@hotmail.fr" ]
braveheart87@hotmail.fr
695efb0fa7da21b94b4a3a25e0caac1d926c84a2
1b1462afd6871c16a4f4e6c71d57b28e4433c250
/student.h
483c2a9ec74b426dafdcbad0ecf2ccd09cad9a33
[]
no_license
srgray17/AssignmentThree-DS
5670ddecdfd1af494d8a58aef978bf5702823173
16d567a64fdc30100c7535783d26592053366c63
refs/heads/master
2023-03-06T01:01:56.979549
2021-02-22T14:52:37
2021-02-22T14:52:37
341,235,787
0
0
null
null
null
null
UTF-8
C++
false
false
575
h
#pragma once #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <cstdlib> #include <fstream> #include <iomanip> #include <stdio.h> using namespace std; typedef string treeType; class Student { private: string fName; string lName; float mark; int id; public: Student(); Student(string fName, string lName, int mark, int id); string getFName(); string getLName(); float getMark(); int getId(); void setFName(string newfname); void setLName(string newlname); void setMark(float newmark); void setId(int id); };
[ "srgray@lakeheadu.ca" ]
srgray@lakeheadu.ca
7545f493c9dac0fe0ee3ac7da6f74ac2f63a6d69
452be58b4c62e6522724740cac332ed0fe446bb8
/src/sql/test_vfs.cc
ca6c82a472db484c1e869b9b97908265d4417f3d
[]
no_license
blockspacer/cobalt-clone-cab7770533804d582eaa66c713a1582f361182d3
b6e802f4182adbf6a7451a5d48dc4e158b395107
0b72f93b07285f3af3c8452ae2ceaf5860ca7c72
refs/heads/master
2020-08-18T11:32:21.458963
2019-10-17T13:09:35
2019-10-17T13:09:35
215,783,613
1
1
null
null
null
null
UTF-8
C++
false
false
8,944
cc
// Copyright 2016 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Adapted from cobalt/storage. #include "sql/test_vfs.h" #include <string.h> #include <algorithm> #include <map> #include "base/compiler_specific.h" #include "base/lazy_instance.h" #include "base/logging.h" #include "base/rand_util.h" #include "base/strings/string_util.h" #include "base/synchronization/lock.h" #include "third_party/sqlite/sqlite3.h" namespace sql { namespace { // A "subclass" of sqlite3_file with our required data structures added. struct virtual_file { sqlite3_file sql_internal_file; std::string* data; base::Lock* lock; int current_lock; int shared; }; // A very simple in-memory virtual file system. class TestVfs { public: typedef std::map<std::string, std::string> FileMap; public: TestVfs() {} ~TestVfs() {} void Register(); void Unregister(); std::string* Open(const char* path) { return &file_map_[path]; } void Delete(const char* path) { file_map_.erase(path); } private: sqlite3_vfs vfs_; FileMap file_map_; }; base::LazyInstance<TestVfs>::DestructorAtExit g_vfs = LAZY_INSTANCE_INITIALIZER; int VfsClose(sqlite3_file* file) { virtual_file* vfile = reinterpret_cast<virtual_file*>(file); delete vfile->lock; return SQLITE_OK; } int VfsRead(sqlite3_file* file, void* out, int bytes, sqlite_int64 offset) { virtual_file* vfile = reinterpret_cast<virtual_file*>(file); base::AutoLock lock(*vfile->lock); if (offset >= static_cast<sqlite_int64>(vfile->data->length())) { return SQLITE_OK; } size_t available = std::max(static_cast<sqlite_int64>(vfile->data->length()) - offset, static_cast<sqlite_int64>(0)); size_t to_read = std::min(available, static_cast<size_t>(bytes)); if (to_read == 0) { return SQLITE_OK; } memcpy(out, &(vfile->data->c_str()[offset]), to_read); return SQLITE_OK; } int VfsWrite(sqlite3_file* file, const void* data, int bytes, sqlite3_int64 offset) { size_t max = offset + bytes; virtual_file* vfile = reinterpret_cast<virtual_file*>(file); base::AutoLock lock(*vfile->lock); if (vfile->data->length() < max) { vfile->data->resize(max); } vfile->data->replace(offset, bytes, reinterpret_cast<const char*>(data), bytes); return SQLITE_OK; } int VfsSync(sqlite3_file* pFile, int flags) { return SQLITE_OK; } int VfsFileControl(sqlite3_file* pFile, int op, void* pArg) { return SQLITE_OK; } int VfsSectorSize(sqlite3_file* file) { // The number of bytes that can be read without disturbing other bytes in the // file. return 1; } int VfsLock(sqlite3_file* file, const int mode) { virtual_file* vfile = reinterpret_cast<virtual_file*>(file); base::AutoLock lock(*vfile->lock); // If there is already a lock of this type or more restrictive, do nothing if (vfile->current_lock >= mode) { return SQLITE_OK; } if (mode == SQLITE_LOCK_SHARED) { DCHECK_EQ(vfile->current_lock, SQLITE_LOCK_NONE); vfile->shared++; vfile->current_lock = SQLITE_LOCK_SHARED; } if (mode == SQLITE_LOCK_RESERVED) { DCHECK_EQ(vfile->current_lock, SQLITE_LOCK_SHARED); vfile->current_lock = SQLITE_LOCK_RESERVED; } if (mode == SQLITE_LOCK_EXCLUSIVE) { if (vfile->current_lock >= SQLITE_LOCK_PENDING) { return SQLITE_BUSY; } vfile->current_lock = SQLITE_LOCK_PENDING; if (vfile->shared > 1) { // There are some outstanding shared locks (greater than one because the // pending lock is an "upgraded" shared lock) return SQLITE_BUSY; } // Acquire the exclusive lock vfile->current_lock = SQLITE_LOCK_EXCLUSIVE; } return SQLITE_OK; } int VfsUnlock(sqlite3_file* file, int mode) { DCHECK_LE(mode, SQLITE_LOCK_SHARED); virtual_file* vfile = reinterpret_cast<virtual_file*>(file); base::AutoLock lock(*vfile->lock); #ifdef STARBOARD #undef COMPILE_ASSERT #define COMPILE_ASSERT static_assert #define sqlite_lock_constants_order_has_changed \ "sqlite lock constants order has changed!" #endif COMPILE_ASSERT(SQLITE_LOCK_NONE < SQLITE_LOCK_SHARED, sqlite_lock_constants_order_has_changed); COMPILE_ASSERT(SQLITE_LOCK_SHARED < SQLITE_LOCK_RESERVED, sqlite_lock_constants_order_has_changed); COMPILE_ASSERT(SQLITE_LOCK_RESERVED < SQLITE_LOCK_PENDING, sqlite_lock_constants_order_has_changed); COMPILE_ASSERT(SQLITE_LOCK_PENDING < SQLITE_LOCK_EXCLUSIVE, sqlite_lock_constants_order_has_changed); if (mode == SQLITE_LOCK_NONE && vfile->current_lock >= SQLITE_LOCK_SHARED) { vfile->shared--; } vfile->current_lock = mode; return SQLITE_OK; } int VfsCheckReservedLock(sqlite3_file* file, int* result) { virtual_file* vfile = reinterpret_cast<virtual_file*>(file); base::AutoLock lock(*vfile->lock); // The function expects a result is 1 if the lock is reserved, pending, or // exclusive; 0 otherwise. *result = vfile->current_lock >= SQLITE_LOCK_RESERVED ? 1 : 0; return SQLITE_OK; } int VfsFileSize(sqlite3_file* file, sqlite3_int64* out_size) { virtual_file* vfile = reinterpret_cast<virtual_file*>(file); *out_size = vfile->data->length(); return SQLITE_OK; } int VfsTruncate(sqlite3_file* file, sqlite3_int64 size) { virtual_file* vfile = reinterpret_cast<virtual_file*>(file); base::AutoLock lock(*vfile->lock); vfile->data->resize(size); return SQLITE_OK; } int VfsDeviceCharacteristics(sqlite3_file* file) { return 0; } const sqlite3_io_methods s_cobalt_vfs_io = { 1, // Structure version number VfsClose, // xClose VfsRead, // xRead VfsWrite, // xWrite VfsTruncate, // xTruncate VfsSync, // xSync VfsFileSize, // xFileSize VfsLock, // xLock VfsUnlock, // xUnlock VfsCheckReservedLock, // xCheckReservedLock VfsFileControl, // xFileControl VfsSectorSize, // xSectorSize VfsDeviceCharacteristics // xDeviceCharacteristics }; int VfsOpen(sqlite3_vfs* sql_vfs, const char* path, sqlite3_file* file, int flags, int* out_flags) { DCHECK(path) << "NULL filename not supported."; virtual_file* vfile = reinterpret_cast<virtual_file*>(file); vfile->lock = new base::Lock; TestVfs* vfs = reinterpret_cast<TestVfs*>(sql_vfs->pAppData); vfile->data = vfs->Open(path); file->pMethods = &s_cobalt_vfs_io; return SQLITE_OK; } int VfsDelete(sqlite3_vfs* sql_vfs, const char* path, int sync_dir) { TestVfs* vfs = reinterpret_cast<TestVfs*>(sql_vfs->pAppData); vfs->Delete(path); return SQLITE_OK; } int VfsFullPathname(sqlite3_vfs* sql_vfs, const char* path, int out_size, char* out_path) { size_t path_size = static_cast<size_t>(out_size); if (base::strlcpy(out_path, path, path_size) < path_size) { return SQLITE_OK; } return SQLITE_ERROR; } int VfsAccess(sqlite3_vfs* sql_vfs, const char* name, int flags, int* result) { // We should always have a valid, readable/writable file. *result |= SQLITE_ACCESS_EXISTS | SQLITE_ACCESS_READWRITE; return SQLITE_OK; } int VfsRandomness(sqlite3_vfs* sql_vfs, int bytes, char* out) { base::RandBytes(out, static_cast<size_t>(bytes)); return SQLITE_OK; } void TestVfs::Register() { memset(&vfs_, 0, sizeof(vfs_)); vfs_.iVersion = 1; vfs_.szOsFile = sizeof(virtual_file); vfs_.mxPathname = 512; vfs_.pNext = NULL; vfs_.zName = "test_vfs"; vfs_.pAppData = this; vfs_.xOpen = VfsOpen; vfs_.xDelete = VfsDelete; vfs_.xAccess = VfsAccess; vfs_.xFullPathname = VfsFullPathname; vfs_.xRandomness = VfsRandomness; // Ensure we are not registering multiple of these with the same name. // Behavior is undefined in that case. DCHECK(sqlite3_vfs_find(vfs_.zName) == NULL); int ret = sqlite3_vfs_register(&vfs_, 1 /* make_default */); DCHECK_EQ(ret, SQLITE_OK); } void TestVfs::Unregister() { int ret = sqlite3_vfs_unregister(&vfs_); file_map_.clear(); DCHECK_EQ(ret, SQLITE_OK); } } // namespace void RegisterTestVfs() { g_vfs.Get().Register(); } void UnregisterTestVfs() { g_vfs.Get().Unregister(); } } // namespace sql
[ "trofimov_d_a@magnit.ru" ]
trofimov_d_a@magnit.ru
2af5680b5d45bda1ee7f4a7141145095d0a3c88a
26ab01c731a26b2a1748acf148d2f3f6937b6df4
/BEHAPPY.cpp
e0ab6755863d8569989cd2f6bd6327cee0adfce7
[]
no_license
prakhs123/standalone-programs
881ae3e800b8dccc7921121fa7e264cbe71e590e
1088196779dc4747069aec9bbfa2ee5f35cf0204
refs/heads/master
2020-11-27T16:46:22.055231
2019-12-22T08:04:55
2019-12-22T08:04:55
229,533,661
0
0
null
null
null
null
UTF-8
C++
false
false
1,088
cpp
#include <iostream> using namespace std; int min(int a1, int a2){ if(a1<a2) return a1; else return a2; } int max(int a1, int a2){ if(a1>a2) return a1; else return a2; } int main(){ int M,N,n,k; int A[21],B[21],a[21]; int S[101][105]; cin>>M>>N; n=M; k=N; for(int i=1;i<=M;i++){ cin>>A[i]>>B[i]; a[i]=B[i]-A[i]; //cout << a[i] << " "; k-=A[i]; } // Formulating the problem as x1 +x2 +x3 + ... + xn =k // where 0 <= xi <= a[i] , where a[i]=B[i]-A[i] // where n=M, k = N- sigma(xi) //cout << k << endl; //cout << n << endl; int p; for(p=0;p<=min(a[1],k);p++) S[1][p]=1; for(;p<=k;p++) S[1][p]=0; for(int i=2;i<=n;i++){ for(int j=0;j<=k;j++){ int s=0; for(int r=j;r>=max(0,j-a[i]);r--){ s += S[i-1][r]; } S[i][j]=s; } } for(int i=1;i<=n;i++){ for(int j=0;j<=k;j++) cout<<S[i][j]<<" "; cout<<endl; } cout<<S[n][k]<<endl; return 0; }
[ "prakhs123@gmail.com" ]
prakhs123@gmail.com
638c20238dbca96b94d4b5e1bf46a110df3980c3
9da899bf6541c6a0514219377fea97df9907f0ae
/Runtime/MovieSceneTracks/Public/MovieSceneTracksComponentTypes.h
97199733ddd8366049fd554b8920d3c27685794c
[]
no_license
peichangliang123/UE4
1aa4df3418c077dd8f82439ecc808cd2e6de4551
20e38f42edc251ee96905ed8e96e1be667bc14a5
refs/heads/master
2023-08-17T11:31:53.304431
2021-09-15T00:31:03
2021-09-15T00:31:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,669
h
// Copyright Epic Games, Inc. All Rights Reserved. #pragma once #include "Math/Transform.h" #include "EntitySystem/BuiltInComponentTypes.h" #include "EntitySystem/MovieSceneEntityIDs.h" #include "EntitySystem/MovieScenePropertySystemTypes.h" #include "Engine/EngineTypes.h" #include "EulerTransform.h" #include "TransformData.h" #include "MovieSceneTracksComponentTypes.generated.h" class UMovieSceneLevelVisibilitySection; struct FMovieSceneObjectBindingID; /** Component data for the level visibility system */ USTRUCT() struct FLevelVisibilityComponentData { GENERATED_BODY() UPROPERTY() TObjectPtr<const UMovieSceneLevelVisibilitySection> Section = nullptr; }; namespace UE { namespace MovieScene { /** Intermediate type used for applying partially animated transforms. Saves us from repteatedly recomposing quaternions from euler angles */ struct FIntermediate3DTransform { float T_X, T_Y, T_Z, R_X, R_Y, R_Z, S_X, S_Y, S_Z; FIntermediate3DTransform() : T_X(0.f), T_Y(0.f), T_Z(0.f), R_X(0.f), R_Y(0.f), R_Z(0.f), S_X(0.f), S_Y(0.f), S_Z(0.f) {} FIntermediate3DTransform(float InT_X, float InT_Y, float InT_Z, float InR_X, float InR_Y, float InR_Z, float InS_X, float InS_Y, float InS_Z) : T_X(InT_X), T_Y(InT_Y), T_Z(InT_Z), R_X(InR_X), R_Y(InR_Y), R_Z(InR_Z), S_X(InS_X), S_Y(InS_Y), S_Z(InS_Z) {} FIntermediate3DTransform(const FVector& InLocation, const FRotator& InRotation, const FVector& InScale) : T_X(InLocation.X), T_Y(InLocation.Y), T_Z(InLocation.Z) , R_X(InRotation.Roll), R_Y(InRotation.Pitch), R_Z(InRotation.Yaw) , S_X(InScale.X), S_Y(InScale.Y), S_Z(InScale.Z) {} float operator[](int32 Index) const { check(Index >= 0 && Index < 9); return (&T_X)[Index]; } FVector GetTranslation() const { return FVector(T_X, T_Y, T_Z); } FRotator GetRotation() const { return FRotator(R_Y, R_Z, R_X); } FVector GetScale() const { return FVector(S_X, S_Y, S_Z); } MOVIESCENETRACKS_API void ApplyTo(USceneComponent* SceneComponent) const; }; struct FComponentAttachParamsDestination { FName SocketName = NAME_None; FName ComponentName = NAME_None; MOVIESCENETRACKS_API USceneComponent* ResolveAttachment(AActor* InParentActor) const; }; struct FComponentAttachParams { EAttachmentRule AttachmentLocationRule = EAttachmentRule::KeepRelative; EAttachmentRule AttachmentRotationRule = EAttachmentRule::KeepRelative; EAttachmentRule AttachmentScaleRule = EAttachmentRule::KeepRelative; MOVIESCENETRACKS_API void ApplyAttach(USceneComponent* NewAttachParent, USceneComponent* ChildComponentToAttach, const FName& SocketName) const; }; struct FComponentDetachParams { EDetachmentRule DetachmentLocationRule = EDetachmentRule::KeepRelative; EDetachmentRule DetachmentRotationRule = EDetachmentRule::KeepRelative; EDetachmentRule DetachmentScaleRule = EDetachmentRule::KeepRelative; MOVIESCENETRACKS_API void ApplyDetach(USceneComponent* NewAttachParent, USceneComponent* ChildComponentToAttach, const FName& SocketName) const; }; struct FAttachmentComponent { FComponentAttachParamsDestination Destination; FComponentAttachParams AttachParams; FComponentDetachParams DetachParams; }; MOVIESCENETRACKS_API void ConvertOperationalProperty(const FIntermediate3DTransform& In, FEulerTransform& Out); MOVIESCENETRACKS_API void ConvertOperationalProperty(const FEulerTransform& In, FIntermediate3DTransform& Out); MOVIESCENETRACKS_API void ConvertOperationalProperty(const FIntermediate3DTransform& In, FTransform& Out); MOVIESCENETRACKS_API void ConvertOperationalProperty(const FTransform& In, FIntermediate3DTransform& Out); struct MOVIESCENETRACKS_API FMovieSceneTracksComponentTypes { ~FMovieSceneTracksComponentTypes(); TPropertyComponents<bool> Bool; TPropertyComponents<float> Float; TPropertyComponents<FTransform, FIntermediate3DTransform> Transform; TPropertyComponents<FEulerTransform, FIntermediate3DTransform> EulerTransform; TPropertyComponents<FIntermediate3DTransform> ComponentTransform; TComponentTypeID<FSourceFloatChannel> QuaternionRotationChannel[3]; TComponentTypeID<USceneComponent*> AttachParent; TComponentTypeID<FAttachmentComponent> AttachComponent; TComponentTypeID<FMovieSceneObjectBindingID> AttachParentBinding; struct { TCustomPropertyRegistration<bool> Bool; TCustomPropertyRegistration<float> Float; TCustomPropertyRegistration<FIntermediate3DTransform> ComponentTransform; } Accessors; TComponentTypeID<FLevelVisibilityComponentData> LevelVisibility; static void Destroy(); static FMovieSceneTracksComponentTypes* Get(); private: FMovieSceneTracksComponentTypes(); }; } // namespace MovieScene } // namespace UE
[ "ouczbs@qq.com" ]
ouczbs@qq.com
a632fe04b2915617edb5caaf023365496e6ff677
50252bf607c166b8d60415643c29945e98f7c1ab
/WalEngine/ThirdParty/include/glm/gtc/random.hpp
83b79ef55172e02f7b30a7bc40fb9b13b0bd0596
[ "MIT" ]
permissive
QuincyKing/WalEngine
8b2ea277f31a683b4dde94d628eeecfc44372682
8f30c4ad200615641777f17c5b0b1dbd15ba6e03
refs/heads/master
2022-03-15T23:54:19.796600
2019-10-28T03:55:49
2019-10-28T03:55:49
156,679,194
0
0
MIT
2019-05-09T15:48:08
2018-11-08T09:06:27
C++
UTF-8
C++
false
false
4,004
hpp
/////////////////////////////////////////////////////////////////////////////////// /// OpenGL Mathematics (glm.g-truc.net) /// /// Copyright (c) 2005 - 2014 G-Truc Creation (www.g-truc.net) /// 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. /// /// Restrictions: /// By making use of the Software for military purposes, you choose to make /// a Bunny unhappy. /// /// 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. /// /// @ref gtc_random /// @file glm/gtc/random.hpp /// @date 2011-09-18 / 2011-09-18 /// @author Christophe Riccio /// /// @see core (dependence) /// @see gtc_half_float (dependence) /// @see gtx_random (extended) /// /// @defgroup gtc_random GLM_GTC_random /// @ingroup gtc /// /// @brief Generate random number from various distribution methods. /// /// <glm/gtc/random.hpp> need to be included to use these functionalities. /////////////////////////////////////////////////////////////////////////////////// #pragma once // Dependency: #include "../vec2.hpp" #include "../vec3.hpp" #if(defined(GLM_MESSAGES) && !defined(GLM_EXT_INCLUDED)) # pragma message("GLM: GLM_GTC_random extension included") #endif namespace glm { /// @addtogroup gtc_random /// @{ /// Generate random numbers in the interval [Min, Max], according a linear distribution /// /// @param Min /// @param Max /// @tparam genType Value type. Currently supported: half (not recommanded), float or double scalars and vectors. /// @see gtc_random template <typename genTYpe> GLM_FUNC_DECL genTYpe linearRand( genTYpe Min, genTYpe Max); template <typename T, precision P, template <typename, precision> class vecType> GLM_FUNC_DECL vecType<T, P> linearRand( vecType<T, P> const & Min, vecType<T, P> const & Max); /// Generate random numbers in the interval [Min, Max], according a gaussian distribution /// /// @param Mean /// @param Deviation /// @see gtc_random template <typename genType> GLM_FUNC_DECL genType gaussRand( genType Mean, genType Deviation); /// Generate a random 2D vector which coordinates are regulary distributed on a circle of a given radius /// /// @param Radius /// @see gtc_random template <typename T> GLM_FUNC_DECL tvec2<T, defaultp> circularRand( T Radius); /// Generate a random 3D vector which coordinates are regulary distributed on a sphere of a given radius /// /// @param Radius /// @see gtc_random template <typename T> GLM_FUNC_DECL tvec3<T, defaultp> sphericalRand( T Radius); /// Generate a random 2D vector which coordinates are regulary distributed within the area of a disk of a given radius /// /// @param Radius /// @see gtc_random template <typename T> GLM_FUNC_DECL tvec2<T, defaultp> diskRand( T Radius); /// Generate a random 3D vector which coordinates are regulary distributed within the volume of a ball of a given radius /// /// @param Radius /// @see gtc_random template <typename T> GLM_FUNC_DECL tvec3<T, defaultp> ballRand( T Radius); /// @} }//namespace glm #include "random.inl"
[ "j88172365@gmail.com" ]
j88172365@gmail.com
9ff7df8a6dad9ca030acb33269483a05ca7cf60c
0d8bb1466cdba2c694d23eb52d764c8f86e90ef9
/richitemdelegate.h
a4ef241620d737aca11979c3b6e6ee70d2a6e128
[]
no_license
alexskull/blockpad
8fe08044928cd015158c660117854e89bdcc3dd3
ae69c13f5c7863d843e91fff7cace9db892f8bcd
refs/heads/master
2021-04-15T13:39:59.026798
2018-09-21T02:17:19
2018-09-21T02:17:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
896
h
#ifndef RICHITEMDELEGATE_H #define RICHITEMDELEGATE_H #include <QObject> #include <QItemDelegate> class RichItemDelegate : public QItemDelegate { Q_OBJECT public: RichItemDelegate(QObject *parent = 0); void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const; void setEditorData(QWidget *editor, const QModelIndex &index) const; static const Qt::ItemDataRole textWidthRole {(Qt::ItemDataRole)(Qt::UserRole)}; static QString nameWebSite(QString hyperlink); protected: void drawDisplay(QPainter *painter, const QStyleOptionViewItem &option, const QRect &rect, const QString &text) const; bool eventFilter(QObject *editor, QEvent *event); private: signals: void sigTabEnterInput(); }; #endif // RICHITEMDELEGATE_H
[ "Alex@e_mail" ]
Alex@e_mail
ef958fe98541a420d6a19380dbe448ca70ec284a
41499f73e807ac9fee5e2ff96a8894d08d967293
/FORKS/C++/vermont/tree/src/modules/packet/filter/IPHeaderFilter.h
086f0d84c0a43f81d2c374b8fcddff7327d54010
[ "GPL-2.0-only", "WTFPL", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
lordnynex/CLEANUP
c9f3058ec96674696339e7e936170a8645ddc09b
77e8e3cad25ce740fefb42859d9945cc482e009a
refs/heads/master
2021-01-10T07:35:08.071207
2016-04-10T22:02:57
2016-04-10T22:02:57
55,870,021
5
1
WTFPL
2023-03-20T11:55:51
2016-04-09T22:36:23
C++
UTF-8
C++
false
false
2,747
h
/* * Vermont Packet Filter * Copyright (C) 2009 Vermont Project * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ /* * PSAMP Reference Implementation * * IPHeaderFilter.h * * Filter by data from IP packet given by (offset, size, comparison, targetvalue) * * Author: Michael Drueing <michael@drueing.de> * */ /* this is a multi-purpose filter which filters 32-bit values from packets example usage: a) filter all packets with IP Protocol = 23 offset=9 (it's located at offset 9) size=1 (it's 1 byte) comparison=CMP_EQ targetvalue=23 ... you should get the idea */ #ifndef IP_HEADER_FILTER_H #define IP_HEADER_FILTER_H // required for htons() and htonl() #include <netinet/in.h> #include "common/msg.h" #include "PacketProcessor.h" // less than #define CMP_LT 0x00 // less or equal #define CMP_LE 0x01 // equal #define CMP_EQ 0x02 // greater or equal #define CMP_GE 0x03 // greater than #define CMP_GT 0x04 // not equal #define CMP_NE 0x05 // Bits are equal -> bitwise AND #define CMP_BIT 0x06 class IPHeaderFilter : public PacketProcessor { public: IPHeaderFilter(int header, int offset, int size, int comparison, int value) : m_header(header), m_offset(offset), m_size(size), m_comparison(comparison), m_value(value) { if(!(size==1 || size==2 || size==4)) { msg(MSG_ERROR, "invalid size of %d, only 1/2/4 supported", size); } // check for 2-byte or 4-byte words and convert them from network byte order if (size == 2) { m_value = htons((unsigned short)(m_value & 0xffff)); } else if (size == 4) { m_value = htonl((unsigned long)m_value); } } virtual bool processPacket(Packet *p); protected: bool compareValues(int srcvalue, int dstvalue); int getData(void *data, int size); /* which header: IP or transport */ int m_header; /* offset from the header above */ int m_offset; /* the size one wants to compare - 1, 2 or 4 bytes */ int m_size; /* the comparison operation, see the CMP_ defines above */ int m_comparison; /* the value to compare against */ int m_value; }; #endif
[ "lordnynex@gmail.com" ]
lordnynex@gmail.com
66b931de9964a2c11dc7c6f3d6567ae007fc639c
52e2964766efe35ede4c7d5dce0975a2dbcf5b65
/rzplayer/src/main/cpp/RzQueue.cpp
b7a30b410b642fa371b65856563bf1ee58e8daec
[]
no_license
xiaoxing1992/MusicJNI
7752686c23bbbed0d640f4916d0c5b2b9cf6e6db
f859c03b7e965fe86b818bf91e346889907b38d7
refs/heads/master
2020-06-14T00:32:35.107387
2019-07-03T16:05:15
2019-07-03T16:05:15
194,837,066
0
0
null
null
null
null
UTF-8
C++
false
false
1,570
cpp
// // Created by Administrator on 2019/7/2. // #include "RzQueue.h" RzQueue::RzQueue(RzPlayStatus *status) { this->rzPlayStatus = status; pthread_mutex_init(&mutexPacket, NULL); pthread_cond_init(&condPacket, NULL); } RzQueue::~RzQueue() { pthread_mutex_destroy(&mutexPacket); pthread_cond_destroy(&condPacket); } int RzQueue::putAVPacket(AVPacket *avPacket) { pthread_mutex_lock(&mutexPacket); queuePacket.push(avPacket); LOGE("放入一个AVPacket到队列中,个数为 == %d",queuePacket.size()); pthread_cond_signal(&condPacket); pthread_mutex_unlock(&mutexPacket); return 0; } int RzQueue::getAVPacket(AVPacket *packet) { pthread_mutex_lock(&mutexPacket); while (rzPlayStatus!=NULL&&!rzPlayStatus->exit){ if(queuePacket.size()>0){ AVPacket *avPacket = queuePacket.front(); if(av_packet_ref(packet,avPacket)==0){ queuePacket.pop(); } av_packet_free(&avPacket);//AVPacket中的第一个参数,就是引用,减到0才真正释放 av_free(avPacket); avPacket = NULL; LOGE("从队列中取出一个AVPacket,还剩下%d个",queuePacket.size()); break; }else { pthread_cond_wait(&condPacket,&mutexPacket); } } pthread_mutex_unlock(&mutexPacket); return 0; } int RzQueue::getQueueSize() { int size = 0; pthread_mutex_lock(&mutexPacket); size = queuePacket.size(); pthread_mutex_unlock(&mutexPacket); return size; }
[ "429487719@qq.com" ]
429487719@qq.com
ff945bfaabdb89a42d640e5614ca001dfd9b70ff
d9a634f3788a08e4dd02745e6764a9e56c4b2fd9
/src/qt/walletmodel.cpp
e314e04ea66f20e53027c9dfab8b5d8c39c27d56
[ "MIT" ]
permissive
hhhogannwo/MAGA
b7f19314cb32d6db064c3caa9324c3386a6c3f2a
cb81907eb1e5a87669a8244d8657041aa8456328
refs/heads/master
2022-03-04T03:07:28.167818
2022-02-17T02:01:27
2022-02-17T02:01:27
172,364,824
2
0
null
null
null
null
UTF-8
C++
false
false
20,063
cpp
// Copyright (c) 2011-2020 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include <config/maga-config.h> #endif #include <qt/walletmodel.h> #include <qt/addresstablemodel.h> #include <qt/clientmodel.h> #include <qt/guiconstants.h> #include <qt/guiutil.h> #include <qt/optionsmodel.h> #include <qt/paymentserver.h> #include <qt/recentrequeststablemodel.h> #include <qt/sendcoinsdialog.h> #include <qt/transactiontablemodel.h> #include <interfaces/handler.h> #include <interfaces/node.h> #include <key_io.h> #include <node/ui_interface.h> #include <psbt.h> #include <util/system.h> // for GetBoolArg #include <util/translation.h> #include <wallet/coincontrol.h> #include <wallet/wallet.h> // for CRecipient #include <stdint.h> #include <QDebug> #include <QMessageBox> #include <QSet> #include <QTimer> WalletModel::WalletModel(std::unique_ptr<interfaces::Wallet> wallet, ClientModel& client_model, const PlatformStyle *platformStyle, QObject *parent) : QObject(parent), m_wallet(std::move(wallet)), m_client_model(&client_model), m_node(client_model.node()), optionsModel(client_model.getOptionsModel()), addressTableModel(nullptr), transactionTableModel(nullptr), recentRequestsTableModel(nullptr), cachedEncryptionStatus(Unencrypted), timer(new QTimer(this)) { fHaveWatchOnly = m_wallet->haveWatchOnly(); addressTableModel = new AddressTableModel(this); transactionTableModel = new TransactionTableModel(platformStyle, this); recentRequestsTableModel = new RecentRequestsTableModel(this); subscribeToCoreSignals(); } WalletModel::~WalletModel() { unsubscribeFromCoreSignals(); } void WalletModel::startPollBalance() { // This timer will be fired repeatedly to update the balance connect(timer, &QTimer::timeout, this, &WalletModel::pollBalanceChanged); timer->start(MODEL_UPDATE_DELAY); } void WalletModel::setClientModel(ClientModel* client_model) { m_client_model = client_model; if (!m_client_model) timer->stop(); } void WalletModel::updateStatus() { EncryptionStatus newEncryptionStatus = getEncryptionStatus(); if(cachedEncryptionStatus != newEncryptionStatus) { Q_EMIT encryptionStatusChanged(); } } void WalletModel::pollBalanceChanged() { // Avoid recomputing wallet balances unless a TransactionChanged or // BlockTip notification was received. if (!fForceCheckBalanceChanged && m_cached_last_update_tip == getLastBlockProcessed()) return; // Try to get balances and return early if locks can't be acquired. This // avoids the GUI from getting stuck on periodical polls if the core is // holding the locks for a longer time - for example, during a wallet // rescan. interfaces::WalletBalances new_balances; uint256 block_hash; if (!m_wallet->tryGetBalances(new_balances, block_hash)) { return; } if (fForceCheckBalanceChanged || block_hash != m_cached_last_update_tip) { fForceCheckBalanceChanged = false; // Balance and number of transactions might have changed m_cached_last_update_tip = block_hash; checkBalanceChanged(new_balances); if(transactionTableModel) transactionTableModel->updateConfirmations(); } } void WalletModel::checkBalanceChanged(const interfaces::WalletBalances& new_balances) { if(new_balances.balanceChanged(m_cached_balances)) { m_cached_balances = new_balances; Q_EMIT balanceChanged(new_balances); } } void WalletModel::updateTransaction() { // Balance and number of transactions might have changed fForceCheckBalanceChanged = true; } void WalletModel::updateAddressBook(const QString &address, const QString &label, bool isMine, const QString &purpose, int status) { if(addressTableModel) addressTableModel->updateEntry(address, label, isMine, purpose, status); } void WalletModel::updateWatchOnlyFlag(bool fHaveWatchonly) { fHaveWatchOnly = fHaveWatchonly; Q_EMIT notifyWatchonlyChanged(fHaveWatchonly); } bool WalletModel::validateAddress(const QString &address) { return IsValidDestinationString(address.toStdString()); } WalletModel::SendCoinsReturn WalletModel::prepareTransaction(WalletModelTransaction &transaction, const CCoinControl& coinControl) { CAmount total = 0; bool fSubtractFeeFromAmount = false; QList<SendCoinsRecipient> recipients = transaction.getRecipients(); std::vector<CRecipient> vecSend; if(recipients.empty()) { return OK; } QSet<QString> setAddress; // Used to detect duplicates int nAddresses = 0; // Pre-check input data for validity for (const SendCoinsRecipient &rcp : recipients) { if (rcp.fSubtractFeeFromAmount) fSubtractFeeFromAmount = true; { // User-entered maga address / amount: if(!validateAddress(rcp.address)) { return InvalidAddress; } if(rcp.amount <= 0) { return InvalidAmount; } setAddress.insert(rcp.address); ++nAddresses; CScript scriptPubKey = GetScriptForDestination(DecodeDestination(rcp.address.toStdString())); CRecipient recipient = {scriptPubKey, rcp.amount, rcp.fSubtractFeeFromAmount}; vecSend.push_back(recipient); total += rcp.amount; } } if(setAddress.size() != nAddresses) { return DuplicateAddress; } CAmount nBalance = m_wallet->getAvailableBalance(coinControl); if(total > nBalance) { return AmountExceedsBalance; } { CAmount nFeeRequired = 0; int nChangePosRet = -1; bilingual_str error; auto& newTx = transaction.getWtx(); newTx = m_wallet->createTransaction(vecSend, coinControl, !wallet().privateKeysDisabled() /* sign */, nChangePosRet, nFeeRequired, error); transaction.setTransactionFee(nFeeRequired); if (fSubtractFeeFromAmount && newTx) transaction.reassignAmounts(nChangePosRet); if(!newTx) { if(!fSubtractFeeFromAmount && (total + nFeeRequired) > nBalance) { return SendCoinsReturn(AmountWithFeeExceedsBalance); } Q_EMIT message(tr("Send Coins"), QString::fromStdString(error.translated), CClientUIInterface::MSG_ERROR); return TransactionCreationFailed; } // Reject absurdly high fee. (This can never happen because the // wallet never creates transactions with fee greater than // m_default_max_tx_fee. This merely a belt-and-suspenders check). if (nFeeRequired > m_wallet->getDefaultMaxTxFee()) { return AbsurdFee; } } return SendCoinsReturn(OK); } WalletModel::SendCoinsReturn WalletModel::sendCoins(WalletModelTransaction &transaction) { QByteArray transaction_array; /* store serialized transaction */ { std::vector<std::pair<std::string, std::string>> vOrderForm; for (const SendCoinsRecipient &rcp : transaction.getRecipients()) { if (!rcp.message.isEmpty()) // Message from normal maga:URI (maga:123...?message=example) vOrderForm.emplace_back("Message", rcp.message.toStdString()); } auto& newTx = transaction.getWtx(); wallet().commitTransaction(newTx, {} /* mapValue */, std::move(vOrderForm)); CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << *newTx; transaction_array.append(&(ssTx[0]), ssTx.size()); } // Add addresses / update labels that we've sent to the address book, // and emit coinsSent signal for each recipient for (const SendCoinsRecipient &rcp : transaction.getRecipients()) { { std::string strAddress = rcp.address.toStdString(); CTxDestination dest = DecodeDestination(strAddress); std::string strLabel = rcp.label.toStdString(); { // Check if we have a new address or an updated label std::string name; if (!m_wallet->getAddress( dest, &name, /* is_mine= */ nullptr, /* purpose= */ nullptr)) { m_wallet->setAddressBook(dest, strLabel, "send"); } else if (name != strLabel) { m_wallet->setAddressBook(dest, strLabel, ""); // "" means don't change purpose } } } Q_EMIT coinsSent(this, rcp, transaction_array); } checkBalanceChanged(m_wallet->getBalances()); // update balance immediately, otherwise there could be a short noticeable delay until pollBalanceChanged hits return SendCoinsReturn(OK); } OptionsModel *WalletModel::getOptionsModel() { return optionsModel; } AddressTableModel *WalletModel::getAddressTableModel() { return addressTableModel; } TransactionTableModel *WalletModel::getTransactionTableModel() { return transactionTableModel; } RecentRequestsTableModel *WalletModel::getRecentRequestsTableModel() { return recentRequestsTableModel; } WalletModel::EncryptionStatus WalletModel::getEncryptionStatus() const { if(!m_wallet->isCrypted()) { return Unencrypted; } else if(m_wallet->isLocked()) { return Locked; } else { return Unlocked; } } bool WalletModel::setWalletEncrypted(bool encrypted, const SecureString &passphrase) { if (encrypted) { return m_wallet->encryptWallet(passphrase); } return false; } bool WalletModel::setWalletLocked(bool locked, const SecureString &passPhrase) { if(locked) { // Lock return m_wallet->lock(); } else { // Unlock return m_wallet->unlock(passPhrase); } } bool WalletModel::changePassphrase(const SecureString &oldPass, const SecureString &newPass) { m_wallet->lock(); // Make sure wallet is locked before attempting pass change return m_wallet->changeWalletPassphrase(oldPass, newPass); } // Handlers for core signals static void NotifyUnload(WalletModel* walletModel) { qDebug() << "NotifyUnload"; bool invoked = QMetaObject::invokeMethod(walletModel, "unload"); assert(invoked); } static void NotifyKeyStoreStatusChanged(WalletModel *walletmodel) { qDebug() << "NotifyKeyStoreStatusChanged"; bool invoked = QMetaObject::invokeMethod(walletmodel, "updateStatus", Qt::QueuedConnection); assert(invoked); } static void NotifyAddressBookChanged(WalletModel *walletmodel, const CTxDestination &address, const std::string &label, bool isMine, const std::string &purpose, ChangeType status) { QString strAddress = QString::fromStdString(EncodeDestination(address)); QString strLabel = QString::fromStdString(label); QString strPurpose = QString::fromStdString(purpose); qDebug() << "NotifyAddressBookChanged: " + strAddress + " " + strLabel + " isMine=" + QString::number(isMine) + " purpose=" + strPurpose + " status=" + QString::number(status); bool invoked = QMetaObject::invokeMethod(walletmodel, "updateAddressBook", Qt::QueuedConnection, Q_ARG(QString, strAddress), Q_ARG(QString, strLabel), Q_ARG(bool, isMine), Q_ARG(QString, strPurpose), Q_ARG(int, status)); assert(invoked); } static void NotifyTransactionChanged(WalletModel *walletmodel, const uint256 &hash, ChangeType status) { Q_UNUSED(hash); Q_UNUSED(status); bool invoked = QMetaObject::invokeMethod(walletmodel, "updateTransaction", Qt::QueuedConnection); assert(invoked); } static void ShowProgress(WalletModel *walletmodel, const std::string &title, int nProgress) { // emits signal "showProgress" bool invoked = QMetaObject::invokeMethod(walletmodel, "showProgress", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(title)), Q_ARG(int, nProgress)); assert(invoked); } static void NotifyWatchonlyChanged(WalletModel *walletmodel, bool fHaveWatchonly) { bool invoked = QMetaObject::invokeMethod(walletmodel, "updateWatchOnlyFlag", Qt::QueuedConnection, Q_ARG(bool, fHaveWatchonly)); assert(invoked); } static void NotifyCanGetAddressesChanged(WalletModel* walletmodel) { bool invoked = QMetaObject::invokeMethod(walletmodel, "canGetAddressesChanged"); assert(invoked); } void WalletModel::subscribeToCoreSignals() { // Connect signals to wallet m_handler_unload = m_wallet->handleUnload(std::bind(&NotifyUnload, this)); m_handler_status_changed = m_wallet->handleStatusChanged(std::bind(&NotifyKeyStoreStatusChanged, this)); m_handler_address_book_changed = m_wallet->handleAddressBookChanged(std::bind(NotifyAddressBookChanged, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4, std::placeholders::_5)); m_handler_transaction_changed = m_wallet->handleTransactionChanged(std::bind(NotifyTransactionChanged, this, std::placeholders::_1, std::placeholders::_2)); m_handler_show_progress = m_wallet->handleShowProgress(std::bind(ShowProgress, this, std::placeholders::_1, std::placeholders::_2)); m_handler_watch_only_changed = m_wallet->handleWatchOnlyChanged(std::bind(NotifyWatchonlyChanged, this, std::placeholders::_1)); m_handler_can_get_addrs_changed = m_wallet->handleCanGetAddressesChanged(std::bind(NotifyCanGetAddressesChanged, this)); } void WalletModel::unsubscribeFromCoreSignals() { // Disconnect signals from wallet m_handler_unload->disconnect(); m_handler_status_changed->disconnect(); m_handler_address_book_changed->disconnect(); m_handler_transaction_changed->disconnect(); m_handler_show_progress->disconnect(); m_handler_watch_only_changed->disconnect(); m_handler_can_get_addrs_changed->disconnect(); } // WalletModel::UnlockContext implementation WalletModel::UnlockContext WalletModel::requestUnlock() { bool was_locked = getEncryptionStatus() == Locked; if(was_locked) { // Request UI to unlock wallet Q_EMIT requireUnlock(); } // If wallet is still locked, unlock was failed or cancelled, mark context as invalid bool valid = getEncryptionStatus() != Locked; return UnlockContext(this, valid, was_locked); } WalletModel::UnlockContext::UnlockContext(WalletModel *_wallet, bool _valid, bool _relock): wallet(_wallet), valid(_valid), relock(_relock) { } WalletModel::UnlockContext::~UnlockContext() { if(valid && relock) { wallet->setWalletLocked(true); } } void WalletModel::UnlockContext::CopyFrom(UnlockContext&& rhs) { // Transfer context; old object no longer relocks wallet *this = rhs; rhs.relock = false; } void WalletModel::loadReceiveRequests(std::vector<std::string>& vReceiveRequests) { vReceiveRequests = m_wallet->getDestValues("rr"); // receive request } bool WalletModel::saveReceiveRequest(const std::string &sAddress, const int64_t nId, const std::string &sRequest) { CTxDestination dest = DecodeDestination(sAddress); std::stringstream ss; ss << nId; std::string key = "rr" + ss.str(); // "rr" prefix = "receive request" in destdata if (sRequest.empty()) return m_wallet->eraseDestData(dest, key); else return m_wallet->addDestData(dest, key, sRequest); } bool WalletModel::bumpFee(uint256 hash, uint256& new_hash) { CCoinControl coin_control; coin_control.m_signal_bip125_rbf = true; std::vector<bilingual_str> errors; CAmount old_fee; CAmount new_fee; CMutableTransaction mtx; if (!m_wallet->createBumpTransaction(hash, coin_control, errors, old_fee, new_fee, mtx)) { QMessageBox::critical(nullptr, tr("Fee bump error"), tr("Increasing transaction fee failed") + "<br />(" + (errors.size() ? QString::fromStdString(errors[0].translated) : "") +")"); return false; } const bool create_psbt = m_wallet->privateKeysDisabled(); // allow a user based fee verification QString questionString = create_psbt ? tr("Do you want to draft a transaction with fee increase?") : tr("Do you want to increase the fee?"); questionString.append("<br />"); questionString.append("<table style=\"text-align: left;\">"); questionString.append("<tr><td>"); questionString.append(tr("Current fee:")); questionString.append("</td><td>"); questionString.append(MAGAUnits::formatHtmlWithUnit(getOptionsModel()->getDisplayUnit(), old_fee)); questionString.append("</td></tr><tr><td>"); questionString.append(tr("Increase:")); questionString.append("</td><td>"); questionString.append(MAGAUnits::formatHtmlWithUnit(getOptionsModel()->getDisplayUnit(), new_fee - old_fee)); questionString.append("</td></tr><tr><td>"); questionString.append(tr("New fee:")); questionString.append("</td><td>"); questionString.append(MAGAUnits::formatHtmlWithUnit(getOptionsModel()->getDisplayUnit(), new_fee)); questionString.append("</td></tr></table>"); SendConfirmationDialog confirmationDialog(tr("Confirm fee bump"), questionString); confirmationDialog.exec(); QMessageBox::StandardButton retval = static_cast<QMessageBox::StandardButton>(confirmationDialog.result()); // cancel sign&broadcast if user doesn't want to bump the fee if (retval != QMessageBox::Yes) { return false; } WalletModel::UnlockContext ctx(requestUnlock()); if(!ctx.isValid()) { return false; } // Short-circuit if we are returning a bumped transaction PSBT to clipboard if (create_psbt) { PartiallySignedTransaction psbtx(mtx); bool complete = false; const TransactionError err = wallet().fillPSBT(SIGHASH_ALL, false /* sign */, true /* bip32derivs */, psbtx, complete, nullptr); if (err != TransactionError::OK || complete) { QMessageBox::critical(nullptr, tr("Fee bump error"), tr("Can't draft transaction.")); return false; } // Serialize the PSBT CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << psbtx; GUIUtil::setClipboard(EncodeBase64(ssTx.str()).c_str()); Q_EMIT message(tr("PSBT copied"), "Copied to clipboard", CClientUIInterface::MSG_INFORMATION); return true; } // sign bumped transaction if (!m_wallet->signBumpTransaction(mtx)) { QMessageBox::critical(nullptr, tr("Fee bump error"), tr("Can't sign transaction.")); return false; } // commit the bumped transaction if(!m_wallet->commitBumpTransaction(hash, std::move(mtx), errors, new_hash)) { QMessageBox::critical(nullptr, tr("Fee bump error"), tr("Could not commit transaction") + "<br />(" + QString::fromStdString(errors[0].translated)+")"); return false; } return true; } bool WalletModel::isWalletEnabled() { return !gArgs.GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET); } QString WalletModel::getWalletName() const { return QString::fromStdString(m_wallet->getWalletName()); } QString WalletModel::getDisplayName() const { const QString name = getWalletName(); return name.isEmpty() ? "["+tr("default wallet")+"]" : name; } bool WalletModel::isMultiwallet() { return m_node.walletClient().getWallets().size() > 1; } void WalletModel::refresh(bool pk_hash_only) { addressTableModel = new AddressTableModel(this, pk_hash_only); } uint256 WalletModel::getLastBlockProcessed() const { return m_client_model ? m_client_model->getBestBlockHash() : uint256{}; }
[ "noreply@github.com" ]
hhhogannwo.noreply@github.com
9cae6e26a487a1a06c748a4643b9b510926cf247
6ca6edd333b67263969f31ff1eecdbf09af1b4e0
/luogu_5019/road.cpp
b4f2120b9b5d153f7db35e46d50195c8a3f067e9
[ "BSD-3-Clause" ]
permissive
skyfackr/luogu_personal_cppcode
eea12a4770c052ec9b140d5186ee061ad787006f
b59af9839745d65091e6c01cddf53e5bb6fb274a
refs/heads/master
2020-04-01T04:49:14.296279
2019-08-02T08:48:18
2019-08-02T08:48:18
152,878,391
0
0
NOASSERTION
2018-10-13T14:18:41
2018-10-13T14:09:35
null
GB18030
C++
false
false
2,610
cpp
#include<bits/stdc++.h> #include<climits> #define regi register int #define ll long long #define maxn 100000 using namespace std; int origin[maxn+5],n; int tree[maxn<<2]; //bool zero[maxn+5]; class Tree//记录最小值,可进行递减操作 { private: int lazytag[maxn<<2]; inline ll ls(ll x) { return x<<1; } inline ll rs(ll x) { return x<<1|1; } inline void tagpush(ll tp,ll sum)//懒标记生成 { tree[tp]-=sum; lazytag[tp]+=sum; return ; } inline void push_down(ll tp)//懒传递 { int tag=lazytag[tp]; tagpush(ls(tp),tag); tagpush(rs(tp),tag); lazytag[tp]=0; return ; } inline void push_up(ll tp)//生成 { tree[tp]=min(tree[ls(tp)],tree[rs(tp)]); return ; } inline int getmid(int l,int r)//抱歉我懒 { return (l+r)>>1; } void build(int l,int r,ll tp)//递归建树 { if (l==r) { tree[tp]=origin[l]; // zero[l]=true; // if (origin[l]==0) zero[l]=true; return ; } ll mid=getmid(l,r); build(l,mid,ls(tp)); build(mid+1,r,rs(tp)); push_up(tp); return ; } inline void update(int mul,int mur,int l,int r,ll tp,int sum)//递归更新,仅支持减法 { if (mul<=l&&r<=mur) { tagpush(tp,sum); return ; } ll mid=getmid(l,r); push_down(tp); if (mul<=mid) update(mul,mur,l,mid,ls(tp),sum); if (mur>=mid+1) update(mul,mur,mid+1,r,rs(tp),sum); push_up(tp); return ; } inline int minget(int mul,int mur,int l,int r,ll tp)//目标最小值 { if (mul<=l&&r<=mur) { return tree[tp]; } ll mid=getmid(l,r); push_down(tp); int ans=INT_MAX; if (mul<=mid) ans=min(minget(mul,mur,l,mid,ls(tp)),ans); if (mur>=mid+1) ans=min(minget(mul,mur,mid+1,r,rs(tp)),ans); return ans; } public: inline void maketree() { build(1,n,1); return ; } inline void fix(int l,int r,int sum) { update(l,r,1,n,1,sum); return ; } inline int find(int l,int r) { return minget(l,r,1,n,1); } }; Tree treee; ll total,ans; int main() { // freopen("road.in","r",stdin); // freopen("road.out","w",stdout); //提交时一定要解除文件度入注释!!! ios::sync_with_stdio(0); cin.tie(0); cin>>n; for (regi i=1;i<=n;i++) cin>>origin[i],total+=origin[i]; treee.maketree(); int l=1,r=1; // zero[n+1]=true; while (total)//需要对拍 { if (!treee.find(l,l)) { while (!treee.find(l,l)&&l<=n) l++; } r=l+1; while (treee.find(r,r)&&r<=n) r++; r--; ll minn=treee.find(l,r); total-=minn*(r-l+1); treee.fix(l,r,minn); ans+=minn; } cout<<ans<<endl; return 0; }
[ "44115200+skyfackr@users.noreply.github.com" ]
44115200+skyfackr@users.noreply.github.com
93ecaef98ac4501fc89c11bf5c4722599f6b2530
ffded7739dfc6b14990ab90a80e33f4c087ea184
/Socket.h
95fb5a1a8b713b93cf46e5fdbca0b889015ed659
[]
no_license
jooney/muduotest
617b44b50b30539e94a8c08df70bd1f577b15ddc
51561ea225b80ea126c9a87ab6bc114caec70a23
refs/heads/master
2021-01-19T20:03:38.080673
2017-11-08T05:37:44
2017-11-08T05:37:44
88,480,317
0
0
null
null
null
null
UTF-8
C++
false
false
1,884
h
// Copyright 2010, Shuo Chen. All rights reserved. // http://code.google.com/p/muduo/ // // Use of this source code is governed by a BSD-style license // that can be found in the License file. // Author: Shuo Chen (chenshuo at chenshuo dot com) // // This is an internal header file, you should not include this. #ifndef MUDUO_NET_SOCKET_H #define MUDUO_NET_SOCKET_H #include <boost/noncopyable.hpp> // struct tcp_info is in <netinet/tcp.h> struct tcp_info; //namespace muduo //{ /// /// TCP networking. /// //namespace net //{ class InetAddress; /// /// Wrapper of socket file descriptor. /// /// It closes the sockfd when desctructs. /// It's thread safe, all operations are delegated to OS. class Socket : boost::noncopyable { public: explicit Socket(int sockfd) : sockfd_(sockfd) { } // Socket(Socket&&) // move constructor in C++11 ~Socket(); int fd() const { return sockfd_; } // return true if success. bool getTcpInfo(struct tcp_info*) const; bool getTcpInfoString(char* buf, int len) const; /// abort if address in use void bindAddress(const InetAddress& localaddr); /// abort if address in use void listen(); /// On success, returns a non-negative integer that is /// a descriptor for the accepted socket, which has been /// set to non-blocking and close-on-exec. *peeraddr is assigned. /// On error, -1 is returned, and *peeraddr is untouched. int accept(InetAddress* peeraddr); void shutdownWrite(); /// /// Enable/disable TCP_NODELAY (disable/enable Nagle's algorithm). /// void setTcpNoDelay(bool on); /// /// Enable/disable SO_REUSEADDR /// void setReuseAddr(bool on); /// /// Enable/disable SO_REUSEPORT /// void setReusePort(bool on); /// /// Enable/disable SO_KEEPALIVE /// void setKeepAlive(bool on); private: const int sockfd_; }; //} //} #endif // MUDUO_NET_SOCKET_H
[ "vikingpanzer@sina.com" ]
vikingpanzer@sina.com
f384c235e6dd4ade16dbeca408a5d0428e55c3d3
c16d6d14dbd7207d714890ef3132251b6f3dd238
/rootToLeafPathSum.cpp
460b31ddaca14506999921c11cbc8851ff7e1e0c
[]
no_license
DevangGarg/BinaryTreesAlgorithms
b39d36406453ab2797a98c76754d78352aed6309
7390e4e1a443dbe93238056e3fe9071999ae200a
refs/heads/master
2022-11-23T04:55:43.056180
2020-06-27T07:33:21
2020-06-27T07:33:21
275,322,293
0
0
null
null
null
null
UTF-8
C++
false
false
968
cpp
#include <iostream> using namespace std; #define bool int class Node { public: int data; Node *lc,*rc; Node(int data) { this -> data = data; this -> lc = NULL; this -> rc = NULL; } }; bool hasPathSum(Node *root,int sum) { if(root == NULL) { return (sum == 0); } else { bool ans = 0; int subSum = sum - root -> data; if(subSum == 0 && root -> lc == NULL && root -> rc == NULL) return 1; if(root -> lc) ans = ans || hasPathSum(root -> lc,subSum); if(root -> rc) ans = ans || hasPathSum(root -> rc,subSum); return ans; } } int main() { int sum = 21; Node *root = new Node(10); root -> lc = new Node(8); root -> rc = new Node(2); root -> lc -> lc = new Node(3); root -> lc -> rc = new Node(5); root -> rc -> lc = new Node(2); if(hasPathSum(root,sum)) cout << "There is a root to leaf path sum with sum = " << sum; else cout << "There is no such sum."; return 0; }
[ "noreply@github.com" ]
DevangGarg.noreply@github.com
4a7dcd8e8c945f2b9942c961a2d37727f255c0c1
45d73de830a7030222f5f5c3278bfd88ff63dd09
/src/qt/transactiondesc.cpp
be844c1240dd62068ab49239c5909ae3e8e7b7a0
[ "MIT" ]
permissive
realcaesar/skicoinBeta
36d84412e9c5ba62911abf27a417c0699de1ea51
a35cbfda4f70cfa41daa3e80fba95d737ef64449
refs/heads/master
2023-03-11T22:07:59.964255
2021-03-04T19:27:23
2021-03-04T19:27:23
309,057,031
0
0
null
null
null
null
UTF-8
C++
false
false
14,113
cpp
// Copyright (c) 2011-2015 The Bitcoin Core developers // Copyright (c) 2014-2020 The Dash Core developers // Copyright (c) 2014-2020 The Skicoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "transactiondesc.h" #include "skicoinunits.h" #include "guiutil.h" #include "paymentserver.h" #include "transactionrecord.h" #include "base58.h" #include "consensus/consensus.h" #include "validation.h" #include "script/script.h" #include "timedata.h" #include "util.h" #include "wallet/db.h" #include "wallet/wallet.h" #include "instantx.h" #include <stdint.h> #include <string> QString TransactionDesc::FormatTxStatus(const CWalletTx& wtx) { AssertLockHeld(cs_main); if (!CheckFinalTx(*wtx.tx)) { if (wtx.tx->nLockTime < LOCKTIME_THRESHOLD) return tr("Open for %n more block(s)", "", wtx.tx->nLockTime - chainActive.Height()); else return tr("Open until %1").arg(GUIUtil::dateTimeStr(wtx.tx->nLockTime)); } else { int nDepth = wtx.GetDepthInMainChain(); if (nDepth < 0) return tr("conflicted"); QString strTxStatus; bool fOffline = (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60) && (wtx.GetRequestCount() == 0); if (fOffline) { strTxStatus = tr("%1/offline").arg(nDepth); } else if (nDepth == 0) { strTxStatus = tr("0/unconfirmed, %1").arg((wtx.InMempool() ? tr("in memory pool") : tr("not in memory pool"))) + (wtx.isAbandoned() ? ", "+tr("abandoned") : ""); } else if (nDepth < 6) { strTxStatus = tr("%1/unconfirmed").arg(nDepth); } else { strTxStatus = tr("%1 confirmations").arg(nDepth); } if(!instantsend.HasTxLockRequest(wtx.GetHash())) return strTxStatus; // regular tx int nSignatures = instantsend.GetTransactionLockSignatures(wtx.GetHash()); int nSignaturesMax = CTxLockRequest(*wtx.tx).GetMaxSignatures(); // InstantSend strTxStatus += " ("; if(instantsend.IsLockedInstantSendTransaction(wtx.GetHash())) { strTxStatus += tr("verified via InstantSend"); } else if(!instantsend.IsTxLockCandidateTimedOut(wtx.GetHash())) { strTxStatus += tr("InstantSend verification in progress - %1 of %2 signatures").arg(nSignatures).arg(nSignaturesMax); } else { strTxStatus += tr("InstantSend verification failed"); } strTxStatus += ")"; return strTxStatus; } } QString TransactionDesc::toHTML(CWallet *wallet, CWalletTx &wtx, TransactionRecord *rec, int unit) { QString strHTML; LOCK2(cs_main, wallet->cs_wallet); strHTML.reserve(4000); strHTML += "<html><font face='verdana, arial, helvetica, sans-serif'>"; int64_t nTime = wtx.GetTxTime(); CAmount nCredit = wtx.GetCredit(ISMINE_ALL); CAmount nDebit = wtx.GetDebit(ISMINE_ALL); CAmount nNet = nCredit - nDebit; strHTML += "<b>" + tr("Status") + ":</b> " + FormatTxStatus(wtx); int nRequests = wtx.GetRequestCount(); if (nRequests != -1) { if (nRequests == 0) strHTML += tr(", has not been successfully broadcast yet"); else if (nRequests > 0) strHTML += tr(", broadcast through %n node(s)", "", nRequests); } strHTML += "<br>"; strHTML += "<b>" + tr("Date") + ":</b> " + (nTime ? GUIUtil::dateTimeStr(nTime) : "") + "<br>"; // // From // if (wtx.IsCoinBase()) { strHTML += "<b>" + tr("Source") + ":</b> " + tr("Generated") + "<br>"; } else if (wtx.mapValue.count("from") && !wtx.mapValue["from"].empty()) { // Online transaction strHTML += "<b>" + tr("From") + ":</b> " + GUIUtil::HtmlEscape(wtx.mapValue["from"]) + "<br>"; } else { // Offline transaction if (nNet > 0) { // Credit if (CSkicoinAddress(rec->address).IsValid()) { CTxDestination address = CSkicoinAddress(rec->address).Get(); if (wallet->mapAddressBook.count(address)) { strHTML += "<b>" + tr("From") + ":</b> " + tr("unknown") + "<br>"; strHTML += "<b>" + tr("To") + ":</b> "; strHTML += GUIUtil::HtmlEscape(rec->address); QString addressOwned = (::IsMine(*wallet, address) == ISMINE_SPENDABLE) ? tr("own address") : tr("watch-only"); if (!wallet->mapAddressBook[address].name.empty()) strHTML += " (" + addressOwned + ", " + tr("label") + ": " + GUIUtil::HtmlEscape(wallet->mapAddressBook[address].name) + ")"; else strHTML += " (" + addressOwned + ")"; strHTML += "<br>"; } } } } // // To // if (wtx.mapValue.count("to") && !wtx.mapValue["to"].empty()) { // Online transaction std::string strAddress = wtx.mapValue["to"]; strHTML += "<b>" + tr("To") + ":</b> "; CTxDestination dest = CSkicoinAddress(strAddress).Get(); if (wallet->mapAddressBook.count(dest) && !wallet->mapAddressBook[dest].name.empty()) strHTML += GUIUtil::HtmlEscape(wallet->mapAddressBook[dest].name) + " "; strHTML += GUIUtil::HtmlEscape(strAddress) + "<br>"; } // // Amount // if (wtx.IsCoinBase() && nCredit == 0) { // // Coinbase // CAmount nUnmatured = 0; BOOST_FOREACH(const CTxOut& txout, wtx.tx->vout) nUnmatured += wallet->GetCredit(txout, ISMINE_ALL); strHTML += "<b>" + tr("Credit") + ":</b> "; if (wtx.IsInMainChain()) strHTML += SkicoinUnits::formatHtmlWithUnit(unit, nUnmatured)+ " (" + tr("matures in %n more block(s)", "", wtx.GetBlocksToMaturity()) + ")"; else strHTML += "(" + tr("not accepted") + ")"; strHTML += "<br>"; } else if (nNet > 0) { // // Credit // strHTML += "<b>" + tr("Credit") + ":</b> " + SkicoinUnits::formatHtmlWithUnit(unit, nNet) + "<br>"; } else { isminetype fAllFromMe = ISMINE_SPENDABLE; BOOST_FOREACH(const CTxIn& txin, wtx.tx->vin) { isminetype mine = wallet->IsMine(txin); if(fAllFromMe > mine) fAllFromMe = mine; } isminetype fAllToMe = ISMINE_SPENDABLE; BOOST_FOREACH(const CTxOut& txout, wtx.tx->vout) { isminetype mine = wallet->IsMine(txout); if(fAllToMe > mine) fAllToMe = mine; } if (fAllFromMe) { if(fAllFromMe & ISMINE_WATCH_ONLY) strHTML += "<b>" + tr("From") + ":</b> " + tr("watch-only") + "<br>"; // // Debit // BOOST_FOREACH(const CTxOut& txout, wtx.tx->vout) { // Ignore change isminetype toSelf = wallet->IsMine(txout); if ((toSelf == ISMINE_SPENDABLE) && (fAllFromMe == ISMINE_SPENDABLE)) continue; if (!wtx.mapValue.count("to") || wtx.mapValue["to"].empty()) { // Offline transaction CTxDestination address; if (ExtractDestination(txout.scriptPubKey, address)) { strHTML += "<b>" + tr("To") + ":</b> "; if (wallet->mapAddressBook.count(address) && !wallet->mapAddressBook[address].name.empty()) strHTML += GUIUtil::HtmlEscape(wallet->mapAddressBook[address].name) + " "; strHTML += GUIUtil::HtmlEscape(CSkicoinAddress(address).ToString()); if(toSelf == ISMINE_SPENDABLE) strHTML += " (own address)"; else if(toSelf & ISMINE_WATCH_ONLY) strHTML += " (watch-only)"; strHTML += "<br>"; } } strHTML += "<b>" + tr("Debit") + ":</b> " + SkicoinUnits::formatHtmlWithUnit(unit, -txout.nValue) + "<br>"; if(toSelf) strHTML += "<b>" + tr("Credit") + ":</b> " + SkicoinUnits::formatHtmlWithUnit(unit, txout.nValue) + "<br>"; } if (fAllToMe) { // Payment to self CAmount nChange = wtx.GetChange(); CAmount nValue = nCredit - nChange; strHTML += "<b>" + tr("Total debit") + ":</b> " + SkicoinUnits::formatHtmlWithUnit(unit, -nValue) + "<br>"; strHTML += "<b>" + tr("Total credit") + ":</b> " + SkicoinUnits::formatHtmlWithUnit(unit, nValue) + "<br>"; } CAmount nTxFee = nDebit - wtx.tx->GetValueOut(); if (nTxFee > 0) strHTML += "<b>" + tr("Transaction fee") + ":</b> " + SkicoinUnits::formatHtmlWithUnit(unit, -nTxFee) + "<br>"; } else { // // Mixed debit transaction // BOOST_FOREACH(const CTxIn& txin, wtx.tx->vin) if (wallet->IsMine(txin)) strHTML += "<b>" + tr("Debit") + ":</b> " + SkicoinUnits::formatHtmlWithUnit(unit, -wallet->GetDebit(txin, ISMINE_ALL)) + "<br>"; BOOST_FOREACH(const CTxOut& txout, wtx.tx->vout) if (wallet->IsMine(txout)) strHTML += "<b>" + tr("Credit") + ":</b> " + SkicoinUnits::formatHtmlWithUnit(unit, wallet->GetCredit(txout, ISMINE_ALL)) + "<br>"; } } strHTML += "<b>" + tr("Net amount") + ":</b> " + SkicoinUnits::formatHtmlWithUnit(unit, nNet, true) + "<br>"; // // Message // if (wtx.mapValue.count("message") && !wtx.mapValue["message"].empty()) strHTML += "<br><b>" + tr("Message") + ":</b><br>" + GUIUtil::HtmlEscape(wtx.mapValue["message"], true) + "<br>"; if (wtx.mapValue.count("comment") && !wtx.mapValue["comment"].empty()) strHTML += "<br><b>" + tr("Comment") + ":</b><br>" + GUIUtil::HtmlEscape(wtx.mapValue["comment"], true) + "<br>"; strHTML += "<b>" + tr("Transaction ID") + ":</b> " + rec->getTxID() + "<br>"; strHTML += "<b>" + tr("Output index") + ":</b> " + QString::number(rec->getOutputIndex()) + "<br>"; strHTML += "<b>" + tr("Transaction total size") + ":</b> " + QString::number(wtx.tx->GetTotalSize()) + " bytes<br>"; // Message from normal skicoin:URI (skicoin:XyZ...?message=example) Q_FOREACH (const PAIRTYPE(std::string, std::string)& r, wtx.vOrderForm) if (r.first == "Message") strHTML += "<br><b>" + tr("Message") + ":</b><br>" + GUIUtil::HtmlEscape(r.second, true) + "<br>"; // // PaymentRequest info: // Q_FOREACH (const PAIRTYPE(std::string, std::string)& r, wtx.vOrderForm) { if (r.first == "PaymentRequest") { PaymentRequestPlus req; req.parse(QByteArray::fromRawData(r.second.data(), r.second.size())); QString merchant; if (req.getMerchant(PaymentServer::getCertStore(), merchant)) strHTML += "<b>" + tr("Merchant") + ":</b> " + GUIUtil::HtmlEscape(merchant) + "<br>"; } } if (wtx.IsCoinBase()) { quint32 numBlocksToMaturity = COINBASE_MATURITY + 1; strHTML += "<br>" + tr("Generated coins must mature %1 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to \"not accepted\" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.").arg(QString::number(numBlocksToMaturity)) + "<br>"; } // // Debug view // if (fDebug) { strHTML += "<hr><br>" + tr("Debug information") + "<br><br>"; BOOST_FOREACH(const CTxIn& txin, wtx.tx->vin) if(wallet->IsMine(txin)) strHTML += "<b>" + tr("Debit") + ":</b> " + SkicoinUnits::formatHtmlWithUnit(unit, -wallet->GetDebit(txin, ISMINE_ALL)) + "<br>"; BOOST_FOREACH(const CTxOut& txout, wtx.tx->vout) if(wallet->IsMine(txout)) strHTML += "<b>" + tr("Credit") + ":</b> " + SkicoinUnits::formatHtmlWithUnit(unit, wallet->GetCredit(txout, ISMINE_ALL)) + "<br>"; strHTML += "<br><b>" + tr("Transaction") + ":</b><br>"; strHTML += GUIUtil::HtmlEscape(wtx.tx->ToString(), true); strHTML += "<br><b>" + tr("Inputs") + ":</b>"; strHTML += "<ul>"; BOOST_FOREACH(const CTxIn& txin, wtx.tx->vin) { COutPoint prevout = txin.prevout; Coin prev; if(pcoinsTip->GetCoin(prevout, prev)) { { strHTML += "<li>"; const CTxOut &vout = prev.out; CTxDestination address; if (ExtractDestination(vout.scriptPubKey, address)) { if (wallet->mapAddressBook.count(address) && !wallet->mapAddressBook[address].name.empty()) strHTML += GUIUtil::HtmlEscape(wallet->mapAddressBook[address].name) + " "; strHTML += QString::fromStdString(CSkicoinAddress(address).ToString()); } strHTML = strHTML + " " + tr("Amount") + "=" + SkicoinUnits::formatHtmlWithUnit(unit, vout.nValue); strHTML = strHTML + " IsMine=" + (wallet->IsMine(vout) & ISMINE_SPENDABLE ? tr("true") : tr("false")); strHTML = strHTML + " IsWatchOnly=" + (wallet->IsMine(vout) & ISMINE_WATCH_ONLY ? tr("true") : tr("false")) + "</li>"; } } } strHTML += "</ul>"; } strHTML += "</font></html>"; return strHTML; }
[ "63470989+caesar-ski@users.noreply.github.com" ]
63470989+caesar-ski@users.noreply.github.com
221479d8aecbe52e4e5db3223fe532e8a201b6c8
7f2d4ffcfbd2437ab347adf0bf609acb2c222eb4
/cl/include/SDK/UIAutomationCore.h
1a0f2409db18f6ed1da7c56bd9e4eb6a8947334d
[]
no_license
mensong/CppScript
d46d5939e8ffad83897b4a28094351093752128c
622e00b49137caf95812735b5938a794537825dd
refs/heads/master
2023-06-08T11:16:47.076693
2023-05-28T04:35:25
2023-05-28T04:35:25
166,553,412
3
1
null
null
null
null
UTF-8
C++
false
false
142,859
h
/* this ALWAYS GENERATED file contains the definitions for the interfaces */ /* File created by MIDL compiler version 7.00.0555 */ /* Compiler settings for uiautomationcore.idl: Oicf, W1, Zp8, env=Win32 (32b run), target_arch=X86 7.00.0555 protocol : dce , ms_ext, c_ext, robust error checks: allocation ref bounds_check enum stub_data VC __declspec() decoration level: __declspec(uuid()), __declspec(selectany), __declspec(novtable) DECLSPEC_UUID(), MIDL_INTERFACE() */ /* @@MIDL_FILE_HEADING( ) */ #pragma warning( disable: 4049 ) /* more than 64k source lines */ /* verify that the <rpcndr.h> version is high enough to compile this file*/ #ifndef __REQUIRED_RPCNDR_H_VERSION__ #define __REQUIRED_RPCNDR_H_VERSION__ 475 #endif /* verify that the <rpcsal.h> version is high enough to compile this file*/ #ifndef __REQUIRED_RPCSAL_H_VERSION__ #define __REQUIRED_RPCSAL_H_VERSION__ 100 #endif #include "rpc.h" #include "rpcndr.h" #ifndef __RPCNDR_H_VERSION__ #error this stub requires an updated version of <rpcndr.h> #endif // __RPCNDR_H_VERSION__ #ifndef __uiautomationcore_h__ #define __uiautomationcore_h__ #if defined(_MSC_VER) && (_MSC_VER >= 1020) #pragma once #endif /* Forward Declarations */ #ifndef __IRawElementProviderSimple_FWD_DEFINED__ #define __IRawElementProviderSimple_FWD_DEFINED__ typedef interface IRawElementProviderSimple IRawElementProviderSimple; #endif /* __IRawElementProviderSimple_FWD_DEFINED__ */ #ifndef __IAccessibleEx_FWD_DEFINED__ #define __IAccessibleEx_FWD_DEFINED__ typedef interface IAccessibleEx IAccessibleEx; #endif /* __IAccessibleEx_FWD_DEFINED__ */ #ifndef __IRawElementProviderFragmentRoot_FWD_DEFINED__ #define __IRawElementProviderFragmentRoot_FWD_DEFINED__ typedef interface IRawElementProviderFragmentRoot IRawElementProviderFragmentRoot; #endif /* __IRawElementProviderFragmentRoot_FWD_DEFINED__ */ #ifndef __IRawElementProviderFragment_FWD_DEFINED__ #define __IRawElementProviderFragment_FWD_DEFINED__ typedef interface IRawElementProviderFragment IRawElementProviderFragment; #endif /* __IRawElementProviderFragment_FWD_DEFINED__ */ #ifndef __IRawElementProviderAdviseEvents_FWD_DEFINED__ #define __IRawElementProviderAdviseEvents_FWD_DEFINED__ typedef interface IRawElementProviderAdviseEvents IRawElementProviderAdviseEvents; #endif /* __IRawElementProviderAdviseEvents_FWD_DEFINED__ */ #ifndef __IRawElementProviderHwndOverride_FWD_DEFINED__ #define __IRawElementProviderHwndOverride_FWD_DEFINED__ typedef interface IRawElementProviderHwndOverride IRawElementProviderHwndOverride; #endif /* __IRawElementProviderHwndOverride_FWD_DEFINED__ */ #ifndef __IProxyProviderWinEventSink_FWD_DEFINED__ #define __IProxyProviderWinEventSink_FWD_DEFINED__ typedef interface IProxyProviderWinEventSink IProxyProviderWinEventSink; #endif /* __IProxyProviderWinEventSink_FWD_DEFINED__ */ #ifndef __IProxyProviderWinEventHandler_FWD_DEFINED__ #define __IProxyProviderWinEventHandler_FWD_DEFINED__ typedef interface IProxyProviderWinEventHandler IProxyProviderWinEventHandler; #endif /* __IProxyProviderWinEventHandler_FWD_DEFINED__ */ #ifndef __IDockProvider_FWD_DEFINED__ #define __IDockProvider_FWD_DEFINED__ typedef interface IDockProvider IDockProvider; #endif /* __IDockProvider_FWD_DEFINED__ */ #ifndef __IExpandCollapseProvider_FWD_DEFINED__ #define __IExpandCollapseProvider_FWD_DEFINED__ typedef interface IExpandCollapseProvider IExpandCollapseProvider; #endif /* __IExpandCollapseProvider_FWD_DEFINED__ */ #ifndef __IGridProvider_FWD_DEFINED__ #define __IGridProvider_FWD_DEFINED__ typedef interface IGridProvider IGridProvider; #endif /* __IGridProvider_FWD_DEFINED__ */ #ifndef __IGridItemProvider_FWD_DEFINED__ #define __IGridItemProvider_FWD_DEFINED__ typedef interface IGridItemProvider IGridItemProvider; #endif /* __IGridItemProvider_FWD_DEFINED__ */ #ifndef __IInvokeProvider_FWD_DEFINED__ #define __IInvokeProvider_FWD_DEFINED__ typedef interface IInvokeProvider IInvokeProvider; #endif /* __IInvokeProvider_FWD_DEFINED__ */ #ifndef __IMultipleViewProvider_FWD_DEFINED__ #define __IMultipleViewProvider_FWD_DEFINED__ typedef interface IMultipleViewProvider IMultipleViewProvider; #endif /* __IMultipleViewProvider_FWD_DEFINED__ */ #ifndef __IRangeValueProvider_FWD_DEFINED__ #define __IRangeValueProvider_FWD_DEFINED__ typedef interface IRangeValueProvider IRangeValueProvider; #endif /* __IRangeValueProvider_FWD_DEFINED__ */ #ifndef __IScrollItemProvider_FWD_DEFINED__ #define __IScrollItemProvider_FWD_DEFINED__ typedef interface IScrollItemProvider IScrollItemProvider; #endif /* __IScrollItemProvider_FWD_DEFINED__ */ #ifndef __ISelectionProvider_FWD_DEFINED__ #define __ISelectionProvider_FWD_DEFINED__ typedef interface ISelectionProvider ISelectionProvider; #endif /* __ISelectionProvider_FWD_DEFINED__ */ #ifndef __IScrollProvider_FWD_DEFINED__ #define __IScrollProvider_FWD_DEFINED__ typedef interface IScrollProvider IScrollProvider; #endif /* __IScrollProvider_FWD_DEFINED__ */ #ifndef __ISelectionItemProvider_FWD_DEFINED__ #define __ISelectionItemProvider_FWD_DEFINED__ typedef interface ISelectionItemProvider ISelectionItemProvider; #endif /* __ISelectionItemProvider_FWD_DEFINED__ */ #ifndef __ISynchronizedInputProvider_FWD_DEFINED__ #define __ISynchronizedInputProvider_FWD_DEFINED__ typedef interface ISynchronizedInputProvider ISynchronizedInputProvider; #endif /* __ISynchronizedInputProvider_FWD_DEFINED__ */ #ifndef __ITableProvider_FWD_DEFINED__ #define __ITableProvider_FWD_DEFINED__ typedef interface ITableProvider ITableProvider; #endif /* __ITableProvider_FWD_DEFINED__ */ #ifndef __ITableItemProvider_FWD_DEFINED__ #define __ITableItemProvider_FWD_DEFINED__ typedef interface ITableItemProvider ITableItemProvider; #endif /* __ITableItemProvider_FWD_DEFINED__ */ #ifndef __IToggleProvider_FWD_DEFINED__ #define __IToggleProvider_FWD_DEFINED__ typedef interface IToggleProvider IToggleProvider; #endif /* __IToggleProvider_FWD_DEFINED__ */ #ifndef __ITransformProvider_FWD_DEFINED__ #define __ITransformProvider_FWD_DEFINED__ typedef interface ITransformProvider ITransformProvider; #endif /* __ITransformProvider_FWD_DEFINED__ */ #ifndef __IValueProvider_FWD_DEFINED__ #define __IValueProvider_FWD_DEFINED__ typedef interface IValueProvider IValueProvider; #endif /* __IValueProvider_FWD_DEFINED__ */ #ifndef __IWindowProvider_FWD_DEFINED__ #define __IWindowProvider_FWD_DEFINED__ typedef interface IWindowProvider IWindowProvider; #endif /* __IWindowProvider_FWD_DEFINED__ */ #ifndef __ILegacyIAccessibleProvider_FWD_DEFINED__ #define __ILegacyIAccessibleProvider_FWD_DEFINED__ typedef interface ILegacyIAccessibleProvider ILegacyIAccessibleProvider; #endif /* __ILegacyIAccessibleProvider_FWD_DEFINED__ */ #ifndef __IItemContainerProvider_FWD_DEFINED__ #define __IItemContainerProvider_FWD_DEFINED__ typedef interface IItemContainerProvider IItemContainerProvider; #endif /* __IItemContainerProvider_FWD_DEFINED__ */ #ifndef __IVirtualizedItemProvider_FWD_DEFINED__ #define __IVirtualizedItemProvider_FWD_DEFINED__ typedef interface IVirtualizedItemProvider IVirtualizedItemProvider; #endif /* __IVirtualizedItemProvider_FWD_DEFINED__ */ #ifndef __ITextRangeProvider_FWD_DEFINED__ #define __ITextRangeProvider_FWD_DEFINED__ typedef interface ITextRangeProvider ITextRangeProvider; #endif /* __ITextRangeProvider_FWD_DEFINED__ */ #ifndef __ITextProvider_FWD_DEFINED__ #define __ITextProvider_FWD_DEFINED__ typedef interface ITextProvider ITextProvider; #endif /* __ITextProvider_FWD_DEFINED__ */ #ifndef __IUIAutomationPatternInstance_FWD_DEFINED__ #define __IUIAutomationPatternInstance_FWD_DEFINED__ typedef interface IUIAutomationPatternInstance IUIAutomationPatternInstance; #endif /* __IUIAutomationPatternInstance_FWD_DEFINED__ */ #ifndef __IUIAutomationPatternHandler_FWD_DEFINED__ #define __IUIAutomationPatternHandler_FWD_DEFINED__ typedef interface IUIAutomationPatternHandler IUIAutomationPatternHandler; #endif /* __IUIAutomationPatternHandler_FWD_DEFINED__ */ #ifndef __IUIAutomationRegistrar_FWD_DEFINED__ #define __IUIAutomationRegistrar_FWD_DEFINED__ typedef interface IUIAutomationRegistrar IUIAutomationRegistrar; #endif /* __IUIAutomationRegistrar_FWD_DEFINED__ */ #ifndef __CUIAutomationRegistrar_FWD_DEFINED__ #define __CUIAutomationRegistrar_FWD_DEFINED__ #ifdef __cplusplus typedef class CUIAutomationRegistrar CUIAutomationRegistrar; #else typedef struct CUIAutomationRegistrar CUIAutomationRegistrar; #endif /* __cplusplus */ #endif /* __CUIAutomationRegistrar_FWD_DEFINED__ */ /* header files for imported files */ #include "oaidl.h" #include "oleacc.h" #ifdef __cplusplus extern "C"{ #endif /* interface __MIDL_itf_uiautomationcore_0000_0000 */ /* [local] */ // ------------------------------------------------------------- // UIAutomationCore.H // // UIAutomation interface definitions and related types and enums // (Generated from UIAutomationCore.idl) // // Copyright (c) Microsoft Corporation. All rights reserved. // ------------------------------------------------------------- enum NavigateDirection { NavigateDirection_Parent = 0, NavigateDirection_NextSibling = 1, NavigateDirection_PreviousSibling = 2, NavigateDirection_FirstChild = 3, NavigateDirection_LastChild = 4 } ; enum ProviderOptions { ProviderOptions_ClientSideProvider = 0x1, ProviderOptions_ServerSideProvider = 0x2, ProviderOptions_NonClientAreaProvider = 0x4, ProviderOptions_OverrideProvider = 0x8, ProviderOptions_ProviderOwnsSetFocus = 0x10, ProviderOptions_UseComThreading = 0x20 } ; DEFINE_ENUM_FLAG_OPERATORS(ProviderOptions) enum StructureChangeType { StructureChangeType_ChildAdded = 0, StructureChangeType_ChildRemoved = ( StructureChangeType_ChildAdded + 1 ) , StructureChangeType_ChildrenInvalidated = ( StructureChangeType_ChildRemoved + 1 ) , StructureChangeType_ChildrenBulkAdded = ( StructureChangeType_ChildrenInvalidated + 1 ) , StructureChangeType_ChildrenBulkRemoved = ( StructureChangeType_ChildrenBulkAdded + 1 ) , StructureChangeType_ChildrenReordered = ( StructureChangeType_ChildrenBulkRemoved + 1 ) } ; enum OrientationType { OrientationType_None = 0, OrientationType_Horizontal = 1, OrientationType_Vertical = 2 } ; enum DockPosition { DockPosition_Top = 0, DockPosition_Left = 1, DockPosition_Bottom = 2, DockPosition_Right = 3, DockPosition_Fill = 4, DockPosition_None = 5 } ; enum ExpandCollapseState { ExpandCollapseState_Collapsed = 0, ExpandCollapseState_Expanded = 1, ExpandCollapseState_PartiallyExpanded = 2, ExpandCollapseState_LeafNode = 3 } ; enum ScrollAmount { ScrollAmount_LargeDecrement = 0, ScrollAmount_SmallDecrement = 1, ScrollAmount_NoAmount = 2, ScrollAmount_LargeIncrement = 3, ScrollAmount_SmallIncrement = 4 } ; enum RowOrColumnMajor { RowOrColumnMajor_RowMajor = 0, RowOrColumnMajor_ColumnMajor = 1, RowOrColumnMajor_Indeterminate = 2 } ; enum ToggleState { ToggleState_Off = 0, ToggleState_On = 1, ToggleState_Indeterminate = 2 } ; enum WindowVisualState { WindowVisualState_Normal = 0, WindowVisualState_Maximized = 1, WindowVisualState_Minimized = 2 } ; enum SynchronizedInputType { SynchronizedInputType_KeyUp = 0x1, SynchronizedInputType_KeyDown = 0x2, SynchronizedInputType_LeftMouseUp = 0x4, SynchronizedInputType_LeftMouseDown = 0x8, SynchronizedInputType_RightMouseUp = 0x10, SynchronizedInputType_RightMouseDown = 0x20 } ; DEFINE_ENUM_FLAG_OPERATORS(SynchronizedInputType) enum WindowInteractionState { WindowInteractionState_Running = 0, WindowInteractionState_Closing = 1, WindowInteractionState_ReadyForUserInteraction = 2, WindowInteractionState_BlockedByModalWindow = 3, WindowInteractionState_NotResponding = 4 } ; enum TextUnit { TextUnit_Character = 0, TextUnit_Format = 1, TextUnit_Word = 2, TextUnit_Line = 3, TextUnit_Paragraph = 4, TextUnit_Page = 5, TextUnit_Document = 6 } ; enum TextPatternRangeEndpoint { TextPatternRangeEndpoint_Start = 0, TextPatternRangeEndpoint_End = 1 } ; enum SupportedTextSelection { SupportedTextSelection_None = 0, SupportedTextSelection_Single = 1, SupportedTextSelection_Multiple = 2 } ; enum AnimationStyle { AnimationStyle_None = 0, AnimationStyle_LasVegasLights = 1, AnimationStyle_BlinkingBackground = 2, AnimationStyle_SparkleText = 3, AnimationStyle_MarchingBlackAnts = 4, AnimationStyle_MarchingRedAnts = 5, AnimationStyle_Shimmer = 6, AnimationStyle_Other = -1 } ; enum BulletStyle { BulletStyle_None = 0, BulletStyle_HollowRoundBullet = 1, BulletStyle_FilledRoundBullet = 2, BulletStyle_HollowSquareBullet = 3, BulletStyle_FilledSquareBullet = 4, BulletStyle_DashBullet = 5, BulletStyle_Other = -1 } ; enum CapStyle { CapStyle_None = 0, CapStyle_SmallCap = 1, CapStyle_AllCap = 2, CapStyle_AllPetiteCaps = 3, CapStyle_PetiteCaps = 4, CapStyle_Unicase = 5, CapStyle_Titling = 6, CapStyle_Other = -1 } ; enum FlowDirections { FlowDirections_Default = 0, FlowDirections_RightToLeft = 1, FlowDirections_BottomToTop = 2, FlowDirections_Vertical = 4 } ; enum HorizontalTextAlignment { HorizontalTextAlignment_Left = 0, HorizontalTextAlignment_Centered = 1, HorizontalTextAlignment_Right = 2, HorizontalTextAlignment_Justified = 3 } ; enum OutlineStyles { OutlineStyles_None = 0, OutlineStyles_Outline = 1, OutlineStyles_Shadow = 2, OutlineStyles_Engraved = 4, OutlineStyles_Embossed = 8 } ; enum TextDecorationLineStyle { TextDecorationLineStyle_None = 0, TextDecorationLineStyle_Single = 1, TextDecorationLineStyle_WordsOnly = 2, TextDecorationLineStyle_Double = 3, TextDecorationLineStyle_Dot = 4, TextDecorationLineStyle_Dash = 5, TextDecorationLineStyle_DashDot = 6, TextDecorationLineStyle_DashDotDot = 7, TextDecorationLineStyle_Wavy = 8, TextDecorationLineStyle_ThickSingle = 9, TextDecorationLineStyle_DoubleWavy = 11, TextDecorationLineStyle_ThickWavy = 12, TextDecorationLineStyle_LongDash = 13, TextDecorationLineStyle_ThickDash = 14, TextDecorationLineStyle_ThickDashDot = 15, TextDecorationLineStyle_ThickDashDotDot = 16, TextDecorationLineStyle_ThickDot = 17, TextDecorationLineStyle_ThickLongDash = 18, TextDecorationLineStyle_Other = -1 } ; typedef int PROPERTYID; typedef int PATTERNID; typedef int EVENTID; typedef int TEXTATTRIBUTEID; typedef int CONTROLTYPEID; struct UiaRect { double left; double top; double width; double height; } ; struct UiaPoint { double x; double y; } ; extern RPC_IF_HANDLE __MIDL_itf_uiautomationcore_0000_0000_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_uiautomationcore_0000_0000_v0_0_s_ifspec; #ifndef __UIA_LIBRARY_DEFINED__ #define __UIA_LIBRARY_DEFINED__ /* library UIA */ /* [hidden][version][lcid][uuid] */ enum UIAutomationType { UIAutomationType_Int = 0x1, UIAutomationType_Bool = 0x2, UIAutomationType_String = 0x3, UIAutomationType_Double = 0x4, UIAutomationType_Point = 0x5, UIAutomationType_Rect = 0x6, UIAutomationType_Element = 0x7, UIAutomationType_Array = 0x10000, UIAutomationType_Out = 0x20000, UIAutomationType_IntArray = ( UIAutomationType_Int | UIAutomationType_Array ) , UIAutomationType_BoolArray = ( UIAutomationType_Bool | UIAutomationType_Array ) , UIAutomationType_StringArray = ( UIAutomationType_String | UIAutomationType_Array ) , UIAutomationType_DoubleArray = ( UIAutomationType_Double | UIAutomationType_Array ) , UIAutomationType_PointArray = ( UIAutomationType_Point | UIAutomationType_Array ) , UIAutomationType_RectArray = ( UIAutomationType_Rect | UIAutomationType_Array ) , UIAutomationType_ElementArray = ( UIAutomationType_Element | UIAutomationType_Array ) , UIAutomationType_OutInt = ( UIAutomationType_Int | UIAutomationType_Out ) , UIAutomationType_OutBool = ( UIAutomationType_Bool | UIAutomationType_Out ) , UIAutomationType_OutString = ( UIAutomationType_String | UIAutomationType_Out ) , UIAutomationType_OutDouble = ( UIAutomationType_Double | UIAutomationType_Out ) , UIAutomationType_OutPoint = ( UIAutomationType_Point | UIAutomationType_Out ) , UIAutomationType_OutRect = ( UIAutomationType_Rect | UIAutomationType_Out ) , UIAutomationType_OutElement = ( UIAutomationType_Element | UIAutomationType_Out ) , UIAutomationType_OutIntArray = ( ( UIAutomationType_Int | UIAutomationType_Array ) | UIAutomationType_Out ) , UIAutomationType_OutBoolArray = ( ( UIAutomationType_Bool | UIAutomationType_Array ) | UIAutomationType_Out ) , UIAutomationType_OutStringArray = ( ( UIAutomationType_String | UIAutomationType_Array ) | UIAutomationType_Out ) , UIAutomationType_OutDoubleArray = ( ( UIAutomationType_Double | UIAutomationType_Array ) | UIAutomationType_Out ) , UIAutomationType_OutPointArray = ( ( UIAutomationType_Point | UIAutomationType_Array ) | UIAutomationType_Out ) , UIAutomationType_OutRectArray = ( ( UIAutomationType_Rect | UIAutomationType_Array ) | UIAutomationType_Out ) , UIAutomationType_OutElementArray = ( ( UIAutomationType_Element | UIAutomationType_Array ) | UIAutomationType_Out ) } ; DEFINE_ENUM_FLAG_OPERATORS(UIAutomationType) struct UIAutomationParameter { enum UIAutomationType type; void *pData; } ; struct UIAutomationPropertyInfo { GUID guid; LPCWSTR pProgrammaticName; enum UIAutomationType type; } ; struct UIAutomationEventInfo { GUID guid; LPCWSTR pProgrammaticName; } ; struct UIAutomationMethodInfo { LPCWSTR pProgrammaticName; BOOL doSetFocus; UINT cInParameters; UINT cOutParameters; enum UIAutomationType *pParameterTypes; LPCWSTR *pParameterNames; } ; struct UIAutomationPatternInfo { GUID guid; LPCWSTR pProgrammaticName; GUID providerInterfaceId; GUID clientInterfaceId; UINT cProperties; struct UIAutomationPropertyInfo *pProperties; UINT cMethods; struct UIAutomationMethodInfo *pMethods; UINT cEvents; struct UIAutomationEventInfo *pEvents; IUIAutomationPatternHandler *pPatternHandler; } ; EXTERN_C const IID LIBID_UIA; #ifndef __UIA_OtherConstants_MODULE_DEFINED__ #define __UIA_OtherConstants_MODULE_DEFINED__ /* module UIA_OtherConstants */ /* [dllname] */ const double UIA_ScrollPatternNoScroll = -1; #endif /* __UIA_OtherConstants_MODULE_DEFINED__ */ #ifndef __IRawElementProviderSimple_INTERFACE_DEFINED__ #define __IRawElementProviderSimple_INTERFACE_DEFINED__ /* interface IRawElementProviderSimple */ /* [unique][uuid][object] */ EXTERN_C const IID IID_IRawElementProviderSimple; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("d6dd68d1-86fd-4332-8666-9abedea2d24c") IRawElementProviderSimple : public IUnknown { public: virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_ProviderOptions( /* [retval][out] */ __RPC__out enum ProviderOptions *pRetVal) = 0; virtual HRESULT STDMETHODCALLTYPE GetPatternProvider( /* [in] */ PATTERNID patternId, /* [retval][out] */ __RPC__deref_out_opt IUnknown **pRetVal) = 0; virtual HRESULT STDMETHODCALLTYPE GetPropertyValue( /* [in] */ PROPERTYID propertyId, /* [retval][out] */ __RPC__out VARIANT *pRetVal) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_HostRawElementProvider( /* [retval][out] */ __RPC__deref_out_opt IRawElementProviderSimple **pRetVal) = 0; }; #else /* C style interface */ typedef struct IRawElementProviderSimpleVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in IRawElementProviderSimple * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ __RPC__deref_out void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in IRawElementProviderSimple * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in IRawElementProviderSimple * This); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_ProviderOptions )( __RPC__in IRawElementProviderSimple * This, /* [retval][out] */ __RPC__out enum ProviderOptions *pRetVal); HRESULT ( STDMETHODCALLTYPE *GetPatternProvider )( __RPC__in IRawElementProviderSimple * This, /* [in] */ PATTERNID patternId, /* [retval][out] */ __RPC__deref_out_opt IUnknown **pRetVal); HRESULT ( STDMETHODCALLTYPE *GetPropertyValue )( __RPC__in IRawElementProviderSimple * This, /* [in] */ PROPERTYID propertyId, /* [retval][out] */ __RPC__out VARIANT *pRetVal); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_HostRawElementProvider )( __RPC__in IRawElementProviderSimple * This, /* [retval][out] */ __RPC__deref_out_opt IRawElementProviderSimple **pRetVal); END_INTERFACE } IRawElementProviderSimpleVtbl; interface IRawElementProviderSimple { CONST_VTBL struct IRawElementProviderSimpleVtbl *lpVtbl; }; #ifdef COBJMACROS #define IRawElementProviderSimple_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IRawElementProviderSimple_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IRawElementProviderSimple_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IRawElementProviderSimple_get_ProviderOptions(This,pRetVal) \ ( (This)->lpVtbl -> get_ProviderOptions(This,pRetVal) ) #define IRawElementProviderSimple_GetPatternProvider(This,patternId,pRetVal) \ ( (This)->lpVtbl -> GetPatternProvider(This,patternId,pRetVal) ) #define IRawElementProviderSimple_GetPropertyValue(This,propertyId,pRetVal) \ ( (This)->lpVtbl -> GetPropertyValue(This,propertyId,pRetVal) ) #define IRawElementProviderSimple_get_HostRawElementProvider(This,pRetVal) \ ( (This)->lpVtbl -> get_HostRawElementProvider(This,pRetVal) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IRawElementProviderSimple_INTERFACE_DEFINED__ */ #ifndef __IAccessibleEx_INTERFACE_DEFINED__ #define __IAccessibleEx_INTERFACE_DEFINED__ /* interface IAccessibleEx */ /* [oleautomation][unique][uuid][object] */ EXTERN_C const IID IID_IAccessibleEx; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("f8b80ada-2c44-48d0-89be-5ff23c9cd875") IAccessibleEx : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE GetObjectForChild( /* [in] */ long idChild, /* [retval][out] */ __RPC__deref_out_opt IAccessibleEx **pRetVal) = 0; virtual HRESULT STDMETHODCALLTYPE GetIAccessiblePair( /* [out] */ __RPC__deref_out_opt IAccessible **ppAcc, /* [out] */ __RPC__out long *pidChild) = 0; virtual HRESULT STDMETHODCALLTYPE GetRuntimeId( /* [retval][out] */ __RPC__deref_out_opt SAFEARRAY * *pRetVal) = 0; virtual HRESULT STDMETHODCALLTYPE ConvertReturnedElement( /* [in] */ __RPC__in_opt IRawElementProviderSimple *pIn, /* [out] */ __RPC__deref_out_opt IAccessibleEx **ppRetValOut) = 0; }; #else /* C style interface */ typedef struct IAccessibleExVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in IAccessibleEx * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ __RPC__deref_out void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in IAccessibleEx * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in IAccessibleEx * This); HRESULT ( STDMETHODCALLTYPE *GetObjectForChild )( __RPC__in IAccessibleEx * This, /* [in] */ long idChild, /* [retval][out] */ __RPC__deref_out_opt IAccessibleEx **pRetVal); HRESULT ( STDMETHODCALLTYPE *GetIAccessiblePair )( __RPC__in IAccessibleEx * This, /* [out] */ __RPC__deref_out_opt IAccessible **ppAcc, /* [out] */ __RPC__out long *pidChild); HRESULT ( STDMETHODCALLTYPE *GetRuntimeId )( __RPC__in IAccessibleEx * This, /* [retval][out] */ __RPC__deref_out_opt SAFEARRAY * *pRetVal); HRESULT ( STDMETHODCALLTYPE *ConvertReturnedElement )( __RPC__in IAccessibleEx * This, /* [in] */ __RPC__in_opt IRawElementProviderSimple *pIn, /* [out] */ __RPC__deref_out_opt IAccessibleEx **ppRetValOut); END_INTERFACE } IAccessibleExVtbl; interface IAccessibleEx { CONST_VTBL struct IAccessibleExVtbl *lpVtbl; }; #ifdef COBJMACROS #define IAccessibleEx_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IAccessibleEx_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IAccessibleEx_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IAccessibleEx_GetObjectForChild(This,idChild,pRetVal) \ ( (This)->lpVtbl -> GetObjectForChild(This,idChild,pRetVal) ) #define IAccessibleEx_GetIAccessiblePair(This,ppAcc,pidChild) \ ( (This)->lpVtbl -> GetIAccessiblePair(This,ppAcc,pidChild) ) #define IAccessibleEx_GetRuntimeId(This,pRetVal) \ ( (This)->lpVtbl -> GetRuntimeId(This,pRetVal) ) #define IAccessibleEx_ConvertReturnedElement(This,pIn,ppRetValOut) \ ( (This)->lpVtbl -> ConvertReturnedElement(This,pIn,ppRetValOut) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IAccessibleEx_INTERFACE_DEFINED__ */ #ifndef __IRawElementProviderFragmentRoot_INTERFACE_DEFINED__ #define __IRawElementProviderFragmentRoot_INTERFACE_DEFINED__ /* interface IRawElementProviderFragmentRoot */ /* [unique][uuid][object] */ EXTERN_C const IID IID_IRawElementProviderFragmentRoot; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("620ce2a5-ab8f-40a9-86cb-de3c75599b58") IRawElementProviderFragmentRoot : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE ElementProviderFromPoint( /* [in] */ double x, /* [in] */ double y, /* [retval][out] */ __RPC__deref_out_opt IRawElementProviderFragment **pRetVal) = 0; virtual HRESULT STDMETHODCALLTYPE GetFocus( /* [retval][out] */ __RPC__deref_out_opt IRawElementProviderFragment **pRetVal) = 0; }; #else /* C style interface */ typedef struct IRawElementProviderFragmentRootVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in IRawElementProviderFragmentRoot * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ __RPC__deref_out void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in IRawElementProviderFragmentRoot * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in IRawElementProviderFragmentRoot * This); HRESULT ( STDMETHODCALLTYPE *ElementProviderFromPoint )( __RPC__in IRawElementProviderFragmentRoot * This, /* [in] */ double x, /* [in] */ double y, /* [retval][out] */ __RPC__deref_out_opt IRawElementProviderFragment **pRetVal); HRESULT ( STDMETHODCALLTYPE *GetFocus )( __RPC__in IRawElementProviderFragmentRoot * This, /* [retval][out] */ __RPC__deref_out_opt IRawElementProviderFragment **pRetVal); END_INTERFACE } IRawElementProviderFragmentRootVtbl; interface IRawElementProviderFragmentRoot { CONST_VTBL struct IRawElementProviderFragmentRootVtbl *lpVtbl; }; #ifdef COBJMACROS #define IRawElementProviderFragmentRoot_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IRawElementProviderFragmentRoot_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IRawElementProviderFragmentRoot_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IRawElementProviderFragmentRoot_ElementProviderFromPoint(This,x,y,pRetVal) \ ( (This)->lpVtbl -> ElementProviderFromPoint(This,x,y,pRetVal) ) #define IRawElementProviderFragmentRoot_GetFocus(This,pRetVal) \ ( (This)->lpVtbl -> GetFocus(This,pRetVal) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IRawElementProviderFragmentRoot_INTERFACE_DEFINED__ */ #ifndef __IRawElementProviderFragment_INTERFACE_DEFINED__ #define __IRawElementProviderFragment_INTERFACE_DEFINED__ /* interface IRawElementProviderFragment */ /* [unique][uuid][object] */ EXTERN_C const IID IID_IRawElementProviderFragment; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("f7063da8-8359-439c-9297-bbc5299a7d87") IRawElementProviderFragment : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE Navigate( /* [in] */ enum NavigateDirection direction, /* [retval][out] */ __RPC__deref_out_opt IRawElementProviderFragment **pRetVal) = 0; virtual HRESULT STDMETHODCALLTYPE GetRuntimeId( /* [retval][out] */ __RPC__deref_out_opt SAFEARRAY * *pRetVal) = 0; virtual HRESULT STDMETHODCALLTYPE get_BoundingRectangle( /* [retval][out] */ __RPC__out struct UiaRect *pRetVal) = 0; virtual HRESULT STDMETHODCALLTYPE GetEmbeddedFragmentRoots( /* [retval][out] */ __RPC__deref_out_opt SAFEARRAY * *pRetVal) = 0; virtual HRESULT STDMETHODCALLTYPE SetFocus( void) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_FragmentRoot( /* [retval][out] */ __RPC__deref_out_opt IRawElementProviderFragmentRoot **pRetVal) = 0; }; #else /* C style interface */ typedef struct IRawElementProviderFragmentVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in IRawElementProviderFragment * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ __RPC__deref_out void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in IRawElementProviderFragment * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in IRawElementProviderFragment * This); HRESULT ( STDMETHODCALLTYPE *Navigate )( __RPC__in IRawElementProviderFragment * This, /* [in] */ enum NavigateDirection direction, /* [retval][out] */ __RPC__deref_out_opt IRawElementProviderFragment **pRetVal); HRESULT ( STDMETHODCALLTYPE *GetRuntimeId )( __RPC__in IRawElementProviderFragment * This, /* [retval][out] */ __RPC__deref_out_opt SAFEARRAY * *pRetVal); HRESULT ( STDMETHODCALLTYPE *get_BoundingRectangle )( __RPC__in IRawElementProviderFragment * This, /* [retval][out] */ __RPC__out struct UiaRect *pRetVal); HRESULT ( STDMETHODCALLTYPE *GetEmbeddedFragmentRoots )( __RPC__in IRawElementProviderFragment * This, /* [retval][out] */ __RPC__deref_out_opt SAFEARRAY * *pRetVal); HRESULT ( STDMETHODCALLTYPE *SetFocus )( __RPC__in IRawElementProviderFragment * This); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_FragmentRoot )( __RPC__in IRawElementProviderFragment * This, /* [retval][out] */ __RPC__deref_out_opt IRawElementProviderFragmentRoot **pRetVal); END_INTERFACE } IRawElementProviderFragmentVtbl; interface IRawElementProviderFragment { CONST_VTBL struct IRawElementProviderFragmentVtbl *lpVtbl; }; #ifdef COBJMACROS #define IRawElementProviderFragment_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IRawElementProviderFragment_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IRawElementProviderFragment_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IRawElementProviderFragment_Navigate(This,direction,pRetVal) \ ( (This)->lpVtbl -> Navigate(This,direction,pRetVal) ) #define IRawElementProviderFragment_GetRuntimeId(This,pRetVal) \ ( (This)->lpVtbl -> GetRuntimeId(This,pRetVal) ) #define IRawElementProviderFragment_get_BoundingRectangle(This,pRetVal) \ ( (This)->lpVtbl -> get_BoundingRectangle(This,pRetVal) ) #define IRawElementProviderFragment_GetEmbeddedFragmentRoots(This,pRetVal) \ ( (This)->lpVtbl -> GetEmbeddedFragmentRoots(This,pRetVal) ) #define IRawElementProviderFragment_SetFocus(This) \ ( (This)->lpVtbl -> SetFocus(This) ) #define IRawElementProviderFragment_get_FragmentRoot(This,pRetVal) \ ( (This)->lpVtbl -> get_FragmentRoot(This,pRetVal) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IRawElementProviderFragment_INTERFACE_DEFINED__ */ #ifndef __IRawElementProviderAdviseEvents_INTERFACE_DEFINED__ #define __IRawElementProviderAdviseEvents_INTERFACE_DEFINED__ /* interface IRawElementProviderAdviseEvents */ /* [unique][uuid][object] */ EXTERN_C const IID IID_IRawElementProviderAdviseEvents; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("a407b27b-0f6d-4427-9292-473c7bf93258") IRawElementProviderAdviseEvents : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE AdviseEventAdded( /* [in] */ EVENTID eventId, /* [in] */ __RPC__in SAFEARRAY * propertyIDs) = 0; virtual HRESULT STDMETHODCALLTYPE AdviseEventRemoved( /* [in] */ EVENTID eventId, /* [in] */ __RPC__in SAFEARRAY * propertyIDs) = 0; }; #else /* C style interface */ typedef struct IRawElementProviderAdviseEventsVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in IRawElementProviderAdviseEvents * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ __RPC__deref_out void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in IRawElementProviderAdviseEvents * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in IRawElementProviderAdviseEvents * This); HRESULT ( STDMETHODCALLTYPE *AdviseEventAdded )( __RPC__in IRawElementProviderAdviseEvents * This, /* [in] */ EVENTID eventId, /* [in] */ __RPC__in SAFEARRAY * propertyIDs); HRESULT ( STDMETHODCALLTYPE *AdviseEventRemoved )( __RPC__in IRawElementProviderAdviseEvents * This, /* [in] */ EVENTID eventId, /* [in] */ __RPC__in SAFEARRAY * propertyIDs); END_INTERFACE } IRawElementProviderAdviseEventsVtbl; interface IRawElementProviderAdviseEvents { CONST_VTBL struct IRawElementProviderAdviseEventsVtbl *lpVtbl; }; #ifdef COBJMACROS #define IRawElementProviderAdviseEvents_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IRawElementProviderAdviseEvents_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IRawElementProviderAdviseEvents_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IRawElementProviderAdviseEvents_AdviseEventAdded(This,eventId,propertyIDs) \ ( (This)->lpVtbl -> AdviseEventAdded(This,eventId,propertyIDs) ) #define IRawElementProviderAdviseEvents_AdviseEventRemoved(This,eventId,propertyIDs) \ ( (This)->lpVtbl -> AdviseEventRemoved(This,eventId,propertyIDs) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IRawElementProviderAdviseEvents_INTERFACE_DEFINED__ */ #ifndef __IRawElementProviderHwndOverride_INTERFACE_DEFINED__ #define __IRawElementProviderHwndOverride_INTERFACE_DEFINED__ /* interface IRawElementProviderHwndOverride */ /* [unique][uuid][object] */ EXTERN_C const IID IID_IRawElementProviderHwndOverride; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("1d5df27c-8947-4425-b8d9-79787bb460b8") IRawElementProviderHwndOverride : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE GetOverrideProviderForHwnd( /* [in] */ __RPC__in HWND hwnd, /* [retval][out] */ __RPC__deref_out_opt IRawElementProviderSimple **pRetVal) = 0; }; #else /* C style interface */ typedef struct IRawElementProviderHwndOverrideVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in IRawElementProviderHwndOverride * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ __RPC__deref_out void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in IRawElementProviderHwndOverride * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in IRawElementProviderHwndOverride * This); HRESULT ( STDMETHODCALLTYPE *GetOverrideProviderForHwnd )( __RPC__in IRawElementProviderHwndOverride * This, /* [in] */ __RPC__in HWND hwnd, /* [retval][out] */ __RPC__deref_out_opt IRawElementProviderSimple **pRetVal); END_INTERFACE } IRawElementProviderHwndOverrideVtbl; interface IRawElementProviderHwndOverride { CONST_VTBL struct IRawElementProviderHwndOverrideVtbl *lpVtbl; }; #ifdef COBJMACROS #define IRawElementProviderHwndOverride_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IRawElementProviderHwndOverride_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IRawElementProviderHwndOverride_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IRawElementProviderHwndOverride_GetOverrideProviderForHwnd(This,hwnd,pRetVal) \ ( (This)->lpVtbl -> GetOverrideProviderForHwnd(This,hwnd,pRetVal) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IRawElementProviderHwndOverride_INTERFACE_DEFINED__ */ #ifndef __IProxyProviderWinEventSink_INTERFACE_DEFINED__ #define __IProxyProviderWinEventSink_INTERFACE_DEFINED__ /* interface IProxyProviderWinEventSink */ /* [unique][uuid][object] */ EXTERN_C const IID IID_IProxyProviderWinEventSink; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("4fd82b78-a43e-46ac-9803-0a6969c7c183") IProxyProviderWinEventSink : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE AddAutomationPropertyChangedEvent( /* [in] */ __RPC__in_opt IRawElementProviderSimple *pProvider, /* [in] */ PROPERTYID id, /* [in] */ VARIANT newValue) = 0; virtual HRESULT STDMETHODCALLTYPE AddAutomationEvent( /* [in] */ __RPC__in_opt IRawElementProviderSimple *pProvider, /* [in] */ EVENTID id) = 0; virtual HRESULT STDMETHODCALLTYPE AddStructureChangedEvent( /* [in] */ __RPC__in_opt IRawElementProviderSimple *pProvider, /* [in] */ enum StructureChangeType structureChangeType, /* [in] */ __RPC__in SAFEARRAY * runtimeId) = 0; }; #else /* C style interface */ typedef struct IProxyProviderWinEventSinkVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in IProxyProviderWinEventSink * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ __RPC__deref_out void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in IProxyProviderWinEventSink * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in IProxyProviderWinEventSink * This); HRESULT ( STDMETHODCALLTYPE *AddAutomationPropertyChangedEvent )( __RPC__in IProxyProviderWinEventSink * This, /* [in] */ __RPC__in_opt IRawElementProviderSimple *pProvider, /* [in] */ PROPERTYID id, /* [in] */ VARIANT newValue); HRESULT ( STDMETHODCALLTYPE *AddAutomationEvent )( __RPC__in IProxyProviderWinEventSink * This, /* [in] */ __RPC__in_opt IRawElementProviderSimple *pProvider, /* [in] */ EVENTID id); HRESULT ( STDMETHODCALLTYPE *AddStructureChangedEvent )( __RPC__in IProxyProviderWinEventSink * This, /* [in] */ __RPC__in_opt IRawElementProviderSimple *pProvider, /* [in] */ enum StructureChangeType structureChangeType, /* [in] */ __RPC__in SAFEARRAY * runtimeId); END_INTERFACE } IProxyProviderWinEventSinkVtbl; interface IProxyProviderWinEventSink { CONST_VTBL struct IProxyProviderWinEventSinkVtbl *lpVtbl; }; #ifdef COBJMACROS #define IProxyProviderWinEventSink_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IProxyProviderWinEventSink_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IProxyProviderWinEventSink_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IProxyProviderWinEventSink_AddAutomationPropertyChangedEvent(This,pProvider,id,newValue) \ ( (This)->lpVtbl -> AddAutomationPropertyChangedEvent(This,pProvider,id,newValue) ) #define IProxyProviderWinEventSink_AddAutomationEvent(This,pProvider,id) \ ( (This)->lpVtbl -> AddAutomationEvent(This,pProvider,id) ) #define IProxyProviderWinEventSink_AddStructureChangedEvent(This,pProvider,structureChangeType,runtimeId) \ ( (This)->lpVtbl -> AddStructureChangedEvent(This,pProvider,structureChangeType,runtimeId) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IProxyProviderWinEventSink_INTERFACE_DEFINED__ */ #ifndef __IProxyProviderWinEventHandler_INTERFACE_DEFINED__ #define __IProxyProviderWinEventHandler_INTERFACE_DEFINED__ /* interface IProxyProviderWinEventHandler */ /* [unique][uuid][object] */ EXTERN_C const IID IID_IProxyProviderWinEventHandler; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("89592ad4-f4e0-43d5-a3b6-bad7e111b435") IProxyProviderWinEventHandler : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE RespondToWinEvent( /* [in] */ DWORD idWinEvent, /* [in] */ __RPC__in HWND hwnd, /* [in] */ LONG idObject, /* [in] */ LONG idChild, /* [in] */ __RPC__in_opt IProxyProviderWinEventSink *pSink) = 0; }; #else /* C style interface */ typedef struct IProxyProviderWinEventHandlerVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in IProxyProviderWinEventHandler * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ __RPC__deref_out void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in IProxyProviderWinEventHandler * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in IProxyProviderWinEventHandler * This); HRESULT ( STDMETHODCALLTYPE *RespondToWinEvent )( __RPC__in IProxyProviderWinEventHandler * This, /* [in] */ DWORD idWinEvent, /* [in] */ __RPC__in HWND hwnd, /* [in] */ LONG idObject, /* [in] */ LONG idChild, /* [in] */ __RPC__in_opt IProxyProviderWinEventSink *pSink); END_INTERFACE } IProxyProviderWinEventHandlerVtbl; interface IProxyProviderWinEventHandler { CONST_VTBL struct IProxyProviderWinEventHandlerVtbl *lpVtbl; }; #ifdef COBJMACROS #define IProxyProviderWinEventHandler_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IProxyProviderWinEventHandler_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IProxyProviderWinEventHandler_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IProxyProviderWinEventHandler_RespondToWinEvent(This,idWinEvent,hwnd,idObject,idChild,pSink) \ ( (This)->lpVtbl -> RespondToWinEvent(This,idWinEvent,hwnd,idObject,idChild,pSink) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IProxyProviderWinEventHandler_INTERFACE_DEFINED__ */ #ifndef __IDockProvider_INTERFACE_DEFINED__ #define __IDockProvider_INTERFACE_DEFINED__ /* interface IDockProvider */ /* [unique][uuid][object] */ EXTERN_C const IID IID_IDockProvider; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("159bc72c-4ad3-485e-9637-d7052edf0146") IDockProvider : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE SetDockPosition( /* [in] */ enum DockPosition dockPosition) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_DockPosition( /* [retval][out] */ __RPC__out enum DockPosition *pRetVal) = 0; }; #else /* C style interface */ typedef struct IDockProviderVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in IDockProvider * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ __RPC__deref_out void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in IDockProvider * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in IDockProvider * This); HRESULT ( STDMETHODCALLTYPE *SetDockPosition )( __RPC__in IDockProvider * This, /* [in] */ enum DockPosition dockPosition); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_DockPosition )( __RPC__in IDockProvider * This, /* [retval][out] */ __RPC__out enum DockPosition *pRetVal); END_INTERFACE } IDockProviderVtbl; interface IDockProvider { CONST_VTBL struct IDockProviderVtbl *lpVtbl; }; #ifdef COBJMACROS #define IDockProvider_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IDockProvider_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IDockProvider_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IDockProvider_SetDockPosition(This,dockPosition) \ ( (This)->lpVtbl -> SetDockPosition(This,dockPosition) ) #define IDockProvider_get_DockPosition(This,pRetVal) \ ( (This)->lpVtbl -> get_DockPosition(This,pRetVal) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IDockProvider_INTERFACE_DEFINED__ */ #ifndef __IExpandCollapseProvider_INTERFACE_DEFINED__ #define __IExpandCollapseProvider_INTERFACE_DEFINED__ /* interface IExpandCollapseProvider */ /* [unique][uuid][object] */ EXTERN_C const IID IID_IExpandCollapseProvider; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("d847d3a5-cab0-4a98-8c32-ecb45c59ad24") IExpandCollapseProvider : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE Expand( void) = 0; virtual HRESULT STDMETHODCALLTYPE Collapse( void) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_ExpandCollapseState( /* [retval][out] */ __RPC__out enum ExpandCollapseState *pRetVal) = 0; }; #else /* C style interface */ typedef struct IExpandCollapseProviderVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in IExpandCollapseProvider * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ __RPC__deref_out void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in IExpandCollapseProvider * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in IExpandCollapseProvider * This); HRESULT ( STDMETHODCALLTYPE *Expand )( __RPC__in IExpandCollapseProvider * This); HRESULT ( STDMETHODCALLTYPE *Collapse )( __RPC__in IExpandCollapseProvider * This); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_ExpandCollapseState )( __RPC__in IExpandCollapseProvider * This, /* [retval][out] */ __RPC__out enum ExpandCollapseState *pRetVal); END_INTERFACE } IExpandCollapseProviderVtbl; interface IExpandCollapseProvider { CONST_VTBL struct IExpandCollapseProviderVtbl *lpVtbl; }; #ifdef COBJMACROS #define IExpandCollapseProvider_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IExpandCollapseProvider_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IExpandCollapseProvider_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IExpandCollapseProvider_Expand(This) \ ( (This)->lpVtbl -> Expand(This) ) #define IExpandCollapseProvider_Collapse(This) \ ( (This)->lpVtbl -> Collapse(This) ) #define IExpandCollapseProvider_get_ExpandCollapseState(This,pRetVal) \ ( (This)->lpVtbl -> get_ExpandCollapseState(This,pRetVal) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IExpandCollapseProvider_INTERFACE_DEFINED__ */ #ifndef __IGridProvider_INTERFACE_DEFINED__ #define __IGridProvider_INTERFACE_DEFINED__ /* interface IGridProvider */ /* [unique][uuid][object] */ EXTERN_C const IID IID_IGridProvider; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("b17d6187-0907-464b-a168-0ef17a1572b1") IGridProvider : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE GetItem( /* [in] */ int row, /* [in] */ int column, /* [retval][out] */ __RPC__deref_out_opt IRawElementProviderSimple **pRetVal) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_RowCount( /* [retval][out] */ __RPC__out int *pRetVal) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_ColumnCount( /* [retval][out] */ __RPC__out int *pRetVal) = 0; }; #else /* C style interface */ typedef struct IGridProviderVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in IGridProvider * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ __RPC__deref_out void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in IGridProvider * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in IGridProvider * This); HRESULT ( STDMETHODCALLTYPE *GetItem )( __RPC__in IGridProvider * This, /* [in] */ int row, /* [in] */ int column, /* [retval][out] */ __RPC__deref_out_opt IRawElementProviderSimple **pRetVal); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_RowCount )( __RPC__in IGridProvider * This, /* [retval][out] */ __RPC__out int *pRetVal); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_ColumnCount )( __RPC__in IGridProvider * This, /* [retval][out] */ __RPC__out int *pRetVal); END_INTERFACE } IGridProviderVtbl; interface IGridProvider { CONST_VTBL struct IGridProviderVtbl *lpVtbl; }; #ifdef COBJMACROS #define IGridProvider_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IGridProvider_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IGridProvider_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IGridProvider_GetItem(This,row,column,pRetVal) \ ( (This)->lpVtbl -> GetItem(This,row,column,pRetVal) ) #define IGridProvider_get_RowCount(This,pRetVal) \ ( (This)->lpVtbl -> get_RowCount(This,pRetVal) ) #define IGridProvider_get_ColumnCount(This,pRetVal) \ ( (This)->lpVtbl -> get_ColumnCount(This,pRetVal) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IGridProvider_INTERFACE_DEFINED__ */ #ifndef __IGridItemProvider_INTERFACE_DEFINED__ #define __IGridItemProvider_INTERFACE_DEFINED__ /* interface IGridItemProvider */ /* [unique][uuid][object] */ EXTERN_C const IID IID_IGridItemProvider; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("d02541f1-fb81-4d64-ae32-f520f8a6dbd1") IGridItemProvider : public IUnknown { public: virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_Row( /* [retval][out] */ __RPC__out int *pRetVal) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_Column( /* [retval][out] */ __RPC__out int *pRetVal) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_RowSpan( /* [retval][out] */ __RPC__out int *pRetVal) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_ColumnSpan( /* [retval][out] */ __RPC__out int *pRetVal) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_ContainingGrid( /* [retval][out] */ __RPC__deref_out_opt IRawElementProviderSimple **pRetVal) = 0; }; #else /* C style interface */ typedef struct IGridItemProviderVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in IGridItemProvider * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ __RPC__deref_out void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in IGridItemProvider * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in IGridItemProvider * This); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_Row )( __RPC__in IGridItemProvider * This, /* [retval][out] */ __RPC__out int *pRetVal); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_Column )( __RPC__in IGridItemProvider * This, /* [retval][out] */ __RPC__out int *pRetVal); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_RowSpan )( __RPC__in IGridItemProvider * This, /* [retval][out] */ __RPC__out int *pRetVal); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_ColumnSpan )( __RPC__in IGridItemProvider * This, /* [retval][out] */ __RPC__out int *pRetVal); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_ContainingGrid )( __RPC__in IGridItemProvider * This, /* [retval][out] */ __RPC__deref_out_opt IRawElementProviderSimple **pRetVal); END_INTERFACE } IGridItemProviderVtbl; interface IGridItemProvider { CONST_VTBL struct IGridItemProviderVtbl *lpVtbl; }; #ifdef COBJMACROS #define IGridItemProvider_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IGridItemProvider_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IGridItemProvider_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IGridItemProvider_get_Row(This,pRetVal) \ ( (This)->lpVtbl -> get_Row(This,pRetVal) ) #define IGridItemProvider_get_Column(This,pRetVal) \ ( (This)->lpVtbl -> get_Column(This,pRetVal) ) #define IGridItemProvider_get_RowSpan(This,pRetVal) \ ( (This)->lpVtbl -> get_RowSpan(This,pRetVal) ) #define IGridItemProvider_get_ColumnSpan(This,pRetVal) \ ( (This)->lpVtbl -> get_ColumnSpan(This,pRetVal) ) #define IGridItemProvider_get_ContainingGrid(This,pRetVal) \ ( (This)->lpVtbl -> get_ContainingGrid(This,pRetVal) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IGridItemProvider_INTERFACE_DEFINED__ */ #ifndef __IInvokeProvider_INTERFACE_DEFINED__ #define __IInvokeProvider_INTERFACE_DEFINED__ /* interface IInvokeProvider */ /* [unique][uuid][object] */ EXTERN_C const IID IID_IInvokeProvider; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("54fcb24b-e18e-47a2-b4d3-eccbe77599a2") IInvokeProvider : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE Invoke( void) = 0; }; #else /* C style interface */ typedef struct IInvokeProviderVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in IInvokeProvider * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ __RPC__deref_out void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in IInvokeProvider * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in IInvokeProvider * This); HRESULT ( STDMETHODCALLTYPE *Invoke )( __RPC__in IInvokeProvider * This); END_INTERFACE } IInvokeProviderVtbl; interface IInvokeProvider { CONST_VTBL struct IInvokeProviderVtbl *lpVtbl; }; #ifdef COBJMACROS #define IInvokeProvider_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IInvokeProvider_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IInvokeProvider_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IInvokeProvider_Invoke(This) \ ( (This)->lpVtbl -> Invoke(This) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IInvokeProvider_INTERFACE_DEFINED__ */ #ifndef __IMultipleViewProvider_INTERFACE_DEFINED__ #define __IMultipleViewProvider_INTERFACE_DEFINED__ /* interface IMultipleViewProvider */ /* [unique][uuid][object] */ EXTERN_C const IID IID_IMultipleViewProvider; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("6278cab1-b556-4a1a-b4e0-418acc523201") IMultipleViewProvider : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE GetViewName( /* [in] */ int viewId, /* [retval][out] */ __RPC__deref_out_opt BSTR *pRetVal) = 0; virtual HRESULT STDMETHODCALLTYPE SetCurrentView( /* [in] */ int viewId) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_CurrentView( /* [retval][out] */ __RPC__out int *pRetVal) = 0; virtual HRESULT STDMETHODCALLTYPE GetSupportedViews( /* [retval][out] */ __RPC__deref_out_opt SAFEARRAY * *pRetVal) = 0; }; #else /* C style interface */ typedef struct IMultipleViewProviderVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in IMultipleViewProvider * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ __RPC__deref_out void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in IMultipleViewProvider * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in IMultipleViewProvider * This); HRESULT ( STDMETHODCALLTYPE *GetViewName )( __RPC__in IMultipleViewProvider * This, /* [in] */ int viewId, /* [retval][out] */ __RPC__deref_out_opt BSTR *pRetVal); HRESULT ( STDMETHODCALLTYPE *SetCurrentView )( __RPC__in IMultipleViewProvider * This, /* [in] */ int viewId); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_CurrentView )( __RPC__in IMultipleViewProvider * This, /* [retval][out] */ __RPC__out int *pRetVal); HRESULT ( STDMETHODCALLTYPE *GetSupportedViews )( __RPC__in IMultipleViewProvider * This, /* [retval][out] */ __RPC__deref_out_opt SAFEARRAY * *pRetVal); END_INTERFACE } IMultipleViewProviderVtbl; interface IMultipleViewProvider { CONST_VTBL struct IMultipleViewProviderVtbl *lpVtbl; }; #ifdef COBJMACROS #define IMultipleViewProvider_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IMultipleViewProvider_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IMultipleViewProvider_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IMultipleViewProvider_GetViewName(This,viewId,pRetVal) \ ( (This)->lpVtbl -> GetViewName(This,viewId,pRetVal) ) #define IMultipleViewProvider_SetCurrentView(This,viewId) \ ( (This)->lpVtbl -> SetCurrentView(This,viewId) ) #define IMultipleViewProvider_get_CurrentView(This,pRetVal) \ ( (This)->lpVtbl -> get_CurrentView(This,pRetVal) ) #define IMultipleViewProvider_GetSupportedViews(This,pRetVal) \ ( (This)->lpVtbl -> GetSupportedViews(This,pRetVal) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IMultipleViewProvider_INTERFACE_DEFINED__ */ #ifndef __IRangeValueProvider_INTERFACE_DEFINED__ #define __IRangeValueProvider_INTERFACE_DEFINED__ /* interface IRangeValueProvider */ /* [unique][uuid][object] */ EXTERN_C const IID IID_IRangeValueProvider; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("36dc7aef-33e6-4691-afe1-2be7274b3d33") IRangeValueProvider : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE SetValue( /* [in] */ double val) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_Value( /* [retval][out] */ __RPC__out double *pRetVal) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_IsReadOnly( /* [retval][out] */ __RPC__out BOOL *pRetVal) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_Maximum( /* [retval][out] */ __RPC__out double *pRetVal) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_Minimum( /* [retval][out] */ __RPC__out double *pRetVal) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_LargeChange( /* [retval][out] */ __RPC__out double *pRetVal) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_SmallChange( /* [retval][out] */ __RPC__out double *pRetVal) = 0; }; #else /* C style interface */ typedef struct IRangeValueProviderVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in IRangeValueProvider * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ __RPC__deref_out void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in IRangeValueProvider * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in IRangeValueProvider * This); HRESULT ( STDMETHODCALLTYPE *SetValue )( __RPC__in IRangeValueProvider * This, /* [in] */ double val); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_Value )( __RPC__in IRangeValueProvider * This, /* [retval][out] */ __RPC__out double *pRetVal); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_IsReadOnly )( __RPC__in IRangeValueProvider * This, /* [retval][out] */ __RPC__out BOOL *pRetVal); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_Maximum )( __RPC__in IRangeValueProvider * This, /* [retval][out] */ __RPC__out double *pRetVal); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_Minimum )( __RPC__in IRangeValueProvider * This, /* [retval][out] */ __RPC__out double *pRetVal); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_LargeChange )( __RPC__in IRangeValueProvider * This, /* [retval][out] */ __RPC__out double *pRetVal); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_SmallChange )( __RPC__in IRangeValueProvider * This, /* [retval][out] */ __RPC__out double *pRetVal); END_INTERFACE } IRangeValueProviderVtbl; interface IRangeValueProvider { CONST_VTBL struct IRangeValueProviderVtbl *lpVtbl; }; #ifdef COBJMACROS #define IRangeValueProvider_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IRangeValueProvider_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IRangeValueProvider_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IRangeValueProvider_SetValue(This,val) \ ( (This)->lpVtbl -> SetValue(This,val) ) #define IRangeValueProvider_get_Value(This,pRetVal) \ ( (This)->lpVtbl -> get_Value(This,pRetVal) ) #define IRangeValueProvider_get_IsReadOnly(This,pRetVal) \ ( (This)->lpVtbl -> get_IsReadOnly(This,pRetVal) ) #define IRangeValueProvider_get_Maximum(This,pRetVal) \ ( (This)->lpVtbl -> get_Maximum(This,pRetVal) ) #define IRangeValueProvider_get_Minimum(This,pRetVal) \ ( (This)->lpVtbl -> get_Minimum(This,pRetVal) ) #define IRangeValueProvider_get_LargeChange(This,pRetVal) \ ( (This)->lpVtbl -> get_LargeChange(This,pRetVal) ) #define IRangeValueProvider_get_SmallChange(This,pRetVal) \ ( (This)->lpVtbl -> get_SmallChange(This,pRetVal) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IRangeValueProvider_INTERFACE_DEFINED__ */ #ifndef __IScrollItemProvider_INTERFACE_DEFINED__ #define __IScrollItemProvider_INTERFACE_DEFINED__ /* interface IScrollItemProvider */ /* [unique][uuid][object] */ EXTERN_C const IID IID_IScrollItemProvider; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("2360c714-4bf1-4b26-ba65-9b21316127eb") IScrollItemProvider : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE ScrollIntoView( void) = 0; }; #else /* C style interface */ typedef struct IScrollItemProviderVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in IScrollItemProvider * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ __RPC__deref_out void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in IScrollItemProvider * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in IScrollItemProvider * This); HRESULT ( STDMETHODCALLTYPE *ScrollIntoView )( __RPC__in IScrollItemProvider * This); END_INTERFACE } IScrollItemProviderVtbl; interface IScrollItemProvider { CONST_VTBL struct IScrollItemProviderVtbl *lpVtbl; }; #ifdef COBJMACROS #define IScrollItemProvider_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IScrollItemProvider_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IScrollItemProvider_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IScrollItemProvider_ScrollIntoView(This) \ ( (This)->lpVtbl -> ScrollIntoView(This) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IScrollItemProvider_INTERFACE_DEFINED__ */ #ifndef __ISelectionProvider_INTERFACE_DEFINED__ #define __ISelectionProvider_INTERFACE_DEFINED__ /* interface ISelectionProvider */ /* [unique][uuid][object] */ EXTERN_C const IID IID_ISelectionProvider; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("fb8b03af-3bdf-48d4-bd36-1a65793be168") ISelectionProvider : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE GetSelection( /* [retval][out] */ __RPC__deref_out_opt SAFEARRAY * *pRetVal) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_CanSelectMultiple( /* [retval][out] */ __RPC__out BOOL *pRetVal) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_IsSelectionRequired( /* [retval][out] */ __RPC__out BOOL *pRetVal) = 0; }; #else /* C style interface */ typedef struct ISelectionProviderVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in ISelectionProvider * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ __RPC__deref_out void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in ISelectionProvider * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in ISelectionProvider * This); HRESULT ( STDMETHODCALLTYPE *GetSelection )( __RPC__in ISelectionProvider * This, /* [retval][out] */ __RPC__deref_out_opt SAFEARRAY * *pRetVal); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_CanSelectMultiple )( __RPC__in ISelectionProvider * This, /* [retval][out] */ __RPC__out BOOL *pRetVal); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_IsSelectionRequired )( __RPC__in ISelectionProvider * This, /* [retval][out] */ __RPC__out BOOL *pRetVal); END_INTERFACE } ISelectionProviderVtbl; interface ISelectionProvider { CONST_VTBL struct ISelectionProviderVtbl *lpVtbl; }; #ifdef COBJMACROS #define ISelectionProvider_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define ISelectionProvider_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define ISelectionProvider_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define ISelectionProvider_GetSelection(This,pRetVal) \ ( (This)->lpVtbl -> GetSelection(This,pRetVal) ) #define ISelectionProvider_get_CanSelectMultiple(This,pRetVal) \ ( (This)->lpVtbl -> get_CanSelectMultiple(This,pRetVal) ) #define ISelectionProvider_get_IsSelectionRequired(This,pRetVal) \ ( (This)->lpVtbl -> get_IsSelectionRequired(This,pRetVal) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __ISelectionProvider_INTERFACE_DEFINED__ */ #ifndef __IScrollProvider_INTERFACE_DEFINED__ #define __IScrollProvider_INTERFACE_DEFINED__ /* interface IScrollProvider */ /* [unique][uuid][object] */ EXTERN_C const IID IID_IScrollProvider; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("b38b8077-1fc3-42a5-8cae-d40c2215055a") IScrollProvider : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE Scroll( /* [in] */ enum ScrollAmount horizontalAmount, /* [in] */ enum ScrollAmount verticalAmount) = 0; virtual HRESULT STDMETHODCALLTYPE SetScrollPercent( /* [in] */ double horizontalPercent, /* [in] */ double verticalPercent) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_HorizontalScrollPercent( /* [retval][out] */ __RPC__out double *pRetVal) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_VerticalScrollPercent( /* [retval][out] */ __RPC__out double *pRetVal) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_HorizontalViewSize( /* [retval][out] */ __RPC__out double *pRetVal) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_VerticalViewSize( /* [retval][out] */ __RPC__out double *pRetVal) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_HorizontallyScrollable( /* [retval][out] */ __RPC__out BOOL *pRetVal) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_VerticallyScrollable( /* [retval][out] */ __RPC__out BOOL *pRetVal) = 0; }; #else /* C style interface */ typedef struct IScrollProviderVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in IScrollProvider * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ __RPC__deref_out void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in IScrollProvider * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in IScrollProvider * This); HRESULT ( STDMETHODCALLTYPE *Scroll )( __RPC__in IScrollProvider * This, /* [in] */ enum ScrollAmount horizontalAmount, /* [in] */ enum ScrollAmount verticalAmount); HRESULT ( STDMETHODCALLTYPE *SetScrollPercent )( __RPC__in IScrollProvider * This, /* [in] */ double horizontalPercent, /* [in] */ double verticalPercent); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_HorizontalScrollPercent )( __RPC__in IScrollProvider * This, /* [retval][out] */ __RPC__out double *pRetVal); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_VerticalScrollPercent )( __RPC__in IScrollProvider * This, /* [retval][out] */ __RPC__out double *pRetVal); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_HorizontalViewSize )( __RPC__in IScrollProvider * This, /* [retval][out] */ __RPC__out double *pRetVal); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_VerticalViewSize )( __RPC__in IScrollProvider * This, /* [retval][out] */ __RPC__out double *pRetVal); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_HorizontallyScrollable )( __RPC__in IScrollProvider * This, /* [retval][out] */ __RPC__out BOOL *pRetVal); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_VerticallyScrollable )( __RPC__in IScrollProvider * This, /* [retval][out] */ __RPC__out BOOL *pRetVal); END_INTERFACE } IScrollProviderVtbl; interface IScrollProvider { CONST_VTBL struct IScrollProviderVtbl *lpVtbl; }; #ifdef COBJMACROS #define IScrollProvider_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IScrollProvider_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IScrollProvider_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IScrollProvider_Scroll(This,horizontalAmount,verticalAmount) \ ( (This)->lpVtbl -> Scroll(This,horizontalAmount,verticalAmount) ) #define IScrollProvider_SetScrollPercent(This,horizontalPercent,verticalPercent) \ ( (This)->lpVtbl -> SetScrollPercent(This,horizontalPercent,verticalPercent) ) #define IScrollProvider_get_HorizontalScrollPercent(This,pRetVal) \ ( (This)->lpVtbl -> get_HorizontalScrollPercent(This,pRetVal) ) #define IScrollProvider_get_VerticalScrollPercent(This,pRetVal) \ ( (This)->lpVtbl -> get_VerticalScrollPercent(This,pRetVal) ) #define IScrollProvider_get_HorizontalViewSize(This,pRetVal) \ ( (This)->lpVtbl -> get_HorizontalViewSize(This,pRetVal) ) #define IScrollProvider_get_VerticalViewSize(This,pRetVal) \ ( (This)->lpVtbl -> get_VerticalViewSize(This,pRetVal) ) #define IScrollProvider_get_HorizontallyScrollable(This,pRetVal) \ ( (This)->lpVtbl -> get_HorizontallyScrollable(This,pRetVal) ) #define IScrollProvider_get_VerticallyScrollable(This,pRetVal) \ ( (This)->lpVtbl -> get_VerticallyScrollable(This,pRetVal) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IScrollProvider_INTERFACE_DEFINED__ */ #ifndef __ISelectionItemProvider_INTERFACE_DEFINED__ #define __ISelectionItemProvider_INTERFACE_DEFINED__ /* interface ISelectionItemProvider */ /* [unique][uuid][object] */ EXTERN_C const IID IID_ISelectionItemProvider; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("2acad808-b2d4-452d-a407-91ff1ad167b2") ISelectionItemProvider : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE Select( void) = 0; virtual HRESULT STDMETHODCALLTYPE AddToSelection( void) = 0; virtual HRESULT STDMETHODCALLTYPE RemoveFromSelection( void) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_IsSelected( /* [retval][out] */ __RPC__out BOOL *pRetVal) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_SelectionContainer( /* [retval][out] */ __RPC__deref_out_opt IRawElementProviderSimple **pRetVal) = 0; }; #else /* C style interface */ typedef struct ISelectionItemProviderVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in ISelectionItemProvider * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ __RPC__deref_out void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in ISelectionItemProvider * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in ISelectionItemProvider * This); HRESULT ( STDMETHODCALLTYPE *Select )( __RPC__in ISelectionItemProvider * This); HRESULT ( STDMETHODCALLTYPE *AddToSelection )( __RPC__in ISelectionItemProvider * This); HRESULT ( STDMETHODCALLTYPE *RemoveFromSelection )( __RPC__in ISelectionItemProvider * This); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_IsSelected )( __RPC__in ISelectionItemProvider * This, /* [retval][out] */ __RPC__out BOOL *pRetVal); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_SelectionContainer )( __RPC__in ISelectionItemProvider * This, /* [retval][out] */ __RPC__deref_out_opt IRawElementProviderSimple **pRetVal); END_INTERFACE } ISelectionItemProviderVtbl; interface ISelectionItemProvider { CONST_VTBL struct ISelectionItemProviderVtbl *lpVtbl; }; #ifdef COBJMACROS #define ISelectionItemProvider_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define ISelectionItemProvider_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define ISelectionItemProvider_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define ISelectionItemProvider_Select(This) \ ( (This)->lpVtbl -> Select(This) ) #define ISelectionItemProvider_AddToSelection(This) \ ( (This)->lpVtbl -> AddToSelection(This) ) #define ISelectionItemProvider_RemoveFromSelection(This) \ ( (This)->lpVtbl -> RemoveFromSelection(This) ) #define ISelectionItemProvider_get_IsSelected(This,pRetVal) \ ( (This)->lpVtbl -> get_IsSelected(This,pRetVal) ) #define ISelectionItemProvider_get_SelectionContainer(This,pRetVal) \ ( (This)->lpVtbl -> get_SelectionContainer(This,pRetVal) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __ISelectionItemProvider_INTERFACE_DEFINED__ */ #ifndef __ISynchronizedInputProvider_INTERFACE_DEFINED__ #define __ISynchronizedInputProvider_INTERFACE_DEFINED__ /* interface ISynchronizedInputProvider */ /* [unique][uuid][object] */ EXTERN_C const IID IID_ISynchronizedInputProvider; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("29db1a06-02ce-4cf7-9b42-565d4fab20ee") ISynchronizedInputProvider : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE StartListening( /* [in] */ enum SynchronizedInputType inputType) = 0; virtual HRESULT STDMETHODCALLTYPE Cancel( void) = 0; }; #else /* C style interface */ typedef struct ISynchronizedInputProviderVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in ISynchronizedInputProvider * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ __RPC__deref_out void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in ISynchronizedInputProvider * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in ISynchronizedInputProvider * This); HRESULT ( STDMETHODCALLTYPE *StartListening )( __RPC__in ISynchronizedInputProvider * This, /* [in] */ enum SynchronizedInputType inputType); HRESULT ( STDMETHODCALLTYPE *Cancel )( __RPC__in ISynchronizedInputProvider * This); END_INTERFACE } ISynchronizedInputProviderVtbl; interface ISynchronizedInputProvider { CONST_VTBL struct ISynchronizedInputProviderVtbl *lpVtbl; }; #ifdef COBJMACROS #define ISynchronizedInputProvider_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define ISynchronizedInputProvider_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define ISynchronizedInputProvider_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define ISynchronizedInputProvider_StartListening(This,inputType) \ ( (This)->lpVtbl -> StartListening(This,inputType) ) #define ISynchronizedInputProvider_Cancel(This) \ ( (This)->lpVtbl -> Cancel(This) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __ISynchronizedInputProvider_INTERFACE_DEFINED__ */ #ifndef __ITableProvider_INTERFACE_DEFINED__ #define __ITableProvider_INTERFACE_DEFINED__ /* interface ITableProvider */ /* [unique][uuid][object] */ EXTERN_C const IID IID_ITableProvider; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("9c860395-97b3-490a-b52a-858cc22af166") ITableProvider : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE GetRowHeaders( /* [retval][out] */ __RPC__deref_out_opt SAFEARRAY * *pRetVal) = 0; virtual HRESULT STDMETHODCALLTYPE GetColumnHeaders( /* [retval][out] */ __RPC__deref_out_opt SAFEARRAY * *pRetVal) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_RowOrColumnMajor( /* [retval][out] */ __RPC__out enum RowOrColumnMajor *pRetVal) = 0; }; #else /* C style interface */ typedef struct ITableProviderVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in ITableProvider * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ __RPC__deref_out void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in ITableProvider * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in ITableProvider * This); HRESULT ( STDMETHODCALLTYPE *GetRowHeaders )( __RPC__in ITableProvider * This, /* [retval][out] */ __RPC__deref_out_opt SAFEARRAY * *pRetVal); HRESULT ( STDMETHODCALLTYPE *GetColumnHeaders )( __RPC__in ITableProvider * This, /* [retval][out] */ __RPC__deref_out_opt SAFEARRAY * *pRetVal); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_RowOrColumnMajor )( __RPC__in ITableProvider * This, /* [retval][out] */ __RPC__out enum RowOrColumnMajor *pRetVal); END_INTERFACE } ITableProviderVtbl; interface ITableProvider { CONST_VTBL struct ITableProviderVtbl *lpVtbl; }; #ifdef COBJMACROS #define ITableProvider_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define ITableProvider_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define ITableProvider_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define ITableProvider_GetRowHeaders(This,pRetVal) \ ( (This)->lpVtbl -> GetRowHeaders(This,pRetVal) ) #define ITableProvider_GetColumnHeaders(This,pRetVal) \ ( (This)->lpVtbl -> GetColumnHeaders(This,pRetVal) ) #define ITableProvider_get_RowOrColumnMajor(This,pRetVal) \ ( (This)->lpVtbl -> get_RowOrColumnMajor(This,pRetVal) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __ITableProvider_INTERFACE_DEFINED__ */ #ifndef __ITableItemProvider_INTERFACE_DEFINED__ #define __ITableItemProvider_INTERFACE_DEFINED__ /* interface ITableItemProvider */ /* [unique][uuid][object] */ EXTERN_C const IID IID_ITableItemProvider; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("b9734fa6-771f-4d78-9c90-2517999349cd") ITableItemProvider : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE GetRowHeaderItems( /* [retval][out] */ __RPC__deref_out_opt SAFEARRAY * *pRetVal) = 0; virtual HRESULT STDMETHODCALLTYPE GetColumnHeaderItems( /* [retval][out] */ __RPC__deref_out_opt SAFEARRAY * *pRetVal) = 0; }; #else /* C style interface */ typedef struct ITableItemProviderVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in ITableItemProvider * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ __RPC__deref_out void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in ITableItemProvider * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in ITableItemProvider * This); HRESULT ( STDMETHODCALLTYPE *GetRowHeaderItems )( __RPC__in ITableItemProvider * This, /* [retval][out] */ __RPC__deref_out_opt SAFEARRAY * *pRetVal); HRESULT ( STDMETHODCALLTYPE *GetColumnHeaderItems )( __RPC__in ITableItemProvider * This, /* [retval][out] */ __RPC__deref_out_opt SAFEARRAY * *pRetVal); END_INTERFACE } ITableItemProviderVtbl; interface ITableItemProvider { CONST_VTBL struct ITableItemProviderVtbl *lpVtbl; }; #ifdef COBJMACROS #define ITableItemProvider_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define ITableItemProvider_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define ITableItemProvider_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define ITableItemProvider_GetRowHeaderItems(This,pRetVal) \ ( (This)->lpVtbl -> GetRowHeaderItems(This,pRetVal) ) #define ITableItemProvider_GetColumnHeaderItems(This,pRetVal) \ ( (This)->lpVtbl -> GetColumnHeaderItems(This,pRetVal) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __ITableItemProvider_INTERFACE_DEFINED__ */ #ifndef __IToggleProvider_INTERFACE_DEFINED__ #define __IToggleProvider_INTERFACE_DEFINED__ /* interface IToggleProvider */ /* [unique][uuid][object] */ EXTERN_C const IID IID_IToggleProvider; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("56d00bd0-c4f4-433c-a836-1a52a57e0892") IToggleProvider : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE Toggle( void) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_ToggleState( /* [retval][out] */ __RPC__out enum ToggleState *pRetVal) = 0; }; #else /* C style interface */ typedef struct IToggleProviderVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in IToggleProvider * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ __RPC__deref_out void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in IToggleProvider * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in IToggleProvider * This); HRESULT ( STDMETHODCALLTYPE *Toggle )( __RPC__in IToggleProvider * This); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_ToggleState )( __RPC__in IToggleProvider * This, /* [retval][out] */ __RPC__out enum ToggleState *pRetVal); END_INTERFACE } IToggleProviderVtbl; interface IToggleProvider { CONST_VTBL struct IToggleProviderVtbl *lpVtbl; }; #ifdef COBJMACROS #define IToggleProvider_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IToggleProvider_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IToggleProvider_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IToggleProvider_Toggle(This) \ ( (This)->lpVtbl -> Toggle(This) ) #define IToggleProvider_get_ToggleState(This,pRetVal) \ ( (This)->lpVtbl -> get_ToggleState(This,pRetVal) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IToggleProvider_INTERFACE_DEFINED__ */ #ifndef __ITransformProvider_INTERFACE_DEFINED__ #define __ITransformProvider_INTERFACE_DEFINED__ /* interface ITransformProvider */ /* [unique][uuid][object] */ EXTERN_C const IID IID_ITransformProvider; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("6829ddc4-4f91-4ffa-b86f-bd3e2987cb4c") ITransformProvider : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE Move( /* [in] */ double x, /* [in] */ double y) = 0; virtual HRESULT STDMETHODCALLTYPE Resize( /* [in] */ double width, /* [in] */ double height) = 0; virtual HRESULT STDMETHODCALLTYPE Rotate( /* [in] */ double degrees) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_CanMove( /* [retval][out] */ __RPC__out BOOL *pRetVal) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_CanResize( /* [retval][out] */ __RPC__out BOOL *pRetVal) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_CanRotate( /* [retval][out] */ __RPC__out BOOL *pRetVal) = 0; }; #else /* C style interface */ typedef struct ITransformProviderVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in ITransformProvider * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ __RPC__deref_out void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in ITransformProvider * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in ITransformProvider * This); HRESULT ( STDMETHODCALLTYPE *Move )( __RPC__in ITransformProvider * This, /* [in] */ double x, /* [in] */ double y); HRESULT ( STDMETHODCALLTYPE *Resize )( __RPC__in ITransformProvider * This, /* [in] */ double width, /* [in] */ double height); HRESULT ( STDMETHODCALLTYPE *Rotate )( __RPC__in ITransformProvider * This, /* [in] */ double degrees); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_CanMove )( __RPC__in ITransformProvider * This, /* [retval][out] */ __RPC__out BOOL *pRetVal); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_CanResize )( __RPC__in ITransformProvider * This, /* [retval][out] */ __RPC__out BOOL *pRetVal); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_CanRotate )( __RPC__in ITransformProvider * This, /* [retval][out] */ __RPC__out BOOL *pRetVal); END_INTERFACE } ITransformProviderVtbl; interface ITransformProvider { CONST_VTBL struct ITransformProviderVtbl *lpVtbl; }; #ifdef COBJMACROS #define ITransformProvider_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define ITransformProvider_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define ITransformProvider_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define ITransformProvider_Move(This,x,y) \ ( (This)->lpVtbl -> Move(This,x,y) ) #define ITransformProvider_Resize(This,width,height) \ ( (This)->lpVtbl -> Resize(This,width,height) ) #define ITransformProvider_Rotate(This,degrees) \ ( (This)->lpVtbl -> Rotate(This,degrees) ) #define ITransformProvider_get_CanMove(This,pRetVal) \ ( (This)->lpVtbl -> get_CanMove(This,pRetVal) ) #define ITransformProvider_get_CanResize(This,pRetVal) \ ( (This)->lpVtbl -> get_CanResize(This,pRetVal) ) #define ITransformProvider_get_CanRotate(This,pRetVal) \ ( (This)->lpVtbl -> get_CanRotate(This,pRetVal) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __ITransformProvider_INTERFACE_DEFINED__ */ #ifndef __IValueProvider_INTERFACE_DEFINED__ #define __IValueProvider_INTERFACE_DEFINED__ /* interface IValueProvider */ /* [unique][uuid][object] */ EXTERN_C const IID IID_IValueProvider; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("c7935180-6fb3-4201-b174-7df73adbf64a") IValueProvider : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE SetValue( /* [in] */ __RPC__in LPCWSTR val) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_Value( /* [retval][out] */ __RPC__deref_out_opt BSTR *pRetVal) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_IsReadOnly( /* [retval][out] */ __RPC__out BOOL *pRetVal) = 0; }; #else /* C style interface */ typedef struct IValueProviderVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in IValueProvider * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ __RPC__deref_out void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in IValueProvider * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in IValueProvider * This); HRESULT ( STDMETHODCALLTYPE *SetValue )( __RPC__in IValueProvider * This, /* [in] */ __RPC__in LPCWSTR val); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_Value )( __RPC__in IValueProvider * This, /* [retval][out] */ __RPC__deref_out_opt BSTR *pRetVal); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_IsReadOnly )( __RPC__in IValueProvider * This, /* [retval][out] */ __RPC__out BOOL *pRetVal); END_INTERFACE } IValueProviderVtbl; interface IValueProvider { CONST_VTBL struct IValueProviderVtbl *lpVtbl; }; #ifdef COBJMACROS #define IValueProvider_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IValueProvider_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IValueProvider_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IValueProvider_SetValue(This,val) \ ( (This)->lpVtbl -> SetValue(This,val) ) #define IValueProvider_get_Value(This,pRetVal) \ ( (This)->lpVtbl -> get_Value(This,pRetVal) ) #define IValueProvider_get_IsReadOnly(This,pRetVal) \ ( (This)->lpVtbl -> get_IsReadOnly(This,pRetVal) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IValueProvider_INTERFACE_DEFINED__ */ #ifndef __IWindowProvider_INTERFACE_DEFINED__ #define __IWindowProvider_INTERFACE_DEFINED__ /* interface IWindowProvider */ /* [unique][uuid][object] */ EXTERN_C const IID IID_IWindowProvider; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("987df77b-db06-4d77-8f8a-86a9c3bb90b9") IWindowProvider : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE SetVisualState( /* [in] */ enum WindowVisualState state) = 0; virtual HRESULT STDMETHODCALLTYPE Close( void) = 0; virtual HRESULT STDMETHODCALLTYPE WaitForInputIdle( /* [in] */ int milliseconds, /* [retval][out] */ __RPC__out BOOL *pRetVal) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_CanMaximize( /* [retval][out] */ __RPC__out BOOL *pRetVal) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_CanMinimize( /* [retval][out] */ __RPC__out BOOL *pRetVal) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_IsModal( /* [retval][out] */ __RPC__out BOOL *pRetVal) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_WindowVisualState( /* [retval][out] */ __RPC__out enum WindowVisualState *pRetVal) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_WindowInteractionState( /* [retval][out] */ __RPC__out enum WindowInteractionState *pRetVal) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_IsTopmost( /* [retval][out] */ __RPC__out BOOL *pRetVal) = 0; }; #else /* C style interface */ typedef struct IWindowProviderVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in IWindowProvider * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ __RPC__deref_out void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in IWindowProvider * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in IWindowProvider * This); HRESULT ( STDMETHODCALLTYPE *SetVisualState )( __RPC__in IWindowProvider * This, /* [in] */ enum WindowVisualState state); HRESULT ( STDMETHODCALLTYPE *Close )( __RPC__in IWindowProvider * This); HRESULT ( STDMETHODCALLTYPE *WaitForInputIdle )( __RPC__in IWindowProvider * This, /* [in] */ int milliseconds, /* [retval][out] */ __RPC__out BOOL *pRetVal); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_CanMaximize )( __RPC__in IWindowProvider * This, /* [retval][out] */ __RPC__out BOOL *pRetVal); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_CanMinimize )( __RPC__in IWindowProvider * This, /* [retval][out] */ __RPC__out BOOL *pRetVal); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_IsModal )( __RPC__in IWindowProvider * This, /* [retval][out] */ __RPC__out BOOL *pRetVal); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_WindowVisualState )( __RPC__in IWindowProvider * This, /* [retval][out] */ __RPC__out enum WindowVisualState *pRetVal); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_WindowInteractionState )( __RPC__in IWindowProvider * This, /* [retval][out] */ __RPC__out enum WindowInteractionState *pRetVal); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_IsTopmost )( __RPC__in IWindowProvider * This, /* [retval][out] */ __RPC__out BOOL *pRetVal); END_INTERFACE } IWindowProviderVtbl; interface IWindowProvider { CONST_VTBL struct IWindowProviderVtbl *lpVtbl; }; #ifdef COBJMACROS #define IWindowProvider_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IWindowProvider_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IWindowProvider_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IWindowProvider_SetVisualState(This,state) \ ( (This)->lpVtbl -> SetVisualState(This,state) ) #define IWindowProvider_Close(This) \ ( (This)->lpVtbl -> Close(This) ) #define IWindowProvider_WaitForInputIdle(This,milliseconds,pRetVal) \ ( (This)->lpVtbl -> WaitForInputIdle(This,milliseconds,pRetVal) ) #define IWindowProvider_get_CanMaximize(This,pRetVal) \ ( (This)->lpVtbl -> get_CanMaximize(This,pRetVal) ) #define IWindowProvider_get_CanMinimize(This,pRetVal) \ ( (This)->lpVtbl -> get_CanMinimize(This,pRetVal) ) #define IWindowProvider_get_IsModal(This,pRetVal) \ ( (This)->lpVtbl -> get_IsModal(This,pRetVal) ) #define IWindowProvider_get_WindowVisualState(This,pRetVal) \ ( (This)->lpVtbl -> get_WindowVisualState(This,pRetVal) ) #define IWindowProvider_get_WindowInteractionState(This,pRetVal) \ ( (This)->lpVtbl -> get_WindowInteractionState(This,pRetVal) ) #define IWindowProvider_get_IsTopmost(This,pRetVal) \ ( (This)->lpVtbl -> get_IsTopmost(This,pRetVal) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IWindowProvider_INTERFACE_DEFINED__ */ #ifndef __ILegacyIAccessibleProvider_INTERFACE_DEFINED__ #define __ILegacyIAccessibleProvider_INTERFACE_DEFINED__ /* interface ILegacyIAccessibleProvider */ /* [unique][uuid][object] */ EXTERN_C const IID IID_ILegacyIAccessibleProvider; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("e44c3566-915d-4070-99c6-047bff5a08f5") ILegacyIAccessibleProvider : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE Select( long flagsSelect) = 0; virtual HRESULT STDMETHODCALLTYPE DoDefaultAction( void) = 0; virtual HRESULT STDMETHODCALLTYPE SetValue( __RPC__in LPCWSTR szValue) = 0; virtual HRESULT STDMETHODCALLTYPE GetIAccessible( /* [retval][out] */ __RPC__deref_out_opt IAccessible **ppAccessible) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_ChildId( /* [retval][out] */ __RPC__out int *pRetVal) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_Name( /* [retval][out] */ __RPC__deref_out_opt BSTR *pszName) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_Value( /* [retval][out] */ __RPC__deref_out_opt BSTR *pszValue) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_Description( /* [retval][out] */ __RPC__deref_out_opt BSTR *pszDescription) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_Role( /* [retval][out] */ __RPC__out DWORD *pdwRole) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_State( /* [retval][out] */ __RPC__out DWORD *pdwState) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_Help( /* [retval][out] */ __RPC__deref_out_opt BSTR *pszHelp) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_KeyboardShortcut( /* [retval][out] */ __RPC__deref_out_opt BSTR *pszKeyboardShortcut) = 0; virtual HRESULT STDMETHODCALLTYPE GetSelection( /* [retval][out] */ __RPC__deref_out_opt SAFEARRAY * *pvarSelectedChildren) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_DefaultAction( /* [retval][out] */ __RPC__deref_out_opt BSTR *pszDefaultAction) = 0; }; #else /* C style interface */ typedef struct ILegacyIAccessibleProviderVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in ILegacyIAccessibleProvider * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ __RPC__deref_out void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in ILegacyIAccessibleProvider * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in ILegacyIAccessibleProvider * This); HRESULT ( STDMETHODCALLTYPE *Select )( __RPC__in ILegacyIAccessibleProvider * This, long flagsSelect); HRESULT ( STDMETHODCALLTYPE *DoDefaultAction )( __RPC__in ILegacyIAccessibleProvider * This); HRESULT ( STDMETHODCALLTYPE *SetValue )( __RPC__in ILegacyIAccessibleProvider * This, __RPC__in LPCWSTR szValue); HRESULT ( STDMETHODCALLTYPE *GetIAccessible )( __RPC__in ILegacyIAccessibleProvider * This, /* [retval][out] */ __RPC__deref_out_opt IAccessible **ppAccessible); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_ChildId )( __RPC__in ILegacyIAccessibleProvider * This, /* [retval][out] */ __RPC__out int *pRetVal); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_Name )( __RPC__in ILegacyIAccessibleProvider * This, /* [retval][out] */ __RPC__deref_out_opt BSTR *pszName); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_Value )( __RPC__in ILegacyIAccessibleProvider * This, /* [retval][out] */ __RPC__deref_out_opt BSTR *pszValue); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_Description )( __RPC__in ILegacyIAccessibleProvider * This, /* [retval][out] */ __RPC__deref_out_opt BSTR *pszDescription); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_Role )( __RPC__in ILegacyIAccessibleProvider * This, /* [retval][out] */ __RPC__out DWORD *pdwRole); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_State )( __RPC__in ILegacyIAccessibleProvider * This, /* [retval][out] */ __RPC__out DWORD *pdwState); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_Help )( __RPC__in ILegacyIAccessibleProvider * This, /* [retval][out] */ __RPC__deref_out_opt BSTR *pszHelp); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_KeyboardShortcut )( __RPC__in ILegacyIAccessibleProvider * This, /* [retval][out] */ __RPC__deref_out_opt BSTR *pszKeyboardShortcut); HRESULT ( STDMETHODCALLTYPE *GetSelection )( __RPC__in ILegacyIAccessibleProvider * This, /* [retval][out] */ __RPC__deref_out_opt SAFEARRAY * *pvarSelectedChildren); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_DefaultAction )( __RPC__in ILegacyIAccessibleProvider * This, /* [retval][out] */ __RPC__deref_out_opt BSTR *pszDefaultAction); END_INTERFACE } ILegacyIAccessibleProviderVtbl; interface ILegacyIAccessibleProvider { CONST_VTBL struct ILegacyIAccessibleProviderVtbl *lpVtbl; }; #ifdef COBJMACROS #define ILegacyIAccessibleProvider_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define ILegacyIAccessibleProvider_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define ILegacyIAccessibleProvider_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define ILegacyIAccessibleProvider_Select(This,flagsSelect) \ ( (This)->lpVtbl -> Select(This,flagsSelect) ) #define ILegacyIAccessibleProvider_DoDefaultAction(This) \ ( (This)->lpVtbl -> DoDefaultAction(This) ) #define ILegacyIAccessibleProvider_SetValue(This,szValue) \ ( (This)->lpVtbl -> SetValue(This,szValue) ) #define ILegacyIAccessibleProvider_GetIAccessible(This,ppAccessible) \ ( (This)->lpVtbl -> GetIAccessible(This,ppAccessible) ) #define ILegacyIAccessibleProvider_get_ChildId(This,pRetVal) \ ( (This)->lpVtbl -> get_ChildId(This,pRetVal) ) #define ILegacyIAccessibleProvider_get_Name(This,pszName) \ ( (This)->lpVtbl -> get_Name(This,pszName) ) #define ILegacyIAccessibleProvider_get_Value(This,pszValue) \ ( (This)->lpVtbl -> get_Value(This,pszValue) ) #define ILegacyIAccessibleProvider_get_Description(This,pszDescription) \ ( (This)->lpVtbl -> get_Description(This,pszDescription) ) #define ILegacyIAccessibleProvider_get_Role(This,pdwRole) \ ( (This)->lpVtbl -> get_Role(This,pdwRole) ) #define ILegacyIAccessibleProvider_get_State(This,pdwState) \ ( (This)->lpVtbl -> get_State(This,pdwState) ) #define ILegacyIAccessibleProvider_get_Help(This,pszHelp) \ ( (This)->lpVtbl -> get_Help(This,pszHelp) ) #define ILegacyIAccessibleProvider_get_KeyboardShortcut(This,pszKeyboardShortcut) \ ( (This)->lpVtbl -> get_KeyboardShortcut(This,pszKeyboardShortcut) ) #define ILegacyIAccessibleProvider_GetSelection(This,pvarSelectedChildren) \ ( (This)->lpVtbl -> GetSelection(This,pvarSelectedChildren) ) #define ILegacyIAccessibleProvider_get_DefaultAction(This,pszDefaultAction) \ ( (This)->lpVtbl -> get_DefaultAction(This,pszDefaultAction) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __ILegacyIAccessibleProvider_INTERFACE_DEFINED__ */ #ifndef __IItemContainerProvider_INTERFACE_DEFINED__ #define __IItemContainerProvider_INTERFACE_DEFINED__ /* interface IItemContainerProvider */ /* [unique][uuid][object] */ EXTERN_C const IID IID_IItemContainerProvider; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("e747770b-39ce-4382-ab30-d8fb3f336f24") IItemContainerProvider : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE FindItemByProperty( /* [in] */ __RPC__in_opt IRawElementProviderSimple *pStartAfter, /* [in] */ PROPERTYID propertyId, /* [in] */ VARIANT value, /* [retval][out] */ __RPC__deref_out_opt IRawElementProviderSimple **pFound) = 0; }; #else /* C style interface */ typedef struct IItemContainerProviderVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in IItemContainerProvider * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ __RPC__deref_out void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in IItemContainerProvider * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in IItemContainerProvider * This); HRESULT ( STDMETHODCALLTYPE *FindItemByProperty )( __RPC__in IItemContainerProvider * This, /* [in] */ __RPC__in_opt IRawElementProviderSimple *pStartAfter, /* [in] */ PROPERTYID propertyId, /* [in] */ VARIANT value, /* [retval][out] */ __RPC__deref_out_opt IRawElementProviderSimple **pFound); END_INTERFACE } IItemContainerProviderVtbl; interface IItemContainerProvider { CONST_VTBL struct IItemContainerProviderVtbl *lpVtbl; }; #ifdef COBJMACROS #define IItemContainerProvider_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IItemContainerProvider_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IItemContainerProvider_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IItemContainerProvider_FindItemByProperty(This,pStartAfter,propertyId,value,pFound) \ ( (This)->lpVtbl -> FindItemByProperty(This,pStartAfter,propertyId,value,pFound) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IItemContainerProvider_INTERFACE_DEFINED__ */ #ifndef __IVirtualizedItemProvider_INTERFACE_DEFINED__ #define __IVirtualizedItemProvider_INTERFACE_DEFINED__ /* interface IVirtualizedItemProvider */ /* [unique][uuid][object] */ EXTERN_C const IID IID_IVirtualizedItemProvider; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("cb98b665-2d35-4fac-ad35-f3c60d0c0b8b") IVirtualizedItemProvider : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE Realize( void) = 0; }; #else /* C style interface */ typedef struct IVirtualizedItemProviderVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in IVirtualizedItemProvider * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ __RPC__deref_out void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in IVirtualizedItemProvider * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in IVirtualizedItemProvider * This); HRESULT ( STDMETHODCALLTYPE *Realize )( __RPC__in IVirtualizedItemProvider * This); END_INTERFACE } IVirtualizedItemProviderVtbl; interface IVirtualizedItemProvider { CONST_VTBL struct IVirtualizedItemProviderVtbl *lpVtbl; }; #ifdef COBJMACROS #define IVirtualizedItemProvider_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IVirtualizedItemProvider_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IVirtualizedItemProvider_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IVirtualizedItemProvider_Realize(This) \ ( (This)->lpVtbl -> Realize(This) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IVirtualizedItemProvider_INTERFACE_DEFINED__ */ #ifndef __ITextRangeProvider_INTERFACE_DEFINED__ #define __ITextRangeProvider_INTERFACE_DEFINED__ /* interface ITextRangeProvider */ /* [unique][uuid][object] */ EXTERN_C const IID IID_ITextRangeProvider; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("5347ad7b-c355-46f8-aff5-909033582f63") ITextRangeProvider : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE Clone( /* [retval][out] */ __RPC__deref_out_opt ITextRangeProvider **pRetVal) = 0; virtual HRESULT STDMETHODCALLTYPE Compare( /* [in] */ __RPC__in_opt ITextRangeProvider *range, /* [retval][out] */ __RPC__out BOOL *pRetVal) = 0; virtual HRESULT STDMETHODCALLTYPE CompareEndpoints( /* [in] */ enum TextPatternRangeEndpoint endpoint, /* [in] */ __RPC__in_opt ITextRangeProvider *targetRange, /* [in] */ enum TextPatternRangeEndpoint targetEndpoint, /* [retval][out] */ __RPC__out int *pRetVal) = 0; virtual HRESULT STDMETHODCALLTYPE ExpandToEnclosingUnit( /* [in] */ enum TextUnit unit) = 0; virtual HRESULT STDMETHODCALLTYPE FindAttribute( /* [in] */ TEXTATTRIBUTEID attributeId, /* [in] */ VARIANT val, /* [in] */ BOOL backward, /* [retval][out] */ __RPC__deref_out_opt ITextRangeProvider **pRetVal) = 0; virtual HRESULT STDMETHODCALLTYPE FindText( /* [in] */ __RPC__in BSTR text, /* [in] */ BOOL backward, /* [in] */ BOOL ignoreCase, /* [retval][out] */ __RPC__deref_out_opt ITextRangeProvider **pRetVal) = 0; virtual HRESULT STDMETHODCALLTYPE GetAttributeValue( /* [in] */ TEXTATTRIBUTEID attributeId, /* [retval][out] */ __RPC__out VARIANT *pRetVal) = 0; virtual HRESULT STDMETHODCALLTYPE GetBoundingRectangles( /* [retval][out] */ __RPC__deref_out_opt SAFEARRAY * *pRetVal) = 0; virtual HRESULT STDMETHODCALLTYPE GetEnclosingElement( /* [retval][out] */ __RPC__deref_out_opt IRawElementProviderSimple **pRetVal) = 0; virtual HRESULT STDMETHODCALLTYPE GetText( /* [in] */ int maxLength, /* [retval][out] */ __RPC__deref_out_opt BSTR *pRetVal) = 0; virtual HRESULT STDMETHODCALLTYPE Move( /* [in] */ enum TextUnit unit, /* [in] */ int count, /* [retval][out] */ __RPC__out int *pRetVal) = 0; virtual HRESULT STDMETHODCALLTYPE MoveEndpointByUnit( /* [in] */ enum TextPatternRangeEndpoint endpoint, /* [in] */ enum TextUnit unit, /* [in] */ int count, /* [retval][out] */ __RPC__out int *pRetVal) = 0; virtual HRESULT STDMETHODCALLTYPE MoveEndpointByRange( /* [in] */ enum TextPatternRangeEndpoint endpoint, /* [in] */ __RPC__in_opt ITextRangeProvider *targetRange, /* [in] */ enum TextPatternRangeEndpoint targetEndpoint) = 0; virtual HRESULT STDMETHODCALLTYPE Select( void) = 0; virtual HRESULT STDMETHODCALLTYPE AddToSelection( void) = 0; virtual HRESULT STDMETHODCALLTYPE RemoveFromSelection( void) = 0; virtual HRESULT STDMETHODCALLTYPE ScrollIntoView( /* [in] */ BOOL alignToTop) = 0; virtual HRESULT STDMETHODCALLTYPE GetChildren( /* [retval][out] */ __RPC__deref_out_opt SAFEARRAY * *pRetVal) = 0; }; #else /* C style interface */ typedef struct ITextRangeProviderVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in ITextRangeProvider * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ __RPC__deref_out void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in ITextRangeProvider * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in ITextRangeProvider * This); HRESULT ( STDMETHODCALLTYPE *Clone )( __RPC__in ITextRangeProvider * This, /* [retval][out] */ __RPC__deref_out_opt ITextRangeProvider **pRetVal); HRESULT ( STDMETHODCALLTYPE *Compare )( __RPC__in ITextRangeProvider * This, /* [in] */ __RPC__in_opt ITextRangeProvider *range, /* [retval][out] */ __RPC__out BOOL *pRetVal); HRESULT ( STDMETHODCALLTYPE *CompareEndpoints )( __RPC__in ITextRangeProvider * This, /* [in] */ enum TextPatternRangeEndpoint endpoint, /* [in] */ __RPC__in_opt ITextRangeProvider *targetRange, /* [in] */ enum TextPatternRangeEndpoint targetEndpoint, /* [retval][out] */ __RPC__out int *pRetVal); HRESULT ( STDMETHODCALLTYPE *ExpandToEnclosingUnit )( __RPC__in ITextRangeProvider * This, /* [in] */ enum TextUnit unit); HRESULT ( STDMETHODCALLTYPE *FindAttribute )( __RPC__in ITextRangeProvider * This, /* [in] */ TEXTATTRIBUTEID attributeId, /* [in] */ VARIANT val, /* [in] */ BOOL backward, /* [retval][out] */ __RPC__deref_out_opt ITextRangeProvider **pRetVal); HRESULT ( STDMETHODCALLTYPE *FindText )( __RPC__in ITextRangeProvider * This, /* [in] */ __RPC__in BSTR text, /* [in] */ BOOL backward, /* [in] */ BOOL ignoreCase, /* [retval][out] */ __RPC__deref_out_opt ITextRangeProvider **pRetVal); HRESULT ( STDMETHODCALLTYPE *GetAttributeValue )( __RPC__in ITextRangeProvider * This, /* [in] */ TEXTATTRIBUTEID attributeId, /* [retval][out] */ __RPC__out VARIANT *pRetVal); HRESULT ( STDMETHODCALLTYPE *GetBoundingRectangles )( __RPC__in ITextRangeProvider * This, /* [retval][out] */ __RPC__deref_out_opt SAFEARRAY * *pRetVal); HRESULT ( STDMETHODCALLTYPE *GetEnclosingElement )( __RPC__in ITextRangeProvider * This, /* [retval][out] */ __RPC__deref_out_opt IRawElementProviderSimple **pRetVal); HRESULT ( STDMETHODCALLTYPE *GetText )( __RPC__in ITextRangeProvider * This, /* [in] */ int maxLength, /* [retval][out] */ __RPC__deref_out_opt BSTR *pRetVal); HRESULT ( STDMETHODCALLTYPE *Move )( __RPC__in ITextRangeProvider * This, /* [in] */ enum TextUnit unit, /* [in] */ int count, /* [retval][out] */ __RPC__out int *pRetVal); HRESULT ( STDMETHODCALLTYPE *MoveEndpointByUnit )( __RPC__in ITextRangeProvider * This, /* [in] */ enum TextPatternRangeEndpoint endpoint, /* [in] */ enum TextUnit unit, /* [in] */ int count, /* [retval][out] */ __RPC__out int *pRetVal); HRESULT ( STDMETHODCALLTYPE *MoveEndpointByRange )( __RPC__in ITextRangeProvider * This, /* [in] */ enum TextPatternRangeEndpoint endpoint, /* [in] */ __RPC__in_opt ITextRangeProvider *targetRange, /* [in] */ enum TextPatternRangeEndpoint targetEndpoint); HRESULT ( STDMETHODCALLTYPE *Select )( __RPC__in ITextRangeProvider * This); HRESULT ( STDMETHODCALLTYPE *AddToSelection )( __RPC__in ITextRangeProvider * This); HRESULT ( STDMETHODCALLTYPE *RemoveFromSelection )( __RPC__in ITextRangeProvider * This); HRESULT ( STDMETHODCALLTYPE *ScrollIntoView )( __RPC__in ITextRangeProvider * This, /* [in] */ BOOL alignToTop); HRESULT ( STDMETHODCALLTYPE *GetChildren )( __RPC__in ITextRangeProvider * This, /* [retval][out] */ __RPC__deref_out_opt SAFEARRAY * *pRetVal); END_INTERFACE } ITextRangeProviderVtbl; interface ITextRangeProvider { CONST_VTBL struct ITextRangeProviderVtbl *lpVtbl; }; #ifdef COBJMACROS #define ITextRangeProvider_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define ITextRangeProvider_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define ITextRangeProvider_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define ITextRangeProvider_Clone(This,pRetVal) \ ( (This)->lpVtbl -> Clone(This,pRetVal) ) #define ITextRangeProvider_Compare(This,range,pRetVal) \ ( (This)->lpVtbl -> Compare(This,range,pRetVal) ) #define ITextRangeProvider_CompareEndpoints(This,endpoint,targetRange,targetEndpoint,pRetVal) \ ( (This)->lpVtbl -> CompareEndpoints(This,endpoint,targetRange,targetEndpoint,pRetVal) ) #define ITextRangeProvider_ExpandToEnclosingUnit(This,unit) \ ( (This)->lpVtbl -> ExpandToEnclosingUnit(This,unit) ) #define ITextRangeProvider_FindAttribute(This,attributeId,val,backward,pRetVal) \ ( (This)->lpVtbl -> FindAttribute(This,attributeId,val,backward,pRetVal) ) #define ITextRangeProvider_FindText(This,text,backward,ignoreCase,pRetVal) \ ( (This)->lpVtbl -> FindText(This,text,backward,ignoreCase,pRetVal) ) #define ITextRangeProvider_GetAttributeValue(This,attributeId,pRetVal) \ ( (This)->lpVtbl -> GetAttributeValue(This,attributeId,pRetVal) ) #define ITextRangeProvider_GetBoundingRectangles(This,pRetVal) \ ( (This)->lpVtbl -> GetBoundingRectangles(This,pRetVal) ) #define ITextRangeProvider_GetEnclosingElement(This,pRetVal) \ ( (This)->lpVtbl -> GetEnclosingElement(This,pRetVal) ) #define ITextRangeProvider_GetText(This,maxLength,pRetVal) \ ( (This)->lpVtbl -> GetText(This,maxLength,pRetVal) ) #define ITextRangeProvider_Move(This,unit,count,pRetVal) \ ( (This)->lpVtbl -> Move(This,unit,count,pRetVal) ) #define ITextRangeProvider_MoveEndpointByUnit(This,endpoint,unit,count,pRetVal) \ ( (This)->lpVtbl -> MoveEndpointByUnit(This,endpoint,unit,count,pRetVal) ) #define ITextRangeProvider_MoveEndpointByRange(This,endpoint,targetRange,targetEndpoint) \ ( (This)->lpVtbl -> MoveEndpointByRange(This,endpoint,targetRange,targetEndpoint) ) #define ITextRangeProvider_Select(This) \ ( (This)->lpVtbl -> Select(This) ) #define ITextRangeProvider_AddToSelection(This) \ ( (This)->lpVtbl -> AddToSelection(This) ) #define ITextRangeProvider_RemoveFromSelection(This) \ ( (This)->lpVtbl -> RemoveFromSelection(This) ) #define ITextRangeProvider_ScrollIntoView(This,alignToTop) \ ( (This)->lpVtbl -> ScrollIntoView(This,alignToTop) ) #define ITextRangeProvider_GetChildren(This,pRetVal) \ ( (This)->lpVtbl -> GetChildren(This,pRetVal) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __ITextRangeProvider_INTERFACE_DEFINED__ */ #ifndef __ITextProvider_INTERFACE_DEFINED__ #define __ITextProvider_INTERFACE_DEFINED__ /* interface ITextProvider */ /* [unique][uuid][object] */ EXTERN_C const IID IID_ITextProvider; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("3589c92c-63f3-4367-99bb-ada653b77cf2") ITextProvider : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE GetSelection( /* [retval][out] */ __RPC__deref_out_opt SAFEARRAY * *pRetVal) = 0; virtual HRESULT STDMETHODCALLTYPE GetVisibleRanges( /* [retval][out] */ __RPC__deref_out_opt SAFEARRAY * *pRetVal) = 0; virtual HRESULT STDMETHODCALLTYPE RangeFromChild( /* [in] */ __RPC__in_opt IRawElementProviderSimple *childElement, /* [retval][out] */ __RPC__deref_out_opt ITextRangeProvider **pRetVal) = 0; virtual HRESULT STDMETHODCALLTYPE RangeFromPoint( /* [in] */ struct UiaPoint point, /* [retval][out] */ __RPC__deref_out_opt ITextRangeProvider **pRetVal) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_DocumentRange( /* [retval][out] */ __RPC__deref_out_opt ITextRangeProvider **pRetVal) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_SupportedTextSelection( /* [retval][out] */ __RPC__out enum SupportedTextSelection *pRetVal) = 0; }; #else /* C style interface */ typedef struct ITextProviderVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in ITextProvider * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ __RPC__deref_out void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in ITextProvider * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in ITextProvider * This); HRESULT ( STDMETHODCALLTYPE *GetSelection )( __RPC__in ITextProvider * This, /* [retval][out] */ __RPC__deref_out_opt SAFEARRAY * *pRetVal); HRESULT ( STDMETHODCALLTYPE *GetVisibleRanges )( __RPC__in ITextProvider * This, /* [retval][out] */ __RPC__deref_out_opt SAFEARRAY * *pRetVal); HRESULT ( STDMETHODCALLTYPE *RangeFromChild )( __RPC__in ITextProvider * This, /* [in] */ __RPC__in_opt IRawElementProviderSimple *childElement, /* [retval][out] */ __RPC__deref_out_opt ITextRangeProvider **pRetVal); HRESULT ( STDMETHODCALLTYPE *RangeFromPoint )( __RPC__in ITextProvider * This, /* [in] */ struct UiaPoint point, /* [retval][out] */ __RPC__deref_out_opt ITextRangeProvider **pRetVal); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_DocumentRange )( __RPC__in ITextProvider * This, /* [retval][out] */ __RPC__deref_out_opt ITextRangeProvider **pRetVal); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_SupportedTextSelection )( __RPC__in ITextProvider * This, /* [retval][out] */ __RPC__out enum SupportedTextSelection *pRetVal); END_INTERFACE } ITextProviderVtbl; interface ITextProvider { CONST_VTBL struct ITextProviderVtbl *lpVtbl; }; #ifdef COBJMACROS #define ITextProvider_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define ITextProvider_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define ITextProvider_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define ITextProvider_GetSelection(This,pRetVal) \ ( (This)->lpVtbl -> GetSelection(This,pRetVal) ) #define ITextProvider_GetVisibleRanges(This,pRetVal) \ ( (This)->lpVtbl -> GetVisibleRanges(This,pRetVal) ) #define ITextProvider_RangeFromChild(This,childElement,pRetVal) \ ( (This)->lpVtbl -> RangeFromChild(This,childElement,pRetVal) ) #define ITextProvider_RangeFromPoint(This,point,pRetVal) \ ( (This)->lpVtbl -> RangeFromPoint(This,point,pRetVal) ) #define ITextProvider_get_DocumentRange(This,pRetVal) \ ( (This)->lpVtbl -> get_DocumentRange(This,pRetVal) ) #define ITextProvider_get_SupportedTextSelection(This,pRetVal) \ ( (This)->lpVtbl -> get_SupportedTextSelection(This,pRetVal) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __ITextProvider_INTERFACE_DEFINED__ */ #ifndef __IUIAutomationPatternInstance_INTERFACE_DEFINED__ #define __IUIAutomationPatternInstance_INTERFACE_DEFINED__ /* interface IUIAutomationPatternInstance */ /* [unique][uuid][object] */ EXTERN_C const IID IID_IUIAutomationPatternInstance; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("c03a7fe4-9431-409f-bed8-ae7c2299bc8d") IUIAutomationPatternInstance : public IUnknown { public: virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetProperty( /* [in] */ UINT index, /* [in] */ BOOL cached, /* [in] */ enum UIAutomationType type, /* [out] */ void *pPtr) = 0; virtual /* [local] */ HRESULT STDMETHODCALLTYPE CallMethod( /* [in] */ UINT index, /* [in] */ const struct UIAutomationParameter *pParams, /* [in] */ UINT cParams) = 0; }; #else /* C style interface */ typedef struct IUIAutomationPatternInstanceVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in IUIAutomationPatternInstance * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ __RPC__deref_out void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in IUIAutomationPatternInstance * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in IUIAutomationPatternInstance * This); /* [local] */ HRESULT ( STDMETHODCALLTYPE *GetProperty )( IUIAutomationPatternInstance * This, /* [in] */ UINT index, /* [in] */ BOOL cached, /* [in] */ enum UIAutomationType type, /* [out] */ void *pPtr); /* [local] */ HRESULT ( STDMETHODCALLTYPE *CallMethod )( IUIAutomationPatternInstance * This, /* [in] */ UINT index, /* [in] */ const struct UIAutomationParameter *pParams, /* [in] */ UINT cParams); END_INTERFACE } IUIAutomationPatternInstanceVtbl; interface IUIAutomationPatternInstance { CONST_VTBL struct IUIAutomationPatternInstanceVtbl *lpVtbl; }; #ifdef COBJMACROS #define IUIAutomationPatternInstance_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IUIAutomationPatternInstance_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IUIAutomationPatternInstance_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IUIAutomationPatternInstance_GetProperty(This,index,cached,type,pPtr) \ ( (This)->lpVtbl -> GetProperty(This,index,cached,type,pPtr) ) #define IUIAutomationPatternInstance_CallMethod(This,index,pParams,cParams) \ ( (This)->lpVtbl -> CallMethod(This,index,pParams,cParams) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IUIAutomationPatternInstance_INTERFACE_DEFINED__ */ #ifndef __IUIAutomationPatternHandler_INTERFACE_DEFINED__ #define __IUIAutomationPatternHandler_INTERFACE_DEFINED__ /* interface IUIAutomationPatternHandler */ /* [unique][uuid][object] */ EXTERN_C const IID IID_IUIAutomationPatternHandler; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("d97022f3-a947-465e-8b2a-ac4315fa54e8") IUIAutomationPatternHandler : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE CreateClientWrapper( /* [in] */ __RPC__in_opt IUIAutomationPatternInstance *pPatternInstance, /* [out] */ __RPC__deref_out_opt IUnknown **pClientWrapper) = 0; virtual /* [local] */ HRESULT STDMETHODCALLTYPE Dispatch( /* [in] */ IUnknown *pTarget, /* [in] */ UINT index, /* [in] */ const struct UIAutomationParameter *pParams, /* [in] */ UINT cParams) = 0; }; #else /* C style interface */ typedef struct IUIAutomationPatternHandlerVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in IUIAutomationPatternHandler * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ __RPC__deref_out void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in IUIAutomationPatternHandler * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in IUIAutomationPatternHandler * This); HRESULT ( STDMETHODCALLTYPE *CreateClientWrapper )( __RPC__in IUIAutomationPatternHandler * This, /* [in] */ __RPC__in_opt IUIAutomationPatternInstance *pPatternInstance, /* [out] */ __RPC__deref_out_opt IUnknown **pClientWrapper); /* [local] */ HRESULT ( STDMETHODCALLTYPE *Dispatch )( IUIAutomationPatternHandler * This, /* [in] */ IUnknown *pTarget, /* [in] */ UINT index, /* [in] */ const struct UIAutomationParameter *pParams, /* [in] */ UINT cParams); END_INTERFACE } IUIAutomationPatternHandlerVtbl; interface IUIAutomationPatternHandler { CONST_VTBL struct IUIAutomationPatternHandlerVtbl *lpVtbl; }; #ifdef COBJMACROS #define IUIAutomationPatternHandler_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IUIAutomationPatternHandler_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IUIAutomationPatternHandler_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IUIAutomationPatternHandler_CreateClientWrapper(This,pPatternInstance,pClientWrapper) \ ( (This)->lpVtbl -> CreateClientWrapper(This,pPatternInstance,pClientWrapper) ) #define IUIAutomationPatternHandler_Dispatch(This,pTarget,index,pParams,cParams) \ ( (This)->lpVtbl -> Dispatch(This,pTarget,index,pParams,cParams) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IUIAutomationPatternHandler_INTERFACE_DEFINED__ */ #ifndef __IUIAutomationRegistrar_INTERFACE_DEFINED__ #define __IUIAutomationRegistrar_INTERFACE_DEFINED__ /* interface IUIAutomationRegistrar */ /* [unique][uuid][object] */ EXTERN_C const IID IID_IUIAutomationRegistrar; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("8609c4ec-4a1a-4d88-a357-5a66e060e1cf") IUIAutomationRegistrar : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE RegisterProperty( /* [in] */ __RPC__in const struct UIAutomationPropertyInfo *property, /* [out] */ __RPC__out PROPERTYID *propertyId) = 0; virtual HRESULT STDMETHODCALLTYPE RegisterEvent( /* [in] */ __RPC__in const struct UIAutomationEventInfo *event, /* [out] */ __RPC__out EVENTID *eventId) = 0; virtual HRESULT STDMETHODCALLTYPE RegisterPattern( /* [in] */ __RPC__in const struct UIAutomationPatternInfo *pattern, /* [out] */ __RPC__out PATTERNID *pPatternId, /* [out] */ __RPC__out PROPERTYID *pPatternAvailablePropertyId, /* [in] */ UINT propertyIdCount, /* [size_is][out] */ __RPC__out_ecount_full(propertyIdCount) PROPERTYID *pPropertyIds, /* [in] */ UINT eventIdCount, /* [size_is][out] */ __RPC__out_ecount_full(eventIdCount) EVENTID *pEventIds) = 0; }; #else /* C style interface */ typedef struct IUIAutomationRegistrarVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in IUIAutomationRegistrar * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ __RPC__deref_out void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in IUIAutomationRegistrar * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in IUIAutomationRegistrar * This); HRESULT ( STDMETHODCALLTYPE *RegisterProperty )( __RPC__in IUIAutomationRegistrar * This, /* [in] */ __RPC__in const struct UIAutomationPropertyInfo *property, /* [out] */ __RPC__out PROPERTYID *propertyId); HRESULT ( STDMETHODCALLTYPE *RegisterEvent )( __RPC__in IUIAutomationRegistrar * This, /* [in] */ __RPC__in const struct UIAutomationEventInfo *event, /* [out] */ __RPC__out EVENTID *eventId); HRESULT ( STDMETHODCALLTYPE *RegisterPattern )( __RPC__in IUIAutomationRegistrar * This, /* [in] */ __RPC__in const struct UIAutomationPatternInfo *pattern, /* [out] */ __RPC__out PATTERNID *pPatternId, /* [out] */ __RPC__out PROPERTYID *pPatternAvailablePropertyId, /* [in] */ UINT propertyIdCount, /* [size_is][out] */ __RPC__out_ecount_full(propertyIdCount) PROPERTYID *pPropertyIds, /* [in] */ UINT eventIdCount, /* [size_is][out] */ __RPC__out_ecount_full(eventIdCount) EVENTID *pEventIds); END_INTERFACE } IUIAutomationRegistrarVtbl; interface IUIAutomationRegistrar { CONST_VTBL struct IUIAutomationRegistrarVtbl *lpVtbl; }; #ifdef COBJMACROS #define IUIAutomationRegistrar_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IUIAutomationRegistrar_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IUIAutomationRegistrar_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IUIAutomationRegistrar_RegisterProperty(This,property,propertyId) \ ( (This)->lpVtbl -> RegisterProperty(This,property,propertyId) ) #define IUIAutomationRegistrar_RegisterEvent(This,event,eventId) \ ( (This)->lpVtbl -> RegisterEvent(This,event,eventId) ) #define IUIAutomationRegistrar_RegisterPattern(This,pattern,pPatternId,pPatternAvailablePropertyId,propertyIdCount,pPropertyIds,eventIdCount,pEventIds) \ ( (This)->lpVtbl -> RegisterPattern(This,pattern,pPatternId,pPatternAvailablePropertyId,propertyIdCount,pPropertyIds,eventIdCount,pEventIds) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IUIAutomationRegistrar_INTERFACE_DEFINED__ */ EXTERN_C const CLSID CLSID_CUIAutomationRegistrar; #ifdef __cplusplus class DECLSPEC_UUID("6e29fabf-9977-42d1-8d0e-ca7e61ad87e6") CUIAutomationRegistrar; #endif #endif /* __UIA_LIBRARY_DEFINED__ */ /* Additional Prototypes for ALL interfaces */ /* end of Additional Prototypes */ #ifdef __cplusplus } #endif #endif
[ "mail0668@gmail.com" ]
mail0668@gmail.com
2b2115e3a7101f8d25ab299b650022d83d01a227
c5c80d70e4c917c770beadb92b8d67a3a364232b
/ml1150258/Examples/ArrayExampleFill2DigitsOutputLessThanMaximum/main.cpp
eb8bde965fc8cd78539302cab531b0e13b54f046
[]
no_license
Riverside-City-College-Computer-Science/Summer14_CSC5_46024
66c3df6630522116b27affdc29c05097a8188890
a7d3ab69fc6798da52747b3833721d931b53f85b
refs/heads/master
2021-01-01T16:39:06.714253
2014-07-31T04:44:19
2014-07-31T04:44:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,803
cpp
/* * File: main.cpp * Author: Dr. Mark E. Lehr * Created on July 21, 2014, 12:42 PM */ //System Libraries #include <cstdlib> #include <ctime> #include <iostream> using namespace std; //Global constants //Function Prototypes void filAray(int [],int); void prnAray(const int [],int,int); float average(const int [],int); int minimum(const int [],int); int maximum(const int [],int); float average(const int [],int,int&,int&); //Execution Begins Here! int main(int argc, char** argv) { //Declare the array and its maximum size const int MAXSZ=200; int array[MAXSZ]; int actSize,nRows,nCols,mxAray,mnAray; //Set the random number seed srand(static_cast<unsigned int>(time(0))); //Prompt for inputs cout<<"Size of Array to fill <= 200"<<endl; cin>>actSize; cout<<"How many rows to display <= Size of the Array?"<<endl; cin>>nRows; //Calculate the number of columns nCols=actSize/nRows; //Fill the Array filAray(array,actSize); //Print the Array prnAray(array,actSize,nCols); //Output some interesting information cout<<"The average = "<<average(array,actSize)<<endl; cout<<"The average = "<<average(array,actSize,mxAray,mnAray)<<endl; cout<<"The max value = "<<mxAray<<endl; cout<<"The min value = "<<mnAray<<endl; mxAray=maximum(array,actSize); mnAray=minimum(array,actSize); cout<<"The max value = "<<mxAray<<endl; cout<<"The min value = "<<mnAray<<endl; //Exit stage right! return 0; } //Function that finds the min an array //Inputs // a -> An array of size >=n // n -> The actual size not the maximum size of the array //Outputs // mn -> max value of the array int minimum(const int a[],int n){ int mn=a[0]; //Loop for the sum and max/min for(int i=1;i<n;i++){ if(mn>a[i])mn=a[i]; } return mn; } //Function that finds the max an array //Inputs // a -> An array of size >=n // n -> The actual size not the maximum size of the array //Outputs // mx -> max value of the array int maximum(const int a[],int n){ int mx=a[0]; //Loop for the sum and max/min for(int i=1;i<n;i++){ if(mx<a[i])mx=a[i]; } return mx; } //Function that averages an array //Inputs // a -> An array of size >=n // n -> The actual size not the maximum size of the array //Outputs // average -> average of the array // mx -> max value of the array // mn -> min value of the array float average(const int a[],int n, int &mx, int &mn){ //Declare a sum and initialize min and max float sum=a[0]; mx=mn=a[0]; //Loop for the sum and max/min for(int i=1;i<n;i++){ sum+=a[i]; if(mx<a[i])mx=a[i]; if(mn>a[i])mn=a[i]; } return sum/n; } //Function that averages an array //Inputs // a -> An array of size >=n // n -> The actual size not the maximum size of the array //Outputs // average -> average of the array float average(const int a[],int n){ //Declare a sum float sum=0.0f; for(int i=0;i<n;i++){ sum+=a[i]; } return sum/n; } //Function that outputs the entire actual size of the array //Inputs // a -> The random 2 digit array // n -> The actual size of the array // c -> The number of columns void prnAray(const int a[],int n,int c){ //Declare any variables cout<<endl<<endl; for(int i=0;i<n;i++){ cout<<a[i]<<" "; if(i%c==(c-1))cout<<endl; } cout<<endl<<endl; } //Function that fills the array with 2 digit numbers //Inputs // a -> An array of size >=n // n -> The actual size not the maximum size of the array //Outputs // a -> as well filled void filAray(int a[],int n){ for(int i=0;i<n;i++){ a[i]=rand()%90+10; } }
[ "mark.lehr@rcc.edu" ]
mark.lehr@rcc.edu
c40236116186e40aca3d9bd8ff97e36a3723db5d
62c976bbd8ba0e2bbfa251ba21a24b3005484dd2
/Naranjas por Kilo/Naranjas por Kilo/main.cpp
3326ee14359df32f3689e3c816895c672e6239c9
[]
no_license
PatricioSaldivar/FundamentsOfProgramming
7e5c81c79cd48fd273880d0590630d52c65284d7
f66ee4cd7b34db72111c5bcb303e0b61900996a6
refs/heads/master
2020-03-29T06:56:07.857308
2018-09-20T17:37:38
2018-09-20T17:37:38
149,634,691
0
0
null
null
null
null
UTF-8
C++
false
false
995
cpp
//Naranjas por Kilo // // // // Pato Saldivar // 17/08/17. // Este programa sirve para encontar el precio de una cierta cantidad de naranjas en kilos. // Analisis: Calcular el precio por kilo de las naranjas // Algoritmo: 1. Pedir los kilos que se compraron // 2. Pedir el precio total que se pago // 3. Resultado = Precio/Kilos // 4. Mostrar resultado // // Casos Prueba Kilos de Naranja: 2 // Precio Total: 10 // Precio por kilo: 5 #include <iostream> using namespace std; int main (){ // insert code here... double kilos, Precio, Precio_por_kilo; cout<< "Cuantos kilos de Naranja Compraras? "; cin>> kilos; cout<< "Cuanto pagaste por los " <<kilos<< " de naranja? "; cin>> Precio; Precio_por_kilo= Precio/kilos; cout<< "El precio por kilo es de " << Precio_por_kilo << " pesos por kilo."; return 0; }
[ "patricio.saldivarf@gmail.com" ]
patricio.saldivarf@gmail.com
f9ac089d29f7a1c99881d284383163b9b29858b2
2c0852fca78065b181d74da5b4c943a698ab342a
/include/UniOP.h
68207694e050d07e66013b5dfab92184f432979c
[ "Apache-2.0" ]
permissive
chncwang/N3LDG
bd56d07e366f1598191a8335b4152bceb5054db9
505011639876756041b0a53f555e8251e2a502c3
refs/heads/master
2021-06-07T07:55:48.496329
2021-05-09T10:56:45
2021-05-09T10:56:45
92,940,925
0
3
null
2018-04-30T12:46:08
2017-05-31T11:49:11
C++
UTF-8
C++
false
false
22,839
h
#ifndef UNIOP_H_ #define UNIOP_H_ /* * UniOP.h: * a simple feed forward neural operation, unary input. * * Created on: Apr 22, 2017 * Author: mszhang */ #include "Param.h" #include "MyLib.h" #include "Node.h" #include "Graph.h" #include "ModelUpdate.h" #include <cstdlib> #include "profiler.h" class UniParams { public: Param W; Param b; bool bUseB; public: UniParams() { bUseB = true; } inline void exportAdaParams(ModelUpdate& ada) { ada.addParam(&W); if (bUseB) { ada.addParam(&b); } } inline void initial(int nOSize, int nISize, bool useB = true) { W.initial(nOSize, nISize); bUseB = useB; if (bUseB) { b.initial(nOSize, 1); } } inline void save(std::ofstream &os) const { os << bUseB << std::endl; W.save(os); if (bUseB) { b.save(os); } } inline void load(std::ifstream &is) { is >> bUseB; W.load(is); if (bUseB) { b.load(is); } } }; // non-linear feed-forward node // input nodes should be specified by forward function // for input variables, we exploit column vector, // which means a concrete input vector x_i is represented by x(0, i), x(1, i), ..., x(n, i) class UniNode : public Node { public: PNode in; UniParams* param; dtype(*activate)(const dtype&); // activation function dtype(*derivate)(const dtype&, const dtype&); // derivation function of activation function Tensor1D ty, lty; public: UniNode() : Node() { in = NULL; activate = ftanh; derivate = dtanh; param = NULL; node_type = "uni"; } ~UniNode() { in = NULL; } inline void init(int ndim, dtype dropout) { Node::init(ndim, dropout); ty.init(ndim); lty.init(ndim); } inline void setParam(UniParams* paramInit) { param = paramInit; } inline void clearValue() { Node::clearValue(); in = NULL; } // define the activate function and its derivation form inline void setFunctions(dtype(*f)(const dtype&), dtype(*f_deri)(const dtype&, const dtype&)) { activate = f; derivate = f_deri; } void forward(Graph *cg, PNode x) { in = x; degree = 0; in->addParent(this); cg->addNode(this); } inline void compute() { ty.mat() = param->W.val.mat() * in->val.mat(); if (param->bUseB) { ty.vec() += param->b.val.vec(); } val.vec() = ty.vec().unaryExpr(ptr_fun(activate)); } inline void backward() { lty.vec() = loss.vec() * ty.vec().binaryExpr(val.vec(), ptr_fun(derivate)); param->W.grad.mat() += lty.mat() * in->val.tmat(); if (param->bUseB) { param->b.grad.vec() += lty.vec(); } in->loss.mat() += param->W.val.mat().transpose() * lty.mat(); } inline PExecute generate(bool bTrain, dtype cur_drop_factor); // better to rewrite for deep understanding bool typeEqual(PNode other) override { bool result = Node::typeEqual(other); if (!result) return false; UniNode* conv_other = (UniNode*)other; if (param != conv_other->param) { return false; } if (activate != conv_other->activate || derivate != conv_other->derivate) { return false; } return true; } size_t typeHashCode() const override { void *act = reinterpret_cast<void*>(activate); void *de = reinterpret_cast<void*>(derivate); return Node::typeHashCode() ^ ::typeHashCode(param) ^ ::typeHashCode(act) ^ (::typeHashCode(de) << 1); } #if USE_GPU void toNodeInfo(NodeInfo &info) const override { Node::toNodeInfo(info); info.input_vals.push_back(in->val.value); info.input_losses.push_back(in->loss.value); } #endif }; // non-linear feed-forward node // input nodes should be specified by forward function // for input variables, we exploit column vector, // which means a concrete input vector x_i is represented by x(0, i), x(1, i), ..., x(n, i) class LinearUniNode : public Node { public: PNode in; UniParams* param; public: LinearUniNode() : Node() { in = NULL; param = NULL; node_type = "linear_uni"; } inline void setParam(UniParams* paramInit) { param = paramInit; } inline void clearValue() { Node::clearValue(); in = NULL; } public: void forward(Graph *cg, PNode x) { in = x; degree = 0; in->addParent(this); cg->addNode(this); } public: inline void compute() { val.mat() = param->W.val.mat() * in->val.mat(); if (param->bUseB) { val.vec() += param->b.val.vec(); } } inline void backward() { param->W.grad.mat() += loss.mat() * in->val.tmat(); if (param->bUseB) { param->b.grad.vec() += loss.vec(); } in->loss.mat() += param->W.val.mat().transpose() * loss.mat(); } public: inline PExecute generate(bool bTrain, dtype cur_drop_factor); // better to rewrite for deep understanding inline bool typeEqual(PNode other) { bool result = Node::typeEqual(other); if (!result) return false; LinearUniNode* conv_other = (LinearUniNode*)other; if (param != conv_other->param) { return false; } return true; } }; // non-linear feed-forward node // input nodes should be specified by forward function // for input variables, we exploit column vector, // which means a concrete input vector x_i is represented by x(0, i), x(1, i), ..., x(n, i) class LinearNode : public Node { public: PNode in; UniParams* param; public: LinearNode() : Node() { in = NULL; param = NULL; node_type = "linear"; } inline void setParam(UniParams* paramInit) { param = paramInit; } inline void clearValue() { Node::clearValue(); in = NULL; } public: void forward(Graph *cg, PNode x) { in = x; degree = 0; in->addParent(this); cg->addNode(this); } public: inline void compute() { val.mat() = param->W.val.mat() * in->val.mat(); } inline void backward() { param->W.grad.mat() += loss.mat() * in->val.tmat(); in->loss.mat() += param->W.val.mat().transpose() * loss.mat(); } public: PExecute generate(bool bTrain, dtype cur_drop_factor); // better to rewrite for deep understanding bool typeEqual(PNode other) override { bool result = Node::typeEqual(other); if (!result) return false; LinearNode* conv_other = (LinearNode*)other; if (param != conv_other->param) { return false; } return true; } size_t typeHashCode() const override { return Node::typeHashCode() ^ ::typeHashCode(param); } #if USE_GPU void toNodeInfo(NodeInfo &info) const override { Node::toNodeInfo(info); info.input_vals.push_back(in->val.value); info.input_losses.push_back(in->loss.value); } #endif }; class UniExecute :public Execute { public: Tensor2D x, ty, y, b; int inDim, outDim; UniParams* param; dtype(*activate)(const dtype&); // activation function dtype(*derivate)(const dtype&, const dtype&); // derivation function of activation function Tensor2D drop_mask; inline void forward() { int count = batch.size(); ty.init(outDim, count); x.init(inDim, count); y.init(outDim, count); drop_mask.init(outDim, count); #if TEST_CUDA || !USE_GPU b.init(outDim, count); #endif #if USE_GPU std::vector<dtype*> xs, ys; xs.reserve(batch.size()); ys.reserve(batch.size()); for (int i = 0; i < batch.size(); ++i) { UniNode *n = static_cast<UniNode*>(batch.at(i)); xs.push_back(n->in->val.value); ys.push_back(n->val.value); } n3ldg_cuda::CopyForUniNodeForward(xs, param->b.val.value, x.value, ty.value, count, inDim, outDim, param->bUseB); n3ldg_cuda::MatrixMultiplyMatrix(param->W.val.value, x.value, ty.value, outDim, inDim, count, param->bUseB); CalculateDropMask(count, outDim, drop_mask); n3ldg_cuda::ActivatedEnum activatedEnum = ToActivatedEnum(activate); n3ldg_cuda::Activated(activatedEnum, ty.value, ys, y.value, outDim, bTrain, dynamicDropValue(), drop_mask.value); for (int i = 0; i<batch.size(); ++i) { UniNode *n = static_cast<UniNode*>(batch.at(i)); } #if TEST_CUDA for (int idx = 0; idx < count; idx++) { UniNode* ptr = (UniNode*)batch[idx]; for (int idy = 0; idy < inDim; idy++) { x[idy][idx] = ptr->in->val[idy]; } if (param->bUseB) { for (int idy = 0; idy < outDim; idy++) { b[idy][idx] = param->b.val.v[idy]; } } } n3ldg_cuda::Assert(x.verify("forward x")); ty.mat() = param->W.val.mat() * x.mat(); if (param->bUseB) { ty.vec() = ty.vec() + b.vec(); } y.vec() = ty.vec().unaryExpr(ptr_fun(activate)); for (int idx = 0; idx < count; idx++) { UniNode* ptr = (UniNode*)batch[idx]; for (int idy = 0; idy < outDim; idy++) { ptr->val[idy] = y[idy][idx]; } } drop_mask.copyFromDeviceToHost(); for (int i = 0; i < count; ++i) { for (int j = 0; j < outDim; ++j) { dtype v = drop_mask[j][i]; batch[i]->drop_mask[j] = v <= dynamicDropValue() ? 0 : 1; } } for (int i = 0; i < count; ++i) { batch[i]->forward_drop(bTrain, drop_factor); n3ldg_cuda::Assert(batch[i]->val.verify("forward batch i val")); } n3ldg_cuda::Assert(ty.verify("forward ty")); n3ldg_cuda::Assert(y.verify("forward y")); #endif #else for (int idx = 0; idx < count; idx++) { UniNode* ptr = (UniNode*)batch[idx]; for (int idy = 0; idy < inDim; idy++) { x[idy][idx] = ptr->in->val[idy]; } if (param->bUseB) { for (int idy = 0; idy < outDim; idy++) { b[idy][idx] = param->b.val.v[idy]; } } } ty.mat() = param->W.val.mat() * x.mat(); if (param->bUseB) { ty.vec() = ty.vec() + b.vec(); } y.vec() = ty.vec().unaryExpr(ptr_fun(activate)); for (int idx = 0; idx < count; idx++) { UniNode* ptr = (UniNode*)batch[idx]; for (int idy = 0; idy < outDim; idy++) { ptr->val[idy] = y[idy][idx]; } } for (int i = 0; i < count; ++i) { dtype drop_value = batch[0]->drop_value; batch[i]->forward_drop(bTrain, drop_factor); } #endif } void backward() { int count = batch.size(); Tensor2D lx, lty, ly; #if USE_GPU lx.init(inDim, count); lty.init(outDim, count); ly.init(outDim, count); std::vector<dtype*> ly_vec; ly_vec.reserve(count); for (int i = 0; i < count; ++i) { UniNode* ptr = (UniNode*)batch[i]; ly_vec.push_back(ptr->loss.value); } n3ldg_cuda::ActivatedEnum activatedEnum = ToActivatedEnum(activate); n3ldg_cuda::CalculateLtyForUniBackward(activatedEnum, ly_vec, ty.value, y.value, drop_mask.value, dynamicDropValue(), lty.value, count, outDim); #if TEST_CUDA n3ldg_cuda::Assert(param->W.grad.verify( "uni backward W grad initial")); #endif n3ldg_cuda::MatrixMultiplyMatrix(lty.value, x.value, param->W.grad.value, outDim, count, inDim, true, true, false); #if TEST_CUDA n3ldg_cuda::Assert(param->W.val.verify("uni W.val initial")); #endif n3ldg_cuda::MatrixMultiplyMatrix(param->W.val.value, lty.value, lx.value, inDim, outDim, count, false, false, true); std::vector<dtype*> losses; losses.reserve(count); for (int idx = 0; idx < count; idx++) { UniNode* ptr = (UniNode*)batch[idx]; losses.push_back(ptr->in->loss.value); } #if TEST_CUDA n3ldg_cuda::Assert( param->b.grad.verify("uni backward param b initial")); #endif n3ldg_cuda::AddLtyToParamBiasAndAddLxToInputLossesForUniBackward( lty.value, lx.value, param->b.grad.value, losses, count, outDim, inDim, param->bUseB); #if TEST_CUDA for (int idx = 0; idx < count; idx++) { UniNode* ptr = (UniNode*)batch[idx]; ptr->backward_drop(); for (int idy = 0; idy < outDim; idy++) { ly[idy][idx] = ptr->loss[idy]; } } n3ldg_cuda::Assert(x.verify("backward x")); lty.vec() = ly.vec() * ty.vec().binaryExpr(y.vec(), ptr_fun(derivate)); n3ldg_cuda::Assert(lty.verify("backward lty")); param->W.grad.mat() += lty.mat() * x.mat().transpose(); n3ldg_cuda::Assert(param->W.grad.verify("backward W grad")); if (param->bUseB) { for (int idx = 0; idx < count; idx++) { for (int idy = 0; idy < outDim; idy++) { param->b.grad.v[idy] += lty[idy][idx]; } } } n3ldg_cuda::Assert(param->b.grad.verify("backward b grad")); lx.mat() += param->W.val.mat().transpose() * lty.mat(); n3ldg_cuda::Assert(lx.verify("backward lx")); for (int idx = 0; idx < count; idx++) { UniNode* ptr = (UniNode*)batch[idx]; for (int idy = 0; idy < inDim; idy++) { ptr->in->loss[idy] += lx[idy][idx]; } } for (Node * n : batch) { UniNode *ptr = static_cast<UniNode *>(n); n3ldg_cuda::Assert(ptr->in->loss.verify("uni backward loss")); } #endif #else lx.init(inDim, count); lty.init(outDim, count); ly.init(outDim, count); for (int idx = 0; idx < count; idx++) { UniNode* ptr = (UniNode*)batch[idx]; ptr->backward_drop(); for (int idy = 0; idy < outDim; idy++) { ly[idy][idx] = ptr->loss[idy]; } } lty.vec() = ly.vec() * ty.vec().binaryExpr(y.vec(), ptr_fun(derivate)); param->W.grad.mat() += lty.mat() * x.mat().transpose(); if (param->bUseB) { for (int idx = 0; idx < count; idx++) { for (int idy = 0; idy < outDim; idy++) { param->b.grad.v[idy] += lty[idy][idx]; } } } lx.mat() += param->W.val.mat().transpose() * lty.mat(); for (int idx = 0; idx < count; idx++) { UniNode* ptr = (UniNode*)batch[idx]; for (int idy = 0; idy < inDim; idy++) { ptr->in->loss[idy] += lx[idy][idx]; } } #endif } }; inline PExecute UniNode::generate(bool bTrain, dtype cur_drop_factor) { UniExecute* exec = new UniExecute(); exec->batch.push_back(this); exec->bTrain = bTrain; exec->drop_factor = cur_drop_factor; exec->inDim = param->W.inDim(); exec->outDim = param->W.outDim(); exec->param = param; exec->activate = activate; exec->derivate = derivate; return exec; }; class LinearUniExecute :public Execute { public: inline void forward() { int count = batch.size(); //#pragma omp parallel for for (int idx = 0; idx < count; idx++) { batch[idx]->compute(); batch[idx]->forward_drop(bTrain, drop_factor); } } inline void backward() { int count = batch.size(); //#pragma omp parallel for for (int idx = 0; idx < count; idx++) { batch[idx]->backward_drop(); batch[idx]->backward(); } } }; inline PExecute LinearUniNode::generate(bool bTrain, dtype cur_drop_factor) { LinearUniExecute* exec = new LinearUniExecute(); exec->batch.push_back(this); exec->bTrain = bTrain; exec->drop_factor = cur_drop_factor; return exec; }; #if USE_GPU class LinearExecute :public Execute { public: Tensor2D x, y, b; int inDim, outDim, count; UniParams* param; void forward() { int count = batch.size(); x.init(inDim, count); y.init(outDim, count); #if TEST_CUDA b.init(outDim, count); #endif std::vector<dtype*> xs, ys; xs.reserve(batch.size()); ys.reserve(batch.size()); for (int i = 0; i < batch.size(); ++i) { LinearNode *n = static_cast<LinearNode*>(batch.at(i)); xs.push_back(n->in->val.value); ys.push_back(n->val.value); } n3ldg_cuda::CopyForUniNodeForward(xs, param->b.val.value, x.value, y.value, count, inDim, outDim, param->bUseB); n3ldg_cuda::MatrixMultiplyMatrix(param->W.val.value, x.value, y.value, outDim, inDim, count, false); std::vector<dtype*> vals; vals.reserve(count); for (Node *node : batch) { vals.push_back(node->val.value); } n3ldg_cuda::CopyFromOneVectorToMultiVals(y.value, vals, count, outDim); #if TEST_CUDA for (int idx = 0; idx < count; idx++) { LinearNode* ptr = (LinearNode*)batch[idx]; for (int idy = 0; idy < inDim; idy++) { x[idy][idx] = ptr->in->val[idy]; } } y.mat() = param->W.val.mat() * x.mat(); n3ldg_cuda::Assert(x.verify("forward x")); n3ldg_cuda::Assert(y.verify("forward y")); for (int idx = 0; idx < count; idx++) { LinearNode* ptr = (LinearNode*)batch[idx]; for (int idy = 0; idy < outDim; idy++) { ptr->val[idy] = y[idy][idx]; } n3ldg_cuda::Assert(ptr->val.verify("linear forward val")); } #endif } void backward() { int count = batch.size(); Tensor2D lx, ly; lx.init(inDim, count); ly.init(outDim, count); std::vector<dtype*> ly_vec; ly_vec.reserve(count); for (int i = 0; i < count; ++i) { UniNode* ptr = (UniNode*)batch[i]; ly_vec.push_back(ptr->loss.value); } n3ldg_cuda::CalculateLyForLinearBackward(ly_vec, ly.value, count, outDim); n3ldg_cuda::MatrixMultiplyMatrix(ly.value, x.value, param->W.grad.value, outDim, count, inDim, true, true, false); n3ldg_cuda::MatrixMultiplyMatrix(param->W.val.value, ly.value, lx.value, inDim, outDim, count, false, false, true); std::vector<dtype*> losses; losses.reserve(count); for (int idx = 0; idx < count; idx++) { UniNode* ptr = (UniNode*)batch[idx]; losses.push_back(ptr->in->loss.value); } n3ldg_cuda::AddLtyToParamBiasAndAddLxToInputLossesForUniBackward( ly.value, lx.value, param->b.grad.value, losses, count, outDim, inDim, param->bUseB); #if TEST_CUDA for (int idx = 0; idx < count; idx++) { UniNode* ptr = (UniNode*)batch[idx]; ptr->backward_drop(); for (int idy = 0; idy < outDim; idy++) { ly[idy][idx] = ptr->loss[idy]; } } assert(x.verify("backward x")); param->W.grad.mat() += ly.mat() * x.mat().transpose(); param->W.grad.verify("backward W grad"); if (param->bUseB) { for (int idx = 0; idx < count; idx++) { for (int idy = 0; idy < outDim; idy++) { param->b.grad.v[idy] += ly[idy][idx]; } } } n3ldg_cuda::Assert(param->b.grad.verify("backward b grad")); lx.mat() += param->W.val.mat().transpose() * ly.mat(); lx.verify("backward lx"); for (int idx = 0; idx < count; idx++) { UniNode* ptr = (UniNode*)batch[idx]; for (int idy = 0; idy < inDim; idy++) { ptr->in->loss[idy] += lx[idy][idx]; } } for (Node * n : batch) { UniNode *ptr = static_cast<UniNode *>(n); n3ldg_cuda::Assert(ptr->in->loss.verify("backward loss")); } #endif } }; #else class LinearExecute :public Execute { public: Tensor2D x, y; int inDim, outDim, count; UniParams* param; inline void forward() { count = batch.size(); x.init(inDim, count); y.init(outDim, count); for (int idx = 0; idx < count; idx++) { LinearNode* ptr = (LinearNode*)batch[idx]; for (int idy = 0; idy < inDim; idy++) { x[idy][idx] = ptr->in->val[idy]; } } y.mat() = param->W.val.mat() * x.mat(); for (int idx = 0; idx < count; idx++) { LinearNode* ptr = (LinearNode*)batch[idx]; for (int idy = 0; idy < outDim; idy++) { ptr->val[idy] = y[idy][idx]; } ptr->forward_drop(bTrain, drop_factor); } } inline void backward() { Tensor2D lx, ly; lx.init(inDim, count); ly.init(outDim, count); for (int idx = 0; idx < count; idx++) { LinearNode* ptr = (LinearNode*)batch[idx]; ptr->backward_drop(); for (int idy = 0; idy < outDim; idy++) { ly[idy][idx] = ptr->loss[idy]; } } param->W.grad.mat() += ly.mat() * x.mat().transpose(); lx.mat() += param->W.val.mat().transpose() * ly.mat(); for (int idx = 0; idx < count; idx++) { LinearNode* ptr = (LinearNode*)batch[idx]; for (int idy = 0; idy < inDim; idy++) { ptr->in->loss[idy] += lx[idy][idx]; } } } }; #endif inline PExecute LinearNode::generate(bool bTrain, dtype cur_drop_factor) { LinearExecute* exec = new LinearExecute(); exec->batch.push_back(this); exec->inDim = param->W.inDim(); exec->outDim = param->W.outDim(); exec->param = param; exec->bTrain = bTrain; return exec; }; #endif /* UNIOP_H_ */
[ "chncwang@gmail.com" ]
chncwang@gmail.com
149b614530b06e412e320ff1d1bc9820b3a5585a
bfda1bcd751bd90331b111d576952ce9fdb8dbf7
/Tests/ConfigurationTests.cpp
56a5c64f5f20414ba4428f8fcf9c34851528008f
[]
no_license
zidik/soccervision
4d19ab7bc471b355b73c2297d29bd16d184a3cbb
f38572d10d4d0f3184b7cac8d0243414c5347e10
refs/heads/master
2021-10-05T16:17:03.530316
2015-12-05T17:42:07
2015-12-05T17:42:07
39,830,458
2
0
null
2015-11-02T23:53:28
2015-07-28T11:37:43
C++
UTF-8
C++
false
false
758
cpp
#include <boost/test/unit_test.hpp> #include "Configuration.h" BOOST_AUTO_TEST_SUITE(COnfigurationTests) BOOST_AUTO_TEST_CASE(Configuration_PropertyTreeMerging) { boost::property_tree::ptree tree1; tree1.put("one.val1", 1); tree1.put("one.val2", 2); tree1.put("other.val1", 3); boost::property_tree::ptree tree2; tree1.put("one.val2", 4); tree1.put("one.val3", 5); PropertyTreeMerger merger; merger.set_ptree(tree1); merger.update_ptree(tree2); BOOST_TEST(merger.get_ptree().get<int>("one.val1") == 1); BOOST_TEST(merger.get_ptree().get<int>("one.val2") == 4); // This one should be overwritten BOOST_TEST(merger.get_ptree().get<int>("one.val3") == 5); BOOST_TEST(merger.get_ptree().get<int>("other.val1") == 3); } BOOST_AUTO_TEST_SUITE_END()
[ "marklaane@gmail.com" ]
marklaane@gmail.com
bf7faec4edc0f816632d5fb4993b82182c9daf79
3d53cd350ad05d5c3f5f842e2f54391a1b440972
/Stepper Motor/joystic_2stepper/joystic_2stepper.ino
dc56c00a586701c136cc35368d14723d6187dc90
[]
no_license
Platforuma/Beginner-s_Arduino_Codes
052a29076ea6a509467fa214fa9e859f893a0080
30be7a599cf6d3415463c04743d322adc49ee0c7
refs/heads/master
2022-08-28T18:47:33.956791
2020-05-27T19:05:37
2020-05-27T19:05:37
267,403,705
0
0
null
null
null
null
UTF-8
C++
false
false
4,651
ino
int a[] = {5,4,3,2}; int b[] = {8,9,10,11}; int x = A0; int y = A1; int i; float d = 5; float s = 5; int xval; int yval; void setup() { // put your setup code here, to run once: for(i=0;i<4;i++){ pinMode(a[i],OUTPUT); pinMode(b[i],OUTPUT); } pinMode(x,INPUT); pinMode(y,INPUT); Serial.begin(9600); } void loop() { // put your main code here, to run repeatedly: int xval = analogRead(x); int yval = analogRead(y); xval = map(xval, 0,1023,1,100); yval = map(yval, 0,1023,1,100); Serial.print("xval: "); Serial.print(xval); Serial.print(" "); Serial.print("yval: "); Serial.println(yval); if (xval>=40 && xval <= 70 && yval>=40 && yval<=70){ digitalWrite(a[0],HIGH); digitalWrite(a[1],HIGH); digitalWrite(a[2],HIGH); digitalWrite(a[3],HIGH); digitalWrite(b[0],HIGH); digitalWrite(b[1],HIGH); digitalWrite(b[2],HIGH); digitalWrite(b[3],HIGH); } else if(xval>=1 && xval <= 35 && yval>=42 && yval<=62){ digitalWrite(a[0],HIGH); digitalWrite(a[1],LOW); digitalWrite(a[2],LOW); digitalWrite(a[3],LOW); digitalWrite(b[0],HIGH); digitalWrite(b[1],HIGH); digitalWrite(b[2],HIGH); digitalWrite(b[3],HIGH); delay(d); digitalWrite(a[0],LOW); digitalWrite(a[1],HIGH); digitalWrite(a[2],LOW); digitalWrite(a[3],LOW); digitalWrite(b[0],HIGH); digitalWrite(b[1],HIGH); digitalWrite(b[2],HIGH); digitalWrite(b[3],HIGH); delay(d); digitalWrite(a[0],LOW); digitalWrite(a[1],LOW); digitalWrite(a[2],HIGH); digitalWrite(a[3],LOW); digitalWrite(b[0],HIGH); digitalWrite(b[1],HIGH); digitalWrite(b[2],HIGH); digitalWrite(b[3],HIGH); delay(d); digitalWrite(a[0],LOW); digitalWrite(a[1],LOW); digitalWrite(a[2],LOW); digitalWrite(a[3],HIGH); digitalWrite(b[0],HIGH); digitalWrite(b[1],HIGH); digitalWrite(b[2],HIGH); digitalWrite(b[3],HIGH); delay(d); } else if(xval>=75 && xval <= 100 && yval>=42 && yval<=62){ digitalWrite(a[0],LOW); digitalWrite(a[1],LOW); digitalWrite(a[2],LOW); digitalWrite(a[3],HIGH); digitalWrite(b[0],HIGH); digitalWrite(b[1],HIGH); digitalWrite(b[2],HIGH); digitalWrite(b[3],HIGH); delay(s); digitalWrite(a[0],LOW); digitalWrite(a[1],LOW); digitalWrite(a[2],HIGH); digitalWrite(a[3],LOW); digitalWrite(b[0],HIGH); digitalWrite(b[1],HIGH); digitalWrite(b[2],HIGH); digitalWrite(b[3],HIGH); delay(s); digitalWrite(a[0],LOW); digitalWrite(a[1],HIGH); digitalWrite(a[2],LOW); digitalWrite(a[3],LOW); digitalWrite(b[0],HIGH); digitalWrite(b[1],HIGH); digitalWrite(b[2],HIGH); digitalWrite(b[3],HIGH); delay(s); digitalWrite(a[0],HIGH); digitalWrite(a[1],LOW); digitalWrite(a[2],LOW); digitalWrite(a[3],LOW); digitalWrite(b[0],HIGH); digitalWrite(b[1],HIGH); digitalWrite(b[2],HIGH); digitalWrite(b[3],HIGH); delay(s); } else if(xval>=40 && xval <= 70 && yval>=1 && yval<=35){ digitalWrite(b[0],HIGH); digitalWrite(b[1],LOW); digitalWrite(b[2],LOW); digitalWrite(b[3],LOW); digitalWrite(a[0],HIGH); digitalWrite(a[1],HIGH); digitalWrite(a[2],HIGH); digitalWrite(a[3],HIGH); delay(d); digitalWrite(a[0],HIGH); digitalWrite(a[1],HIGH); digitalWrite(a[2],HIGH); digitalWrite(a[3],HIGH); digitalWrite(b[0],LOW); digitalWrite(b[1],HIGH); digitalWrite(b[2],LOW); digitalWrite(b[3],LOW); delay(d); digitalWrite(a[0],HIGH); digitalWrite(a[1],HIGH); digitalWrite(a[2],HIGH); digitalWrite(a[3],HIGH); digitalWrite(b[0],LOW); digitalWrite(b[1],LOW); digitalWrite(b[2],HIGH); digitalWrite(b[3],LOW); delay(d); digitalWrite(a[0],HIGH); digitalWrite(a[1],HIGH); digitalWrite(a[2],HIGH); digitalWrite(a[3],HIGH); digitalWrite(b[0],LOW); digitalWrite(b[1],LOW); digitalWrite(b[2],LOW); digitalWrite(b[3],HIGH); delay(d); } else if(xval>=1 && xval <= 35 && yval>=70 && yval<=100){ digitalWrite(b[0],LOW); digitalWrite(b[1],LOW); digitalWrite(b[2],LOW); digitalWrite(b[3],HIGH); digitalWrite(a[0],HIGH); digitalWrite(a[1],HIGH); digitalWrite(a[2],HIGH); digitalWrite(a[3],HIGH); delay(s); digitalWrite(b[0],LOW); digitalWrite(b[1],LOW); digitalWrite(b[2],HIGH); digitalWrite(b[3],LOW); digitalWrite(a[0],HIGH); digitalWrite(a[1],HIGH); digitalWrite(a[2],HIGH); digitalWrite(a[3],HIGH); delay(s); digitalWrite(b[0],LOW); digitalWrite(b[1],HIGH); digitalWrite(b[2],LOW); digitalWrite(b[3],LOW); digitalWrite(a[0],HIGH); digitalWrite(a[1],HIGH); digitalWrite(a[2],HIGH); digitalWrite(a[3],HIGH); delay(s); digitalWrite(b[0],HIGH); digitalWrite(b[1],LOW); digitalWrite(b[2],LOW); digitalWrite(b[3],LOW); digitalWrite(a[0],HIGH); digitalWrite(a[1],HIGH); digitalWrite(a[2],HIGH); digitalWrite(a[3],HIGH); delay(s); } else{ Serial.println("Error"); } }
[ "noreply@github.com" ]
Platforuma.noreply@github.com
97f8222c9df013b969603297b5d950198549b99a
b28305dab0be0e03765c62b97bcd7f49a4f8073d
/ash/assistant/assistant_controller.cc
c863fa28a0f905863d42e2e1ceb219578e9fc974
[ "BSD-3-Clause" ]
permissive
svarvel/browser-android-tabs
9e5e27e0a6e302a12fe784ca06123e5ce090ced5
bd198b4c7a1aca2f3e91f33005d881f42a8d0c3f
refs/heads/base-72.0.3626.105
2020-04-24T12:16:31.442851
2019-08-02T19:15:36
2019-08-02T19:15:36
171,950,555
1
2
NOASSERTION
2019-08-02T19:15:37
2019-02-21T21:47:44
null
UTF-8
C++
false
false
10,273
cc
// Copyright 2018 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 "ash/assistant/assistant_controller.h" #include <algorithm> #include <utility> #include "ash/accessibility/accessibility_controller.h" #include "ash/assistant/assistant_cache_controller.h" #include "ash/assistant/assistant_controller_observer.h" #include "ash/assistant/assistant_interaction_controller.h" #include "ash/assistant/assistant_notification_controller.h" #include "ash/assistant/assistant_screen_context_controller.h" #include "ash/assistant/assistant_setup_controller.h" #include "ash/assistant/assistant_ui_controller.h" #include "ash/assistant/util/deep_link_util.h" #include "ash/new_window_controller.h" #include "ash/session/session_controller.h" #include "ash/shell.h" #include "ash/utility/screenshot_controller.h" #include "ash/voice_interaction/voice_interaction_controller.h" #include "base/bind.h" #include "base/memory/scoped_refptr.h" #include "services/content/public/mojom/constants.mojom.h" #include "services/service_manager/public/cpp/connector.h" namespace ash { AssistantController::AssistantController() : assistant_volume_control_binding_(this), assistant_cache_controller_( std::make_unique<AssistantCacheController>(this)), assistant_interaction_controller_( std::make_unique<AssistantInteractionController>(this)), assistant_notification_controller_( std::make_unique<AssistantNotificationController>(this)), assistant_screen_context_controller_( std::make_unique<AssistantScreenContextController>(this)), assistant_setup_controller_( std::make_unique<AssistantSetupController>(this)), assistant_ui_controller_(std::make_unique<AssistantUiController>(this)), weak_factory_(this) { Shell::Get()->voice_interaction_controller()->AddLocalObserver(this); chromeos::CrasAudioHandler::Get()->AddAudioObserver(this); AddObserver(this); NotifyConstructed(); } AssistantController::~AssistantController() { NotifyDestroying(); chromeos::CrasAudioHandler::Get()->RemoveAudioObserver(this); Shell::Get()->accessibility_controller()->RemoveObserver(this); Shell::Get()->voice_interaction_controller()->RemoveLocalObserver(this); RemoveObserver(this); } void AssistantController::BindRequest( mojom::AssistantControllerRequest request) { assistant_controller_bindings_.AddBinding(this, std::move(request)); } void AssistantController::BindRequest( mojom::AssistantVolumeControlRequest request) { assistant_volume_control_binding_.Bind(std::move(request)); } void AssistantController::AddObserver(AssistantControllerObserver* observer) { observers_.AddObserver(observer); } void AssistantController::RemoveObserver( AssistantControllerObserver* observer) { observers_.RemoveObserver(observer); } void AssistantController::SetAssistant( chromeos::assistant::mojom::AssistantPtr assistant) { assistant_ = std::move(assistant); // Provide reference to sub-controllers. assistant_interaction_controller_->SetAssistant(assistant_.get()); assistant_notification_controller_->SetAssistant(assistant_.get()); assistant_screen_context_controller_->SetAssistant(assistant_.get()); assistant_ui_controller_->SetAssistant(assistant_.get()); // The Assistant service needs to have accessibility state synced with ash // and be notified of any accessibility status changes in the future to // provide an opportunity to turn on/off A11Y features. Shell::Get()->accessibility_controller()->AddObserver(this); OnAccessibilityStatusChanged(); } void AssistantController::SetAssistantImageDownloader( mojom::AssistantImageDownloaderPtr assistant_image_downloader) { assistant_image_downloader_ = std::move(assistant_image_downloader); } void AssistantController::OpenAssistantSettings() { // Launch Assistant settings via deeplink. OpenUrl(assistant::util::CreateAssistantSettingsDeepLink()); } void AssistantController::DownloadImage( const GURL& url, mojom::AssistantImageDownloader::DownloadCallback callback) { DCHECK(assistant_image_downloader_); const mojom::UserSession* user_session = Shell::Get()->session_controller()->GetUserSession(0); if (!user_session) { LOG(WARNING) << "Unable to retrieve active user session."; std::move(callback).Run(gfx::ImageSkia()); return; } AccountId account_id = user_session->user_info->account_id; assistant_image_downloader_->Download(account_id, url, std::move(callback)); } void AssistantController::OnDeepLinkReceived( assistant::util::DeepLinkType type, const std::map<std::string, std::string>& params) { using assistant::util::DeepLinkParam; using assistant::util::DeepLinkType; switch (type) { case DeepLinkType::kChromeSettings: { // Chrome Settings deep links are opened in a new browser tab. OpenUrl(assistant::util::GetChromeSettingsUrl( assistant::util::GetDeepLinkParam(params, DeepLinkParam::kPage))); break; } case DeepLinkType::kFeedback: // TODO(dmblack): Possibly use a new FeedbackSource (this method defaults // to kFeedbackSourceAsh). This may be useful for differentiating feedback // UI and behavior for Assistant. Shell::Get()->new_window_controller()->OpenFeedbackPage(); break; case DeepLinkType::kScreenshot: // We close the UI before taking the screenshot as it's probably not the // user's intention to include the Assistant in the picture. assistant_ui_controller_->CloseUi(AssistantExitPoint::kUnspecified); Shell::Get()->screenshot_controller()->TakeScreenshotForAllRootWindows(); break; case DeepLinkType::kTaskManager: // Open task manager window. Shell::Get()->new_window_controller()->ShowTaskManager(); break; case DeepLinkType::kUnsupported: case DeepLinkType::kOnboarding: case DeepLinkType::kQuery: case DeepLinkType::kReminders: case DeepLinkType::kSettings: case DeepLinkType::kWhatsOnMyScreen: // No action needed. break; } } void AssistantController::SetVolume(int volume, bool user_initiated) { volume = std::min(100, volume); volume = std::max(volume, 0); chromeos::CrasAudioHandler::Get()->SetOutputVolumePercent(volume); } void AssistantController::SetMuted(bool muted) { chromeos::CrasAudioHandler::Get()->SetOutputMute(muted); } void AssistantController::AddVolumeObserver(mojom::VolumeObserverPtr observer) { volume_observer_.AddPtr(std::move(observer)); int output_volume = chromeos::CrasAudioHandler::Get()->GetOutputVolumePercent(); bool mute = chromeos::CrasAudioHandler::Get()->IsOutputMuted(); OnOutputMuteChanged(mute, false /* system_adjust */); OnOutputNodeVolumeChanged(0 /* node */, output_volume); } void AssistantController::OnOutputMuteChanged(bool mute_on, bool system_adjust) { volume_observer_.ForAllPtrs([mute_on](mojom::VolumeObserver* observer) { observer->OnMuteStateChanged(mute_on); }); } void AssistantController::OnOutputNodeVolumeChanged(uint64_t node, int volume) { // |node| refers to the active volume device, which we don't care here. volume_observer_.ForAllPtrs([volume](mojom::VolumeObserver* observer) { observer->OnVolumeChanged(volume); }); } void AssistantController::OnAccessibilityStatusChanged() { // The Assistant service needs to be informed of changes to accessibility // state so that it can turn on/off A11Y features appropriately. assistant_->OnAccessibilityStatusChanged( Shell::Get()->accessibility_controller()->IsSpokenFeedbackEnabled()); } void AssistantController::OpenUrl(const GURL& url, bool from_server) { if (assistant::util::IsDeepLinkUrl(url)) { NotifyDeepLinkReceived(url); return; } // The new tab should be opened with a user activation since the user // interacted with the Assistant to open the url. Shell::Get()->new_window_controller()->NewTabWithUrl( url, /*from_user_interaction=*/true); NotifyUrlOpened(url, from_server); } void AssistantController::GetNavigableContentsFactory( content::mojom::NavigableContentsFactoryRequest request) { const mojom::UserSession* user_session = Shell::Get()->session_controller()->GetUserSession(0); if (!user_session) { LOG(WARNING) << "Unable to retrieve active user session."; return; } const base::Optional<base::Token>& service_instance_group = user_session->user_info->service_instance_group; if (!service_instance_group) { LOG(ERROR) << "Unable to retrieve service instance group."; return; } Shell::Get()->connector()->BindInterface( service_manager::ServiceFilter::ByNameInGroup( content::mojom::kServiceName, *service_instance_group), std::move(request)); } void AssistantController::NotifyConstructed() { for (AssistantControllerObserver& observer : observers_) observer.OnAssistantControllerConstructed(); } void AssistantController::NotifyDestroying() { for (AssistantControllerObserver& observer : observers_) observer.OnAssistantControllerDestroying(); } void AssistantController::NotifyDeepLinkReceived(const GURL& deep_link) { using assistant::util::DeepLinkType; // Retrieve deep link type and parsed parameters. DeepLinkType type = assistant::util::GetDeepLinkType(deep_link); const std::map<std::string, std::string> params = assistant::util::GetDeepLinkParams(deep_link); for (AssistantControllerObserver& observer : observers_) observer.OnDeepLinkReceived(type, params); } void AssistantController::NotifyUrlOpened(const GURL& url, bool from_server) { for (AssistantControllerObserver& observer : observers_) observer.OnUrlOpened(url, from_server); } void AssistantController::OnVoiceInteractionStatusChanged( mojom::VoiceInteractionState state) { if (state == mojom::VoiceInteractionState::NOT_READY) assistant_ui_controller_->HideUi(AssistantExitPoint::kUnspecified); } base::WeakPtr<AssistantController> AssistantController::GetWeakPtr() { return weak_factory_.GetWeakPtr(); } } // namespace ash
[ "artem@brave.com" ]
artem@brave.com
fc9c34a9295c51113ea95c3697184913626fc429
b4879875d0e7b932b33cd7af62d621eaf2071c82
/online_judges/codejam/Store Credit.cpp
f5bfe07d73f8ed0c5b25bf8a05abef79bf223d4f
[]
no_license
ayoubc/competitive-programming
9b57dcec5dab00d9f3ff4016286d66d16d7565e4
5ccc8d873825954116c945baf4d2ebefd76bd63e
refs/heads/master
2023-08-16T20:48:58.399708
2023-08-02T20:44:31
2023-08-02T20:44:31
164,316,604
2
0
null
null
null
null
UTF-8
C++
false
false
572
cpp
#include<bits/stdc++.h> using namespace std; int items[2005]; int main(){ freopen("A-large-practice.in","r",stdin); freopen("A-large-practice.out","w",stdout); int n,c,l,index1,index2; scanf("%d",&n); for(int t=1;t<=n;t++){ scanf("%d",&c); scanf("%d",&l); for(int i=0;i<l;i++) scanf("%d",&items[i]); bool found = false; for(int i=0;i<l;i++){ for(int j=i+1;j<l;j++){ if(items[j]==c - items[i]){ index1 = i; index2 = j; found = true; break; } } if(found) break; } printf("Case #%d: %d %d\n",t,index1+1,index2+1); } }
[ "ayoubch807@gmail.com" ]
ayoubch807@gmail.com
0e80d16bd699bc85deeeaf016cec15541681aeea
041d52327dcc541fe8fcaf30942c0108339c1597
/include/beast/http/fields.hpp
7774fe7758bdcc3fe910902d7463fcc010f1a23e
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
AlexeyAB/Beast
19d8e4ab1a9a428b8863d3b5c9ad17033ef4d6a7
458fa7e4e239e1c9e41066e61da2ae8f71d26220
refs/heads/master
2021-01-24T08:34:25.690406
2017-06-03T02:16:57
2017-06-03T07:14:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,284
hpp
// // Copyright (c) 2013-2017 Vinnie Falco (vinnie dot falco at gmail dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef BEAST_HTTP_FIELDS_HPP #define BEAST_HTTP_FIELDS_HPP #include <beast/config.hpp> #include <beast/core/string_view.hpp> #include <beast/core/detail/empty_base_optimization.hpp> #include <beast/http/verb.hpp> #include <beast/http/detail/fields.hpp> #include <boost/lexical_cast.hpp> #include <boost/optional.hpp> #include <algorithm> #include <cctype> #include <memory> #include <string> #include <type_traits> #include <utility> namespace beast { namespace http { /** A container for storing HTTP header fields. This container is designed to store the field value pairs that make up the fields and trailers in an HTTP message. Objects of this type are iterable, with each element holding the field name and field value. Field names are stored as-is, but comparisons are case-insensitive. When the container is iterated, the fields are presented in the order of insertion. For fields with the same name, the container behaves as a `std::multiset`; there will be a separate value for each occurrence of the field name. @note Meets the requirements of @b FieldSequence. */ template<class Allocator> class basic_fields : #if ! BEAST_DOXYGEN private beast::detail::empty_base_optimization< typename std::allocator_traits<Allocator>:: template rebind_alloc< detail::basic_fields_base::element>>, #endif public detail::basic_fields_base { using alloc_type = typename std::allocator_traits<Allocator>:: template rebind_alloc< detail::basic_fields_base::element>; using alloc_traits = std::allocator_traits<alloc_type>; using size_type = typename std::allocator_traits<Allocator>::size_type; boost::optional<verb> verb_; void delete_all(); void move_assign(basic_fields&, std::false_type); void move_assign(basic_fields&, std::true_type); void copy_assign(basic_fields const&, std::false_type); void copy_assign(basic_fields const&, std::true_type); template<class FieldSequence> void copy_from(FieldSequence const& fs) { for(auto const& e : fs) insert(e.first, e.second); } public: /// The type of allocator used. using allocator_type = Allocator; /** The value type of the field sequence. Meets the requirements of @b Field. */ #if BEAST_DOXYGEN using value_type = implementation_defined; #endif /// A const iterator to the field sequence #if BEAST_DOXYGEN using iterator = implementation_defined; #endif /// A const iterator to the field sequence #if BEAST_DOXYGEN using const_iterator = implementation_defined; #endif /// Default constructor. basic_fields() = default; /// Destructor ~basic_fields(); /** Construct the fields. @param alloc The allocator to use. */ explicit basic_fields(Allocator const& alloc); /** Move constructor. The moved-from object becomes an empty field sequence. @param other The object to move from. */ basic_fields(basic_fields&& other); /** Move assignment. The moved-from object becomes an empty field sequence. @param other The object to move from. */ basic_fields& operator=(basic_fields&& other); /// Copy constructor. basic_fields(basic_fields const&); /// Copy assignment. basic_fields& operator=(basic_fields const&); /// Copy constructor. template<class OtherAlloc> basic_fields(basic_fields<OtherAlloc> const&); /// Copy assignment. template<class OtherAlloc> basic_fields& operator=(basic_fields<OtherAlloc> const&); /// Returns a const iterator to the beginning of the field sequence. const_iterator begin() const { return list_.cbegin(); } /// Returns a const iterator to the end of the field sequence. const_iterator end() const { return list_.cend(); } /// Returns a const iterator to the beginning of the field sequence. const_iterator cbegin() const { return list_.cbegin(); } /// Returns a const iterator to the end of the field sequence. const_iterator cend() const { return list_.cend(); } /// Returns `true` if the specified field exists. bool exists(string_view const& name) const { return set_.find(name, less{}) != set_.end(); } /// Returns the number of values for the specified field. std::size_t count(string_view const& name) const; /** Returns an iterator to the case-insensitive matching field name. If more than one field with the specified name exists, the first field defined by insertion order is returned. */ iterator find(string_view const& name) const; /** Returns the value for a case-insensitive matching header, or `""`. If more than one field with the specified name exists, the first field defined by insertion order is returned. */ string_view const operator[](string_view const& name) const; /// Clear the contents of the basic_fields. void clear() noexcept; /** Remove a field. If more than one field with the specified name exists, all matching fields will be removed. @param name The name of the field(s) to remove. @return The number of fields removed. */ std::size_t erase(string_view const& name); /** Insert a field value. If a field with the same name already exists, the existing field is untouched and a new field value pair is inserted into the container. @param name The name of the field. @param value A string holding the value of the field. */ void insert(string_view const& name, string_view value); /** Insert a field value. If a field with the same name already exists, the existing field is untouched and a new field value pair is inserted into the container. @param name The name of the field @param value The value of the field. The object will be converted to a string using `boost::lexical_cast`. */ template<class T> typename std::enable_if< ! std::is_constructible<string_view, T>::value>::type insert(string_view name, T const& value) { insert(name, boost::lexical_cast<std::string>(value)); } /** Replace a field value. First removes any values with matching field names, then inserts the new field value. @param name The name of the field. @param value A string holding the value of the field. */ void replace(string_view const& name, string_view value); /** Replace a field value. First removes any values with matching field names, then inserts the new field value. @param name The name of the field @param value The value of the field. The object will be converted to a string using `boost::lexical_cast`. */ template<class T> typename std::enable_if< ! std::is_constructible<string_view, T>::value>::type replace(string_view const& name, T const& value) { replace(name, boost::lexical_cast<std::string>(value)); } #if BEAST_DOXYGEN private: #endif string_view method() const; void method(verb v); void method(string_view const& s); string_view target() const { return (*this)[":target"]; } void target(string_view const& s) { return this->replace(":target", s); } string_view reason() const { return (*this)[":reason"]; } void reason(string_view const& s) { return this->replace(":reason", s); } }; /// A typical HTTP header fields container using fields = basic_fields<std::allocator<char>>; } // http } // beast #include <beast/http/impl/fields.ipp> #endif
[ "vinnie.falco@gmail.com" ]
vinnie.falco@gmail.com
6e585b1e6e362b406b569f926d62d0f15e82ae93
0cac2210f68f2c17dc2e7375bf1ae7f6427b096b
/core/thirdparty/ovf/test/binary.cpp
a1e83371c34f161cf17d8fc07d86fe7fbd1cce97
[ "MIT" ]
permissive
spirit-code/spirit
43e4fbb3d99049490f7fe89b0fc1736589c58f29
e82250d3b14411c2c2fa292d143f13e3e111ad8c
refs/heads/master
2023-06-12T23:29:10.559514
2023-03-17T16:15:44
2023-03-17T16:16:17
69,043,835
114
61
MIT
2023-06-04T19:52:34
2016-09-23T16:51:17
C++
UTF-8
C++
false
false
9,023
cpp
#include <catch.hpp> #include <ovf.h> #include <iostream> TEST_CASE( "Binary", "[binary]" ) { const char * testfile = "testfile_cpp_bin.ovf"; SECTION( "write" ) { // segment header auto segment = ovf_segment_create(); // segment->title = const_cast<char *>("ovf test title - write"); // segment->comment = const_cast<char *>("test write"); segment->valuedim = 3; segment->n_cells[0] = 2; segment->n_cells[1] = 2; segment->n_cells[2] = 1; segment->N = 4; // data std::vector<double> field(3*segment->N, 1); field[0] = 3; field[3] = 2; field[6] = 1; field[9] = 0; // open auto file = ovf_open(testfile); // write int success = ovf_write_segment_8(file, segment, field.data(), OVF_FORMAT_BIN); if( OVF_OK != success ) std::cerr << ovf_latest_message(file) << std::endl; REQUIRE( success == OVF_OK ); // close ovf_close(file); } SECTION( "append" ) { // segment header auto segment = ovf_segment_create(); // segment->title = const_cast<char *>("ovf test title - append"); // segment->comment = const_cast<char *>("test append"); segment->valuedim = 3; segment->n_cells[0] = 2; segment->n_cells[1] = 2; segment->n_cells[2] = 1; segment->N = 4; // data std::vector<double> field(3*segment->N, 1); field[0] = 6; field[3] = 4; field[6] = 2; field[9] = 0; // open auto file = ovf_open(testfile); // write int success = ovf_append_segment_8(file, segment, field.data(), OVF_FORMAT_BIN); if( OVF_OK != success ) std::cerr << ovf_latest_message(file) << std::endl; REQUIRE( success == OVF_OK ); // close ovf_close(file); } SECTION( "read first segment" ) { // segment header auto segment = ovf_segment_create(); // open auto file = ovf_open(testfile); REQUIRE( file->n_segments == 2 ); int index = 0; // read header int success = ovf_read_segment_header(file, index, segment); if( OVF_OK != success ) std::cerr << ovf_latest_message(file) << std::endl; REQUIRE( success == OVF_OK ); REQUIRE( segment->N == 4 ); // data std::vector<float> field(3*segment->N); // read data success = ovf_read_segment_data_4(file, index, segment, field.data()); if( OVF_OK != success ) std::cerr << ovf_latest_message(file) << std::endl; REQUIRE( success == OVF_OK ); REQUIRE( field[0] == 3 ); REQUIRE( field[1] == 1 ); REQUIRE( field[3] == 2 ); REQUIRE( field[6] == 1 ); REQUIRE( field[9] == 0 ); // close ovf_close(file); } SECTION( "read second segment") { // segment header auto segment = ovf_segment_create(); // open auto file = ovf_open(testfile); REQUIRE( file->n_segments == 2 ); int index = 1; // read header int success = ovf_read_segment_header(file, index, segment); if( OVF_OK != success ) std::cerr << ovf_latest_message(file) << std::endl; REQUIRE( success == OVF_OK ); REQUIRE( segment->N == 4 ); // data std::vector<double> field(3*segment->N); // read data success = ovf_read_segment_data_8(file, index, segment, field.data()); if( OVF_OK != success ) std::cerr << ovf_latest_message(file) << std::endl; REQUIRE( success == OVF_OK ); REQUIRE( field[0] == 6 ); REQUIRE( field[1] == 1 ); REQUIRE( field[3] == 4 ); REQUIRE( field[6] == 2 ); REQUIRE( field[9] == 0 ); // close ovf_close(file); } } TEST_CASE( "Mixed binary and CSV", "[mixed]" ) { const char * testfile = "testfile_cpp_mixed.ovf"; SECTION( "write" ) { // segment header auto segment = ovf_segment_create(); segment->title = const_cast<char *>("ovf test title - write"); segment->comment = const_cast<char *>("test write csv"); segment->valuedim = 3; segment->n_cells[0] = 2; segment->n_cells[1] = 2; segment->n_cells[2] = 1; segment->N = 4; // data std::vector<float> field(3*segment->N, -1); field[0] = 3; field[3] = 2; field[6] = 1; field[9] = 0; // for( auto x : field ) // std::cerr << " " << x; // std::cerr << std::endl; // open auto file = ovf_open(testfile); // write int success = ovf_write_segment_4(file, segment, field.data(), OVF_FORMAT_BIN); if( OVF_OK != success ) std::cerr << ovf_latest_message(file) << std::endl; REQUIRE( success == OVF_OK ); // close ovf_close(file); } SECTION( "append" ) { // segment header auto segment = ovf_segment_create(); // segment->title = const_cast<char *>("ovf test title - append"); // segment->comment = const_cast<char *>("test append"); segment->valuedim = 3; segment->n_cells[0] = 2; segment->n_cells[1] = 2; segment->n_cells[2] = 1; segment->N = 4; // data std::vector<double> field(3*segment->N, -2); field[0] = 6; field[3] = 4; field[6] = 2; field[9] = 0; // open auto file = ovf_open(testfile); // write int success = ovf_append_segment_8(file, segment, field.data(), OVF_FORMAT_BIN); if( OVF_OK != success ) std::cerr << ovf_latest_message(file) << std::endl; REQUIRE( success == OVF_OK ); // close ovf_close(file); } SECTION( "append" ) { // segment header auto segment = ovf_segment_create(); // segment->title = const_cast<char *>("ovf test title - append"); // segment->comment = const_cast<char *>("test append"); segment->valuedim = 3; segment->n_cells[0] = 2; segment->n_cells[1] = 2; segment->n_cells[2] = 1; segment->N = 4; // data std::vector<double> field(3*segment->N, -3); field[0] = 6; field[3] = 4; field[6] = 2; field[9] = 0; // open auto file = ovf_open(testfile); // write int success = ovf_append_segment_8(file, segment, field.data(), OVF_FORMAT_CSV); if( OVF_OK != success ) std::cerr << ovf_latest_message(file) << std::endl; REQUIRE( success == OVF_OK ); // close ovf_close(file); } SECTION( "read first segment" ) { // segment header auto segment = ovf_segment_create(); // open auto file = ovf_open(testfile); REQUIRE( file->n_segments == 3 ); int index = 0; // read header int success = ovf_read_segment_header(file, index, segment); if( OVF_OK != success ) std::cerr << ovf_latest_message(file) << std::endl; REQUIRE( success == OVF_OK ); REQUIRE( segment->N == 4 ); // data std::vector<float> field(3*segment->N, -3000); // read data success = ovf_read_segment_data_4(file, index, segment, field.data()); if( OVF_OK != success ) std::cerr << ovf_latest_message(file) << std::endl; REQUIRE( success == OVF_OK ); REQUIRE( field[0] == 3 ); REQUIRE( field[1] == -1 ); REQUIRE( field[3] == 2 ); REQUIRE( field[4] == -1 ); REQUIRE( field[6] == 1 ); REQUIRE( field[7] == -1 ); REQUIRE( field[9] == 0 ); // close ovf_close(file); } SECTION( "read second segment") { // segment header auto segment = ovf_segment_create(); // open auto file = ovf_open(testfile); REQUIRE( file->n_segments == 3 ); int index = 1; // read header int success = ovf_read_segment_header(file, index, segment); if( OVF_OK != success ) std::cerr << ovf_latest_message(file) << std::endl; REQUIRE( success == OVF_OK ); REQUIRE( segment->N == 4 ); // data std::vector<double> field(3*segment->N); // read data success = ovf_read_segment_data_8(file, index, segment, field.data()); if( OVF_OK != success ) std::cerr << ovf_latest_message(file) << std::endl; REQUIRE( success == OVF_OK ); REQUIRE( field[0] == 6 ); // REQUIRE( field[1] == 1 ); // REQUIRE( field[3] == 4 ); // REQUIRE( field[6] == 2 ); // REQUIRE( field[9] == 0 ); // close ovf_close(file); } }
[ "g.mueller@fz-juelich.de" ]
g.mueller@fz-juelich.de
e891b5e88cbdc7238607c2688a37c47f20437317
852807314cfb24c959badacd5cc405ec469c50be
/Client/CallbackInterfaceClient.cpp
85bce4a9107035c1b7e2468b1e2858fc52d73109
[]
no_license
munibsyed/RaknetChatSystemV2
623e43f76dd55bb5737f41caa88e306c8561d5f2
fe93c95e05c89c161a7016436ed643144b07f79b
refs/heads/master
2021-01-19T20:51:14.847215
2017-05-08T10:48:39
2017-05-08T10:48:39
88,568,366
1
0
null
null
null
null
UTF-8
C++
false
false
676
cpp
#include "CallbackInterfaceClient.h" bool CallbackInterfaceClient::OnFile(OnFileStruct * onFileStruct) { std::cout << "Received file on client end." << std::endl; std::string fileData = ""; for (int i = 0; i < onFileStruct->byteLengthOfThisFile; i++) { fileData += onFileStruct->fileData[i]; } std::string filename = onFileStruct->fileName; //filename = "C:\\Users\\munib\\Documents\\" + filename; std::cout << "Writing to: " << filename << std::endl; std::ofstream outputFile; outputFile.open(filename, std::ios::binary); outputFile << fileData; outputFile.close(); return false; } void CallbackInterfaceClient::OnFileProgress(FileProgressStruct * fps) { }
[ "nitro_mo@syed.podzone.net" ]
nitro_mo@syed.podzone.net
2b3a112c34ff6bc1fc40549d649e45b826bb3fb9
c14b2b8a2ddb956a9dc877f2005852b51195c98b
/libs/famitracker/Source/InstrumentVRC7.cpp
fcf15bf30ccba8200f45b6104914e45edf4044dc
[]
no_license
zeroCoder1/nesicide
9d946f0961b4f1bc4ae18c4debdbcfc34e8bf293
7d0da9f0c31b581a29d23747b275127d41964542
refs/heads/master
2020-12-28T19:46:19.673017
2013-11-10T04:08:27
2013-11-10T04:08:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,091
cpp
/* ** FamiTracker - NES/Famicom sound tracker ** Copyright (C) 2005-2012 Jonathan Liss ** ** 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 ** Library General Public License for more details. To obtain a ** copy of the GNU Library General Public License, write to the Free ** Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. ** ** Any permitted reproduction of these routines, in whole or in part, ** must bear this legend. */ #include <vector> #include "stdafx.h" #include "FamiTrackerDoc.h" #include "Instrument.h" #include "Compiler.h" #include "DocumentFile.h" /* * class CInstrumentVRC7 * */ CInstrumentVRC7::CInstrumentVRC7() : m_iPatch(0) { m_iRegs[0] = 0; m_iRegs[1] = 0; m_iRegs[2] = 0; m_iRegs[3] = 0; m_iRegs[4] = 0; m_iRegs[5] = 0; m_iRegs[6] = 0; m_iRegs[7] = 0; } CInstrument *CInstrumentVRC7::Clone() const { CInstrumentVRC7 *pNew = new CInstrumentVRC7(); pNew->SetPatch(GetPatch()); for (int i = 0; i < 8; ++i) pNew->SetCustomReg(i, GetCustomReg(i)); pNew->SetName(GetName()); return pNew; } void CInstrumentVRC7::Store(CDocumentFile *pDocFile) { pDocFile->WriteBlockInt(m_iPatch); for (int i = 0; i < 8; ++i) pDocFile->WriteBlockChar(GetCustomReg(i)); } bool CInstrumentVRC7::Load(CDocumentFile *pDocFile) { m_iPatch = pDocFile->GetBlockInt(); for (int i = 0; i < 8; ++i) SetCustomReg(i, pDocFile->GetBlockChar()); return true; } void CInstrumentVRC7::SaveFile(CFile *pFile, CFamiTrackerDoc *pDoc) { unsigned char Var; pFile->Write(&m_iPatch, sizeof(int)); for (int i = 0; i < 8; ++i) { Var = GetCustomReg(i); pFile->Write(&Var, 1); } } bool CInstrumentVRC7::LoadFile(CFile *pFile, int iVersion, CFamiTrackerDoc *pDoc) { unsigned char Var; pFile->Read(&m_iPatch, sizeof(int)); for (int i = 0; i < 8; ++i) { pFile->Read(&Var, 1); SetCustomReg(i, Var); } return true; } int CInstrumentVRC7::Compile(CChunk *pChunk, int Index) { int Patch = GetPatch(); pChunk->StoreByte(Patch << 4); // Shift up by 4 to make room for volume if (Patch == 0) { // Write custom patch settings for (int i = 0; i < 8; ++i) { pChunk->StoreByte(GetCustomReg(i)); } } return (Patch == 0) ? 9 : 1; } bool CInstrumentVRC7::CanRelease() const { return false; // This can use release but disable it when previewing notes } void CInstrumentVRC7::SetPatch(unsigned int Patch) { m_iPatch = Patch; InstrumentChanged(); } unsigned int CInstrumentVRC7::GetPatch() const { return m_iPatch; } void CInstrumentVRC7::SetCustomReg(int Reg, unsigned int Value) { m_iRegs[Reg] = Value; InstrumentChanged(); } unsigned int CInstrumentVRC7::GetCustomReg(int Reg) const { return m_iRegs[Reg]; }
[ "christopher_pow@hotmail.com" ]
christopher_pow@hotmail.com
bdc886c13c0043694ce55228e1f0650dc59e0306
ee55b825e505044d38455acb0cfef1a6f817c3d9
/GraphCheck.cpp
941325abcfd185958a3c776fd80d80406864dc53
[]
no_license
Ahmed-Halim/ACM
8665fabce10c9c62ea811aad15dcb22e3a5fd7d2
425221f4d14cdda3dbfa3993fa1e3b81b273fce8
refs/heads/master
2021-05-01T22:10:35.363215
2019-04-30T18:24:34
2019-04-30T18:24:34
120,969,457
0
0
null
null
null
null
UTF-8
C++
false
false
1,408
cpp
#include <bits/stdc++.h> using namespace std; #define PI acos(-1) #define EPS 1e-9 #define MOD 1e9+7 #define SET(a) memset(a , 0 , sizeof(a)) #define Fast ios_base::sync_with_stdio(false) int N , E , u , v; vector <vector <int>> adj; vector <int> DFS , visited; int Cycle = 0 , Bidirctional = 0 , Forward = 0; void GraphCheck (int u) { visited[u] = 2; for (auto v : adj[u]) { if (visited[v] == 0) { DFS[v] = u; GraphCheck(v); } else if (visited[v] == 2) { if (v == DFS[u]) { Bidirctional++; cout << "Bidirctional : " << u << " " << v << " - " << v << " " << u << endl; } else { Cycle++; cout << "Cycle : " << u << " " << v << endl; } } else if (visited[v] == 1) { Forward++; cout << "Forword : " << u << " " << v << endl; } } visited[u] = 1; } int main(){ Fast; cin >> N >> E; adj = vector <vector <int>> (N+1); visited = vector <int> (N+1); DFS = vector <int> (N+1); for (int i = 0; i < E; i++) { cin >> u >> v; adj[u].push_back(v); } for (int i = 1; i <= N; i++) { if (visited[i] == 0) GraphCheck(i); } cout << Cycle << " " << Bidirctional << " " << Forward << endl; return 0; }
[ "noreply@github.com" ]
Ahmed-Halim.noreply@github.com
76bdeca7897ed7ff2eac5fced34dfeddc4ac5899
1de85d140cb8846cc9daa0c68d2dce9e547750bc
/antlr_demo/thirdpart/antlr4/antlr4-runtime/tree/ErrorNodeImpl.h
87b804ed64a182b278cb72a8cb9014a6f423a26f
[ "MIT" ]
permissive
caicai0/ios_demo
22789cfad05adbe11fbd8091750f15357ef53d08
659dc972192c0ab2f8be16a4b695a88b3d7bc60b
refs/heads/master
2021-01-19T13:18:23.733595
2018-05-28T23:27:44
2018-05-28T23:27:44
82,381,342
1
0
null
null
null
null
UTF-8
C++
false
false
962
h
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. * Use of this file is governed by the BSD 3-clause license that * can be found in the LICENSE.txt file in the project root. */ #pragma once #include "ErrorNode.h" #include "TerminalNodeImpl.h" #include "Interval.h" #include "Any.h" namespace antlr4 { namespace tree { /// <summary> /// Represents a token that was consumed during resynchronization /// rather than during a valid match operation. For example, /// we will create this kind of a node during single token insertion /// and deletion as well as during "consume until error recovery set" /// upon no viable alternative exceptions. /// </summary> class ANTLR4CPP_PUBLIC ErrorNodeImpl : public virtual TerminalNodeImpl, public virtual ErrorNode { public: ErrorNodeImpl(Token *token); virtual antlrcpp::Any accept(ParseTreeVisitor *visitor) override; }; } // namespace tree } // namespace antlr4
[ "972008514@qq.com" ]
972008514@qq.com
1211025bded4239bee1075ce91e6d2b499d0988b
d79fde7ea8fa66cb00bf80ade480b8fd1e2026c6
/arduino/asservgrosrobot/driver/PID_Beta6.cpp
1782bf6753a18d8d30825c16dc0f8b8bc9799ad8
[]
no_license
utcoupe/Coupe2012
0904aa5685bd2ce6f4199fb2dccf96c16c36a972
6a2faf6aded4bab2fe2cb56023035a0b8b5917bf
refs/heads/master
2020-03-31T08:40:26.230775
2013-03-16T15:30:27
2013-03-16T15:30:27
2,495,593
7
0
null
null
null
null
UTF-8
C++
false
false
34
cpp
../../asserv5/driver/PID_Beta6.cpp
[ "thomas.recouvreux@gmail.com" ]
thomas.recouvreux@gmail.com
481ea54f9c7bd56fbc6879ce8af587054c41434d
aaf7b95178b1342ef0f7cb41cda19e8d62dd82e4
/src/CryptoNoteCore/CryptoNoteBasicImpl.h
fcd7d3afcebb9beadd62af4bf5774800397632a4
[ "MIT", "BSD-3-Clause" ]
permissive
mounirrquiba/novocoin-project
45c70b306eaa23350e2f398ae3057595dede6698
cb99bf47014343eabc0d1131d93fa050a07e430d
refs/heads/master
2020-03-10T03:07:01.908338
2018-04-09T22:29:13
2018-04-09T22:29:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,486
h
// Copyright (c) 2018 The Novocoin developers, Parts of this file are originally copyright (c) 2011-2016 The Cryptonote developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #pragma once #include "Common/StringTools.h" #include "crypto/crypto.h" #include "crypto/hash.h" #include "CryptoNoteCore/CryptoNoteBasic.h" namespace CryptoNote { /************************************************************************/ /* */ /************************************************************************/ template<class t_array> struct array_hasher: std::unary_function<t_array&, size_t> { size_t operator()(const t_array& val) const { return boost::hash_range(&val.data[0], &val.data[sizeof(val.data)]); } }; /************************************************************************/ /* CryptoNote helper functions */ /************************************************************************/ uint64_t getPenalizedAmount(uint64_t amount, size_t medianSize, size_t currentBlockSize); std::string getAccountAddressAsStr(uint64_t prefix, const AccountPublicAddress& adr); bool parseAccountAddressString(uint64_t& prefix, AccountPublicAddress& adr, const std::string& str); bool is_coinbase(const Transaction& tx); bool operator ==(const CryptoNote::Transaction& a, const CryptoNote::Transaction& b); bool operator ==(const CryptoNote::Block& a, const CryptoNote::Block& b); } template <class T> std::ostream &print256(std::ostream &o, const T &v) { return o << "<" << Common::podToHex(v) << ">"; } bool parse_hash256(const std::string& str_hash, Crypto::Hash& hash); namespace Crypto { inline std::ostream &operator <<(std::ostream &o, const Crypto::PublicKey &v) { return print256(o, v); } inline std::ostream &operator <<(std::ostream &o, const Crypto::SecretKey &v) { return print256(o, v); } inline std::ostream &operator <<(std::ostream &o, const Crypto::KeyDerivation &v) { return print256(o, v); } inline std::ostream &operator <<(std::ostream &o, const Crypto::KeyImage &v) { return print256(o, v); } inline std::ostream &operator <<(std::ostream &o, const Crypto::Signature &v) { return print256(o, v); } inline std::ostream &operator <<(std::ostream &o, const Crypto::Hash &v) { return print256(o, v); } }
[ "37153171+techqc@users.noreply.github.com" ]
37153171+techqc@users.noreply.github.com
7cb3f00d5252448f06cad2e646935f9bc9179c24
f5630241fdbca375962a48ca4d4ddb753927939c
/main.cpp
d8ef6db7a4961146f8ebe4081e27d292d4339ba6
[]
no_license
ellkorablina/First-summer-practice-project
4233ebfb09c05a5356728575b158c781c9cfd6ef
60dcb5be141311dedf6c7143ea7f76d10a71c3cc
refs/heads/master
2020-12-02T21:16:13.728246
2017-07-05T06:31:10
2017-07-05T06:31:10
96,284,498
0
1
null
null
null
null
UTF-8
C++
false
false
1,146
cpp
//#include "crtdynmem.h" #ifdef _DEBUG #define _CRTDBG_MAP_ALLOC #endif #include <crtdbg.h> #include "list.h" #include <iostream> using namespace std; int main() { setlocale(LC_ALL, "ru"); { my_list arr; cin >> arr; try{ cout << arr; } catch (const char *c) { cout<<c<<endl; } cout << "length=" << arr.length() << endl; cout << "count=" << arr.count_elem() << endl; cout << endl; try{ arr.print_elem(); } catch (const char *c) { cout<<c<<endl; } double d=5; arr.for_each(add_five); cout << endl; try{ cout << "i=5 data=" << arr[5] << endl;// work cout << "i=4 data=" << arr[4] << endl;// work } catch (const char *c) { cout<<c<<endl; } system("pause"); } _CrtDumpMemoryLeaks(); _CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_FILE ); _CrtSetReportFile( _CRT_WARN, _CRTDBG_FILE_STDOUT ); return 0; }
[ "noreply@github.com" ]
ellkorablina.noreply@github.com
b3426d44adce7f10bfd3271ef9f1cee5baf7afc2
28d33b9746d814de1a5a007f941c52375717f55d
/code/jni/states/GameStateManager.h
925096d158f64f96d4fe188ba020d3a31b1a407e
[]
no_license
andrewtc/AndroidWars
21aba7252384eb14e974e382a2120b8c6700bea6
e540c4bd9f950ffbb13afa3e2d3d7fa987898678
refs/heads/master
2021-01-17T21:02:15.892878
2014-05-13T20:02:12
2014-05-13T20:02:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,297
h
#pragma once namespace mage { /** * Manages and updates all registered GameStates. */ class GameStateManager { public: GameStateManager(); ~GameStateManager(); template< class GameStateSubclass > void ChangeState( const Dictionary& parameters = Dictionary() ); void CancelStateChange(); void DestroyActiveState(); void Update( float elapsedTime ); void Draw(); void OnScreenSizeChanged( int32 w, int32 h ); void OnPointerDown( const Pointer& pointer ); void OnPointerUp( const Pointer& pointer ); void OnPointerMotion( const Pointer& activePointer, const PointersByID& pointersByID ); GameState* GetActiveState() const; bool HasActiveState() const; bool HasPendingStateChange() const; private: void ExitActiveState(); GameState* mActiveState; GameState* mPendingState; Dictionary mPendingStateParameters; }; template< class GameStateSubclass > void GameStateManager::ChangeState( const Dictionary& parameters ) { // If we were about to transition to some other state, cancel the state change. CancelStateChange(); // Instantiate the new GameState instance to switch in. mPendingState = new GameStateSubclass(); // Copy the parameters to be passed to the new GameState instance. mPendingStateParameters = parameters; } }
[ "hydraskillz@gmail.com" ]
hydraskillz@gmail.com
bf85747031301acf3c6d27a65b7fd495aa5c62ff
6fc7689f8e0a4634f538b9e205c5a74538ddc0ce
/Snake.h
234a51f53c17a76826a6fecdbc9d504a25939430
[]
no_license
NikolaCv/ascii-games
4eca6a94b768732d53bafbfe154232f30959c238
083564c4097936684a8a8c97fc7f57e1444800ae
refs/heads/master
2020-04-05T09:37:27.167463
2019-04-24T17:37:28
2019-04-24T17:37:28
156,764,383
0
0
null
null
null
null
UTF-8
C++
false
false
488
h
#ifndef SNAKE_H_INCLUDED #define SNAKE_H_INCLUDED typedef struct Snake { int x, y ; }Snake; class zmija { private: int n, m, x, y, xf, yf; char mapa[100][100], c; Snake snake[10000]; int d, dir, eat; float speed, speedlim; char z; bool pobeda; public: zmija(); void draw(); void move(); bool gameover(); void food(); void eatf(); void pravac(); void gameoverprint(); bool pobedaf(); void pobedaprint(); // ~zmija(); }; #endif // SNAKE_H_INCLUDED
[ "44877969+NikolaCv@users.noreply.github.com" ]
44877969+NikolaCv@users.noreply.github.com
a64f48bb9b79807e6005a27686f0e2d8bfe43604
27361aae63bce47015d12c9c4e382b7952f22315
/GameLiftTutorial/Source/GameLiftTutorial/Public/MyActor.h
9f6ea1aa2ad42273e9744921bee3429c47331d2e
[]
no_license
WinterPu/GameLiftUE4-Repo
4d25518477789ccbb7576800adce2cc837f7d6d5
7a26474f9da2787d9085ee2a5ae0d32158c24434
refs/heads/master
2022-06-11T09:01:08.541808
2020-05-08T12:54:44
2020-05-08T12:54:44
261,746,296
0
0
null
null
null
null
UTF-8
C++
false
false
520
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/Actor.h" #include "MyActor.generated.h" UCLASS() class GAMELIFTTUTORIAL_API AMyActor : public AActor { GENERATED_BODY() public: // Sets default values for this actor's properties AMyActor(); protected: // Called when the game starts or when spawned virtual void BeginPlay() override; public: // Called every frame virtual void Tick(float DeltaTime) override; };
[ "striveant@outlook.com" ]
striveant@outlook.com
ed6f7fc8fdc5fd445b669e72a6d1a21083779ced
24ac6ca41cbc244cd6afdf9a826b9c4caf048064
/src/structures/molecule.h
a9abbe370137573620f1a34e5dab151054e35aff
[ "MIT" ]
permissive
sb-ncbr/ChargeFW2
65dfb6cc43716436526bb77ff3fa6b60c8c4f4c1
ff834973aee4c8bb349247dce72a4f6152329187
refs/heads/master
2023-05-22T14:20:28.559269
2023-05-22T05:37:00
2023-05-22T05:37:00
155,414,593
6
4
MIT
2023-05-22T05:37:02
2018-10-30T15:59:11
C++
UTF-8
C++
false
false
3,264
h
// // Created by krab1k on 23/10/18. // #pragma once #include <fmt/format.h> #include <utility> #include <string> #include <vector> #include <tuple> #include <map> #include <memory> #include <nanoflann.hpp> #include "atom.h" #include "bond.h" class AtomKDTreeAdaptor; typedef nanoflann::KDTreeSingleIndexAdaptor< nanoflann::L2_Simple_Adaptor<double, AtomKDTreeAdaptor>, AtomKDTreeAdaptor, 3> kdtree_t; class Molecule { std::string name_; std::unique_ptr<std::vector<Atom> > atoms_; std::unique_ptr<std::vector<Bond> > bonds_; std::vector<int> max_hbo_{}; std::vector<std::string> neighbour_elements_{}; std::vector<char> bond_info_{}; std::vector<int> bond_distances_{}; std::unique_ptr<kdtree_t> index_{nullptr}; std::unique_ptr<AtomKDTreeAdaptor> adaptor_{nullptr}; [[nodiscard]] std::vector<size_t> get_bonded(size_t atom_idx) const; void init_bond_info(); void init_bond_distances(); void init_distance_tree(); public: [[nodiscard]] const std::vector<Atom> &atoms() const { return *atoms_; } [[nodiscard]] const std::vector<Bond> &bonds() const { return *bonds_; } [[nodiscard]] const std::string &name() const { return name_; } [[nodiscard]] bool bonded(const Atom &atom1, const Atom &atom2) const; [[nodiscard]] const Bond *get_bond(const Atom &atom1, const Atom &atom2) const; [[nodiscard]] int bond_order(const Atom &atom1, const Atom &atom2) const; [[nodiscard]] int degree(const Atom &atom) const; [[nodiscard]] const std::vector<int> &get_max_bond_orders() const { return max_hbo_; } [[nodiscard]] const std::vector<std::string> &get_bonded_elements() const { return neighbour_elements_; } [[nodiscard]] std::vector<const Atom *> get_close_atoms(const Atom &atom, double cutoff) const; Molecule() = default; Molecule(std::string name, std::unique_ptr<std::vector<Atom> > atoms, std::unique_ptr<std::vector<Bond> > bonds); [[nodiscard]] int bond_distance(const Atom &atom1, const Atom &atom2) const; [[nodiscard]] std::vector<const Atom *> k_bond_distance(const Atom &atom, size_t k) const; [[nodiscard]] int total_charge() const; [[nodiscard]] bool is_protein() const { return not(*atoms_)[0].chain_id().empty(); } friend class MoleculeSet; }; namespace fmt { template<> struct formatter<Molecule> { template<typename ParseContext> constexpr auto parse(ParseContext &ctx) { return ctx.begin(); } template<typename FormatContext> auto format(const Molecule &m, FormatContext &ctx) { return format_to(ctx.begin(), "Molecule {} Atoms: {} Bonds {}\n", m.name(), m.atoms().size(), m.bonds().size()); } }; } class AtomKDTreeAdaptor { const Molecule *molecule_; public: explicit AtomKDTreeAdaptor(const Molecule *molecule) : molecule_{molecule} {} [[nodiscard]] inline size_t kdtree_get_point_count() const { return molecule_->atoms().size(); } [[nodiscard]] inline double kdtree_get_pt(const size_t idx, const size_t dim) const { return molecule_->atoms()[idx].pos()[dim]; } template<class BBOX> bool kdtree_get_bbox(BBOX &) const { return false; } };
[ "tom@krab1k.net" ]
tom@krab1k.net
84d72bea9696b6c33e91a694e149ffea4346a0cb
f1351774d78768797b1264189ee32744da7cae0b
/cyber/node/reader.h
2272cb314727c5448fc14f3551d03e2478c462ea
[ "Apache-2.0" ]
permissive
quning18/apollo_ros_bridge
ffe46f93bad39550eff7c6115a0a4fa74fcc4e4d
dcf3974281f714c45d55a2abf893e82ff95c5012
refs/heads/master
2020-06-24T19:30:16.086950
2019-08-08T20:43:52
2019-08-08T20:43:52
199,062,290
3
0
Apache-2.0
2019-07-26T18:20:46
2019-07-26T18:20:45
null
UTF-8
C++
false
false
9,710
h
/****************************************************************************** * Copyright 2018 The Apollo Authors. 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. *****************************************************************************/ #ifndef CYBER_NODE_READER_H_ #define CYBER_NODE_READER_H_ #include <algorithm> #include <list> #include <memory> #include <mutex> #include <string> #include <unordered_map> #include <utility> #include <vector> #include "cyber/blocker/blocker.h" #include "cyber/common/global_data.h" #include "cyber/croutine/routine_factory.h" #include "cyber/data/data_visitor.h" #include "cyber/node/reader_base.h" #include "cyber/proto/topology_change.pb.h" #include "cyber/scheduler/scheduler_factory.h" #include "cyber/service_discovery/topology_manager.h" #include "cyber/time/time.h" #include "cyber/transport/transport.h" namespace apollo { namespace cyber { template <typename M0> using CallbackFunc = std::function<void(const std::shared_ptr<M0>&)>; using proto::RoleType; const uint32_t DEFAULT_PENDING_QUEUE_SIZE = 1; /** * @class Reader * @brief . * * Reader objecte subscribes to the channel for message received. * */ template <typename MessageT> class Reader : public ReaderBase { public: using BlockerPtr = std::unique_ptr<blocker::Blocker<MessageT>>; using ReceiverPtr = std::shared_ptr<transport::Receiver<MessageT>>; using ChangeConnection = typename service_discovery::Manager::ChangeConnection; using Iterator = typename std::list<std::shared_ptr<MessageT>>::const_iterator; /** * @brief Constuctor a Reader object. * * @param role_attr is a protobuf message RoleAttributes, which includes the * channel name and other info. * @param reader_func is the callback function, when the message is recevied. * @param pending_queue_size is the max depth of message cache queue. * @warning the recevied messages is enqueue a queue,the queue's depth is * pending_queue_size */ explicit Reader(const proto::RoleAttributes& role_attr, const CallbackFunc<MessageT>& reader_func = nullptr, uint32_t pending_queue_size = DEFAULT_PENDING_QUEUE_SIZE); virtual ~Reader(); bool Init() override; void Shutdown() override; void Observe() override; void ClearData() override; bool HasReceived() const override; bool Empty() const override; double GetDelaySec() const override; uint32_t PendingQueueSize() const override; virtual void Enqueue(const std::shared_ptr<MessageT>& msg); virtual void SetHistoryDepth(const uint32_t& depth); virtual uint32_t GetHistoryDepth() const; virtual std::shared_ptr<MessageT> GetLatestObserved() const; virtual std::shared_ptr<MessageT> GetOldestObserved() const; virtual Iterator Begin() const { return blocker_->ObservedBegin(); } virtual Iterator End() const { return blocker_->ObservedEnd(); } bool HasWriter() override; void GetWriters(std::vector<proto::RoleAttributes>* writers) override; protected: double latest_recv_time_sec_ = -1.0; double second_to_lastest_recv_time_sec_ = -1.0; uint32_t pending_queue_size_; private: void JoinTheTopology(); void LeaveTheTopology(); void OnChannelChange(const proto::ChangeMsg& change_msg); CallbackFunc<MessageT> reader_func_; ReceiverPtr receiver_ = nullptr; std::string croutine_name_; BlockerPtr blocker_ = nullptr; ChangeConnection change_conn_; service_discovery::ChannelManagerPtr channel_manager_ = nullptr; }; template <typename MessageT> Reader<MessageT>::Reader(const proto::RoleAttributes& role_attr, const CallbackFunc<MessageT>& reader_func, uint32_t pending_queue_size) : ReaderBase(role_attr), pending_queue_size_(pending_queue_size), reader_func_(reader_func) { blocker_.reset(new blocker::Blocker<MessageT>(blocker::BlockerAttr( role_attr.qos_profile().depth(), role_attr.channel_name()))); } template <typename MessageT> Reader<MessageT>::~Reader() { Shutdown(); } template <typename MessageT> void Reader<MessageT>::Enqueue(const std::shared_ptr<MessageT>& msg) { second_to_lastest_recv_time_sec_ = latest_recv_time_sec_; latest_recv_time_sec_ = Time::Now().ToSecond(); blocker_->Publish(msg); } template <typename MessageT> void Reader<MessageT>::Observe() { blocker_->Observe(); } template <typename MessageT> bool Reader<MessageT>::Init() { if (init_.exchange(true)) { return true; } std::function<void(const std::shared_ptr<MessageT>&)> func; if (reader_func_ != nullptr) { func = [this](const std::shared_ptr<MessageT>& msg) { this->Enqueue(msg); this->reader_func_(msg); }; } else { func = [this](const std::shared_ptr<MessageT>& msg) { this->Enqueue(msg); }; } auto sched = scheduler::Instance(); croutine_name_ = role_attr_.node_name() + "_" + role_attr_.channel_name(); auto dv = std::make_shared<data::DataVisitor<MessageT>>( role_attr_.channel_id(), pending_queue_size_); // Using factory to wrap templates. croutine::RoutineFactory factory = croutine::CreateRoutineFactory<MessageT>(std::move(func), dv); if (!sched->CreateTask(factory, croutine_name_)) { AERROR << "Create Task Failed!"; init_.exchange(false); return false; } receiver_ = ReceiverManager<MessageT>::Instance()->GetReceiver(role_attr_); this->role_attr_.set_id(receiver_->id().HashValue()); channel_manager_ = service_discovery::TopologyManager::Instance()->channel_manager(); JoinTheTopology(); return true; } template <typename MessageT> void Reader<MessageT>::Shutdown() { if (!init_.exchange(false)) { return; } LeaveTheTopology(); receiver_ = nullptr; channel_manager_ = nullptr; if (!croutine_name_.empty()) { scheduler::Instance()->RemoveTask(croutine_name_); } } template <typename MessageT> void Reader<MessageT>::JoinTheTopology() { // add listener change_conn_ = channel_manager_->AddChangeListener(std::bind( &Reader<MessageT>::OnChannelChange, this, std::placeholders::_1)); // get peer writers const std::string& channel_name = this->role_attr_.channel_name(); std::vector<proto::RoleAttributes> writers; channel_manager_->GetWritersOfChannel(channel_name, &writers); for (auto& writer : writers) { receiver_->Enable(writer); } channel_manager_->Join(this->role_attr_, proto::RoleType::ROLE_READER, message::HasSerializer<MessageT>::value); } template <typename MessageT> void Reader<MessageT>::LeaveTheTopology() { channel_manager_->RemoveChangeListener(change_conn_); channel_manager_->Leave(this->role_attr_, proto::RoleType::ROLE_READER); } template <typename MessageT> void Reader<MessageT>::OnChannelChange(const proto::ChangeMsg& change_msg) { if (change_msg.role_type() != proto::RoleType::ROLE_WRITER) { return; } auto& writer_attr = change_msg.role_attr(); if (writer_attr.channel_name() != this->role_attr_.channel_name()) { return; } auto operate_type = change_msg.operate_type(); if (operate_type == proto::OperateType::OPT_JOIN) { receiver_->Enable(writer_attr); } else { receiver_->Disable(writer_attr); } } template <typename MessageT> bool Reader<MessageT>::HasReceived() const { return !blocker_->IsPublishedEmpty(); } template <typename MessageT> bool Reader<MessageT>::Empty() const { return blocker_->IsObservedEmpty(); } template <typename MessageT> double Reader<MessageT>::GetDelaySec() const { if (latest_recv_time_sec_ < 0) { return -1.0; } if (second_to_lastest_recv_time_sec_ < 0) { return Time::Now().ToSecond() - latest_recv_time_sec_; } return std::max((Time::Now().ToSecond() - latest_recv_time_sec_), (latest_recv_time_sec_ - second_to_lastest_recv_time_sec_)); } template <typename MessageT> uint32_t Reader<MessageT>::PendingQueueSize() const { return pending_queue_size_; } template <typename MessageT> std::shared_ptr<MessageT> Reader<MessageT>::GetLatestObserved() const { return blocker_->GetLatestObservedPtr(); } template <typename MessageT> std::shared_ptr<MessageT> Reader<MessageT>::GetOldestObserved() const { return blocker_->GetOldestObservedPtr(); } template <typename MessageT> void Reader<MessageT>::ClearData() { blocker_->ClearPublished(); blocker_->ClearObserved(); } template <typename MessageT> void Reader<MessageT>::SetHistoryDepth(const uint32_t& depth) { blocker_->set_capacity(depth); } template <typename MessageT> uint32_t Reader<MessageT>::GetHistoryDepth() const { return static_cast<uint32_t>(blocker_->capacity()); } template <typename MessageT> bool Reader<MessageT>::HasWriter() { if (!init_.load()) { return false; } return channel_manager_->HasWriter(role_attr_.channel_name()); } template <typename MessageT> void Reader<MessageT>::GetWriters(std::vector<proto::RoleAttributes>* writers) { if (writers == nullptr) { return; } if (!init_.load()) { return; } channel_manager_->GetWritersOfChannel(role_attr_.channel_name(), writers); } } // namespace cyber } // namespace apollo #endif // CYBER_NODE_READER_H_
[ "abhilash@ridecell.com" ]
abhilash@ridecell.com
f5eb972526f33d8c88b2f6bf5cf0d856ee76ee0c
022ddbfd08623b855f50331861309d5429753d99
/比赛/PAT/乙级/1005德才论 (25)/main.cpp
32249f58dc8ea1437bba659d369eeb54b862d68b
[]
no_license
xluos/ACM
06d6881dac8c12e6e0ded66fc5da43974e3520e7
e90707178cc203e0e36092dc73bdc807c7daa246
refs/heads/master
2020-06-21T07:20:14.584736
2018-03-20T13:26:53
2018-03-20T13:26:53
94,203,765
4
0
null
null
null
null
UTF-8
C++
false
false
1,150
cpp
#include <bits/stdc++.h> using namespace std; struct node{ int id,de,ca,lei,zong; }; int cmp(node a,node b) { if(a.lei==b.lei) { if(a.zong==b.zong) { if(a.de==b.de) return a.id<b.id; return a.de>b.de; } return a.zong>b.zong; } return a.lei<b.lei; } int main() { int sum=0,n,l,h; node a[100005],ans; cin>>n>>l>>h; while(n--) { scanf("%d %d %d",&ans.id,&ans.de,&ans.ca); if(ans.ca>=l&&ans.de>=l) { ans.zong=ans.ca+ans.de; if(ans.de>=h) { if(ans.ca>=h) ans.lei=1; else ans.lei=2; } else { if(ans.de>=ans.ca) ans.lei=3; else ans.lei=4; } a[sum++]=ans; } } sort(a,a+sum,cmp); cout<<sum<<endl; for(int i=0;i<sum;i++) { printf("%d %d %d\n",a[i].id,a[i].de,a[i].ca); } return 0; }
[ "email@xluos.com" ]
email@xluos.com