hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
a84442cee063dad11d5a9cad2c5d748f9fcc3c46
4,971
cc
C++
src/actions/transformations/js_decode.cc
Peercraft/deb-modsecurity
6d608c3ea5d762b370bf682ba24e2febffd4f382
[ "Apache-2.0" ]
null
null
null
src/actions/transformations/js_decode.cc
Peercraft/deb-modsecurity
6d608c3ea5d762b370bf682ba24e2febffd4f382
[ "Apache-2.0" ]
null
null
null
src/actions/transformations/js_decode.cc
Peercraft/deb-modsecurity
6d608c3ea5d762b370bf682ba24e2febffd4f382
[ "Apache-2.0" ]
null
null
null
/* * ModSecurity, http://www.modsecurity.org/ * Copyright (c) 2015 Trustwave Holdings, Inc. (http://www.trustwave.com/) * * 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 * * If any of the files related to licensing are missing or if you have any * other questions related to licensing please contact Trustwave Holdings, Inc. * directly using the email address security@modsecurity.org. * */ #include "src/actions/transformations/js_decode.h" #include <string.h> #include <iostream> #include <string> #include <algorithm> #include <functional> #include <cctype> #include <locale> #include "modsecurity/transaction.h" #include "src/actions/transformations/transformation.h" #include "src/utils/string.h" namespace modsecurity { namespace actions { namespace transformations { std::string JsDecode::evaluate(std::string value, Transaction *transaction) { std::string ret; unsigned char *input = NULL; input = reinterpret_cast<unsigned char *> (malloc(sizeof(char) * value.length()+1)); if (input == NULL) { return ""; } memcpy(input, value.c_str(), value.length()+1); size_t i = inplace(input, value.length()); ret.assign(reinterpret_cast<char *>(input), i); free(input); return ret; } int JsDecode::inplace(unsigned char *input, u_int64_t input_len) { unsigned char *d = (unsigned char *)input; int64_t i, count; i = count = 0; while (i < input_len) { if (input[i] == '\\') { /* Character is an escape. */ if ((i + 5 < input_len) && (input[i + 1] == 'u') && (VALID_HEX(input[i + 2])) && (VALID_HEX(input[i + 3])) && (VALID_HEX(input[i + 4])) && (VALID_HEX(input[i + 5]))) { /* \uHHHH */ /* Use only the lower byte. */ *d = utils::string::x2c(&input[i + 4]); /* Full width ASCII (ff01 - ff5e) needs 0x20 added */ if ((*d > 0x00) && (*d < 0x5f) && ((input[i + 2] == 'f') || (input[i + 2] == 'F')) && ((input[i + 3] == 'f') || (input[i + 3] == 'F'))) { (*d) += 0x20; } d++; count++; i += 6; } else if ((i + 3 < input_len) && (input[i + 1] == 'x') && VALID_HEX(input[i + 2]) && VALID_HEX(input[i + 3])) { /* \xHH */ *d++ = utils::string::x2c(&input[i + 2]); count++; i += 4; } else if ((i + 1 < input_len) && ISODIGIT(input[i + 1])) { /* \OOO (only one byte, \000 - \377) */ char buf[4]; int j = 0; while ((i + 1 + j < input_len) && (j < 3)) { buf[j] = input[i + 1 + j]; j++; if (!ISODIGIT(input[i + 1 + j])) break; } buf[j] = '\0'; if (j > 0) { /* Do not use 3 characters if we will be > 1 byte */ if ((j == 3) && (buf[0] > '3')) { j = 2; buf[j] = '\0'; } *d++ = (unsigned char)strtol(buf, NULL, 8); i += 1 + j; count++; } } else if (i + 1 < input_len) { /* \C */ unsigned char c = input[i + 1]; switch (input[i + 1]) { case 'a' : c = '\a'; break; case 'b' : c = '\b'; break; case 'f' : c = '\f'; break; case 'n' : c = '\n'; break; case 'r' : c = '\r'; break; case 't' : c = '\t'; break; case 'v' : c = '\v'; break; /* The remaining (\?,\\,\',\") are just a removal * of the escape char which is default. */ } *d++ = c; i += 2; count++; } else { /* Not enough bytes */ while (i < input_len) { *d++ = input[i++]; count++; } } } else { *d++ = input[i++]; count++; } } *d = '\0'; return count; } } // namespace transformations } // namespace actions } // namespace modsecurity
29.414201
79
0.396097
Peercraft
a844f6aba74c1648276a9afad698796cd588e967
578
cc
C++
zircon/system/ulib/blobfs/test/zstd-fuzzer.cc
casey/fuchsia
2b965e9a1e8f2ea346db540f3611a5be16bb4d6b
[ "BSD-3-Clause" ]
14
2020-10-25T05:48:36.000Z
2021-09-20T02:46:20.000Z
src/storage/blobfs/test/zstd-fuzzer.cc
JokeZhang/fuchsia
d6e9dea8dca7a1c8fa89d03e131367e284b30d23
[ "BSD-3-Clause" ]
1
2022-01-14T23:38:40.000Z
2022-01-14T23:38:40.000Z
src/storage/blobfs/test/zstd-fuzzer.cc
JokeZhang/fuchsia
d6e9dea8dca7a1c8fa89d03e131367e284b30d23
[ "BSD-3-Clause" ]
4
2020-12-28T17:04:45.000Z
2022-03-12T03:20:44.000Z
// Copyright 2019 The Fuchsia 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 <vector> #include "compression/zstd-plain.h" extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { size_t compressed_size = size; size_t uncompressed_size = size * 2; std::vector<uint8_t> uncompressed_buf(uncompressed_size); blobfs::ZSTDDecompressor decompressor; decompressor.Decompress(uncompressed_buf.data(), &uncompressed_size, data, compressed_size); return 0; }
32.111111
94
0.768166
casey
a8456f4eb566a0323d9dd3568e9f97544a298234
3,114
cpp
C++
modfile/records/obbaserecord.cpp
uesp/tes4lib
7b426c9209ff7996d3d763e6d4e217abfefae406
[ "MIT" ]
1
2021-02-07T07:32:14.000Z
2021-02-07T07:32:14.000Z
modfile/records/obbaserecord.cpp
uesp/tes4lib
7b426c9209ff7996d3d763e6d4e217abfefae406
[ "MIT" ]
null
null
null
modfile/records/obbaserecord.cpp
uesp/tes4lib
7b426c9209ff7996d3d763e6d4e217abfefae406
[ "MIT" ]
null
null
null
/*=========================================================================== * * File: Obbaserecord.CPP * Author: Dave Humphrey (uesp@m0use.net) * Created On: April 10, 2006 * * Description * *=========================================================================*/ /* Include Files */ #include "obbaserecord.h" #include "../obrecordhandler.h" /*=========================================================================== * * Class CObBaseRecord Constructor * *=========================================================================*/ CObBaseRecord::CObBaseRecord () { m_pParent = NULL; m_pParentGroup = NULL; m_CacheFlags = 0; } /*=========================================================================== * End of Class CObBaseRecord Constructor *=========================================================================*/ /*=========================================================================== * * Class CObBaseRecord Destructor * *=========================================================================*/ CObBaseRecord::~CObBaseRecord () { Destroy(); } /*=========================================================================== * End of Class CObBaseRecord Destructor *=========================================================================*/ /*=========================================================================== * * Class CObBaseRecord Method - void Destroy (void); * * Destroy object contents. * *=========================================================================*/ void CObBaseRecord::Destroy (void) { m_pParentGroup = NULL; m_CacheFlags = 0; } /*=========================================================================== * End of Class Method CObBaseRecord::Destroy() *=========================================================================*/ /*=========================================================================== * * Class CObBaseRecord Method - bool IsActive (void) const; * *=========================================================================*/ bool CObBaseRecord::IsActive (void) const { return (m_pParent ? m_pParent->IsActive() : false); } /*=========================================================================== * End of Class Method CObBaseRecord::IsActive() *=========================================================================*/ /*=========================================================================== * * Function - bool ReadObBaseHeader (File, Header); * * Helper function to read base header data for a group or record * from the current location in the given file. * *=========================================================================*/ bool ReadObBaseHeader (CObFile& File, obbaseheader_t& Header) { return File.Read(&Header, OB_BASEHEADER_SIZE); } /*=========================================================================== * End of Function ReadObBaseHeader() *=========================================================================*/
35.386364
78
0.293192
uesp
a8484a0e76b6ce7699001f2443443000fd133519
7,230
cc
C++
components/sync/engine/net/sync_server_connection_manager.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
575
2015-06-18T23:58:20.000Z
2022-03-23T09:32:39.000Z
components/sync/engine/net/sync_server_connection_manager.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
components/sync/engine/net/sync_server_connection_manager.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
52
2015-07-14T10:40:50.000Z
2022-03-15T01:11:49.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/sync/engine/net/sync_server_connection_manager.h" #include <stdint.h> #include <utility> #include "base/bind.h" #include "base/callback_helpers.h" #include "components/sync/engine/cancelation_signal.h" #include "components/sync/engine/net/http_post_provider_factory.h" #include "components/sync/engine/net/http_post_provider_interface.h" #include "net/base/net_errors.h" #include "net/http/http_status_code.h" namespace syncer { namespace { // This provides HTTP Post functionality through the interface provided // by the application hosting the syncer backend. class Connection : public CancelationSignal::Observer { public: // All pointers must not be null and must outlive this object. Connection(HttpPostProviderFactory* factory, CancelationSignal* cancelation_signal); ~Connection() override; HttpResponse Init(const GURL& connection_url, const std::string& access_token, const std::string& payload); bool ReadBufferResponse(std::string* buffer_out, HttpResponse* response); bool ReadDownloadResponse(HttpResponse* response, std::string* buffer_out); // CancelationSignal::Observer overrides. void OnCancelationSignalReceived() override; private: int ReadResponse(std::string* out_buffer, int length) const; // Pointer to the factory we use for creating HttpPostProviders. We do not // own |factory_|. HttpPostProviderFactory* const factory_; // Cancelation signal is signalled when engine shuts down. Current blocking // operation should be aborted. CancelationSignal* const cancelation_signal_; scoped_refptr<HttpPostProviderInterface> const post_provider_; std::string buffer_; DISALLOW_COPY_AND_ASSIGN(Connection); }; Connection::Connection(HttpPostProviderFactory* factory, CancelationSignal* cancelation_signal) : factory_(factory), cancelation_signal_(cancelation_signal), post_provider_(factory_->Create()) { DCHECK(factory); DCHECK(cancelation_signal); DCHECK(post_provider_); } Connection::~Connection() = default; HttpResponse Connection::Init(const GURL& sync_request_url, const std::string& access_token, const std::string& payload) { post_provider_->SetURL(sync_request_url); if (!access_token.empty()) { std::string headers; headers = "Authorization: Bearer " + access_token; post_provider_->SetExtraRequestHeaders(headers.c_str()); } // Must be octet-stream, or the payload may be parsed for a cookie. post_provider_->SetPostPayload("application/octet-stream", payload.length(), payload.data()); // Issue the POST, blocking until it finishes. if (!cancelation_signal_->TryRegisterHandler(this)) { // Return early because cancelation signal was signaled. return HttpResponse::ForUnspecifiedError(); } base::ScopedClosureRunner auto_unregister(base::BindOnce( &CancelationSignal::UnregisterHandler, base::Unretained(cancelation_signal_), base::Unretained(this))); int net_error_code = 0; int http_status_code = 0; if (!post_provider_->MakeSynchronousPost(&net_error_code, &http_status_code)) { DCHECK_NE(net_error_code, net::OK); DVLOG(1) << "Http POST failed, error returns: " << net_error_code; return HttpResponse::ForNetError(net_error_code); } // We got a server response, copy over response codes and content. HttpResponse response = HttpResponse::ForHttpStatusCode(http_status_code); response.content_length = static_cast<int64_t>(post_provider_->GetResponseContentLength()); response.payload_length = static_cast<int64_t>(post_provider_->GetResponseContentLength()); // Write the content into the buffer. buffer_.assign(post_provider_->GetResponseContent(), post_provider_->GetResponseContentLength()); return response; } bool Connection::ReadBufferResponse(std::string* buffer_out, HttpResponse* response) { if (net::HTTP_OK != response->http_status_code) { response->server_status = HttpResponse::SYNC_SERVER_ERROR; return false; } if (response->content_length <= 0) return false; const int64_t bytes_read = ReadResponse(buffer_out, static_cast<int>(response->content_length)); if (bytes_read != response->content_length) { response->server_status = HttpResponse::IO_ERROR; return false; } return true; } bool Connection::ReadDownloadResponse(HttpResponse* response, std::string* buffer_out) { const int64_t bytes_read = ReadResponse(buffer_out, static_cast<int>(response->content_length)); if (bytes_read != response->content_length) { LOG(ERROR) << "Mismatched content lengths, server claimed " << response->content_length << ", but sent " << bytes_read; response->server_status = HttpResponse::IO_ERROR; return false; } return true; } int Connection::ReadResponse(std::string* out_buffer, int length) const { int bytes_read = buffer_.length(); CHECK_LE(length, bytes_read); out_buffer->assign(buffer_); return bytes_read; } void Connection::OnCancelationSignalReceived() { DCHECK(post_provider_); post_provider_->Abort(); } } // namespace SyncServerConnectionManager::SyncServerConnectionManager( const GURL& sync_request_url, std::unique_ptr<HttpPostProviderFactory> factory, CancelationSignal* cancelation_signal) : sync_request_url_(sync_request_url), post_provider_factory_(std::move(factory)), cancelation_signal_(cancelation_signal) { DCHECK(post_provider_factory_); DCHECK(cancelation_signal_); } SyncServerConnectionManager::~SyncServerConnectionManager() = default; HttpResponse SyncServerConnectionManager::PostBuffer( const std::string& buffer_in, const std::string& access_token, std::string* buffer_out) { if (access_token.empty()) { // Print a log to distinguish this "known failure" from others. DVLOG(1) << "ServerConnectionManager forcing SYNC_AUTH_ERROR due to missing" " access token"; return HttpResponse::ForHttpStatusCode(net::HTTP_UNAUTHORIZED); } if (cancelation_signal_->IsSignalled()) { return HttpResponse::ForUnspecifiedError(); } auto connection = std::make_unique<Connection>(post_provider_factory_.get(), cancelation_signal_); // Note that the post may be aborted by now, which will just cause Init to // fail with CONNECTION_UNAVAILABLE. HttpResponse http_response = connection->Init(sync_request_url_, access_token, buffer_in); if (http_response.server_status == HttpResponse::SYNC_AUTH_ERROR) { ClearAccessToken(); } else if (http_response.server_status == HttpResponse::SERVER_CONNECTION_OK) { connection->ReadBufferResponse(buffer_out, &http_response); } return http_response; } } // namespace syncer
34.428571
80
0.717151
Ron423c
a859ffcda73443198aa4f1e6f89bd3a2501e2e90
2,541
hpp
C++
ivarp/include/ivarp/math_fn/eval/custom.hpp
phillip-keldenich/squares-in-disk
501ebeb00b909b9264a9611fd63e082026cdd262
[ "MIT" ]
null
null
null
ivarp/include/ivarp/math_fn/eval/custom.hpp
phillip-keldenich/squares-in-disk
501ebeb00b909b9264a9611fd63e082026cdd262
[ "MIT" ]
null
null
null
ivarp/include/ivarp/math_fn/eval/custom.hpp
phillip-keldenich/squares-in-disk
501ebeb00b909b9264a9611fd63e082026cdd262
[ "MIT" ]
null
null
null
// The code is open source under the MIT license. // Copyright 2019-2020, Phillip Keldenich, TU Braunschweig, Algorithms Group // https://ibr.cs.tu-bs.de/alg // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies // of the Software, and to permit persons to whom the Software is furnished to do // so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // // Created by Phillip Keldenich on 22.11.19. // #pragma once namespace ivarp { namespace impl { template<typename Context, typename FnType, typename... Args_, typename ArgArray> struct EvaluateImpl<Context, MathCustomFunction<FnType,Args_...>, ArgArray> { using CalledType = MathCustomFunction<FnType,Args_...>; using NumberType = typename Context::NumberType; using ArgsType = typename CalledType::Args; IVARP_HD_OVERLOAD_ON_CUDA_NT(NumberType, static NumberType eval(const CalledType& c, const ArgArray& args) noexcept(AllowsCUDA<NumberType>::value) { return do_eval(c, args, IndexRange<0,sizeof...(Args_)>{}); } ) private: IVARP_HD_OVERLOAD_TEMPLATE_ON_CUDA_NT(IVARP_TEMPLATE_PARAMS(std::size_t... Inds), NumberType, static NumberType do_eval(const CalledType& c, const ArgArray& args, IndexPack<Inds...>) noexcept(AllowsCUDA<NumberType>::value) { return c.functor.template eval<Context>( (PredicateEvaluateImpl<Context, TupleElementType<Inds,ArgsType>, ArgArray>::eval( get<Inds>(c.args), args ))... ); } ) }; } }
43.067797
117
0.681621
phillip-keldenich
a85be22b7ff30f9baa398b2a425d727c6faf163b
14,129
cpp
C++
test/range/test-any_range.cpp
rogiervd/range
2ed4ee2063a02cadc575fe4e7a3b7dd61bbd2b5d
[ "Apache-2.0" ]
null
null
null
test/range/test-any_range.cpp
rogiervd/range
2ed4ee2063a02cadc575fe4e7a3b7dd61bbd2b5d
[ "Apache-2.0" ]
null
null
null
test/range/test-any_range.cpp
rogiervd/range
2ed4ee2063a02cadc575fe4e7a3b7dd61bbd2b5d
[ "Apache-2.0" ]
null
null
null
/* Copyright 2013, 2015 Rogier van Dalen. 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. */ #define BOOST_TEST_MODULE test_range_any_range #include "utility/test/boost_unit_test.hpp" #include "range/any_range.hpp" #include <list> #include <vector> #include <tuple> #include "range/std.hpp" #include "range/tuple.hpp" #include "range/function_range.hpp" #include "weird_count.hpp" #include "unique_range.hpp" using range::front; using range::back; using range::default_direction; using range::empty; using range::size; using range::first; using range::drop; using range::chop; using range::chop_in_place; using range::has; namespace callable = range::callable; using range::any_range; using range::make_any_range; BOOST_AUTO_TEST_SUITE(test_range_any_range) BOOST_AUTO_TEST_CASE (test_any_range_has) { { typedef any_range <int, range::capability::unique_capabilities> range; // first and drop only available for rvalue references. static_assert (has <callable::empty (range const &)>::value, ""); static_assert (!has <callable::first (range const &)>::value, ""); static_assert (!has <callable::size (range const &)>::value, ""); static_assert (!has <callable::drop (range const &)>::value, ""); static_assert (!has <callable::drop (range const &, int)>::value, ""); static_assert (has <callable::chop (range &&)>::value, ""); static_assert (has <callable::chop_in_place (range &)>::value, ""); static_assert (has < callable::empty (range const &, direction::back)>::value, ""); static_assert (!has < callable::first (range const &, direction::back)>::value, ""); static_assert (!has < callable::size (range const &, direction::back)>::value, ""); static_assert (!has < callable::drop (range const &, direction::back)>::value, ""); static_assert (!has < callable::drop (range const &, int, direction::back)>::value, ""); static_assert (!has < callable::chop (range &&, direction::back)>::value, ""); static_assert (!has < callable::chop_in_place (range &, direction::back)>::value, ""); } { typedef any_range <int, range::capability::forward_capabilities> range; static_assert (has <callable::empty (range const &)>::value, ""); static_assert (has <callable::first (range const &)>::value, ""); static_assert (!has <callable::size (range const &)>::value, ""); static_assert (has <callable::drop (range const &)>::value, ""); static_assert (!has <callable::drop (range const &, int)>::value, ""); static_assert (has <callable::chop (range &&)>::value, ""); static_assert (has <callable::chop_in_place (range &)>::value, ""); static_assert (has < callable::empty (range const &, direction::back)>::value, ""); static_assert (!has < callable::first (range const &, direction::back)>::value, ""); static_assert (!has < callable::size (range const &, direction::back)>::value, ""); static_assert (!has < callable::drop (range const &, direction::back)>::value, ""); static_assert (!has < callable::drop (range const &, int, direction::back)>::value, ""); static_assert (!has < callable::chop (range &&, direction::back)>::value, ""); static_assert (!has < callable::chop_in_place (range &, direction::back)>::value, ""); } { typedef any_range <int, range::capability::bidirectional_capabilities> range; static_assert (has <callable::empty (range const &)>::value, ""); static_assert (has <callable::first (range const &)>::value, ""); static_assert (!has <callable::size (range const &)>::value, ""); static_assert (has <callable::drop (range const &)>::value, ""); static_assert (!has <callable::drop (range const &, int)>::value, ""); static_assert (has <callable::chop (range &&)>::value, ""); static_assert (has <callable::chop_in_place (range &)>::value, ""); static_assert (has < callable::empty (range const &, direction::back)>::value, ""); static_assert (has < callable::first (range const &, direction::back)>::value, ""); static_assert (!has < callable::size (range const &, direction::back)>::value, ""); static_assert (has < callable::drop (range const &, direction::back)>::value, ""); static_assert (!has < callable::drop (range const &, int, direction::back)>::value, ""); static_assert (has < callable::chop (range &&, direction::back)>::value, ""); static_assert (has < callable::chop_in_place (range &, direction::back)>::value, ""); } { typedef any_range <int, range::capability::random_access_capabilities> range; static_assert (has <callable::empty (range const &)>::value, ""); static_assert (has <callable::first (range const &)>::value, ""); static_assert (has <callable::size (range const &)>::value, ""); static_assert (has <callable::drop (range const &)>::value, ""); static_assert (has <callable::drop (range const &, int)>::value, ""); static_assert (has <callable::chop (range &&)>::value, ""); static_assert (has <callable::chop_in_place (range &)>::value, ""); static_assert (has < callable::empty (range const &, direction::back)>::value, ""); static_assert (has < callable::first (range const &, direction::back)>::value, ""); static_assert (has < callable::size (range const &, direction::back)>::value, ""); static_assert (has < callable::drop (range const &, direction::back)>::value, ""); static_assert (has < callable::drop (range const &, int, direction::back)>::value, ""); static_assert (has < callable::chop (range &&, direction::back)>::value, ""); static_assert (has < callable::chop_in_place (range &, direction::back)>::value, ""); } } BOOST_AUTO_TEST_CASE (test_any_range_homogeneous) { std::vector <int> v; v.push_back (4); v.push_back (5); v.push_back (6); v.push_back (7); { any_range <int &> a (v); BOOST_CHECK (!range::empty (a)); BOOST_CHECK_EQUAL (range::first (a), 4); a = range::drop (a); BOOST_CHECK (!range::empty (a)); auto chopped = range::chop (a); BOOST_CHECK_EQUAL (chopped.first(), 5); BOOST_CHECK (!range::empty (chopped.rest())); a = chopped.move_rest(); BOOST_CHECK (!range::empty (a)); BOOST_CHECK_EQUAL (range::first (a), 6); int & e = range::chop_in_place (a); BOOST_CHECK_EQUAL (e, 6); BOOST_CHECK_EQUAL (&e, &v [2]); BOOST_CHECK (!range::empty (a)); BOOST_CHECK_EQUAL (range::first (a), 7); a = range::drop (a); BOOST_CHECK (range::empty (a)); } { auto a = range::make_any_range (v); BOOST_MPL_ASSERT (( range::has <callable::empty (decltype (a), direction::back)>)); BOOST_MPL_ASSERT (( range::has <callable::first (decltype (a), direction::front)>)); BOOST_MPL_ASSERT (( range::has <callable::size (decltype (a), direction::back)>)); BOOST_MPL_ASSERT (( range::has <callable::drop (decltype (a), direction::back)>)); BOOST_MPL_ASSERT (( range::has <callable::drop (decltype (a), int, direction::front)>)); BOOST_CHECK (!empty (a)); BOOST_CHECK_EQUAL (size (a), 4u); BOOST_CHECK_EQUAL (size (drop (a)), 3u); BOOST_CHECK_EQUAL (first (drop (a)), 5); BOOST_CHECK_EQUAL (first (drop (a, 2)), 6); BOOST_CHECK_EQUAL (first (a, back), 7); BOOST_CHECK_EQUAL (first (drop (a, back), back), 6); BOOST_CHECK_EQUAL (first (drop (a, 2, back), back), 5); BOOST_CHECK (empty (drop (a, 4), back)); first (drop (a)) = 14; BOOST_CHECK_EQUAL (v[1], 14); // Convert to default capabilities any_range <int &> a2 (a); BOOST_CHECK (!empty (a2)); a2 = drop (a2); BOOST_CHECK (!empty (a2)); // Was 5, now 14. BOOST_CHECK_EQUAL (first (a2), 14); a2 = drop (a2); BOOST_CHECK (!empty (a2)); BOOST_CHECK_EQUAL (first (a2), 6); a2 = drop (a2); BOOST_CHECK (!empty (a2)); BOOST_CHECK_EQUAL (first (a2), 7); a2 = drop (a2); BOOST_CHECK (empty (a2)); // Convert to different type: int & -> long should be fine. any_range <long> al (a); BOOST_CHECK (!empty (al)); BOOST_CHECK_EQUAL (first (al), 4l); BOOST_CHECK_EQUAL (first (drop (al)), 14l); al = drop (drop (al)); BOOST_CHECK (!empty (al)); BOOST_CHECK_EQUAL (first (al), 6l); BOOST_CHECK (!empty (drop (al))); BOOST_CHECK_EQUAL (first (drop (al)), 7l); al = drop (drop (al)); BOOST_CHECK (empty (al)); } } BOOST_AUTO_TEST_CASE (test_any_range_unique) { std::vector <int> v; v.push_back (4); v.push_back (5); v.push_back (6); v.push_back (7); { auto a = make_any_range (unique_view (v)); static_assert (!std::is_constructible < decltype (a), decltype (a) const &>::value, ""); BOOST_CHECK_EQUAL (first (a), 4); a = drop (std::move (a)); BOOST_CHECK_EQUAL (chop_in_place (a), 5); auto b = std::move (a); BOOST_CHECK_EQUAL (chop_in_place (b), 6); BOOST_CHECK_EQUAL (chop_in_place (b), 7); BOOST_CHECK (empty (b)); } { any_range <int, range::capability::unique_capabilities> a ( one_time_view (v)); // first and drop are not available. BOOST_CHECK_EQUAL (chop_in_place (a), 4); auto chopped = chop (std::move (a)); BOOST_CHECK_EQUAL (chopped.first(), 5); a = chopped.move_rest(); BOOST_CHECK_EQUAL (chop_in_place (a), 6); auto b = std::move (a); BOOST_CHECK_EQUAL (chop_in_place (b), 7); BOOST_CHECK (empty (b)); } { struct count { int i; count() : i (0) {} int operator() () { return ++i; } }; any_range <int, range::capability::unique_capabilities> a ( range::make_function_range (count())); BOOST_CHECK_EQUAL (chop_in_place (a), 1); BOOST_CHECK_EQUAL (chop_in_place (a), 2); } } BOOST_AUTO_TEST_CASE (test_any_range_heterogeneous) { { std::tuple <> t; any_range <int> a (t); BOOST_CHECK (empty (a)); } { std::tuple <int> t (7); any_range <int> a (t); BOOST_CHECK (!empty (a)); BOOST_CHECK_EQUAL (first (a), 7); any_range <int> a_next = drop (a); BOOST_CHECK (empty (a_next)); } { std::tuple <int, char, long> t (7, 'a', 294l); any_range <long> a (t); BOOST_CHECK (!empty (a)); BOOST_CHECK_EQUAL (first (a), 7l); a = drop (a); BOOST_CHECK (!empty (a)); BOOST_CHECK_EQUAL (first (a), long ('a')); a = drop (a); BOOST_CHECK (!empty (a)); BOOST_CHECK_EQUAL (first (a), 294l); a = drop (a); BOOST_CHECK (empty (a)); } { std::tuple <int, char, long> t (7, 'a', 294l); any_range <long, range::capability::bidirectional_capabilities> a (t); BOOST_CHECK (!empty (a)); BOOST_CHECK_EQUAL (chop_in_place (a), 7l); BOOST_CHECK (!empty (a)); BOOST_CHECK_EQUAL (chop_in_place (a, back), 294l); BOOST_CHECK (!empty (a)); BOOST_CHECK_EQUAL (chop_in_place (a, back), long ('a')); BOOST_CHECK (empty (a)); } } BOOST_AUTO_TEST_CASE (test_any_range_copy_move) { typedef any_range <int, meta::map < meta::map_element <range::capability::default_direction, direction::front>, meta::map_element <direction::front, meta::set < range::capability::empty, range::capability::size, range::capability::first>>>> range_with_size; typedef any_range <int, meta::map < meta::map_element <range::capability::default_direction, direction::front>, meta::map_element <direction::front, meta::set < range::capability::empty, range::capability::first>>>> range_without_size; std::vector <int> v; v.push_back (26); static_assert ( !std::is_constructible <range_with_size, range_with_size const & >::value, "The range cannot be copied so it is not copy-constructible"); static_assert ( !std::is_constructible <range_without_size, range_with_size const & >::value, "The range cannot be copied so it is not copy-constructible"); static_assert ( std::is_constructible <range_with_size, range_with_size &&>::value, "Moving to the same type is a pointer operation."); static_assert ( !std::is_constructible <range_without_size, range_with_size &&>::value, "The range cannot be copied so it is not move-constructible " "with different capabilities."); range_with_size r (v); range_with_size r2 (std::move (r)); BOOST_CHECK_EQUAL (size (r2), 1); } BOOST_AUTO_TEST_SUITE_END()
36.228205
80
0.583764
rogiervd
a85df51766a4e04ecc4d4dff6e50cdae3d006497
13,423
cc
C++
DRsim/src/DRsimDetectorConstruction.cc
kyHwangs/DRC_generic
efb5a791c57706ac1848907af5bef36cb8480ca2
[ "Apache-2.0" ]
null
null
null
DRsim/src/DRsimDetectorConstruction.cc
kyHwangs/DRC_generic
efb5a791c57706ac1848907af5bef36cb8480ca2
[ "Apache-2.0" ]
null
null
null
DRsim/src/DRsimDetectorConstruction.cc
kyHwangs/DRC_generic
efb5a791c57706ac1848907af5bef36cb8480ca2
[ "Apache-2.0" ]
1
2022-03-28T04:06:32.000Z
2022-03-28T04:06:32.000Z
#include "DRsimDetectorConstruction.hh" #include "DRsimCellParameterisation.hh" #include "DRsimFilterParameterisation.hh" #include "DRsimMirrorParameterisation.hh" #include "DRsimSiPMSD.hh" #include "G4VPhysicalVolume.hh" #include "G4PVPlacement.hh" #include "G4PVParameterised.hh" #include "G4IntersectionSolid.hh" #include "G4SDManager.hh" #include "G4LogicalSkinSurface.hh" #include "G4LogicalBorderSurface.hh" #include "G4LogicalVolumeStore.hh" #include "G4SolidStore.hh" #include "G4PhysicalVolumeStore.hh" #include "G4GeometryManager.hh" #include "G4Colour.hh" #include "G4SystemOfUnits.hh" #include "Randomize.hh" using namespace std; G4ThreadLocal DRsimMagneticField* DRsimDetectorConstruction::fMagneticField = 0; G4ThreadLocal G4FieldManager* DRsimDetectorConstruction::fFieldMgr = 0; int DRsimDetectorConstruction::fNofRow = 7; int DRsimDetectorConstruction::fNofModules = fNofRow * fNofRow; DRsimDetectorConstruction::DRsimDetectorConstruction() : G4VUserDetectorConstruction(), fMessenger(0), fMaterials(NULL) { DefineCommands(); DefineMaterials(); clad_C_rMin = 0.49*mm; clad_C_rMax = 0.50*mm; clad_C_Dz = 2.5*m; clad_C_Sphi = 0.; clad_C_Dphi = 2.*M_PI; core_C_rMin = 0.*mm; core_C_rMax = 0.49*mm; core_C_Dz = 2.5*m; core_C_Sphi = 0.; core_C_Dphi = 2.*M_PI; clad_S_rMin = 0.485*mm; clad_S_rMax = 0.50*mm; clad_S_Dz = 2.5*m; clad_S_Sphi = 0.; clad_S_Dphi = 2.*M_PI; core_S_rMin = 0.*mm; core_S_rMax = 0.485*mm; core_S_Dz = 2.5*m; core_S_Sphi = 0.; core_S_Dphi = 2.*M_PI; PMTT = 0.3*mm; filterT = 0.01*mm; reflectorT = 0.03*mm; fVisAttrOrange = new G4VisAttributes(G4Colour(1.0,0.5,0.,1.0)); fVisAttrOrange->SetVisibility(true); fVisAttrBlue = new G4VisAttributes(G4Colour(0.,0.,1.0,1.0)); fVisAttrBlue->SetVisibility(true); fVisAttrGray = new G4VisAttributes(G4Colour(0.3,0.3,0.3,0.3)); fVisAttrGray->SetVisibility(true); fVisAttrGreen = new G4VisAttributes(G4Colour(0.3,0.7,0.3)); fVisAttrGreen->SetVisibility(true); } DRsimDetectorConstruction::~DRsimDetectorConstruction() { delete fMessenger; delete fMaterials; delete fVisAttrOrange; delete fVisAttrBlue; delete fVisAttrGray; delete fVisAttrGreen; } void DRsimDetectorConstruction::DefineMaterials() { fMaterials = DRsimMaterials::GetInstance(); } G4VPhysicalVolume* DRsimDetectorConstruction::Construct() { G4GeometryManager::GetInstance()->OpenGeometry(); G4PhysicalVolumeStore::GetInstance()->Clean(); G4LogicalVolumeStore::GetInstance()->Clean(); G4SolidStore::GetInstance()->Clean(); checkOverlaps = false; G4VSolid* worldSolid = new G4Box("worldBox",10.*m,10.*m,10.*m); worldLogical = new G4LogicalVolume(worldSolid,FindMaterial("G4_Galactic"),"worldLogical"); G4VPhysicalVolume* worldPhysical = new G4PVPlacement(0,G4ThreeVector(),worldLogical,"worldPhysical",0,false,0,checkOverlaps); fFrontL = 1500.; // NOTE :: Length from the center of world box to center of module fTowerDepth = 2500.; fModuleH = 90; fModuleW = 90; fFiberUnitH = 1.; // fRandomSeed = 1; doFiber = true; doReflector = false; doPMT = true; fiberUnit = new G4Box("fiber_SQ", (fFiberUnitH/2) *mm, (1./2) *mm, (fTowerDepth/2) *mm); fiberClad = new G4Tubs("fiber", 0, clad_C_rMax, fTowerDepth/2., 0 *deg, 360. *deg); // S is the same fiberCoreC = new G4Tubs("fiberC", 0, core_C_rMax, fTowerDepth/2., 0 *deg, 360. *deg); fiberCoreS = new G4Tubs("fiberS", 0, core_S_rMax, fTowerDepth/2., 0 *deg, 360. *deg); dimCalc = new dimensionCalc(); dimCalc->SetFrontL(fFrontL); dimCalc->SetTower_height(fTowerDepth); dimCalc->SetPMTT(PMTT+filterT); dimCalc->SetReflectorT(reflectorT); dimCalc->SetNofModules(fNofModules); dimCalc->SetNofRow(fNofRow); ModuleBuild(ModuleLogical,PMTGLogical,PMTfilterLogical,PMTcellLogical,PMTcathLogical,ReflectorMirrorLogical,fiberUnitIntersection,fiberCladIntersection,fiberCoreIntersection,fModuleProp); delete dimCalc; return worldPhysical; } void DRsimDetectorConstruction::ConstructSDandField() { G4SDManager* SDman = G4SDManager::GetSDMpointer(); G4String SiPMName = "SiPMSD"; // ! Not a memory leak - SDs are deleted by G4SDManager. Deleting them manually will cause double delete! if ( doPMT ) { for (int i = 0; i < fNofModules; i++) { DRsimSiPMSD* SiPMSDmodule = new DRsimSiPMSD("Module"+std::to_string(i), "ModuleC"+std::to_string(i), fModuleProp.at(i)); SDman->AddNewDetector(SiPMSDmodule); PMTcathLogical[i]->SetSensitiveDetector(SiPMSDmodule); } } } void DRsimDetectorConstruction::ModuleBuild(G4LogicalVolume* ModuleLogical_[], G4LogicalVolume* PMTGLogical_[], G4LogicalVolume* PMTfilterLogical_[], G4LogicalVolume* PMTcellLogical_[], G4LogicalVolume* PMTcathLogical_[], G4LogicalVolume* ReflectorMirrorLogical_[], std::vector<G4LogicalVolume*> fiberUnitIntersection_[], std::vector<G4LogicalVolume*> fiberCladIntersection_[], std::vector<G4LogicalVolume*> fiberCoreIntersection_[], std::vector<DRsimInterface::DRsimModuleProperty>& ModuleProp_) { for (int i = 0; i < fNofModules; i++) { moduleName = setModuleName(i); dimCalc->SetisModule(true); module = new G4Box("Mudule", (fModuleH/2.) *mm, (fModuleW/2.) *mm, (fTowerDepth/2.) *mm ); ModuleLogical_[i] = new G4LogicalVolume(module,FindMaterial("Copper"),moduleName); // G4VPhysicalVolume* modulePhysical = new G4PVPlacement(0,dimCalc->GetOrigin(i),ModuleLogical_[i],moduleName,worldLogical,false,0,checkOverlaps); new G4PVPlacement(0,dimCalc->GetOrigin(i),ModuleLogical_[i],moduleName,worldLogical,false,0,checkOverlaps); if ( doPMT ) { dimCalc->SetisModule(false); pmtg = new G4Box("PMTG", (fModuleH/2.) *mm, (fModuleW/2.) *mm, (PMTT+filterT)/2. *mm ); PMTGLogical_[i] = new G4LogicalVolume(pmtg,FindMaterial("G4_AIR"),moduleName); new G4PVPlacement(0,dimCalc->GetOrigin_PMTG(i),PMTGLogical_[i],moduleName,worldLogical,false,0,checkOverlaps); } FiberImplement(i,ModuleLogical_,fiberUnitIntersection_,fiberCladIntersection_,fiberCoreIntersection_); DRsimInterface::DRsimModuleProperty ModulePropSingle; ModulePropSingle.towerXY = fTowerXY; ModulePropSingle.ModuleNum = i; ModuleProp_.push_back(ModulePropSingle); if ( doPMT ) { G4VSolid* SiPMlayerSolid = new G4Box("SiPMlayerSolid", (fModuleH/2.) *mm, (fModuleW/2.) *mm, (PMTT/2.) *mm ); G4LogicalVolume* SiPMlayerLogical = new G4LogicalVolume(SiPMlayerSolid,FindMaterial("G4_AIR"),"SiPMlayerLogical"); new G4PVPlacement(0,G4ThreeVector(0.,0.,filterT/2.),SiPMlayerLogical,"SiPMlayerPhysical",PMTGLogical_[i],false,0,checkOverlaps); G4VSolid* filterlayerSolid = new G4Box("filterlayerSolid", (fModuleH/2.) *mm, (fModuleW/2.) *mm, (filterT/2.) *mm ); G4LogicalVolume* filterlayerLogical = new G4LogicalVolume(filterlayerSolid,FindMaterial("Glass"),"filterlayerLogical"); new G4PVPlacement(0,G4ThreeVector(0.,0.,-PMTT/2.),filterlayerLogical,"filterlayerPhysical",PMTGLogical_[i],false,0,checkOverlaps); G4VSolid* PMTcellSolid = new G4Box("PMTcellSolid", 1.2/2. *mm, 1.2/2. *mm, PMTT/2. *mm ); PMTcellLogical_[i] = new G4LogicalVolume(PMTcellSolid,FindMaterial("Glass"),"PMTcellLogical_"); DRsimCellParameterisation* PMTcellParam = new DRsimCellParameterisation(fTowerXY.first,fTowerXY.second); G4PVParameterised* PMTcellPhysical = new G4PVParameterised("PMTcellPhysical",PMTcellLogical_[i],SiPMlayerLogical,kXAxis,fTowerXY.first*fTowerXY.second,PMTcellParam); G4VSolid* PMTcathSolid = new G4Box("PMTcathSolid", 1.2/2. *mm, 1.2/2. *mm, filterT/2. *mm ); PMTcathLogical_[i] = new G4LogicalVolume(PMTcathSolid,FindMaterial("Silicon"),"PMTcathLogical_"); new G4PVPlacement(0,G4ThreeVector(0.,0.,(PMTT-filterT)/2.*mm),PMTcathLogical_[i],"PMTcathPhysical",PMTcellLogical_[i],false,0,checkOverlaps); new G4LogicalSkinSurface("Photocath_surf",PMTcathLogical_[i],FindSurface("SiPMSurf")); G4VSolid* filterSolid = new G4Box("filterSolid", 1.2/2. *mm, 1.2/2. *mm, filterT/2. *mm ); PMTfilterLogical_[i] = new G4LogicalVolume(filterSolid,FindMaterial("Gelatin"),"PMTfilterLogical_"); DRsimFilterParameterisation* filterParam = new DRsimFilterParameterisation(fTowerXY.first,fTowerXY.second); G4PVParameterised* filterPhysical = new G4PVParameterised("filterPhysical",PMTfilterLogical_[i],filterlayerLogical,kXAxis,fTowerXY.first*fTowerXY.second/2,filterParam); new G4LogicalBorderSurface("filterSurf",filterPhysical,PMTcellPhysical,FindSurface("FilterSurf")); PMTcathLogical_[i]->SetVisAttributes(fVisAttrGreen); PMTfilterLogical_[i]->SetVisAttributes(fVisAttrOrange); } if ( doReflector ) { G4VSolid* ReflectorlayerSolid = new G4Box("ReflectorlayerSolid", (fModuleH/2.) *mm, (fModuleW/2.) *mm, (reflectorT/2.) *mm ); G4LogicalVolume* ReflectorlayerLogical = new G4LogicalVolume(ReflectorlayerSolid,FindMaterial("G4_Galactic"),"ReflectorlayerLogical"); new G4PVPlacement(0,dimCalc->GetOrigin_Reflector(i),ReflectorlayerLogical,"ReflectorlayerPhysical",worldLogical,false,0,checkOverlaps); G4VSolid* mirrorSolid = new G4Box("mirrorSolid", 1.2/2. *mm, 1.2/2. *mm, reflectorT/2. *mm ); ReflectorMirrorLogical_[i] = new G4LogicalVolume(mirrorSolid,FindMaterial("Aluminum"),"ReflectorMirrorLogical_"); DRsimMirrorParameterisation* mirrorParam = new DRsimMirrorParameterisation(fTowerXY.first,fTowerXY.second); G4PVParameterised* mirrorPhysical = new G4PVParameterised("mirrorPhysical",ReflectorMirrorLogical_[i],ReflectorlayerLogical,kXAxis,fTowerXY.first*fTowerXY.second/2,mirrorParam); // new G4LogicalBorderSurface("MirrorSurf",mirrorPhysical,modulePhysical,FindSurface("MirrorSurf")); new G4LogicalSkinSurface("MirrorSurf",ReflectorMirrorLogical_[i],FindSurface("MirrorSurf")); ReflectorMirrorLogical_[i]->SetVisAttributes(fVisAttrGray); } } } void DRsimDetectorConstruction::DefineCommands() {} void DRsimDetectorConstruction::FiberImplement(G4int i, G4LogicalVolume* ModuleLogical__[], std::vector<G4LogicalVolume*> fiberUnitIntersection__[], std::vector<G4LogicalVolume*> fiberCladIntersection__[], std::vector<G4LogicalVolume*> fiberCoreIntersection__[]) { fFiberX.clear(); fFiberY.clear(); fFiberWhich.clear(); int NofFiber = 60; int NofPlate = 60; double randDeviation = 0.; // double randDeviation = fFiberUnitH - 1.; fTowerXY = std::make_pair(NofPlate,NofFiber); G4bool fWhich = false; for (int k = 0; k < NofPlate; k++) { for (int j = 0; j < NofFiber; j++) { /* ? fX : # of plate , fY : # of fiber in the plate */ G4float fX = -90.*mm/2 + k*1.5*mm + 0.75*mm; G4float fY = -90.*mm/2 + j*1.5*mm + 0.75*mm; fWhich = !fWhich; fFiberX.push_back(fX); fFiberY.push_back(fY); fFiberWhich.push_back(fWhich); } if ( NofFiber%2==0 ) { fWhich = !fWhich; } } if ( doFiber ) { for (unsigned int j = 0; j<fFiberX.size(); j++) { if ( !fFiberWhich.at(j) ) { //c fibre tfiberCladIntersection = new G4IntersectionSolid("fiberClad",fiberClad,module,0,G4ThreeVector(-fFiberX.at(j),-fFiberY.at(j),0.)); fiberCladIntersection__[i].push_back(new G4LogicalVolume(tfiberCladIntersection,FindMaterial("FluorinatedPolymer"),name)); new G4PVPlacement(0,G4ThreeVector(fFiberX.at(j),fFiberY.at(j),0),fiberCladIntersection__[i].at(j),name,ModuleLogical__[i],false,j,checkOverlaps); tfiberCoreIntersection = new G4IntersectionSolid("fiberCore",fiberCoreC,module,0,G4ThreeVector(-fFiberX.at(j),-fFiberY.at(j),0.)); fiberCoreIntersection__[i].push_back(new G4LogicalVolume(tfiberCoreIntersection,FindMaterial("PMMA"),name)); new G4PVPlacement(0,G4ThreeVector(0.,0.,0.),fiberCoreIntersection__[i].at(j),name,fiberCladIntersection__[i].at(j),false,j,checkOverlaps); fiberCladIntersection__[i].at(j)->SetVisAttributes(fVisAttrGray); fiberCoreIntersection__[i].at(j)->SetVisAttributes(fVisAttrBlue); } else { // s fibre tfiberCladIntersection = new G4IntersectionSolid("fiberClad",fiberClad,module,0,G4ThreeVector(-fFiberX.at(j),-fFiberY.at(j),0.)); fiberCladIntersection__[i].push_back(new G4LogicalVolume(tfiberCladIntersection,FindMaterial("PMMA"),name)); new G4PVPlacement(0,G4ThreeVector(fFiberX.at(j),fFiberY.at(j),0),fiberCladIntersection__[i].at(j),name,ModuleLogical__[i],false,j,checkOverlaps); tfiberCoreIntersection = new G4IntersectionSolid("fiberCore",fiberCoreS,module,0,G4ThreeVector(-fFiberX.at(j),-fFiberY.at(j),0.)); fiberCoreIntersection__[i].push_back(new G4LogicalVolume(tfiberCoreIntersection,FindMaterial("Polystyrene"),name)); new G4PVPlacement(0,G4ThreeVector(0.,0.,0.),fiberCoreIntersection__[i].at(j),name,fiberCladIntersection__[i].at(j),false,j,checkOverlaps); fiberCladIntersection__[i].at(j)->SetVisAttributes(fVisAttrGray); fiberCoreIntersection__[i].at(j)->SetVisAttributes(fVisAttrOrange); } } } }
46.286207
212
0.716606
kyHwangs
a85e22945433eba2ae0840f32b9c59fbc589962a
10,259
hpp
C++
chat_room/ChatRoom_multithreads/cpp_headers/aws_s3.hpp
LiaoWC/cpp_programs
da78030d02cb916466ad5f0b0794f5c443cc05b4
[ "MIT" ]
null
null
null
chat_room/ChatRoom_multithreads/cpp_headers/aws_s3.hpp
LiaoWC/cpp_programs
da78030d02cb916466ad5f0b0794f5c443cc05b4
[ "MIT" ]
null
null
null
chat_room/ChatRoom_multithreads/cpp_headers/aws_s3.hpp
LiaoWC/cpp_programs
da78030d02cb916466ad5f0b0794f5c443cc05b4
[ "MIT" ]
null
null
null
#ifndef _AWS_S3_HPP_ #define _AWS_S3_HPP_ #include <iostream> #include <fstream> #include <sys/stat.h> #include <fstream> #include <string> #include <aws/core/Aws.h> #include <aws/s3/S3Client.h> #include <aws/s3/model/DeleteObjectRequest.h> #include <aws/s3/model/PutObjectRequest.h> #include <aws/s3/model/GetObjectRequest.h> #include <aws/s3/model/CreateBucketRequest.h> #define getObjectBuffer 5120 using namespace std; // //snippet-start:[s3.cpp.list_buckets.inc] // #include <aws/core/Aws.h> // #include <aws/s3/S3Client.h> // #include <aws/s3/model/Bucket.h> // //snippet-end:[s3.cpp.list_buckets.inc] // /** // * List your Amazon S3 buckets. // */ // int main(int argc, char** argv) // { // Aws::SDKOptions options; // Aws::InitAPI(options); // { // // snippet-start:[s3.cpp.list_buckets.code] // Aws::S3::S3Client s3_client; // auto outcome = s3_client.ListBuckets(); // if (outcome.IsSuccess()) // { // std::cout << "Your Amazon S3 buckets:" << std::endl; // Aws::Vector<Aws::S3::Model::Bucket> bucket_list = // outcome.GetResult().GetBuckets(); // for (auto const &bucket : bucket_list) // { // std::cout << " * " << bucket.GetName() << std::endl; // } // } // else // { // std::cout << "ListBuckets error: " // << outcome.GetError().GetExceptionName() << " - " // << outcome.GetError().GetMessage() << std::endl; // } // // snippet-end:[s3.cpp.list_buckets.code] // } // Aws::ShutdownAPI(options); // } // //snippet-start:[s3.cpp.delete_bucket.inc] // #include <aws/core/Aws.h> // #include <aws/s3/S3Client.h> // #include <aws/s3/model/DeleteBucketRequest.h> // //snippet-end:[s3.cpp.delete_bucket.inc] // /** // * Delete an Amazon S3 bucket. // * // * ++ Warning ++ This code will actually delete the bucket that you specify! // */ // int main(int argc, char** argv) // { // if (argc < 2) // { // std::cout << "delete_bucket - delete an S3 bucket" << std::endl // << "\nUsage:" << std::endl // << " delete_bucket <bucket> [region]" << std::endl // << "\nWhere:" << std::endl // << " bucket - the bucket to delete" << std::endl // << " region - AWS region for the bucket" << std::endl // << " (optional, default: us-east-1)" << std::endl // << "\nNote! This will actually delete the bucket that you specify!" // << std::endl // << "\nExample:" << std::endl // << " delete_bucket testbucket\n" << std::endl << std::endl; // exit(1); // } // Aws::SDKOptions options; // Aws::InitAPI(options); // { // const Aws::String bucket_name = argv[1]; // const Aws::String user_region = (argc >= 3) ? argv[2] : "us-east-1"; // std::cout << "Deleting S3 bucket: " << bucket_name << std::endl; // // snippet-start:[s3.cpp.delete_bucket.code] // Aws::Client::ClientConfiguration config; // config.region = user_region; // Aws::S3::S3Client s3_client(config); // Aws::S3::Model::DeleteBucketRequest bucket_request; // bucket_request.SetBucket(bucket_name); // auto outcome = s3_client.DeleteBucket(bucket_request); // if (outcome.IsSuccess()) // { // std::cout << "Done!" << std::endl; // } // else // { // std::cout << "DeleteBucket error: " // << outcome.GetError().GetExceptionName() << " - " // << outcome.GetError().GetMessage() << std::endl; // } // // snippet-end:[s3.cpp.delete_bucket.code] // } // Aws::ShutdownAPI(options); // } // //snippet-end:[s3.cpp.create_bucket.inc] namespace awsS3 { bool create_bucket(const Aws::String &bucket_name, const Aws::S3::Model::BucketLocationConstraint &region = Aws::S3::Model::BucketLocationConstraint::us_east_1) { // Set up the request Aws::S3::Model::CreateBucketRequest request; request.SetBucket(bucket_name); // Is the region other than us-east-1 (N. Virginia)? if (region != Aws::S3::Model::BucketLocationConstraint::us_east_1) { // Specify the region as a location constraint Aws::S3::Model::CreateBucketConfiguration bucket_config; bucket_config.SetLocationConstraint(region); request.SetCreateBucketConfiguration(bucket_config); } // Create the bucket Aws::S3::S3Client s3_client; auto outcome = s3_client.CreateBucket(request); if (!outcome.IsSuccess()) { auto err = outcome.GetError(); std::cout << "ERROR: CreateBucket: " << err.GetExceptionName() << ": " << err.GetMessage() << std::endl; return false; } return true; } inline bool file_exists(const std::string &name) { struct stat buffer; return (stat(name.c_str(), &buffer) == 0); } bool put_s3_object(const Aws::String &s3_bucket_name, const Aws::String &s3_object_name, const std::string &file_name, const Aws::String &region = "") { // Verify file_name exists if (!file_exists(file_name)) { std::cout << "ERROR: NoSuchFile: The specified file does not exist" << std::endl; return false; } // If region is specified, use it Aws::Client::ClientConfiguration clientConfig; if (!region.empty()) clientConfig.region = region; // Set up request // snippet-start:[s3.cpp.put_object.code] Aws::S3::S3Client s3_client(clientConfig); Aws::S3::Model::PutObjectRequest object_request; object_request.SetBucket(s3_bucket_name); object_request.SetKey(s3_object_name); const std::shared_ptr<Aws::IOStream> input_data = Aws::MakeShared<Aws::FStream>("SampleAllocationTag", file_name.c_str(), std::ios_base::in | std::ios_base::binary); object_request.SetBody(input_data); // Put the object auto put_object_outcome = s3_client.PutObject(object_request); if (!put_object_outcome.IsSuccess()) { auto error = put_object_outcome.GetError(); std::cout << "ERROR: " << error.GetExceptionName() << ": " << error.GetMessage() << std::endl; return false; } return true; // snippet-end:[s3.cpp.put_object.code] } /** * Get an object from an Amazon S3 bucket. */ string get_object(const Aws::String &bucket_name, const Aws::String &object_name) { // Set up the request Aws::S3::S3Client s3_client; Aws::S3::Model::GetObjectRequest object_request; object_request.SetBucket(bucket_name); object_request.SetKey(object_name); // Get the object auto get_object_outcome = s3_client.GetObject(object_request); if (get_object_outcome.IsSuccess()) { // Get an Aws::IOStream reference to the retrieved file auto &retrieved_file = get_object_outcome.GetResultWithOwnership().GetBody(); //#if 1 // Output the first line of the retrieved text file char file_data[getObjectBuffer] = {0}; retrieved_file.getline(file_data, getObjectBuffer - 1); //std::cout << file_data << std::endl; string rt(file_data); return file_data; // #else // // Alternatively, read the object's contents and write to a file // const char *filename = "/PATH/FILE_NAME"; // std::ofstream output_file(filename, std::ios::binary); // output_file << retrieved_file.rdbuf(); // #endif } else { auto error = get_object_outcome.GetError(); std::cout << "ERROR: " << error.GetExceptionName() << ": " << error.GetMessage() << std::endl; string rt = ""; return rt; } // snippet-end:[s3.cpp.get_object.code] } /** * Delete an object from an Amazon S3 bucket. * * ++ warning ++ This will actually delete the named object! */ bool delete_object(const Aws::String &bucket_name, const Aws::String key_name) { //std::cout << "Deleting" << key_name << " from S3 bucket: " << bucket_name << std::endl; //cout << bucket_name << " ||| " << key_name << endl; Aws::S3::S3Client s3_client; Aws::S3::Model::DeleteObjectRequest object_request; object_request.WithBucket(bucket_name).WithKey(key_name); auto delete_object_outcome = s3_client.DeleteObject(object_request); return (delete_object_outcome.IsSuccess()); } } // namespace awsS3 #endif
39.007605
136
0.499951
LiaoWC
a85ea5203a902486716faaf97cc4619262159d6c
1,530
cpp
C++
src/prod/src/Management/healthmanager/RequestContextKind.cpp
vishnuk007/service-fabric
d0afdea185ae932cc3c9eacf179692e6fddbc630
[ "MIT" ]
2,542
2018-03-14T21:56:12.000Z
2019-05-06T01:18:20.000Z
src/prod/src/Management/healthmanager/RequestContextKind.cpp
vishnuk007/service-fabric
d0afdea185ae932cc3c9eacf179692e6fddbc630
[ "MIT" ]
994
2019-05-07T02:39:30.000Z
2022-03-31T13:23:04.000Z
src/prod/src/Management/healthmanager/RequestContextKind.cpp
vishnuk007/service-fabric
d0afdea185ae932cc3c9eacf179692e6fddbc630
[ "MIT" ]
300
2018-03-14T21:57:17.000Z
2019-05-06T20:07:00.000Z
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" namespace Management { namespace HealthManager { namespace RequestContextKind { void WriteToTextWriter(__in Common::TextWriter & w, Enum e) { switch(e) { case Report: w << "Report"; return; case SequenceStream: w << "SequenceStream"; return; case QueryEntityDetail: w << "QueryEntityDetail"; return; case QueryEntityChildren: w << "QueryEntityChildren"; return; case Query: w << "Query"; return; case QueryEntityHealthStateChunk: w << "QueryEntityHealthStateChunk"; return; case QueryEntityHealthState: w << "QueryEntityHealthState"; return; case QueryEntityUnhealthyChildren: w << "QueryEntityUnhealthyChildren"; return; default: w << "RequestContextKind(" << static_cast<uint>(e) << ')'; return; } } BEGIN_ENUM_STRUCTURED_TRACE( RequestContextKind ) ADD_CASTED_ENUM_MAP_VALUE_RANGE( RequestContextKind, Report, LAST_STATE) END_ENUM_STRUCTURED_TRACE( RequestContextKind ) } } }
40.263158
99
0.538562
vishnuk007
a85f657b71cb0c42e060c9ab6f5cc1cd63fc78cb
617
hpp
C++
configuration/ConfigurationArgumentProcessor_test/ConfigurationArgumentProcessor_test.hpp
leighgarbs/toolbox
fd9ceada534916fa8987cfcb5220cece2188b304
[ "MIT" ]
null
null
null
configuration/ConfigurationArgumentProcessor_test/ConfigurationArgumentProcessor_test.hpp
leighgarbs/toolbox
fd9ceada534916fa8987cfcb5220cece2188b304
[ "MIT" ]
null
null
null
configuration/ConfigurationArgumentProcessor_test/ConfigurationArgumentProcessor_test.hpp
leighgarbs/toolbox
fd9ceada534916fa8987cfcb5220cece2188b304
[ "MIT" ]
null
null
null
#if !defined CONFIGURATION_ARGUMENT_PROCESSOR_TEST #define CONFIGURATION_ARGUMENT_PROCESSOR_TEST #include "Test.hpp" #include "TestCases.hpp" #include "TestMacros.hpp" namespace Configuration { TEST_CASES_BEGIN(ArgumentProcessor_test) TEST(RegisterPositionalArgument) TEST(RegisterOptionalArgument) TEST_CASES_BEGIN(Process) TEST(PositionalArgument) TEST(OptionalArgument) TEST(OptionalCountingArgument) TEST(Combined) TEST_CASES_END(Process) TEST(IsRegistered) TEST_CASES_END(ArgumentProcessor_test) } #endif
19.28125
50
0.71799
leighgarbs
a86091b209f28ffda96c75f7c9b23c708af8aa8f
1,179
cpp
C++
src/entity/BeerCard.cpp
MattSkala/bang-game
42b174fef07a8c6b7af1895e6ddf75507bd2fa42
[ "MIT" ]
9
2015-05-29T22:51:53.000Z
2021-03-07T15:46:28.000Z
src/entity/BeerCard.cpp
MattSkala/bang-game
42b174fef07a8c6b7af1895e6ddf75507bd2fa42
[ "MIT" ]
null
null
null
src/entity/BeerCard.cpp
MattSkala/bang-game
42b174fef07a8c6b7af1895e6ddf75507bd2fa42
[ "MIT" ]
4
2017-01-07T02:25:47.000Z
2021-11-04T08:18:07.000Z
#include "BeerCard.h" #include "../Game.h" #include "../net/GameServer.h" #include <iostream> using namespace std; BeerCard::BeerCard(string original_name, string name, int count) : InstantCard(original_name, name, count) { } int BeerCard::play(Game *game, Player *player, int position, int target, int target_card) { if (player->isPending() && (player->getLife() > 0 || target_others_)) { return Game::ERROR_INVALID_REACTION; } if (target_self_) { if (player->getLife() == player->getMaxLife()) { return Game::ERROR_BEER_NO_EFFECT; } player->increaseLife(); } if (target_others_) { for (Player * item : game->getPlayers()) { if (item != player && item->isAlive()) { item->increaseLife(); } } } game->discardCard(player, position); if (player->isPending()) { player->setPending(false); if (game->getPendingPlayers().size() == 0) { game->setPendingCard(NULL); } } return Game::SUCCESS; } string BeerCard::print() const { string str = Card::print(); str += " \u2665"; return str; }
24.5625
110
0.577608
MattSkala
a86a1e1a299294034d2c3563889e6e9a8ade19c6
2,771
cpp
C++
inference-engine/src/low_precision_transformations/src/power.cpp
shre2398/openvino
f84a6d97ace26b75ae9d852525a997cbaba32e6a
[ "Apache-2.0" ]
2
2020-11-18T14:14:06.000Z
2020-11-28T04:55:57.000Z
inference-engine/src/low_precision_transformations/src/power.cpp
shre2398/openvino
f84a6d97ace26b75ae9d852525a997cbaba32e6a
[ "Apache-2.0" ]
1
2020-12-22T05:01:12.000Z
2020-12-23T09:49:43.000Z
inference-engine/src/low_precision_transformations/src/power.cpp
shre2398/openvino
f84a6d97ace26b75ae9d852525a997cbaba32e6a
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2020 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "low_precision_transformations/power.hpp" #include <algorithm> #include <caseless.hpp> #include <string> #include <memory> #include <vector> #include "low_precision_transformations/common/ie_lpt_exception.hpp" #include "low_precision_transformations/network_helper.hpp" using namespace InferenceEngine; using namespace InferenceEngine::details; bool PowerTransformation::canBeTransformed(const TransformationContext& context, const CNNLayer& layer) const { if (!LayerTransformation::canBeTransformed(context, layer)) { return false; } if (layer.insData.size() != 1) { THROW_IE_LPT_EXCEPTION(layer) << "layer inputs '" << layer.insData.size() << "' is not correct"; } if (!CaselessEq<std::string>()(layer.type, "Power")) { THROW_IE_LPT_EXCEPTION(layer) << "layer '" << layer.name << "' is not correct"; } const PowerLayer* powerLayer = dynamic_cast<const PowerLayer*>(&layer); if (powerLayer == nullptr) { THROW_IE_LPT_EXCEPTION(layer) << "unexpected Power layer type"; } if (powerLayer->power != 1.f) { return false; } const CNNLayerPtr parent = CNNNetworkHelper::getParent(layer, 0); return !(parent->type != "ScaleShift"); } void PowerTransformation::transform(TransformationContext& context, CNNLayer& layer) const { if (!canBeTransformed(context, layer)) { return; } const PowerLayer* powerLayer = dynamic_cast<const PowerLayer*>(&layer); if (powerLayer == nullptr) { THROW_IE_LPT_EXCEPTION(layer) << "unexpected Power layer type"; } auto scale_and_shift_blob = [] (Blob::Ptr &&blob, float scale, float shift) { auto float_data = CNNNetworkHelper::getFloatData(blob); auto float_data_ptr = float_data.get(); auto float_data_size = blob->size(); for (size_t i = 0ul; i < float_data_size; i++) { float_data_ptr[i] = float_data_ptr[i] * scale + shift; } CNNNetworkHelper::fillBlobByFP32(blob, float_data_ptr); }; const CNNLayerPtr parent = CNNNetworkHelper::getParent(layer, 0); scale_and_shift_blob(CNNNetworkHelper::getBlob(parent, "weights"), powerLayer->scale, 0.0f); scale_and_shift_blob(CNNNetworkHelper::getBlob(parent, "biases") , powerLayer->scale, powerLayer->offset); const std::vector<CNNLayerPtr> children = CNNNetworkHelper::getChildren(layer); CNNNetworkHelper::removeLayer(context.network, std::make_shared<CNNLayer>(layer)); context.removeLayer(layer); if (children.empty()) { const std::string originalName = layer.name; CNNNetworkHelper::renameLayer(context.network, parent->name, layer.name); } }
35.075949
111
0.691447
shre2398
a86b36606b70fd77b4b9118cc6e54bf4366c7dae
1,811
cpp
C++
mshp/algo/graphs/Dijkstra_dist_from_given_to_all.cpp
zer0main/problems
264dd359f74e0906b9b7505506d50c879c4fb737
[ "MIT" ]
5
2015-12-25T20:53:39.000Z
2017-07-18T23:19:04.000Z
mshp/algo/graphs/Dijkstra_dist_from_given_to_all.cpp
zer0main/problems
264dd359f74e0906b9b7505506d50c879c4fb737
[ "MIT" ]
null
null
null
mshp/algo/graphs/Dijkstra_dist_from_given_to_all.cpp
zer0main/problems
264dd359f74e0906b9b7505506d50c879c4fb737
[ "MIT" ]
null
null
null
/* * Copyright (C) 2015-2017 Pavel Dolgov * * See the LICENSE file for terms of use. */ #include <bits/stdc++.h> #define MAX_LENGTH 1000000000 typedef std::vector<int> Ints; typedef std::vector<bool> Bools; typedef std::pair<int, int> IntPair; typedef std::vector<IntPair> IntPairs; typedef std::vector<IntPairs> IntPairsVect; int N, edges_n, cities_n, start; IntPairsVect g; Ints dist, cities; Bools used; void Dijkstra() { dist[start] = 0; for (int i = 0; i < N; i++) { int v = -1; for (int j = 0; j < N; j++) { if (!used[j] && ((v == -1) || (dist[j] < dist[v]))) { v = j; } } if (dist[v] == MAX_LENGTH) { break; } used[v] = true; for (int j = 0; j < g[v].size(); j++) { if (dist[g[v][j].first] > (dist[v] + g[v][j].second)) { dist[g[v][j].first] = dist[v] + g[v][j].second; } } } } int main() { std::cin >> N >> edges_n >> cities_n >> start; start--; g.resize(N); used.resize(N, false); dist.resize(N, MAX_LENGTH); for (int i = 0; i < cities_n; i++) { int city_n; std::cin >> city_n; cities.push_back(city_n - 1); } for (int i = 0; i < edges_n; i++) { int n1, n2, weight; std::cin >> n1 >> n2 >> weight; g[n1 - 1].push_back(IntPair(n2 - 1, weight)); g[n2 - 1].push_back(IntPair(n1 - 1, weight)); } Dijkstra(); IntPairs ans; for (int i = 0; i < cities.size(); i++) { int d = dist[cities[i]]; ans.push_back(IntPair(d, cities[i])); } std::sort(ans.begin(), ans.end()); for (int i = 0; i < ans.size(); i++) { std::cout << ans[i].second + 1 << " " << ans[i].first << "\n"; } return 0; }
25.152778
70
0.484263
zer0main
a86b85be14ff439ef1872f123b2e6ed04ecfaa94
4,053
cpp
C++
src/coreclr/ToolBox/superpmi/mcs/verbdumpmap.cpp
JimmyCushnie/runtime
b7eb82871f1d742efb444873e11dd6241cea73d2
[ "MIT" ]
3
2021-06-24T15:39:52.000Z
2021-11-04T02:13:43.000Z
src/coreclr/ToolBox/superpmi/mcs/verbdumpmap.cpp
JimmyCushnie/runtime
b7eb82871f1d742efb444873e11dd6241cea73d2
[ "MIT" ]
18
2019-12-03T00:21:59.000Z
2022-01-30T04:45:58.000Z
src/coreclr/ToolBox/superpmi/mcs/verbdumpmap.cpp
JimmyCushnie/runtime
b7eb82871f1d742efb444873e11dd6241cea73d2
[ "MIT" ]
2
2022-01-23T12:24:04.000Z
2022-02-07T15:44:03.000Z
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include "standardpch.h" #include "simpletimer.h" #include "methodcontext.h" #include "methodcontextiterator.h" #include "verbdumpmap.h" #include "verbildump.h" #include "spmiutil.h" #include "spmidumphelper.h" // Dump the CSV format header for all the columns we're going to dump. void DumpMapHeader() { printf("index,"); // printf("process name,"); printf("method name,"); printf("full signature,"); printf("jit flags\n"); } void DumpMap(int index, MethodContext* mc) { CORINFO_METHOD_INFO cmi; unsigned int flags = 0; mc->repCompileMethod(&cmi, &flags); const char* moduleName = nullptr; const char* methodName = mc->repGetMethodName(cmi.ftn, &moduleName); const char* className = mc->repGetClassName(mc->repGetMethodClass(cmi.ftn)); printf("%d,", index); // printf("\"%s\",", mc->cr->repProcessName()); printf("%s:%s,", className, methodName); // Also, dump the full method signature printf("\""); DumpAttributeToConsoleBare(mc->repGetMethodAttribs(cmi.ftn)); DumpPrimToConsoleBare(mc, cmi.args.retType, CastHandle(cmi.args.retTypeClass)); printf(" %s", methodName); // Show class and method generic params, if there are any CORINFO_SIG_INFO sig; mc->repGetMethodSig(cmi.ftn, &sig, nullptr); const unsigned classInst = sig.sigInst.classInstCount; if (classInst > 0) { for (unsigned i = 0; i < classInst; i++) { CORINFO_CLASS_HANDLE ci = sig.sigInst.classInst[i]; className = mc->repGetClassName(ci); printf("%s%s%s%s", i == 0 ? "[" : "", i > 0 ? ", " : "", className, i == classInst - 1 ? "]" : ""); } } const unsigned methodInst = sig.sigInst.methInstCount; if (methodInst > 0) { for (unsigned i = 0; i < methodInst; i++) { CORINFO_CLASS_HANDLE ci = sig.sigInst.methInst[i]; className = mc->repGetClassName(ci); printf("%s%s%s%s", i == 0 ? "[" : "", i > 0 ? ", " : "", className, i == methodInst - 1 ? "]" : ""); } } printf("("); DumpSigToConsoleBare(mc, &cmi.args); printf(")\""); // Dump the jit flags CORJIT_FLAGS corJitFlags; mc->repGetJitFlags(&corJitFlags, sizeof(corJitFlags)); unsigned long long rawFlags = corJitFlags.GetFlagsRaw(); // Add in the "fake" pgo flags bool hasEdgeProfile = false; bool hasClassProfile = false; bool hasLikelyClass = false; ICorJitInfo::PgoSource pgoSource = ICorJitInfo::PgoSource::Unknown; if (mc->hasPgoData(hasEdgeProfile, hasClassProfile, hasLikelyClass, pgoSource)) { rawFlags |= 1ULL << (EXTRA_JIT_FLAGS::HAS_PGO); if (hasEdgeProfile) { rawFlags |= 1ULL << (EXTRA_JIT_FLAGS::HAS_EDGE_PROFILE); } if (hasClassProfile) { rawFlags |= 1ULL << (EXTRA_JIT_FLAGS::HAS_CLASS_PROFILE); } if (hasLikelyClass) { rawFlags |= 1ULL << (EXTRA_JIT_FLAGS::HAS_LIKELY_CLASS); } if (pgoSource == ICorJitInfo::PgoSource::Static) { rawFlags |= 1ULL << (EXTRA_JIT_FLAGS::HAS_STATIC_PROFILE); } if (pgoSource == ICorJitInfo::PgoSource::Dynamic) { rawFlags |= 1ULL << (EXTRA_JIT_FLAGS::HAS_DYNAMIC_PROFILE); } } printf(", %s\n", SpmiDumpHelper::DumpJitFlags(rawFlags).c_str()); } int verbDumpMap::DoWork(const char* nameOfInput) { MethodContextIterator mci; if (!mci.Initialize(nameOfInput)) return -1; DumpMapHeader(); while (mci.MoveNext()) { MethodContext* mc = mci.Current(); DumpMap(mci.MethodContextNumber(), mc); } if (!mci.Destroy()) return -1; return 0; }
27.760274
83
0.585986
JimmyCushnie
a87087d87447957d1ebad46267fb85baf7063457
1,930
cpp
C++
testing/visualizer/Main.cpp
ElliottSlingsby/ChunkPool
b4dd1bc5c8e88b2519029bca8329ef7092e8352f
[ "MIT" ]
null
null
null
testing/visualizer/Main.cpp
ElliottSlingsby/ChunkPool
b4dd1bc5c8e88b2519029bca8329ef7092e8352f
[ "MIT" ]
null
null
null
testing/visualizer/Main.cpp
ElliottSlingsby/ChunkPool
b4dd1bc5c8e88b2519029bca8329ef7092e8352f
[ "MIT" ]
null
null
null
#include "ChunkPool.hpp" #include <iostream> #include <ctime> #include <random> #include <chrono> // Testing code, shouldn't really be here struct Test{ inline Test(int x = 0, int y = 0, int z = 0) : x(x), y(y), z(z){} inline void print() const{ std::cout << x << ", " << y << ", " << z << "\n"; } int x; int y; int z; uint8_t filler[256]; // bytes }; int main(int argc, char *argv[]){ srand((unsigned int)time(nullptr)); ChunkPool pool(32 * 1024); // 32 KB unsigned int count = 100000; for (unsigned int i = 0; i < count; i++){ Test& test = *((Test*)pool.get(pool.set(sizeof(Test)))); test = Test(rand(), rand(), rand()); } std::chrono::high_resolution_clock::time_point start = std::chrono::high_resolution_clock::now(); std::chrono::high_resolution_clock::time_point end = std::chrono::high_resolution_clock::now(); std::chrono::high_resolution_clock::duration dt = end - start; float max = 5.f; float seconds = max; unsigned int counter = 0; while (seconds > 0){ dt = end - start; start = std::chrono::high_resolution_clock::now(); auto iter = pool.begin(); while (iter.valid()){ *((Test*)iter.get()) = Test(rand(), rand(), rand()); iter.next(); } //std::cout << std::chrono::duration_cast<std::chrono::duration<float>>(dt).count() * 1000 << " ms\n"; seconds -= std::chrono::duration_cast<std::chrono::duration<float>>(dt).count(); counter++; end = std::chrono::high_resolution_clock::now(); } std::cout << "FPS : " << counter / max << "\n"; start = std::chrono::high_resolution_clock::now(); // Randomly remove half all elements for (unsigned int i = 0; i < count; i++){ if (!(rand() % 100)) pool.erase(i); } end = std::chrono::high_resolution_clock::now(); dt = end - start; std::cout << "Removing : " << std::chrono::duration_cast<std::chrono::duration<float>>(dt).count() * 1000 << " ms\n"; std::getchar(); return 0; }
21.685393
118
0.614508
ElliottSlingsby
a871bc75a1f740ea9243e61d603db9554171f971
272
cpp
C++
PrintImageSizeUtil/PrintImageSizeUtil.cpp
myarichuk/HunterDemo
def3f9e2ef6dbef901249ff71724217a9137e744
[ "MIT" ]
null
null
null
PrintImageSizeUtil/PrintImageSizeUtil.cpp
myarichuk/HunterDemo
def3f9e2ef6dbef901249ff71724217a9137e744
[ "MIT" ]
null
null
null
PrintImageSizeUtil/PrintImageSizeUtil.cpp
myarichuk/HunterDemo
def3f9e2ef6dbef901249ff71724217a9137e744
[ "MIT" ]
null
null
null
// PrintImageSizeUtil.cpp : Defines the entry point for the application. // #include "PrintImageSizeUtil.h" using namespace std; int main() { const auto img = cv::imread("e:\\Capture.JPG"); cout << "image size: " << img.cols << "x" << img.rows << endl; return 0; }
19.428571
73
0.654412
myarichuk
a8790a439b8e7fa3f7e15f220a17325b429f4990
34,783
cxx
C++
StRoot/StEventUtilities/StuProbabilityPidAlgorithm.cxx
xiaohaijin/RHIC-STAR
a305cb0a6ac15c8165bd8f0d074d7075d5e58752
[ "MIT" ]
2
2018-12-24T19:37:00.000Z
2022-02-28T06:57:20.000Z
StRoot/StEventUtilities/StuProbabilityPidAlgorithm.cxx
xiaohaijin/RHIC-STAR
a305cb0a6ac15c8165bd8f0d074d7075d5e58752
[ "MIT" ]
null
null
null
StRoot/StEventUtilities/StuProbabilityPidAlgorithm.cxx
xiaohaijin/RHIC-STAR
a305cb0a6ac15c8165bd8f0d074d7075d5e58752
[ "MIT" ]
null
null
null
/*************************************************************************** * * $Id: StuProbabilityPidAlgorithm.cxx,v 1.34 2004/09/19 00:07:28 perev Exp $ * * Author:Aihong Tang, Richard Witt(FORTRAN version). Kent State University * Send questions to aihong@cnr.physics.kent.edu *************************************************************************** * * Description: A functor that do PID base on Probability (Amplitude) info. * *************************************************************************** * * $Log: StuProbabilityPidAlgorithm.cxx,v $ * Revision 1.34 2004/09/19 00:07:28 perev * Small Walgrind leak fixed * * Revision 1.33 2004/04/09 15:46:16 aihong * add isPIDTableRead() * * Revision 1.32 2003/09/02 17:58:09 perev * gcc 3.2 updates + WarnOff * * Revision 1.31 2003/06/24 02:53:14 aihong * update for dAu PIDtable * * Revision 1.30 2003/05/02 21:32:08 aihong * destroy myBandBGFcn in destructor * * Revision 1.29 2003/04/30 20:37:12 perev * Warnings cleanup. Modified lines marked VP * * Revision 1.28 2002/12/20 20:26:44 aihong * let it handle P02gd table * * Revision 1.27 2002/12/11 15:35:53 aihong * put in fabs in processPIDAsFuntion() * * Revision 1.26 2002/04/19 16:36:41 perev * bug fix,init to zero * * Revision 1.25 2002/01/17 03:25:27 aihong * add production Tag to take care of different centrality def. between different productions * * Revision 1.24 2001/03/21 18:16:13 aihong * constructor without StEvent added * * Revision 1.23 2001/03/21 17:54:30 aihong * add processPIDAsFunction() * * Revision 1.22 2000/12/28 21:00:57 aihong * remove temp. fix * * Revision 1.21 2000/12/26 23:27:05 aihong * temperory fix for e amp tail * * Revision 1.20 2000/12/20 16:55:16 aihong * let it survive when no support PIDTable is present * * Revision 1.19 2000/12/18 23:51:36 aihong * mExtrap related bug fixed * * Revision 1.10 2000/08/16 12:46:07 aihong * bug killed * * Revision 1.9 2000/08/15 23:04:18 aihong * speed it up by looking up table * * Revision 1.8 2000/07/22 22:45:27 aihong * change include path * * Revision 1.7 2000/07/12 16:29:38 aihong * change to avoid possible name confliction from StarClassLibary * * Revision 1.6 2000/05/24 14:35:41 ullrich * Added 'const' to compile on Sun CC5. * * Revision 1.5 2000/05/05 19:25:39 aihong * modified ctor * * Revision 1.2 2000/03/09 20:45:04 aihong * add head for Log * **************************************************************************/ #include <float.h> #include <Stsstream.h> #include "Stiostream.h" //this line should be deleted later #include "TFile.h" #include "TF1.h" #include "StMessMgr.h" #include "StPhysicalHelixD.hh" #include "PhysicalConstants.h" #include "StuProbabilityPidAlgorithm.h" #include "StEventUtilities/BetheBlochFunction.hh" #include "StEventUtilities/MaxllBoltz.hh" #include "StEventUtilities/Linear.hh" #include "StEventUtilities/StuFtpcRefMult.hh" #include "StEventUtilities/StuRefMult.hh" //TMap::FindObject goes wild!! TMap::GetValue works. //------------------------------- StuProbabilityPidAlgorithm::StuProbabilityPidAlgorithm(StEvent& ev): mPionMinusProb(0.), mElectronProb(0.), mKaonMinusProb(0.), mAntiProtonProb(0.), mPionPlusProb(0.), mPositronProb(0.), mKaonPlusProb(0.), mProtonProb(0.){ PID[0]=-1;//should be sth.standard say unIdentified. PID[1]=-1; PID[2]=-1; PID[3]=-1; mProb[0]=0; mProb[1]=0; mProb[2]=0; mProb[3]=0; table = StParticleTable::instance(); mExtrap=false; mEvent=&ev; //init funtions myBandBGFcn =new TF1("myBandBGFcn",BetheBlochFunction, 0.,5., 7); Double_t myPars[7] ={ 1.072, 0.3199, 1.66032e-07, 1, 1, 2.71172e-07, 0.0005 }; myBandBGFcn->SetParameters(&myPars[0]); } //------------------------------- StuProbabilityPidAlgorithm::StuProbabilityPidAlgorithm(): mPionMinusProb(0.), mElectronProb(0.), mKaonMinusProb(0.), mAntiProtonProb(0.), mPionPlusProb(0.), mPositronProb(0.), mKaonPlusProb(0.), mProtonProb(0.){ PID[0]=-1;//should be sth.standard say unIdentified. PID[1]=-1; PID[2]=-1; PID[3]=-1; mProb[0]=0; mProb[1]=0; mProb[2]=0; mProb[3]=0; table = StParticleTable::instance(); mExtrap=false; //init funtions myBandBGFcn =new TF1("myBandBGFcn",BetheBlochFunction, 0.,5., 7); Double_t myPars[7] ={ 1.072, 0.3199, 1.66032e-07, 1, 1, 2.71172e-07, 0.0005 }; myBandBGFcn->SetParameters(&myPars[0]); } //------------------------------- StuProbabilityPidAlgorithm::~StuProbabilityPidAlgorithm(){ /* no op */ delete myBandBGFcn; } //------------------------------- void StuProbabilityPidAlgorithm::setDedxMethod(StDedxMethod method){ StuProbabilityPidAlgorithm::mDedxMethod=method; } //------------------------------- bool StuProbabilityPidAlgorithm::isPIDTableRead(){ return StuProbabilityPidAlgorithm::mPIDTableRead; } //------------------------------- StParticleDefinition* StuProbabilityPidAlgorithm::mostLikelihoodParticle(){ return table->findParticleByGeantId(PID[0]); } //------------------------------- StParticleDefinition* StuProbabilityPidAlgorithm::secondLikelihoodParticle(){ return table->findParticleByGeantId(PID[1]); } //------------------------------- StParticleDefinition* StuProbabilityPidAlgorithm::thirdLikelihoodParticle(){ return table->findParticleByGeantId(PID[2]); } //------------------------------- StParticleDefinition* StuProbabilityPidAlgorithm::getParticle(int i){ if (i>=0 && i<4){ return table->findParticleByGeantId(PID[i]); } else { gMessMgr->Error()<<"StuProbabilityPidAlgorithm::getParticle(int i), i must be 0,1,2,3 only. "<<endm; return 0; } } //------------------------------- double StuProbabilityPidAlgorithm::getProbability(int i){ if (i>=0 && i<4){ return mProb[i]; } else { gMessMgr->Error()<<"StuProbabilityPidAlgorithm::getProbability(int i), i must be 0,1,2,3 only. "<<endm; return 0.0; } } //------------------------------- double StuProbabilityPidAlgorithm::mostLikelihoodProbability(){ return mProb[0]; } //------------------------------- double StuProbabilityPidAlgorithm::secondLikelihoodProbability(){ return mProb[1]; } //------------------------------- double StuProbabilityPidAlgorithm::thirdLikelihoodProbability(){ return mProb[2]; } //------------------------------- bool StuProbabilityPidAlgorithm::isExtrap(){ return mExtrap; } //------------------------------- StParticleDefinition* StuProbabilityPidAlgorithm::operator() (const StTrack& theTrack, const StSPtrVecTrackPidTraits& traits){ PID[0]=-1;//should be sth.standard say unIdentified. PID[1]=-1; PID[2]=-1; PID[3]=-1; mProb[0]=0; mProb[1]=0; mProb[2]=0; mProb[3]=0; mExtrap=false; mPionMinusProb=0.; mElectronProb=0.; mKaonMinusProb=0.; mAntiProtonProb=0.; mPionPlusProb=0.; mPositronProb=0.; mKaonPlusProb=0.; mProtonProb=0.; if (mPIDTableRead) { double rig =0.0; double dedx =0.0; double dca =0.0; //in units of cm. int nhits =0; int charge =0; double eta =0.; double cent =0.; // % central StPrimaryVertex* primaryVtx=mEvent->primaryVertex(); const StPhysicalHelixD& helix=theTrack.geometry()->helix(); dca=helix.distance(primaryVtx->position()); //cent in cross section if (mProductionTag){ if ( (mProductionTag->GetString()).Contains("P01gl") || (mProductionTag->GetString()).Contains("P02gd") ){ cent = getCentrality(uncorrectedNumberOfNegativePrimaries(*mEvent)); } else if ( (mProductionTag->GetString()).Contains("P03ia_dAu") ){ cent = getCentrality(uncorrectedNumberOfFtpcEastPrimaries(*mEvent)); } else { gMessMgr->Error()<<"Production tag "<<mProductionTag->GetString().Data()<<" in PIDTable is filled but its name is not recognized ! "<<endm; } } else { //the first PID table has no production tag cent = getCentrality(uncorrectedNumberOfNegativePrimaries(*mEvent)); } const StDedxPidTraits* dedxPidTr=0; charge=(theTrack.geometry())->charge(); for (int itrait = 0; itrait < int(traits.size()); itrait++){ dedxPidTr = 0; if (traits[itrait]->detector() == kTpcId) { // // tpc pid trait // const StTrackPidTraits* thisTrait = traits[itrait]; // // perform cast to make the pid trait a dedx trait // dedxPidTr = dynamic_cast<const StDedxPidTraits*>(thisTrait); } if (dedxPidTr && dedxPidTr->method() == mDedxMethod) break; } if (dedxPidTr) { dedx=dedxPidTr->mean(); nhits=dedxPidTr->numberOfPoints(); } if (dedx!=0.0 && nhits>=0 //dedx ==0.0 no sense && thisPEnd > 0. && thisEtaEnd > 0. // *End ==0, no PIDTable read. && thisNHitsEnd > 0. ){ const StThreeVectorF& p=theTrack.geometry()->momentum(); rig=double(p.mag()/charge); if (mProductionTag){ //for AuAu, +/- eta were folded together when building PID //table, for dAu, + and - eta were treated differently. if ( (mProductionTag->GetString()).Contains("P01gl") || (mProductionTag->GetString()).Contains("P02gd") ){ eta=fabs(p.pseudoRapidity()); } else if ( (mProductionTag->GetString()).Contains("P03ia_dAu") ){ eta=p.pseudoRapidity(); } else { gMessMgr->Error()<<"Production tag "<<mProductionTag->GetString().Data()<<" in PIDTable is filled but its name is not recognized ! "<<endm; } } else { //the first PID table has no production tag eta = fabs(p.pseudoRapidity()); } rig = fabs(rig); dedx = (dedx>thisDedxStart) ? dedx : thisDedxStart; rig = (rig >thisPStart) ? rig : thisPStart; rig = (rig <thisPEnd ) ? rig : thisPEnd*0.9999; eta = (eta >thisEtaStart) ? eta : thisEtaStart; eta = (eta <thisEtaEnd ) ? eta : thisEtaEnd*0.9999; nhits = (nhits > int(thisNHitsStart)) ? nhits : int(thisNHitsStart); nhits = (nhits < int(thisNHitsEnd) ) ? nhits : int(thisNHitsEnd-1); //----------------get all info. I want for a track. now do PID setCalibrations(eta, nhits); if (dedx<thisDedxEnd){ fillPIDByLookUpTable(cent, dca, charge,rig, eta, nhits,dedx); } else { lowRigPID(rig,dedx,charge);} } else if (dedx==0.0){ fillAsUnknown();} // do not do deuteron or higher myBandBGFcn->SetParameter(3,1); myBandBGFcn->SetParameter(4,1.45); if (dedx>myBandBGFcn->Eval(rig,0,0)) fillAsUnknown(); } else fillAsUnknown(); fillPIDHypothis(); return table->findParticleByGeantId(PID[0]); } //------------------------------- void StuProbabilityPidAlgorithm::lowRigPID(double rig,double dedx,int theCharge){ double upper; double lower; double rigidity=fabs(rig); double mdedx=dedx; double fakeMass=0.; //pion fakeMass=0.32075026; myBandBGFcn->SetParameter(3,1); myBandBGFcn->SetParameter(4,0.32075026 ); lower =0.; upper =myBandBGFcn->Eval(rigidity,0,0); if (mdedx>lower && mdedx<upper){ PID[0]=(theCharge>0.0)? 8 : 9; //pi+/- mProb[0]=1.0; mProb[1]=0.0; mProb[2]=0.0; mProb[3]=0.0; } lower = upper; //kaon fakeMass=0.709707; myBandBGFcn->SetParameter(3,1); myBandBGFcn->SetParameter(4,fakeMass); upper =myBandBGFcn->Eval(rigidity,0,0); if (mdedx>lower && mdedx<upper){ PID[0]=(theCharge>0.0)? 11:12; //k+/- mProb[0]=1.0; mProb[1]=0.0; mProb[2]=0.0; mProb[3]=0.0; } lower = upper; //proton/pBar fakeMass=1.45; myBandBGFcn->SetParameter(3,1); myBandBGFcn->SetParameter(4,fakeMass); upper =myBandBGFcn->Eval(rigidity,0,0); if (mdedx>lower && mdedx<upper){ PID[0]=(theCharge>0.0)? 14:15; //proton/antiproton mProb[0]=1.0; mProb[1]=0.0; mProb[2]=0.0; mProb[3]=0.0; } /* lower = upper; //deuteron fakeMass=2.4; myBandBGFcn->SetParameter(3,1); myBandBGFcn->SetParameter(4,fakeMass); upper =myBandBGFcn->Eval(rigidity,0,0); if (mdedx>lower && mdedx<upper){ PID[0]=45; //deuteron mProb[0]=1.0; mProb[1]=0.0; mProb[2]=0.0; mProb[3]=0.0; } lower = upper; //triton m = -1.5374; //New slope needed for deuterons and tritons. a = 1.8121e-5; upper = a*::pow(rigidity,m); if (mdedx>lower && mdedx<upper){ PID[0]=46; //triton mProb[0]=1.0; mProb[1]=0.0; mProb[2]=0.0; mProb[3]=0.0; } */ } //------------------------------- void StuProbabilityPidAlgorithm::fillAsUnknown(){ for (int i=0; i<4; i++) { PID[i]=-1; mProb[i]=-1; } } //------------------------------- void StuProbabilityPidAlgorithm::readParametersFromFile(TString fileName){ TFile f(fileName,"READ"); if (f.IsOpen()){ delete StuProbabilityPidAlgorithm::mEAmp ; delete StuProbabilityPidAlgorithm::mECenter ; delete StuProbabilityPidAlgorithm::mESigma ; delete StuProbabilityPidAlgorithm::mPiAmp ; delete StuProbabilityPidAlgorithm::mPiCenter ; delete StuProbabilityPidAlgorithm::mPiSigma ; delete StuProbabilityPidAlgorithm::mKAmp ; delete StuProbabilityPidAlgorithm::mKCenter ; delete StuProbabilityPidAlgorithm::mKSigma ; delete StuProbabilityPidAlgorithm::mPAmp ; delete StuProbabilityPidAlgorithm::mPCenter ; delete StuProbabilityPidAlgorithm::mPSigma ; delete StuProbabilityPidAlgorithm::mEqualyDividableRangeStartSet; delete StuProbabilityPidAlgorithm::mEqualyDividableRangeEndSet; delete StuProbabilityPidAlgorithm::mEqualyDividableRangeNBinsSet; delete StuProbabilityPidAlgorithm::mNoEqualyDividableRangeNBinsSet; delete StuProbabilityPidAlgorithm::mMultiBinEdgeSet ; delete StuProbabilityPidAlgorithm::mDcaBinEdgeSet ; delete StuProbabilityPidAlgorithm::mBBPrePar; delete StuProbabilityPidAlgorithm::mBBTurnOver; delete StuProbabilityPidAlgorithm::mBBOffSet; delete StuProbabilityPidAlgorithm::mBBScale; delete StuProbabilityPidAlgorithm::mBBSaturate; delete StuProbabilityPidAlgorithm::mProductionTag; StuProbabilityPidAlgorithm::mEAmp =(TVectorD* )f.Get("eAmp"); StuProbabilityPidAlgorithm::mECenter =(TVectorD* )f.Get("eCenter"); StuProbabilityPidAlgorithm::mESigma =(TVectorD* )f.Get("eSigma"); StuProbabilityPidAlgorithm::mPiAmp =(TVectorD* )f.Get("piAmp"); StuProbabilityPidAlgorithm::mPiCenter =(TVectorD* )f.Get("piCenter"); StuProbabilityPidAlgorithm::mPiSigma =(TVectorD* )f.Get("piSigma"); StuProbabilityPidAlgorithm::mKAmp =(TVectorD* )f.Get("kAmp"); StuProbabilityPidAlgorithm::mKCenter =(TVectorD* )f.Get("kCenter"); StuProbabilityPidAlgorithm::mKSigma =(TVectorD* )f.Get("kSigma"); StuProbabilityPidAlgorithm::mPAmp =(TVectorD* )f.Get("pAmp"); StuProbabilityPidAlgorithm::mPCenter =(TVectorD* )f.Get("pCenter"); StuProbabilityPidAlgorithm::mPSigma =(TVectorD* )f.Get("pSigma"); StuProbabilityPidAlgorithm::mEqualyDividableRangeStartSet =(TVectorD* )f.Get("EqualyDividableRangeStartSet"); StuProbabilityPidAlgorithm::mEqualyDividableRangeEndSet =(TVectorD* )f.Get("EqualyDividableRangeEndSet"); StuProbabilityPidAlgorithm::mEqualyDividableRangeNBinsSet =(TVectorD* )f.Get("EqualyDividableRangeNBinsSet"); StuProbabilityPidAlgorithm::mNoEqualyDividableRangeNBinsSet =(TVectorD* )f.Get("NoEqualyDividableRangeNBinsSet"); StuProbabilityPidAlgorithm::mMultiBinEdgeSet =(TVectorD* )f.Get("MultiBinEdgeSet"); StuProbabilityPidAlgorithm::mDcaBinEdgeSet =(TVectorD* )f.Get("DcaBinEdgeSet"); StuProbabilityPidAlgorithm::mBBPrePar =(TVectorD* )f.Get("BBPrePar"); StuProbabilityPidAlgorithm::mBBTurnOver =(TVectorD* )f.Get("BBTurnOver"); StuProbabilityPidAlgorithm::mBBOffSet =(TVectorD* )f.Get("BBOffSet"); StuProbabilityPidAlgorithm::mBBScale =(TVectorD* )f.Get("BBScale"); StuProbabilityPidAlgorithm::mBBSaturate =(TVectorD* )f.Get("BBSaturate"); StuProbabilityPidAlgorithm::mProductionTag =(TObjString* )f.Get("productionTag"); StuProbabilityPidAlgorithm::thisMultBins =int((*mNoEqualyDividableRangeNBinsSet)(0)); StuProbabilityPidAlgorithm::thisDcaBins =int((*mNoEqualyDividableRangeNBinsSet)(1)); StuProbabilityPidAlgorithm::thisChargeBins =int((*mNoEqualyDividableRangeNBinsSet)(2)); StuProbabilityPidAlgorithm::thisPBins =int((*mEqualyDividableRangeNBinsSet)(1)); StuProbabilityPidAlgorithm::thisEtaBins =int((*mEqualyDividableRangeNBinsSet)(2)); StuProbabilityPidAlgorithm::thisNHitsBins =int((*mEqualyDividableRangeNBinsSet)(3)); StuProbabilityPidAlgorithm::thisDedxStart =(*mEqualyDividableRangeStartSet)(0); StuProbabilityPidAlgorithm::thisPStart =(*mEqualyDividableRangeStartSet)(1); StuProbabilityPidAlgorithm::thisEtaStart =(*mEqualyDividableRangeStartSet)(2); StuProbabilityPidAlgorithm::thisNHitsStart =(*mEqualyDividableRangeStartSet)(3); StuProbabilityPidAlgorithm::thisDedxEnd =(*mEqualyDividableRangeEndSet)(0); StuProbabilityPidAlgorithm::thisPEnd =(*mEqualyDividableRangeEndSet)(1); StuProbabilityPidAlgorithm::thisEtaEnd =(*mEqualyDividableRangeEndSet)(2); StuProbabilityPidAlgorithm::thisNHitsEnd =(*mEqualyDividableRangeEndSet)(3); StuProbabilityPidAlgorithm::mPIDTableRead=true; } else if (!f.IsOpen()) { gMessMgr->Error()<<"Data file "<<fileName<<" open failed "<<endm; return; } } /* uncomment this method when data base is available and stable. //------------------------------- void StuProbabilityPidAlgorithm::readParametersFromTable(St_Table* tb){ if (mDataTable!=tb) {//database changed. StuProbabilityPidAlgorithm::refreshParameters(tb); mDataTable=tb; }else if (mDataTable==tb) {return;}//database no change. no need refreshing. } */ /*uncomment this method when data base is available and stable. //------------------------------- void StuProbabilityPidAlgorithm::refreshParameters(St_Table* theTable){ int i; if (mDataSet.GetEntries()>0) mDataSet.Delete(); St_tpcDedxPidAmpDb* temp=(St_tpcDedxPidAmpDb *)theTable; tpcDedxPidAmpDb_st* pars=(tpcDedxPidAmpDb_st *)temp->GetTable(); StPidAmpChannelInfoOut* theInfoOut=new StPidAmpChannelInfoOut(0,45,0,FLT_MAX); TObjArray* theOnlyChannel=new TObjArray(); theOnlyChannel->Add(theInfoOut); StuProbabilityPidAlgorithm::readAType(StElectron::instance(),pars->eMeanPar, pars->eAmpPar, pars->eSigPar,pars->gasCalib, theOnlyChannel); mDataSet.Add(theOnlyChannel); } */ //------------------------------- int StuProbabilityPidAlgorithm::thisMultBins=0; int StuProbabilityPidAlgorithm::thisDcaBins=0; int StuProbabilityPidAlgorithm::thisChargeBins=0; int StuProbabilityPidAlgorithm::thisPBins=0; int StuProbabilityPidAlgorithm::thisEtaBins=0; int StuProbabilityPidAlgorithm::thisNHitsBins=0; double StuProbabilityPidAlgorithm::thisDedxStart=0.; double StuProbabilityPidAlgorithm::thisDedxEnd=0; double StuProbabilityPidAlgorithm::thisPStart=0; double StuProbabilityPidAlgorithm::thisPEnd=0; double StuProbabilityPidAlgorithm::thisEtaStart=0; double StuProbabilityPidAlgorithm::thisEtaEnd=0; double StuProbabilityPidAlgorithm::thisNHitsStart=0; double StuProbabilityPidAlgorithm::thisNHitsEnd=0; bool StuProbabilityPidAlgorithm::mPIDTableRead=false; StDedxMethod StuProbabilityPidAlgorithm::mDedxMethod=kTruncatedMeanId; TVectorD* StuProbabilityPidAlgorithm::mEAmp = new TVectorD(); TVectorD* StuProbabilityPidAlgorithm::mECenter = new TVectorD(); TVectorD* StuProbabilityPidAlgorithm::mESigma = new TVectorD(); TVectorD* StuProbabilityPidAlgorithm::mPiAmp = new TVectorD(); TVectorD* StuProbabilityPidAlgorithm::mPiCenter = new TVectorD(); TVectorD* StuProbabilityPidAlgorithm::mPiSigma = new TVectorD(); TVectorD* StuProbabilityPidAlgorithm::mKAmp = new TVectorD(); TVectorD* StuProbabilityPidAlgorithm::mKCenter = new TVectorD(); TVectorD* StuProbabilityPidAlgorithm::mKSigma = new TVectorD(); TVectorD* StuProbabilityPidAlgorithm::mPAmp = new TVectorD(); TVectorD* StuProbabilityPidAlgorithm::mPCenter = new TVectorD(); TVectorD* StuProbabilityPidAlgorithm::mPSigma = new TVectorD(); TVectorD* StuProbabilityPidAlgorithm::mEqualyDividableRangeStartSet = new TVectorD(); TVectorD* StuProbabilityPidAlgorithm::mEqualyDividableRangeEndSet = new TVectorD(); TVectorD* StuProbabilityPidAlgorithm::mEqualyDividableRangeNBinsSet = new TVectorD(); TVectorD* StuProbabilityPidAlgorithm::mNoEqualyDividableRangeNBinsSet = new TVectorD(); TVectorD* StuProbabilityPidAlgorithm::mMultiBinEdgeSet = new TVectorD(); TVectorD* StuProbabilityPidAlgorithm::mDcaBinEdgeSet = new TVectorD(); TVectorD* StuProbabilityPidAlgorithm::mBBPrePar = new TVectorD(); TVectorD* StuProbabilityPidAlgorithm::mBBTurnOver = new TVectorD(); TVectorD* StuProbabilityPidAlgorithm::mBBOffSet = new TVectorD(); TVectorD* StuProbabilityPidAlgorithm::mBBScale = new TVectorD(); TVectorD* StuProbabilityPidAlgorithm::mBBSaturate = new TVectorD(); TObjString* StuProbabilityPidAlgorithm::mProductionTag = new TObjString(); //------------------------------- //St_Table* StuProbabilityPidAlgorithm::mDataTable=0; //------------------------------- void StuProbabilityPidAlgorithm::fillPIDByLookUpTable(double myCentrality, double myDca, int myCharge, double myRig, double myEta, int myNhits, double myDedx) { //assume bound has been checked before they enter this func. int theMultBin=getCentralityBin(myCentrality); int theDcaBin = (myDca>(*mDcaBinEdgeSet)(1)) ? 1 : 0; int theChargeBin=(myCharge>0) ? 1 : 0; int thePBin=int(thisPBins*myRig/(thisPEnd-thisPStart)); int theEtaBin=int(thisEtaBins*(myEta-thisEtaStart)/(thisEtaEnd-thisEtaStart)); int theNHitsBin=int(thisNHitsBins*float(myNhits)/(thisNHitsEnd-thisNHitsStart)); int totalEntry = thisMultBins*thisDcaBins*thisChargeBins*thisPBins*thisEtaBins*thisNHitsBins; int positionPointer=0; totalEntry=totalEntry/thisMultBins; positionPointer=positionPointer+totalEntry*theMultBin; totalEntry=totalEntry/thisDcaBins; positionPointer=positionPointer+totalEntry*theDcaBin; totalEntry=totalEntry/thisChargeBins; positionPointer=positionPointer+totalEntry*theChargeBin; totalEntry=totalEntry/thisPBins; positionPointer=positionPointer+totalEntry*thePBin; totalEntry=totalEntry/thisEtaBins; positionPointer=positionPointer+totalEntry*theEtaBin; totalEntry=totalEntry/thisNHitsBins; positionPointer=positionPointer+totalEntry*theNHitsBin; //now calculate prob. TF1 eGaus("eGaus","gaus",thisDedxStart,thisDedxStart); TF1 piGaus("piGaus","gaus",thisDedxStart,thisDedxStart); TF1 kGaus("kGaus","gaus",thisDedxStart,thisDedxStart); TF1 pGaus("pGaus","gaus",thisDedxStart,thisDedxStart); eGaus.SetParameter(0, (*mEAmp)(positionPointer)); eGaus.SetParameter(1, (*mECenter)(positionPointer)); eGaus.SetParameter(2, (*mESigma)(positionPointer)); piGaus.SetParameter(0, (*mPiAmp)(positionPointer)); piGaus.SetParameter(1, (*mPiCenter)(positionPointer)); piGaus.SetParameter(2, (*mPiSigma)(positionPointer)); kGaus.SetParameter(0, (*mKAmp)(positionPointer)); kGaus.SetParameter(1, (*mKCenter)(positionPointer)); kGaus.SetParameter(2, (*mKSigma)(positionPointer)); pGaus.SetParameter(0, (*mPAmp)(positionPointer)); pGaus.SetParameter(1, (*mPCenter)(positionPointer)); pGaus.SetParameter(2, (*mPSigma)(positionPointer)); double eContribution=0; if (mEAmp && mECenter && mESigma) eContribution = eGaus.Eval(myDedx,0.,0.); // if (fabs(myRig)>0.95) eContribution=0; //will deal with it later. double piContribution=0; if (mPiAmp && mPiCenter && mPiSigma) piContribution = piGaus.Eval(myDedx,0.,0.); double kContribution=0; if (mKAmp && mKCenter && mKSigma) kContribution = kGaus.Eval(myDedx,0.,0.); double pContribution=0; if (mPAmp && mPCenter && mPSigma) pContribution = pGaus.Eval(myDedx,0.,0.); double total = eContribution+piContribution+kContribution+pContribution; double eProb=0; double piProb=0; double kProb=0; double pProb=0; if (total>0) { eProb=eContribution/total; piProb=piContribution/total; kProb=kContribution/total; pProb=pContribution/total; } fill(eProb, int((myCharge>0) ? 2 : 3 )); fill(piProb, int((myCharge>0) ? 8 : 9 )); fill(kProb, int((myCharge>0) ? 11 : 12 )); fill(pProb, int((myCharge>0) ? 14 : 15 )); int nn=-1; float PathHeight=1.0e-7; float halfHeight=(11-2.0)*PathHeight/2.0; if (fabs(myRig) > 0.3) { if ((myDedx<(((*mPiCenter)(positionPointer))+halfHeight-nn*PathHeight)) && (myDedx > ( ((*mKCenter)(positionPointer))-halfHeight+nn*PathHeight) )) mExtrap=true; } } //------------------------------- void StuProbabilityPidAlgorithm::fillPIDHypothis(){ for (int i=0; i<4; i++){ switch (PID[i]) { case 2 : mPositronProb=mProb[i]; break; case 3 : mElectronProb=mProb[i]; break; case 8 : mPionPlusProb=mProb[i]; break; case 9 : mPionMinusProb=mProb[i]; break; case 11 : mKaonPlusProb=mProb[i]; break; case 12 : mKaonMinusProb=mProb[i]; break; case 14 : mProtonProb=mProb[i]; break; case 15 : mAntiProtonProb=mProb[i]; break; } } } //------------------------------- int StuProbabilityPidAlgorithm::getCentralityBin(double theCent){ int theBin=0; //input % centrality. output the corres. bin. for (int mm = (thisMultBins-1); mm>0; mm--) { if (theCent< (*mMultiBinEdgeSet)(mm) ) theBin=mm; } return theBin; } //------------------------------- double StuProbabilityPidAlgorithm::getCentrality(int theMult){ if (mProductionTag){ if ( (mProductionTag->GetString()).Contains("P01gl") || (mProductionTag->GetString()).Contains("P02gd") ){ return getCentrality_P01gl(theMult); } else if ((mProductionTag->GetString()).Contains("P03ia_dAu")){ return getCentrality_P03ia_dAu(theMult); } else { gMessMgr->Error()<<"Production tag "<<mProductionTag->GetString().Data()<<" in PIDTable is filled but its name is not recognized ! "<<endm; } } else {//the first PID table does not have a productionTag // limits // For Cut Set 1 // 225 ~ 3% // 215 ~ 5% // 200 ~ 7% // 180 ~ 10% // 140 ~ 18% // 130 ~ 20% // 120 ~ 23% // 115 ~ 24% // 100 ~ 28% // highMedLimit = 180; // 10% // medLowLimit = 108; //~26% if (theMult > 225 ) return 0.03; else if (theMult > 215 ) return 0.05; else if (theMult > 200 ) return 0.07; else if (theMult > 180 ) return 0.10; else if (theMult > 140 ) return 0.18; else if (theMult > 130 ) return 0.20; else if (theMult > 120 ) return 0.23; else if (theMult > 115 ) return 0.24; else if (theMult > 100 ) return 0.28; else return 0.99; } return 0.99; } //------------------------------- double StuProbabilityPidAlgorithm::getCentrality_P01gl(int theMult){ //from Zhangbu's study //5% 474 //10% 409 //20% 302 //30% 216 //40% 149 //50% 98 //60% 59 //70% 32 //80% 14 if (theMult*2. > 474 ) return 0.03; //use Nch instead of hminus. so *2. else if (theMult*2. > 409 ) return 0.10; else if (theMult*2. > 302 ) return 0.20; else if (theMult*2. > 216 ) return 0.30; else if (theMult*2. > 149 ) return 0.40; else if (theMult*2. > 98 ) return 0.50; else if (theMult*2. > 59 ) return 0.60; else if (theMult*2. > 32 ) return 0.70; else if (theMult*2. > 14 ) return 0.80; else return 0.99; } //------------------------------- double StuProbabilityPidAlgorithm::getCentrality_P03ia_dAu(int theMult){ //from Joern's study // * centrality bin multiplicity FTPC east percentOfEvents // * 1 <=11 100-40 // * 2 <=17 40-20 // * 3 >=18 20-0 if (theMult >= 18 ) return 0.19; //do not need to be exact. else if (theMult >= 12 ) return 0.39; //just for gettting bin # correctly. else if (theMult > 0 ) return 0.8; else return 0.99; } //------------------------------- void StuProbabilityPidAlgorithm::fill(double prob, int geantId){ if (prob>mProb[0]) { mProb[3]=mProb[2]; mProb[2]=mProb[1]; mProb[1]=mProb[0]; mProb[0]=prob; PID[3]=PID[2]; PID[2]=PID[1]; PID[1]=PID[0]; PID[0]=geantId; } else if (prob>mProb[1]){ mProb[3]=mProb[2]; mProb[2]=mProb[1]; mProb[1]=prob; PID[3]=PID[2]; PID[2]=PID[1]; PID[1] =geantId; } else if (prob>mProb[2]){ mProb[3]=mProb[2]; mProb[2]=prob; PID[3]=PID[2]; PID[2]=geantId; } else if (prob>=mProb[3]){ mProb[3]=prob; PID[3]=geantId; } } //------------------------------------------------ int StuProbabilityPidAlgorithm::getCalibPosition(double theEta, int theNHits){ int theEtaBin=int(thisEtaBins*(theEta-thisEtaStart)/(thisEtaEnd-thisEtaStart)); int theNHitsBin=int(thisNHitsBins*float(theNHits)/(thisNHitsEnd-thisNHitsStart)); int totalEntry = thisEtaBins*thisNHitsBins; int positionPointer=0; totalEntry=totalEntry/thisEtaBins; positionPointer=positionPointer+totalEntry*theEtaBin; totalEntry=totalEntry/thisNHitsBins; positionPointer=positionPointer+totalEntry*theNHitsBin; return positionPointer; } //-------------------------------------------- void StuProbabilityPidAlgorithm::setCalibrations(double theEta, int theNhits){ int thePosition=getCalibPosition(theEta,theNhits); myBandBGFcn->SetParameter(5,(*mBBScale)(thePosition)); myBandBGFcn->SetParameter(2,(*mBBOffSet)(thePosition)); if (mProductionTag){ if ( (mProductionTag->GetString()).Contains("P01gl") || (mProductionTag->GetString()).Contains("P02gd")){ myBandBGFcn->SetParameter(0,(*mBBPrePar)(thePosition)); myBandBGFcn->SetParameter(1,(*mBBTurnOver)(thePosition)); myBandBGFcn->SetParameter(6,(*mBBSaturate)(thePosition)); } } } //-------------------------------------cent,dca,charge,rig,eta,nhits,dedx void StuProbabilityPidAlgorithm::processPIDAsFunction (double theCent, double theDca, int theCharge, double theRig, double theEta, int theNhits, double theDedx){ PID[0]=-1;//should be sth.standard say unIdentified. PID[1]=-1; PID[2]=-1; PID[3]=-1; mProb[0]=0; mProb[1]=0; mProb[2]=0; mProb[3]=0; mExtrap=false; mPionMinusProb=0.; mElectronProb=0.; mKaonMinusProb=0.; mAntiProtonProb=0.; mPionPlusProb=0.; mPositronProb=0.; mKaonPlusProb=0.; mProtonProb=0.; if (mPIDTableRead) { double rig =fabs(theRig); double dedx =theDedx; double dca =theDca; //in units of cm. int nhits =theNhits; int charge =theCharge; double eta =0.; double cent =theCent; // % central if (mProductionTag){ //for AuAu, +/- eta were folded together when building PID //table, for dAu, + and - eta were treated differently. if ( (mProductionTag->GetString()).Contains("P01gl") || (mProductionTag->GetString()).Contains("P02gd") ){ eta=fabs(theEta); } else if ( (mProductionTag->GetString()).Contains("P03ia_dAu") ){ eta=theEta; } else { gMessMgr->Error()<<"Production tag "<<mProductionTag->GetString().Data()<<" in PIDTable is filled but its name is not recognized ! "<<endm; } } else { //the first PID table has no production tag eta = fabs(theEta); } if (dedx!=0.0 && nhits>=0 //dedx ==0.0 no sense && thisPEnd > 0. && thisEtaEnd > 0. // *End ==0, no PIDTable read. && thisNHitsEnd > 0. ){ rig = fabs(rig); dedx = (dedx>thisDedxStart) ? dedx : thisDedxStart; rig = (rig >thisPStart) ? rig : thisPStart; rig = (rig <thisPEnd ) ? rig : thisPEnd*0.9999; eta = (eta >thisEtaStart) ? eta : thisEtaStart; eta = (eta <thisEtaEnd ) ? eta : thisEtaEnd*0.9999; nhits = (nhits > int(thisNHitsStart)) ? nhits : int(thisNHitsStart); nhits = (nhits < int(thisNHitsEnd) ) ? nhits : int(thisNHitsEnd-1); //----------------get all info. I want for a track. now do PID setCalibrations(eta, nhits); if (dedx<thisDedxEnd){ fillPIDByLookUpTable(cent, dca, charge,rig, eta, nhits,dedx); } else { lowRigPID(rig,dedx,charge);} } else if (dedx==0.0){ fillAsUnknown();} // do not do deuteron or higher myBandBGFcn->SetParameter(3,1); myBandBGFcn->SetParameter(4,1.45); if (dedx>myBandBGFcn->Eval(rig,0,0)) fillAsUnknown(); } else fillAsUnknown(); fillPIDHypothis(); }
29.72906
161
0.619239
xiaohaijin
a879d12611f6ebd30250cdb311437014b97d3515
247
cpp
C++
src/test.cpp
Liuchang0812/leetcode
d71f87b0035e661d0009f4382b39c4787c355f89
[ "MIT" ]
9
2015-09-09T20:28:31.000Z
2019-05-15T09:13:07.000Z
src/test.cpp
liuchang0812/leetcode
d71f87b0035e661d0009f4382b39c4787c355f89
[ "MIT" ]
1
2015-02-25T13:10:09.000Z
2015-02-25T13:10:09.000Z
src/test.cpp
liuchang0812/leetcode
d71f87b0035e661d0009f4382b39c4787c355f89
[ "MIT" ]
1
2016-08-31T19:14:52.000Z
2016-08-31T19:14:52.000Z
#include <deque> #include <iostream> using namespace std; int main() { deque<int> dq; dq.push(1); dq.push(2); dq.push(4); for (auto i = dq.begin(); i != dq.end(); ++i) { cout << *i << endl; } return 0; }
13
49
0.48583
Liuchang0812
a87e1a085c5c9fe8cf1a9fea4be0a5f7384565d6
111,505
cxx
C++
main/sw/source/filter/ww8/docxattributeoutput.cxx
jimjag/openoffice
74746a22d8cc22b031b00fcd106f4496bf936c77
[ "Apache-2.0" ]
1
2019-12-27T19:25:34.000Z
2019-12-27T19:25:34.000Z
main/sw/source/filter/ww8/docxattributeoutput.cxx
ackza/openoffice
d49dfe9c625750e261c7ed8d6ccac8d361bf3418
[ "Apache-2.0" ]
1
2019-11-25T03:08:58.000Z
2019-11-25T03:08:58.000Z
main/sw/source/filter/ww8/docxattributeoutput.cxx
ackza/openoffice
d49dfe9c625750e261c7ed8d6ccac8d361bf3418
[ "Apache-2.0" ]
6
2019-11-19T00:28:25.000Z
2019-11-22T06:48:49.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #include "docxattributeoutput.hxx" #include "docxexport.hxx" #include "docxfootnotes.hxx" #include "writerwordglue.hxx" #include "wrtww8.hxx" #include "ww8par.hxx" #include <oox/token/tokens.hxx> #include <oox/export/drawingml.hxx> #include <oox/export/utils.hxx> #include <oox/export/vmlexport.hxx> #include <i18npool/mslangid.hxx> #include <hintids.hxx> #include <svl/poolitem.hxx> #include <editeng/fontitem.hxx> #include <editeng/tstpitem.hxx> #include <editeng/adjitem.hxx> #include <editeng/spltitem.hxx> #include <editeng/widwitem.hxx> #include <editeng/lspcitem.hxx> #include <editeng/keepitem.hxx> #include <editeng/shaditem.hxx> #include <editeng/brshitem.hxx> #include <editeng/postitem.hxx> #include <editeng/wghtitem.hxx> #include <editeng/kernitem.hxx> #include <editeng/crsditem.hxx> #include <editeng/cmapitem.hxx> #include <editeng/wrlmitem.hxx> #include <editeng/udlnitem.hxx> #include <editeng/langitem.hxx> #include <editeng/escpitem.hxx> #include <editeng/fhgtitem.hxx> #include <editeng/colritem.hxx> #include <editeng/hyznitem.hxx> #include <editeng/brkitem.hxx> #include <editeng/lrspitem.hxx> #include <editeng/ulspitem.hxx> #include <editeng/boxitem.hxx> #include <editeng/cntritem.hxx> #include <editeng/shdditem.hxx> #include <editeng/akrnitem.hxx> #include <editeng/pbinitem.hxx> #include <editeng/emphitem.hxx> #include <editeng/twolinesitem.hxx> #include <editeng/charscaleitem.hxx> #include <editeng/charrotateitem.hxx> #include <editeng/charreliefitem.hxx> #include <editeng/paravertalignitem.hxx> #include <editeng/pgrditem.hxx> #include <editeng/frmdiritem.hxx> #include <editeng/blnkitem.hxx> #include <editeng/charhiddenitem.hxx> #include <svx/svdmodel.hxx> #include <svx/svdobj.hxx> #include <docufld.hxx> #include <flddropdown.hxx> #include <format.hxx> #include <fmtclds.hxx> #include <fmtinfmt.hxx> #include <fmtfld.hxx> #include <fmtfsize.hxx> #include <fmtftn.hxx> #include <fmtrowsplt.hxx> #include <fmtline.hxx> #include <frmfmt.hxx> #include <frmatr.hxx> #include <ftninfo.hxx> #include <htmltbl.hxx> #include <ndgrf.hxx> #include <ndtxt.hxx> #include <node.hxx> #include <pagedesc.hxx> #include <paratr.hxx> #include <swmodule.hxx> #include <swtable.hxx> #include <txtftn.hxx> #include <txtinet.hxx> #include <numrule.hxx> #include <rtl/strbuf.hxx> #include <rtl/ustrbuf.hxx> #include <rtl/ustring.hxx> #include <tools/color.hxx> #include <com/sun/star/i18n/ScriptType.hdl> #if OSL_DEBUG_LEVEL > 0 #include <stdio.h> #endif using rtl::OString; using rtl::OStringBuffer; using rtl::OUString; using rtl::OUStringBuffer; using rtl::OUStringToOString; using namespace oox; using namespace docx; using namespace sax_fastparser; using namespace nsSwDocInfoSubType; using namespace nsFieldFlags; using namespace sw::util; void DocxAttributeOutput::RTLAndCJKState( bool bIsRTL, sal_uInt16 /*nScript*/ ) { if (bIsRTL) m_pSerializer->singleElementNS( XML_w, XML_rtl, FSNS( XML_w, XML_val ), "true", FSEND ); } void DocxAttributeOutput::StartParagraph( ww8::WW8TableNodeInfo::Pointer_t pTextNodeInfo ) { if ( m_nColBreakStatus == COLBRK_POSTPONE ) m_nColBreakStatus = COLBRK_WRITE; // Output table/table row/table cell starts if needed if ( pTextNodeInfo.get() ) { sal_uInt32 nRow = pTextNodeInfo->getRow(); sal_uInt32 nCell = pTextNodeInfo->getCell(); // New cell/row? if ( m_nTableDepth > 0 && !m_bTableCellOpen ) { ww8::WW8TableNodeInfoInner::Pointer_t pDeepInner( pTextNodeInfo->getInnerForDepth( m_nTableDepth ) ); if ( pDeepInner->getCell() == 0 ) StartTableRow( pDeepInner ); StartTableCell( pDeepInner ); } if ( nRow == 0 && nCell == 0 ) { // Do we have to start the table? // [If we are at the rigth depth already, it means that we // continue the table cell] sal_uInt32 nCurrentDepth = pTextNodeInfo->getDepth(); if ( nCurrentDepth > m_nTableDepth ) { // Start all the tables that begin here for ( sal_uInt32 nDepth = m_nTableDepth + 1; nDepth <= pTextNodeInfo->getDepth(); ++nDepth ) { ww8::WW8TableNodeInfoInner::Pointer_t pInner( pTextNodeInfo->getInnerForDepth( nDepth ) ); StartTable( pInner ); StartTableRow( pInner ); StartTableCell( pInner ); } m_nTableDepth = nCurrentDepth; } } } m_pSerializer->startElementNS( XML_w, XML_p, FSEND ); // postpone the output of the run (we get it before the paragraph // properties, but must write it after them) m_pSerializer->mark(); // no section break in this paragraph yet; can be set in SectionBreak() m_pSectionInfo = NULL; m_bParagraphOpened = true; } void DocxAttributeOutput::EndParagraph( ww8::WW8TableNodeInfoInner::Pointer_t pTextNodeInfoInner ) { // write the paragraph properties + the run, already in the correct order m_pSerializer->mergeTopMarks(); m_pSerializer->endElementNS( XML_w, XML_p ); // Check for end of cell, rows, tables here FinishTableRowCell( pTextNodeInfoInner ); m_bParagraphOpened = false; } void DocxAttributeOutput::FinishTableRowCell( ww8::WW8TableNodeInfoInner::Pointer_t pInner, bool bForceEmptyParagraph ) { if ( pInner.get() ) { // Where are we in the table sal_uInt32 nRow = pInner->getRow( ); const SwTable *pTable = pInner->getTable( ); const SwTableLines& rLines = pTable->GetTabLines( ); sal_uInt16 nLinesCount = rLines.Count( ); if ( pInner->isEndOfCell() ) { if ( bForceEmptyParagraph ) m_pSerializer->singleElementNS( XML_w, XML_p, FSEND ); EndTableCell(); } // This is a line end if ( pInner->isEndOfLine() ) EndTableRow(); // This is the end of the table if ( pInner->isEndOfLine( ) && ( nRow + 1 ) == nLinesCount ) EndTable(); } } void DocxAttributeOutput::EmptyParagraph() { m_pSerializer->singleElementNS( XML_w, XML_p, FSEND ); } void DocxAttributeOutput::StartParagraphProperties( const SwTxtNode& rNode ) { // output page/section breaks // Writer can have them at the beginning of a paragraph, or at the end, but // in docx, we have to output them in the paragraph properties of the last // paragraph in a section. To get it right, we have to switch to the next // paragraph, and detect the section breaks there. SwNodeIndex aNextIndex( rNode, 1 ); if ( aNextIndex.GetNode().IsTxtNode() ) { const SwTxtNode* pTxtNode = static_cast< SwTxtNode* >( &aNextIndex.GetNode() ); m_rExport.OutputSectionBreaks( pTxtNode->GetpSwAttrSet(), *pTxtNode ); } else if ( aNextIndex.GetNode().IsTableNode() ) { const SwTableNode* pTableNode = static_cast< SwTableNode* >( &aNextIndex.GetNode() ); const SwFrmFmt *pFmt = pTableNode->GetTable().GetFrmFmt(); m_rExport.OutputSectionBreaks( &(pFmt->GetAttrSet()), *pTableNode ); } // postpone the output so that we can later [in EndParagraphProperties()] // prepend the properties before the run m_pSerializer->mark(); m_pSerializer->startElementNS( XML_w, XML_pPr, FSEND ); // and output the section break now (if it appeared) if ( m_pSectionInfo ) { m_rExport.SectionProperties( *m_pSectionInfo ); m_pSectionInfo = NULL; } InitCollectedParagraphProperties(); } void DocxAttributeOutput::InitCollectedParagraphProperties() { m_pSpacingAttrList = NULL; } void DocxAttributeOutput::WriteCollectedParagraphProperties() { if ( m_pSpacingAttrList ) { XFastAttributeListRef xAttrList( m_pSpacingAttrList ); m_pSpacingAttrList = NULL; m_pSerializer->singleElementNS( XML_w, XML_spacing, xAttrList ); } } void DocxAttributeOutput::EndParagraphProperties() { WriteCollectedParagraphProperties(); m_pSerializer->endElementNS( XML_w, XML_pPr ); if ( m_nColBreakStatus == COLBRK_WRITE ) { m_pSerializer->startElementNS( XML_w, XML_r, FSEND ); m_pSerializer->singleElementNS( XML_w, XML_br, FSNS( XML_w, XML_type ), "column", FSEND ); m_pSerializer->endElementNS( XML_w, XML_r ); m_nColBreakStatus = COLBRK_NONE; } // merge the properties _before_ the run (strictly speaking, just // after the start of the paragraph) m_pSerializer->mergeTopMarks( sax_fastparser::MERGE_MARKS_PREPEND ); } void DocxAttributeOutput::StartRun( const SwRedlineData* pRedlineData ) { // if there is some redlining in the document, output it StartRedline( pRedlineData ); // postpone the output of the start of a run (there are elements that need // to be written before the start of the run, but we learn which they are // _inside_ of the run) m_pSerializer->mark(); // let's call it "postponed run start" // postpone the output of the text (we get it before the run properties, // but must write it after them) m_pSerializer->mark(); // let's call it "postponed text" } void DocxAttributeOutput::EndRun() { // Write field starts for ( std::vector<FieldInfos>::iterator pIt = m_Fields.begin(); pIt != m_Fields.end(); ++pIt ) { // Add the fields starts for all but hyperlinks and TOCs if ( pIt->bOpen && pIt->pField ) { StartField_Impl( *pIt ); // Remove the field from the stack if only the start has to be written // Unknown fields sould be removed too if ( !pIt->bClose || ( pIt->eType == ww::eUNKNOWN ) ) { m_Fields.erase( pIt ); --pIt; } } } // write the run properties + the text, already in the correct order m_pSerializer->mergeTopMarks(); // merges with "postponed text", see above // level down, to be able to prepend the actual run start attribute (just // before "postponed run start") m_pSerializer->mark(); // let's call it "actual run start" // prepend the actual run start if ( m_pHyperlinkAttrList ) { XFastAttributeListRef xAttrList ( m_pHyperlinkAttrList ); m_pSerializer->startElementNS( XML_w, XML_hyperlink, xAttrList ); } // Write the hyperlink and toc fields starts for ( std::vector<FieldInfos>::iterator pIt = m_Fields.begin(); pIt != m_Fields.end(); ++pIt ) { // Add the fields starts for hyperlinks, TOCs and index marks if ( pIt->bOpen ) { StartField_Impl( *pIt, sal_True ); // Remove the field if no end needs to be written if ( !pIt->bClose ) { m_Fields.erase( pIt ); --pIt; } } } DoWriteBookmarks( ); WriteCommentRanges(); m_pSerializer->startElementNS( XML_w, XML_r, FSEND ); m_pSerializer->mergeTopMarks( sax_fastparser::MERGE_MARKS_PREPEND ); // merges with "postponed run start", see above // write the run start + the run content m_pSerializer->mergeTopMarks(); // merges the "actual run start" // append the actual run end m_pSerializer->endElementNS( XML_w, XML_r ); if ( m_pHyperlinkAttrList ) { m_pSerializer->endElementNS( XML_w, XML_hyperlink ); m_pHyperlinkAttrList = NULL; } while ( m_Fields.begin() != m_Fields.end() ) { EndField_Impl( m_Fields.front( ) ); m_Fields.erase( m_Fields.begin( ) ); } // if there is some redlining in the document, output it EndRedline(); } void DocxAttributeOutput::WriteCommentRanges() { if (m_bPostitStart) { m_bPostitStart = false; OString idstr = OString::valueOf( sal_Int32( m_postitFieldsMaxId )); m_pSerializer->singleElementNS( XML_w, XML_commentRangeStart, FSNS( XML_w, XML_id ), idstr.getStr(), FSEND ); } if (m_bPostitEnd) { m_bPostitEnd = false; OString idstr = OString::valueOf( sal_Int32( m_postitFieldsMaxId )); m_pSerializer->singleElementNS( XML_w, XML_commentRangeEnd, FSNS( XML_w, XML_id ), idstr.getStr(), FSEND ); } } void DocxAttributeOutput::WritePostitFieldStart() { m_bPostitStart = true; } void DocxAttributeOutput::WritePostitFieldEnd() { m_bPostitEnd = true; } void DocxAttributeOutput::DoWriteBookmarks() { // Write the start bookmarks for ( std::vector< OString >::const_iterator it = m_rMarksStart.begin(), end = m_rMarksStart.end(); it < end; ++it ) { const OString& rName = *it; // Output the bookmark sal_uInt16 nId = m_nNextMarkId++; m_rOpenedMarksIds[rName] = nId; m_pSerializer->singleElementNS( XML_w, XML_bookmarkStart, FSNS( XML_w, XML_id ), OString::valueOf( sal_Int32( nId ) ).getStr( ), FSNS( XML_w, XML_name ), rName.getStr(), FSEND ); } m_rMarksStart.clear(); // export the end bookmarks for ( std::vector< OString >::const_iterator it = m_rMarksEnd.begin(), end = m_rMarksEnd.end(); it < end; ++it ) { const OString& rName = *it; // Get the id of the bookmark std::map< OString, sal_uInt16 >::iterator pPos = m_rOpenedMarksIds.find( rName ); if ( pPos != m_rOpenedMarksIds.end( ) ) { sal_uInt16 nId = ( *pPos ).second; m_pSerializer->singleElementNS( XML_w, XML_bookmarkEnd, FSNS( XML_w, XML_id ), OString::valueOf( sal_Int32( nId ) ).getStr( ), FSEND ); m_rOpenedMarksIds.erase( rName ); } } m_rMarksEnd.clear(); } void DocxAttributeOutput::StartField_Impl( FieldInfos& rInfos, sal_Bool bWriteRun ) { if ( rInfos.pField && rInfos.eType == ww::eUNKNOWN ) { // Expand unsupported fields RunText( rInfos.pField->Expand( ) ); } else if ( rInfos.eType != ww::eNONE ) // HYPERLINK fields are just commands { if ( bWriteRun ) m_pSerializer->startElementNS( XML_w, XML_r, FSEND ); if ( rInfos.eType == ww::eFORMDROPDOWN ) { m_pSerializer->startElementNS( XML_w, XML_fldChar, FSNS( XML_w, XML_fldCharType ), "begin", FSEND ); const SwDropDownField& rFld2 = *(SwDropDownField*)rInfos.pField; uno::Sequence<rtl::OUString> aItems = rFld2.GetItemSequence(); GetExport().DoComboBox(rFld2.GetName(), rFld2.GetHelp(), rFld2.GetToolTip(), rFld2.GetSelectedItem(), aItems); m_pSerializer->endElementNS( XML_w, XML_fldChar ); if ( bWriteRun ) m_pSerializer->endElementNS( XML_w, XML_r ); } else { // Write the field start m_pSerializer->singleElementNS( XML_w, XML_fldChar, FSNS( XML_w, XML_fldCharType ), "begin", FSEND ); if ( bWriteRun ) m_pSerializer->endElementNS( XML_w, XML_r ); // The hyperlinks fields can't be expanded: the value is // normally in the text run if ( !rInfos.pField ) CmdField_Impl( rInfos ); } } } void DocxAttributeOutput::DoWriteCmd( String& rCmd ) { // Write the Field command m_pSerializer->startElementNS( XML_w, XML_instrText, FSEND ); m_pSerializer->writeEscaped( OUString( rCmd ) ); m_pSerializer->endElementNS( XML_w, XML_instrText ); } void DocxAttributeOutput::CmdField_Impl( FieldInfos& rInfos ) { m_pSerializer->startElementNS( XML_w, XML_r, FSEND ); xub_StrLen nNbToken = rInfos.sCmd.GetTokenCount( '\t' ); for ( xub_StrLen i = 0; i < nNbToken; i++ ) { String sToken = rInfos.sCmd.GetToken( i, '\t' ); // Write the Field command DoWriteCmd( sToken ); // Replace tabs by </instrText><tab/><instrText> if ( i < ( nNbToken - 1 ) ) RunText( String::CreateFromAscii( "\t" ) ); } m_pSerializer->endElementNS( XML_w, XML_r ); // Write the Field separator m_pSerializer->startElementNS( XML_w, XML_r, FSEND ); m_pSerializer->singleElementNS( XML_w, XML_fldChar, FSNS( XML_w, XML_fldCharType ), "separate", FSEND ); m_pSerializer->endElementNS( XML_w, XML_r ); } void DocxAttributeOutput::EndField_Impl( FieldInfos& rInfos ) { // The command has to be written before for the hyperlinks if ( rInfos.pField ) { CmdField_Impl( rInfos ); } // Write the bookmark start if any OUString aBkmName( m_sFieldBkm ); if ( aBkmName.getLength( ) > 0 ) { m_pSerializer->singleElementNS( XML_w, XML_bookmarkStart, FSNS( XML_w, XML_id ), OString::valueOf( sal_Int32( m_nNextMarkId ) ).getStr( ), FSNS( XML_w, XML_name ), OUStringToOString( aBkmName, RTL_TEXTENCODING_UTF8 ).getStr( ), FSEND ); } if (rInfos.pField ) // For hyperlinks and TOX { // Write the Field latest value m_pSerializer->startElementNS( XML_w, XML_r, FSEND ); // Find another way for hyperlinks RunText( rInfos.pField->Expand( ) ); m_pSerializer->endElementNS( XML_w, XML_r ); } // Write the bookmark end if any if ( aBkmName.getLength( ) > 0 ) { m_pSerializer->singleElementNS( XML_w, XML_bookmarkEnd, FSNS( XML_w, XML_id ), OString::valueOf( sal_Int32( m_nNextMarkId ) ).getStr( ), FSEND ); m_nNextMarkId++; } // Write the Field end m_pSerializer->startElementNS( XML_w, XML_r, FSEND ); m_pSerializer->singleElementNS( XML_w, XML_fldChar, FSNS( XML_w, XML_fldCharType ), "end", FSEND ); m_pSerializer->endElementNS( XML_w, XML_r ); // Write the ref field if a bookmark had to be set and the field // should be visible if ( rInfos.pField ) { sal_uInt16 nSubType = rInfos.pField->GetSubType( ); bool bIsSetField = rInfos.pField->GetTyp( )->Which( ) == RES_SETEXPFLD; bool bShowRef = ( !bIsSetField || ( nSubType & nsSwExtendedSubType::SUB_INVISIBLE ) ) ? false : true; if ( ( m_sFieldBkm.Len( ) > 0 ) && bShowRef ) { // Write the field beginning m_pSerializer->startElementNS( XML_w, XML_r, FSEND ); m_pSerializer->singleElementNS( XML_w, XML_fldChar, FSNS( XML_w, XML_fldCharType ), "begin", FSEND ); m_pSerializer->endElementNS( XML_w, XML_r ); rInfos.sCmd = FieldString( ww::eREF ); rInfos.sCmd.APPEND_CONST_ASC( "\"" ); rInfos.sCmd += m_sFieldBkm; rInfos.sCmd.APPEND_CONST_ASC( "\" " ); // Clean the field bookmark data to avoid infinite loop m_sFieldBkm = String( ); // Write the end of the field EndField_Impl( rInfos ); } } } void DocxAttributeOutput::StartRunProperties() { // postpone the output so that we can later [in EndRunProperties()] // prepend the properties before the text m_pSerializer->mark(); m_pSerializer->startElementNS( XML_w, XML_rPr, FSEND ); InitCollectedRunProperties(); } void DocxAttributeOutput::InitCollectedRunProperties() { m_pFontsAttrList = NULL; m_pEastAsianLayoutAttrList = NULL; m_pCharLangAttrList = NULL; } void DocxAttributeOutput::WriteCollectedRunProperties() { // Write all differed properties if ( m_pFontsAttrList ) { XFastAttributeListRef xAttrList( m_pFontsAttrList ); m_pFontsAttrList = NULL; m_pSerializer->singleElementNS( XML_w, XML_rFonts, xAttrList ); } if ( m_pEastAsianLayoutAttrList ) { XFastAttributeListRef xAttrList( m_pEastAsianLayoutAttrList ); m_pEastAsianLayoutAttrList = NULL; m_pSerializer->singleElementNS( XML_w, XML_eastAsianLayout, xAttrList ); } if ( m_pCharLangAttrList ) { XFastAttributeListRef xAttrList( m_pCharLangAttrList ); m_pCharLangAttrList = NULL; m_pSerializer->singleElementNS( XML_w, XML_lang, xAttrList ); } } void DocxAttributeOutput::EndRunProperties( const SwRedlineData* /*pRedlineData*/ ) { WriteCollectedRunProperties(); m_pSerializer->endElementNS( XML_w, XML_rPr ); // write footnotes/endnotes if we have any FootnoteEndnoteReference(); // merge the properties _before_ the run text (strictly speaking, just // after the start of the run) m_pSerializer->mergeTopMarks( sax_fastparser::MERGE_MARKS_PREPEND ); } /** Output sal_Unicode* as a run text (<t>the text</t>). When bMove is true, update rBegin to point _after_ the end of the text + 1, meaning that it skips one character after the text. This is to make the switch in DocxAttributeOutput::RunText() nicer ;-) */ static void impl_WriteRunText( FSHelperPtr pSerializer, sal_Int32 nTextToken, const sal_Unicode* &rBegin, const sal_Unicode* pEnd, bool bMove = true ) { const sal_Unicode *pBegin = rBegin; // skip one character after the end if ( bMove ) rBegin = pEnd + 1; if ( pBegin >= pEnd ) return; // we want to write at least one character // we have to add 'preserve' when starting/ending with space if ( *pBegin == sal_Unicode( ' ' ) || *( pEnd - 1 ) == sal_Unicode( ' ' ) ) { pSerializer->startElementNS( XML_w, nTextToken, FSNS( XML_xml, XML_space ), "preserve", FSEND ); } else pSerializer->startElementNS( XML_w, nTextToken, FSEND ); pSerializer->writeEscaped( OUString( pBegin, pEnd - pBegin ) ); pSerializer->endElementNS( XML_w, nTextToken ); } void DocxAttributeOutput::RunText( const String& rText, rtl_TextEncoding /*eCharSet*/ ) { OUString aText( rText ); // one text can be split into more <w:t>blah</w:t>'s by line breaks etc. const sal_Unicode *pBegin = aText.getStr(); const sal_Unicode *pEnd = pBegin + aText.getLength(); // the text run is usually XML_t, with the exception of the deleted text sal_Int32 nTextToken = XML_t; if ( m_pRedlineData && m_pRedlineData->GetType() == nsRedlineType_t::REDLINE_DELETE ) nTextToken = XML_delText; for ( const sal_Unicode *pIt = pBegin; pIt < pEnd; ++pIt ) { switch ( *pIt ) { case 0x09: // tab impl_WriteRunText( m_pSerializer, nTextToken, pBegin, pIt ); m_pSerializer->singleElementNS( XML_w, XML_tab, FSEND ); break; case 0x0b: // line break impl_WriteRunText( m_pSerializer, nTextToken, pBegin, pIt ); m_pSerializer->singleElementNS( XML_w, XML_br, FSEND ); break; default: if ( *pIt < 0x0020 ) // filter out the control codes { impl_WriteRunText( m_pSerializer, nTextToken, pBegin, pIt ); OSL_TRACE( "Ignored control code %x in a text run.", *pIt ); } break; } } impl_WriteRunText( m_pSerializer, nTextToken, pBegin, pEnd, false ); } void DocxAttributeOutput::RawText( const String& /*rText*/, bool /*bForceUnicode*/, rtl_TextEncoding /*eCharSet*/ ) { OSL_TRACE("TODO DocxAttributeOutput::RawText( const String& rText, bool bForceUnicode, rtl_TextEncoding eCharSet )\n" ); } void DocxAttributeOutput::StartRuby( const SwTxtNode& /*rNode*/, const SwFmtRuby& /*rRuby*/ ) { OSL_TRACE("TODO DocxAttributeOutput::StartRuby( const SwTxtNode& rNode, const SwFmtRuby& rRuby )\n" ); } void DocxAttributeOutput::EndRuby() { OSL_TRACE( "TODO DocxAttributeOutput::EndRuby()\n" ); } bool DocxAttributeOutput::AnalyzeURL( const String& rUrl, const String& rTarget, String* pLinkURL, String* pMark ) { bool bBookMarkOnly = AttributeOutputBase::AnalyzeURL( rUrl, rTarget, pLinkURL, pMark ); String sURL = *pLinkURL; String sMark = *pMark; bool bOutputField = sMark.Len(); if ( bOutputField ) { if ( bBookMarkOnly ) sURL = FieldString( ww::eHYPERLINK ); else { String sFld( FieldString( ww::eHYPERLINK ) ); sFld.APPEND_CONST_ASC( "\"" ); sURL.Insert( sFld, 0 ); sURL += '\"'; } if ( sMark.Len() ) ( ( sURL.APPEND_CONST_ASC( " \\l \"" ) ) += sMark ) += '\"'; if ( rTarget.Len() ) ( sURL.APPEND_CONST_ASC( " \\n " ) ) += rTarget; } *pLinkURL = sURL; *pMark = sMark; return bBookMarkOnly; } bool DocxAttributeOutput::StartURL( const String& rUrl, const String& rTarget ) { String sMark; String sUrl; bool bBookmarkOnly = AnalyzeURL( rUrl, rTarget, &sUrl, &sMark ); if ( sMark.Len() && !bBookmarkOnly ) { m_rExport.OutputField( NULL, ww::eHYPERLINK, sUrl ); } else { // Output a hyperlink XML element m_pHyperlinkAttrList = m_pSerializer->createAttrList(); if ( !bBookmarkOnly ) { OUString osUrl( sUrl ); ::rtl::OString sId = m_rExport.AddRelation( S( "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" ), osUrl, S("External") ); m_pHyperlinkAttrList->add( FSNS( XML_r, XML_id), sId.getStr()); } else m_pHyperlinkAttrList->add( FSNS( XML_w, XML_anchor ), OUStringToOString( OUString( sMark ), RTL_TEXTENCODING_UTF8 ).getStr( ) ); OUString sTarget( rTarget ); if ( sTarget.getLength( ) > 0 ) { OString soTarget = OUStringToOString( sTarget, RTL_TEXTENCODING_UTF8 ); m_pHyperlinkAttrList->add(FSNS( XML_w, XML_tgtFrame ), soTarget.getStr()); } } return true; } bool DocxAttributeOutput::EndURL() { return true; } void DocxAttributeOutput::FieldVanish( const String& rTxt, ww::eField eType ) { WriteField_Impl( NULL, eType, rTxt, WRITEFIELD_ALL ); } void DocxAttributeOutput::Redline( const SwRedlineData* /*pRedline*/ ) { OSL_TRACE( "TODO DocxAttributeOutput::Redline( const SwRedlineData* pRedline )\n" ); } /// Append the number as 2-digit when less than 10. static void impl_AppendTwoDigits( OStringBuffer &rBuffer, sal_Int32 nNum ) { if ( nNum < 0 || nNum > 99 ) { rBuffer.append( "00" ); return; } if ( nNum < 10 ) rBuffer.append( '0' ); rBuffer.append( nNum ); } /** Convert DateTime to xsd::dateTime string. I guess there must be an implementation of this somewhere in OOo, but I failed to find it, unfortunately :-( */ static OString impl_DateTimeToOString( const DateTime& rDateTime ) { DateTime aInUTC( rDateTime ); aInUTC.ConvertToUTC(); OStringBuffer aBuffer( 25 ); aBuffer.append( sal_Int32( aInUTC.GetYear() ) ); aBuffer.append( '-' ); impl_AppendTwoDigits( aBuffer, aInUTC.GetMonth() ); aBuffer.append( '-' ); impl_AppendTwoDigits( aBuffer, aInUTC.GetDay() ); aBuffer.append( 'T' ); impl_AppendTwoDigits( aBuffer, aInUTC.GetHour() ); aBuffer.append( ':' ); impl_AppendTwoDigits( aBuffer, aInUTC.GetMin() ); aBuffer.append( ':' ); impl_AppendTwoDigits( aBuffer, aInUTC.GetSec() ); aBuffer.append( 'Z' ); // we are in UTC return aBuffer.makeStringAndClear(); } void DocxAttributeOutput::StartRedline( const SwRedlineData* pRedlineData ) { m_pRedlineData = pRedlineData; if ( !m_pRedlineData ) return; // FIXME check if it's necessary to travel over the Next()'s in pRedlineData OString aId( OString::valueOf( m_nRedlineId++ ) ); const String &rAuthor( SW_MOD()->GetRedlineAuthor( pRedlineData->GetAuthor() ) ); OString aAuthor( OUStringToOString( rAuthor, RTL_TEXTENCODING_UTF8 ) ); OString aDate( impl_DateTimeToOString( pRedlineData->GetTimeStamp() ) ); switch ( pRedlineData->GetType() ) { case nsRedlineType_t::REDLINE_INSERT: m_pSerializer->startElementNS( XML_w, XML_ins, FSNS( XML_w, XML_id ), aId.getStr(), FSNS( XML_w, XML_author ), aAuthor.getStr(), FSNS( XML_w, XML_date ), aDate.getStr(), FSEND ); break; case nsRedlineType_t::REDLINE_DELETE: m_pSerializer->startElementNS( XML_w, XML_del, FSNS( XML_w, XML_id ), aId.getStr(), FSNS( XML_w, XML_author ), aAuthor.getStr(), FSNS( XML_w, XML_date ), aDate.getStr(), FSEND ); break; case nsRedlineType_t::REDLINE_FORMAT: OSL_TRACE( "TODO DocxAttributeOutput::StartRedline()\n" ); default: break; } } void DocxAttributeOutput::EndRedline() { if ( !m_pRedlineData ) return; switch ( m_pRedlineData->GetType() ) { case nsRedlineType_t::REDLINE_INSERT: m_pSerializer->endElementNS( XML_w, XML_ins ); break; case nsRedlineType_t::REDLINE_DELETE: m_pSerializer->endElementNS( XML_w, XML_del ); break; case nsRedlineType_t::REDLINE_FORMAT: OSL_TRACE( "TODO DocxAttributeOutput::EndRedline()\n" ); break; default: break; } m_pRedlineData = NULL; } void DocxAttributeOutput::FormatDrop( const SwTxtNode& /*rNode*/, const SwFmtDrop& /*rSwFmtDrop*/, sal_uInt16 /*nStyle*/, ww8::WW8TableNodeInfo::Pointer_t /*pTextNodeInfo*/, ww8::WW8TableNodeInfoInner::Pointer_t ) { OSL_TRACE( "TODO DocxAttributeOutput::FormatDrop( const SwTxtNode& rNode, const SwFmtDrop& rSwFmtDrop, sal_uInt16 nStyle )\n" ); } void DocxAttributeOutput::ParagraphStyle( sal_uInt16 nStyle ) { OString aStyleId( "style" ); aStyleId += OString::valueOf( sal_Int32( nStyle ) ); m_pSerializer->singleElementNS( XML_w, XML_pStyle, FSNS( XML_w, XML_val ), aStyleId.getStr(), FSEND ); } #if 0 void DocxAttributeOutput::InTable() { #if OSL_DEBUG_LEVEL > 0 OSL_TRACE( "TODO DocxAttributeOutput::InTable()\n" ); #endif } void DocxAttributeOutput::TableRowProperties( bool /*bHeader*/, long /*nCellHeight*/, bool /*bCannotSplit*/, bool /*bRightToLeft*/ ) { #if OSL_DEBUG_LEVEL > 0 OSL_TRACE( "TODO DocxAttributeOutput::TableRowProperties()\n" ); #endif } #endif static OString impl_ConvertColor( const Color &rColor ) { OString color( "auto" ); if ( rColor.GetColor() != COL_AUTO ) { const char pHexDigits[] = "0123456789ABCDEF"; char pBuffer[] = "000000"; pBuffer[0] = pHexDigits[ ( rColor.GetRed() >> 4 ) & 0x0F ]; pBuffer[1] = pHexDigits[ rColor.GetRed() & 0x0F ]; pBuffer[2] = pHexDigits[ ( rColor.GetGreen() >> 4 ) & 0x0F ]; pBuffer[3] = pHexDigits[ rColor.GetGreen() & 0x0F ]; pBuffer[4] = pHexDigits[ ( rColor.GetBlue() >> 4 ) & 0x0F ]; pBuffer[5] = pHexDigits[ rColor.GetBlue() & 0x0F ]; color = OString( pBuffer ); } return color; } static void impl_borderLine( FSHelperPtr pSerializer, sal_Int32 elementToken, const SvxBorderLine* pBorderLine, sal_uInt16 nDist ) { FastAttributeList* pAttr = pSerializer->createAttrList(); sal_uInt16 inW = pBorderLine->GetInWidth(); sal_uInt16 outW = pBorderLine->GetOutWidth(); sal_uInt16 nWidth = inW + outW; // Compute val attribute value // Can be one of: // single, double, // basicWideOutline, basicWideInline // OOXml also supports those types of borders, but we'll try to play with the first ones. // thickThinMediumGap, thickThinLargeGap, thickThinSmallGap // thinThickLargeGap, thinThickMediumGap, thinThickSmallGap const char* pVal = "single"; if ( pBorderLine->isDouble() ) { if ( inW == outW ) pVal = ( sal_Char* )"double"; else if ( inW > outW ) { pVal = ( sal_Char* )"thinThickMediumGap"; } else if ( inW < outW ) { pVal = ( sal_Char* )"thickThinMediumGap"; } } pAttr->add( FSNS( XML_w, XML_val ), OString( pVal ) ); // Compute the sz attribute // The unit is the 8th of point nWidth = sal_Int32( nWidth / 2.5 ); sal_uInt16 nMinWidth = 2; sal_uInt16 nMaxWidth = 96; if ( nWidth > nMaxWidth ) nWidth = nMaxWidth; else if ( nWidth < nMinWidth ) nWidth = nMinWidth; pAttr->add( FSNS( XML_w, XML_sz ), OString::valueOf( sal_Int32( nWidth ) ) ); // Get the distance (in pt) pAttr->add( FSNS( XML_w, XML_space ), OString::valueOf( sal_Int32( nDist / 20 ) ) ); // Get the color code as an RRGGBB hex value OString sColor( impl_ConvertColor( pBorderLine->GetColor( ) ) ); pAttr->add( FSNS( XML_w, XML_color ), sColor ); XFastAttributeListRef xAttrs( pAttr ); pSerializer->singleElementNS( XML_w, elementToken, xAttrs ); } static void impl_pageBorders( FSHelperPtr pSerializer, const SvxBoxItem& rBox ) { static const sal_uInt16 aBorders[] = { BOX_LINE_TOP, BOX_LINE_LEFT, BOX_LINE_BOTTOM, BOX_LINE_RIGHT }; static const sal_uInt16 aXmlElements[] = { XML_top, XML_left, XML_bottom, XML_right }; const sal_uInt16* pBrd = aBorders; for( int i = 0; i < 4; ++i, ++pBrd ) { const SvxBorderLine* pLn = rBox.GetLine( *pBrd ); if ( pLn ) impl_borderLine( pSerializer, aXmlElements[i], pLn, 0 ); } } void DocxAttributeOutput::TableCellProperties( ww8::WW8TableNodeInfoInner::Pointer_t pTableTextNodeInfoInner ) { m_pSerializer->startElementNS( XML_w, XML_tcPr, FSEND ); const SwTableBox *pTblBox = pTableTextNodeInfoInner->getTableBox( ); // The cell borders m_pSerializer->startElementNS( XML_w, XML_tcBorders, FSEND ); SwFrmFmt *pFmt = pTblBox->GetFrmFmt( ); impl_pageBorders( m_pSerializer, pFmt->GetBox( ) ); m_pSerializer->endElementNS( XML_w, XML_tcBorders ); // Vertical merges long vSpan = pTblBox->getRowSpan( ); if ( vSpan > 1 ) { m_pSerializer->singleElementNS( XML_w, XML_vMerge, FSNS( XML_w, XML_val ), "restart", FSEND ); } else if ( vSpan < 0 ) { m_pSerializer->singleElementNS( XML_w, XML_vMerge, FSNS( XML_w, XML_val ), "continue", FSEND ); } // Horizontal spans const SwWriteTableRows& aRows = m_pTableWrt->GetRows( ); SwWriteTableRow *pRow = aRows[ pTableTextNodeInfoInner->getRow( ) ]; SwWriteTableCell *pCell = pRow->GetCells( )[ pTableTextNodeInfoInner->getCell( ) ]; sal_uInt16 nColSpan = pCell->GetColSpan(); if ( nColSpan > 1 ) m_pSerializer->singleElementNS( XML_w, XML_gridSpan, FSNS( XML_w, XML_val ), OString::valueOf( sal_Int32( nColSpan ) ).getStr(), FSEND ); TableBackgrounds( pTableTextNodeInfoInner ); // Cell preferred width SwTwips nWidth = GetGridCols( pTableTextNodeInfoInner )[ pTableTextNodeInfoInner->getCell() ]; m_pSerializer->singleElementNS( XML_w, XML_tcW, FSNS( XML_w, XML_w ), OString::valueOf( sal_Int32( nWidth ) ).getStr( ), FSNS( XML_w, XML_type ), "dxa", FSEND ); // Cell margins m_pSerializer->startElementNS( XML_w, XML_tcMar, FSEND ); const SvxBoxItem& rBox = pFmt->GetBox( ); static const sal_uInt16 aBorders[] = { BOX_LINE_TOP, BOX_LINE_LEFT, BOX_LINE_BOTTOM, BOX_LINE_RIGHT }; static const sal_uInt16 aXmlElements[] = { XML_top, XML_left, XML_bottom, XML_right }; const sal_uInt16* pBrd = aBorders; for( int i = 0; i < 4; ++i, ++pBrd ) { sal_Int32 nDist = sal_Int32( rBox.GetDistance( *pBrd ) ); m_pSerializer->singleElementNS( XML_w, aXmlElements[i], FSNS( XML_w, XML_w ), OString::valueOf( nDist ).getStr( ), FSNS( XML_w, XML_type ), "dxa", FSEND ); } m_pSerializer->endElementNS( XML_w, XML_tcMar ); TableVerticalCell( pTableTextNodeInfoInner ); m_pSerializer->endElementNS( XML_w, XML_tcPr ); } void DocxAttributeOutput::InitTableHelper( ww8::WW8TableNodeInfoInner::Pointer_t pTableTextNodeInfoInner ) { sal_uInt32 nPageSize = 0; bool bRelBoxSize = false; // Create the SwWriteTable instance to use col spans (and maybe other infos) GetTablePageSize( pTableTextNodeInfoInner, nPageSize, bRelBoxSize ); const SwTable* pTable = pTableTextNodeInfoInner->getTable( ); const SwFrmFmt *pFmt = pTable->GetFrmFmt( ); SwTwips nTblSz = pFmt->GetFrmSize( ).GetWidth( ); const SwHTMLTableLayout *pLayout = pTable->GetHTMLTableLayout(); if( pLayout && pLayout->IsExportable() ) m_pTableWrt = new SwWriteTable( pLayout ); else m_pTableWrt = new SwWriteTable( pTable->GetTabLines(), (sal_uInt16)nPageSize, (sal_uInt16)nTblSz, false); } void DocxAttributeOutput::StartTable( ww8::WW8TableNodeInfoInner::Pointer_t pTableTextNodeInfoInner ) { m_pSerializer->startElementNS( XML_w, XML_tbl, FSEND ); InitTableHelper( pTableTextNodeInfoInner ); TableDefinition( pTableTextNodeInfoInner ); } void DocxAttributeOutput::EndTable() { m_pSerializer->endElementNS( XML_w, XML_tbl ); if ( m_nTableDepth > 0 ) --m_nTableDepth; // We closed the table; if it is a nested table, the cell that contains it // still continues m_bTableCellOpen = true; // Cleans the table helper delete m_pTableWrt, m_pTableWrt = NULL; } void DocxAttributeOutput::StartTableRow( ww8::WW8TableNodeInfoInner::Pointer_t pTableTextNodeInfoInner ) { m_pSerializer->startElementNS( XML_w, XML_tr, FSEND ); // Output the row properties m_pSerializer->startElementNS( XML_w, XML_trPr, FSEND ); // Header row: tblHeader const SwTable *pTable = pTableTextNodeInfoInner->getTable( ); if ( pTable->GetRowsToRepeat( ) > pTableTextNodeInfoInner->getRow( ) ) m_pSerializer->singleElementNS( XML_w, XML_tblHeader, FSNS( XML_w, XML_val ), "true", FSEND ); TableHeight( pTableTextNodeInfoInner ); TableCanSplit( pTableTextNodeInfoInner ); m_pSerializer->endElementNS( XML_w, XML_trPr ); } void DocxAttributeOutput::EndTableRow( ) { m_pSerializer->endElementNS( XML_w, XML_tr ); } void DocxAttributeOutput::StartTableCell( ww8::WW8TableNodeInfoInner::Pointer_t pTableTextNodeInfoInner ) { if ( !m_pTableWrt ) InitTableHelper( pTableTextNodeInfoInner ); m_pSerializer->startElementNS( XML_w, XML_tc, FSEND ); // Write the cell properties here TableCellProperties( pTableTextNodeInfoInner ); m_bTableCellOpen = true; } void DocxAttributeOutput::EndTableCell( ) { m_pSerializer->endElementNS( XML_w, XML_tc ); m_bTableCellOpen = false; } void DocxAttributeOutput::TableInfoCell( ww8::WW8TableNodeInfoInner::Pointer_t /*pTableTextNodeInfoInner*/ ) { } void DocxAttributeOutput::TableInfoRow( ww8::WW8TableNodeInfoInner::Pointer_t /*pTableTextNodeInfo*/ ) { } void DocxAttributeOutput::TableDefinition( ww8::WW8TableNodeInfoInner::Pointer_t pTableTextNodeInfoInner ) { // Write the table properties m_pSerializer->startElementNS( XML_w, XML_tblPr, FSEND ); sal_uInt32 nPageSize = 0; bool bRelBoxSize = false; // Create the SwWriteTable instance to use col spans (and maybe other infos) GetTablePageSize( pTableTextNodeInfoInner, nPageSize, bRelBoxSize ); // Output the table preferred width if ( nPageSize != 0 ) m_pSerializer->singleElementNS( XML_w, XML_tblW, FSNS( XML_w, XML_w ), OString::valueOf( sal_Int32( nPageSize ) ).getStr( ), FSNS( XML_w, XML_type ), "dxa", FSEND ); // Output the table borders TableDefaultBorders( pTableTextNodeInfoInner ); TableBidi( pTableTextNodeInfoInner ); // Output the table alignement const SwTable *pTable = pTableTextNodeInfoInner->getTable(); SwFrmFmt *pTblFmt = pTable->GetFrmFmt( ); const char* pJcVal; sal_Int32 nIndent = 0; switch ( pTblFmt->GetHoriOrient( ).GetHoriOrient( ) ) { case text::HoriOrientation::CENTER: pJcVal = "center"; break; case text::HoriOrientation::RIGHT: pJcVal = "right"; break; default: case text::HoriOrientation::NONE: case text::HoriOrientation::LEFT_AND_WIDTH: { pJcVal = "left"; nIndent = sal_Int32( pTblFmt->GetLRSpace( ).GetLeft( ) ); break; } } m_pSerializer->singleElementNS( XML_w, XML_jc, FSNS( XML_w, XML_val ), pJcVal, FSEND ); // Table indent if ( nIndent != 0 ) m_pSerializer->singleElementNS( XML_w, XML_tblInd, FSNS( XML_w, XML_w ), OString::valueOf( nIndent ).getStr( ), FSNS( XML_w, XML_type ), "dxa", FSEND ); m_pSerializer->endElementNS( XML_w, XML_tblPr ); // Write the table grid infos m_pSerializer->startElementNS( XML_w, XML_tblGrid, FSEND ); std::vector<SwTwips> gridCols = GetGridCols( pTableTextNodeInfoInner ); for ( std::vector<SwTwips>::const_iterator it = gridCols.begin(); it != gridCols.end(); ++it ) m_pSerializer->singleElementNS( XML_w, XML_gridCol, FSNS( XML_w, XML_w ), OString::valueOf( sal_Int32( *it ) ).getStr( ), FSEND ); m_pSerializer->endElementNS( XML_w, XML_tblGrid ); } void DocxAttributeOutput::TableDefaultBorders( ww8::WW8TableNodeInfoInner::Pointer_t pTableTextNodeInfoInner ) { const SwTableBox * pTabBox = pTableTextNodeInfoInner->getTableBox(); const SwFrmFmt * pFrmFmt = pTabBox->GetFrmFmt(); // the defaults of the table are taken from the top-left cell m_pSerializer->startElementNS( XML_w, XML_tblBorders, FSEND ); impl_pageBorders( m_pSerializer, pFrmFmt->GetBox( ) ); m_pSerializer->endElementNS( XML_w, XML_tblBorders ); } void DocxAttributeOutput::TableBackgrounds( ww8::WW8TableNodeInfoInner::Pointer_t pTableTextNodeInfoInner ) { const SwTableBox *pTblBox = pTableTextNodeInfoInner->getTableBox( ); const SwFrmFmt *pFmt = pTblBox->GetFrmFmt( ); const SfxPoolItem *pI = NULL; Color aColor; if ( SFX_ITEM_ON == pFmt->GetAttrSet().GetItemState( RES_BACKGROUND, false, &pI ) ) aColor = dynamic_cast<const SvxBrushItem *>(pI)->GetColor(); else aColor = COL_AUTO; OString sColor = impl_ConvertColor( aColor ); m_pSerializer->singleElementNS( XML_w, XML_shd, FSNS( XML_w, XML_fill ), sColor.getStr( ), FSEND ); } void DocxAttributeOutput::TableHeight( ww8::WW8TableNodeInfoInner::Pointer_t pTableTextNodeInfoInner ) { const SwTableBox * pTabBox = pTableTextNodeInfoInner->getTableBox(); const SwTableLine * pTabLine = pTabBox->GetUpper(); const SwFrmFmt * pLineFmt = pTabLine->GetFrmFmt(); const SwFmtFrmSize& rLSz = pLineFmt->GetFrmSize(); if ( ATT_VAR_SIZE != rLSz.GetHeightSizeType() && rLSz.GetHeight() ) { sal_Int32 nHeight = rLSz.GetHeight(); const char *pRule = NULL; switch ( rLSz.GetHeightSizeType() ) { case ATT_FIX_SIZE: pRule = "exact"; break; case ATT_MIN_SIZE: pRule = "atLeast"; break; default: break; } if ( pRule ) m_pSerializer->singleElementNS( XML_w, XML_trHeight, FSNS( XML_w, XML_val ), OString::valueOf( nHeight ).getStr( ), FSNS( XML_w, XML_hRule ), pRule, FSEND ); } } void DocxAttributeOutput::TableCanSplit( ww8::WW8TableNodeInfoInner::Pointer_t pTableTextNodeInfoInner ) { const SwTableBox * pTabBox = pTableTextNodeInfoInner->getTableBox(); const SwTableLine * pTabLine = pTabBox->GetUpper(); const SwFrmFmt * pLineFmt = pTabLine->GetFrmFmt(); const SwFmtRowSplit& rSplittable = pLineFmt->GetRowSplit( ); const char* pCantSplit = ( !rSplittable.GetValue( ) ) ? "on" : "off"; m_pSerializer->singleElementNS( XML_w, XML_cantSplit, FSNS( XML_w, XML_val ), pCantSplit, FSEND ); } void DocxAttributeOutput::TableBidi( ww8::WW8TableNodeInfoInner::Pointer_t pTableTextNodeInfoInner ) { const SwTable * pTable = pTableTextNodeInfoInner->getTable(); const SwFrmFmt * pFrmFmt = pTable->GetFrmFmt(); if ( m_rExport.TrueFrameDirection( *pFrmFmt ) == FRMDIR_HORI_RIGHT_TOP ) { m_pSerializer->singleElementNS( XML_w, XML_bidiVisual, FSNS( XML_w, XML_val ), "on", FSEND ); } } void DocxAttributeOutput::TableVerticalCell( ww8::WW8TableNodeInfoInner::Pointer_t pTableTextNodeInfoInner ) { const SwTableBox * pTabBox = pTableTextNodeInfoInner->getTableBox(); const SwFrmFmt *pFrmFmt = pTabBox->GetFrmFmt( ); if ( FRMDIR_VERT_TOP_RIGHT == m_rExport.TrueFrameDirection( *pFrmFmt ) ) m_pSerializer->singleElementNS( XML_w, XML_textDirection, FSNS( XML_w, XML_val ), "tbRl", FSEND ); } void DocxAttributeOutput::TableNodeInfo( ww8::WW8TableNodeInfo::Pointer_t /*pNodeInfo*/ ) { OSL_TRACE( "TODO: DocxAttributeOutput::TableNodeInfo( ww8::WW8TableNodeInfo::Pointer_t pNodeInfo )\n" ); } void DocxAttributeOutput::TableNodeInfoInner( ww8::WW8TableNodeInfoInner::Pointer_t pNodeInfoInner ) { // This is called when the nested table ends in a cell, and there's no // paragraph benhind that; so we must check for the ends of cell, rows, // tables // ['true' to write an empty paragraph, MS Word insists on that] FinishTableRowCell( pNodeInfoInner, true ); } void DocxAttributeOutput::TableOrientation( ww8::WW8TableNodeInfoInner::Pointer_t /*pTableTextNodeInfoInner*/ ) { OSL_TRACE( "TODO: DocxAttributeOutput::TableOrientation( ww8::WW8TableNodeInfoInner::Pointer_t pTableTextNodeInfoInner )\n" ); } void DocxAttributeOutput::TableSpacing( ww8::WW8TableNodeInfoInner::Pointer_t /*pTableTextNodeInfoInner*/ ) { #if OSL_DEBUG_LEVEL > 0 fprintf( stderr, "TODO: DocxAttributeOutput::TableSpacing( ww8::WW8TableNodeInfoInner::Pointer_t pTableTextNodeInfoInner )\n" ); #endif } void DocxAttributeOutput::TableRowEnd( sal_uInt32 /*nDepth*/ ) { OSL_TRACE( "TODO: DocxAttributeOutput::TableRowEnd( sal_uInt32 nDepth = 1 )\n" ); } void DocxAttributeOutput::StartStyles() { m_pSerializer->startElementNS( XML_w, XML_styles, FSNS( XML_xmlns, XML_w ), "http://schemas.openxmlformats.org/wordprocessingml/2006/main", FSEND ); } void DocxAttributeOutput::EndStyles( sal_uInt16 /*nNumberOfStyles*/ ) { m_pSerializer->endElementNS( XML_w, XML_styles ); } void DocxAttributeOutput::DefaultStyle( sal_uInt16 nStyle ) { // are these the values of enum ww::sti (see ../inc/wwstyles.hxx)? #if OSL_DEBUG_LEVEL > 0 OSL_TRACE( "TODO DocxAttributeOutput::DefaultStyle( sal_uInt16 nStyle )- %d\n", nStyle ); #else (void) nStyle; // to quiet the warning #endif } void DocxAttributeOutput::FlyFrameGraphic( const SwGrfNode& rGrfNode, const Size& rSize ) { #if OSL_DEBUG_LEVEL > 0 OSL_TRACE( "TODO DocxAttributeOutput::FlyFrameGraphic( const SwGrfNode& rGrfNode, const Size& rSize ) - some stuff still missing\n" ); #endif // create the relation ID OString aRelId; sal_Int32 nImageType; if ( rGrfNode.IsLinkedFile() ) { // linked image, just create the relation String aFileName; rGrfNode.GetFileFilterNms( &aFileName, 0 ); // TODO Convert the file name to relative for better interoperability aRelId = m_rExport.AddRelation( S( "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" ), OUString( aFileName ), S( "External" ) ); nImageType = XML_link; } else { // inline, we also have to write the image itself Graphic& rGraphic = const_cast< Graphic& >( rGrfNode.GetGrf() ); m_rDrawingML.SetFS( m_pSerializer ); // to be sure that we write to the right stream OUString aImageId = m_rDrawingML.WriteImage( rGraphic ); aRelId = OUStringToOString( aImageId, RTL_TEXTENCODING_UTF8 ); nImageType = XML_embed; } if ( aRelId.getLength() == 0 ) return; m_pSerializer->startElementNS( XML_w, XML_drawing, FSEND ); m_pSerializer->startElementNS( XML_wp, XML_inline, XML_distT, "0", XML_distB, "0", XML_distL, "0", XML_distR, "0", FSEND ); // extent of the image OString aWidth( OString::valueOf( TwipsToEMU( rSize.Width() ) ) ); OString aHeight( OString::valueOf( TwipsToEMU( rSize.Height() ) ) ); m_pSerializer->singleElementNS( XML_wp, XML_extent, XML_cx, aWidth.getStr(), XML_cy, aHeight.getStr(), FSEND ); // TODO - the right effectExtent, extent including the effect m_pSerializer->singleElementNS( XML_wp, XML_effectExtent, XML_l, "0", XML_t, "0", XML_r, "0", XML_b, "0", FSEND ); // picture description // TODO the right image description m_pSerializer->startElementNS( XML_wp, XML_docPr, XML_id, "1", XML_name, "Picture", XML_descr, "A description...", FSEND ); // TODO hyperlink // m_pSerializer->singleElementNS( XML_a, XML_hlinkClick, // FSNS( XML_xmlns, XML_a ), "http://schemas.openxmlformats.org/drawingml/2006/main", // FSNS( XML_r, XML_id ), "rId4", // FSEND ); m_pSerializer->endElementNS( XML_wp, XML_docPr ); m_pSerializer->startElementNS( XML_wp, XML_cNvGraphicFramePr, FSEND ); // TODO change aspect? m_pSerializer->singleElementNS( XML_a, XML_graphicFrameLocks, FSNS( XML_xmlns, XML_a ), "http://schemas.openxmlformats.org/drawingml/2006/main", XML_noChangeAspect, "1", FSEND ); m_pSerializer->endElementNS( XML_wp, XML_cNvGraphicFramePr ); m_pSerializer->startElementNS( XML_a, XML_graphic, FSNS( XML_xmlns, XML_a ), "http://schemas.openxmlformats.org/drawingml/2006/main", FSEND ); m_pSerializer->startElementNS( XML_a, XML_graphicData, XML_uri, "http://schemas.openxmlformats.org/drawingml/2006/picture", FSEND ); m_pSerializer->startElementNS( XML_pic, XML_pic, FSNS( XML_xmlns, XML_pic ), "http://schemas.openxmlformats.org/drawingml/2006/picture", FSEND ); m_pSerializer->startElementNS( XML_pic, XML_nvPicPr, FSEND ); // TODO the right image description m_pSerializer->startElementNS( XML_pic, XML_cNvPr, XML_id, "0", XML_name, "Picture", XML_descr, "A description...", FSEND ); // TODO hyperlink // m_pSerializer->singleElementNS( XML_a, XML_hlinkClick, // FSNS( XML_r, XML_id ), "rId4", // FSEND ); m_pSerializer->endElementNS( XML_pic, XML_cNvPr ); m_pSerializer->startElementNS( XML_pic, XML_cNvPicPr, FSEND ); // TODO change aspect? m_pSerializer->singleElementNS( XML_a, XML_picLocks, XML_noChangeAspect, "1", XML_noChangeArrowheads, "1", FSEND ); m_pSerializer->endElementNS( XML_pic, XML_cNvPicPr ); m_pSerializer->endElementNS( XML_pic, XML_nvPicPr ); // the actual picture m_pSerializer->startElementNS( XML_pic, XML_blipFill, FSEND ); m_pSerializer->singleElementNS( XML_a, XML_blip, FSNS( XML_r, nImageType ), aRelId.getStr(), FSEND ); m_pSerializer->singleElementNS( XML_a, XML_srcRect, FSEND ); m_pSerializer->startElementNS( XML_a, XML_stretch, FSEND ); m_pSerializer->singleElementNS( XML_a, XML_fillRect, FSEND ); m_pSerializer->endElementNS( XML_a, XML_stretch ); m_pSerializer->endElementNS( XML_pic, XML_blipFill ); // TODO setup the right values below m_pSerializer->startElementNS( XML_pic, XML_spPr, XML_bwMode, "auto", FSEND ); m_pSerializer->startElementNS( XML_a, XML_xfrm, FSEND ); m_pSerializer->singleElementNS( XML_a, XML_off, XML_x, "0", XML_y, "0", FSEND ); m_pSerializer->singleElementNS( XML_a, XML_ext, XML_cx, aWidth.getStr(), XML_cy, aHeight.getStr(), FSEND ); m_pSerializer->endElementNS( XML_a, XML_xfrm ); m_pSerializer->startElementNS( XML_a, XML_prstGeom, XML_prst, "rect", FSEND ); m_pSerializer->singleElementNS( XML_a, XML_avLst, FSEND ); m_pSerializer->endElementNS( XML_a, XML_prstGeom ); m_pSerializer->singleElementNS( XML_a, XML_noFill, FSEND ); m_pSerializer->startElementNS( XML_a, XML_ln, XML_w, "9525", FSEND ); m_pSerializer->singleElementNS( XML_a, XML_noFill, FSEND ); m_pSerializer->singleElementNS( XML_a, XML_miter, XML_lim, "800000", FSEND ); m_pSerializer->singleElementNS( XML_a, XML_headEnd, FSEND ); m_pSerializer->singleElementNS( XML_a, XML_tailEnd, FSEND ); m_pSerializer->endElementNS( XML_a, XML_ln ); m_pSerializer->endElementNS( XML_pic, XML_spPr ); m_pSerializer->endElementNS( XML_pic, XML_pic ); m_pSerializer->endElementNS( XML_a, XML_graphicData ); m_pSerializer->endElementNS( XML_a, XML_graphic ); m_pSerializer->endElementNS( XML_wp, XML_inline ); m_pSerializer->endElementNS( XML_w, XML_drawing ); } void DocxAttributeOutput::OutputFlyFrame_Impl( const sw::Frame &rFrame, const Point& /*rNdTopLeft*/ ) { m_pSerializer->mark(); switch ( rFrame.GetWriterType() ) { case sw::Frame::eGraphic: { const SwNode *pNode = rFrame.GetContent(); const SwGrfNode *pGrfNode = pNode ? pNode->GetGrfNode() : 0; if ( pGrfNode ) FlyFrameGraphic( *pGrfNode, rFrame.GetLayoutSize() ); } break; case sw::Frame::eDrawing: { const SdrObject* pSdrObj = rFrame.GetFrmFmt().FindRealSdrObject(); if ( pSdrObj ) { bool bSwapInPage = false; if ( !pSdrObj->GetPage() ) { if ( SwDrawModel* pModel = m_rExport.pDoc->GetDrawModel() ) { if ( SdrPage *pPage = pModel->GetPage( 0 ) ) { bSwapInPage = true; const_cast< SdrObject* >( pSdrObj )->SetPage( pPage ); } } } m_pSerializer->startElementNS( XML_w, XML_pict, FSEND ); m_rExport.VMLExporter().AddSdrObject( *pSdrObj ); m_pSerializer->endElementNS( XML_w, XML_pict ); if ( bSwapInPage ) const_cast< SdrObject* >( pSdrObj )->SetPage( 0 ); } } break; default: #if OSL_DEBUG_LEVEL > 0 OSL_TRACE( "TODO DocxAttributeOutput::OutputFlyFrame_Impl( const sw::Frame& rFrame, const Point& rNdTopLeft ) - frame type '%s'\n", rFrame.GetWriterType() == sw::Frame::eTxtBox? "eTxtBox": ( rFrame.GetWriterType() == sw::Frame::eOle? "eOle": ( rFrame.GetWriterType() == sw::Frame::eFormControl? "eFormControl": "???" ) ) ); #endif break; } m_pSerializer->mergeTopMarks( sax_fastparser::MERGE_MARKS_POSTPONE ); } void DocxAttributeOutput::StartStyle( const String& rName, bool bPapFmt, sal_uInt16 nBase, sal_uInt16 nNext, sal_uInt16 /*nWwId*/, sal_uInt16 nId ) { OString aStyle( "style" ); m_pSerializer->startElementNS( XML_w, XML_style, FSNS( XML_w, XML_type ), bPapFmt? "paragraph": "character", // FIXME is this correct? FSNS( XML_w, XML_styleId ), ( aStyle + OString::valueOf( sal_Int32( nId ) ) ).getStr(), FSEND ); m_pSerializer->singleElementNS( XML_w, XML_name, FSNS( XML_w, XML_val ), OUStringToOString( OUString( rName ), RTL_TEXTENCODING_UTF8 ).getStr(), FSEND ); if ( nBase != 0x0FFF ) { m_pSerializer->singleElementNS( XML_w, XML_basedOn, FSNS( XML_w, XML_val ), ( aStyle + OString::valueOf( sal_Int32( nBase ) ) ).getStr(), FSEND ); } m_pSerializer->singleElementNS( XML_w, XML_next, FSNS( XML_w, XML_val ), ( aStyle + OString::valueOf( sal_Int32( nNext ) ) ).getStr(), FSEND ); } void DocxAttributeOutput::EndStyle() { m_pSerializer->endElementNS( XML_w, XML_style ); } void DocxAttributeOutput::StartStyleProperties( bool bParProp, sal_uInt16 /*nStyle*/ ) { if ( bParProp ) { m_pSerializer->startElementNS( XML_w, XML_pPr, FSEND ); InitCollectedParagraphProperties(); } else { m_pSerializer->startElementNS( XML_w, XML_rPr, FSEND ); InitCollectedRunProperties(); } } void DocxAttributeOutput::EndStyleProperties( bool bParProp ) { if ( bParProp ) { WriteCollectedParagraphProperties(); m_pSerializer->endElementNS( XML_w, XML_pPr ); } else { WriteCollectedRunProperties(); m_pSerializer->endElementNS( XML_w, XML_rPr ); } } void DocxAttributeOutput::OutlineNumbering( sal_uInt8 nLvl, const SwNumFmt& /*rNFmt*/, const SwFmt& /*rFmt*/ ) { if ( nLvl >= WW8ListManager::nMaxLevel ) nLvl = WW8ListManager::nMaxLevel - 1; m_pSerializer->singleElementNS( XML_w, XML_outlineLvl, FSNS( XML_w, XML_val ), OString::valueOf( sal_Int32( nLvl ) ).getStr( ), FSEND ); } void DocxAttributeOutput::PageBreakBefore( bool bBreak ) { if ( bBreak ) m_pSerializer->singleElementNS( XML_w, XML_pageBreakBefore, FSEND ); else m_pSerializer->singleElementNS( XML_w, XML_pageBreakBefore, FSNS( XML_w, XML_val ), "off", FSEND ); } void DocxAttributeOutput::SectionBreak( sal_uInt8 nC, const WW8_SepInfo* pSectionInfo ) { switch ( nC ) { case msword::ColumnBreak: // The column break should be output in the next paragraph... m_nColBreakStatus = COLBRK_POSTPONE; break; case msword::PageBreak: if ( pSectionInfo ) { if ( !m_bParagraphOpened ) { // Create a dummy paragraph if needed m_pSerializer->startElementNS( XML_w, XML_p, FSEND ); m_pSerializer->startElementNS( XML_w, XML_pPr, FSEND ); m_rExport.SectionProperties( *pSectionInfo ); m_pSerializer->endElementNS( XML_w, XML_pPr ); m_pSerializer->endElementNS( XML_w, XML_p ); } else { // postpone the output of this; it has to be done inside the // paragraph properties, so remember it until then m_pSectionInfo = pSectionInfo; } } else { m_pSerializer->startElementNS( XML_w, XML_r, FSEND ); m_pSerializer->singleElementNS( XML_w, XML_br, FSNS( XML_w, XML_type ), "page", FSEND ); m_pSerializer->endElementNS( XML_w, XML_r ); } break; default: #if OSL_DEBUG_LEVEL > 0 OSL_TRACE( "Unknown section break to write: %d\n", nC ); #endif break; } } void DocxAttributeOutput::StartSection() { m_pSerializer->startElementNS( XML_w, XML_sectPr, FSEND ); m_bOpenedSectPr = true; } void DocxAttributeOutput::EndSection() { // Write the section properties if ( m_pSpacingAttrList ) { XFastAttributeListRef xAttrList( m_pSpacingAttrList ); m_pSpacingAttrList = NULL; m_pSerializer->singleElementNS( XML_w, XML_pgMar, xAttrList ); } m_pSerializer->endElementNS( XML_w, XML_sectPr ); m_bOpenedSectPr = false; } void DocxAttributeOutput::SectionFormProtection( bool bProtected ) { if ( bProtected ) m_pSerializer->singleElementNS( XML_w, XML_formProt, FSEND ); else m_pSerializer->singleElementNS( XML_w, XML_formProt, FSNS( XML_w, XML_val ), "off", FSEND ); } void DocxAttributeOutput::SectionLineNumbering( sal_uLong /*nRestartNo*/, const SwLineNumberInfo& /*rLnNumInfo*/ ) { // see 2.6.8 lnNumType (Line Numbering Settings) #if OSL_DEBUG_LEVEL > 0 OSL_TRACE( "TODO DocxAttributeOutput::SectionLineNumbering()\n" ); #endif } void DocxAttributeOutput::SectionTitlePage() { m_pSerializer->singleElementNS( XML_w, XML_titlePg, FSEND ); } void DocxAttributeOutput::SectionPageBorders( const SwFrmFmt* pFmt, const SwFrmFmt* /*pFirstPageFmt*/ ) { // Output the margins const SvxBoxItem& rBox = pFmt->GetBox( ); const SvxBorderLine* pBottom = rBox.GetBottom( ); const SvxBorderLine* pTop = rBox.GetTop( ); const SvxBorderLine* pLeft = rBox.GetLeft( ); const SvxBorderLine* pRight = rBox.GetRight( ); if ( pBottom || pTop || pLeft || pRight ) { // All distances are relative to the text margins m_pSerializer->startElementNS( XML_w, XML_pgBorders, FSNS( XML_w, XML_display ), "allPages", FSNS( XML_w, XML_offsetFrom ), "text", FSEND ); m_pSerializer->mark(); m_pSerializer->endElementNS( XML_w, XML_pgBorders ); m_pSerializer->mark(); } } void DocxAttributeOutput::SectionBiDi( bool bBiDi ) { if ( bBiDi ) m_pSerializer->singleElementNS( XML_w, XML_bidi, FSEND ); } static OString impl_NumberingType( sal_uInt16 nNumberingType ) { OString aType; switch ( nNumberingType ) { case SVX_NUM_CHARS_UPPER_LETTER: case SVX_NUM_CHARS_UPPER_LETTER_N: aType = "upperLetter"; break; case SVX_NUM_CHARS_LOWER_LETTER: case SVX_NUM_CHARS_LOWER_LETTER_N: aType = "lowerLetter"; break; case SVX_NUM_ROMAN_UPPER: aType = "upperRoman"; break; case SVX_NUM_ROMAN_LOWER: aType = "lowerRoman"; break; case SVX_NUM_ARABIC: aType = "decimal"; break; case SVX_NUM_BITMAP: case SVX_NUM_CHAR_SPECIAL: aType = "bullet"; break; default: aType = "none"; break; } return aType; } void DocxAttributeOutput::SectionPageNumbering( sal_uInt16 nNumType, sal_uInt16 nPageRestartNumber ) { // FIXME Not called properly with page styles like "First Page" FastAttributeList* pAttr = m_pSerializer->createAttrList(); // 0 means no restart: then don't output that attribute if 0 if ( nPageRestartNumber > 0 ) pAttr->add( FSNS( XML_w, XML_start ), OString::valueOf( sal_Int32( nPageRestartNumber ) ) ); // nNumType corresponds to w:fmt. See WW8Export::GetNumId() for more precisions OString aFmt( impl_NumberingType( nNumType ) ); if ( aFmt.getLength() ) pAttr->add( FSNS( XML_w, XML_fmt ), aFmt.getStr() ); XFastAttributeListRef xAttrs( pAttr ); m_pSerializer->singleElementNS( XML_w, XML_pgNumType, xAttrs ); // see 2.6.12 pgNumType (Page Numbering Settings) #if OSL_DEBUG_LEVEL > 0 OSL_TRACE( "TODO DocxAttributeOutput::SectionPageNumbering()\n" ); #endif } void DocxAttributeOutput::SectionType( sal_uInt8 nBreakCode ) { /* break code: 0 No break, 1 New column 2 New page, 3 Even page, 4 Odd page */ const char* pType = NULL; switch ( nBreakCode ) { case 1: pType = "nextColumn"; break; case 2: pType = "nextPage"; break; case 3: pType = "evenPage"; break; case 4: pType = "oddPage"; break; default: pType = "continuous"; break; } if ( pType ) m_pSerializer->singleElementNS( XML_w, XML_type, FSNS( XML_w, XML_val ), pType, FSEND ); } void DocxAttributeOutput::StartFont( const String& rFamilyName ) const { m_pSerializer->startElementNS( XML_w, XML_font, FSNS( XML_w, XML_name ), OUStringToOString( OUString( rFamilyName ), RTL_TEXTENCODING_UTF8 ).getStr(), FSEND ); } void DocxAttributeOutput::EndFont() const { m_pSerializer->endElementNS( XML_w, XML_font ); } void DocxAttributeOutput::FontAlternateName( const String& rName ) const { m_pSerializer->singleElementNS( XML_w, XML_altName, FSNS( XML_w, XML_val ), OUStringToOString( OUString( rName ), RTL_TEXTENCODING_UTF8 ).getStr(), FSEND ); } void DocxAttributeOutput::FontCharset( sal_uInt8 nCharSet ) const { OString aCharSet( OString::valueOf( sal_Int32( nCharSet ), 16 ) ); if ( aCharSet.getLength() == 1 ) aCharSet = OString( "0" ) + aCharSet; m_pSerializer->singleElementNS( XML_w, XML_charset, FSNS( XML_w, XML_val ), aCharSet.getStr(), FSEND ); } void DocxAttributeOutput::FontFamilyType( FontFamily eFamily ) const { const char *pFamily = NULL; switch ( eFamily ) { case FAMILY_ROMAN: pFamily = "roman"; break; case FAMILY_SWISS: pFamily = "swiss"; break; case FAMILY_MODERN: pFamily = "modern"; break; case FAMILY_SCRIPT: pFamily = "script"; break; case FAMILY_DECORATIVE: pFamily = "decorative"; break; default: pFamily = "auto"; break; // no font family } if ( pFamily ) m_pSerializer->singleElementNS( XML_w, XML_family, FSNS( XML_w, XML_val ), pFamily, FSEND ); } void DocxAttributeOutput::FontPitchType( FontPitch ePitch ) const { const char *pPitch = NULL; switch ( ePitch ) { case PITCH_VARIABLE: pPitch = "variable"; break; case PITCH_FIXED: pPitch = "fixed"; break; default: pPitch = "default"; break; // no info about the pitch } if ( pPitch ) m_pSerializer->singleElementNS( XML_w, XML_pitch, FSNS( XML_w, XML_val ), pPitch, FSEND ); } void DocxAttributeOutput::NumberingDefinition( sal_uInt16 nId, const SwNumRule &rRule ) { // nId is the same both for abstract numbering definition as well as the // numbering definition itself // TODO check that this is actually true & fix if not ;-) OString aId( OString::valueOf( sal_Int32( nId ) ) ); m_pSerializer->startElementNS( XML_w, XML_num, FSNS( XML_w, XML_numId ), aId.getStr(), FSEND ); m_pSerializer->singleElementNS( XML_w, XML_abstractNumId, FSNS( XML_w, XML_val ), aId.getStr(), FSEND ); #if OSL_DEBUG_LEVEL > 0 // TODO ww8 version writes this, anything to do about it here? if ( rRule.IsContinusNum() ) OSL_TRACE( "TODO DocxAttributeOutput::NumberingDefinition()\n" ); #else (void) rRule; // to quiet the warning... #endif m_pSerializer->endElementNS( XML_w, XML_num ); } void DocxAttributeOutput::StartAbstractNumbering( sal_uInt16 nId ) { m_pSerializer->startElementNS( XML_w, XML_abstractNum, FSNS( XML_w, XML_abstractNumId ), OString::valueOf( sal_Int32( nId ) ).getStr(), FSEND ); } void DocxAttributeOutput::EndAbstractNumbering() { m_pSerializer->endElementNS( XML_w, XML_abstractNum ); } void DocxAttributeOutput::NumberingLevel( sal_uInt8 nLevel, sal_uInt16 nStart, sal_uInt16 nNumberingType, SvxAdjust eAdjust, const sal_uInt8 * /*pNumLvlPos*/, sal_uInt8 nFollow, const wwFont *pFont, const SfxItemSet *pOutSet, sal_Int16 nIndentAt, sal_Int16 nFirstLineIndex, sal_Int16 /*nListTabPos*/, const String &rNumberingString ) { m_pSerializer->startElementNS( XML_w, XML_lvl, FSNS( XML_w, XML_ilvl ), OString::valueOf( sal_Int32( nLevel ) ).getStr(), FSEND ); // start with the nStart value m_pSerializer->singleElementNS( XML_w, XML_start, FSNS( XML_w, XML_val ), OString::valueOf( sal_Int32( nStart ) ).getStr(), FSEND ); // format OString aFmt( impl_NumberingType( nNumberingType ) ); if ( aFmt.getLength() ) m_pSerializer->singleElementNS( XML_w, XML_numFmt, FSNS( XML_w, XML_val ), aFmt.getStr(), FSEND ); // justification const char *pJc; switch ( eAdjust ) { case SVX_ADJUST_CENTER: pJc = "center"; break; case SVX_ADJUST_RIGHT: pJc = "right"; break; default: pJc = "left"; break; } m_pSerializer->singleElementNS( XML_w, XML_lvlJc, FSNS( XML_w, XML_val ), pJc, FSEND ); // suffix const char *pSuffix = NULL; switch ( nFollow ) { case 1: pSuffix = "space"; break; case 2: pSuffix = "nothing"; break; default: /*pSuffix = "tab";*/ break; } if ( pSuffix ) m_pSerializer->singleElementNS( XML_w, XML_suff, FSNS( XML_w, XML_val ), pSuffix, FSEND ); // text OUString aText( rNumberingString ); OUStringBuffer aBuffer( aText.getLength() + WW8ListManager::nMaxLevel ); const sal_Unicode *pPrev = aText.getStr(); const sal_Unicode *pIt = aText.getStr(); while ( pIt < aText.getStr() + aText.getLength() ) { // convert the level values to %NUMBER form // (we don't use pNumLvlPos at all) // FIXME so far we support the ww8 limit of levels only if ( *pIt < sal_Unicode( WW8ListManager::nMaxLevel ) ) { aBuffer.append( pPrev, pIt - pPrev ); aBuffer.appendAscii( "%" ); aBuffer.append( OUString::valueOf( sal_Int32( *pIt ) + 1 ) ); pPrev = pIt + 1; } ++pIt; } if ( pPrev < pIt ) aBuffer.append( pPrev, pIt - pPrev ); m_pSerializer->singleElementNS( XML_w, XML_lvlText, FSNS( XML_w, XML_val ), OUStringToOString( aBuffer.makeStringAndClear(), RTL_TEXTENCODING_UTF8 ).getStr(), FSEND ); // indentation m_pSerializer->startElementNS( XML_w, XML_pPr, FSEND ); m_pSerializer->singleElementNS( XML_w, XML_ind, FSNS( XML_w, XML_left ), OString::valueOf( sal_Int32( nIndentAt ) ).getStr(), FSNS( XML_w, XML_hanging ), OString::valueOf( sal_Int32( -nFirstLineIndex ) ).getStr(), FSEND ); m_pSerializer->endElementNS( XML_w, XML_pPr ); // font if ( pOutSet ) { m_pSerializer->startElementNS( XML_w, XML_rPr, FSEND ); if ( pFont ) { OString aFamilyName( OUStringToOString( OUString( pFont->GetFamilyName() ), RTL_TEXTENCODING_UTF8 ) ); m_pSerializer->singleElementNS( XML_w, XML_rFonts, FSNS( XML_w, XML_ascii ), aFamilyName.getStr(), FSNS( XML_w, XML_hAnsi ), aFamilyName.getStr(), FSNS( XML_w, XML_cs ), aFamilyName.getStr(), FSNS( XML_w, XML_hint ), "default", FSEND ); } m_rExport.OutputItemSet( *pOutSet, false, true, i18n::ScriptType::LATIN ); m_pSerializer->endElementNS( XML_w, XML_rPr ); } // TODO anything to do about nListTabPos? m_pSerializer->endElementNS( XML_w, XML_lvl ); } void DocxAttributeOutput::CharCaseMap( const SvxCaseMapItem& rCaseMap ) { switch ( rCaseMap.GetValue() ) { case SVX_CASEMAP_KAPITAELCHEN: m_pSerializer->singleElementNS( XML_w, XML_smallCaps, FSEND ); break; case SVX_CASEMAP_VERSALIEN: m_pSerializer->singleElementNS( XML_w, XML_caps, FSEND ); break; default: // Something that ooxml does not support m_pSerializer->singleElementNS( XML_w, XML_smallCaps, FSNS( XML_w, XML_val ), "off", FSEND ); m_pSerializer->singleElementNS( XML_w, XML_caps, FSNS( XML_w, XML_val ), "off", FSEND ); break; } } void DocxAttributeOutput::CharColor( const SvxColorItem& rColor ) { const Color aColor( rColor.GetValue() ); OString aColorString; aColorString = impl_ConvertColor( aColor ); m_pSerializer->singleElementNS( XML_w, XML_color, FSNS( XML_w, XML_val ), aColorString.getStr(), FSEND ); } void DocxAttributeOutput::CharContour( const SvxContourItem& rContour ) { if ( rContour.GetValue() ) m_pSerializer->singleElementNS( XML_w, XML_outline, FSEND ); else m_pSerializer->singleElementNS( XML_w, XML_outline, FSNS( XML_w, XML_val ), "off", FSEND ); } void DocxAttributeOutput::CharCrossedOut( const SvxCrossedOutItem& rCrossedOut ) { switch ( rCrossedOut.GetStrikeout() ) { case STRIKEOUT_DOUBLE: m_pSerializer->singleElementNS( XML_w, XML_dstrike, FSEND ); break; case STRIKEOUT_NONE: m_pSerializer->singleElementNS( XML_w, XML_dstrike, FSNS( XML_w, XML_val ), "off", FSEND ); m_pSerializer->singleElementNS( XML_w, XML_strike, FSNS( XML_w, XML_val ), "off", FSEND ); break; default: m_pSerializer->singleElementNS( XML_w, XML_strike, FSEND ); break; } } void DocxAttributeOutput::CharEscapement( const SvxEscapementItem& /*rEscapement*/ ) { #if OSL_DEBUG_LEVEL > 0 OSL_TRACE( "TODO DocxAttributeOutput::CharEscapement()\n" ); #endif } void DocxAttributeOutput::CharFont( const SvxFontItem& rFont) { if (!m_pFontsAttrList) m_pFontsAttrList = m_pSerializer->createAttrList(); OUString sFontName(rFont.GetFamilyName()); OString sFontNameUtf8 = OUStringToOString(sFontName, RTL_TEXTENCODING_UTF8); m_pFontsAttrList->add(FSNS(XML_w, XML_ascii), sFontNameUtf8); m_pFontsAttrList->add(FSNS(XML_w, XML_hAnsi), sFontNameUtf8); } void DocxAttributeOutput::CharFontSize( const SvxFontHeightItem& rFontSize) { OString fontSize = OString::valueOf( sal_Int32( ( rFontSize.GetHeight() + 5 ) / 10 ) ); switch ( rFontSize.Which() ) { case RES_CHRATR_FONTSIZE: case RES_CHRATR_CJK_FONTSIZE: m_pSerializer->singleElementNS( XML_w, XML_sz, FSNS( XML_w, XML_val ), fontSize.getStr(), FSEND ); break; case RES_CHRATR_CTL_FONTSIZE: m_pSerializer->singleElementNS( XML_w, XML_szCs, FSNS( XML_w, XML_val ), fontSize.getStr(), FSEND ); break; } } void DocxAttributeOutput::CharKerning( const SvxKerningItem& rKerning ) { OString aKerning = OString::valueOf( ( sal_Int32 ) rKerning.GetValue() ); m_pSerializer->singleElementNS( XML_w, XML_kern, FSNS(XML_w, XML_val), aKerning.getStr(), FSEND ); } void DocxAttributeOutput::CharLanguage( const SvxLanguageItem& rLanguage ) { if (!m_pCharLangAttrList) m_pCharLangAttrList = m_pSerializer->createAttrList(); ::com::sun::star::lang::Locale xLocale= MsLangId::convertLanguageToLocale( rLanguage.GetLanguage( ) ); OString sLanguage = OUStringToOString(xLocale.Language, RTL_TEXTENCODING_UTF8); OString sCountry = OUStringToOString(xLocale.Country, RTL_TEXTENCODING_UTF8); OString aLanguageCode = sLanguage + "-" + sCountry; switch ( rLanguage.Which() ) { case RES_CHRATR_LANGUAGE: m_pCharLangAttrList->add(FSNS(XML_w, XML_val), aLanguageCode); break; case RES_CHRATR_CJK_LANGUAGE: m_pCharLangAttrList->add(FSNS(XML_w, XML_eastAsia), aLanguageCode); break; case RES_CHRATR_CTL_LANGUAGE: m_pCharLangAttrList->add(FSNS(XML_w, XML_bidi), aLanguageCode); break; } } void DocxAttributeOutput::CharPosture( const SvxPostureItem& rPosture ) { if ( rPosture.GetPosture() != ITALIC_NONE ) m_pSerializer->singleElementNS( XML_w, XML_i, FSEND ); else m_pSerializer->singleElementNS( XML_w, XML_i, FSNS( XML_w, XML_val ), "off", FSEND ); } void DocxAttributeOutput::CharShadow( const SvxShadowedItem& rShadow ) { if ( rShadow.GetValue() ) m_pSerializer->singleElementNS( XML_w, XML_shadow, FSEND ); else m_pSerializer->singleElementNS( XML_w, XML_shadow, FSNS( XML_w, XML_val ), "off", FSEND ); } void DocxAttributeOutput::CharUnderline( const SvxUnderlineItem& rUnderline ) { const char *pUnderline; switch ( rUnderline.GetLineStyle() ) { case UNDERLINE_SINGLE: pUnderline = "single"; break; case UNDERLINE_BOLD: pUnderline = "thick"; break; case UNDERLINE_DOUBLE: pUnderline = "double"; break; case UNDERLINE_DOTTED: pUnderline = "dotted"; break; case UNDERLINE_DASH: pUnderline = "dash"; break; case UNDERLINE_DASHDOT: pUnderline = "dotDash"; break; case UNDERLINE_DASHDOTDOT: pUnderline = "dotDotDash"; break; case UNDERLINE_WAVE: pUnderline = "wave"; break; case UNDERLINE_BOLDDOTTED: pUnderline = "dottedHeavy"; break; case UNDERLINE_BOLDDASH: pUnderline = "dashedHeavy"; break; case UNDERLINE_LONGDASH: pUnderline = "dashLongHeavy"; break; case UNDERLINE_BOLDLONGDASH: pUnderline = "dashLongHeavy"; break; case UNDERLINE_BOLDDASHDOT: pUnderline = "dashDotHeavy"; break; case UNDERLINE_BOLDDASHDOTDOT: pUnderline = "dashDotDotHeavy"; break; case UNDERLINE_BOLDWAVE: pUnderline = "wavyHeavy"; break; case UNDERLINE_DOUBLEWAVE: pUnderline = "wavyDouble"; break; case UNDERLINE_NONE: // fall through default: pUnderline = "none"; break; } m_pSerializer->singleElementNS( XML_w, XML_u, FSNS( XML_w, XML_val ), pUnderline, FSEND ); } void DocxAttributeOutput::CharWeight( const SvxWeightItem& rWeight ) { if ( rWeight.GetWeight() == WEIGHT_BOLD ) m_pSerializer->singleElementNS( XML_w, XML_b, FSEND ); else m_pSerializer->singleElementNS( XML_w, XML_b, FSNS( XML_w, XML_val ), "off", FSEND ); } void DocxAttributeOutput::CharAutoKern( const SvxAutoKernItem& ) { #if OSL_DEBUG_LEVEL > 0 OSL_TRACE( "TODO DocxAttributeOutput::CharAutoKern()\n" ); #endif } void DocxAttributeOutput::CharAnimatedText( const SvxBlinkItem& rBlink ) { if ( rBlink.GetValue() ) m_pSerializer->singleElementNS(XML_w, XML_effect, FSNS( XML_w, XML_val ), "blinkBackground", FSEND ); else m_pSerializer->singleElementNS(XML_w, XML_effect, FSNS( XML_w, XML_val ), "none", FSEND ); } void DocxAttributeOutput::CharBackground( const SvxBrushItem& rBrush ) { m_pSerializer->singleElementNS( XML_w, XML_shd, FSNS( XML_w, XML_fill ), impl_ConvertColor( rBrush.GetColor() ).getStr(), FSEND ); } void DocxAttributeOutput::CharFontCJK( const SvxFontItem& rFont ) { if (!m_pFontsAttrList) m_pFontsAttrList = m_pSerializer->createAttrList(); OUString sFontName(rFont.GetFamilyName()); OString sFontNameUtf8 = OUStringToOString(sFontName, RTL_TEXTENCODING_UTF8); m_pFontsAttrList->add(FSNS(XML_w, XML_eastAsia), sFontNameUtf8); } void DocxAttributeOutput::CharPostureCJK( const SvxPostureItem& rPosture ) { if ( rPosture.GetPosture() != ITALIC_NONE ) m_pSerializer->singleElementNS( XML_w, XML_i, FSEND ); else m_pSerializer->singleElementNS( XML_w, XML_i, FSNS( XML_w, XML_val ), "off", FSEND ); } void DocxAttributeOutput::CharWeightCJK( const SvxWeightItem& rWeight ) { if ( rWeight.GetWeight() == WEIGHT_BOLD ) m_pSerializer->singleElementNS( XML_w, XML_b, FSEND ); else m_pSerializer->singleElementNS( XML_w, XML_b, FSNS( XML_w, XML_val ), "off", FSEND ); } void DocxAttributeOutput::CharFontCTL( const SvxFontItem& rFont ) { if (!m_pFontsAttrList) m_pFontsAttrList = m_pSerializer->createAttrList(); OUString sFontName(rFont.GetFamilyName()); OString sFontNameUtf8 = OUStringToOString(sFontName, RTL_TEXTENCODING_UTF8); m_pFontsAttrList->add(FSNS(XML_w, XML_cs), sFontNameUtf8); } void DocxAttributeOutput::CharPostureCTL( const SvxPostureItem& rPosture) { if ( rPosture.GetPosture() != ITALIC_NONE ) m_pSerializer->singleElementNS( XML_w, XML_iCs, FSEND ); else m_pSerializer->singleElementNS( XML_w, XML_iCs, FSNS( XML_w, XML_val ), "off", FSEND ); } void DocxAttributeOutput::CharWeightCTL( const SvxWeightItem& rWeight ) { if ( rWeight.GetWeight() == WEIGHT_BOLD ) m_pSerializer->singleElementNS( XML_w, XML_bCs, FSEND ); else m_pSerializer->singleElementNS( XML_w, XML_bCs, FSNS( XML_w, XML_val ), "off", FSEND ); } void DocxAttributeOutput::CharRotate( const SvxCharRotateItem& rRotate) { if ( !rRotate.GetValue() ) return; if (!m_pEastAsianLayoutAttrList) m_pEastAsianLayoutAttrList = m_pSerializer->createAttrList(); OString sTrue((sal_Char *)"true"); m_pEastAsianLayoutAttrList->add(FSNS(XML_w, XML_vert), sTrue); if (rRotate.IsFitToLine()) m_pEastAsianLayoutAttrList->add(FSNS(XML_w, XML_vertCompress), sTrue); } void DocxAttributeOutput::CharEmphasisMark( const SvxEmphasisMarkItem& rEmphasisMark ) { const char *pEmphasis; switch ( rEmphasisMark.GetValue() ) { case EMPHASISMARK_NONE: pEmphasis = "none"; break; case EMPHASISMARK_SIDE_DOTS: pEmphasis = "dot"; break; case EMPHASISMARK_CIRCLE_ABOVE: pEmphasis = "circle"; break; case EMPHASISMARK_DOTS_BELOW: pEmphasis = "underDot"; break; default: pEmphasis = "comma"; break; } m_pSerializer->singleElementNS( XML_w, XML_em, FSNS( XML_w, XML_val ), pEmphasis, FSEND ); } void DocxAttributeOutput::CharTwoLines( const SvxTwoLinesItem& rTwoLines ) { if ( !rTwoLines.GetValue() ) return; if (!m_pEastAsianLayoutAttrList) m_pEastAsianLayoutAttrList = m_pSerializer->createAttrList(); OString sTrue((sal_Char *)"true"); m_pEastAsianLayoutAttrList->add(FSNS(XML_w, XML_combine), sTrue); sal_Unicode cStart = rTwoLines.GetStartBracket(); sal_Unicode cEnd = rTwoLines.GetEndBracket(); if (!cStart && !cEnd) return; OString sBracket; if ((cStart == '{') || (cEnd == '}')) sBracket = (sal_Char *)"curly"; else if ((cStart == '<') || (cEnd == '>')) sBracket = (sal_Char *)"angle"; else if ((cStart == '[') || (cEnd == ']')) sBracket = (sal_Char *)"square"; else sBracket = (sal_Char *)"round"; m_pEastAsianLayoutAttrList->add(FSNS(XML_w, XML_combineBrackets), sBracket); } void DocxAttributeOutput::CharScaleWidth( const SvxCharScaleWidthItem& rScaleWidth ) { m_pSerializer->singleElementNS( XML_w, XML_w, FSNS( XML_w, XML_val ), rtl::OString::valueOf( sal_Int32( rScaleWidth.GetValue() ) ).getStr(), FSEND ); } void DocxAttributeOutput::CharRelief( const SvxCharReliefItem& rRelief ) { switch ( rRelief.GetValue() ) { case RELIEF_EMBOSSED: m_pSerializer->singleElementNS( XML_w, XML_emboss, FSEND ); break; case RELIEF_ENGRAVED: m_pSerializer->singleElementNS( XML_w, XML_imprint, FSEND ); break; default: m_pSerializer->singleElementNS( XML_w, XML_emboss, FSNS( XML_w, XML_val ), "off", FSEND ); m_pSerializer->singleElementNS( XML_w, XML_imprint, FSNS( XML_w, XML_val ), "off", FSEND ); break; } } void DocxAttributeOutput::CharHidden( const SvxCharHiddenItem& rHidden ) { if ( rHidden.GetValue() ) m_pSerializer->singleElementNS( XML_w, XML_vanish, FSEND ); else m_pSerializer->singleElementNS( XML_w, XML_vanish, FSNS( XML_w, XML_val ), "off", FSEND ); } void DocxAttributeOutput::TextINetFormat( const SwFmtINetFmt& rLink ) { const SwTxtINetFmt* pINetFmt = rLink.GetTxtINetFmt(); const SwCharFmt* pCharFmt = pINetFmt->GetCharFmt(); OString aStyleId( "style" ); aStyleId += OString::valueOf( sal_Int32( m_rExport.GetId( *pCharFmt ) ) ); m_pSerializer->singleElementNS( XML_w, XML_rStyle, FSNS( XML_w, XML_val ), aStyleId.getStr(), FSEND ); } void DocxAttributeOutput::TextCharFormat( const SwFmtCharFmt& ) { #if OSL_DEBUG_LEVEL > 0 OSL_TRACE( "TODO DocxAttributeOutput::TextCharFormat()\n" ); #endif } void DocxAttributeOutput::RefField( const SwField& rFld, const String& rRef ) { sal_uInt16 nType = rFld.GetTyp( )->Which( ); if ( nType == RES_GETEXPFLD ) { String sCmd = FieldString( ww::eREF ); sCmd.APPEND_CONST_ASC( "\"" ); sCmd += rRef; sCmd.APPEND_CONST_ASC( "\" " ); m_rExport.OutputField( &rFld, ww::eREF, sCmd ); } // There is nothing to do here for the set fields } void DocxAttributeOutput::HiddenField( const SwField& /*rFld*/ ) { #if OSL_DEBUG_LEVEL > 0 OSL_TRACE( "TODO DocxAttributeOutput::HiddenField()\n" ); #endif } void DocxAttributeOutput::PostitField( const SwField* /* pFld*/ ) { #if OSL_DEBUG_LEVEL > 0 OSL_TRACE( "TODO DocxAttributeOutput::PostitField()\n" ); #endif } bool DocxAttributeOutput::DropdownField( const SwField* pFld ) { bool bExpand = false; ww::eField eType = ww::eFORMDROPDOWN; String sCmd = FieldString( eType ); GetExport( ).OutputField( pFld, eType, sCmd ); return bExpand; } void DocxAttributeOutput::SetField( const SwField& rFld, ww::eField eType, const String& rCmd ) { // field bookmarks are handled in the EndRun method GetExport().OutputField(&rFld, eType, rCmd ); } void DocxAttributeOutput::WriteExpand( const SwField* pFld ) { // Will be written in the next End Run String sCmd; m_rExport.OutputField( pFld, ww::eUNKNOWN, sCmd ); } void DocxAttributeOutput::WriteField_Impl( const SwField* pFld, ww::eField eType, const String& rFldCmd, sal_uInt8 nMode ) { struct FieldInfos infos; infos.pField = pFld; infos.sCmd = rFldCmd; infos.eType = eType; infos.bClose = WRITEFIELD_CLOSE & nMode; infos.bOpen = WRITEFIELD_START & nMode; m_Fields.push_back( infos ); if ( pFld ) { sal_uInt16 nType = pFld->GetTyp( )->Which( ); sal_uInt16 nSubType = pFld->GetSubType(); // TODO Any other field types here ? if ( ( nType == RES_SETEXPFLD ) && ( nSubType & nsSwGetSetExpType::GSE_STRING ) ) { const SwSetExpField *pSet = ( const SwSetExpField* )( pFld ); m_sFieldBkm = pSet->GetPar1( ); } else if ( nType == RES_DROPDOWN ) { const SwDropDownField* pDropDown = ( const SwDropDownField* )( pFld ); m_sFieldBkm = pDropDown->GetName( ); } } } void DocxAttributeOutput::WriteBookmarks_Impl( std::vector< OUString >& rStarts, std::vector< OUString >& rEnds ) { for ( std::vector< OUString >::const_iterator it = rStarts.begin(), end = rStarts.end(); it < end; ++it ) { OString rName = OUStringToOString( *it, RTL_TEXTENCODING_UTF8 ).getStr( ); m_rMarksStart.push_back( rName ); } rStarts.clear(); for ( std::vector< OUString >::const_iterator it = rEnds.begin(), end = rEnds.end(); it < end; ++it ) { OString rName = OUStringToOString( *it, RTL_TEXTENCODING_UTF8 ).getStr( ); m_rMarksEnd.push_back( rName ); } rEnds.clear(); } void DocxAttributeOutput::TextFootnote_Impl( const SwFmtFtn& rFootnote ) { const SwEndNoteInfo& rInfo = rFootnote.IsEndNote()? m_rExport.pDoc->GetEndNoteInfo(): m_rExport.pDoc->GetFtnInfo(); // footnote/endnote run properties const SwCharFmt* pCharFmt = rInfo.GetAnchorCharFmt( *m_rExport.pDoc ); OString aStyleId( "style" ); aStyleId += OString::valueOf( sal_Int32( m_rExport.GetId( *pCharFmt ) ) ); m_pSerializer->singleElementNS( XML_w, XML_rStyle, FSNS( XML_w, XML_val ), aStyleId.getStr(), FSEND ); // remember the footnote/endnote to // 1) write the footnoteReference/endnoteReference in EndRunProperties() // 2) be able to dump them all to footnotes.xml/endnotes.xml if ( !rFootnote.IsEndNote() ) m_pFootnotesList->add( rFootnote ); else m_pEndnotesList->add( rFootnote ); } void DocxAttributeOutput::FootnoteEndnoteReference() { sal_Int32 nId; const SwFmtFtn *pFootnote = m_pFootnotesList->getCurrent( nId ); // both cannot be set at the same time - if they are, it's a bug if ( !pFootnote ) pFootnote = m_pEndnotesList->getCurrent( nId ); if ( !pFootnote ) return; sal_Int32 nToken = pFootnote->IsEndNote()? XML_endnoteReference: XML_footnoteReference; // write it if ( pFootnote->GetNumStr().Len() == 0 ) { // autonumbered m_pSerializer->singleElementNS( XML_w, nToken, FSNS( XML_w, XML_id ), ::rtl::OString::valueOf( nId ).getStr(), FSEND ); } else { // not autonumbered m_pSerializer->singleElementNS( XML_w, nToken, FSNS( XML_w, XML_customMarkFollows ), "1", FSNS( XML_w, XML_id ), ::rtl::OString::valueOf( nId ).getStr(), FSEND ); RunText( pFootnote->GetNumStr() ); } } void DocxAttributeOutput::FootnotesEndnotes( bool bFootnotes ) { const FootnotesVector& rVector = bFootnotes? m_pFootnotesList->getVector(): m_pEndnotesList->getVector(); sal_Int32 nBody = bFootnotes? XML_footnotes: XML_endnotes; sal_Int32 nItem = bFootnotes? XML_footnote: XML_endnote; m_pSerializer->startElementNS( XML_w, nBody, FSNS( XML_xmlns, XML_w ), "http://schemas.openxmlformats.org/wordprocessingml/2006/main", FSEND ); sal_Int32 nIndex = 0; // separator m_pSerializer->startElementNS( XML_w, nItem, FSNS( XML_w, XML_id ), OString::valueOf( nIndex++ ).getStr(), FSNS( XML_w, XML_type ), "separator", FSEND ); m_pSerializer->startElementNS( XML_w, XML_p, FSEND ); m_pSerializer->startElementNS( XML_w, XML_r, FSEND ); m_pSerializer->singleElementNS( XML_w, XML_separator, FSEND ); m_pSerializer->endElementNS( XML_w, XML_r ); m_pSerializer->endElementNS( XML_w, XML_p ); m_pSerializer->endElementNS( XML_w, nItem ); // separator m_pSerializer->startElementNS( XML_w, nItem, FSNS( XML_w, XML_id ), OString::valueOf( nIndex++ ).getStr(), FSNS( XML_w, XML_type ), "continuationSeparator", FSEND ); m_pSerializer->startElementNS( XML_w, XML_p, FSEND ); m_pSerializer->startElementNS( XML_w, XML_r, FSEND ); m_pSerializer->singleElementNS( XML_w, XML_continuationSeparator, FSEND ); m_pSerializer->endElementNS( XML_w, XML_r ); m_pSerializer->endElementNS( XML_w, XML_p ); m_pSerializer->endElementNS( XML_w, nItem ); // footnotes/endnotes themselves for ( FootnotesVector::const_iterator i = rVector.begin(); i != rVector.end(); ++i, ++nIndex ) { m_pSerializer->startElementNS( XML_w, nItem, FSNS( XML_w, XML_id ), OString::valueOf( nIndex ).getStr(), FSEND ); const SwNodeIndex* pIndex = (*i)->GetTxtFtn()->GetStartNode(); m_rExport.WriteSpecialText( pIndex->GetIndex() + 1, pIndex->GetNode().EndOfSectionIndex(), bFootnotes? TXT_FTN: TXT_EDN ); m_pSerializer->endElementNS( XML_w, nItem ); } m_pSerializer->endElementNS( XML_w, nBody ); } void DocxAttributeOutput::ParaLineSpacing_Impl( short nSpace, short /*nMulti*/ ) { if ( !m_pSpacingAttrList ) m_pSpacingAttrList = m_pSerializer->createAttrList(); if ( nSpace < 0 ) { m_pSpacingAttrList->add( FSNS( XML_w, XML_lineRule ), "exact" ); m_pSpacingAttrList->add( FSNS( XML_w, XML_line ), OString::valueOf( sal_Int32( -nSpace ) ) ); } else if ( nSpace > 0 ) { m_pSpacingAttrList->add( FSNS( XML_w, XML_lineRule ), "atLeast" ); m_pSpacingAttrList->add( FSNS( XML_w, XML_line ), OString::valueOf( sal_Int32( nSpace ) ) ); } else m_pSpacingAttrList->add( FSNS( XML_w, XML_lineRule ), "auto" ); } void DocxAttributeOutput::ParaAdjust( const SvxAdjustItem& rAdjust ) { const char *pAdjustString; switch ( rAdjust.GetAdjust() ) { case SVX_ADJUST_LEFT: pAdjustString = "left"; break; case SVX_ADJUST_RIGHT: pAdjustString = "right"; break; case SVX_ADJUST_BLOCKLINE: case SVX_ADJUST_BLOCK: pAdjustString = "both"; break; case SVX_ADJUST_CENTER: pAdjustString = "center"; break; default: return; // not supported attribute } m_pSerializer->singleElementNS( XML_w, XML_jc, FSNS( XML_w, XML_val ), pAdjustString, FSEND ); } void DocxAttributeOutput::ParaSplit( const SvxFmtSplitItem& rSplit ) { if (rSplit.GetValue()) m_pSerializer->singleElementNS( XML_w, XML_keepLines, FSNS( XML_w, XML_val ), "off", FSEND ); else m_pSerializer->singleElementNS( XML_w, XML_keepLines, FSEND ); } void DocxAttributeOutput::ParaWidows( const SvxWidowsItem& rWidows ) { if (rWidows.GetValue()) m_pSerializer->singleElementNS( XML_w, XML_widowControl, FSEND ); else m_pSerializer->singleElementNS( XML_w, XML_widowControl, FSNS( XML_w, XML_val ), "off", FSEND ); } static void impl_WriteTabElement( FSHelperPtr pSerializer, const SvxTabStop& rTab, long nCurrentLeft ) { FastAttributeList *pTabElementAttrList = pSerializer->createAttrList(); switch (rTab.GetAdjustment()) { case SVX_TAB_ADJUST_RIGHT: pTabElementAttrList->add( FSNS( XML_w, XML_val ), OString( (sal_Char *)"right") ); break; case SVX_TAB_ADJUST_DECIMAL: pTabElementAttrList->add( FSNS( XML_w, XML_val ), OString( (sal_Char *)"decimal") ); break; case SVX_TAB_ADJUST_CENTER: pTabElementAttrList->add( FSNS( XML_w, XML_val ), OString( (sal_Char *)"center") ); break; case SVX_TAB_ADJUST_DEFAULT: case SVX_TAB_ADJUST_LEFT: default: pTabElementAttrList->add( FSNS( XML_w, XML_val ), OString( (sal_Char *)"left") ); break; } pTabElementAttrList->add( FSNS( XML_w, XML_pos ), OString::valueOf( rTab.GetTabPos() + nCurrentLeft ) ); sal_Unicode cFillChar = rTab.GetFill(); if (sal_Unicode('.') == cFillChar ) pTabElementAttrList->add( FSNS( XML_w, XML_leader ), OString( (sal_Char *) "dot" ) ); else if ( sal_Unicode('-') == cFillChar ) pTabElementAttrList->add( FSNS( XML_w, XML_leader ), OString( (sal_Char *) "hyphen" ) ); else if ( sal_Unicode(0xB7) == cFillChar ) // middle dot pTabElementAttrList->add( FSNS( XML_w, XML_leader ), OString( (sal_Char *) "middleDot" ) ); else if ( sal_Unicode('_') == cFillChar ) pTabElementAttrList->add( FSNS( XML_w, XML_leader ), OString( (sal_Char *) "underscore" ) ); else pTabElementAttrList->add( FSNS( XML_w, XML_leader ), OString( (sal_Char *) "none" ) ); pSerializer->singleElementNS( XML_w, XML_tab, pTabElementAttrList ); } void DocxAttributeOutput::ParaTabStop( const SvxTabStopItem& rTabStop ) { const SfxPoolItem* pLR = m_rExport.HasItem( RES_LR_SPACE ); long nCurrentLeft = pLR ? ((const SvxLRSpaceItem*)pLR)->GetTxtLeft() : 0; m_pSerializer->startElementNS( XML_w, XML_tabs, FSEND ); sal_uInt16 nCount = rTabStop.Count(); for (sal_uInt16 i = 0; i < nCount; i++ ) impl_WriteTabElement( m_pSerializer, rTabStop[i], nCurrentLeft ); m_pSerializer->endElementNS( XML_w, XML_tabs ); } void DocxAttributeOutput::ParaHyphenZone( const SvxHyphenZoneItem& rHyphenZone ) { m_pSerializer->singleElementNS( XML_w, XML_suppressAutoHyphens, FSNS( XML_w, XML_val ), rHyphenZone.IsHyphen( ) ? "false" : "true" , FSEND ); } void DocxAttributeOutput::ParaNumRule_Impl( const SwTxtNode* /*pTxtNd*/, sal_Int32 nLvl, sal_Int32 nNumId ) { if ( USHRT_MAX != nNumId && 0 != nNumId ) { m_pSerializer->startElementNS( XML_w, XML_numPr, FSEND ); m_pSerializer->singleElementNS( XML_w, XML_ilvl, FSNS( XML_w, XML_val ), OString::valueOf( sal_Int32( nLvl )).getStr(), FSEND ); m_pSerializer->singleElementNS( XML_w, XML_numId, FSNS( XML_w, XML_val ), OString::valueOf( sal_Int32( nNumId )).getStr(), FSEND ); m_pSerializer->endElementNS( XML_w, XML_numPr ); } } void DocxAttributeOutput::ParaScriptSpace( const SfxBoolItem& rScriptSpace ) { sal_uInt16 nXmlElement = 0; switch ( rScriptSpace.Which( ) ) { case RES_PARATR_SCRIPTSPACE: nXmlElement = XML_autoSpaceDE; break; case RES_PARATR_HANGINGPUNCTUATION: nXmlElement = XML_overflowPunct; break; case RES_PARATR_FORBIDDEN_RULES: nXmlElement = XML_kinsoku; break; } if ( nXmlElement ) { m_pSerializer->singleElementNS( XML_w, nXmlElement, FSNS( XML_w, XML_val ), rScriptSpace.GetValue( ) ? "true": "false", FSEND ); } } void DocxAttributeOutput::ParaVerticalAlign( const SvxParaVertAlignItem& rAlign ) { const char *pAlignString; switch ( rAlign.GetValue() ) { case SvxParaVertAlignItem::BASELINE: pAlignString = "baseline"; break; case SvxParaVertAlignItem::TOP: pAlignString = "top"; break; case SvxParaVertAlignItem::CENTER: pAlignString = "center"; break; case SvxParaVertAlignItem::BOTTOM: pAlignString = "bottom"; break; case SvxParaVertAlignItem::AUTOMATIC: pAlignString = "auto"; break; default: return; // not supported attribute } m_pSerializer->singleElementNS( XML_w, XML_textAlignment, FSNS( XML_w, XML_val ), pAlignString, FSEND ); } void DocxAttributeOutput::ParaSnapToGrid( const SvxParaGridItem& rGrid ) { m_pSerializer->singleElementNS( XML_w, XML_snapToGrid, FSNS( XML_w, XML_val ), rGrid.GetValue( ) ? "true": "false", FSEND ); } void DocxAttributeOutput::FormatFrameSize( const SwFmtFrmSize& rSize ) { if ( m_rExport.bOutFlyFrmAttrs ) { #if OSL_DEBUG_LEVEL > 0 OSL_TRACE( "TODO DocxAttributeOutput::FormatFrameSize() - Fly frames\n" ); #endif } else if ( m_rExport.bOutPageDescs ) { FastAttributeList *attrList = m_pSerializer->createAttrList( ); if ( m_rExport.pAktPageDesc->GetLandscape( ) ) attrList->add( FSNS( XML_w, XML_orient ), "landscape" ); attrList->add( FSNS( XML_w, XML_w ), OString::valueOf( rSize.GetWidth( ) ) ); attrList->add( FSNS( XML_w, XML_h ), OString::valueOf( rSize.GetHeight( ) ) ); XFastAttributeListRef xAttrList( attrList ); attrList = NULL; m_pSerializer->singleElementNS( XML_w, XML_pgSz, xAttrList ); } } void DocxAttributeOutput::FormatPaperBin( const SvxPaperBinItem& ) { #if OSL_DEBUG_LEVEL > 0 OSL_TRACE( "TODO DocxAttributeOutput::FormatPaperBin()\n" ); #endif } void DocxAttributeOutput::FormatLRSpace( const SvxLRSpaceItem& rLRSpace ) { if ( m_rExport.bOutFlyFrmAttrs ) { #if OSL_DEBUG_LEVEL > 0 OSL_TRACE( "DocxAttributeOutput::FormatLRSpace() - Fly frames\n" ); #endif } else if ( m_rExport.bOutPageDescs ) { if ( !m_pSpacingAttrList ) m_pSpacingAttrList = m_pSerializer->createAttrList(); sal_uInt16 nLDist, nRDist; const SfxPoolItem* pItem = m_rExport.HasItem( RES_BOX ); if ( pItem ) { nRDist = ((SvxBoxItem*)pItem)->CalcLineSpace( BOX_LINE_LEFT ); nLDist = ((SvxBoxItem*)pItem)->CalcLineSpace( BOX_LINE_RIGHT ); } else nLDist = nRDist = 0; nLDist = nLDist + (sal_uInt16)rLRSpace.GetLeft(); nRDist = nRDist + (sal_uInt16)rLRSpace.GetRight(); m_pSpacingAttrList->add( FSNS( XML_w, XML_left ), OString::valueOf( sal_Int32( nLDist ) ) ); m_pSpacingAttrList->add( FSNS( XML_w, XML_right ), OString::valueOf( sal_Int32( nRDist ) ) ); } else { FastAttributeList *pLRSpaceAttrList = m_pSerializer->createAttrList(); pLRSpaceAttrList->add( FSNS( XML_w, XML_left ), OString::valueOf( (sal_Int32) rLRSpace.GetTxtLeft() ) ); pLRSpaceAttrList->add( FSNS( XML_w, XML_right ), OString::valueOf( (sal_Int32) rLRSpace.GetRight() ) ); sal_Int32 nFirstLineAdjustment = rLRSpace.GetTxtFirstLineOfst(); if (nFirstLineAdjustment > 0) pLRSpaceAttrList->add( FSNS( XML_w, XML_firstLine ), OString::valueOf( nFirstLineAdjustment ) ); else pLRSpaceAttrList->add( FSNS( XML_w, XML_hanging ), OString::valueOf( - nFirstLineAdjustment ) ); m_pSerializer->singleElementNS( XML_w, XML_ind, pLRSpaceAttrList ); } } void DocxAttributeOutput::FormatULSpace( const SvxULSpaceItem& rULSpace ) { if (!m_pSpacingAttrList) m_pSpacingAttrList = m_pSerializer->createAttrList(); if ( m_rExport.bOutFlyFrmAttrs ) { } else if (m_rExport.bOutPageDescs ) { ASSERT( m_rExport.GetCurItemSet(), "Impossible" ); if ( !m_rExport.GetCurItemSet() ) return; HdFtDistanceGlue aDistances( *m_rExport.GetCurItemSet() ); if ( aDistances.HasHeader() ) { // Header top m_pSpacingAttrList->add( FSNS( XML_w, XML_header ), OString::valueOf( sal_Int32( aDistances.dyaHdrTop ) ) ); } // Page top m_pSpacingAttrList->add( FSNS( XML_w, XML_top ), OString::valueOf( sal_Int32( aDistances.dyaTop ) ) ); if ( aDistances.HasFooter() ) { // Footer bottom m_pSpacingAttrList->add( FSNS( XML_w, XML_footer ), OString::valueOf( sal_Int32( aDistances.dyaHdrBottom ) ) ); } // Page Bottom m_pSpacingAttrList->add( FSNS( XML_w, XML_bottom ), OString::valueOf( sal_Int32( aDistances.dyaBottom ) ) ); } else { m_pSpacingAttrList->add( FSNS( XML_w, XML_before ), OString::valueOf( (sal_Int32)rULSpace.GetUpper() ) ); m_pSpacingAttrList->add( FSNS( XML_w, XML_after ), OString::valueOf( (sal_Int32)rULSpace.GetLower() ) ); } } void DocxAttributeOutput::FormatSurround( const SwFmtSurround& ) { #if OSL_DEBUG_LEVEL > 0 OSL_TRACE( "TODO DocxAttributeOutput::FormatSurround()\n" ); #endif } void DocxAttributeOutput::FormatVertOrientation( const SwFmtVertOrient& ) { #if OSL_DEBUG_LEVEL > 0 OSL_TRACE( "TODO DocxAttributeOutput::FormatVertOrientation()\n" ); #endif } void DocxAttributeOutput::FormatHorizOrientation( const SwFmtHoriOrient& ) { #if OSL_DEBUG_LEVEL > 0 OSL_TRACE( "TODO DocxAttributeOutput::FormatHorizOrientation()\n" ); #endif } void DocxAttributeOutput::FormatAnchor( const SwFmtAnchor& ) { #if OSL_DEBUG_LEVEL > 0 OSL_TRACE( "TODO DocxAttributeOutput::FormatAnchor()\n" ); #endif } void DocxAttributeOutput::FormatBackground( const SvxBrushItem& rBrush ) { if ( !m_rExport.bOutPageDescs ) { OString sColor = impl_ConvertColor( rBrush.GetColor( ) ); m_pSerializer->singleElementNS( XML_w, XML_shd, FSNS( XML_w, XML_fill ), sColor.getStr( ), FSEND ); } #if OSL_DEBUG_LEVEL > 0 OSL_TRACE( "TODO DocxAttributeOutput::FormatBackground()\n" ); #endif } void DocxAttributeOutput::FormatBox( const SvxBoxItem& rBox ) { if ( !m_bOpenedSectPr ) { // Normally open the borders tag for paragraphs m_pSerializer->startElementNS( XML_w, XML_pBdr, FSEND ); } impl_pageBorders( m_pSerializer, rBox ); if ( m_bOpenedSectPr ) { // Special handling for pgBorder m_pSerializer->mergeTopMarks( sax_fastparser::MERGE_MARKS_PREPEND ); m_pSerializer->mergeTopMarks( ); } else { // Normally close the borders tag for paragraphs m_pSerializer->endElementNS( XML_w, XML_pBdr ); } } void DocxAttributeOutput::FormatColumns_Impl( sal_uInt16 nCols, const SwFmtCol& rCol, bool bEven, SwTwips nPageSize ) { // Get the columns attributes FastAttributeList *pColsAttrList = m_pSerializer->createAttrList(); pColsAttrList->add( FSNS( XML_w, XML_num ), OString::valueOf( sal_Int32( nCols ) ). getStr( ) ); const char* pEquals = "false"; if ( bEven ) { sal_uInt16 nWidth = rCol.GetGutterWidth( true ); pColsAttrList->add( FSNS( XML_w, XML_space ), OString::valueOf( sal_Int32( nWidth ) ).getStr( ) ); pEquals = "true"; } pColsAttrList->add( FSNS( XML_w, XML_equalWidth ), pEquals ); bool bHasSep = COLADJ_NONE == rCol.GetLineAdj( ); pColsAttrList->add( FSNS( XML_w, XML_sep ), bHasSep ? "true" : "false" ); // Write the element m_pSerializer->startElementNS( XML_w, XML_cols, pColsAttrList ); // Write the columns width if non-equals const SwColumns & rColumns = rCol.GetColumns( ); if ( !bEven ) { for ( sal_uInt16 n = 0; n < nCols; ++n ) { FastAttributeList *pColAttrList = m_pSerializer->createAttrList(); sal_uInt16 nWidth = rCol.CalcPrtColWidth( n, ( sal_uInt16 ) nPageSize ); pColAttrList->add( FSNS( XML_w, XML_w ), OString::valueOf( sal_Int32( nWidth ) ).getStr( ) ); if ( n + 1 != nCols ) { sal_uInt16 nSpacing = rColumns[n]->GetRight( ) + rColumns[n + 1]->GetLeft( ); pColAttrList->add( FSNS( XML_w, XML_space ), OString::valueOf( sal_Int32( nSpacing ) ).getStr( ) ); } m_pSerializer->singleElementNS( XML_w, XML_col, pColAttrList ); } } m_pSerializer->endElementNS( XML_w, XML_cols ); } void DocxAttributeOutput::FormatKeep( const SvxFmtKeepItem& ) { m_pSerializer->singleElementNS( XML_w, XML_keepNext, FSEND ); } void DocxAttributeOutput::FormatTextGrid( const SwTextGridItem& ) { OSL_TRACE( "TODO DocxAttributeOutput::FormatTextGrid()\n" ); } void DocxAttributeOutput::FormatLineNumbering( const SwFmtLineNumber& rNumbering ) { if ( !rNumbering.IsCount( ) ) m_pSerializer->singleElementNS( XML_w, XML_suppressLineNumbers, FSEND ); } void DocxAttributeOutput::FormatFrameDirection( const SvxFrameDirectionItem& rDirection ) { OString sTextFlow; bool bBiDi = false; short nDir = rDirection.GetValue(); if ( nDir == FRMDIR_ENVIRONMENT ) nDir = GetExport( ).GetDefaultFrameDirection( ); switch ( nDir ) { default: case FRMDIR_HORI_LEFT_TOP: sTextFlow = OString( "lrTb" ); break; case FRMDIR_HORI_RIGHT_TOP: sTextFlow = OString( "lrTb" ); bBiDi = true; break; case FRMDIR_VERT_TOP_LEFT: // many things but not this one case FRMDIR_VERT_TOP_RIGHT: sTextFlow = OString( "tbRl" ); break; } if ( m_rExport.bOutPageDescs ) { m_pSerializer->singleElementNS( XML_w, XML_textDirection, FSNS( XML_w, XML_val ), sTextFlow.getStr( ), FSEND ); if ( bBiDi ) m_pSerializer->singleElementNS( XML_w, XML_bidi, FSEND ); } else if ( !m_rExport.bOutFlyFrmAttrs ) { if ( bBiDi ) m_pSerializer->singleElementNS( XML_w, XML_bidi, FSEND ); } } DocxAttributeOutput::DocxAttributeOutput( DocxExport &rExport, FSHelperPtr pSerializer, oox::drawingml::DrawingML* pDrawingML ) : m_rExport( rExport ), m_pSerializer( pSerializer ), m_rDrawingML( *pDrawingML ), m_pFontsAttrList( NULL ), m_pEastAsianLayoutAttrList( NULL ), m_pCharLangAttrList( NULL ), m_pSpacingAttrList( NULL ), m_pHyperlinkAttrList( NULL ), m_pFootnotesList( new ::docx::FootnotesList() ), m_pEndnotesList( new ::docx::FootnotesList() ), m_pSectionInfo( NULL ), m_pRedlineData( NULL ), m_nRedlineId( 0 ), m_bOpenedSectPr( false ), m_sFieldBkm( ), m_nNextMarkId( 0 ), m_bPostitStart(false), m_bPostitEnd(false), m_pTableWrt( NULL ), m_bTableCellOpen( false ), m_nTableDepth( 0 ), m_bParagraphOpened( false ), m_nColBreakStatus( COLBRK_NONE ) { } DocxAttributeOutput::~DocxAttributeOutput() { delete m_pFontsAttrList, m_pFontsAttrList = NULL; delete m_pEastAsianLayoutAttrList, m_pEastAsianLayoutAttrList = NULL; delete m_pCharLangAttrList, m_pCharLangAttrList = NULL; delete m_pSpacingAttrList, m_pSpacingAttrList = NULL; delete m_pHyperlinkAttrList, m_pHyperlinkAttrList = NULL; delete m_pFootnotesList, m_pFootnotesList = NULL; delete m_pEndnotesList, m_pEndnotesList = NULL; delete m_pTableWrt, m_pTableWrt = NULL; } MSWordExportBase& DocxAttributeOutput::GetExport() { return m_rExport; } bool DocxAttributeOutput::HasFootnotes() { return !m_pFootnotesList->isEmpty(); } bool DocxAttributeOutput::HasEndnotes() { return !m_pEndnotesList->isEmpty(); }
33.464886
213
0.637819
jimjag
a87ede10a7fddd75d660071f5973acce06b32bd8
4,892
cpp
C++
Source/main.cpp
RPKQ/OpenGL_scratchUp
cbe0268d6bb86bc0de49fafdcf078e5b85395964
[ "CC-BY-3.0" ]
null
null
null
Source/main.cpp
RPKQ/OpenGL_scratchUp
cbe0268d6bb86bc0de49fafdcf078e5b85395964
[ "CC-BY-3.0" ]
null
null
null
Source/main.cpp
RPKQ/OpenGL_scratchUp
cbe0268d6bb86bc0de49fafdcf078e5b85395964
[ "CC-BY-3.0" ]
null
null
null
#include "Program.h" #include "AssimpModel.h" #include "Camera.h" #include "../Source/GLIncludes.h" using namespace glm; using namespace std; enum { MENU_TIMER_START, MENU_TIMER_STOP, MENU_EXIT, MENU_SHADER_NORMAL, MENU_SHADER_LIGHTING, MENU_SHADER_TEXTURE, MENU_SCENE_SPONZA, MENU_SCENE_EMPIRE}; const int windowW = 1024, windowH = 768; glm::mat4 modelMat; glm::mat4 perspectMat; Program* programNormal; Program* programTexture; Program* programLight; Program* program; AssimpModel* model; AssimpModel* model_sponza; AssimpModel* model_lostEmpire; Camera* cam; GLubyte timer_cnt = 0; bool timer_enabled = true; unsigned int timer_speed = 16; void DisplayFunc() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); program->use(); program->setMat4("pvMat", perspectMat * cam->getViewMat()); program->setMat4("modelMat", glm::mat4(1.0)); program->setVec3("lightPos", glm::vec3(100000.0, 100000.0, 200000.0)); program->setBool("useTex", true); model->draw(); glutSwapBuffers(); } void KeyboardFunc(unsigned char key, int x, int y) { switch (key) { case 'w': cam->moveLocal(Camera::FRONT); break; case 's': cam->moveLocal(Camera::BACK); break; case 'a': cam->moveLocal(Camera::LEFT); break; case 'd': cam->moveLocal(Camera::RIGHT); break; case 'z': cam->moveLocal(Camera::UP); break; case 'x': cam->moveLocal(Camera::DOWN); break; default: break; } } void MotionFunc(int moveX, int moveY) { cam->rotateWithMouse(moveX, moveY); } void MouseFunc(int button, int state, int x, int y) { if (state == GLUT_UP) { cam->endOfRotate(); } } void TimerFunc(int val) { timer_cnt++; glutPostRedisplay(); if (timer_enabled) { glutTimerFunc(timer_speed, TimerFunc, val); } } void ReshapeFunc(int width, int height) { glViewport(0, 0, width, height); float viewportAspect = (float)width / (float)height; perspectMat = glm::perspective(glm::radians(60.0f), viewportAspect, 0.1f, 1500.0f); } void InitCallbackFuncs() { glutDisplayFunc(DisplayFunc); glutKeyboardFunc(KeyboardFunc); glutMotionFunc(MotionFunc); glutMouseFunc(MouseFunc); glutTimerFunc(timer_speed, TimerFunc, 0); glutReshapeFunc(ReshapeFunc); } void MenuFunc(int id) { switch (id) { case MENU_TIMER_START: if (!timer_enabled) { timer_enabled = true; glutTimerFunc(timer_speed, TimerFunc, 0); } break; case MENU_TIMER_STOP: timer_enabled = false; break; case MENU_EXIT: exit(0); break; case MENU_SHADER_NORMAL: program = programNormal; break; case MENU_SHADER_TEXTURE: program = programTexture; break; case MENU_SHADER_LIGHTING: program = programLight; break; case MENU_SCENE_SPONZA: model = model_sponza; cam->setMoveSpeed(5.0); break; case MENU_SCENE_EMPIRE: model = model_lostEmpire; cam->setMoveSpeed(1.0); break; default: break; } } void InitMenu() { int menu_main = glutCreateMenu(MenuFunc); int menu_timer = glutCreateMenu(MenuFunc); int menu_shader = glutCreateMenu(MenuFunc); int menu_scene = glutCreateMenu(MenuFunc); glutSetMenu(menu_main); glutAddSubMenu("Timer", menu_timer); glutAddSubMenu("Shader", menu_shader); glutAddSubMenu("Scene", menu_scene); glutAddMenuEntry("Exit", MENU_EXIT); glutSetMenu(menu_timer); glutAddMenuEntry("Start", MENU_TIMER_START); glutAddMenuEntry("Stop", MENU_TIMER_STOP); glutSetMenu(menu_shader); glutAddMenuEntry("normal", MENU_SHADER_NORMAL); glutAddMenuEntry("texture", MENU_SHADER_TEXTURE); glutAddMenuEntry("lighting", MENU_SHADER_LIGHTING); glutSetMenu(menu_scene); glutAddMenuEntry("lost empire", MENU_SCENE_EMPIRE); glutAddMenuEntry("sponza", MENU_SCENE_SPONZA); glutSetMenu(menu_main); glutAttachMenu(GLUT_RIGHT_BUTTON); } void InitObjects() { // setup camera cam = new Camera(vec3(0.0f, 15.0f, 20.0f), vec3(0.0f, 15.0f, 0.0f), vec3(0.0f, 1.0f, 0.0f)); // setup program programTexture = new Program("vs.vs.glsl", "fs.fs.glsl"); programLight = new Program("vs.vs.glsl", "light.fs.glsl"); programNormal = new Program("vs.vs.glsl", "normal.fs.glsl"); program = programTexture; // load models model_sponza = new AssimpModel("sponza.obj"); model_lostEmpire = new AssimpModel("lost_empire.obj"); model = model_sponza; } void Init() { // Init Window and GLUT glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH); glutInitWindowSize(windowW, windowH); glutInitWindowPosition(100, 100); glutCreateWindow("Window"); // Must be done after glut is initialized! GLenum res = glewInit(); if (res != GLEW_OK) { fprintf(stderr, "Error: '%s'\n", glewGetErrorString(res)); system("pause"); exit(1); } glClearColor(1.0, 1.0, 1.0, 0.0); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); InitMenu(); InitObjects(); InitCallbackFuncs(); // init reshape window ReshapeFunc(windowW, windowH); } int main(int argc, char *argv[]) { glutInit(&argc, argv); Init(); glutMainLoop(); return 0; }
20.817021
93
0.721382
RPKQ
a87f9995346bdbc64b7a057d0247ff93196ea47e
3,538
cc
C++
src/artm_tests/rpcz_canary_test.cc
marinadudarenko/bigartm
c7072663581c59e970ef165a577dc4969810a19d
[ "Apache-2.0" ]
null
null
null
src/artm_tests/rpcz_canary_test.cc
marinadudarenko/bigartm
c7072663581c59e970ef165a577dc4969810a19d
[ "Apache-2.0" ]
null
null
null
src/artm_tests/rpcz_canary_test.cc
marinadudarenko/bigartm
c7072663581c59e970ef165a577dc4969810a19d
[ "Apache-2.0" ]
null
null
null
// Copyright 2014, Additive Regularization of Topic Models. #include <memory> #include "boost/thread.hpp" #include "gtest/gtest.h" #include "rpcz/application.hpp" #include "rpcz/server.hpp" #include "rpcz/rpc.hpp" #include "artm/core/zmq_context.h" #include "artm_tests/rpcz_canary_service.pb.h" #include "artm_tests/rpcz_canary_service.rpcz.h" // To generate protobuf files: // copy utils/protoc-2.5.0-win32/protoc.exe to /src folder // cd to /src folder and execute the following: // .\protoc.exe --cpp_out=. --rpcz_plugin_out=. .\artm_tests\rpcz_canary_service.proto const std::string error_message = "Some error had happened"; const int error_code = -999; class SearchServiceImpl : public SearchService { virtual void Search( const SearchRequest& request, rpcz::reply<SearchResponse> reply) { if (request.query() == "make_error") { reply.Error(error_code, error_message); } else { SearchResponse response; response.add_results("result1 for " + request.query()); response.add_results("this is result2"); reply.send(response); } } }; std::unique_ptr<rpcz::application> server_application; void RpczServerThreadFunction() { SearchServiceImpl search_service; rpcz::application::options options(3); options.zeromq_context = ::artm::core::ZmqContext::singleton().get(); server_application.reset(new rpcz::application(options)); rpcz::server server(*server_application); server.register_service(&search_service); server.bind("tcp://*:5555"); server_application->run(); } void ConnectAndQuery(int timeout = -1L, bool make_error = false) { rpcz::application::options options(3); options.zeromq_context = ::artm::core::ZmqContext::singleton().get(); rpcz::application client_application(options); SearchService_Stub search_service_proxy( client_application.create_rpc_channel("tcp://localhost:5555"), true); SearchRequest request; SearchResponse response; try { request.set_page_number(10); if (make_error) { request.set_query("make_error"); } else { request.set_query("my query"); } search_service_proxy.Search(request, &response, timeout); ASSERT_EQ(response.results_size(), 2); ASSERT_EQ(response.results(0), "result1 for my query"); ASSERT_EQ(response.results(1), "this is result2"); } catch(const ::rpcz::rpc_error& error) { if (timeout != -1L) { ASSERT_EQ(error.get_status(), rpcz::status::DEADLINE_EXCEEDED); } else { ASSERT_TRUE(make_error); if (make_error) { ASSERT_EQ(error.get_application_error_code(), error_code); ASSERT_EQ(error.get_error_message(), error_message); } } } } // artm_tests.exe --gtest_filter=Rpcz.Canary TEST(Rpcz, Canary) { boost::thread t(&RpczServerThreadFunction); ConnectAndQuery(); ASSERT_TRUE(server_application != nullptr); server_application->terminate(); t.join(); server_application.reset(); } // artm_tests.exe --gtest_filter=Rpcz.Timeout TEST(Rpcz, Timeout) { // Timeout test does not create a server to connect to, and sets the timeout for the first RPCZ call. // The expectation of the test is to get an exception with rpcz::status::DEADLINE_EXCEEDED being set. ConnectAndQuery(10); } // artm_tests.exe --gtest_filter=Rpcz.ErrorHandling TEST(Rpcz, ErrorHandling) { boost::thread t(&RpczServerThreadFunction); ConnectAndQuery(-1L, true); ASSERT_TRUE(server_application != nullptr); server_application->terminate(); t.join(); server_application.reset(); }
29.239669
103
0.716507
marinadudarenko
a882177b8642f430d5802c0b9a63584f4ae61854
2,089
cpp
C++
test/k2node_problematic_input_tests2.cpp
CristobalM/c-k2tree-dyn
8e9d12b2ad72efaba750e7600f82025c7e4082ee
[ "MIT" ]
2
2021-11-13T03:46:39.000Z
2022-01-09T17:42:03.000Z
test/k2node_problematic_input_tests2.cpp
CristobalM/c-k2tree-dyn
8e9d12b2ad72efaba750e7600f82025c7e4082ee
[ "MIT" ]
null
null
null
test/k2node_problematic_input_tests2.cpp
CristobalM/c-k2tree-dyn
8e9d12b2ad72efaba750e7600f82025c7e4082ee
[ "MIT" ]
null
null
null
// // Created by cristobal on 9/24/21. // #include <gtest/gtest.h> extern "C" { #include <k2node.h> } using vp_t = std::vector<std::pair<unsigned long, unsigned long>>; TEST(k2node_problematic_input_tests2, full_scan_test) { struct k2node *root_node = create_k2node(); struct k2qstate st; TREE_DEPTH_T treedepth = 64; TREE_DEPTH_T cutdepth = 10; init_k2qstate(&st, treedepth, 256, cutdepth); unsigned long col = 710230858; unsigned long row = 4951110; int already_exists; k2node_insert_point(root_node, col, row, &st, &already_exists); struct k2node_lazy_handler_naive_scan_t lh; k2node_naive_scan_points_lazy_init(root_node, &st, &lh); std::vector<std::pair<unsigned long, unsigned long>> results_lazy; for (;;) { int has_next; k2node_naive_scan_points_lazy_has_next(&lh, &has_next); if (!has_next) break; pair2dl_t result; k2node_naive_scan_points_lazy_next(&lh, &result); results_lazy.emplace_back(result.col, result.row); } ASSERT_EQ(results_lazy.size(), 1); ASSERT_EQ(results_lazy[0].first, col); ASSERT_EQ(results_lazy[0].second, row); free_rec_k2node(root_node, 0, st.cut_depth); clean_k2qstate(&st); } TEST(k2node_problematic_input_tests2, band_row_scan) { struct k2node *root_node = create_k2node(); struct k2qstate st; TREE_DEPTH_T treedepth = 64; TREE_DEPTH_T cutdepth = 10; init_k2qstate(&st, treedepth, 256, cutdepth); unsigned long col = 710230858; unsigned long row = 4951110; int already_exists; k2node_insert_point(root_node, col, row, &st, &already_exists); struct k2node_lazy_handler_report_band_t lh; k2node_report_row_lazy_init(&lh, root_node, &st, row); std::vector<unsigned long> results_lazy; for (;;) { int has_next; k2node_report_band_has_next(&lh, &has_next); if (!has_next) break; uint64_t result; k2node_report_band_next(&lh, &result); results_lazy.push_back(result); } ASSERT_EQ(results_lazy.size(), 1); ASSERT_EQ(results_lazy[0], col); free_rec_k2node(root_node, 0, st.cut_depth); clean_k2qstate(&st); }
24.869048
68
0.721876
CristobalM
a883b658b1e81dc4e10753441051c4208c03e1ba
4,332
cpp
C++
tests/pimpl_tests/pimpl_basic_header_only/heap_allocations.cpp
lubkoll/friendly-type-erasure
719830233a8652ccf18164653b466b0054a617f6
[ "MIT" ]
null
null
null
tests/pimpl_tests/pimpl_basic_header_only/heap_allocations.cpp
lubkoll/friendly-type-erasure
719830233a8652ccf18164653b466b0054a617f6
[ "MIT" ]
22
2016-08-03T16:51:10.000Z
2016-11-23T20:53:03.000Z
tests/pimpl_tests/pimpl_basic_header_only/heap_allocations.cpp
lubkoll/friendly-type-erasure
719830233a8652ccf18164653b466b0054a617f6
[ "MIT" ]
null
null
null
//#include <gtest/gtest.h> //#include "interface.hh" //#include "../mock_fooable.hh" //#include "../util.hh" //using Fooable = Basic::Fooable; //using Mock::MockFooable; //TEST( TestBasicFooable_HeapAllocations, Empty ) //{ // auto expected_heap_allocations = 0u; // CHECK_HEAP_ALLOC( Fooable fooable, // expected_heap_allocations ); // CHECK_HEAP_ALLOC( Fooable copy(fooable), // expected_heap_allocations ); // CHECK_HEAP_ALLOC( Fooable move( std::move(fooable) ), // expected_heap_allocations ); // CHECK_HEAP_ALLOC( Fooable copy_assign; // copy_assign = move, // expected_heap_allocations ); // CHECK_HEAP_ALLOC( Fooable move_assign; // move_assign = std::move(copy_assign), // expected_heap_allocations ); //} //TEST( TestBasicFooable_HeapAllocations, CopyFromValue ) //{ // auto expected_heap_allocations = 1u; // MockFooable mock_fooable; // CHECK_HEAP_ALLOC( Fooable fooable( mock_fooable ), // expected_heap_allocations ); //} //TEST( TestBasicFooable_HeapAllocations, CopyConstruction ) //{ // auto expected_heap_allocations = 1u; // Fooable fooable = MockFooable(); // CHECK_HEAP_ALLOC( Fooable other( fooable ), // expected_heap_allocations ); //} //TEST( TestBasicFooable_HeapAllocations, CopyFromValueWithReferenceWrapper ) //{ // auto expected_heap_allocations = 1u; // MockFooable mock_fooable; // CHECK_HEAP_ALLOC( Fooable fooable( std::ref(mock_fooable) ), // expected_heap_allocations ); //} //TEST( TestBasicFooable_HeapAllocations, MoveFromValue ) //{ // auto expected_heap_allocations = 1u; // MockFooable mock_fooable; // CHECK_HEAP_ALLOC( Fooable fooable( std::move(mock_fooable) ), // expected_heap_allocations ); //} //TEST( TestBasicFooable_HeapAllocations, MoveConstruction ) //{ // auto expected_heap_allocations = 0u; // Fooable fooable = MockFooable(); // CHECK_HEAP_ALLOC( Fooable other( std::move(fooable) ), // expected_heap_allocations ); //} //TEST( TestBasicFooable_HeapAllocations, MoveFromValueWithReferenceWrapper ) //{ // auto expected_heap_allocations = 1u; // MockFooable mock_fooable; // CHECK_HEAP_ALLOC( Fooable fooable( std::move(std::ref(mock_fooable)) ), // expected_heap_allocations ); //} //TEST( TestBasicFooable_HeapAllocations, CopyAssignFromValue ) //{ // auto expected_heap_allocations = 1u; // MockFooable mock_fooable; // CHECK_HEAP_ALLOC( Fooable fooable; // fooable = mock_fooable, // expected_heap_allocations ); //} //TEST( TestBasicFooable_HeapAllocations, CopyAssignment ) //{ // auto expected_heap_allocations = 1u; // Fooable fooable = MockFooable(); // CHECK_HEAP_ALLOC( Fooable other; // other = fooable, // expected_heap_allocations ); //} //TEST( TestBasicFooable_HeapAllocations, CopyAssignFromValuenWithReferenceWrapper ) //{ // auto expected_heap_allocations = 1u; // MockFooable mock_fooable; // CHECK_HEAP_ALLOC( Fooable fooable; // fooable = std::ref(mock_fooable), // expected_heap_allocations ); //} //TEST( TestBasicFooable_HeapAllocations, MoveAssignFromValue ) //{ // auto expected_heap_allocations = 1u; // MockFooable mock_fooable; // CHECK_HEAP_ALLOC( Fooable fooable; // fooable = std::move(mock_fooable), // expected_heap_allocations ); //} //TEST( TestBasicFooable_HeapAllocations, MoveAssignment ) //{ // auto expected_heap_allocations = 0u; // Fooable fooable = MockFooable(); // CHECK_HEAP_ALLOC( Fooable other; // other = std::move(fooable), // expected_heap_allocations ); //} //TEST( TestBasicFooable_HeapAllocations, MoveAssignFromValueWithReferenceWrapper ) //{ // auto expected_heap_allocations = 1u; // MockFooable mock_fooable; // CHECK_HEAP_ALLOC( Fooable fooable; // fooable = std::move(std::ref(mock_fooable)), // expected_heap_allocations ); //}
29.671233
84
0.638273
lubkoll
a88422596f89658265ad65448671277abd428709
423
hpp
C++
libsamp/libxrpc/xmlrpc-c-1.16.29/include/xmlrpc-c/base64.hpp
olebole/voclient
abeee7783f4e84404a8c3a9646bb57f48988b24a
[ "MIT" ]
2
2019-12-01T15:19:09.000Z
2019-12-02T16:48:42.000Z
libsamp/libxrpc/xmlrpc-c-1.16.29/include/xmlrpc-c/base64.hpp
mjfitzpatrick/voclient
3264c0df294cecc518e5c6a7e6b2aba3f1c76373
[ "MIT" ]
1
2019-11-30T13:48:50.000Z
2019-12-02T19:40:25.000Z
libsamp/libxrpc/xmlrpc-c-1.16.29/include/xmlrpc-c/base64.hpp
mjfitzpatrick/voclient
3264c0df294cecc518e5c6a7e6b2aba3f1c76373
[ "MIT" ]
null
null
null
#ifndef XMLRPC_BASE64_HPP_INCLUDED #define XMLRPC_BASE64_HPP_INCLUDED #include <string> #include <vector> namespace xmlrpc_c { enum newlineCtl {NEWLINE_NO, NEWLINE_YES}; std::string base64FromBytes( std::vector<unsigned char> const& bytes, xmlrpc_c::newlineCtl const newlineCtl = xmlrpc_c::NEWLINE_YES); std::vector<unsigned char> bytesFromBase64(std::string const& base64); } // namespace #endif
16.269231
74
0.754137
olebole
a885f6f314b0365739ff6bfbe9cfb9a4a8394f54
962
hpp
C++
CodeRed/Vulkan/VulkanSwapChain.hpp
LinkClinton/Code-Red
491621144aba559f068c7f91d71e3d0d7c87761e
[ "MIT" ]
34
2019-09-11T09:12:16.000Z
2022-02-13T12:50:25.000Z
CodeRed/Vulkan/VulkanSwapChain.hpp
LinkClinton/Code-Red
491621144aba559f068c7f91d71e3d0d7c87761e
[ "MIT" ]
7
2019-09-22T14:21:26.000Z
2020-03-24T10:36:20.000Z
CodeRed/Vulkan/VulkanSwapChain.hpp
LinkClinton/Code-Red
491621144aba559f068c7f91d71e3d0d7c87761e
[ "MIT" ]
6
2019-10-21T18:05:55.000Z
2021-04-22T05:07:30.000Z
#pragma once #include "../Interface/GpuSwapChain.hpp" #include "VulkanUtility.hpp" #ifdef __ENABLE__VULKAN__ namespace CodeRed { class VulkanSwapChain final : public GpuSwapChain { public: explicit VulkanSwapChain( const std::shared_ptr<GpuLogicalDevice>& device, const std::shared_ptr<GpuCommandQueue>& queue, const WindowInfo& info, const PixelFormat& format, const size_t buffer_count = 2); ~VulkanSwapChain(); void resize(const size_t width, const size_t height) override; void present() override; auto currentBufferIndex() const -> size_t override; auto swapChain() const noexcept -> vk::SwapchainKHR { return mSwapChain; } auto surface() const noexcept -> vk::SurfaceKHR { return mSurface; } private: void initializeSwapChain(); void updateCurrentFrameIndex(); private: vk::SwapchainKHR mSwapChain; vk::SurfaceKHR mSurface; vk::Semaphore mSemaphore; uint32_t mCurrentBufferIndex = 0; }; } #endif
21.863636
76
0.740125
LinkClinton
a888391d77c4bf5c0886e107f0b4b35c0415904b
3,011
hpp
C++
include/jbkernel/IVoidEthernet.hpp
JohnnyB1290/jblib-platform-abstract-jbkernel
6e9e3e26e0ea4cbfdffc5cdde30e64ae78dc82a7
[ "Apache-2.0" ]
null
null
null
include/jbkernel/IVoidEthernet.hpp
JohnnyB1290/jblib-platform-abstract-jbkernel
6e9e3e26e0ea4cbfdffc5cdde30e64ae78dc82a7
[ "Apache-2.0" ]
null
null
null
include/jbkernel/IVoidEthernet.hpp
JohnnyB1290/jblib-platform-abstract-jbkernel
6e9e3e26e0ea4cbfdffc5cdde30e64ae78dc82a7
[ "Apache-2.0" ]
null
null
null
/** * @file * @brief Void Ethernet Interface * * * @note * Copyright © 2019 Evgeniy Ivanov. Contacts: <strelok1290@gmail.com> * All rights reserved. * @note * 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 * @note * 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. * * @note * This file is a part of JB_Lib. */ #ifndef IVOIDETHERNET_HPP_ #define IVOIDETHERNET_HPP_ #include "jbkernel/jb_common.h" #if USE_LWIP #include "lwip/pbuf.h" #endif namespace jblib { namespace jbkernel { typedef enum { PARAMETER_MAC = 0, PARAMETER_TX_UNLOCK, PARAMETER_LINK, PARAMETER_SPEED, PARAMETER_NAME, } IVoidEthernetParameters_t; typedef enum { SPEED_10_M = 0, SPEED_100_M = 1, SPEED_AUTONEG = 2, SPEED_1000_M = 3, }IVoidEthernetSpeed_t; class IVoidEthernet { public: IVoidEthernet(void){} virtual ~IVoidEthernet(void){} virtual void initialize(void) = 0; virtual void start(void) = 0; virtual void reset(void) = 0; virtual void getParameter(const uint8_t number, void* const value) = 0; virtual void setParameter(const uint8_t number, void* const value) = 0; virtual bool isTxQueueFull(void) = 0; virtual void addToTxQueue(EthernetFrame* const frame, uint16_t frameSize) = 0; #if USE_LWIP virtual void addToTxQueue(struct pbuf* p) = 0; #endif virtual uint16_t pullOutRxFrame(EthernetFrame* const frame) = 0; uint32_t getErrorsCounter() const { return errorsCounter_; } void setErrorsCounter(uint32_t errorsCounter = 0) { errorsCounter_ = errorsCounter; } uint32_t getRxBytesCounter() const { return rxBytesCounter_; } void setRxBytesCounter(uint32_t rxBytesCounter = 0) { rxBytesCounter_ = rxBytesCounter; } uint32_t getRxFramesCounter() const { return rxFramesCounter_; } void setRxFramesCounter(uint32_t rxFramesCounter = 0) { rxFramesCounter_ = rxFramesCounter; } uint32_t getTxBytesCounter() const { return txBytesCounter_; } void setTxBytesCounter(uint32_t txBytesCounter = 0) { txBytesCounter_ = txBytesCounter; } uint32_t getTxFramesCounter() const { return txFramesCounter_; } void setTxFramesCounter(uint32_t txFramesCounter = 0) { txFramesCounter_ = txFramesCounter; } protected: uint32_t txFramesCounter_ = 0; uint32_t txBytesCounter_ = 0; uint32_t rxFramesCounter_ = 0; uint32_t rxBytesCounter_ = 0; uint32_t errorsCounter_ = 0; }; class IEthernetListener { public: IEthernetListener(void){ } virtual ~IEthernetListener(void){ } virtual void parseFrame(EthernetFrame* const frame, uint16_t frameSize, IVoidEthernet* const source, void* parameter) = 0; }; } } #endif /* IVOIDETHERNET_HPP_ */
29.23301
94
0.756891
JohnnyB1290
a888f5426dbaf33bdc3f32567acf49c1dd5e918a
10,364
cpp
C++
Remove_bad_split_good/Assign05P1.cpp
awagsta/Data-Structures-and-Algorithms
d32dc118ff7392421dd61c0ff8cca0eebb27747a
[ "MIT" ]
null
null
null
Remove_bad_split_good/Assign05P1.cpp
awagsta/Data-Structures-and-Algorithms
d32dc118ff7392421dd61c0ff8cca0eebb27747a
[ "MIT" ]
null
null
null
Remove_bad_split_good/Assign05P1.cpp
awagsta/Data-Structures-and-Algorithms
d32dc118ff7392421dd61c0ff8cca0eebb27747a
[ "MIT" ]
null
null
null
#include "llcpInt.h" #include <iostream> #include <cstdlib> #include <ctime> using namespace std; void SeedRand(); int BoundedRandomInt(int lowerBound, int upperBound); int ListLengthCheck(Node* head, int whatItShouldBe); bool match(Node* head, const int procInts[], int procSize); void PruneArray(int a[], int& size, char whichOne); void ShowArray(const int a[], int size); void DebugShowCase(int whichCase, int totalCasesToDo, const int caseValues[], int caseSize); int main() { int TEST_CASES_TO_DO = 900000, testCasesDone = 0, LO_SIZE = 1, HI_SIZE = 20, LO_VALUE = -3, HI_VALUE = 12; int numInts, used_INI, used, used_LE5, used_GE7, intCount, intHolder, iLenChk, iLenChk_LE5, iLenChk_GE7; int *intArr_INI = 0, *intArr = 0, *intArr_LE5 = 0, *intArr_GE7 = 0; Node *head = 0, *head_LE5, // intentionally left uninitialized *head_GE7; // intentionally left uninitialized RemBadSplitGood(head, head_LE5, head_GE7); cout << "================================" << endl; if (head->data == -99 && head->link == 0 && head_LE5->data == -99 && head_LE5->link == 0 && head_GE7->data == -99 && head_GE7->link == 0) { ListClear(head, 1); ListClear(head_LE5, 1); ListClear(head_GE7, 1); cout << "test with empty list ... passed" << endl; } else { cout << "test with empty list ... failed" << endl; exit(EXIT_FAILURE); } cout << "================================" << endl; // SeedRand(); // disabled for reproducible result do { ++testCasesDone; numInts = BoundedRandomInt(LO_SIZE, HI_SIZE); intArr_INI = new int [numInts]; intArr = new int [numInts]; intArr_LE5 = new int [numInts]; intArr_GE7 = new int [numInts]; used_INI = used = used_LE5 = used_GE7 = 0; for (intCount = 0; intCount < numInts; ++intCount) { intHolder = BoundedRandomInt(LO_VALUE, HI_VALUE); intArr_INI[used_INI++] = intHolder; intArr[used++] = intHolder; InsertAsTail(head, intHolder); } PruneArray(intArr, used, 'I'); if (testCasesDone % 45000 == 0) { cout << "================================" << endl; clog << "testing case " << testCasesDone << " of " << TEST_CASES_TO_DO << endl; clog << "================================" << endl; ShowArray(intArr_INI, used_INI); cout << "initial\"[09] list\": "; ShowArray(intArr, used); } for (int i = 0; i < used; ++i) { intHolder = intArr[i]; intArr_LE5[used_LE5++] = intHolder; intArr_GE7[used_GE7++] = intHolder; } PruneArray(intArr, used, 'O'); PruneArray(intArr_LE5, used_LE5, 'L'); PruneArray(intArr_GE7, used_GE7, 'G'); // DebugShowCase(testCasesDone, TEST_CASES_TO_DO, intArr_INI, used_INI); RemBadSplitGood(head, head_LE5, head_GE7); iLenChk = ListLengthCheck(head, used); if (iLenChk != 0) { if (iLenChk == -1) { cout << "\"==6\" list node-count error ... too few" << endl; cout << "test_case: "; ShowArray(intArr_INI, used_INI); cout << "#expected: " << used << endl; cout << "#returned: " << FindListLength(head) << endl; } else { cout << "\"==6\" list node-count error ... too many (circular list?)" << endl; cout << "test_case: "; ShowArray(intArr_INI, used_INI); cout << "#expected: " << used << endl; cout << "returned # is higher (may be infinite)" << endl; } exit(EXIT_FAILURE); } iLenChk_LE5 = ListLengthCheck(head_LE5, used_LE5); if (iLenChk_LE5 != 0) { if (iLenChk_LE5 == -1) { cout << "\"<=5\" list node-count error ... too few" << endl; cout << "test_case: "; ShowArray(intArr_INI, used_INI); cout << "#expected: " << used_LE5 << endl; cout << "#returned: " << FindListLength(head_LE5) << endl; } else { cout << "\"<=5\" list node-count error ... too many (circular list?)" << endl; cout << "test_case: "; ShowArray(intArr_INI, used_INI); cout << "#expected: " << used_LE5 << endl; cout << "returned # is higher (may be infinite)" << endl; } exit(EXIT_FAILURE); } iLenChk_GE7 = ListLengthCheck(head_GE7, used_GE7); if (iLenChk_GE7 != 0) { if (iLenChk_GE7 == -1) { cout << "\">=7\" list node-count error ... too few" << endl; cout << "test_case: "; ShowArray(intArr_INI, used_INI); cout << "#expected: " << used_GE7 << endl; cout << "#returned: " << FindListLength(head_GE7) << endl; } else { cout << "\">=7\" list node-count error ... too many (circular list?)" << endl; cout << "test_case: "; ShowArray(intArr_INI, used_INI); cout << "#expected: " << used_GE7 << endl; cout << "returned # is higher (may be infinite)" << endl; } exit(EXIT_FAILURE); } if ( !match(head, intArr, used) || !match(head_LE5, intArr_LE5, used_LE5) || !match(head_GE7, intArr_GE7, used_GE7) ) { cout << "Contents error ... mismatch found in value or order" << endl; cout << "test case at issue: "; ShowArray(intArr_INI, used_INI); cout << "ought2b \"==6 list\": "; ShowArray(intArr, used); cout << " \"<=5 list\": "; ShowArray(intArr_LE5, used_LE5); cout << " \">=7 list\": "; ShowArray(intArr_GE7, used_GE7); cout << "outcome \"==6 list\": "; ShowAll(cout, head); cout << " \"<=5 list\": "; ShowAll(cout, head_LE5); cout << " \">=7 list\": "; ShowAll(cout, head_GE7); exit(EXIT_FAILURE); } if (testCasesDone % 45000 == 0) { //cout << "================================" << endl; //clog << "testing case " << testCasesDone // << " of " << TEST_CASES_TO_DO << endl; //clog << "================================" << endl; //ShowArray(intArr_INI, used_INI); cout << "ought2b \"==6 list\": "; ShowArray(intArr, used); cout << " \"<=5 list\": "; ShowArray(intArr_LE5, used_LE5); cout << " \">=7 list\": "; ShowArray(intArr_GE7, used_GE7); cout << "outcome \"==6 list\": "; ShowAll(cout, head); cout << " \"<=5 list\": "; ShowAll(cout, head_LE5); cout << " \">=7 list\": "; ShowAll(cout, head_GE7); } ListClear(head, 1); ListClear(head_LE5, 1); ListClear(head_GE7, 1); delete [] intArr_INI; delete [] intArr; delete [] intArr_LE5; delete [] intArr_GE7; intArr_INI = intArr = intArr_LE5 = intArr_GE7 = 0; } while (testCasesDone < TEST_CASES_TO_DO); cout << "================================" << endl; cout << "test program terminated normally" << endl; cout << "================================" << endl; return EXIT_SUCCESS; } ///////////////////////////////////////////////////////////////////// // Function to seed the random number generator // PRE: none // POST: The random number generator has been seeded. ///////////////////////////////////////////////////////////////////// void SeedRand() { srand( (unsigned) time(NULL) ); } ///////////////////////////////////////////////////////////////////// // Function to generate a random integer between // lowerBound and upperBound (inclusive) // PRE: lowerBound is a positive integer. // upperBound is a positive integer. // upperBound is larger than lowerBound // The random number generator has been seeded. // POST: A random integer between lowerBound and upperBound // has been returned. ///////////////////////////////////////////////////////////////////// int BoundedRandomInt(int lowerBound, int upperBound) { return ( rand() % (upperBound - lowerBound + 1) ) + lowerBound; } ///////////////////////////////////////////////////////////////////// // Function to check # of nodes in list against what it should be // POST: returns // -1 if # of nodes is less than what it should be // 0 if # of nodes is equal to what it should be // 1 if # of nodes is more than what it should be ///////////////////////////////////////////////////////////////////// int ListLengthCheck(Node* head, int whatItShouldBe) { int length = 0; while (head != 0) { ++length; if (length > whatItShouldBe) return 1; head = head->link; } return (length < whatItShouldBe) ? -1 : 0; } bool match(Node* head, const int procInts[], int procSize) { int iProc = 0; while (head != 0) { if (iProc == procSize) return false; if (head->data != procInts[iProc]) return false; ++iProc; head = head->link; } return true; } void PruneArray(int a[], int& size, char whichOne) { int target, count = 0, i; for (i = 0; i < size; ++i) { target = a[i]; if ( (whichOne == 'O' && target != 6) || (whichOne == 'L' && target > 5) || (whichOne == 'G' && target < 7) || ( whichOne == 'I' && (target < 0 || target > 9) ) ) ++count; else if (count) a[i - count] = a[i]; } size -= count; if (size == 0) { if (whichOne == 'O' || whichOne == 'L' || whichOne == 'G') { a[0] = -99; ++size; } } } void ShowArray(const int a[], int size) { for (int i = 0; i < size; ++i) cout << a[i] << " "; cout << endl; } void DebugShowCase(int whichCase, int totalCasesToDo, const int caseValues[], int caseSize) { cout << "test case " << whichCase << " of " << totalCasesToDo << endl; cout << "test case: "; ShowArray(caseValues, caseSize); }
31.987654
123
0.489579
awagsta
a88bc31a83c5f97d81192f7d0a59b0b995720750
720
cpp
C++
1-FMT_IO/number-comparer.cpp
lotcz/PJC_ukoly
33d4c8b32c78b6a0df26e05c47fef840aa08cfe3
[ "MIT" ]
null
null
null
1-FMT_IO/number-comparer.cpp
lotcz/PJC_ukoly
33d4c8b32c78b6a0df26e05c47fef840aa08cfe3
[ "MIT" ]
null
null
null
1-FMT_IO/number-comparer.cpp
lotcz/PJC_ukoly
33d4c8b32c78b6a0df26e05c47fef840aa08cfe3
[ "MIT" ]
null
null
null
#include "number-comparer.hpp" #include <iostream> #include <stdexcept> #include <sstream> /** * return true if str1 is bigger than str2. */ bool NumberComparer::compare(std::string& str1, std::string& str2) { if (str1.length() > str2.length()) { return true; } else if (str1.length() < str2.length()) { return false; } else { return (str1 > str2); } } std::string NumberComparer::max_number(std::istream& in) { std::string max = ""; std::string str = ""; char chr; while (in.get(chr)) { if (chr == ',') { if (compare(str, max)) { max = str; } str = ""; } else { str += chr; } } if (compare(str, max)) { max = str; } return max; }
17.560976
68
0.551389
lotcz
a897a7eb67ba1ca897b7a4239b86136bb047b69d
464
cpp
C++
main/simplified-chess-engine/simplified-chess-engine-note.cpp
EliahKagan/old-practice-snapshot
1b53897eac6902f8d867c8f154ce2a489abb8133
[ "0BSD" ]
null
null
null
main/simplified-chess-engine/simplified-chess-engine-note.cpp
EliahKagan/old-practice-snapshot
1b53897eac6902f8d867c8f154ce2a489abb8133
[ "0BSD" ]
null
null
null
main/simplified-chess-engine/simplified-chess-engine-note.cpp
EliahKagan/old-practice-snapshot
1b53897eac6902f8d867c8f154ce2a489abb8133
[ "0BSD" ]
null
null
null
// move southwest for (auto ii = i, jj = j, d = std::min(i, j); d != 0u; --d) { if (board_[--ii][--jj] == Object::empty) { if (try_move(i, j, ii, jj)) return true; } else { if (!belongs_to(player_, board_[ii][jj]) && try_move(i, j, ii, jj)) return true; break; // can't move past even a capturable piece } }
38.666667
69
0.392241
EliahKagan
a89889a31d8cf760da02d84a186e39e997b683af
17,960
cpp
C++
src/common/settings.cpp
linquize/cppan
014d9604183360dfa0628f5ec71198b57f89d9fc
[ "Apache-2.0" ]
null
null
null
src/common/settings.cpp
linquize/cppan
014d9604183360dfa0628f5ec71198b57f89d9fc
[ "Apache-2.0" ]
null
null
null
src/common/settings.cpp
linquize/cppan
014d9604183360dfa0628f5ec71198b57f89d9fc
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2016-2017, Egor Pugin * * 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 "settings.h" #include "access_table.h" #include "config.h" #include "database.h" #include "directories.h" #include "exceptions.h" #include "hash.h" #include "program.h" #include "stamp.h" #include <boost/algorithm/string.hpp> #include <boost/nowide/fstream.hpp> #include <primitives/hasher.h> #include <primitives/templates.h> #include <primitives/log.h> DECLARE_STATIC_LOGGER(logger, "settings"); void BuildSettings::set_build_dirs(const String &name) { filename = name; filename_without_ext = name; source_directory = directories.build_dir; if (directories.build_dir_type == SettingsType::Local || directories.build_dir_type == SettingsType::None) { source_directory /= (CPPAN_LOCAL_BUILD_PREFIX + filename); } else { source_directory_hash = sha256_short(name); source_directory /= source_directory_hash; } binary_directory = source_directory / "build"; } void BuildSettings::append_build_dirs(const path &p) { source_directory /= p; binary_directory = source_directory / "build"; } Settings::Settings() { build_dir = temp_directory_path() / "build"; storage_dir = get_root_directory() / STORAGE_DIR; } void Settings::load(const path &p, const SettingsType type) { auto root = load_yaml_config(p); load(root, type); } void Settings::load(const yaml &root, const SettingsType type) { load_main(root, type); auto get_storage_dir = [this](SettingsType type) { switch (type) { case SettingsType::Local: return cppan_dir / STORAGE_DIR; case SettingsType::User: return Settings::get_user_settings().storage_dir; case SettingsType::System: return Settings::get_system_settings().storage_dir; default: { auto d = fs::absolute(storage_dir); fs::create_directories(d); return fs::canonical(d); } } }; auto get_build_dir = [this](const path &p, SettingsType type, const auto &dirs) { switch (type) { case SettingsType::Local: return current_thread_path(); case SettingsType::User: case SettingsType::System: return dirs.storage_dir_tmp / "build"; default: return p; } }; Directories dirs; dirs.storage_dir_type = storage_dir_type; auto sd = get_storage_dir(storage_dir_type); dirs.set_storage_dir(sd); dirs.build_dir_type = build_dir_type; dirs.set_build_dir(get_build_dir(build_dir, build_dir_type, dirs)); directories.update(dirs, type); } void Settings::load_main(const yaml &root, const SettingsType type) { auto packages_dir_type_from_string = [](const String &s, const String &key) { if (s == "local") return SettingsType::Local; if (s == "user") return SettingsType::User; if (s == "system") return SettingsType::System; throw std::runtime_error("Unknown '" + key + "'. Should be one of [local, user, system]"); }; get_map_and_iterate(root, "remotes", [this](auto &kv) { auto n = kv.first.template as<String>(); bool o = n == DEFAULT_REMOTE_NAME; // origin Remote rm; Remote *prm = o ? &remotes[0] : &rm; prm->name = n; YAML_EXTRACT_VAR(kv.second, prm->url, "url", String); YAML_EXTRACT_VAR(kv.second, prm->data_dir, "data_dir", String); YAML_EXTRACT_VAR(kv.second, prm->user, "user", String); YAML_EXTRACT_VAR(kv.second, prm->token, "token", String); if (!o) remotes.push_back(*prm); }); YAML_EXTRACT_AUTO(disable_update_checks); YAML_EXTRACT_AUTO(max_download_threads); YAML_EXTRACT(storage_dir, String); YAML_EXTRACT(build_dir, String); YAML_EXTRACT(cppan_dir, String); YAML_EXTRACT(output_dir, String); /*#ifdef _WIN32 // correctly convert to utf-8 #define CONVERT_DIR(x) x = to_wstring(x.string()) CONVERT_DIR(storage_dir); CONVERT_DIR(build_dir); CONVERT_DIR(cppan_dir); CONVERT_DIR(output_dir); #endif*/ auto &p = root["proxy"]; if (p.IsDefined()) { if (!p.IsMap()) throw std::runtime_error("'proxy' should be a map"); YAML_EXTRACT_VAR(p, proxy.host, "host", String); YAML_EXTRACT_VAR(p, proxy.user, "user", String); } storage_dir_type = packages_dir_type_from_string(get_scalar<String>(root, "storage_dir_type", "user"), "storage_dir_type"); if (root["storage_dir"].IsDefined()) storage_dir_type = SettingsType::None; build_dir_type = packages_dir_type_from_string(get_scalar<String>(root, "build_dir_type", "system"), "build_dir_type"); if (root["build_dir"].IsDefined()) build_dir_type = SettingsType::None; // read these first from local settings // and they'll be overriden in bs (if they exist there) YAML_EXTRACT_AUTO(use_cache); YAML_EXTRACT_AUTO(show_ide_projects); YAML_EXTRACT_AUTO(add_run_cppan_target); YAML_EXTRACT_AUTO(cmake_verbose); YAML_EXTRACT_AUTO(build_system_verbose); YAML_EXTRACT_AUTO(verify_all); YAML_EXTRACT_AUTO(copy_all_libraries_to_output); YAML_EXTRACT_AUTO(copy_import_libs); YAML_EXTRACT_AUTO(rc_enabled); YAML_EXTRACT_AUTO(short_local_names); YAML_EXTRACT_AUTO(full_path_executables); YAML_EXTRACT_AUTO(var_check_jobs); YAML_EXTRACT_AUTO(install_prefix); YAML_EXTRACT_AUTO(build_warning_level); YAML_EXTRACT_AUTO(meta_target_suffix); // read build settings if (type == SettingsType::Local) { // at first, we load bs from current root load_build(root); // then override settings with specific (or default) config yaml current_build; if (root["builds"].IsDefined()) { // yaml will not keep sorting of keys in map // so we can take 'first' build in document if (root["current_build"].IsDefined()) { if (root["builds"][root["current_build"].template as<String>()].IsDefined()) current_build = root["builds"][root["current_build"].template as<String>()]; else { // on empty config name we build the first configuration LOG_WARN(logger, "No such build config '" + root["current_build"].template as<String>() + "' in builds directive. Trying to build the first configuration."); current_build = root["builds"].begin()->second; } } } else if (root["build"].IsDefined()) current_build = root["build"]; load_build(current_build); } // read project settings (deps etc.) if (type == SettingsType::Local && load_project) { Project p; p.allow_relative_project_names = true; p.allow_local_dependencies = true; p.load(root); dependencies = p.dependencies; } } void Settings::load_build(const yaml &root) { if (root.IsNull()) return; // extract YAML_EXTRACT_AUTO(c_compiler); YAML_EXTRACT_AUTO(cxx_compiler); YAML_EXTRACT_AUTO(compiler); YAML_EXTRACT_AUTO(c_compiler_flags); if (c_compiler_flags.empty()) YAML_EXTRACT_VAR(root, c_compiler_flags, "c_flags", String); YAML_EXTRACT_AUTO(cxx_compiler_flags); if (cxx_compiler_flags.empty()) YAML_EXTRACT_VAR(root, cxx_compiler_flags, "cxx_flags", String); YAML_EXTRACT_AUTO(compiler_flags); YAML_EXTRACT_AUTO(link_flags); YAML_EXTRACT_AUTO(link_libraries); YAML_EXTRACT_AUTO(configuration); YAML_EXTRACT_AUTO(generator); YAML_EXTRACT_AUTO(system_version); YAML_EXTRACT_AUTO(toolset); YAML_EXTRACT_AUTO(use_shared_libs); YAML_EXTRACT_VAR(root, use_shared_libs, "build_shared_libs", bool); YAML_EXTRACT_AUTO(silent); YAML_EXTRACT_AUTO(use_cache); YAML_EXTRACT_AUTO(show_ide_projects); YAML_EXTRACT_AUTO(add_run_cppan_target); YAML_EXTRACT_AUTO(cmake_verbose); YAML_EXTRACT_AUTO(build_system_verbose); YAML_EXTRACT_AUTO(verify_all); YAML_EXTRACT_AUTO(copy_all_libraries_to_output); YAML_EXTRACT_AUTO(copy_import_libs); YAML_EXTRACT_AUTO(rc_enabled); YAML_EXTRACT_AUTO(short_local_names); YAML_EXTRACT_AUTO(full_path_executables); YAML_EXTRACT_AUTO(var_check_jobs); YAML_EXTRACT_AUTO(install_prefix); YAML_EXTRACT_AUTO(build_warning_level); YAML_EXTRACT_AUTO(meta_target_suffix); for (int i = 0; i < CMakeConfigurationType::Max; i++) { auto t = configuration_types[i]; boost::to_lower(t); YAML_EXTRACT_VAR(root, c_compiler_flags_conf[i], "c_compiler_flags_" + t, String); if (c_compiler_flags_conf[i].empty()) YAML_EXTRACT_VAR(root, c_compiler_flags_conf[i], "c_flags_" + t, String); YAML_EXTRACT_VAR(root, cxx_compiler_flags_conf[i], "cxx_compiler_flags_" + t, String); if (cxx_compiler_flags_conf[i].empty()) YAML_EXTRACT_VAR(root, cxx_compiler_flags_conf[i], "cxx_flags_" + t, String); YAML_EXTRACT_VAR(root, compiler_flags_conf[i], "compiler_flags_" + t, String); YAML_EXTRACT_VAR(root, link_flags_conf[i], "link_flags_" + t, String); } cmake_options = get_sequence<String>(root["cmake_options"]); get_string_map(root, "env", env); // process if (c_compiler.empty()) c_compiler = cxx_compiler; if (c_compiler.empty()) c_compiler = compiler; if (cxx_compiler.empty()) cxx_compiler = compiler; if (!compiler_flags.empty()) { c_compiler_flags += " " + compiler_flags; cxx_compiler_flags += " " + compiler_flags; } for (int i = 0; i < CMakeConfigurationType::Max; i++) { if (!compiler_flags_conf[i].empty()) { c_compiler_flags_conf[i] += " " + compiler_flags_conf[i]; cxx_compiler_flags_conf[i] += " " + compiler_flags_conf[i]; } } } bool Settings::is_custom_build_dir() const { return build_dir_type == SettingsType::Local || build_dir_type == SettingsType::None; } String Settings::get_hash() const { Hasher h; h |= c_compiler; h |= cxx_compiler; h |= compiler; h |= c_compiler_flags; for (int i = 0; i < CMakeConfigurationType::Max; i++) h |= c_compiler_flags_conf[i]; h |= cxx_compiler_flags; for (int i = 0; i < CMakeConfigurationType::Max; i++) h |= cxx_compiler_flags_conf[i]; h |= compiler_flags; for (int i = 0; i < CMakeConfigurationType::Max; i++) h |= compiler_flags_conf[i]; h |= link_flags; for (int i = 0; i < CMakeConfigurationType::Max; i++) h |= link_flags_conf[i]; h |= link_libraries; h |= generator; h |= system_version; h |= toolset; h |= use_shared_libs; h |= configuration; h |= default_configuration; // besides we track all valuable ENV vars // to be sure that we'll load correct config auto add_env = [&h](const char *var) { auto e = getenv(var); if (!e) return; h |= String(e); }; add_env("PATH"); add_env("Path"); add_env("FPATH"); add_env("CPATH"); // windows, msvc add_env("VSCOMNTOOLS"); add_env("VS71COMNTOOLS"); add_env("VS80COMNTOOLS"); add_env("VS90COMNTOOLS"); add_env("VS100COMNTOOLS"); add_env("VS110COMNTOOLS"); add_env("VS120COMNTOOLS"); add_env("VS130COMNTOOLS"); add_env("VS140COMNTOOLS"); add_env("VS141COMNTOOLS"); // 2017? add_env("VS150COMNTOOLS"); add_env("VS151COMNTOOLS"); add_env("VS160COMNTOOLS"); // for the future add_env("INCLUDE"); add_env("LIB"); // gcc add_env("COMPILER_PATH"); add_env("LIBRARY_PATH"); add_env("C_INCLUDE_PATH"); add_env("CPLUS_INCLUDE_PATH"); add_env("OBJC_INCLUDE_PATH"); //add_env("LD_LIBRARY_PATH"); // do we need these? //add_env("DYLD_LIBRARY_PATH"); add_env("CC"); add_env("CFLAGS"); add_env("CXXFLAGS"); add_env("CPPFLAGS"); return h.hash; } bool Settings::checkForUpdates() const { if (disable_update_checks) return false; #ifdef _WIN32 String stamp_file = "/client/.service/win32.stamp"; #elif __APPLE__ String stamp_file = "/client/.service/macos.stamp"; #else String stamp_file = "/client/.service/linux.stamp"; #endif auto fn = fs::temp_directory_path() / fs::unique_path(); download_file(remotes[0].url + stamp_file, fn); auto stamp_remote = boost::trim_copy(read_file(fn)); fs::remove(fn); boost::replace_all(stamp_remote, "\"", ""); uint64_t s1 = std::stoull(cppan_stamp); uint64_t s2 = std::stoull(stamp_remote); if (!(s1 != 0 && s2 != 0 && s2 > s1)) return false; LOG_INFO(logger, "New version of the CPPAN client is available!"); LOG_INFO(logger, "Feel free to upgrade it from website (https://cppan.org/) or simply run:"); LOG_INFO(logger, "cppan --self-upgrade"); #ifdef _WIN32 LOG_INFO(logger, "(or the same command but from administrator)"); #else LOG_INFO(logger, "or"); LOG_INFO(logger, "sudo cppan --self-upgrade"); #endif LOG_INFO(logger, ""); return true; } Settings &Settings::get(SettingsType type) { static Settings settings[toIndex(SettingsType::Max) + 1]; auto i = toIndex(type); auto &s = settings[i]; switch (type) { case SettingsType::Local: { RUN_ONCE { s = get(SettingsType::User); }; } break; case SettingsType::User: { std::exception_ptr eptr; RUN_ONCE { try { s = get(SettingsType::System); auto fn = get_config_filename(); if (!fs::exists(fn)) { boost::system::error_code ec; fs::create_directories(fn.parent_path(), ec); if (ec) throw std::runtime_error(ec.message()); auto ss = get(SettingsType::System); ss.save(fn); } s.load(fn, SettingsType::User); } catch (...) { eptr = std::current_exception(); } }; if (eptr) std::rethrow_exception(eptr); } break; case SettingsType::System: { RUN_ONCE { auto fn = CONFIG_ROOT "default"; if (!fs::exists(fn)) return; s.load(fn, SettingsType::System); }; } break; } return s; } Settings &Settings::get_system_settings() { return get(SettingsType::System); } Settings &Settings::get_user_settings() { return get(SettingsType::User); } Settings &Settings::get_local_settings() { return get(SettingsType::Local); } void Settings::clear_local_settings() { get_local_settings() = get_user_settings(); } void Settings::save(const path &p) const { boost::nowide::ofstream o(p.string()); if (!o) throw std::runtime_error("Cannot open file: " + p.string()); yaml root; root["remotes"][DEFAULT_REMOTE_NAME]["url"] = remotes[0].url; root["storage_dir"] = storage_dir.string(); o << dump_yaml_config(root); } void cleanConfig(const String &c) { if (c.empty()) return; auto h = hash_config(c); auto remove_pair = [&](const auto &dir) { fs::remove_all(dir / c); fs::remove_all(dir / h); }; remove_pair(directories.storage_dir_bin); remove_pair(directories.storage_dir_lib); remove_pair(directories.storage_dir_exp); #ifdef _WIN32 remove_pair(directories.storage_dir_lnk); #endif // for cfg we also remove xxx.cmake files (found with xxx.c.cmake files) remove_pair(directories.storage_dir_cfg); for (auto &f : boost::make_iterator_range(fs::directory_iterator(directories.storage_dir_cfg), {})) { if (!fs::is_regular_file(f) || f.path().extension() != ".cmake") continue; auto parts = split_string(f.path().string(), "."); if (parts.size() == 2) { if (parts[0] == c || parts[0] == h) fs::remove(f); continue; } if (parts.size() == 3) { if (parts[1] == c || parts[1] == h) { fs::remove(parts[0] + ".cmake"); fs::remove(parts[1] + ".cmake"); fs::remove(f); } continue; } } // obj auto &sdb = getServiceDatabase(); for (auto &p : sdb.getInstalledPackages()) { auto d = p.getDirObj() / "build"; if (!fs::exists(d)) continue; for (auto &f : boost::make_iterator_range(fs::directory_iterator(d), {})) { if (!fs::is_directory(f)) continue; if (f.path().filename() == c || f.path().filename() == h) fs::remove_all(f); } } // config hashes (in sdb) sdb.removeConfigHashes(c); sdb.removeConfigHashes(h); } void cleanConfigs(const Strings &configs) { for (auto &c : configs) cleanConfig(c); }
29.636964
127
0.619488
linquize
a899d8c1bf83a99b830acff1dad1e2b64c4eeba4
2,987
hpp
C++
modules/encode/src/video/video_stream/video_stream.hpp
HFauto/CNStream
1d4847327fff83eedbc8de6911855c5f7bb2bf22
[ "Apache-2.0" ]
null
null
null
modules/encode/src/video/video_stream/video_stream.hpp
HFauto/CNStream
1d4847327fff83eedbc8de6911855c5f7bb2bf22
[ "Apache-2.0" ]
null
null
null
modules/encode/src/video/video_stream/video_stream.hpp
HFauto/CNStream
1d4847327fff83eedbc8de6911855c5f7bb2bf22
[ "Apache-2.0" ]
null
null
null
/************************************************************************* * Copyright (C) [2020] by Cambricon, 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 * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. *************************************************************************/ #ifndef __VIDEO_STREAM_HPP__ #define __VIDEO_STREAM_HPP__ #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #if (CV_MAJOR_VERSION >= 3) #include <opencv2/imgcodecs/imgcodecs.hpp> #endif #include <string> #include "tiler/tiler.hpp" #include "../video_encoder/video_encoder.hpp" #include "../video_common.hpp" namespace cnstream { namespace video { class VideoStream; } class VideoStream { public: using PacketInfo = VideoEncoder::PacketInfo; using Event = VideoEncoder::Event; using EventCallback = VideoEncoder::EventCallback; using ColorFormat = Tiler::ColorFormat; using Buffer = Tiler::Buffer; using Rect = Tiler::Rect; struct Param { int width; int height; int tile_cols; int tile_rows; double frame_rate; int time_base; int bit_rate; int gop_size; VideoPixelFormat pixel_format = VideoPixelFormat::NV21; VideoCodecType codec_type = VideoCodecType::H264; bool mlu_encoder = true; bool resample = true; int device_id = -1; }; explicit VideoStream(const Param &param); ~VideoStream(); // no copying VideoStream(const VideoStream &) = delete; VideoStream &operator=(const VideoStream &) = delete; VideoStream(VideoStream &&); VideoStream &operator=(VideoStream &&); bool Open(); bool Close(bool wait_finish = false); bool Update(const cv::Mat &mat, ColorFormat color, int64_t timestamp, const std::string &stream_id, void *user_data = nullptr); bool Update(const Buffer *buffer, int64_t timestamp, const std::string &stream_id, void *user_data = nullptr); bool Clear(const std::string &stream_id); void SetEventCallback(EventCallback func); int RequestFrameBuffer(VideoFrame *frame); int GetPacket(VideoPacket *packet, PacketInfo *info = nullptr); private: video::VideoStream *stream_ = nullptr; }; } // namespace cnstream #endif // __VIDEO_STREAM_HPP__
31.776596
112
0.694342
HFauto
a89a3303c865f25d9aaeefc2ff9659cc08253660
2,035
cpp
C++
Daemon/ydotoold.cpp
StoneDot/ydotool
cf38f107bb998e938cdf8cd5cd5eafb88739a414
[ "MIT" ]
null
null
null
Daemon/ydotoold.cpp
StoneDot/ydotool
cf38f107bb998e938cdf8cd5cd5eafb88739a414
[ "MIT" ]
null
null
null
Daemon/ydotoold.cpp
StoneDot/ydotool
cf38f107bb998e938cdf8cd5cd5eafb88739a414
[ "MIT" ]
null
null
null
/* This file is part of ydotool. Copyright (C) 2018-2019 ReimuNotMoe This program is free software: you can redistribute it and/or modify it under the terms of the MIT License. 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. */ #include "ydotoold.hpp" using namespace ydotool; //struct ep_ctx { // size_t bufpos_read = 0; // uint8_t buf_read[8]; //}; // //void fd_set_nonblocking(int fd) { // int flag = fcntl(fd, F_GETFL) | O_NONBLOCK; // fcntl(fd, F_SETFL, flag); //} Instance instance; static int client_handler(int fd) { uInputRawData buf{0}; while (true) { int rc = recv(fd, &buf, sizeof(buf), MSG_WAITALL); if (rc == sizeof(buf)) { instance.uInputContext->Emit(buf.type, buf.code, buf.value); } else { return 0; } } } int main(int argc, char **argv) { const char path_socket[] = "/tmp/.ydotool_socket"; unlink(path_socket); int fd_listener = socket(AF_UNIX, SOCK_STREAM, 0); if (fd_listener == -1) { std::cerr << "ydotoold: " << "failed to create socket: " << strerror(errno) << "\n"; abort(); } sockaddr_un addr{0}; memset(&addr, 0, sizeof(addr)); addr.sun_family = AF_UNIX; strncpy(addr.sun_path, path_socket, sizeof(addr.sun_path)-1); if (bind(fd_listener, (struct sockaddr *)&addr, sizeof(addr))) { std::cerr << "ydotoold: " << "failed to bind to socket [" << path_socket << "]: " << strerror(errno) << "\n"; abort(); } if (listen(fd_listener, 16)) { std::cerr << "ydotoold: " << "failed to listen on socket [" << path_socket << "]: " << strerror(errno) << "\n"; abort(); } chmod(path_socket, 0600); std::cerr << "ydotoold: " << "listening on socket " << path_socket << "\n"; instance.Init("ydotoold virtual device"); while (int fd_client = accept(fd_listener, nullptr, nullptr)) { std::cerr << "ydotoold: accepted client\n"; std::thread thd(client_handler, fd_client); thd.detach(); } }
23.662791
113
0.653071
StoneDot
a89b9d3fecc3cb13ea796b2a462af7d2ae414ca2
331
cpp
C++
Unreal4/FogOfWar/UnchartedWaters/Source/unchartedwaters/UI/UWGameHUD.cpp
fangguanya/study
4e0ae19d97c5665208657fdb280bd2c25ce05190
[ "MIT" ]
null
null
null
Unreal4/FogOfWar/UnchartedWaters/Source/unchartedwaters/UI/UWGameHUD.cpp
fangguanya/study
4e0ae19d97c5665208657fdb280bd2c25ce05190
[ "MIT" ]
null
null
null
Unreal4/FogOfWar/UnchartedWaters/Source/unchartedwaters/UI/UWGameHUD.cpp
fangguanya/study
4e0ae19d97c5665208657fdb280bd2c25ce05190
[ "MIT" ]
1
2022-03-08T01:36:39.000Z
2022-03-08T01:36:39.000Z
#pragma once // !< All right is reserved by HW-Storm Game Studio, Even not mentioned clearly with signature. // !< This is not a free ware, Please do-not copy it outside of HW-Storm Game Studio // !< File : UWGameState // !< Date : 2/27/2017 12:03:53 PM // !< Author : fanggang #include "unchartedwaters.h" #include "UWGameHUD.h"
33.1
95
0.700906
fangguanya
a89bd2a83e044b1bcaab8b2b6b77ecf6d8ca80bd
2,197
cc
C++
src/base-element.cc
banetl/bson-parser
b5c15c1f10863d7e4ea2aa6fc07188728ed2de04
[ "MIT" ]
null
null
null
src/base-element.cc
banetl/bson-parser
b5c15c1f10863d7e4ea2aa6fc07188728ed2de04
[ "MIT" ]
null
null
null
src/base-element.cc
banetl/bson-parser
b5c15c1f10863d7e4ea2aa6fc07188728ed2de04
[ "MIT" ]
1
2018-04-05T11:53:23.000Z
2018-04-05T11:53:23.000Z
#include <map> #include <string> #include "base-element.hh" #include "utils.hh" namespace bson { BaseElement::BaseElement(BaseElement::Type type, const std::string key) : type_(type), key_(key) { } std::string BaseElement::get_type_string(BaseElement::Type e) const { const std::map<BaseElement::Type, const std::string> type_to_str { { BaseElement::Type::bfp, "64-bit binary floating point" }, { BaseElement::Type::str, "UTF-8 string" }, { BaseElement::Type::doc, "Embedded document" }, { BaseElement::Type::array, "Array" }, { BaseElement::Type::bdata, "Binary data" }, { BaseElement::Type::undef, "Undefined (value) — Deprecated" }, { BaseElement::Type::oid, "ObjectId" }, { BaseElement::Type::bf, "Boolean \"false\"" }, { BaseElement::Type::bt, "Boolean \"true\"" }, { BaseElement::Type::date, "UTC datetime" }, { BaseElement::Type::null, "Null value" }, { BaseElement::Type::regex, "Regular expression" }, { BaseElement::Type::dbp, "DBPointer" }, { BaseElement::Type::jvs, "JavaScript code" }, { BaseElement::Type::symbol, "Symbol" }, { BaseElement::Type::jvsg, "JavaScript code w/ scope" }, { BaseElement::Type::i32, "32-bit integer" }, { BaseElement::Type::time, "Timestamp" }, { BaseElement::Type::i64, "64-bit integer" }, { BaseElement::Type::d128, "128-bit decimal floating point" }, { BaseElement::Type::min, "Min key" }, { BaseElement::Type::max, "Max key" }, }; auto it = type_to_str.find(e); return (it != type_to_str.end()) ? it->second : "Error"; } std::ostream& BaseElement::dump(std::ostream& ostr) const { ostr << "Element:" << utils::iendl << "type: " << this->get_type_string(type_) << utils::iendl << "key: " << key_ << utils::iendl; return ostr; } std::ostream& operator<<(std::ostream& ostr, const BaseElement& elt) { return elt.dump(ostr); } }
35.435484
75
0.543013
banetl
a89c4847dfe0405d41b72a1e6dd932ef1b11774a
78
cpp
C++
Windows/VS2017/vtkCommonDataModel/vtkCommonDataModel.cpp
WinBuilds/VTK
508ab2644432973724259184f2cb83aced602484
[ "BSD-3-Clause" ]
null
null
null
Windows/VS2017/vtkCommonDataModel/vtkCommonDataModel.cpp
WinBuilds/VTK
508ab2644432973724259184f2cb83aced602484
[ "BSD-3-Clause" ]
null
null
null
Windows/VS2017/vtkCommonDataModel/vtkCommonDataModel.cpp
WinBuilds/VTK
508ab2644432973724259184f2cb83aced602484
[ "BSD-3-Clause" ]
null
null
null
#include "vtkCommonDataModel.h" vtkCommonDataModel::vtkCommonDataModel() { }
13
40
0.794872
WinBuilds
a89eef6e13458396ada343fe487e175568f46273
1,068
cpp
C++
1138/main.cpp
Heliovic/PAT_Solutions
7c5dd554654045308f2341713c3e52cc790beb59
[ "MIT" ]
2
2019-03-18T12:55:38.000Z
2019-09-07T10:11:26.000Z
1138/main.cpp
Heliovic/My_PAT_Answer
7c5dd554654045308f2341713c3e52cc790beb59
[ "MIT" ]
null
null
null
1138/main.cpp
Heliovic/My_PAT_Answer
7c5dd554654045308f2341713c3e52cc790beb59
[ "MIT" ]
null
null
null
#include <cstdio> #define MAX_N 51200 using namespace std; int preorder[MAX_N]; int inorder[MAX_N]; int N; bool flag = false; struct node { int data; node* lc; node* rc; node() {lc = rc = NULL;} }; node* root = NULL; node* rebuild(int pl, int pr, int il, int ir) { if (pl > pr || il > ir) return NULL; node* n = new node; n->data = preorder[pl]; int k; for (int i = il; i <= ir; i++) { if (n->data == inorder[i]) { k = i; break; } } n->lc = rebuild(pl + 1, pl + k - il, il, k - 1); n->rc = rebuild(pl + k - il + 1, pr, k + 1, ir); return n; } void post(node* r) { if (r == NULL || flag) return; post(r->lc); post(r->rc); if (!flag) printf("%d", r->data); flag = true; } int main() { scanf("%d", &N); for (int i = 1; i <= N; i++) scanf("%d", &preorder[i]); for (int i = 1; i <= N; i++) scanf("%d", &inorder[i]); root = rebuild(1, N, 1, N); post(root); return 0; }
14.630137
52
0.449438
Heliovic
a89fcd5e438d7336e0b0c8500f12c62691943fd9
3,043
cc
C++
dali/operators/audio/mfcc/mfcc_test.cc
cyyever/DALI
e2b2d5a061da605e3e9e681017a7b2d53fe41a62
[ "ECL-2.0", "Apache-2.0" ]
3,967
2018-06-19T04:39:09.000Z
2022-03-31T10:57:53.000Z
dali/operators/audio/mfcc/mfcc_test.cc
cyyever/DALI
e2b2d5a061da605e3e9e681017a7b2d53fe41a62
[ "ECL-2.0", "Apache-2.0" ]
3,494
2018-06-21T07:09:58.000Z
2022-03-31T19:44:51.000Z
dali/operators/audio/mfcc/mfcc_test.cc
cyyever/DALI
e2b2d5a061da605e3e9e681017a7b2d53fe41a62
[ "ECL-2.0", "Apache-2.0" ]
531
2018-06-19T23:53:10.000Z
2022-03-30T08:35:59.000Z
// Copyright (c) 2019, NVIDIA CORPORATION. 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 <gtest/gtest.h> #include "dali/operators/audio/mfcc/mfcc.h" namespace dali { namespace detail { namespace test { void check_lifter_coeffs(span<const float> coeffs, double lifter, int64_t length) { ASSERT_EQ(length, coeffs.size()); auto coeffs_data = coeffs.data(); ASSERT_NE(nullptr, coeffs_data); for (int64_t i = 0; i < length; i++) { float expected = 1.0 + 0.5 * lifter * std::sin((i + 1) * M_PI / lifter); EXPECT_NEAR(expected, coeffs_data[i], 1e-4); } } TEST(LifterCoeffsCPU, correctness) { LifterCoeffs<CPUBackend> coeffs; auto lifter = 0.0f; coeffs.Calculate(10, lifter); ASSERT_TRUE(coeffs.empty()); lifter = 1.234f; coeffs.Calculate(10, lifter); check_lifter_coeffs(make_cspan(coeffs), lifter, 10); coeffs.Calculate(20, lifter); check_lifter_coeffs(make_cspan(coeffs), lifter, 20); lifter = 2.234f; coeffs.Calculate(10, lifter); check_lifter_coeffs(make_cspan(coeffs), lifter, 10); coeffs.Calculate(5, lifter); check_lifter_coeffs(make_cspan(coeffs), lifter, 10); } TEST(LifterCoeffsGPU, correctness) { LifterCoeffs<GPUBackend> coeffs; std::vector<float> coeffs_cpu; auto lifter = 0.0f; coeffs.Calculate(10, lifter); ASSERT_TRUE(coeffs.empty()); lifter = 1.234f; coeffs.Calculate(10, lifter); coeffs_cpu.resize(coeffs.size()); CUDA_CALL(cudaMemcpy(coeffs_cpu.data(), coeffs.data(), coeffs.size() * sizeof(float), cudaMemcpyDeviceToHost)); check_lifter_coeffs(make_cspan(coeffs_cpu), lifter, coeffs.size()); coeffs.Calculate(20, lifter); coeffs_cpu.resize(coeffs.size()); CUDA_CALL(cudaMemcpy(coeffs_cpu.data(), coeffs.data(), coeffs.size() * sizeof(float), cudaMemcpyDeviceToHost)); check_lifter_coeffs(make_cspan(coeffs_cpu), lifter, coeffs.size()); coeffs.Calculate(10, lifter); coeffs_cpu.resize(coeffs.size()); CUDA_CALL(cudaMemcpy(coeffs_cpu.data(), coeffs.data(), coeffs.size() * sizeof(float), cudaMemcpyDeviceToHost)); check_lifter_coeffs(make_cspan(coeffs_cpu), lifter, coeffs.size()); coeffs.Calculate(5, lifter); coeffs_cpu.resize(coeffs.size()); CUDA_CALL(cudaMemcpy(coeffs_cpu.data(), coeffs.data(), coeffs.size() * sizeof(float), cudaMemcpyDeviceToHost)); check_lifter_coeffs(make_cspan(coeffs_cpu), lifter, coeffs.size()); } } // namespace test } // namespace detail } // namespace dali
33.43956
83
0.706211
cyyever
a8a14c7d3df92eedec7c0ef7250beb0ab8f8eb30
1,840
cc
C++
chrome_frame/plugin_url_request.cc
Scopetta197/chromium
b7bf8e39baadfd9089de2ebdc0c5d982de4a9820
[ "BSD-3-Clause" ]
212
2015-01-31T11:55:58.000Z
2022-02-22T06:35:11.000Z
chrome_frame/plugin_url_request.cc
1065672644894730302/Chromium
239dd49e906be4909e293d8991e998c9816eaa35
[ "BSD-3-Clause" ]
5
2015-03-27T14:29:23.000Z
2019-09-25T13:23:12.000Z
chrome_frame/plugin_url_request.cc
1065672644894730302/Chromium
239dd49e906be4909e293d8991e998c9816eaa35
[ "BSD-3-Clause" ]
221
2015-01-07T06:21:24.000Z
2022-02-11T02:51:12.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome_frame/plugin_url_request.h" #include "chrome/common/automation_messages.h" PluginUrlRequest::PluginUrlRequest() : delegate_(NULL), remote_request_id_(-1), post_data_len_(0), enable_frame_busting_(false), resource_type_(ResourceType::MAIN_FRAME), load_flags_(0), is_chunked_upload_(false) { } PluginUrlRequest::~PluginUrlRequest() { } bool PluginUrlRequest::Initialize(PluginUrlRequestDelegate* delegate, int remote_request_id, const std::string& url, const std::string& method, const std::string& referrer, const std::string& extra_headers, net::UploadData* upload_data, ResourceType::Type resource_type, bool enable_frame_busting, int load_flags) { delegate_ = delegate; remote_request_id_ = remote_request_id; url_ = url; method_ = method; referrer_ = referrer; extra_headers_ = extra_headers; resource_type_ = resource_type; load_flags_ = load_flags; if (upload_data) { // We store a pointer to UrlmonUploadDataStream and not net::UploadData // since UrlmonUploadDataStream implements thread safe ref counting and // UploadData does not. CComObject<UrlmonUploadDataStream>* upload_stream = NULL; HRESULT hr = CComObject<UrlmonUploadDataStream>::CreateInstance( &upload_stream); if (FAILED(hr)) { NOTREACHED(); } else { post_data_len_ = upload_data->GetContentLengthSync(); upload_stream->AddRef(); upload_stream->Initialize(upload_data); upload_data_.Attach(upload_stream); is_chunked_upload_ = upload_data->is_chunked(); } } enable_frame_busting_ = enable_frame_busting; return true; }
31.724138
77
0.729348
Scopetta197
a8a15dd1bd099b9a6edfeeb0e0d7f1e8fe317f19
93
hpp
C++
lib/hwlib-extra/hwlib-extra.hpp
Fusion86/gesture-gloves
17ebff2c7ea63cffd4f78e9d7ec35a004cb457e2
[ "MIT" ]
null
null
null
lib/hwlib-extra/hwlib-extra.hpp
Fusion86/gesture-gloves
17ebff2c7ea63cffd4f78e9d7ec35a004cb457e2
[ "MIT" ]
null
null
null
lib/hwlib-extra/hwlib-extra.hpp
Fusion86/gesture-gloves
17ebff2c7ea63cffd4f78e9d7ec35a004cb457e2
[ "MIT" ]
null
null
null
#pragma once #include <hwlib.hpp> hwlib::ostream& operator<<(hwlib::ostream& os, float f);
15.5
56
0.698925
Fusion86
a8a1843d2251bfd8946be5202b9fc309288531db
2,315
hpp
C++
src/seal/kernel/sum_seal.hpp
EvonneH/he-transformer
85b3b629e46a25795ffcd913c8c5ffe7e4d50afc
[ "Apache-2.0" ]
null
null
null
src/seal/kernel/sum_seal.hpp
EvonneH/he-transformer
85b3b629e46a25795ffcd913c8c5ffe7e4d50afc
[ "Apache-2.0" ]
null
null
null
src/seal/kernel/sum_seal.hpp
EvonneH/he-transformer
85b3b629e46a25795ffcd913c8c5ffe7e4d50afc
[ "Apache-2.0" ]
null
null
null
//***************************************************************************** // Copyright 2018-2020 Intel Corporation // // 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 <vector> #include "he_type.hpp" #include "ngraph/coordinate_transform.hpp" #include "ngraph/type/element_type.hpp" #include "seal/he_seal_backend.hpp" #include "seal/kernel/add_seal.hpp" namespace ngraph::runtime::he { inline void sum_seal(std::vector<HEType>& arg, std::vector<HEType>& out, const Shape& in_shape, const Shape& out_shape, const AxisSet& reduction_axes, const element::Type& element_type, HESealBackend& he_seal_backend) { NGRAPH_CHECK(he_seal_backend.is_supported_type(element_type), "Unsupported type ", element_type); CoordinateTransform output_transform(out_shape); bool complex_packing = arg.size() > 0 ? arg[0].complex_packing() : false; size_t batch_size = arg.size() > 0 ? arg[0].batch_size() : 1; for (const Coordinate& output_coord : output_transform) { // TODO(fboemer): batch size const auto out_coord_idx = output_transform.index(output_coord); out[out_coord_idx] = HEType(HEPlaintext(std::vector<double>(batch_size, 0)), complex_packing); } CoordinateTransform input_transform(in_shape); for (const Coordinate& input_coord : input_transform) { Coordinate output_coord = reduce(input_coord, reduction_axes); auto& input = arg[input_transform.index(input_coord)]; auto& output = out[output_transform.index(output_coord)]; scalar_add_seal(input, output, output, he_seal_backend); } } } // namespace ngraph::runtime::he
39.237288
80
0.657451
EvonneH
a8a36661456c5bf9ba950af734daceb336b578d5
16,767
cpp
C++
ace/tao/tests/rtcorba/RTMutex/server.cpp
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
46
2015-12-04T17:12:58.000Z
2022-03-11T04:30:49.000Z
ace/tao/tests/rtcorba/RTMutex/server.cpp
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
null
null
null
ace/tao/tests/rtcorba/RTMutex/server.cpp
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
23
2016-10-24T09:18:14.000Z
2022-02-25T02:11:35.000Z
// server.cpp,v 1.7 2001/06/12 18:58:41 fhunleth Exp #include "tao/corba.h" #include "tao/RTCORBA/RTCORBA.h" #include "ace/Thread_Manager.h" #include "ace/High_Res_Timer.h" #include "ace/Get_Opt.h" static int test_try_lock_flag = #if defined (ACE_HAS_MUTEX_TIMEOUTS) && !defined (ACE_HAS_WTHREADS) 1; #else // Don't test try_lock timed waits unless the underlying OS supports it // Windows is the exception. It supports some mutex timeouts, so // it has ACE_HAS_MUTEX_TIMEOUTS defined, but it doesn't support // thread mutex timeouts which is what is needed for this to work. 0; #endif /* defined (ACE_HAS_MUTEX_TIMEOUTS) && !defined (ACE_HAS_WTHREADS) */ // Parse command-line arguments. static int parse_args (int argc, char *argv[]) { ACE_Get_Opt get_opts (argc, argv, "t"); int c; while ((c = get_opts ()) != -1) switch (c) { case 't': test_try_lock_flag = 0; break; case '?': default: ACE_ERROR_RETURN ((LM_ERROR, "usage: %s " "-t" "\n", argv [0]), -1); } return 0; } static int check_for_nil (CORBA::Object_ptr obj, const char *msg) { if (CORBA::is_nil (obj)) ACE_ERROR_RETURN ((LM_ERROR, "ERROR: Object reference <%s> is nil\n", msg), -1); else return 0; } static int test_mutex_simple (RTCORBA::RTORB_ptr rt_orb) { // Test the basic interface of the RTCORBA::Mutex This test should // run even on platforms without thread support. ACE_TRY_NEW_ENV { RTCORBA::Mutex_var my_mutex; my_mutex = rt_orb->create_mutex (ACE_TRY_ENV); ACE_TRY_CHECK; my_mutex->lock (ACE_TRY_ENV); ACE_TRY_CHECK; my_mutex->unlock (ACE_TRY_ENV); ACE_TRY_CHECK; my_mutex->lock (ACE_TRY_ENV); ACE_TRY_CHECK; my_mutex->unlock (ACE_TRY_ENV); ACE_TRY_CHECK; rt_orb->destroy_mutex (my_mutex.in (), ACE_TRY_ENV); ACE_TRY_CHECK; } ACE_CATCHANY { ACE_PRINT_EXCEPTION (ACE_ANY_EXCEPTION, "Unexpected exception caught in test_mutex_simple()"); return 1; } ACE_ENDTRY; return 0; } #if (TAO_HAS_NAMED_RT_MUTEXES == 1) static int test_named_mutex_simple (RTCORBA::RTORB_ptr rt_orb) { // Test the basic interface of the named RTCORBA::Mutex(es) This // test should run even on platforms without thread support. ACE_TRY_NEW_ENV { RTCORBA::Mutex_var larry_mutex1; RTCORBA::Mutex_var moe_mutex1; CORBA::Boolean created_flag; larry_mutex1 = rt_orb->create_named_mutex ("larry", created_flag, ACE_TRY_ENV); ACE_TRY_CHECK; if (created_flag != 1) ACE_ERROR_RETURN ((LM_ERROR, "ERROR: Expected named mutex larry to be created, but it wasn't\n"), 1); moe_mutex1 = rt_orb->create_named_mutex ("moe", created_flag, ACE_TRY_ENV); ACE_TRY_CHECK; if (created_flag != 1) ACE_ERROR_RETURN ((LM_ERROR, "ERROR: Expected named mutex moe to be created, but it wasn't\n"), 1); larry_mutex1->lock (ACE_TRY_ENV); ACE_TRY_CHECK; larry_mutex1->unlock (ACE_TRY_ENV); ACE_TRY_CHECK; // Test creating the mutex a second time { RTCORBA::Mutex_var larry_mutex2; larry_mutex2 = rt_orb->create_named_mutex ("larry", created_flag, ACE_TRY_ENV); ACE_TRY_CHECK; if (created_flag != 0) ACE_ERROR_RETURN ((LM_ERROR, "ERROR: Expected named mutex to already be created, but it wasn't\n"), 1); // test the pointers... if (ACE_reinterpret_cast (void *, larry_mutex1.in ()) != ACE_reinterpret_cast (void *, larry_mutex2.in ())) ACE_ERROR_RETURN ((LM_ERROR, "ERROR: Should have gotten the same mutex, but didn't\n"), 1); larry_mutex2->lock (ACE_TRY_ENV); ACE_TRY_CHECK; larry_mutex2->unlock (ACE_TRY_ENV); ACE_TRY_CHECK; } // test opening the mutex { RTCORBA::Mutex_var larry_mutex3; larry_mutex3 = rt_orb->open_named_mutex ("larry", ACE_TRY_ENV); ACE_TRY_CHECK; // test the pointers... if (ACE_reinterpret_cast (void *,larry_mutex1.in ()) != ACE_reinterpret_cast (void *,larry_mutex3.in ())) ACE_ERROR_RETURN ((LM_ERROR, "ERROR: Should have gotten the same mutex, but didn't\n"), 1); larry_mutex3->lock (ACE_TRY_ENV); ACE_TRY_CHECK; larry_mutex3->unlock (ACE_TRY_ENV); ACE_TRY_CHECK; } // Make sure that nothing has been broken behind the scenes. larry_mutex1->lock (ACE_TRY_ENV); ACE_TRY_CHECK; larry_mutex1->unlock (ACE_TRY_ENV); ACE_TRY_CHECK; rt_orb->destroy_mutex (larry_mutex1.in (), ACE_TRY_ENV); ACE_TRY_CHECK; rt_orb->destroy_mutex (moe_mutex1.in (), ACE_TRY_ENV); ACE_TRY_CHECK; } ACE_CATCHANY { ACE_PRINT_EXCEPTION (ACE_ANY_EXCEPTION, "Unexpected exception caught in test_named_mutex_simple()"); return 1; } ACE_ENDTRY; return 0; } static int test_named_mutex_exception (RTCORBA::RTORB_ptr rt_orb) { // Test that open_named_mutex returns an exception when the mutex // name isn't found. // This test should run even on platforms without thread support. ACE_TRY_NEW_ENV { RTCORBA::Mutex_var larry_mutex1; larry_mutex1 = rt_orb->open_named_mutex ("larry", ACE_TRY_ENV); ACE_TRY_CHECK; ACE_ERROR_RETURN ((LM_ERROR, "Expected a MutexNotFound exception, but didn't get one.\n"), 1); } ACE_CATCH (RTCORBA::RTORB::MutexNotFound, ex) { ACE_DEBUG ((LM_DEBUG, "Caught expected MutexNotFound exception.\n")); } ACE_CATCHANY { ACE_PRINT_EXCEPTION (ACE_ANY_EXCEPTION, "Unexpected exception caught in test_named_mutex_exception()"); return 1; } ACE_ENDTRY; return 0; } #endif /* TAO_HAS_NAMED_RT_MUTEXES == 1 */ #if defined (ACE_HAS_THREADS) const size_t MAX_ITERATIONS=10; const size_t MAX_THREADS=4; struct Mutex_Test_Data { RTCORBA::Mutex_ptr mutex; int *shared_var; int *error_flag; }; static void * mutex_test_thread (void *args) { Mutex_Test_Data *data = ACE_reinterpret_cast (Mutex_Test_Data *, args); RTCORBA::Mutex_ptr mutex = data->mutex; int *shared_var = data->shared_var; ACE_OS::srand (ACE_OS::time (0)); ACE_TRY_NEW_ENV { for (size_t i = 0; i < MAX_ITERATIONS / 2; i++) { ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%P|%t) = trying to lock on iteration %d\n"), i)); mutex->lock (); ACE_TRY_CHECK; ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%P|%t) = locked on iteration %d\n"), i)); // Check if the shared var is a value it shouldn't be when // we're under the lock. if (*shared_var != 0) { ACE_ERROR ((LM_ERROR, "Expected shared_var to be 0 under the mutex\n")); *data->error_flag = 1; } *shared_var = 1; // Sleep for a random amount of time between 0 and 2 // seconds. Note that it's ok to use rand() here because we // are running within the critical section defined by the // Thread_Mutex. ACE_OS::sleep (ACE_OS::rand () % 2); if (*shared_var != 1) { ACE_ERROR ((LM_ERROR, "Expected shared_var to still be 1 after sleeping\n")); *data->error_flag = 1; } *shared_var = 0; mutex->unlock (); ACE_TRY_CHECK; ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%P|%t) = unlocked on iteration %d\n"), i)); } } ACE_CATCHANY { ACE_PRINT_EXCEPTION (ACE_ANY_EXCEPTION, "Unexpected exception caught in mutex_test_thread()"); *data->error_flag = 1; } ACE_ENDTRY; return 0; } static int test_mutex_threads (RTCORBA::RTORB_ptr rt_orb) { // test the RTCORBA::Mutex implementation be spawning many threads // that repeatedly content for a lock. This code is based on the // tests/Thread_Mutex_Test code. Mutex_Test_Data test_data; const u_int n_threads = #if defined (__Lynx__) 3; /* It just doesn't work with 4 threads. (Advice from Thread_Mutex_Test.cpp) */ #else /* ! __Lynx__ */ MAX_THREADS; #endif /* ! __Lynx__ */ int shared_var = 0; int error_flag = 0; ACE_TRY_NEW_ENV { RTCORBA::Mutex_ptr mutex = rt_orb->create_mutex (ACE_TRY_ENV); ACE_TRY_CHECK; test_data.mutex = mutex; test_data.shared_var = &shared_var; test_data.error_flag = &error_flag; if (ACE_Thread_Manager::instance ()->spawn_n (n_threads, ACE_THR_FUNC (mutex_test_thread), (void *) &test_data, THR_NEW_LWP | THR_DETACHED) == -1) ACE_ERROR ((LM_ERROR, ACE_TEXT ("%p\n%a"), ACE_TEXT ("thread create failed"))); // Wait for the threads to exit. ACE_Thread_Manager::instance ()->wait (); CORBA::release (mutex); } ACE_CATCHANY { ACE_PRINT_EXCEPTION (ACE_ANY_EXCEPTION, "Unexpected exception caught in test_mutex_threads()"); return 1; } ACE_ENDTRY; return error_flag; } static void * mutex_test_try_lock_thread (void *args) { // test out try_lock() failure cases Mutex_Test_Data *data = ACE_reinterpret_cast (Mutex_Test_Data *, args); RTCORBA::Mutex_ptr mutex = data->mutex; CORBA::Boolean result; ACE_TRY_NEW_ENV { // check that try_lock (0) returns false ACE_DEBUG ((LM_DEBUG,"attempting try_lock (0) - expect failure (but no exceptions) \n")); result = mutex->try_lock (0u, ACE_TRY_ENV); ACE_TRY_CHECK; if (result) { ACE_ERROR ((LM_ERROR, "try_lock succeeded, but expected a failure\n")); *data->error_flag = 1; } if (test_try_lock_flag) { ACE_High_Res_Timer timer; // Check that try_lock (timeout) returns false (and times // out) ACE_DEBUG ((LM_DEBUG, "attempting try_lock (5 sec) - expect failure after 5 secs (but no exceptions)\n")); timer.start (); result = mutex->try_lock (50000000u /*5sec*/,ACE_TRY_ENV); ACE_TRY_CHECK; timer.stop (); if (result) { ACE_ERROR ((LM_ERROR, "try_lock (timeout) succeeded, but expected a failure\n")); *data->error_flag = 1; } ACE_Time_Value measured; timer.elapsed_time (measured); ACE_DEBUG ((LM_DEBUG, "try_lock returned after %u secs, %u usecs\n", measured.sec(), measured.usec())); if ((measured.sec() == 4 && measured.usec() >= 500000) || (measured.sec() == 5 && measured.usec() <= 500000)) /* success */; else { ACE_ERROR ((LM_ERROR, "try_lock timed out not as expected\n")); *data->error_flag = 1; } } } ACE_CATCHANY { ACE_PRINT_EXCEPTION (ACE_ANY_EXCEPTION, "Unexpected exception caught in mutex_test_try_lock_thread()"); *data->error_flag = 1; } ACE_ENDTRY; return 0; } static int test_mutex_try_lock (RTCORBA::RTORB_ptr rt_orb) { Mutex_Test_Data test_data; CORBA::Boolean result; int shared_var = 0; int error_flag = 0; ACE_TRY_NEW_ENV { RTCORBA::Mutex_ptr mutex = rt_orb->create_mutex (ACE_TRY_ENV); ACE_TRY_CHECK; // Test out try_lock and keep the lock so that the spawned task // can test out try_lock failure cases result = mutex->try_lock (0u, ACE_TRY_ENV); ACE_TRY_CHECK; if (!result) ACE_ERROR_RETURN ((LM_ERROR, "try_lock failed\n"), 1); test_data.mutex = mutex; test_data.shared_var = &shared_var; test_data.error_flag = &error_flag; ACE_DEBUG ((LM_DEBUG, "Spawning the test thread\n")); if (ACE_Thread_Manager::instance ()->spawn (ACE_THR_FUNC (mutex_test_try_lock_thread), (void *) &test_data, THR_NEW_LWP | THR_DETACHED) == -1) ACE_ERROR ((LM_ERROR, ACE_TEXT ("%p\n%a"), ACE_TEXT ("thread create failed"))); // Wait for the threads to exit. ACE_Thread_Manager::instance ()->wait (); CORBA::release (mutex); } ACE_CATCHANY { ACE_PRINT_EXCEPTION (ACE_ANY_EXCEPTION, "Unexpected exception caught in test_mutex_try_lock()"); return 1; } ACE_ENDTRY; return error_flag; } #endif /* ACE_HAS_THREADS */ int main (int argc, char *argv[]) { ACE_TRY_NEW_ENV { // ORB. CORBA::ORB_var orb = CORBA::ORB_init (argc, argv, "", ACE_TRY_ENV); ACE_TRY_CHECK; // Parse arguments. if (parse_args (argc, argv) != 0) return 1; // RTORB. CORBA::Object_var object = orb->resolve_initial_references ("RTORB", ACE_TRY_ENV); ACE_TRY_CHECK; RTCORBA::RTORB_var rt_orb = RTCORBA::RTORB::_narrow (object.in (), ACE_TRY_ENV); ACE_TRY_CHECK; if (check_for_nil (rt_orb.in (), "RTORB") == -1) return 1; ACE_DEBUG ((LM_DEBUG, "Running RTCORBA Mutex unit tests\n")); if (test_mutex_simple (rt_orb.in ()) != 0) ACE_ERROR_RETURN ((LM_ERROR, "test_mutex_simple failed\n"), 1); #if (TAO_HAS_NAMED_RT_MUTEXES == 1) if (test_named_mutex_simple (rt_orb.in ()) != 0) ACE_ERROR_RETURN ((LM_ERROR, "test_named_mutex_simple failed\n"), 1); if (test_named_mutex_exception (rt_orb. in ()) != 0) ACE_ERROR_RETURN ((LM_ERROR, "test_named_mutex_exception failed\n"), 1); #else ACE_DEBUG ((LM_DEBUG, "Named RT_Mutex support is not enabled. " "Skipping Named RT_Mutex tests.\n")); #endif /* TAO_HAS_NAMED_RT_MUTEXES == 1 */ #if defined (ACE_HAS_THREADS) if (test_mutex_threads (rt_orb.in ()) != 0) ACE_ERROR_RETURN ((LM_ERROR, "test_mutex_threads failed\n"), 1); else if (test_mutex_try_lock (rt_orb.in ()) != 0) ACE_ERROR_RETURN ((LM_ERROR, "test_mutex_try_lock failed\n"), 1); #endif /* ACE_HAS_THREADS */ ACE_DEBUG ((LM_DEBUG, "Mutex test finished\n\n")); } ACE_CATCHANY { ACE_PRINT_EXCEPTION (ACE_ANY_EXCEPTION, "Unexpected exception caught in Mutex test server:"); return 1; } ACE_ENDTRY; return 0; }
29.109375
107
0.532534
tharindusathis
a8a521f777439850ad9f7a57b50d90c80a2093c7
10,656
cc
C++
ui/gl/delegated_ink_point_renderer_gpu_unittest.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2020-10-18T02:33:40.000Z
2020-10-18T02:33:40.000Z
ui/gl/delegated_ink_point_renderer_gpu_unittest.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
3
2021-05-17T16:28:52.000Z
2021-05-21T22:42:22.000Z
ui/gl/delegated_ink_point_renderer_gpu_unittest.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/gl/delegated_ink_point_renderer_gpu.h" #include <memory> #include "base/run_loop.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/base/win/hidden_window.h" #include "ui/gfx/geometry/vector2d_f.h" #include "ui/gl/dc_layer_tree.h" #include "ui/gl/direct_composition_surface_win.h" #include "ui/gl/gl_angle_util_win.h" #include "ui/gl/gl_context.h" #include "ui/gl/init/gl_factory.h" namespace gl { namespace { class DelegatedInkPointRendererGpuTest : public testing::Test { public: DelegatedInkPointRendererGpuTest() : parent_window_(ui::GetHiddenWindow()) {} DirectCompositionSurfaceWin* surface() { return surface_.get(); } DCLayerTree* layer_tree() { return surface()->GetLayerTreeForTesting(); } DCLayerTree::DelegatedInkRenderer* ink_renderer() { return layer_tree()->GetInkRendererForTesting(); } void SendDelegatedInkPointBasedOnPrevious() { const base::circular_deque<gfx::DelegatedInkPoint>& ink_points = ink_renderer()->DelegatedInkPointsForTesting(); DCHECK(!ink_points.empty()); auto last_point = ink_points.back(); ink_renderer()->StoreDelegatedInkPoint(gfx::DelegatedInkPoint( last_point.point() + gfx::Vector2dF(5, 5), last_point.timestamp() + base::TimeDelta::FromMicroseconds(10), last_point.pointer_id())); } void SendMetadata(const gfx::DelegatedInkMetadata& metadata) { surface()->SetDelegatedInkTrailStartPoint( std::make_unique<gfx::DelegatedInkMetadata>(metadata)); } gfx::DelegatedInkMetadata SendMetadataBasedOnStoredPoint(uint64_t point) { const base::circular_deque<gfx::DelegatedInkPoint>& ink_points = ink_renderer()->DelegatedInkPointsForTesting(); EXPECT_GE(ink_points.size(), point); auto ink_point = ink_points[point]; gfx::DelegatedInkMetadata metadata( ink_point.point(), /*diameter=*/3, SK_ColorBLACK, ink_point.timestamp(), gfx::RectF(0, 0, 100, 100), /*hovering=*/false); SendMetadata(metadata); return metadata; } void StoredMetadataMatchesSentMetadata( const gfx::DelegatedInkMetadata& sent_metadata) { gfx::DelegatedInkMetadata* renderer_metadata = ink_renderer()->MetadataForTesting(); EXPECT_TRUE(renderer_metadata); EXPECT_EQ(renderer_metadata->point(), sent_metadata.point()); EXPECT_EQ(renderer_metadata->diameter(), sent_metadata.diameter()); EXPECT_EQ(renderer_metadata->color(), sent_metadata.color()); EXPECT_EQ(renderer_metadata->timestamp(), sent_metadata.timestamp()); EXPECT_EQ(renderer_metadata->presentation_area(), sent_metadata.presentation_area()); EXPECT_EQ(renderer_metadata->is_hovering(), sent_metadata.is_hovering()); } protected: void SetUp() override { // Without this, the following check always fails. gl::init::InitializeGLNoExtensionsOneOff(/*init_bindings=*/true); if (!QueryDirectCompositionDevice(QueryD3D11DeviceObjectFromANGLE())) { LOG(WARNING) << "GL implementation not using DirectComposition, skipping test."; return; } CreateDirectCompositionSurfaceWin(); if (!surface_->SupportsDelegatedInk()) { LOG(WARNING) << "Delegated ink unsupported, skipping test."; return; } CreateGLContext(); surface_->SetEnableDCLayers(true); // Create the swap chain constexpr gfx::Size window_size(100, 100); EXPECT_TRUE(surface_->Resize(window_size, 1.0, gfx::ColorSpace(), true)); EXPECT_TRUE(surface_->SetDrawRectangle(gfx::Rect(window_size))); } void TearDown() override { context_ = nullptr; if (surface_) DestroySurface(std::move(surface_)); gl::init::ShutdownGL(false); } private: void CreateDirectCompositionSurfaceWin() { DirectCompositionSurfaceWin::Settings settings; surface_ = base::MakeRefCounted<DirectCompositionSurfaceWin>( parent_window_, DirectCompositionSurfaceWin::VSyncCallback(), settings); EXPECT_TRUE(surface_->Initialize(GLSurfaceFormat())); // ImageTransportSurfaceDelegate::DidCreateAcceleratedSurfaceChildWindow() // is called in production code here. However, to remove dependency from // gpu/ipc/service/image_transport_surface_delegate.h, here we directly // executes the required minimum code. if (parent_window_) ::SetParent(surface_->window(), parent_window_); } void CreateGLContext() { context_ = gl::init::CreateGLContext(nullptr, surface_.get(), GLContextAttribs()); EXPECT_TRUE(context_->MakeCurrent(surface_.get())); } void DestroySurface(scoped_refptr<DirectCompositionSurfaceWin> surface) { scoped_refptr<base::TaskRunner> task_runner = surface->GetWindowTaskRunnerForTesting(); DCHECK(surface->HasOneRef()); surface = nullptr; base::RunLoop run_loop; task_runner->PostTask(FROM_HERE, run_loop.QuitClosure()); run_loop.Run(); } HWND parent_window_; scoped_refptr<DirectCompositionSurfaceWin> surface_; scoped_refptr<GLContext> context_; }; // Test to confirm that points and tokens are stored and removed correctly based // on when the metadata and points arrive. TEST_F(DelegatedInkPointRendererGpuTest, StoreAndRemovePointsAndTokens) { if (!surface() || !surface()->SupportsDelegatedInk()) return; // Send some points and make sure they are all stored even with no metadata. ink_renderer()->StoreDelegatedInkPoint( gfx::DelegatedInkPoint(gfx::PointF(10, 10), base::TimeTicks::Now(), 1)); const uint64_t kPointsToStore = 5u; for (uint64_t i = 1; i < kPointsToStore; ++i) SendDelegatedInkPointBasedOnPrevious(); EXPECT_EQ(ink_renderer()->DelegatedInkPointsForTesting().size(), kPointsToStore); EXPECT_TRUE(ink_renderer()->InkTrailTokensForTesting().empty()); EXPECT_FALSE(ink_renderer()->MetadataForTesting()); EXPECT_TRUE(ink_renderer()->WaitForNewTrailToDrawForTesting()); // Now send metadata that matches the first stored point. This should result // in all of the points being drawn and matching tokens stored. None of the // points should be removed from the circular deque because they are stored // until a metadata arrives with a later timestamp gfx::DelegatedInkMetadata metadata = SendMetadataBasedOnStoredPoint(0); EXPECT_EQ(ink_renderer()->DelegatedInkPointsForTesting().size(), kPointsToStore); EXPECT_EQ(ink_renderer()->InkTrailTokensForTesting().size(), kPointsToStore); EXPECT_FALSE(ink_renderer()->WaitForNewTrailToDrawForTesting()); StoredMetadataMatchesSentMetadata(metadata); // Now send a metadata that matches a later one of the points. It should // result in some of the stored points being erased, and one more token erased // than points erased. This is because we don't need to store the token of the // point that exactly matches the metadata. const uint64_t kPointToSend = 3u; metadata = SendMetadataBasedOnStoredPoint(kPointToSend); EXPECT_EQ(ink_renderer()->DelegatedInkPointsForTesting().size(), kPointsToStore - kPointToSend); // Subtract one extra because the token for the point that matches the new // metadata is erased too. EXPECT_EQ(ink_renderer()->InkTrailTokensForTesting().size(), kPointsToStore - kPointToSend - 1); StoredMetadataMatchesSentMetadata(metadata); // Now send a metadata after all of the stored point to make sure that it // results in all the tokens and stored points being erased because a new // trail is started. gfx::DelegatedInkPoint last_point = ink_renderer()->DelegatedInkPointsForTesting().back(); metadata = gfx::DelegatedInkMetadata( last_point.point() + gfx::Vector2dF(2, 2), /*diameter=*/3, SK_ColorBLACK, last_point.timestamp() + base::TimeDelta::FromMicroseconds(20), gfx::RectF(0, 0, 100, 100), /*hovering=*/false); SendMetadata(metadata); EXPECT_EQ(ink_renderer()->DelegatedInkPointsForTesting().size(), 0u); EXPECT_EQ(ink_renderer()->InkTrailTokensForTesting().size(), 0u); StoredMetadataMatchesSentMetadata(metadata); } // Basic test to confirm that points are drawn as they arrive if they are in the // presentation area and after the metadata's timestamp. TEST_F(DelegatedInkPointRendererGpuTest, DrawPointsAsTheyArrive) { if (!surface() || !surface()->SupportsDelegatedInk()) return; gfx::DelegatedInkMetadata metadata( gfx::PointF(12, 12), /*diameter=*/3, SK_ColorBLACK, base::TimeTicks::Now(), gfx::RectF(10, 10, 90, 90), /*hovering=*/false); SendMetadata(metadata); // Send some points that should all be drawn to ensure that they are all drawn // as they arrive. const uint64_t kPointsToSend = 5u; for (uint64_t i = 1u; i <= kPointsToSend; ++i) { if (i == 1) { ink_renderer()->StoreDelegatedInkPoint(gfx::DelegatedInkPoint( metadata.point(), metadata.timestamp(), /*pointer_id=*/1)); } else { SendDelegatedInkPointBasedOnPrevious(); } EXPECT_EQ(ink_renderer()->DelegatedInkPointsForTesting().size(), i); EXPECT_EQ(ink_renderer()->InkTrailTokensForTesting().size(), i); } // Now send a point that is outside of the presentation area to ensure that // it is not drawn. It will still be stored - this is so if a future metadata // arrives with a presentation area that would contain this point, it can // still be drawn. gfx::DelegatedInkPoint last_point = ink_renderer()->DelegatedInkPointsForTesting().back(); gfx::DelegatedInkPoint outside_point( gfx::PointF(5, 5), last_point.timestamp() + base::TimeDelta::FromMicroseconds(10), /*pointer_id=*/1); EXPECT_FALSE(metadata.presentation_area().Contains((outside_point.point()))); ink_renderer()->StoreDelegatedInkPoint(outside_point); const uint64_t kTotalPointsSent = kPointsToSend + 1u; EXPECT_EQ(ink_renderer()->DelegatedInkPointsForTesting().size(), kTotalPointsSent); EXPECT_EQ(ink_renderer()->InkTrailTokensForTesting().size(), kPointsToSend); // Then send a metadata with a larger presentation area and timestamp earlier // than the above point to confirm it will be the only point drawn, but all // the points with later timestamps will be stored. const uint64_t kMetadataToSend = 3u; SendMetadataBasedOnStoredPoint(kMetadataToSend); EXPECT_EQ(ink_renderer()->DelegatedInkPointsForTesting().size(), kTotalPointsSent - kMetadataToSend); EXPECT_EQ(ink_renderer()->InkTrailTokensForTesting().size(), 1u); } } // namespace } // namespace gl
40.51711
80
0.730199
DamieFC
a8a73509cf5477194e49a6c65a2499eddbe23dd0
4,720
cc
C++
src/shared/load_data_command.cc
schinmayee/nimbus
170cd15e24a7a88243a6ea80aabadc0fc0e6e177
[ "BSD-3-Clause" ]
20
2017-07-03T19:09:09.000Z
2021-09-10T02:53:56.000Z
src/shared/load_data_command.cc
schinmayee/nimbus
170cd15e24a7a88243a6ea80aabadc0fc0e6e177
[ "BSD-3-Clause" ]
null
null
null
src/shared/load_data_command.cc
schinmayee/nimbus
170cd15e24a7a88243a6ea80aabadc0fc0e6e177
[ "BSD-3-Clause" ]
9
2017-09-17T02:05:06.000Z
2020-01-31T00:12:01.000Z
/* * Copyright 2013 Stanford University. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * - Neither the name of the copyright holders nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * A command sent from the controller to a worker to load a physical data from * non-volatile memory. This command is used to rewind from a distributed * checkpoint in the system in case of failure. * * Author: Omid Mashayekhi <omidm@stanford.edu> */ #include "src/shared/load_data_command.h" using namespace nimbus; // NOLINT using boost::tokenizer; using boost::char_separator; LoadDataCommand::LoadDataCommand() { name_ = LOAD_DATA_NAME; type_ = LOAD_DATA; } LoadDataCommand::LoadDataCommand(const ID<job_id_t>& job_id, const ID<physical_data_id_t>& to_physical_data_id, const std::string& handle, const IDSet<job_id_t>& before) : job_id_(job_id), to_physical_data_id_(to_physical_data_id), handle_(handle), before_set_(before) { name_ = LOAD_DATA_NAME; type_ = LOAD_DATA; } LoadDataCommand::~LoadDataCommand() { } SchedulerCommand* LoadDataCommand::Clone() { return new LoadDataCommand(); } bool LoadDataCommand::Parse(const std::string& data) { LoadDataPBuf buf; bool result = buf.ParseFromString(data); if (!result) { dbg(DBG_ERROR, "ERROR: Failed to parse LoadDataCommand from string.\n"); return false; } else { ReadFromProtobuf(buf); return true; } } bool LoadDataCommand::Parse(const SchedulerPBuf& buf) { if (!buf.has_load_data()) { dbg(DBG_ERROR, "ERROR: Failed to parse LoadDataCommand from SchedulerPBuf.\n"); return false; } else { return ReadFromProtobuf(buf.load_data()); } } std::string LoadDataCommand::ToNetworkData() { std::string result; // First we construct a general scheduler buffer, then // add the spawn compute field to it, then serialize. SchedulerPBuf buf; buf.set_type(SchedulerPBuf_Type_LOAD_DATA); LoadDataPBuf* cmd = buf.mutable_load_data(); WriteToProtobuf(cmd); buf.SerializeToString(&result); return result; } std::string LoadDataCommand::ToString() { std::string str; str += (name_ + ","); str += ("job-id:" + job_id_.ToNetworkData() + ","); str += ("to-physical-data-id:" + to_physical_data_id_.ToNetworkData() + ","); str += ("handle:" + handle_ + ","); str += ("before:" + before_set_.ToNetworkData()); return str; } ID<job_id_t> LoadDataCommand::job_id() { return job_id_; } ID<physical_data_id_t> LoadDataCommand::to_physical_data_id() { return to_physical_data_id_; } std::string LoadDataCommand::handle() { return handle_; } IDSet<job_id_t> LoadDataCommand::before_set() { return before_set_; } bool LoadDataCommand::ReadFromProtobuf(const LoadDataPBuf& buf) { job_id_.set_elem(buf.job_id()); to_physical_data_id_.set_elem(buf.to_physical_id()); handle_ = buf.handle(); before_set_.ConvertFromRepeatedField(buf.before_set().ids()); return true; } bool LoadDataCommand::WriteToProtobuf(LoadDataPBuf* buf) { buf->set_job_id(job_id().elem()); buf->set_to_physical_id(to_physical_data_id().elem()); buf->set_handle(handle()); before_set_.ConvertToRepeatedField(buf->mutable_before_set()->mutable_ids()); return true; }
30.849673
83
0.718856
schinmayee
a8a77df15ad77dd3277bb2ca4dc8a1e6e20d0ab2
9,893
cc
C++
android_webview/browser/hardware_renderer.cc
hokein/chromium
69328672dd0c5b93e0b65fc344feb11bbdc37b6b
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2019-04-27T20:21:55.000Z
2019-04-27T20:21:55.000Z
android_webview/browser/hardware_renderer.cc
hokein/chromium
69328672dd0c5b93e0b65fc344feb11bbdc37b6b
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
android_webview/browser/hardware_renderer.cc
hokein/chromium
69328672dd0c5b93e0b65fc344feb11bbdc37b6b
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "android_webview/browser/hardware_renderer.h" #include "android_webview/browser/aw_gl_surface.h" #include "android_webview/browser/browser_view_renderer.h" #include "android_webview/browser/gl_view_renderer_manager.h" #include "android_webview/browser/scoped_app_gl_state_restore.h" #include "android_webview/common/aw_switches.h" #include "android_webview/public/browser/draw_gl.h" #include "base/command_line.h" #include "base/debug/trace_event.h" #include "base/strings/string_number_conversions.h" #include "content/public/browser/browser_thread.h" #include "content/public/common/content_switches.h" #include "ui/gfx/transform.h" using content::BrowserThread; namespace android_webview { namespace { // Used to calculate memory and resource allocation. Determined experimentally. const size_t g_memory_multiplier = 10; const size_t g_num_gralloc_limit = 150; const size_t kBytesPerPixel = 4; const size_t kMemoryAllocationStep = 5 * 1024 * 1024; base::LazyInstance<scoped_refptr<internal::DeferredGpuCommandService> > g_service = LAZY_INSTANCE_INITIALIZER; } // namespace DrawGLResult::DrawGLResult() : did_draw(false), clip_contains_visible_rect(false) {} HardwareRenderer::HardwareRenderer(content::SynchronousCompositor* compositor, BrowserViewRendererClient* client) : compositor_(compositor), client_(client), last_egl_context_(eglGetCurrentContext()), manager_key_(GLViewRendererManager::GetInstance()->NullKey()) { DCHECK(compositor_); DCHECK(last_egl_context_); } HardwareRenderer::~HardwareRenderer() { GLViewRendererManager* mru = GLViewRendererManager::GetInstance(); if (manager_key_ != mru->NullKey()) { mru->NoLongerExpectsDrawGL(manager_key_); manager_key_ = mru->NullKey(); } if (gl_surface_) { ScopedAppGLStateRestore state_restore( ScopedAppGLStateRestore::MODE_RESOURCE_MANAGEMENT); internal::ScopedAllowGL allow_gl; compositor_->ReleaseHwDraw(); gl_surface_ = NULL; } DCHECK(manager_key_ == GLViewRendererManager::GetInstance()->NullKey()); } bool HardwareRenderer::InitializeHardwareDraw() { TRACE_EVENT0("android_webview", "InitializeHardwareDraw"); if (!g_service.Get()) { g_service.Get() = new internal::DeferredGpuCommandService; content::SynchronousCompositor::SetGpuService(g_service.Get()); } bool success = true; if (!gl_surface_) { scoped_refptr<AwGLSurface> gl_surface = new AwGLSurface; success = compositor_->InitializeHwDraw(gl_surface); if (success) gl_surface_ = gl_surface; } return success; } DrawGLResult HardwareRenderer::DrawGL(AwDrawGLInfo* draw_info, const DrawGLInput& input) { TRACE_EVENT0("android_webview", "HardwareRenderer::DrawGL"); manager_key_ = GLViewRendererManager::GetInstance()->DidDrawGL(manager_key_, this); DrawGLResult result; // We need to watch if the current Android context has changed and enforce // a clean-up in the compositor. EGLContext current_context = eglGetCurrentContext(); if (!current_context) { DLOG(ERROR) << "DrawGL called without EGLContext"; return result; } // TODO(boliu): Handle context loss. if (last_egl_context_ != current_context) DLOG(WARNING) << "EGLContextChanged"; ScopedAppGLStateRestore state_restore(ScopedAppGLStateRestore::MODE_DRAW); internal::ScopedAllowGL allow_gl; if (draw_info->mode == AwDrawGLInfo::kModeProcess) return result; if (!InitializeHardwareDraw()) { DLOG(ERROR) << "WebView hardware initialization failed"; return result; } // Update memory budget. This will no-op in compositor if the policy has not // changed since last draw. content::SynchronousCompositorMemoryPolicy policy; policy.bytes_limit = g_memory_multiplier * kBytesPerPixel * input.global_visible_rect.width() * input.global_visible_rect.height(); // Round up to a multiple of kMemoryAllocationStep. policy.bytes_limit = (policy.bytes_limit / kMemoryAllocationStep + 1) * kMemoryAllocationStep; policy.num_resources_limit = g_num_gralloc_limit; SetMemoryPolicy(policy); gl_surface_->SetBackingFrameBufferObject( state_restore.framebuffer_binding_ext()); gfx::Transform transform; transform.matrix().setColMajorf(draw_info->transform); transform.Translate(input.scroll.x(), input.scroll.y()); gfx::Rect clip_rect(draw_info->clip_left, draw_info->clip_top, draw_info->clip_right - draw_info->clip_left, draw_info->clip_bottom - draw_info->clip_top); gfx::Rect viewport_rect; if (draw_info->is_layer) { viewport_rect = clip_rect; } else { viewport_rect = input.global_visible_rect; clip_rect.Intersect(viewport_rect); } result.clip_contains_visible_rect = clip_rect.Contains(viewport_rect); result.did_draw = compositor_->DemandDrawHw(gfx::Size(draw_info->width, draw_info->height), transform, viewport_rect, clip_rect, state_restore.stencil_enabled()); gl_surface_->ResetBackingFrameBufferObject(); return result; } bool HardwareRenderer::TrimMemory(int level, bool visible) { // Constants from Android ComponentCallbacks2. enum { TRIM_MEMORY_RUNNING_LOW = 10, TRIM_MEMORY_UI_HIDDEN = 20, TRIM_MEMORY_BACKGROUND = 40, }; // Not urgent enough. TRIM_MEMORY_UI_HIDDEN is treated specially because // it does not indicate memory pressure, but merely that the app is // backgrounded. if (level < TRIM_MEMORY_RUNNING_LOW || level == TRIM_MEMORY_UI_HIDDEN) return false; // Do not release resources on view we expect to get DrawGL soon. if (level < TRIM_MEMORY_BACKGROUND && visible) return false; if (!eglGetCurrentContext()) { NOTREACHED(); return false; } DCHECK_EQ(last_egl_context_, eglGetCurrentContext()); // Just set the memory limit to 0 and drop all tiles. This will be reset to // normal levels in the next DrawGL call. content::SynchronousCompositorMemoryPolicy policy; policy.bytes_limit = 0; policy.num_resources_limit = 0; if (memory_policy_ == policy) return false; TRACE_EVENT0("android_webview", "BrowserViewRenderer::TrimMemory"); ScopedAppGLStateRestore state_restore( ScopedAppGLStateRestore::MODE_RESOURCE_MANAGEMENT); internal::ScopedAllowGL allow_gl; SetMemoryPolicy(policy); return true; } void HardwareRenderer::SetMemoryPolicy( content::SynchronousCompositorMemoryPolicy& new_policy) { if (memory_policy_ == new_policy) return; memory_policy_ = new_policy; compositor_->SetMemoryPolicy(memory_policy_); } bool HardwareRenderer::RequestDrawGL() { return client_->RequestDrawGL(NULL); } // static void HardwareRenderer::CalculateTileMemoryPolicy() { CommandLine* cl = CommandLine::ForCurrentProcess(); const char kDefaultTileSize[] = "384"; if (!cl->HasSwitch(switches::kDefaultTileWidth)) cl->AppendSwitchASCII(switches::kDefaultTileWidth, kDefaultTileSize); if (!cl->HasSwitch(switches::kDefaultTileHeight)) cl->AppendSwitchASCII(switches::kDefaultTileHeight, kDefaultTileSize); } namespace internal { bool ScopedAllowGL::allow_gl = false; // static bool ScopedAllowGL::IsAllowed() { return GLViewRendererManager::GetInstance()->OnRenderThread() && allow_gl; } ScopedAllowGL::ScopedAllowGL() { DCHECK(GLViewRendererManager::GetInstance()->OnRenderThread()); DCHECK(!allow_gl); allow_gl = true; if (g_service.Get()) g_service.Get()->RunTasks(); } ScopedAllowGL::~ScopedAllowGL() { allow_gl = false; } DeferredGpuCommandService::DeferredGpuCommandService() {} DeferredGpuCommandService::~DeferredGpuCommandService() { base::AutoLock lock(tasks_lock_); DCHECK(tasks_.empty()); } namespace { void RequestProcessGL() { HardwareRenderer* renderer = GLViewRendererManager::GetInstance()->GetMostRecentlyDrawn(); if (!renderer || !renderer->RequestDrawGL()) { LOG(ERROR) << "Failed to request GL process. Deadlock likely: " << !!renderer; } } } // namespace // static void DeferredGpuCommandService::RequestProcessGLOnUIThread() { if (BrowserThread::CurrentlyOn(BrowserThread::UI)) { RequestProcessGL(); } else { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&RequestProcessGL)); } } // Called from different threads! void DeferredGpuCommandService::ScheduleTask(const base::Closure& task) { { base::AutoLock lock(tasks_lock_); tasks_.push(task); } if (ScopedAllowGL::IsAllowed()) { RunTasks(); } else { RequestProcessGLOnUIThread(); } } void DeferredGpuCommandService::ScheduleIdleWork( const base::Closure& callback) { // TODO(sievers): Should this do anything? } bool DeferredGpuCommandService::UseVirtualizedGLContexts() { return true; } void DeferredGpuCommandService::RunTasks() { bool has_more_tasks; { base::AutoLock lock(tasks_lock_); has_more_tasks = tasks_.size() > 0; } while (has_more_tasks) { base::Closure task; { base::AutoLock lock(tasks_lock_); task = tasks_.front(); tasks_.pop(); } task.Run(); { base::AutoLock lock(tasks_lock_); has_more_tasks = tasks_.size() > 0; } } } void DeferredGpuCommandService::AddRef() const { base::RefCountedThreadSafe<DeferredGpuCommandService>::AddRef(); } void DeferredGpuCommandService::Release() const { base::RefCountedThreadSafe<DeferredGpuCommandService>::Release(); } } // namespace internal } // namespace android_webview
30.253823
79
0.721722
hokein
a8a91abb8516aa351c075c34550896cbe193bb21
6,802
cpp
C++
src/imtjson/src/imtjson/array.cpp
martykadlcek/trading-bot
c2f34ef1e6746f02642dde3cb3d11010213f0121
[ "MIT" ]
7
2017-01-12T08:56:33.000Z
2022-03-09T17:25:20.000Z
src/imtjson/src/imtjson/array.cpp
martykadlcek/trading-bot
c2f34ef1e6746f02642dde3cb3d11010213f0121
[ "MIT" ]
1
2017-01-19T16:25:01.000Z
2017-01-19T16:25:01.000Z
src/imtjson/src/imtjson/array.cpp
martykadlcek/trading-bot
c2f34ef1e6746f02642dde3cb3d11010213f0121
[ "MIT" ]
1
2016-10-14T06:24:16.000Z
2016-10-14T06:24:16.000Z
#include "array.h" #include "arrayValue.h" #include "object.h" #include <time.h> namespace json { Array::Array(Value value): base(value),changes(value) { } Array::Array() : base(AbstractArrayValue::getEmptyArray()) { } Array::Array(const std::initializer_list<Value> &v) { reserve(v.size()); for (auto &&x : v) push_back(x); } Array & Array::push_back(const Value & v) { changes.push_back(v.v); return *this; } Array & Array::add(const Value & v) { changes.push_back(v.v); return *this; } Array & Array::addSet(const StringView<Value>& v) { changes.reserve(changes.size() + v.length); for (std::size_t i = 0; i < v.length; i++) changes.push_back(v.data[i].v); return *this; } Array& json::Array::addSet(const Value& v) { changes.reserve(changes.size() + v.size()); for (std::size_t i = 0, cnt = v.size(); i < cnt; i++) changes.push_back(v[i].getHandle()); return *this; } Array & Array::insert(std::size_t pos, const Value & v) { extendChanges(pos); changes.insert(changes.begin()+(pos - changes.offset), v.v); return *this; } Array & Array::insertSet(std::size_t pos, const StringView<Value>& v) { extendChanges(pos); changes.insert(changes.begin() + (pos - changes.offset), v.length, PValue()); for (std::size_t i = 0; i < v.length; i++) { changes[pos + changes.offset + i] = v.data[i].v; } return *this; } Array& json::Array::insertSet(std::size_t pos, const Value& v) { extendChanges(pos); changes.insert(changes.begin() + (pos - changes.offset), v.size(), PValue()); for (std::size_t i = 0, cnt = v.size(); i < cnt; i++) { changes[pos + changes.offset + i] = v[i].v; } return *this; } Array& json::Array::addSet(const std::initializer_list<Value>& v) { return addSet(StringView<Value>(v)); } Array& json::Array::insertSet(std::size_t pos, const std::initializer_list<Value>& v) { return insertSet(pos,StringView<Value>(v)); } Array & Array::erase(std::size_t pos) { extendChanges(pos); changes.erase(changes.begin() + (pos - changes.offset)); return *this; } Array & Array::eraseSet(std::size_t pos, std::size_t length) { extendChanges(pos); auto b = changes.begin() + (pos - changes.offset); auto e = b + length ; changes.erase(b,e); return *this; } Array & Array::trunc(std::size_t pos) { if (pos < changes.offset) { changes.offset = pos; changes.clear(); } else { changes.erase(changes.begin() + (pos - changes.offset), changes.end()); } return *this; } Array &Array::clear() { changes.offset = 0; changes.clear(); return *this; } Array &Array::revert() { changes.offset = base.size(); changes.clear(); return *this; } Array & Array::set(std::size_t pos, const Value & v) { extendChanges(pos); changes[pos - changes.offset] = v.getHandle(); return *this; } Value Array::operator[](std::size_t pos) const { if (pos < changes.offset) return base[pos]; else { pos -= changes.offset; return changes.at(pos); } } ValueRef Array::makeRef(std::size_t pos) { return ValueRef(*this, pos); } std::size_t Array::size() const { return changes.offset + changes.size(); } bool Array::empty() const { return size() == 0; } PValue Array::commit() const { if (empty()) return AbstractArrayValue::getEmptyArray(); if (!dirty()) return base.getHandle(); std::size_t needSz = changes.offset + changes.size(); RefCntPtr<ArrayValue> result = ArrayValue::create(needSz); for (std::size_t x = 0; x < changes.offset; ++x) { result->push_back(base[x].getHandle()); } for (auto &&x : changes) { if (x->type() != undefined) result->push_back(x); } return PValue::staticCast(result); } Object2Array Array::object(std::size_t pos) { return Object2Array((*this)[pos],*this,pos); } Array2Array Array::array(std::size_t pos) { return Array2Array((*this)[pos], *this, pos); } bool Array::dirty() const { return changes.offset != base.size() || !changes.empty(); } void Array::extendChanges(size_t pos) { if (pos < changes.offset) { changes.insert(changes.begin(), changes.offset - pos, PValue()); for (std::size_t x = pos; x < changes.offset; ++x) { changes[x - pos] = base[x].v; } changes.offset = pos; } } Array::~Array() { } ArrayIterator Array::begin() const { return ArrayIterator(this,0); } ArrayIterator Array::end() const { return ArrayIterator(this,size()); } Array &Array::reserve(std::size_t items) { changes.reserve(items); return *this; } Object2Array Array::addObject() { std::size_t pos = size(); add(AbstractObjectValue::getEmptyObject()); return object(pos); } Array2Array Array::addArray() { std::size_t pos = size(); add(AbstractArrayValue::getEmptyArray()); return array(pos); } StringView<PValue> Array::getItems(const Value& v) { const IValue *pv = v.getHandle(); const ArrayValue *av = dynamic_cast<const ArrayValue *>(pv->unproxy()); if (av) return av->getItems(); else return StringView<PValue>(); } Array::Array(const Array& other):base(other.base),changes(other.changes) { } Array::Array(Array&& other):base(std::move(other.base)),changes(std::move(other.changes)) { } Array& Array::operator =(const Array& other) { if (this == &other) return *this; base = other.base; changes = other.changes; return *this; } Array& Array::operator =(Array&& other) { if (this == &other) return *this; base = std::move(other.base); changes = std::move(other.changes); return *this; } Array::Changes::Changes(const Changes& base) :std::vector<PValue>(base),offset(base.offset) { } Array::Changes::Changes(Changes&& base) :std::vector<PValue>(std::move(base)),offset(base.offset) { } Array::Changes& Array::Changes::operator =(const Changes& base) { std::vector<PValue>::operator =(base); offset = base.offset; return *this; } Array::Changes& Array::Changes::operator =(Changes&& base) { std::vector<PValue>::operator =(std::move(base)); offset = base.offset; return *this; } Array& Array::reverse() { Array out; for (std::size_t x = size(); x > 0; x--) out.add((*this)[x-1]); *this = std::move(out); return *this; } Array& Array::slice(Int start) { if (start < 0) { if (-start < (Int)size()) { return slice(size()+start); } } else if (start >= (Int)size()) { clear(); } else { eraseSet(0,start); } return *this; } Array& Array::slice(Int start, Int end) { if (end < 0) { if (-end < (Int)size()) { slice(start, (Int)size()+end); } else { clear(); } } else if (end < (Int)size()) { trunc(end); } return slice(start); } Array& json::Array::setSize(std::size_t length, Value fillVal) { reserve(length); if (size() > length) return trunc(length); while (size() < length) add(fillVal); return *this; } }
21.593651
91
0.636136
martykadlcek
a8a9a9b0eab95164006e56947f358a6338c08fac
7,014
hpp
C++
mesp/mesp_inner.hpp
KuceraMartin/mesp-fpt
295a6a65ba5aedde775eb57805d7a74124e63c66
[ "MIT" ]
null
null
null
mesp/mesp_inner.hpp
KuceraMartin/mesp-fpt
295a6a65ba5aedde775eb57805d7a74124e63c66
[ "MIT" ]
null
null
null
mesp/mesp_inner.hpp
KuceraMartin/mesp-fpt
295a6a65ba5aedde775eb57805d7a74124e63c66
[ "MIT" ]
null
null
null
#ifndef IMPL_MESP_INNER_HPP #define IMPL_MESP_INNER_HPP #include <boost/dynamic_bitset.hpp> #include <queue> #include <stack> #include <unordered_map> #include <unordered_set> #include <vector> #include "../common/common.hpp" #include "../common/graph.hpp" #include "constrained_set_cover.hpp" class mesp_inner { public: int k; int pi_first, pi_last; std::shared_ptr<const graph> G; std::shared_ptr<const std::unordered_set<int>> C; path solution; private: std::unordered_set<int> L; std::vector<int> pi; std::unordered_map<int, int> e; public: mesp_inner(const std::shared_ptr<const graph> &G, const std::shared_ptr<const std::unordered_set<int>> &C, int k, int pi_first = -1, int pi_last = -1): G(G), C(C), k(k), pi_first(pi_first), pi_last(pi_last) {} bool solve() { init_L(); do { init_pi(); do { if (!can_pi()) continue; init_e(); do { if (solve_inner()) return true; } while (next_e()); } while (next_pi()); } while (next_L()); return false; } private: bool solve_inner() { auto candidate_segments = get_segments(); if (!candidate_segments.has_value()) return false; std::unordered_set<int> I(L.begin(), L.end()); std::vector<int> h_inv((*candidate_segments).size(), -1); std::vector<std::vector<path>> candidates; for (int i = 0; i < candidate_segments->size(); i++) { if ((*candidate_segments)[i].size() == 1) { for (int u : (*candidate_segments)[i][0]) I.insert(u); continue; } candidates.emplace_back(std::move((*candidate_segments)[i])); h_inv[i] = candidates.size() - 1; } std::unordered_set<int> U; for (int v = 0; v < G->n; v++) { if (C->count(v) || I.count(v)) continue; if (estimate_path_dst(v) > k + 1) return false; if (estimate_path_dst(v) == k + 1) U.insert(v); } if (U.size() > 2 * (pi.size() - 1)) return false; std::vector<int> requirements; for (int u = 0; u < G->n; u++) { if (L.count(u)) continue; if (!C->count(u) && !U.count(u)) continue; int need_dst = e.count(u) ? e[u] : k; if (G->distance(u, I) <= need_dst) continue; requirements.push_back(u); } const std::function<boost::dynamic_bitset<>(const path &)> psi = [this, &requirements] (const path &segment) { boost::dynamic_bitset<> res(requirements.size(), 0); if (segment.empty()) return res; for (int i = 0; i < requirements.size(); i++) { int u = requirements[i]; int need_dst = e.count(u) ? e[u] : k; if (G->distance(u, segment) <= need_dst) { res[i] = true; } } return res; }; auto true_segment_id = constrained_set_cover(requirements, candidates, psi); if (!true_segment_id.has_value()) return false; solution.clear(); for (int i = 0; i < pi.size() - 1; i++) { solution.push_back(pi[i]); path &segment = h_inv[i] == -1 ? (*candidate_segments)[i][0] : candidates[h_inv[i]][(*true_segment_id)[h_inv[i]]]; for (int s : segment) solution.push_back(s); } solution.push_back(pi.back()); return G->ecc(solution) <= k; } std::optional<std::vector<std::vector<path>>> get_segments() const { std::vector<std::vector<path>> candidate_segments(pi.size() - 1); for (int i = 0; i < pi.size() - 1; i++) { std::queue<int> q; q.push(pi[i + 1]); std::unordered_map<int, int> dst = {{pi[i + 1], 0}}; while (!q.empty()) { int u = q.front(); q.pop(); if (u == pi[i]) break; for (int v : G->neighbors(u)) { if (dst.count(v)) continue; if (C->count(v) && v != pi[i]) continue; dst[v] = dst[u] + 1; q.push(v); } } if (!dst.count(pi[i])) return std::nullopt; if (dst[pi[i]] != G->distance(pi[i + 1], pi[i])) return std::nullopt; std::vector<path> Sigma; std::vector<int> K; for (int u : G->neighbors(pi[i])) { if (!dst.count(u) || dst[u] != dst[pi[i]] - 1) continue; if (u == pi[i + 1]) { Sigma.emplace_back(); break; } for (int v : G->neighbors(u)) { if (!dst.count(v) || dst[v] != dst[u] - 1) continue; Sigma.push_back({u}); int K_added = 0; while (v != pi[i + 1]) { int p = Sigma.back().back(); if (estimate_path_dst(v) > k) { if (K_added++ < 2) K.push_back(v); if (K.size() > 4) return std::nullopt; } Sigma.back().push_back(v); for (int n : G->neighbors(v)) { if (!dst.count(n) || dst[n] != dst[v] - 1) continue; if (n == p) continue; v = n; break; } } } } for (auto &segment : Sigma) { std::vector<int> K_sat(K.size(), 0); for (int j = 0; j < K.size(); j++) { K_sat[j] |= G->distance(K[j], segment) <= k; } bool is_sat = true; for (bool s : K_sat) is_sat |= s; if (is_sat) { candidate_segments[i].emplace_back(std::move(segment)); } } } return candidate_segments; } void init_L() { L.clear(); auto C_iter = C->begin(); if (pi_first == -1) { L.insert(*C_iter); ++C_iter; } else { L.insert(pi_first); } if (pi_last == -1) { L.insert(*C_iter); } else { L.insert(pi_last); } } bool next_L() { int max_size = C->size(); if (pi_first != -1) max_size++; if (pi_last != -1) max_size++; if (L.size() == max_size) return false; do { for (int v : *C) { if (L.count(v)) { L.erase(v); } else { L.insert(v); break; } } } while (L.size() < 2); return true; } void init_pi() { pi.clear(); pi.reserve(L.size()); if (pi_first != -1) pi.push_back(pi_first); for (int u : L) { if (u == pi_first || u == pi_last) continue; pi.push_back(u); } if (pi_last != -1) pi.push_back(pi_last); std::sort(pi.begin() + (pi_first == -1 ? 0 : 1), pi.end() - (pi_last == -1 ? 0 : 1)); } bool can_pi() const { int length = 0; for (int i = 0; i < pi.size() - 1; i++) { length += G->distance(pi[i], pi[i + 1]); } return length == G->distance(pi[0], pi.back()); } bool next_pi() { int first = pi_first == -1 ? 0 : 1; int last = (int) pi.size() - (pi_last == -1 ? 1 : 2); if (first >= last) return false; int m = last - 1; while (m >= first && pi[m] > pi[m + 1]) m--; if (m < first) return false; int k = last; while (pi[m] > pi[k]) k--; std::swap(pi[m], pi[k]); int p = m + 1; int q = last; while (p < q) { std::swap(pi[p], pi[q]); p++; q--; } return true; } void init_e() { e.clear(); for (int v : *C) { if (L.count(v)) continue; e[v] = 1; } } bool next_e() { int cnt = 0; for (int v : *C) { if (L.count(v)) continue; if (e[v] < k) { e[v]++; break; } else { e[v] = 1; cnt++; } } return cnt < e.size(); } int estimate_path_dst(int u) const { int res = INF; if (pi_first != -1) { res = std::min(res, G->distance(u, pi_first)); } if (pi_last != -1) { res = std::min(res, G->distance(u, pi_last)); } for (int v : *C) { int e_v = e.count(v) ? e.at(v) : 0; res = std::min(res, G->distance(u, v) + e_v); } return res; } }; #endif //IMPL_MESP_INNER_HPP
22.699029
152
0.550613
KuceraMartin
a8aefe93bfad9ad7ea0f6ba41d5a8a505d0ab170
271
hh
C++
src/state/secondary_variable_field_evaluator_fromfunction_reg.hh
fmyuan/amanzi
edb7b815ae6c22956c8519acb9d87b92a9915ed4
[ "RSA-MD" ]
37
2017-04-26T16:27:07.000Z
2022-03-01T07:38:57.000Z
src/state/secondary_variable_field_evaluator_fromfunction_reg.hh
fmyuan/amanzi
edb7b815ae6c22956c8519acb9d87b92a9915ed4
[ "RSA-MD" ]
494
2016-09-14T02:31:13.000Z
2022-03-13T18:57:05.000Z
src/state/secondary_variable_field_evaluator_fromfunction_reg.hh
fmyuan/amanzi
edb7b815ae6c22956c8519acb9d87b92a9915ed4
[ "RSA-MD" ]
43
2016-09-26T17:58:40.000Z
2022-03-25T02:29:59.000Z
#include "secondary_variable_field_evaluator_fromfunction.hh" namespace Amanzi { Utils::RegisteredFactory<FieldEvaluator,SecondaryVariableFieldEvaluatorFromFunction> SecondaryVariableFieldEvaluatorFromFunction::fac_("secondary variable from function"); } // namespace
33.875
171
0.867159
fmyuan
a8afd9a3901aeb387f0d1d3bb52b34b43906382b
18,919
cc
C++
QFSClient/qfs_client_implementation.cc
aristanetworks/quantumfs
4636946c38db75f7d1034b626a3f92b0dd77fbe0
[ "Apache-2.0" ]
3
2019-02-23T02:01:54.000Z
2019-09-24T16:29:26.000Z
QFSClient/qfs_client_implementation.cc
aristanetworks/quantumfs
4636946c38db75f7d1034b626a3f92b0dd77fbe0
[ "Apache-2.0" ]
null
null
null
QFSClient/qfs_client_implementation.cc
aristanetworks/quantumfs
4636946c38db75f7d1034b626a3f92b0dd77fbe0
[ "Apache-2.0" ]
2
2019-11-22T01:18:54.000Z
2020-04-19T01:27:16.000Z
// Copyright (c) 2016 Arista Networks, Inc. // Use of this source code is governed by the Apache License 2.0 // that can be found in the COPYING file. #include "QFSClient/qfs_client_implementation.h" #include <fcntl.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <unistd.h> #include <jansson.h> #include <algorithm> #include <ios> #include <vector> #include "./libqfs.h" #include "QFSClient/qfs_client.h" #include "QFSClient/qfs_client_data.h" #include "QFSClient/qfs_client_test.h" #include "QFSClient/qfs_client_util.h" namespace qfsclient { ApiContext::ApiContext() : request_json_object(NULL), response_json_object(NULL) { } ApiContext::~ApiContext() { SetRequestJsonObject(NULL); SetResponseJsonObject(NULL); } void ApiContext::SetRequestJsonObject(json_t *request_json_object) { if (this->request_json_object) { json_decref(this->request_json_object); this->request_json_object = NULL; } this->request_json_object = request_json_object; } json_t *ApiContext::GetRequestJsonObject() const { return request_json_object; } void ApiContext::SetResponseJsonObject(json_t *response_json_object) { if (this->response_json_object) { json_decref(this->response_json_object); this->response_json_object = NULL; } this->response_json_object = response_json_object; } json_t *ApiContext::GetResponseJsonObject() const { return response_json_object; } CommandBuffer::CommandBuffer() { } CommandBuffer::~CommandBuffer() { } // Remove the trailing zeros from the tail of the response void CommandBuffer::Sanitize() { auto size = this->data.size(); for (auto it = this->data.crbegin(); it != this->data.crend(); ++it) { if (*it) { break; } // *it is a trailing zero, discard it --size; } this->data.resize(size); } // Copy the contents of the given CommandBuffer into this one void CommandBuffer::Copy(const CommandBuffer &source) { this->data = source.data; } // Return a const pointer to the data in the buffer const byte *CommandBuffer::Data() const { return this->data.data(); } // Return the size of the data stored in the buffer size_t CommandBuffer::Size() const { return this->data.size(); } // Reset the buffer such that it will contain no data and will // have a zero size void CommandBuffer::Reset() { this->data.clear(); } // Append a block of data to the buffer. Returns an error if the // buffer would have to be grown too large to add this block ErrorCode CommandBuffer::Append(const byte *data, size_t size) { try { this->data.insert(this->data.end(), data, data + size); } catch (...) { return kBufferTooBig; } return kSuccess; } // copy a string into the buffer, but without a NUL terminator. An error will // be returned if the buffer would have to be grown too large to fit the string. ErrorCode CommandBuffer::CopyString(const char *s) { this->data.clear(); return this->Append((const byte *)s, strlen(s)); } Error GetApi(Api **api) { *api = new ApiImpl(); return util::getError(kSuccess); } Error GetApi(const char *path, Api **api) { *api = new ApiImpl(path); return util::getError(kSuccess); } void ReleaseApi(Api *api) { if (api != NULL) { delete reinterpret_cast<ApiImpl*>(api); } } ApiImpl::ApiImpl() : fd(-1), path(""), api_inode_id(kInodeIdApi), test_hook(NULL) { } ApiImpl::ApiImpl(const char *path) : fd(-1), path(path), api_inode_id(kInodeIdApi), test_hook(NULL) { } ApiImpl::~ApiImpl() { Close(); } Error ApiImpl::Open() { return this->OpenCommon(false); } Error ApiImpl::TestOpen() { return this->OpenCommon(true); } Error ApiImpl::OpenCommon(bool inTest) { if (this->path.length() == 0) { // Path was not passed to constructor: determine path Error err; if (inTest) { err = this->DeterminePathInTest(); } else { err = this->DeterminePath(); } if (err.code != kSuccess) { return err; } } if (this->fd == -1) { int flags = O_RDWR | O_CLOEXEC; #if defined(O_DIRECT) if (!inTest) { flags |= O_DIRECT; } #endif this->fd = open(this->path.c_str(), flags); if (this->fd == -1) { return util::getError(kCantOpenApiFile, this->path); } } return util::getError(kSuccess); } void ApiImpl::Close() { if (this->fd != -1) { int err = close(this->fd); if (err != 0) { printf("Error when closing api: %d\n", errno); } this->fd = -1; } } Error ApiImpl::SendCommand(const CommandBuffer &command, CommandBuffer *response) { Error err = this->Open(); if (err.code != kSuccess) { return err; } err = this->WriteCommand(command); if (err.code != kSuccess) { return err; } if (this->test_hook) { Error err = this->test_hook->PostWriteHook(); if (err.code != kSuccess) { return err; } err = this->test_hook->PreReadHook(response); if (err.code != kSuccess) { return err; } return util::getError(kSuccess); } return this->ReadResponse(response); } Error ApiImpl::WriteCommand(const CommandBuffer &command) { if (this->fd == -1) { return util::getError(kApiFileNotOpen); } int err = lseek(this->fd, 0, SEEK_SET); if (err == -1) { return util::getError(kApiFileSeekFail, this->path); } util::AlignedMem<512> data(command.Size()); memcpy(*data, command.Data(), command.Size()); // We must write the whole command at once int written = write(this->fd, *data, command.Size()); if (written == -1 || written != command.Size()) { return util::getError(kApiFileWriteFail, this->path); } return util::getError(kSuccess); } Error ApiImpl::ReadResponse(CommandBuffer *command) { ErrorCode err = kSuccess; if (this->fd == -1) { return util::getError(kApiFileNotOpen); } int errCode = lseek(this->fd, 0, SEEK_SET); if (errCode == -1) { return util::getError(kApiFileSeekFail); } // read up to 4k at a time, stopping on EOF command->Reset(); static const ssize_t BufferSize = 4096; util::AlignedMem<512> data(BufferSize); for (ssize_t num = BufferSize; num == BufferSize;) { num = read(this->fd, *data, data.Size()); if (num == 0) { break; } if (num < 0) { // any read failure *except* an EOF is a failure return util::getError(kApiFileReadFail, this->path); } err = command->Append(reinterpret_cast<const byte *>(*data), num); if (err != kSuccess) { return util::getError(err); } } command->Sanitize(); return util::getError(err); } Error ApiImpl::DeterminePath() { FindApiPath_return apiPath = FindApiPath(); if (strlen(apiPath.r1) != 0) { return util::getError(kCantFindApiFile, std::string(apiPath.r1)); } this->path = std::string(apiPath.r0); return util::getError(kSuccess); } Error ApiImpl::DeterminePathInTest() { // getcwd() with a NULL first parameter results in a buffer of whatever size // is required being allocated, which we must then free. PATH_MAX isn't // known at compile time (and it is possible for paths to be longer than // PATH_MAX anyway) char *cwd = getcwd(NULL, 0); if (!cwd) { return util::getError(kDontKnowCwd); } std::vector<std::string> directories; std::string path; std::string currentDir(cwd); free(cwd); util::Split(currentDir, "/", &directories); while (true) { util::Join(directories, "/", &path); path = "/" + path + "/" + kApiPath; struct stat path_status; if (lstat(path.c_str(), &path_status) == 0) { if (((S_ISREG(path_status.st_mode)) || (S_ISLNK(path_status.st_mode))) && (path_status.st_ino == this->api_inode_id)) { // we found an API *file* with the correct // inode ID: success this->path = path; return util::getError(kSuccess, this->path); } // Note: it's valid to have a file *or* directory called // 'api' that isn't the actual api file: in that case we // should just keep walking up the tree towards the root } if (directories.size() == 0) { // We got to / without finding the api file: fail return util::getError(kCantFindApiFile, currentDir); } // Remove last entry from directories and continue moving up // the directory tree by one level directories.pop_back(); } return util::getError(kCantFindApiFile, currentDir); } Error ApiImpl::CheckWorkspaceNameValid(const char *workspace_name) { std::string str(workspace_name); std::vector<std::string> tokens; util::Split(str, "/", &tokens); // name must have *exactly* two '/' characters (in which case it will have // three tokens if split by '/' if (tokens.size() != 3) { return util::getError(kWorkspaceNameInvalid, workspace_name); } return util::getError(kSuccess); } Error ApiImpl::CheckWorkspacePathValid(const char *workspace_path) { std::string str(workspace_path); std::vector<std::string> tokens; util::Split(str, "/", &tokens); // path must have *at least* two '/' characters (in which case it will have // three or more tokens if split by '/' if (tokens.size() < 3) { return util::getError(kWorkspacePathInvalid, workspace_path); } return util::getError(kSuccess); } Error ApiImpl::CheckCommonApiResponse(const CommandBuffer &response, ApiContext *context) { json_error_t json_error; // parse JSON in response into a std::unordered_map<std::string, bool> json_t *response_json = json_loadb((const char *)response.Data(), response.Size(), 0, &json_error); context->SetResponseJsonObject(response_json); if (response_json == NULL) { std::string details = util::buildJsonErrorDetails( json_error.text, (const char *)response.Data(), response.Size()); return util::getError(kJsonDecodingError, details); } json_t *response_json_obj; // note about cleaning up response_json_obj: this isn't necessary // as long as we use format character 'o' below, because in this case // the reference count of response_json isn't increased and we don't // leak any references. However, format character 'O' *will* increase the // reference count and in that case we would need to clean up afterwards. int success = json_unpack_ex(response_json, &json_error, 0, "o", &response_json_obj); if (success != 0) { std::string details = util::buildJsonErrorDetails( json_error.text, (const char *)response.Data(), response.Size()); return util::getError(kJsonDecodingError, details); } json_t *error_json_obj = json_object_get(response_json_obj, kErrorCode); if (error_json_obj == NULL) { std::string details = util::buildJsonErrorDetails( kErrorCode, (const char *)response.Data(), response.Size()); return util::getError(kMissingJsonObject, details); } json_t *message_json_obj = json_object_get(response_json_obj, kMessage); if (message_json_obj == NULL) { std::string details = util::buildJsonErrorDetails( kMessage, (const char *)response.Data(), response.Size()); return util::getError(kMissingJsonObject, details); } if (!json_is_integer(error_json_obj)) { std::string details = util::buildJsonErrorDetails( "error code in response JSON is not valid", (const char *)response.Data(), response.Size()); return util::getError(kJsonDecodingError, details); } CommandError apiError = (CommandError)json_integer_value(error_json_obj); if (apiError != kCmdOk) { std::string api_error = util::getApiError( apiError, json_string_value(message_json_obj)); std::string details = util::buildJsonErrorDetails( api_error, (const char *)response.Data(), response.Size()); return util::getError(kApiError, details); } return util::getError(kSuccess); } Error ApiImpl::SendJson(ApiContext *context) { json_t *request_json = context->GetRequestJsonObject(); // we pass these flags to json_dumps() because: // JSON_COMPACT: there's no good reason for verbose JSON // JSON_SORT_KEYS: so that the tests can get predictable JSON and will // be able to compare generated JSON reliably char *request_json_str = json_dumps(request_json, JSON_COMPACT | JSON_SORT_KEYS); CommandBuffer command; command.CopyString(request_json_str); free(request_json_str); // free the JSON string created by json_dumps() // send CommandBuffer and receive response in another one CommandBuffer response; Error err = this->SendCommand(command, &response); if (err.code != kSuccess) { return err; } err = this->CheckCommonApiResponse(response, context); if (err.code != kSuccess) { return err; } return util::getError(kSuccess); } Error ApiImpl::GetAccessed(const char *workspace_root, PathsAccessed *paths) { Error err = this->CheckWorkspaceNameValid(workspace_root); if (err.code != kSuccess) { return err; } // create JSON in a CommandBuffer with: // CommandId = kGetAccessed and // WorkspaceRoot = workspace_root json_error_t json_error; json_t *request_json = json_pack_ex(&json_error, 0, kGetAccessedJSON, kCommandId, kCmdGetAccessed, kWorkspaceRoot, workspace_root); if (request_json == NULL) { return util::getError(kJsonEncodingError, json_error.text); } ApiContext context; context.SetRequestJsonObject(request_json); err = this->SendJson(&context); if (err.code != kSuccess) { return err; } err = this->PrepareAccessedListResponse(&context, paths); if (err.code != kSuccess) { return err; } return util::getError(kSuccess); } Error ApiImpl::InsertInode(const char *destination, const char *key, uint32_t permissions, uint32_t uid, uint32_t gid) { Error err = this->CheckWorkspacePathValid(destination); if (err.code != kSuccess) { return err; } // create JSON with: // CommandId = kCmdInsertInode and // DstPath = destination // Key = key // Uid = uid // Gid = gid // Permissions = permissions json_error_t json_error; json_t *request_json = json_pack_ex(&json_error, 0, kInsertInodeJSON, kCommandId, kCmdInsertInode, kDstPath, destination, kKey, key, kUid, uid, kGid, gid, kPermissions, permissions); if (request_json == NULL) { return util::getError(kJsonEncodingError, json_error.text); } ApiContext context; context.SetRequestJsonObject(request_json); err = this->SendJson(&context); if (err.code != kSuccess) { return err; } return util::getError(kSuccess); } Error ApiImpl::Branch(const char *source, const char *destination) { Error err = this->CheckWorkspaceNameValid(source); if (err.code != kSuccess) { return err; } err = this->CheckWorkspaceNameValid(destination); if (err.code != kSuccess) { return err; } // create JSON with: // CommandId = kCmdBranchRequest and // Src = source // Dst = destination json_error_t json_error; json_t *request_json = json_pack_ex(&json_error, 0, kBranchJSON, kCommandId, kCmdBranchRequest, kSource, source, kDestination, destination); if (request_json == NULL) { return util::getError(kJsonEncodingError, json_error.text); } ApiContext context; context.SetRequestJsonObject(request_json); err = this->SendJson(&context); if (err.code != kSuccess) { return err; } return util::getError(kSuccess); } Error ApiImpl::Delete(const char *workspace) { Error err = this->CheckWorkspaceNameValid(workspace); if (err.code != kSuccess) { return err; } // create JSON with: // CommandId = kCmdDeleteWorkspace and // Workspace = workspace json_error_t json_error; json_t *request_json = json_pack_ex(&json_error, 0, kDeleteJSON, kCommandId, kCmdDeleteWorkspace, kWorkspacePath, workspace); if (request_json == NULL) { return util::getError(kJsonEncodingError, json_error.text); } ApiContext context; context.SetRequestJsonObject(request_json); err = this->SendJson(&context); if (err.code != kSuccess) { return err; } return util::getError(kSuccess); } Error ApiImpl::SetBlock(const std::vector<byte> &key, const std::vector<byte> &data) { // convert key and data to base64 before stuffing into JSON std::string base64_key; std::string base64_data; Error err; err = util::base64_encode(key, &base64_key); if (err.code != kSuccess) { return err; } err = util::base64_encode(data, &base64_data); if (err.code != kSuccess) { return err; } // create JSON with: // CommandId = kCmdSetBlock and // Key = key // Data = data json_error_t json_error; json_t *request_json = json_pack_ex(&json_error, 0, kSetBlockJSON, kCommandId, kCmdSetBlock, kKey, base64_key.c_str(), kData, base64_data.c_str()); if (request_json == NULL) { return util::getError(kJsonEncodingError, json_error.text); } ApiContext context; context.SetRequestJsonObject(request_json); err = this->SendJson(&context); if (err.code != kSuccess) { return err; } return util::getError(kSuccess); } Error ApiImpl::GetBlock(const std::vector<byte> &key, std::vector<byte> *data) { // convert key to base64 before stuffing into JSON std::string base64_key; Error err; err = util::base64_encode(key, &base64_key); if (err.code != kSuccess) { return err; } // create JSON with: // CommandId = kCmdGetBlock and // Key = key json_error_t json_error; json_t *request_json = json_pack_ex(&json_error, 0, kGetBlockJSON, kCommandId, kCmdGetBlock, kKey, base64_key.c_str()); if (request_json == NULL) { return util::getError(kJsonEncodingError, json_error.text); } ApiContext context; context.SetRequestJsonObject(request_json); err = this->SendJson(&context); if (err.code != kSuccess) { return err; } json_t *response_json = context.GetResponseJsonObject(); json_t *data_json_obj = json_object_get(response_json, kData); if (data_json_obj == NULL) { return util::getError(kMissingJsonObject, kData); } if (!json_is_string(data_json_obj)) { return util::getError(kJsonObjectWrongType, "expected string for " + std::string(kData)); } const char *data_base64 = json_string_value(data_json_obj); // convert data_base64 from base64 to binary before setting value in data err = util::base64_decode(data_base64, data); if (err.code != kSuccess) { return err; } return util::getError(kSuccess); } Error ApiImpl::PrepareAccessedListResponse( const ApiContext *context, PathsAccessed *accessed_list) { json_error_t json_error; json_t *response_json = context->GetResponseJsonObject(); json_t *path_list_json_obj = json_object_get(response_json, kPathList); if (path_list_json_obj == NULL) { return util::getError(kMissingJsonObject, kPathList); } json_t *accessed_list_json_obj = json_object_get(path_list_json_obj, kPaths); if (accessed_list_json_obj == NULL) { return util::getError(kMissingJsonObject, kPaths); } const char *k; json_t *v; json_object_foreach(accessed_list_json_obj, k, v) { if (json_is_integer(v)) { accessed_list->paths[std::string(k)] = json_integer_value(v); } } return util::getError(kSuccess); } } // namespace qfsclient
24.828084
83
0.69343
aristanetworks
a8b165b4934772d0c528880b4800c6b25ea181f7
352
cpp
C++
files/mnem_gen_abacaba.cpp
kborozdin/palindromic-length
2fad58e82b5cc079bfceb9e782b7e2a8ee4306d2
[ "MIT" ]
null
null
null
files/mnem_gen_abacaba.cpp
kborozdin/palindromic-length
2fad58e82b5cc079bfceb9e782b7e2a8ee4306d2
[ "MIT" ]
null
null
null
files/mnem_gen_abacaba.cpp
kborozdin/palindromic-length
2fad58e82b5cc079bfceb9e782b7e2a8ee4306d2
[ "MIT" ]
null
null
null
// abacaba #include <stdio.h> #include <string.h> #define MAX 100000 char str[MAX]; int main(int argc,char *argv[]) { int n,k,i; sscanf(argv[1],"%d",&n); str[0]='a'; k=1; char c='a'; for(;n>1;--n) { str[k]=++c; for(i=0;i<k;++i) str[k+1+i]=str[i]; k=k+k+1; } printf("%s\n",str); return 0; }
14.666667
34
0.465909
kborozdin
a8b269f1eddb55832cddc194dcb7ca705ca1e3d4
644
hpp
C++
Notemania/include/Screen.hpp
lunacys/Notemania
fcf314ea37fa3f5aa0ca7817708d0b5e8ec171ba
[ "MIT" ]
1
2017-06-27T09:38:45.000Z
2017-06-27T09:38:45.000Z
Notemania/include/Screen.hpp
lunacys/Notemania
fcf314ea37fa3f5aa0ca7817708d0b5e8ec171ba
[ "MIT" ]
1
2017-06-29T16:31:41.000Z
2017-06-29T16:31:41.000Z
Notemania/include/Screen.hpp
lunacys/Notemania
fcf314ea37fa3f5aa0ca7817708d0b5e8ec171ba
[ "MIT" ]
3
2017-06-27T09:52:19.000Z
2017-07-20T13:35:12.000Z
#ifndef NOMA_SCREEN_HPP_ #define NOMA_SCREEN_HPP_ #include <string> namespace noma { class IScreenManager; class Screen { public: Screen* find_screen(); Screen* find_screen(const std::string& name); void show(const std::string& name, bool hideThis); void show(); void hide(); virtual void initialize(); virtual void update(double dt); virtual void render(); IScreenManager* screen_manager; bool is_initialized; bool is_visible; protected: Screen(); private: }; } // namespace noma #endif // NOMA_SCREEN_HPP_
16.512821
58
0.607143
lunacys
a8b4b00360a361a9ab20ec12fc0a4f1669270887
1,413
cpp
C++
src/main.cpp
OpenGene/pecheck
e0ee9e4a7b43a429c520e7620b29673cbd71abcc
[ "MIT" ]
8
2018-07-27T05:57:33.000Z
2022-01-19T10:07:26.000Z
src/main.cpp
KimBioInfoStudio/pecheck
e0ee9e4a7b43a429c520e7620b29673cbd71abcc
[ "MIT" ]
1
2019-08-01T12:54:33.000Z
2019-08-02T00:09:43.000Z
src/main.cpp
KimBioInfoStudio/pecheck
e0ee9e4a7b43a429c520e7620b29673cbd71abcc
[ "MIT" ]
2
2019-05-21T05:38:00.000Z
2020-10-14T13:56:23.000Z
#include <stdio.h> #include <time.h> #include "cmdline.h" #include "common.h" #include "options.h" #include "unittest.h" #include <sstream> #include "pecheck.h" #include "util.h" string command; int main(int argc, char* argv[]){ // display version info if no argument is given if(argc == 1) { cout << "A tool to check paired-end FASTQ data integrity" << endl << "version " << VERSION_NUM << endl; } if (argc == 2 && strcmp(argv[1], "test")==0){ UnitTest tester; tester.run(); return 0; } cmdline::parser cmd; // input/output cmd.add<string>("in1", 'i', "read1 file name", true, ""); cmd.add<string>("in2", 'I', "read2 file name", true, ""); cmd.add<string>("json", 'j', "json report file name", true, "pecheck.json"); cmd.parse_check(argc, argv); stringstream ss; for(int i=0;i<argc;i++){ ss << argv[i] << " "; } command = ss.str(); time_t t1 = time(NULL); Options opt; opt.in1 = cmd.get<string>("in1"); opt.in2 = cmd.get<string>("in2"); opt.jsonFile = cmd.get<string>("json"); opt.validate(); PECheck pecheck(&opt); pecheck.run(); time_t t2 = time(NULL); cerr << endl << "JSON report: " << opt.jsonFile << endl; cerr << endl << command << endl; cerr << "pecheck v" << VERSION_NUM << ", time used: " << (t2)-t1 << " seconds" << endl; return 0; }
24.789474
111
0.561217
OpenGene
a8b65727aab1d85755f8257aad436a6bbbb7b5eb
3,712
cpp
C++
BasicBMPDiff/diff-PNG.cpp
kolmoblocks/imageexpander
661cc9761465910dec2859c9195fac68765b2cb4
[ "Zlib" ]
2
2019-02-19T20:55:33.000Z
2019-04-03T21:01:24.000Z
BasicBMPDiff/diff-PNG.cpp
kolmoblocks/imageexpander
661cc9761465910dec2859c9195fac68765b2cb4
[ "Zlib" ]
null
null
null
BasicBMPDiff/diff-PNG.cpp
kolmoblocks/imageexpander
661cc9761465910dec2859c9195fac68765b2cb4
[ "Zlib" ]
null
null
null
#include "lodepng.h" #include <iostream> using namespace std; unsigned int gcd(unsigned int u, unsigned int v) { // simple cases (termination) if (u == v) return u; if (u == 0) return v; if (v == 0) return u; // look for factors of 2 if (~u & 1) // u is even { if (v & 1) // v is odd return gcd(u >> 1, v); else // both u and v are even return gcd(u >> 1, v >> 1) << 1; } if (~v & 1) // u is odd, v is even return gcd(u, v >> 1); // reduce larger argument if (u > v) return gcd((u - v) >> 1, v); return gcd((v - u) >> 1, u); } // generateDiff(string, string) // generates the diff, which is used by expand_image to expand the lower // resolution image. void generateDiff (const char *lowRes, const char *highRes){ std::vector<unsigned char> lowResImage; std::vector<unsigned char> highResImage; unsigned lowResWidth, lowResHeight, highResWidth, highResHeight; unsigned error = lodepng::decode(lowResImage, lowResWidth, lowResHeight, lowRes, LCT_RGB, 8); if (error) { std::cout << error; return; } error = lodepng::decode(highResImage, highResWidth, highResHeight, highRes, LCT_RGB, 8); if (error) { std::cout << error; return; } unsigned denom = gcd(lowResWidth, highResWidth); // finding numerator and denominator of ratio (lowFactor, highFactor respectively) int lowFactor = lowResWidth / denom; int highFactor = highResWidth / denom; // finding diffWidth from the difference between smaller vs newer chunk sizes int diffWidth = highFactor * highFactor - lowFactor * lowFactor; int highResArea = highResWidth * highResHeight; // finding diffHeight from the number of chunks in a whole highRes image by finding the number of whole chunks (rounded up) for along the height and the width. int diffHeight = (highResWidth % highFactor == 0 ? highResWidth / highFactor : highResWidth / highFactor + 1 ) * (highResHeight % highFactor == 0 ? highResHeight / highFactor : highResHeight / highFactor + 1 ); std::vector<unsigned char> diffVec; const unsigned int height = highResHeight; const unsigned int width = highResWidth; // iterating through blocks, x and y indicate the top left positions of each block. for (std::size_t y=0; y<height; y+= highFactor) { for (std::size_t x=0; x<width; x+= highFactor) { // iterating through inner block pixels, innerX and innerY indicate the current position of the block we are at. for (int innerX = x; innerX < x+highFactor; ++innerX) { for (int innerY = y; innerY < y+highFactor; ++innerY) { // only get and set pixel if the block is not included in the old block (for now it is the top left smaller square with sides of length "lowFactor") if (!(innerX < x+lowFactor) || !(innerY < y+lowFactor)) { // set pixel of the diff at diffX , diffY with the Color at the highResImage at innerX , innerY diffVec.push_back(highResImage.at((innerX+innerY*highResWidth)*3)); diffVec.push_back(highResImage.at((innerX+innerY*highResWidth)*3+1)); diffVec.push_back(highResImage.at((innerX+innerY*highResWidth)*3+2)); } } } } } error = lodepng::encode("diff.png", diffVec, diffWidth, diffHeight, LCT_RGB ,8); cout<<diffVec.size()<<' ' << diffWidth << ' ' << diffHeight <<endl; std::cout << lodepng_error_text(error) << std::endl; } int main(int argc, char *argv[]){ // argv[1]: smaller file generateDiff(argv[1], argv[2]); }
36.752475
163
0.625808
kolmoblocks
a8b88121050448fe8c94270714dd59868be40852
452
cpp
C++
Tests/Experiments/Sources/MemFunc.cpp
Anonymus-Player/HackSolutions
7d865de8ec06bb098a3a11bd6328faaaf96dc1df
[ "MIT" ]
33
2020-11-20T14:58:25.000Z
2022-03-04T10:04:08.000Z
Tests/Experiments/Sources/MemFunc.cpp
Anonymus-Player/HackSolutions
7d865de8ec06bb098a3a11bd6328faaaf96dc1df
[ "MIT" ]
8
2021-01-05T23:18:32.000Z
2022-02-22T18:25:37.000Z
Tests/Experiments/Sources/MemFunc.cpp
Anonymus-Player/HackSolutions
7d865de8ec06bb098a3a11bd6328faaaf96dc1df
[ "MIT" ]
6
2021-01-05T22:02:57.000Z
2022-02-22T18:34:22.000Z
#include <TypeTraits.hpp> template <typename T> struct TestStruct { T* data = nullptr; hsd::usize sz = 0; TestStruct(T* ptr, hsd::usize size) : data{ptr}, sz{size} {} T* begin() { return data; } T* end() { return data + sz; } }; template <typename T> concept IsContainer = requires { hsd::declval<T>().begin(); }; int main() { static_assert(IsContainer<TestStruct<int>>); }
13.69697
48
0.553097
Anonymus-Player
a8bb07fe1da63d2f5d30853b9fc90a29e67dff58
11,170
cpp
C++
libAuto/main.cpp
fbergmann/auto-sbml
effb04e17405949aa6cbb596f3fd38b22cff3b36
[ "Unlicense" ]
1
2020-02-15T01:09:18.000Z
2020-02-15T01:09:18.000Z
libAuto/main.cpp
fbergmann/auto-sbml
effb04e17405949aa6cbb596f3fd38b22cff3b36
[ "Unlicense" ]
null
null
null
libAuto/main.cpp
fbergmann/auto-sbml
effb04e17405949aa6cbb596f3fd38b22cff3b36
[ "Unlicense" ]
null
null
null
#include "auto_f2c.h" #include "auto_c.h" int AUTO_main(int argc,char *argv[]); #ifdef WIN32 /* @@edc: added for windows getopt */ extern char *optarg; int getopt(int nargc, char * const *nargv, const char *ostr); #endif #ifdef FLOATING_POINT_TRAP #include <fpu_control.h> /* This is a x86 specific function only used for debugging. It turns on various floating point traps. */ static int trapfpe() { fpu_control_t traps; traps = _FPU_DEFAULT & (~(_FPU_MASK_IM | _FPU_MASK_ZM | _FPU_MASK_OM)); _FPU_SETCW(traps); } #endif BEGIN_AUTO_NAMESPACE; FILE *fp2 = NULL; FILE *fp3 = NULL; FILE *fp6 = NULL; FILE *fp7 = NULL; FILE *fp8 = NULL; FILE *fp9 = NULL; FILE *fp12 = NULL; void CloseAllFiles() { if (fp2 != NULL) {fflush(fp2); fclose(fp2); fp2= NULL;} if (fp3 != NULL) {fflush(fp3);fclose(fp3); fp3= NULL;} if (fp6 != NULL) {fflush(fp6);fclose(fp6); fp6= NULL;} if (fp7 != NULL) {fflush(fp7);fclose(fp7); fp7= NULL;} if (fp8 != NULL) {fflush(fp8);fclose(fp8); fp8= NULL;} if (fp9 != NULL) {fflush(fp9);fclose(fp9); fp9= NULL;} if (fp12 != NULL) {fflush(fp12);fclose(fp12); fp12= NULL;} } // initialize these... they may be reset before a call to AUTO_main int num_model_pars = 10; int num_total_pars = 2*num_model_pars; int sysoff = num_model_pars; // add changable fort names for ease char fort_name[13][512]; int fort_names_are_valid = 0; void SetFortNames(const char *key) { sprintf(fort_name[2], "%s.2", key); sprintf(fort_name[3], "%s.3", key); sprintf(fort_name[6], "%s.6", key); sprintf(fort_name[7], "%s.7", key); sprintf(fort_name[8], "%s.8", key); sprintf(fort_name[9], "%s.9", key); sprintf(fort_name[12], "%s.12", key); } int global_conpar_type=CONPAR_DEFAULT; int global_setubv_type=SETUBV_DEFAULT; int global_reduce_type=REDUCE_DEFAULT; int global_num_procs=1; int global_verbose_flag=0; static void options(){ fprintf(fp6, "-v: Give verbose output.\n"); fprintf(fp6, "-m: Use the Message Passing Interface library for parallelization.\n"); fprintf(fp6, "-t: Use the Pthreads library for parallelization.\n"); fprintf(fp6, " This option takes one of three arguements.\n"); fprintf(fp6, " 'conpar' parallelizes the condensation of parameters routine.\n"); fprintf(fp6, " 'setubv' parallelizes the jacobian setup routine.\n"); fprintf(fp6, " 'reduce' parallelizes the nested dissection routine.\n"); fprintf(fp6, " 'all' parallelizes all routines.\n"); fprintf(fp6, " In general the recommeneded option is 'all'.\n"); fprintf(fp6, "-#: The number of processing units to use (currently only used with the -t option)\n"); } static void scheme_not_supported_error(char *scheme) { fprintf(fp6, "'%s' not available in this binary\n",scheme); fprintf(fp6, "Support for '%s' needs to be included at compile time\n",scheme); throw "not supported"; //return 0; //exit(0); } int AUTO_main(int argc,char *argv[]) { #ifdef WIN32 clock_t time0, time1; #else struct timeval *time0,*time1; #endif integer *icp = new integer[num_total_pars]; doublereal *par = new doublereal[num_total_pars], *thl = new doublereal[num_total_pars]; doublereal *thu = NULL; integer *iuz= NULL; doublereal *vuz= NULL; iap_type iap; rap_type rap; function_list list; #ifdef USAGE struct rusage *init_usage,*total_usage; usage_start(&init_usage); usage_start(&total_usage); #endif #ifdef FLOATING_POINT_TRAP trapfpe(); #endif #ifdef MPI MPI_Init(&argc,&argv); #endif // check if we should set fort_names or not if(!fort_names_are_valid) { SetFortNames("fort"); strcpy(fort_name[6], "stdout"); } OPEN_FP3: fp3 = fopen(fort_name[3],"r"); if(fp3 == NULL) { fprintf(stderr,"warning: Could not open %s\n", fort_name[3]); // don't die, just "touch" the file fp3 = fopen(fort_name[3], "w"); if(fp3 == NULL) { fprintf(stderr,"Error: couldn't not create %s\n", fort_name[3]); throw "Error: Could not open fort.3"; //return -1; //exit(1); } fclose(fp3); goto OPEN_FP3; } fp6 = fopen(fort_name[6],"w"); if(fp6 == NULL) { fprintf(stderr,"Error: Could not open %s\n", fort_name[6]); throw "Error: Could not open fort.6"; //return -1; //exit(1); } //#ifdef LIBRARY_ONLY //if(strcmp(fort_name[6], "stdout")) //{ // fp6 = fopen(fort_name[6],"w"); // if(fp6 == NULL) { // fprintf(stderr,"Error: Could not open %s\n", fort_name[6]); // throw "Error: Could not open fort.2"; // //return -1; // //exit(1); // } //} //else // fp6 = stdout; //#endif fp7 = fopen(fort_name[7],"w"); if(fp7 == NULL) { fprintf(stderr,"Error: Could not open %s\n", fort_name[7]); throw "Error: Could not open fort.7"; //return -1; //exit(1); } fp9 = fopen(fort_name[9],"w"); if(fp9 == NULL) { fprintf(stderr,"Error: Could not open %s\n", fort_name[9]); throw "Error: Could not open fort.9"; //return -1; //exit(1); } { int c; while (1) { c = getopt(argc, argv, "mt:?#:v"); if (c == -1) break; switch (c){ case 'v': global_verbose_flag=1; break; case 'm': #ifdef MPI global_conpar_type = CONPAR_MPI; global_setubv_type = SETUBV_MPI; break; #endif scheme_not_supported_error("mpi"); break; case 't': #ifdef PTHREADS if(strcmp(optarg,"setubv")==0) { global_setubv_type = SETUBV_PTHREADS; } else if(strcmp(optarg,"conpar")==0) { global_conpar_type = CONPAR_PTHREADS; } else if(strcmp(optarg,"reduce")==0) { global_conpar_type = REDUCE_PTHREADS; } else if(strcmp(optarg,"all")==0) { global_conpar_type = CONPAR_PTHREADS; global_setubv_type = SETUBV_PTHREADS; global_reduce_type = REDUCE_PTHREADS; } else { fprintf(stderr,"Unknown type for threads '%s'. Using 'all'\n",optarg); global_conpar_type = CONPAR_PTHREADS; global_setubv_type = SETUBV_PTHREADS; } break; #endif scheme_not_supported_error("threads"); break; case '#': global_num_procs=atoi(optarg); break; case '?': options(); return 0; //exit(0); break; default: printf ("?? getopt returned character code 0%o ??\n", c); options(); return 0; //exit(1); //exit(0); } } // while } // scope #ifdef MPI { char processor_name[MPI_MAX_PROCESSOR_NAME]; int myid,namelen; MPI_Comm_rank(MPI_COMM_WORLD,&myid); MPI_Get_processor_name(processor_name,&namelen); if(global_verbose_flag) { fprintf(stderr,"Process %d on %s with pid %ld\n", myid, processor_name, (long int)getpid()); } if(myid!=0) { global_conpar_type = CONPAR_MPI; global_setubv_type = SETUBV_MPI; mpi_worker(); } } #endif /* Initialization : */ iap.mynode = mynode(); iap.numnodes = numnodes(); if (iap.numnodes > 1) { iap.parallel_flag = 1; } else { iap.parallel_flag = 0; } while(1){ time_start(&time0); time_start(&time1); /* NOTE: thu is allocated inside this function, and the pointer is passed back. I know this is ugly, but this function does a bit of work to get thu setup correctly, as well as figuring out the size the array should be. What really should happen is to have one function which reads fort.2 and another fuction which initializes the array. That way the allocation could happen between the two calles. */ { logical eof; init(&iap, &rap, par, icp, thl, &thu, &iuz, &vuz, &eof); if (eof) { break; } } /* Find restart label and determine type of restart point. */ if (iap.irs > 0) { logical found = FALSE_; findlb(&iap, &rap, iap.irs, &(iap.nfpr), &found); if (! found) { if (iap.mynode == 0) { fprintf(stderr,"\nRestart label %4ld not found\n",iap.irs); } throw "Restart label not found"; //return 0; //exit(0); } } #ifdef MPI if(global_setubv_type==SETUBV_MPI) { /* A few words about what is going on here. ips, irs, isw, itp, and nfpr are used to choose which functions are used for funi, icni, bcni, etc. unfortunately, their values are changed in init1 and chdim. In the old version of AUTO the functions were already choosen by the point these values were modified, so there was no problem. Now, in the message passing parallel version, the workers need both versions, since they both need to select the appropriate functions (using the old values) and actually compute (using the new values). */ int comm_size,i; integer funi_icni_params[5]; MPI_Comm_size(MPI_COMM_WORLD,&comm_size); funi_icni_params[0]=iap.ips; funi_icni_params[1]=iap.irs; funi_icni_params[2]=iap.isw; funi_icni_params[3]=iap.itp; funi_icni_params[4]=iap.nfpr; for(i=1;i<comm_size;i++){ /*Send message to get worker into init mode*/ { int message=AUTO_MPI_INIT_MESSAGE; MPI_Send(&message,1,MPI_INT,i,0,MPI_COMM_WORLD); } } MPI_Bcast(funi_icni_params,5,MPI_LONG,0,MPI_COMM_WORLD); } #endif set_function_pointers(iap,&list); init1(&iap, &rap, icp, par); chdim(&iap); /* Create the allocations for the global structures used in autlib3.c and autlib5.c. These are purely an efficiency thing. The allocation and deallocation of these scratch areas takes up a nontrivial amount of time if done directly in the wrapper functions in autlib3.c*/ allocate_global_memory(iap); /* ---------------------------------------------------------- */ /* ---------------------------------------------------------- */ /* One-parameter continuations */ /* ---------------------------------------------------------- */ /* ---------------------------------------------------------- */ #ifdef AUTO_CONSTRUCT_DESTRUCT user_construct(argc,argv); #endif #ifdef USAGE usage_end(init_usage,"main initialization"); #endif if(list.type==AUTOAE) autoae(&iap, &rap, par, icp, list.aelist.funi, list.aelist.stpnt, list.aelist.pvli, thl, thu, iuz, vuz); if(list.type==AUTOBV) autobv(&iap, &rap, par, icp, list.bvlist.funi, list.bvlist.bcni, list.bvlist.icni, list.bvlist.stpnt, list.bvlist.pvli, thl, thu, iuz, vuz); #ifdef USAGE usage_end(total_usage,"total"); #endif time_end(time0,"Total Time ",fp9); fprintf(fp9,"----------------------------------------------"); fprintf(fp9,"----------------------------------------------\n"); time_end(time1,"",fp6); #ifdef AUTO_CONSTRUCT_DESTRUCT user_destruct(); #endif } #ifdef MPI { int message = AUTO_MPI_KILL_MESSAGE; int size,i; MPI_Comm_size(MPI_COMM_WORLD,&size); for(i=1;i<size;i++) MPI_Send(&message,1,MPI_INT,i,0,MPI_COMM_WORLD); } MPI_Finalize(); #endif delete [] icp; delete [] par; delete [] thl; if (thu) free(thu); if (iuz) free(iuz); if (vuz) free(vuz); // close files CloseAllFiles(); // fclose(fp2); fp2 = NULL; // fclose(fp3); fp3 = NULL; ////#ifdef LIBRARY_ONLY //// if(fp6 != stdout) // fclose(fp6);fp6 = NULL; //// fp6 = NULL; ////#else //// fp6 = stdout; ////#endif // fclose(fp7); fp7 = NULL; // fclose(fp8); fp8 = NULL; // fclose(fp9); fp9 = NULL; return 0; } END_AUTO_NAMESPACE; //#ifndef LIBRARY_ONLY /* @@edc: compiling in main will be an option now */ ////int main(int argc,char *argv[]) //{ //#ifdef __cplusplus //using LibAuto::AUTO_main; //#endif // return AUTO_main(argc, argv); //} //#endif
25.444191
107
0.644852
fbergmann
a8bdd701da715f8ddec5009a55759eeec5710eef
648
cpp
C++
lab11_9_1question/lab11_9_1/lab11_9_1.cpp
wjingzhe/CPP_lab
081ba3612c2d96ffd074061ca1800b7f31486c37
[ "MIT" ]
null
null
null
lab11_9_1question/lab11_9_1/lab11_9_1.cpp
wjingzhe/CPP_lab
081ba3612c2d96ffd074061ca1800b7f31486c37
[ "MIT" ]
null
null
null
lab11_9_1question/lab11_9_1/lab11_9_1.cpp
wjingzhe/CPP_lab
081ba3612c2d96ffd074061ca1800b7f31486c37
[ "MIT" ]
null
null
null
// lab11_9_1.cpp : Defines the entry point for the console application. // #include "stdafx.h" int _tmain(int argc, _TCHAR* argv[]) { return 0; } #include<iostream> #include<fstream> using namespace std; void main() { ofstream file; file.open("input.txt"); file<<"aaaaaaaa\nbbbbbbbb\ncccccccc"; file.close(); ifstream filei("input.txt"); ofstream fileo; fileo.open("output.txt"); char c; filei>>noskipws; int i=1; fileo<<i<<"."; cout<<i<<"."; while(filei>>c) { if(c=='\n') { i++; fileo<<"\n"; cout<<"\n"; fileo<<i<<"."; cout<<i<<"."; } else { fileo<<c; cout<<c; } } filei.close(); fileo.close(); }
14.4
71
0.591049
wjingzhe
a8bdf0cb01d14fe0d613c5aadc67c00c0cbf7a4d
1,491
hpp
C++
System/include/Switch/System/IO/WatcherChangeTypes.hpp
kkptm/CppLikeCSharp
b2d8d9da9973c733205aa945c9ba734de0c734bc
[ "MIT" ]
4
2021-10-14T01:43:00.000Z
2022-03-13T02:16:08.000Z
System/include/Switch/System/IO/WatcherChangeTypes.hpp
kkptm/CppLikeCSharp
b2d8d9da9973c733205aa945c9ba734de0c734bc
[ "MIT" ]
null
null
null
System/include/Switch/System/IO/WatcherChangeTypes.hpp
kkptm/CppLikeCSharp
b2d8d9da9973c733205aa945c9ba734de0c734bc
[ "MIT" ]
2
2022-03-13T02:16:06.000Z
2022-03-14T14:32:57.000Z
/// @file /// @brief Contains Switch::System::IO::WatcherChangeTypes enum. #pragma once #include <Switch/As.hpp> #include <Switch/System/EventArgs.hpp> #include <Switch/System/Exception.hpp> /// @brief The Switch namespace contains all fundamental classes to access Hardware, Os, System, and more. namespace Switch { /// @brief The System namespace contains fundamental classes and base classes that define commonly-used value and reference data types, events and event handlers, interfaces, attributes, and processing exceptions. namespace System { /// @brief The System::IO namespace contains types that allow reading and writing to files and data streams, and types that provide basic file and directory support. namespace IO { /// @brief Changes that might occur to a file or directory. /// This enumeration has a FlagsAttribute attribute that allows a bitwise combination of its member values. enum class WatcherChangeTypes { /// @brief The creation, deletion, change, or renaming of a file or folder. All = 15, /// @brief The creation of a file or folder. Created = 1, /// @brief The deletion of a file or folder. Deleted = 2, /// @brief The change of a file or folder. The types of changes include: changes to size, attributes, security settings, last write, and last access time. Changed = 4, /// @brief The renaming of a file or folder. Renamed = 8 }; } } }
46.59375
215
0.695506
kkptm
a8bfdb823c5e96782c15b039d0f919d295062e3a
1,493
cpp
C++
d04/ex04/BocalSteroid.cpp
ncoden/42_CPP_pool
9f2d9aa030b65e3ad967086bff97e80e23705a29
[ "Apache-2.0" ]
5
2018-02-10T12:33:53.000Z
2021-03-28T09:27:05.000Z
d04/ex04/BocalSteroid.cpp
ncoden/42_CPP_pool
9f2d9aa030b65e3ad967086bff97e80e23705a29
[ "Apache-2.0" ]
null
null
null
d04/ex04/BocalSteroid.cpp
ncoden/42_CPP_pool
9f2d9aa030b65e3ad967086bff97e80e23705a29
[ "Apache-2.0" ]
6
2017-11-25T17:34:43.000Z
2020-12-20T12:00:04.000Z
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* BocalSteroid.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ncoden <ncoden@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/06/22 16:42:09 by ncoden #+# #+# */ /* Updated: 2015/06/22 16:59:43 by ncoden ### ########.fr */ /* */ /* ************************************************************************** */ #include <iostream> #include <string> #include "BocalSteroid.hpp" BocalSteroid::BocalSteroid(void) {} BocalSteroid::BocalSteroid(BocalSteroid const &src) { *this = src; } BocalSteroid::~BocalSteroid(void) {} BocalSteroid &BocalSteroid::operator=(BocalSteroid const &rhs) { (void)rhs; return (*this); } std::string BocalSteroid::beMined(DeepCoreMiner *laser) const { (void)laser; return ("Zazium"); } std::string BocalSteroid::beMined(StripMiner *laser) const { (void)laser; return ("Krpite"); } std::string const BocalSteroid::getName(void) const { return ("BocalSteroid"); }
29.27451
80
0.352981
ncoden
a8c077c12d6da2d3d73a0234c8dd362c44040fe6
4,126
hpp
C++
xr3core/h/xr/strings/stringutils.hpp
zyndor/xrhodes
15017c2ba6499b19e1dd327608ffb44dbaba7a4e
[ "BSD-2-Clause" ]
7
2018-11-13T09:44:56.000Z
2022-01-12T02:22:41.000Z
xr3core/h/xr/strings/stringutils.hpp
zyndor/xrhodes
15017c2ba6499b19e1dd327608ffb44dbaba7a4e
[ "BSD-2-Clause" ]
2
2018-10-30T08:19:02.000Z
2018-12-31T18:48:13.000Z
xr3core/h/xr/strings/stringutils.hpp
zyndor/xrhodes
15017c2ba6499b19e1dd327608ffb44dbaba7a4e
[ "BSD-2-Clause" ]
null
null
null
#ifndef XR_STRINGUTILS_HPP #define XR_STRINGUTILS_HPP //============================================================================== // // XRhodes // // copyright (c) Gyorgy Straub. All rights reserved. // // License: https://github.com/zyndor/xrhodes#License-bsd-2-clause // //============================================================================== #include <cstdint> #include <sstream> namespace xr { ///@return @a original, or if it's null, an empty string. char const* GetStringSafe(char const* original); ///@brief Attempts to convert @a from to @a to. ///@return Whether the operation was successful. template <typename T> bool StringTo(char const* from, T& to); ///@brief Finds all instances of @a find in @a original and replaces them with /// @replace, writing no more than @a bufferSize characters of the result to /// @a buffer and the actual length of the processed string to @a processedSize. /// Does not allocate memory. If, after writing the string there's space left in /// the buffer (i.e. processedSize < bufferSize), it will write a null terminator. ///@param original: original string. May contain \0 characters; is not required /// to be null-terminated. ///@param originalSize: size of original string. ///@param find: null-terminated string to find. ///@param replace: null-terminated string to replace instances of find. ///@param bufferSize: the size of the provided buffer. No more than this many /// characters will be written. ///@param buffer: buffer to write the result to. ///@param processedSize: output. The number of characters actually written. /// Guaranteed to be less then or equal to @a bufferSize. ///@return The start of the replaced string. char const* Replace(char const* original, size_t originalSize, char const* find, char const* replace, size_t bufferSize, char* buffer, size_t& processedSize); ///@brief This overload of Replace() operates on a null-terminated string, /// not requiring the size of @a original to be supplied. char const* Replace(char const* original, char const* find, char const* replace, size_t bufferSize, char* buffer, size_t& processedSize); ///@brief Converts the character @a c into its two-byte textual hex /// representation. ///@return One past the last character written to in @a buffer. ///@note Does not null terminate. char* Char2Hex(char c, char buffer[2]); ///@brief URL-encodes the first @a originalSize characters of @a original, /// writing up to @a bufferSize characters into the provided @a buffer and the /// actual length of the processed string to @a processedSize. /// Writes a null terminator if it can. ///@param original: original string. May contain \0 characters; is not required /// to be null-terminated. ///@param originalSize: size of original string. ///@param bufferSize: the size of the provided buffer. No more than this many /// characters will be written. ///@param buffer: buffer to write the result to. ///@param processedSize: output. The number of characters actually written. /// Guaranteed to be less then or equal to @a bufferSize. ///@return One past the last character written to in @a buffer, NOT including /// a null terminator it may have written. char const* UrlEncode(char const* original, size_t originalSize, size_t bufferSize, char* buffer, size_t& processedSize); ///@brief This overload of UrlEncode() operates on a null-terminated string, /// not requiring the size of @a original to be supplied. char const* UrlEncode(char const* original, size_t bufferSize, char* buffer, size_t& processedSize); //============================================================================== // inline //============================================================================== inline char const* GetStringSafe(char const* original) { return original != nullptr ? original : ""; } //============================================================================== template <typename T> inline bool StringTo(const char* from, T& to) { std::istringstream iss(from); return !(iss >> std::ws >> to).fail() && (iss >> std::ws).eof(); } } // xr #endif //XR_STRINGUTILS_HPP
40.851485
83
0.663354
zyndor
a8c0fe199980d190c1b9e2178703ca920d1da278
18,180
cpp
C++
src/mame/drivers/dietgo.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
26
2015-03-31T06:25:51.000Z
2021-12-14T09:29:04.000Z
src/mame/drivers/dietgo.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
null
null
null
src/mame/drivers/dietgo.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
10
2015-03-27T05:45:51.000Z
2022-02-04T06:57:36.000Z
// license:BSD-3-Clause // copyright-holders:Bryan McPhail, David Haywood /* Diet Go Go Driver by Bryan McPhail and David Haywood. Hold both START buttons on bootup to display version notice. Diet Go Go (Japan) DATA EAST DE-0370-2 NAME LOCATION TYPE ----------------------- JW-02 14M 27C512 JW-01-2 5H 27C2001 JW-00-2 4H " PAL16L8B 7H PAL16L8B 6H PAL16R6A 11H */ #include "emu.h" #include "cpu/h6280/h6280.h" #include "cpu/m68000/m68000.h" #include "sound/okim6295.h" #include "sound/ymopm.h" #include "machine/decocrpt.h" #include "machine/deco102.h" #include "machine/deco104.h" #include "video/deco16ic.h" #include "video/decospr.h" #include "emupal.h" #include "screen.h" #include "speaker.h" namespace { class dietgo_state : public driver_device { public: dietgo_state(const machine_config &mconfig, device_type type, const char *tag) : driver_device(mconfig, type, tag) , m_pf_rowscroll(*this, "pf%u_rowscroll", 1) , m_spriteram(*this, "spriteram") , m_decrypted_opcodes(*this, "decrypted_opcodes") , m_maincpu(*this, "maincpu") , m_audiocpu(*this, "audiocpu") , m_deco_tilegen(*this, "tilegen") , m_deco104(*this, "ioprot104") , m_sprgen(*this, "spritegen") { } void dietgo(machine_config &config); void init_dietgo(); private: // memory pointers required_shared_ptr_array<uint16_t, 2> m_pf_rowscroll; required_shared_ptr<uint16_t> m_spriteram; required_shared_ptr<uint16_t> m_decrypted_opcodes; // devices required_device<cpu_device> m_maincpu; required_device<h6280_device> m_audiocpu; required_device<deco16ic_device> m_deco_tilegen; required_device<deco104_device> m_deco104; required_device<decospr_device> m_sprgen; uint32_t screen_update(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect); DECO16IC_BANK_CB_MEMBER(bank_callback); uint16_t protection_region_0_104_r(offs_t offset); void protection_region_0_104_w(offs_t offset, uint16_t data, uint16_t mem_mask = ~0); void decrypted_opcodes_map(address_map &map); void main_map(address_map &map); void sound_map(address_map &map); }; uint32_t dietgo_state::screen_update(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect) { uint16_t flip = m_deco_tilegen->pf_control_r(0); flip_screen_set(BIT(flip, 7)); m_sprgen->set_flip_screen(BIT(flip, 7)); m_deco_tilegen->pf_update(m_pf_rowscroll[0], m_pf_rowscroll[1]); bitmap.fill(256, cliprect); /* not verified */ m_deco_tilegen->tilemap_2_draw(screen, bitmap, cliprect, TILEMAP_DRAW_OPAQUE, 0); m_deco_tilegen->tilemap_1_draw(screen, bitmap, cliprect, 0, 0); m_sprgen->draw_sprites(bitmap, cliprect, m_spriteram, 0x400); return 0; } uint16_t dietgo_state::protection_region_0_104_r(offs_t offset) { int real_address = 0 + (offset * 2); int deco146_addr = bitswap<32>(real_address, /* NC */31,30,29,28,27,26,25,24,23,22,21,20,19,18, 13,12,11,/**/ 17,16,15,14, 10,9,8, 7,6,5,4, 3,2,1,0) & 0x7fff; uint8_t cs = 0; uint16_t data = m_deco104->read_data(deco146_addr, cs); return data; } void dietgo_state::protection_region_0_104_w(offs_t offset, uint16_t data, uint16_t mem_mask) { int real_address = 0 + (offset * 2); int deco146_addr = bitswap<32>(real_address, /* NC */31,30,29,28,27,26,25,24,23,22,21,20,19,18, 13,12,11,/**/ 17,16,15,14, 10,9,8, 7,6,5,4, 3,2,1,0) & 0x7fff; uint8_t cs = 0; m_deco104->write_data(deco146_addr, data, mem_mask, cs); } void dietgo_state::main_map(address_map &map) { map(0x000000, 0x07ffff).rom(); map(0x200000, 0x20000f).w(m_deco_tilegen, FUNC(deco16ic_device::pf_control_w)); map(0x210000, 0x211fff).w(m_deco_tilegen, FUNC(deco16ic_device::pf1_data_w)); map(0x212000, 0x213fff).w(m_deco_tilegen, FUNC(deco16ic_device::pf2_data_w)); map(0x220000, 0x2207ff).writeonly().share(m_pf_rowscroll[0]); map(0x222000, 0x2227ff).writeonly().share(m_pf_rowscroll[1]); map(0x280000, 0x2807ff).ram().share(m_spriteram); map(0x300000, 0x300bff).ram().w("palette", FUNC(palette_device::write16)).share("palette"); map(0x340000, 0x343fff).rw(FUNC(dietgo_state::protection_region_0_104_r), FUNC(dietgo_state::protection_region_0_104_w)).share("prot16ram"); // Protection device map(0x380000, 0x38ffff).ram(); // mainram } void dietgo_state::decrypted_opcodes_map(address_map &map) { map(0x000000, 0x07ffff).rom().share(m_decrypted_opcodes); } // Physical memory map (21 bits) void dietgo_state::sound_map(address_map &map) { map(0x000000, 0x00ffff).rom(); map(0x100000, 0x100001).noprw(); // YM2203 - this board doesn't have one map(0x110000, 0x110001).rw("ymsnd", FUNC(ym2151_device::read), FUNC(ym2151_device::write)); map(0x120000, 0x120001).rw("oki", FUNC(okim6295_device::read), FUNC(okim6295_device::write)); map(0x130000, 0x130001).noprw(); // This board only has 1 oki chip map(0x140000, 0x140000).r(m_deco104, FUNC(deco104_device::soundlatch_r)); map(0x1f0000, 0x1f1fff).ram(); } static INPUT_PORTS_START( dietgo ) PORT_START("SYSTEM") // Verified as 4 bit input port only PORT_BIT( 0x0001, IP_ACTIVE_LOW, IPT_COIN1 ) PORT_BIT( 0x0002, IP_ACTIVE_LOW, IPT_COIN2 ) PORT_BIT( 0x0004, IP_ACTIVE_LOW, IPT_SERVICE1 ) PORT_BIT( 0x0008, IP_ACTIVE_HIGH, IPT_CUSTOM ) PORT_VBLANK("screen") PORT_START("INPUTS") PORT_BIT( 0x0001, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_8WAY PORT_PLAYER(1) PORT_BIT( 0x0002, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_PLAYER(1) PORT_BIT( 0x0004, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_PLAYER(1) PORT_BIT( 0x0008, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_PLAYER(1) PORT_BIT( 0x0010, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(1) PORT_BIT( 0x0020, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(1) PORT_BIT( 0x0040, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_PLAYER(1) PORT_BIT( 0x0080, IP_ACTIVE_LOW, IPT_START1 ) PORT_BIT( 0x0100, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_8WAY PORT_PLAYER(2) PORT_BIT( 0x0200, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_PLAYER(2) PORT_BIT( 0x0400, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_PLAYER(2) PORT_BIT( 0x0800, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_PLAYER(2) PORT_BIT( 0x1000, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(2) PORT_BIT( 0x2000, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(2) PORT_BIT( 0x4000, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_PLAYER(2) PORT_BIT( 0x8000, IP_ACTIVE_LOW, IPT_START2 ) PORT_START("DSW") PORT_DIPNAME( 0x0007, 0x0007, DEF_STR( Coin_A ) ) PORT_DIPSETTING( 0x0000, DEF_STR( 3C_1C ) ) PORT_DIPSETTING( 0x0001, DEF_STR( 2C_1C ) ) PORT_DIPSETTING( 0x0007, DEF_STR( 1C_1C ) ) PORT_DIPSETTING( 0x0006, DEF_STR( 1C_2C ) ) PORT_DIPSETTING( 0x0005, DEF_STR( 1C_3C ) ) PORT_DIPSETTING( 0x0004, DEF_STR( 1C_4C ) ) PORT_DIPSETTING( 0x0003, DEF_STR( 1C_5C ) ) PORT_DIPSETTING( 0x0002, DEF_STR( 1C_6C ) ) PORT_DIPNAME( 0x0038, 0x0038, DEF_STR( Coin_B ) ) PORT_DIPSETTING( 0x0000, DEF_STR( 3C_1C ) ) PORT_DIPSETTING( 0x0008, DEF_STR( 2C_1C ) ) PORT_DIPSETTING( 0x0038, DEF_STR( 1C_1C ) ) PORT_DIPSETTING( 0x0030, DEF_STR( 1C_2C ) ) PORT_DIPSETTING( 0x0028, DEF_STR( 1C_3C ) ) PORT_DIPSETTING( 0x0020, DEF_STR( 1C_4C ) ) PORT_DIPSETTING( 0x0018, DEF_STR( 1C_5C ) ) PORT_DIPSETTING( 0x0010, DEF_STR( 1C_6C ) ) PORT_DIPNAME( 0x0040, 0x0040, DEF_STR( Flip_Screen ) ) PORT_DIPSETTING( 0x0040, DEF_STR( Off ) ) PORT_DIPSETTING( 0x0000, DEF_STR( On ) ) PORT_DIPNAME( 0x0080, 0x0080, "Continue Coin" ) PORT_DIPSETTING( 0x0080, "1 Start/1 Continue" ) PORT_DIPSETTING( 0x0000, "2 Start/1 Continue" ) PORT_DIPNAME( 0x0300, 0x0300, DEF_STR( Lives ) ) PORT_DIPSETTING( 0x0100, "1" ) PORT_DIPSETTING( 0x0000, "2" ) PORT_DIPSETTING( 0x0300, "3" ) PORT_DIPSETTING( 0x0200, "4" ) PORT_DIPNAME( 0x0c00, 0x0c00, DEF_STR( Difficulty ) ) PORT_DIPSETTING( 0x0800, DEF_STR( Easy ) ) PORT_DIPSETTING( 0x0c00, DEF_STR( Normal ) ) PORT_DIPSETTING( 0x0400, DEF_STR( Hard ) ) PORT_DIPSETTING( 0x0000, DEF_STR( Hardest ) ) PORT_DIPNAME( 0x1000, 0x1000, DEF_STR( Free_Play ) ) PORT_DIPSETTING( 0x1000, DEF_STR( Off ) ) PORT_DIPSETTING( 0x0000, DEF_STR( On ) ) PORT_DIPNAME( 0x2000, 0x2000, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x2000, DEF_STR( Off ) ) PORT_DIPSETTING( 0x0000, DEF_STR( On ) ) PORT_DIPNAME( 0x4000, 0x4000, DEF_STR( Unknown ) ) // Demo_Sounds ) ) PORT_DIPSETTING( 0x4000, DEF_STR( Off ) ) // Players don't move in attract mode if on!? PORT_DIPSETTING( 0x0000, DEF_STR( On ) ) PORT_DIPNAME( 0x8000, 0x8000, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x8000, DEF_STR( Off ) ) PORT_DIPSETTING( 0x0000, DEF_STR( On ) ) INPUT_PORTS_END static const gfx_layout tile_8x8_layout = { 8,8, RGN_FRAC(1,2), 4, { RGN_FRAC(1,2)+8,RGN_FRAC(1,2)+0,RGN_FRAC(0,2)+8,RGN_FRAC(0,2)+0 }, { STEP8(0,1) }, { STEP8(0,8*2) }, 8*16 }; static const gfx_layout tile_16x16_layout = { 16,16, RGN_FRAC(1,2), 4, { RGN_FRAC(1,2)+8,RGN_FRAC(1,2)+0,RGN_FRAC(0,2)+8,RGN_FRAC(0,2)+0 }, { STEP8(16*8*2,1), STEP8(0,1) }, { STEP16(0,8*2) }, 32*16 }; static GFXDECODE_START( gfx_dietgo ) GFXDECODE_ENTRY( "tiles", 0, tile_8x8_layout, 0, 32 ) // Tiles (8x8) GFXDECODE_ENTRY( "tiles", 0, tile_16x16_layout, 0, 32 ) // Tiles (16x16) GFXDECODE_ENTRY( "sprites", 0, tile_16x16_layout, 512, 16 ) // Sprites (16x16) GFXDECODE_END DECO16IC_BANK_CB_MEMBER(dietgo_state::bank_callback) { return (bank & 0x70) << 8; } void dietgo_state::dietgo(machine_config &config) { // basic machine hardware M68000(config, m_maincpu, XTAL(28'000'000) / 2); // DE102 (verified on PCB) m_maincpu->set_addrmap(AS_PROGRAM, &dietgo_state::main_map); m_maincpu->set_addrmap(AS_OPCODES, &dietgo_state::decrypted_opcodes_map); m_maincpu->set_vblank_int("screen", FUNC(dietgo_state::irq6_line_hold)); H6280(config, m_audiocpu, XTAL(32'220'000) / 4 / 3); // Custom chip 45; XIN is 32.220MHZ/4, verified on PCB m_audiocpu->set_addrmap(AS_PROGRAM, &dietgo_state::sound_map); m_audiocpu->add_route(ALL_OUTPUTS, "mono", 0); // internal sound unused // video hardware screen_device &screen(SCREEN(config, "screen", SCREEN_TYPE_RASTER)); screen.set_refresh_hz(58); screen.set_vblank_time(ATTOSECONDS_IN_USEC(2500)); // not accurate screen.set_size(40*8, 32*8); screen.set_visarea(0*8, 40*8-1, 1*8, 31*8-1); screen.set_screen_update(FUNC(dietgo_state::screen_update)); screen.set_palette("palette"); PALETTE(config, "palette").set_format(palette_device::xBGR_888, 1024); GFXDECODE(config, "gfxdecode", "palette", gfx_dietgo); DECO16IC(config, m_deco_tilegen, 0); m_deco_tilegen->set_pf1_size(DECO_64x32); m_deco_tilegen->set_pf2_size(DECO_64x32); m_deco_tilegen->set_pf1_col_bank(0x00); m_deco_tilegen->set_pf2_col_bank(0x10); m_deco_tilegen->set_pf1_col_mask(0x0f); m_deco_tilegen->set_pf2_col_mask(0x0f); m_deco_tilegen->set_bank1_callback(FUNC(dietgo_state::bank_callback)); m_deco_tilegen->set_bank2_callback(FUNC(dietgo_state::bank_callback)); m_deco_tilegen->set_pf12_8x8_bank(0); m_deco_tilegen->set_pf12_16x16_bank(1); m_deco_tilegen->set_gfxdecode_tag("gfxdecode"); DECO_SPRITE(config, m_sprgen, 0); m_sprgen->set_gfx_region(2); m_sprgen->set_gfxdecode_tag("gfxdecode"); DECO104PROT(config, m_deco104, 0); m_deco104->port_a_cb().set_ioport("INPUTS"); m_deco104->port_b_cb().set_ioport("SYSTEM"); m_deco104->port_c_cb().set_ioport("DSW"); m_deco104->soundlatch_irq_cb().set_inputline(m_audiocpu, 0); m_deco104->set_interface_scramble_interleave(); m_deco104->set_use_magic_read_address_xor(true); // sound hardware SPEAKER(config, "mono").front_center(); ym2151_device &ymsnd(YM2151(config, "ymsnd", XTAL(32'220'000) / 9)); // verified on PCB ymsnd.irq_handler().set_inputline(m_audiocpu, 1); // IRQ2 ymsnd.add_route(ALL_OUTPUTS, "mono", 0.45); OKIM6295(config, "oki", XTAL(32'220'000) / 32, okim6295_device::PIN7_HIGH).add_route(ALL_OUTPUTS, "mono", 0.60); // verified on PCB } ROM_START( dietgo ) ROM_REGION( 0x80000, "maincpu", 0 ) // DE102 code (encrypted) ROM_LOAD16_BYTE( "jy_00-2.4h", 0x000001, 0x040000, CRC(014dcf62) SHA1(1a28ce4a643ec8b6f062b1200342ed4dc6db38a1) ) ROM_LOAD16_BYTE( "jy_01-2.5h", 0x000000, 0x040000, CRC(793ebd83) SHA1(b9178f18ce6e9fca848cbbf9dce3f3856672bf94) ) ROM_REGION( 0x10000, "audiocpu", 0 ) ROM_LOAD( "jy_02.14m", 0x00000, 0x10000, CRC(4e3492a5) SHA1(5f302bdbacbf95ea9f3694c48545a1d6bba4b019) ) ROM_REGION( 0x100000, "tiles", 0 ) ROM_LOAD( "may-00.10a", 0x00000, 0x100000, CRC(234d1f8d) SHA1(42d23aad20df20cbd2359cc12bdd47636b2027d3) ) ROM_REGION( 0x200000, "sprites", 0 ) ROM_LOAD( "may-01.14a", 0x000000, 0x100000, CRC(2da57d04) SHA1(3898e9fef365ecaa4d86aa11756b527a4fffb494) ) ROM_LOAD( "may-02.16a", 0x100000, 0x100000, CRC(3a66a713) SHA1(beeb99156332cf4870738f7769b719a02d7b40af) ) ROM_REGION( 0x80000, "oki", 0 ) ROM_LOAD( "may-03.11l", 0x00000, 0x80000, CRC(b6e42bae) SHA1(c282cdf7db30fb63340cc609bf00f5ab63a75583) ) ROM_REGION( 0x0600, "plds", 0 ) ROM_LOAD( "pal16l8b_vd-00.6h", 0x0000, 0x0104, NO_DUMP ) // PAL is read protected ROM_LOAD( "pal16l8b_vd-01.7h", 0x0200, 0x0104, NO_DUMP ) // PAL is read protected ROM_LOAD( "pal16r6a_vd-02.11h", 0x0400, 0x0104, NO_DUMP ) // PAL is read protected ROM_END ROM_START( dietgoe ) // weird, still version 1.1 but different (earlier) date ROM_REGION( 0x80000, "maincpu", 0 ) // DE102 code (encrypted) ROM_LOAD16_BYTE( "jy_00-1.4h", 0x000001, 0x040000, CRC(8bce137d) SHA1(55f5b1c89330803c6147f9656f2cabe8d1de8478) ) ROM_LOAD16_BYTE( "jy_01-1.5h", 0x000000, 0x040000, CRC(eca50450) SHA1(1a24117e3b1b66d7dbc5484c94cc2c627d34e6a3) ) ROM_REGION( 0x10000, "audiocpu", 0 ) ROM_LOAD( "jy_02.14m", 0x00000, 0x10000, CRC(4e3492a5) SHA1(5f302bdbacbf95ea9f3694c48545a1d6bba4b019) ) ROM_REGION( 0x100000, "tiles", 0 ) ROM_LOAD( "may-00.10a", 0x00000, 0x100000, CRC(234d1f8d) SHA1(42d23aad20df20cbd2359cc12bdd47636b2027d3) ) ROM_REGION( 0x200000, "sprites", 0 ) ROM_LOAD( "may-01.14a", 0x000000, 0x100000, CRC(2da57d04) SHA1(3898e9fef365ecaa4d86aa11756b527a4fffb494) ) ROM_LOAD( "may-02.16a", 0x100000, 0x100000, CRC(3a66a713) SHA1(beeb99156332cf4870738f7769b719a02d7b40af) ) ROM_REGION( 0x80000, "oki", 0 ) ROM_LOAD( "may-03.11l", 0x00000, 0x80000, CRC(b6e42bae) SHA1(c282cdf7db30fb63340cc609bf00f5ab63a75583) ) ROM_REGION( 0x0600, "plds", 0 ) ROM_LOAD( "pal16l8b_vd-00.6h", 0x0000, 0x0104, NO_DUMP ) // PAL is read protected ROM_LOAD( "pal16l8b_vd-01.7h", 0x0200, 0x0104, NO_DUMP ) // PAL is read protected ROM_LOAD( "pal16r6a_vd-02.11h", 0x0400, 0x0104, NO_DUMP ) // PAL is read protected ROM_END ROM_START( dietgou ) ROM_REGION( 0x80000, "maincpu", 0 ) // DE102 code (encrypted) ROM_LOAD16_BYTE( "jx_00-.4h", 0x000001, 0x040000, CRC(1a9de04f) SHA1(7ce1e7cf4cdce2b02da4df2a6ae9a9e665e24422) ) ROM_LOAD16_BYTE( "jx_01-.5h", 0x000000, 0x040000, CRC(79c097c8) SHA1(be49055ee324535e1118d243bd49e74ec1d2a2d7) ) ROM_REGION( 0x10000, "audiocpu", 0 ) ROM_LOAD( "jx_02.14m", 0x00000, 0x10000, CRC(4e3492a5) SHA1(5f302bdbacbf95ea9f3694c48545a1d6bba4b019) ) // Same as other regions but different label ROM_REGION( 0x100000, "tiles", 0 ) ROM_LOAD( "may-00.10a", 0x00000, 0x100000, CRC(234d1f8d) SHA1(42d23aad20df20cbd2359cc12bdd47636b2027d3) ) ROM_REGION( 0x200000, "sprites", 0 ) ROM_LOAD( "may-01.14a", 0x000000, 0x100000, CRC(2da57d04) SHA1(3898e9fef365ecaa4d86aa11756b527a4fffb494) ) ROM_LOAD( "may-02.16a", 0x100000, 0x100000, CRC(3a66a713) SHA1(beeb99156332cf4870738f7769b719a02d7b40af) ) ROM_REGION( 0x80000, "oki", 0 ) ROM_LOAD( "may-03.11l", 0x00000, 0x80000, CRC(b6e42bae) SHA1(c282cdf7db30fb63340cc609bf00f5ab63a75583) ) ROM_REGION( 0x0600, "plds", 0 ) ROM_LOAD( "pal16l8b_vd-00.6h", 0x0000, 0x0104, NO_DUMP ) // PAL is read protected ROM_LOAD( "pal16l8b_vd-01.7h", 0x0200, 0x0104, NO_DUMP ) // PAL is read protected ROM_LOAD( "pal16r6a_vd-02.11h", 0x0400, 0x0104, NO_DUMP ) // PAL is read protected ROM_END ROM_START( dietgoj ) ROM_REGION( 0x80000, "maincpu", 0 ) // DE102 code (encrypted) ROM_LOAD16_BYTE( "jw_00-2.4h", 0x000001, 0x040000, CRC(e6ba6c49) SHA1(d5eaea81f1353c58c03faae67428f7ee98e766b1) ) ROM_LOAD16_BYTE( "jw_01-2.5h", 0x000000, 0x040000, CRC(684a3d57) SHA1(bd7a57ba837a1dc8f92b5ebcb46e50db1f98524f) ) ROM_REGION( 0x10000, "audiocpu", 0 ) ROM_LOAD( "jw_02.14m", 0x00000, 0x10000, CRC(4e3492a5) SHA1(5f302bdbacbf95ea9f3694c48545a1d6bba4b019) ) // Same as other regions but different label ROM_REGION( 0x100000, "tiles", 0 ) ROM_LOAD( "may-00.10a", 0x00000, 0x100000, CRC(234d1f8d) SHA1(42d23aad20df20cbd2359cc12bdd47636b2027d3) ) ROM_REGION( 0x200000, "sprites", 0 ) ROM_LOAD( "may-01.14a", 0x000000, 0x100000, CRC(2da57d04) SHA1(3898e9fef365ecaa4d86aa11756b527a4fffb494) ) ROM_LOAD( "may-02.16a", 0x100000, 0x100000, CRC(3a66a713) SHA1(beeb99156332cf4870738f7769b719a02d7b40af) ) ROM_REGION( 0x80000, "oki", 0 ) ROM_LOAD( "may-03.11l", 0x00000, 0x80000, CRC(b6e42bae) SHA1(c282cdf7db30fb63340cc609bf00f5ab63a75583) ) ROM_REGION( 0x0600, "plds", 0 ) ROM_LOAD( "pal16l8b_vd-00.6h", 0x0000, 0x0104, NO_DUMP ) // PAL is read protected ROM_LOAD( "pal16l8b_vd-01.7h", 0x0200, 0x0104, NO_DUMP ) // PAL is read protected ROM_LOAD( "pal16r6a_vd-02.11h", 0x0400, 0x0104, NO_DUMP ) // PAL is read protected ROM_END void dietgo_state::init_dietgo() { deco56_decrypt_gfx(machine(), "tiles"); deco102_decrypt_cpu((uint16_t *)memregion("maincpu")->base(), m_decrypted_opcodes, 0x80000, 0xe9ba, 0x01, 0x19); } } // Anonymous namespace GAME( 1992, dietgo, 0, dietgo, dietgo, dietgo_state, init_dietgo, ROT0, "Data East Corporation", "Diet Go Go (Euro v1.1 1992.09.26)", MACHINE_SUPPORTS_SAVE ) GAME( 1992, dietgoe, dietgo, dietgo, dietgo, dietgo_state, init_dietgo, ROT0, "Data East Corporation", "Diet Go Go (Euro v1.1 1992.08.04)" , MACHINE_SUPPORTS_SAVE ) GAME( 1992, dietgou, dietgo, dietgo, dietgo, dietgo_state, init_dietgo, ROT0, "Data East Corporation", "Diet Go Go (USA v1.1 1992.09.26)", MACHINE_SUPPORTS_SAVE ) GAME( 1992, dietgoj, dietgo, dietgo, dietgo, dietgo_state, init_dietgo, ROT0, "Data East Corporation", "Diet Go Go (Japan v1.1 1992.09.26)", MACHINE_SUPPORTS_SAVE )
41.793103
167
0.740484
Robbbert
a8c1159b3471732e1290bc1af1d285b6d70f9610
63
cpp
C++
src/Graphics/stb_image/stb_image.cpp
jkbz64/Zadymka
16c2bf66ce6c3bbff8eeeb3fad291b2939e4a5b7
[ "MIT" ]
2
2020-03-18T16:13:04.000Z
2021-07-30T12:18:52.000Z
src/Graphics/stb_image/stb_image.cpp
jkbz64/Zadymka
16c2bf66ce6c3bbff8eeeb3fad291b2939e4a5b7
[ "MIT" ]
null
null
null
src/Graphics/stb_image/stb_image.cpp
jkbz64/Zadymka
16c2bf66ce6c3bbff8eeeb3fad291b2939e4a5b7
[ "MIT" ]
null
null
null
#define STB_IMAGE_IMPLEMENTATION #include "../stb/stb_image.h"
21
32
0.793651
jkbz64
a8c381722bb1c74255fd83b43e9432d36c56ee35
3,068
hh
C++
TrkBase/TrkModuleId.hh
brownd1978/FastSim
05f590d72d8e7f71856fd833114a38b84fc7fd48
[ "Apache-2.0" ]
null
null
null
TrkBase/TrkModuleId.hh
brownd1978/FastSim
05f590d72d8e7f71856fd833114a38b84fc7fd48
[ "Apache-2.0" ]
null
null
null
TrkBase/TrkModuleId.hh
brownd1978/FastSim
05f590d72d8e7f71856fd833114a38b84fc7fd48
[ "Apache-2.0" ]
null
null
null
//-------------------------------------------------------------------------- // File and Version Information: // $Id: TrkModuleId.hh,v 1.3 2007/02/05 22:16:38 brownd Exp $ // // Description: // Trivial class to identify modules used in tracking. // Environment: // Software developed for the BaBar Detector at the SLAC B-Factory. // // Copyright Information: // Copyright (C) 2004 Lawrence Berkeley Laboratory // // Author(s): David Brown, 11/22/04 // //------------------------------------------------------------------------ #ifndef TRKMODULEID_HH #define TRKMODULEID_HH class TrkHistory; class TrkRecoTrk; #include <map> #include <vector> #include <string> class TrkModuleId { public: // enums defining module mapping. existing values should NEVER BE CHANGED, // new numbers may be added as needed enum trkFinders {nofinder=0,dchl3trkconverter=1,dchtrackfinder=2, dchradtrkfinder=3,dcxtrackfinder=4,dcxsparsefinder=5, svttrackfinder=6,svtcircle2helix=7, nfinders}; enum trkModifiers {nomodifier=0,dcxhitadder=1,dchtrkfitupdater=2,trksettrackt0=3, trksettrackt1=4,dchkal1dfit=5,dchkalrx=6,svtkal1dfit=7, svtkalrx=8,dchkalfinalfit=9, svtkalfinalfit=10,trksvthitadder=11,trackmerge=12, trkdchhitadder=13,trkdchradhitadder=14,defaultkalrx=15, trkhitfix=16,trkloopfix=17,trksvthafix=18,trkfailedfix=19,trkmomfix=20, nmodifiers}; // single accessor static const TrkModuleId& instance(); // singleton class, so constructor is protected. Use 'instance' method ~TrkModuleId(); // translate enum values to strings const std::string& finder(int ifnd) const; const std::string& modifier(int imod) const; // translate string to enum value int finder(const std::string& fndmod) const; int modifier(const std::string& modmod) const; // same for TrkHistory. If the module specified isn't a finder (modifier) // the appropriate version of 0 will be returned int finder(const TrkHistory& hist) const; int modifier(const TrkHistory& hist) const; // access maps const std::map<std::string,int>& finders() const { return _finders;} const std::map<std::string,int>& modifiers() const { return _modifiers;} // allow extending the finder and modifier maps void addFinder(const TrkHistory& hist); void addModifier(const TrkHistory& hist); // fill and decode a bitmap of finders/modifiers from a track. unsigned finderMap(const TrkRecoTrk*) const; void setFinders(TrkRecoTrk* trk,unsigned findermap) const; unsigned modifierMap(const TrkRecoTrk*) const; void setModifiers(TrkRecoTrk* trk,unsigned findermap) const; private: // static instance static TrkModuleId* _instance; TrkModuleId(); // pre-empt TrkModuleId(const TrkModuleId&); TrkModuleId& operator =(const TrkModuleId&); // map of finder module names to numbers std::map<std::string,int> _finders; // map of modifier module names to numbers std::map<std::string,int> _modifiers; // reverse-mapping std::vector<std::string> _findernames; std::vector<std::string> _modifiernames; }; #endif
36.52381
92
0.70339
brownd1978
a8c8c88328a9de59b535c4606e69b5fdc6de8b99
399
cpp
C++
App/Source/ECS/System/Render/SpriteRendererSystem.cpp
Clymiaru/GDPARCM_InteractiveLoadingScreen
20b6de0719ab3bd0e50efbbc792470826de8e7f1
[ "MIT" ]
null
null
null
App/Source/ECS/System/Render/SpriteRendererSystem.cpp
Clymiaru/GDPARCM_InteractiveLoadingScreen
20b6de0719ab3bd0e50efbbc792470826de8e7f1
[ "MIT" ]
null
null
null
App/Source/ECS/System/Render/SpriteRendererSystem.cpp
Clymiaru/GDPARCM_InteractiveLoadingScreen
20b6de0719ab3bd0e50efbbc792470826de8e7f1
[ "MIT" ]
null
null
null
#include "pch.h" #include "SpriteRendererSystem.h" SpriteRendererSystem::SpriteRendererSystem() { } SpriteRendererSystem::~SpriteRendererSystem() { } void SpriteRendererSystem::Render(sf::RenderWindow& window) { for (auto* component : m_SpriteRendererComponentList) { auto transform = component->GetTransform(); auto sprite = component->GetSprite(); window.draw(sprite, transform); } }
19
59
0.754386
Clymiaru
a8d1dcb69247bb3c4f6d515cf8603296d5587cfd
1,995
cpp
C++
hiro/qt/action/menu-radio-item.cpp
mp-lee/higan
c38a771f2272c3ee10fcb99f031e982989c08c60
[ "Intel", "ISC" ]
38
2018-04-05T05:00:05.000Z
2022-02-06T00:02:02.000Z
hiro/qt/action/menu-radio-item.cpp
ameer-bauer/higan-097
a4a28968173ead8251cfa7cd6b5bf963ee68308f
[ "Info-ZIP" ]
1
2018-04-29T19:45:14.000Z
2018-04-29T19:45:14.000Z
hiro/qt/action/menu-radio-item.cpp
ameer-bauer/higan-097
a4a28968173ead8251cfa7cd6b5bf963ee68308f
[ "Info-ZIP" ]
8
2018-04-16T22:37:46.000Z
2021-02-10T07:37:03.000Z
#if defined(Hiro_MenuRadioItem) namespace hiro { auto pMenuRadioItem::construct() -> void { qtMenuRadioItem = new QtMenuRadioItem(*this); qtActionGroup = new QActionGroup(nullptr); qtMenuRadioItem->setCheckable(true); qtMenuRadioItem->setActionGroup(qtActionGroup); qtMenuRadioItem->setChecked(true); qtMenuRadioItem->connect(qtMenuRadioItem, SIGNAL(triggered()), SLOT(onActivate())); if(auto parent = _parentMenu()) { parent->qtMenu->addAction(qtMenuRadioItem); } if(auto parent = _parentPopupMenu()) { parent->qtPopupMenu->addAction(qtMenuRadioItem); } setGroup(state().group); _setState(); } auto pMenuRadioItem::destruct() -> void { delete qtMenuRadioItem; delete qtActionGroup; qtMenuRadioItem = nullptr; qtActionGroup = nullptr; } auto pMenuRadioItem::setChecked() -> void { _setState(); } auto pMenuRadioItem::setGroup(sGroup group) -> void { bool first = true; if(auto& group = state().group) { for(auto& weak : group->state.objects) { if(auto object = weak.acquire()) { if(auto menuRadioItem = dynamic_cast<mMenuRadioItem*>(object.data())) { if(auto self = menuRadioItem->self()) { self->qtMenuRadioItem->setChecked(menuRadioItem->state.checked = first); first = false; } } } } } } auto pMenuRadioItem::setText(const string& text) -> void { _setState(); } auto pMenuRadioItem::_setState() -> void { if(auto& group = state().group) { if(auto object = group->object(0)) { if(auto menuRadioItem = dynamic_cast<mMenuRadioItem*>(object.data())) { if(auto self = menuRadioItem->self()) { qtMenuRadioItem->setActionGroup(self->qtActionGroup); } } } } qtMenuRadioItem->setChecked(state().checked); qtMenuRadioItem->setText(QString::fromUtf8(state().text)); } auto QtMenuRadioItem::onActivate() -> void { if(p.state().checked) return; p.self().setChecked(); p.self().doActivate(); } } #endif
25.253165
85
0.66416
mp-lee
a8d3aed4aa014d868ef457e9b6be1f6f89f6772a
1,093
hpp
C++
headers/MyFunctions.hpp
DetlevCM/chemical-kinetics-solver
7010fd6c72c29a0d912ad0c353ff13a5b643cc04
[ "MIT" ]
3
2015-07-03T20:14:00.000Z
2021-02-02T13:45:31.000Z
headers/MyFunctions.hpp
DetlevCM/chemical-kinetics-solver
7010fd6c72c29a0d912ad0c353ff13a5b643cc04
[ "MIT" ]
null
null
null
headers/MyFunctions.hpp
DetlevCM/chemical-kinetics-solver
7010fd6c72c29a0d912ad0c353ff13a5b643cc04
[ "MIT" ]
4
2017-11-09T19:49:18.000Z
2020-08-04T18:29:28.000Z
#ifndef _MY_OTHER_FUNCTIONS_ #define _MY_OTHER_FUNCTIONS_ //*** Define some of my random hard to classify functions ***// void Process_User_Input( FileNames& filenames, vector<string> User_Inputs ); void Get_Mechanism( string filename , Reaction_Mechanism& reaction_mechanism ); vector< double > Get_Delta_N( const vector< SingleReactionData >& Reactions ); // Making Scheme Irreversible vector< SingleReactionData > Make_Irreversible( vector< SingleReactionData > Reactions, const vector< ThermodynamicData > Thermodynamics, double Initial_Temperature, /// use initial temperature from initial data double Range // specify +/- range around initial temperature ); void Synchronize_Gas_Liquid_Model( size_t number_synchronized_species, size_t liquid_species_count, size_t gas_species_count, // gas and liquid counts so I know where concentration entries belong to double *y, // concentrations (&temperature) from the ODE solver double Vliq_div_Vgas, vector< double > Henry_Constants // need to line up with species IDs ); #endif /* _MY_OTHER_FUNCTIONS_ */
27.325
129
0.778591
DetlevCM
a8d405a417d9ccd8e5ed083a3bdff37c310de5a4
1,427
cpp
C++
ace/tao/tao_idl/be/be_visitor_root/any_op.cpp
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
46
2015-12-04T17:12:58.000Z
2022-03-11T04:30:49.000Z
ace/tao/tao_idl/be/be_visitor_root/any_op.cpp
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
null
null
null
ace/tao/tao_idl/be/be_visitor_root/any_op.cpp
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
23
2016-10-24T09:18:14.000Z
2022-02-25T02:11:35.000Z
// // any_op.cpp,v 1.2 1998/08/03 17:39:59 gonzo Exp // // ============================================================================ // // = LIBRARY // TAO IDL // // = FILENAME // any_op.cpp // // = DESCRIPTION // Visitor generating code for the Any operators for types defined in Root's // scope. // // = AUTHOR // Aniruddha Gokhale // // ============================================================================ #include "idl.h" #include "idl_extern.h" #include "be.h" #include "be_visitor_root.h" ACE_RCSID(be_visitor_root, any_op, "any_op.cpp,v 1.2 1998/08/03 17:39:59 gonzo Exp") // *************************************************************************** // Root visitor for generating Any operator declarations in the client header // and stub // *************************************************************************** be_visitor_root_any_op::be_visitor_root_any_op (be_visitor_context *ctx) : be_visitor_root (ctx) { } be_visitor_root_any_op::~be_visitor_root_any_op (void) { } int be_visitor_root_any_op::visit_root (be_root *node) { // all we have to do is to visit the scope and generate code if (this->visit_scope (node) == -1) { ACE_ERROR_RETURN ((LM_ERROR, "(%N:%l) be_visitor_root::visit_root - " "codegen for scope failed\n"), -1); } return 0; }
25.035088
85
0.480028
tharindusathis
a8d942a2fb1a8ef5b8f33043378af3d4b7bc2422
1,125
hpp
C++
src/lib/interface/ChoixReseau.hpp
uvsq21603504/in608-tcp_ip_simulation
95cedcbe7dab5991b84e182297b6ada3ae24679b
[ "MIT" ]
null
null
null
src/lib/interface/ChoixReseau.hpp
uvsq21603504/in608-tcp_ip_simulation
95cedcbe7dab5991b84e182297b6ada3ae24679b
[ "MIT" ]
null
null
null
src/lib/interface/ChoixReseau.hpp
uvsq21603504/in608-tcp_ip_simulation
95cedcbe7dab5991b84e182297b6ada3ae24679b
[ "MIT" ]
null
null
null
#ifndef CHOIXRESEAU_H #define CHOIXRESEAU_H #include <QApplication> #include <QWidget> #include <QPushButton> #include <QLabel> #include <QVBoxLayout> #include <QComboBox> #include <QSpinBox> #include <QMessageBox> class ChoixReseau : public QVBoxLayout { Q_OBJECT private : // Attributs QComboBox* m_Depart; QComboBox* m_Arrive; QSpinBox* m_Ssthresh; QSpinBox* m_PaquetNombre; QComboBox* m_PaquetType; QPushButton* m_Valider; QMessageBox* m_VerifConfig; QPushButton* m_ConfigSimple; QPushButton* m_ConfigMaison; QPushButton* m_ConfigPme; QPushButton* m_ConfigEntreprise; QMessageBox* m_VerifReseau; public : // Constructeur ChoixReseau(); // Destructeur ~ChoixReseau(); // Méthode void analyseConfig(); private slots : // Méthodes Slots void selectConfigSimple(); void selectConfigMaison(); void selectConfigPme(); void selectConfigEntreprise(); void verifConfigMessage(); }; #endif // CHOIXRESEAU_H
20.089286
40
0.639111
uvsq21603504
a8dbec634780730c6ded9a899e8c74607aed8677
2,394
cc
C++
folding_libs/MELIBS/arpack++/examples/band/complex/bcompreg.cc
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
1
2016-05-16T02:27:46.000Z
2016-05-16T02:27:46.000Z
arpack++/examples/band/complex/bcompreg.cc
red2901/sandbox
fae6c1624cc9957593d030f3b0306dbded29f0a2
[ "MIT" ]
null
null
null
arpack++/examples/band/complex/bcompreg.cc
red2901/sandbox
fae6c1624cc9957593d030f3b0306dbded29f0a2
[ "MIT" ]
null
null
null
/* ARPACK++ v1.2 2/18/2000 c++ interface to ARPACK code. MODULE BCompReg.cc. Example program that illustrates how to solve a complex standard eigenvalue problem in regular mode using the ARluCompStdEig class. 1) Problem description: In this example we try to solve A*x = x*lambda in regular mode, where A is obtained from the standard central difference discretization of the convection-diffusion operator (Laplacian u) + rho*(du / dx) on the unit square [0,1]x[0,1] with zero Dirichlet boundary conditions. 2) Data structure used to represent matrix A: {ndiagL, ndiagU, A}: matrix A data in band format. The columns of A are stored sequentially in vector A. ndiagL and ndiagU supply the lower and upper bandwidth of A, respectively. 3) Included header files: File Contents ----------- --------------------------------------------- bcmatrxa.h CompMatrixA, a function that generates matrix A in band format. arbnsmat.h The ARbdNonSymMatrix class definition. arbscomp.h The ARluCompStdEig class definition. lcompsol.h The Solution function. arcomp.h The "arcomplex" (complex) type definition. 4) ARPACK Authors: Richard Lehoucq Kristyn Maschhoff Danny Sorensen Chao Yang Dept. of Computational & Applied Mathematics Rice University Houston, Texas */ #include "arcomp.h" #include "arbscomp.h" #include "arbnsmat.h" #include "bcmatrxa.h" #include "lcompsol.h" int main() { // Defining variables; int nx; int n; // Dimension of the problem. int ndiagL; // Lower bandwidth of A and B. int ndiagU; // Upper bandwidth of A and B. arcomplex<double>* valA; // pointer to an array that stores // the elements of A. // Creating a complex matrix. nx = 10; CompMatrixA(nx, n, ndiagL, ndiagU, valA); ARbdNonSymMatrix<arcomplex<double>, double> A(n, ndiagL, ndiagU, valA); // Defining what we need: the four eigenvectors of A with largest magnitude. ARluCompStdEig<double> dprob(4L, A); // Finding eigenvalues and eigenvectors. dprob.FindEigenvectors(); // Printing solution. Solution(A, dprob); } // main
28.164706
78
0.620301
parasol-ppl
a8df4e4843a9caae2341d5511806be09178b1caa
2,702
hh
C++
asv_wave_sim_gazebo_plugins/include/asv_wave_sim_gazebo_plugins/Algorithm.hh
minzlee/asv_wave_sim
d9426e1b7b75d43f0c1bd3201e6ba62e54af968f
[ "Apache-2.0" ]
25
2019-05-29T04:55:19.000Z
2022-03-18T19:07:07.000Z
asv_wave_sim_gazebo_plugins/include/asv_wave_sim_gazebo_plugins/Algorithm.hh
minzlee/asv_wave_sim
d9426e1b7b75d43f0c1bd3201e6ba62e54af968f
[ "Apache-2.0" ]
12
2019-02-14T16:26:57.000Z
2022-03-30T19:44:33.000Z
asv_wave_sim_gazebo_plugins/include/asv_wave_sim_gazebo_plugins/Algorithm.hh
minzlee/asv_wave_sim
d9426e1b7b75d43f0c1bd3201e6ba62e54af968f
[ "Apache-2.0" ]
11
2019-05-29T04:55:22.000Z
2022-02-23T11:55:32.000Z
// Copyright (C) 2019 Rhys Mainwaring // // 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 <https://www.gnu.org/licenses/>. /// \file Algorithm.hh /// \brief Methods for sorting indexes into arrays and vectors. #ifndef _ASV_WAVE_SIM_GAZEBO_PLUGINS_ALGORITHM_HH_ #define _ASV_WAVE_SIM_GAZEBO_PLUGINS_ALGORITHM_HH_ #include <algorithm> #include <array> #include <numeric> #include <vector> namespace asv { /// \brief A small collection of static template methods for sorting arrays and vectors. namespace algorithm { /// \brief Sort and keep track of indexes (largest first) /// /// See: /// <https://stackoverflow.com/questions/1577475/c-sorting-and-keeping-track-of-indexes> /// /// Usage: /// \code /// for (auto i: sort_indexes(v)) { /// cout << v[i] << endl; /// } /// \endcode /// /// \param[in] _v The array to be indexed. /// \return A vector of indexes in to the input array. template <typename T> std::vector<size_t> sort_indexes(const std::vector<T>& _v) { // initialize original index locations std::vector<size_t> idx(_v.size()); std::iota(idx.begin(), idx.end(), 0); // sort indexes based on comparing values in _v std::sort(idx.begin(), idx.end(), [&_v](size_t i1, size_t i2) {return _v[i1] > _v[i2];}); return idx; } /// \brief Sort and keep track of indexes (largest first) /// /// This version is for sorting std::array<T, N> /// \param[in] _v The array to be indexed. /// \return An array of indexes in to the input array. template <typename T, std::size_t N> std::array<size_t, N> sort_indexes(const std::array<T, N>& _v) { // initialize original index locations std::array<size_t, N> idx; std::iota(idx.begin(), idx.end(), 0); // sort indexes based on comparing values in _v std::sort(idx.begin(), idx.end(), [&_v](size_t i1, size_t i2) {return _v[i1] > _v[i2];}); return idx; } } // namespace algorithm } // namespace asv #endif // _ASV_WAVE_SIM_GAZEBO_PLUGINS_ALGORITHM_HH_
32.554217
92
0.650259
minzlee
a8df7a4757ddd44f3fc42950a12d2712010c532f
630
cpp
C++
CCC/Stage1/96-Done/ccc96s5.cpp
zzh8829/CompetitiveProgramming
36f36b10269b4648ca8be0b08c2c49e96abede25
[ "MIT" ]
1
2017-10-01T00:51:39.000Z
2017-10-01T00:51:39.000Z
CCC/Stage1/96-Done/ccc96s5.cpp
zzh8829/CompetitiveProgramming
36f36b10269b4648ca8be0b08c2c49e96abede25
[ "MIT" ]
null
null
null
CCC/Stage1/96-Done/ccc96s5.cpp
zzh8829/CompetitiveProgramming
36f36b10269b4648ca8be0b08c2c49e96abede25
[ "MIT" ]
null
null
null
#include <iostream> #include <cstdio> using namespace std; int len,a[100001],b[100001]; int main() { int n; scanf("%d",&n); for(int cs=0;cs!=n;cs++) { int fo=0,ok=1; cin >> len; for(int i=0;i!=len;i++) scanf("%d",&a[i]); for(int i=0;i!=len;i++) { scanf("%d",&b[i]); if( !fo && b[i]>=a[i] && ok) { ok=0; fo=i; } } int max=0; for(int i=fo;i!=len;i++) { int j=i+max; while(j<len && b[j]>=a[i]) j++; j--; if(j>=len) continue; max=j-i>max?j-i:max; } printf("The maximum distance is %d\n", max); } system("pause"); return 0; }
16.153846
47
0.460317
zzh8829
a8e05fb9e6cce6191951628ed578fd922dc23416
4,043
cpp
C++
systems/plants/shapes/Geometry.cpp
peteflorence/drake
42bc694cd2371c73f79967a6a653be769935b33f
[ "BSD-3-Clause" ]
null
null
null
systems/plants/shapes/Geometry.cpp
peteflorence/drake
42bc694cd2371c73f79967a6a653be769935b33f
[ "BSD-3-Clause" ]
null
null
null
systems/plants/shapes/Geometry.cpp
peteflorence/drake
42bc694cd2371c73f79967a6a653be769935b33f
[ "BSD-3-Clause" ]
1
2021-09-29T19:37:28.000Z
2021-09-29T19:37:28.000Z
#include <fstream> #include "Geometry.h" #include "spruce.hh" using namespace std; using namespace Eigen; namespace DrakeShapes { Geometry::Geometry() : shape(UNKNOWN) {} Geometry::Geometry(const Geometry& other) { shape = other.getShape(); } Geometry::Geometry(Shape shape) : shape(shape) {}; const Shape Geometry::getShape() const { return shape; } Geometry* Geometry::clone() const { return new Geometry(*this); } Sphere::Sphere(double radius) : Geometry(SPHERE), radius(radius) {} Sphere* Sphere::clone() const { return new Sphere(*this); } Box::Box(const Eigen::Vector3d& size) : Geometry(BOX), size(size) {} Box* Box::clone() const { return new Box(*this); } Cylinder::Cylinder(double radius, double length) : Geometry( CYLINDER), radius(radius), length(length) {} Cylinder* Cylinder::clone() const { return new Cylinder(*this); } Capsule::Capsule(double radius, double length) : Geometry(CAPSULE), radius(radius), length(length) {} Capsule* Capsule::clone() const { return new Capsule(*this); } Mesh::Mesh(const string& filename) : Geometry(MESH), filename(filename) {} Mesh::Mesh(const string& filename, const string& resolved_filename) : Geometry(MESH), filename(filename), resolved_filename(resolved_filename) {} bool Mesh::extractMeshVertices(Matrix3Xd& vertex_coordinates) const { //DEBUG //cout << "Mesh::extractMeshVertices: resolved_filename = " << resolved_filename << endl; //END_DEBUG if (resolved_filename.empty()) { return false; } spruce::path spath(resolved_filename); string ext = spath.extension(); std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower); ifstream file; //DEBUG //cout << "Mesh::extractMeshVertices: do we have obj?" << endl; //END_DEBUG if (ext.compare(".obj")==0) { //cout << "Loading mesh from " << fname << " (scale = " << scale << ")" << endl; file.open(spath.getStr().c_str(),ifstream::in); } else { //DEBUG //cout << "Mesh::extractMeshVertices: check for obj file with same name" << endl; //END_DEBUG spath.setExtension(".obj"); if ( spath.exists() ) { // try changing the extension to obj and loading // cout << "Loading mesh from " << mypath.replace_extension(".obj").native() << endl; file.open(spath.getStr().c_str(),ifstream::in); } } if (!file.is_open()) { cerr << "Warning: Mesh " << spath.getStr() << " ignored because it does not have extension .obj (nor can I find a juxtaposed file with a .obj extension)" << endl; return false; } //DEBUG //cout << "Mesh::extractMeshVertices: Count num_vertices" << endl; //END_DEBUG string line; // Count the number of vertices and resize vertex_coordinates int num_vertices = 0; while (getline(file,line)) { istringstream iss(line); string type; if (iss >> type && type == "v") { ++num_vertices; } } //DEBUG //cout << "Mesh::extractMeshVertices: num_vertices = " << num_vertices << endl; //END_DEBUG vertex_coordinates.resize(3, num_vertices); file.clear(); file.seekg(0, file.beg); //DEBUG //cout << "Mesh::extractMeshVertices: Read vertices" << endl; //END_DEBUG double d; int j = 0; while (getline(file,line)) { istringstream iss(line); string type; if (iss >> type && type == "v") { //DEBUG //cout << "Mesh::extractMeshVertices: Vertex" << j << endl; //END_DEBUG int i = 0; while (iss >> d) { vertex_coordinates(i++, j) = d; } ++j; } } return true; } Mesh* Mesh::clone() const { return new Mesh(*this); } MeshPoints::MeshPoints(const Eigen::Matrix3Xd& points) : Geometry(MESH_POINTS), points(points) {} MeshPoints* MeshPoints::clone() const { return new MeshPoints(*this); } }
24.355422
168
0.602276
peteflorence
a8e111523c6465fb68467a1daa5dafa19c120812
2,127
cpp
C++
src/OptimizedBvh.cpp
AndresTraks/BulletSharp
c277666667f91c58191f4cfa97f117053de679ef
[ "MIT" ]
245
2015-01-02T14:11:26.000Z
2022-03-18T08:56:36.000Z
src/OptimizedBvh.cpp
AndresTraks/BulletSharp
c277666667f91c58191f4cfa97f117053de679ef
[ "MIT" ]
50
2015-01-04T22:32:21.000Z
2021-06-08T20:26:24.000Z
src/OptimizedBvh.cpp
AndresTraks/BulletSharp
c277666667f91c58191f4cfa97f117053de679ef
[ "MIT" ]
69
2015-04-03T15:38:44.000Z
2022-01-20T14:27:30.000Z
#include "StdAfx.h" #include "OptimizedBvh.h" #include "StridingMeshInterface.h" #define Native static_cast<btOptimizedBvh*>(_native) OptimizedBvh::OptimizedBvh(btOptimizedBvh* native, bool preventDelete) : QuantizedBvh(native, preventDelete) { } OptimizedBvh::OptimizedBvh() : QuantizedBvh(new btOptimizedBvh(), false) { } #ifndef DISABLE_BVH void OptimizedBvh::Build(StridingMeshInterface^ triangles, bool useQuantizedAabbCompression, Vector3 bvhAabbMin, Vector3 bvhAabbMax) { VECTOR3_CONV(bvhAabbMin); VECTOR3_CONV(bvhAabbMax); Native->build(triangles->_native, useQuantizedAabbCompression, VECTOR3_USE(bvhAabbMin), VECTOR3_USE(bvhAabbMax)); VECTOR3_DEL(bvhAabbMin); VECTOR3_DEL(bvhAabbMax); } OptimizedBvh^ OptimizedBvh::DeSerializeInPlace(IntPtr alignedDataBuffer, unsigned int dataBufferSize, bool swapEndian) { if (alignedDataBuffer == IntPtr::Zero) { return nullptr; } btOptimizedBvh* quantizedBvhPtr = btOptimizedBvh::deSerializeInPlace(alignedDataBuffer.ToPointer(), dataBufferSize, swapEndian); return gcnew OptimizedBvh(quantizedBvhPtr, true); } void OptimizedBvh::Refit(StridingMeshInterface^ triangles, Vector3 aabbMin, Vector3 aabbMax) { VECTOR3_CONV(aabbMin); VECTOR3_CONV(aabbMax); Native->refit(triangles->_native, VECTOR3_USE(aabbMin), VECTOR3_USE(aabbMax)); VECTOR3_DEL(aabbMin); VECTOR3_DEL(aabbMax); } void OptimizedBvh::RefitPartial(StridingMeshInterface^ triangles, Vector3 aabbMin, Vector3 aabbMax) { VECTOR3_CONV(aabbMin); VECTOR3_CONV(aabbMax); Native->refitPartial(triangles->_native, VECTOR3_USE(aabbMin), VECTOR3_USE(aabbMax)); VECTOR3_DEL(aabbMin); VECTOR3_DEL(aabbMax); } bool OptimizedBvh::SerializeInPlace(IntPtr alignedDataBuffer, unsigned int dataBufferSize, bool swapEndian) { return Native->serializeInPlace(alignedDataBuffer.ToPointer(), dataBufferSize, swapEndian); } void OptimizedBvh::UpdateBvhNodes(StridingMeshInterface^ meshInterface, int firstNode, int endNode, int index) { Native->updateBvhNodes(meshInterface->_native, firstNode, endNode, index); } #endif
28.36
117
0.77527
AndresTraks
a8e13198cf7b051b3c5e3db005b77c2552950850
14,284
ipp
C++
implement/oglplus/enums/ext/nv_path_metric_query_class.ipp
Extrunder/oglplus
c7c8266a1571d0b4c8b02d9c8ca6a7b6a6f51791
[ "BSL-1.0" ]
459
2016-03-16T04:11:37.000Z
2022-03-31T08:05:21.000Z
implement/oglplus/enums/ext/nv_path_metric_query_class.ipp
Extrunder/oglplus
c7c8266a1571d0b4c8b02d9c8ca6a7b6a6f51791
[ "BSL-1.0" ]
2
2016-08-08T18:26:27.000Z
2017-05-08T23:42:22.000Z
implement/oglplus/enums/ext/nv_path_metric_query_class.ipp
Extrunder/oglplus
c7c8266a1571d0b4c8b02d9c8ca6a7b6a6f51791
[ "BSL-1.0" ]
47
2016-05-31T15:55:52.000Z
2022-03-28T14:49:40.000Z
// File implement/oglplus/enums/ext/nv_path_metric_query_class.ipp // // Automatically generated file, DO NOT modify manually. // Edit the source 'source/enums/oglplus/ext/nv_path_metric_query.txt' // or the 'source/enums/make_enum.py' script instead. // // Copyright 2010-2015 Matus Chochlik. // 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 // namespace enums { template <typename Base, template<PathNVMetricQuery> class Transform> class EnumToClass<Base, PathNVMetricQuery, Transform> : public Base { private: Base& _base(void) { return *this; } public: #if defined GL_GLYPH_WIDTH_BIT_NV # if defined GlyphWidth # pragma push_macro("GlyphWidth") # undef GlyphWidth Transform<PathNVMetricQuery::GlyphWidth> GlyphWidth; # pragma pop_macro("GlyphWidth") # else Transform<PathNVMetricQuery::GlyphWidth> GlyphWidth; # endif #endif #if defined GL_GLYPH_HEIGHT_BIT_NV # if defined GlyphHeight # pragma push_macro("GlyphHeight") # undef GlyphHeight Transform<PathNVMetricQuery::GlyphHeight> GlyphHeight; # pragma pop_macro("GlyphHeight") # else Transform<PathNVMetricQuery::GlyphHeight> GlyphHeight; # endif #endif #if defined GL_GLYPH_HORIZONTAL_BEARING_X_BIT_NV # if defined GlyphHorizontalBearingX # pragma push_macro("GlyphHorizontalBearingX") # undef GlyphHorizontalBearingX Transform<PathNVMetricQuery::GlyphHorizontalBearingX> GlyphHorizontalBearingX; # pragma pop_macro("GlyphHorizontalBearingX") # else Transform<PathNVMetricQuery::GlyphHorizontalBearingX> GlyphHorizontalBearingX; # endif #endif #if defined GL_GLYPH_HORIZONTAL_BEARING_Y_BIT_NV # if defined GlyphHorizontalBearingY # pragma push_macro("GlyphHorizontalBearingY") # undef GlyphHorizontalBearingY Transform<PathNVMetricQuery::GlyphHorizontalBearingY> GlyphHorizontalBearingY; # pragma pop_macro("GlyphHorizontalBearingY") # else Transform<PathNVMetricQuery::GlyphHorizontalBearingY> GlyphHorizontalBearingY; # endif #endif #if defined GL_GLYPH_HORIZONTAL_BEARING_ADVANCE_BIT_NV # if defined GlyphHorizontalBearingAdvance # pragma push_macro("GlyphHorizontalBearingAdvance") # undef GlyphHorizontalBearingAdvance Transform<PathNVMetricQuery::GlyphHorizontalBearingAdvance> GlyphHorizontalBearingAdvance; # pragma pop_macro("GlyphHorizontalBearingAdvance") # else Transform<PathNVMetricQuery::GlyphHorizontalBearingAdvance> GlyphHorizontalBearingAdvance; # endif #endif #if defined GL_GLYPH_VERTICAL_BEARING_X_BIT_NV # if defined GlyphVerticalBearingX # pragma push_macro("GlyphVerticalBearingX") # undef GlyphVerticalBearingX Transform<PathNVMetricQuery::GlyphVerticalBearingX> GlyphVerticalBearingX; # pragma pop_macro("GlyphVerticalBearingX") # else Transform<PathNVMetricQuery::GlyphVerticalBearingX> GlyphVerticalBearingX; # endif #endif #if defined GL_GLYPH_VERTICAL_BEARING_Y_BIT_NV # if defined GlyphVerticalBearingY # pragma push_macro("GlyphVerticalBearingY") # undef GlyphVerticalBearingY Transform<PathNVMetricQuery::GlyphVerticalBearingY> GlyphVerticalBearingY; # pragma pop_macro("GlyphVerticalBearingY") # else Transform<PathNVMetricQuery::GlyphVerticalBearingY> GlyphVerticalBearingY; # endif #endif #if defined GL_GLYPH_VERTICAL_BEARING_ADVANCE_BIT_NV # if defined GlyphVerticalBearingAdvance # pragma push_macro("GlyphVerticalBearingAdvance") # undef GlyphVerticalBearingAdvance Transform<PathNVMetricQuery::GlyphVerticalBearingAdvance> GlyphVerticalBearingAdvance; # pragma pop_macro("GlyphVerticalBearingAdvance") # else Transform<PathNVMetricQuery::GlyphVerticalBearingAdvance> GlyphVerticalBearingAdvance; # endif #endif #if defined GL_GLYPH_HAS_KERNING_BIT_NV # if defined GlyphHasKerning # pragma push_macro("GlyphHasKerning") # undef GlyphHasKerning Transform<PathNVMetricQuery::GlyphHasKerning> GlyphHasKerning; # pragma pop_macro("GlyphHasKerning") # else Transform<PathNVMetricQuery::GlyphHasKerning> GlyphHasKerning; # endif #endif #if defined GL_FONT_X_MIN_BOUNDS_BIT_NV # if defined FontXMinBounds # pragma push_macro("FontXMinBounds") # undef FontXMinBounds Transform<PathNVMetricQuery::FontXMinBounds> FontXMinBounds; # pragma pop_macro("FontXMinBounds") # else Transform<PathNVMetricQuery::FontXMinBounds> FontXMinBounds; # endif #endif #if defined GL_FONT_Y_MIN_BOUNDS_BIT_NV # if defined FontYMinBounds # pragma push_macro("FontYMinBounds") # undef FontYMinBounds Transform<PathNVMetricQuery::FontYMinBounds> FontYMinBounds; # pragma pop_macro("FontYMinBounds") # else Transform<PathNVMetricQuery::FontYMinBounds> FontYMinBounds; # endif #endif #if defined GL_FONT_X_MAX_BOUNDS_BIT_NV # if defined FontXMaxBounds # pragma push_macro("FontXMaxBounds") # undef FontXMaxBounds Transform<PathNVMetricQuery::FontXMaxBounds> FontXMaxBounds; # pragma pop_macro("FontXMaxBounds") # else Transform<PathNVMetricQuery::FontXMaxBounds> FontXMaxBounds; # endif #endif #if defined GL_FONT_Y_MAX_BOUNDS_BIT_NV # if defined FontYMaxBounds # pragma push_macro("FontYMaxBounds") # undef FontYMaxBounds Transform<PathNVMetricQuery::FontYMaxBounds> FontYMaxBounds; # pragma pop_macro("FontYMaxBounds") # else Transform<PathNVMetricQuery::FontYMaxBounds> FontYMaxBounds; # endif #endif #if defined GL_FONT_UNITS_PER_EM_BIT_NV # if defined FontUnitsPerEm # pragma push_macro("FontUnitsPerEm") # undef FontUnitsPerEm Transform<PathNVMetricQuery::FontUnitsPerEm> FontUnitsPerEm; # pragma pop_macro("FontUnitsPerEm") # else Transform<PathNVMetricQuery::FontUnitsPerEm> FontUnitsPerEm; # endif #endif #if defined GL_FONT_ASCENDER_BIT_NV # if defined FontAscender # pragma push_macro("FontAscender") # undef FontAscender Transform<PathNVMetricQuery::FontAscender> FontAscender; # pragma pop_macro("FontAscender") # else Transform<PathNVMetricQuery::FontAscender> FontAscender; # endif #endif #if defined GL_FONT_DESCENDER_BIT_NV # if defined FontDescender # pragma push_macro("FontDescender") # undef FontDescender Transform<PathNVMetricQuery::FontDescender> FontDescender; # pragma pop_macro("FontDescender") # else Transform<PathNVMetricQuery::FontDescender> FontDescender; # endif #endif #if defined GL_FONT_HEIGHT_BIT_NV # if defined FontHeight # pragma push_macro("FontHeight") # undef FontHeight Transform<PathNVMetricQuery::FontHeight> FontHeight; # pragma pop_macro("FontHeight") # else Transform<PathNVMetricQuery::FontHeight> FontHeight; # endif #endif #if defined GL_FONT_MAX_ADVANCE_WIDTH_BIT_NV # if defined FontMaxAdvanceWidth # pragma push_macro("FontMaxAdvanceWidth") # undef FontMaxAdvanceWidth Transform<PathNVMetricQuery::FontMaxAdvanceWidth> FontMaxAdvanceWidth; # pragma pop_macro("FontMaxAdvanceWidth") # else Transform<PathNVMetricQuery::FontMaxAdvanceWidth> FontMaxAdvanceWidth; # endif #endif #if defined GL_FONT_MAX_ADVANCE_HEIGHT_BIT_NV # if defined FontMaxAdvanceHeight # pragma push_macro("FontMaxAdvanceHeight") # undef FontMaxAdvanceHeight Transform<PathNVMetricQuery::FontMaxAdvanceHeight> FontMaxAdvanceHeight; # pragma pop_macro("FontMaxAdvanceHeight") # else Transform<PathNVMetricQuery::FontMaxAdvanceHeight> FontMaxAdvanceHeight; # endif #endif #if defined GL_FONT_UNDERLINE_POSITION_BIT_NV # if defined FontUnderlinePosition # pragma push_macro("FontUnderlinePosition") # undef FontUnderlinePosition Transform<PathNVMetricQuery::FontUnderlinePosition> FontUnderlinePosition; # pragma pop_macro("FontUnderlinePosition") # else Transform<PathNVMetricQuery::FontUnderlinePosition> FontUnderlinePosition; # endif #endif #if defined GL_FONT_UNDERLINE_THICKNESS_BIT_NV # if defined FontUnderlineThickness # pragma push_macro("FontUnderlineThickness") # undef FontUnderlineThickness Transform<PathNVMetricQuery::FontUnderlineThickness> FontUnderlineThickness; # pragma pop_macro("FontUnderlineThickness") # else Transform<PathNVMetricQuery::FontUnderlineThickness> FontUnderlineThickness; # endif #endif #if defined GL_FONT_HAS_KERNING_BIT_NV # if defined FontHasKerning # pragma push_macro("FontHasKerning") # undef FontHasKerning Transform<PathNVMetricQuery::FontHasKerning> FontHasKerning; # pragma pop_macro("FontHasKerning") # else Transform<PathNVMetricQuery::FontHasKerning> FontHasKerning; # endif #endif EnumToClass(void) { } EnumToClass(Base&& base) : Base(std::move(base)) #if defined GL_GLYPH_WIDTH_BIT_NV # if defined GlyphWidth # pragma push_macro("GlyphWidth") # undef GlyphWidth , GlyphWidth(_base()) # pragma pop_macro("GlyphWidth") # else , GlyphWidth(_base()) # endif #endif #if defined GL_GLYPH_HEIGHT_BIT_NV # if defined GlyphHeight # pragma push_macro("GlyphHeight") # undef GlyphHeight , GlyphHeight(_base()) # pragma pop_macro("GlyphHeight") # else , GlyphHeight(_base()) # endif #endif #if defined GL_GLYPH_HORIZONTAL_BEARING_X_BIT_NV # if defined GlyphHorizontalBearingX # pragma push_macro("GlyphHorizontalBearingX") # undef GlyphHorizontalBearingX , GlyphHorizontalBearingX(_base()) # pragma pop_macro("GlyphHorizontalBearingX") # else , GlyphHorizontalBearingX(_base()) # endif #endif #if defined GL_GLYPH_HORIZONTAL_BEARING_Y_BIT_NV # if defined GlyphHorizontalBearingY # pragma push_macro("GlyphHorizontalBearingY") # undef GlyphHorizontalBearingY , GlyphHorizontalBearingY(_base()) # pragma pop_macro("GlyphHorizontalBearingY") # else , GlyphHorizontalBearingY(_base()) # endif #endif #if defined GL_GLYPH_HORIZONTAL_BEARING_ADVANCE_BIT_NV # if defined GlyphHorizontalBearingAdvance # pragma push_macro("GlyphHorizontalBearingAdvance") # undef GlyphHorizontalBearingAdvance , GlyphHorizontalBearingAdvance(_base()) # pragma pop_macro("GlyphHorizontalBearingAdvance") # else , GlyphHorizontalBearingAdvance(_base()) # endif #endif #if defined GL_GLYPH_VERTICAL_BEARING_X_BIT_NV # if defined GlyphVerticalBearingX # pragma push_macro("GlyphVerticalBearingX") # undef GlyphVerticalBearingX , GlyphVerticalBearingX(_base()) # pragma pop_macro("GlyphVerticalBearingX") # else , GlyphVerticalBearingX(_base()) # endif #endif #if defined GL_GLYPH_VERTICAL_BEARING_Y_BIT_NV # if defined GlyphVerticalBearingY # pragma push_macro("GlyphVerticalBearingY") # undef GlyphVerticalBearingY , GlyphVerticalBearingY(_base()) # pragma pop_macro("GlyphVerticalBearingY") # else , GlyphVerticalBearingY(_base()) # endif #endif #if defined GL_GLYPH_VERTICAL_BEARING_ADVANCE_BIT_NV # if defined GlyphVerticalBearingAdvance # pragma push_macro("GlyphVerticalBearingAdvance") # undef GlyphVerticalBearingAdvance , GlyphVerticalBearingAdvance(_base()) # pragma pop_macro("GlyphVerticalBearingAdvance") # else , GlyphVerticalBearingAdvance(_base()) # endif #endif #if defined GL_GLYPH_HAS_KERNING_BIT_NV # if defined GlyphHasKerning # pragma push_macro("GlyphHasKerning") # undef GlyphHasKerning , GlyphHasKerning(_base()) # pragma pop_macro("GlyphHasKerning") # else , GlyphHasKerning(_base()) # endif #endif #if defined GL_FONT_X_MIN_BOUNDS_BIT_NV # if defined FontXMinBounds # pragma push_macro("FontXMinBounds") # undef FontXMinBounds , FontXMinBounds(_base()) # pragma pop_macro("FontXMinBounds") # else , FontXMinBounds(_base()) # endif #endif #if defined GL_FONT_Y_MIN_BOUNDS_BIT_NV # if defined FontYMinBounds # pragma push_macro("FontYMinBounds") # undef FontYMinBounds , FontYMinBounds(_base()) # pragma pop_macro("FontYMinBounds") # else , FontYMinBounds(_base()) # endif #endif #if defined GL_FONT_X_MAX_BOUNDS_BIT_NV # if defined FontXMaxBounds # pragma push_macro("FontXMaxBounds") # undef FontXMaxBounds , FontXMaxBounds(_base()) # pragma pop_macro("FontXMaxBounds") # else , FontXMaxBounds(_base()) # endif #endif #if defined GL_FONT_Y_MAX_BOUNDS_BIT_NV # if defined FontYMaxBounds # pragma push_macro("FontYMaxBounds") # undef FontYMaxBounds , FontYMaxBounds(_base()) # pragma pop_macro("FontYMaxBounds") # else , FontYMaxBounds(_base()) # endif #endif #if defined GL_FONT_UNITS_PER_EM_BIT_NV # if defined FontUnitsPerEm # pragma push_macro("FontUnitsPerEm") # undef FontUnitsPerEm , FontUnitsPerEm(_base()) # pragma pop_macro("FontUnitsPerEm") # else , FontUnitsPerEm(_base()) # endif #endif #if defined GL_FONT_ASCENDER_BIT_NV # if defined FontAscender # pragma push_macro("FontAscender") # undef FontAscender , FontAscender(_base()) # pragma pop_macro("FontAscender") # else , FontAscender(_base()) # endif #endif #if defined GL_FONT_DESCENDER_BIT_NV # if defined FontDescender # pragma push_macro("FontDescender") # undef FontDescender , FontDescender(_base()) # pragma pop_macro("FontDescender") # else , FontDescender(_base()) # endif #endif #if defined GL_FONT_HEIGHT_BIT_NV # if defined FontHeight # pragma push_macro("FontHeight") # undef FontHeight , FontHeight(_base()) # pragma pop_macro("FontHeight") # else , FontHeight(_base()) # endif #endif #if defined GL_FONT_MAX_ADVANCE_WIDTH_BIT_NV # if defined FontMaxAdvanceWidth # pragma push_macro("FontMaxAdvanceWidth") # undef FontMaxAdvanceWidth , FontMaxAdvanceWidth(_base()) # pragma pop_macro("FontMaxAdvanceWidth") # else , FontMaxAdvanceWidth(_base()) # endif #endif #if defined GL_FONT_MAX_ADVANCE_HEIGHT_BIT_NV # if defined FontMaxAdvanceHeight # pragma push_macro("FontMaxAdvanceHeight") # undef FontMaxAdvanceHeight , FontMaxAdvanceHeight(_base()) # pragma pop_macro("FontMaxAdvanceHeight") # else , FontMaxAdvanceHeight(_base()) # endif #endif #if defined GL_FONT_UNDERLINE_POSITION_BIT_NV # if defined FontUnderlinePosition # pragma push_macro("FontUnderlinePosition") # undef FontUnderlinePosition , FontUnderlinePosition(_base()) # pragma pop_macro("FontUnderlinePosition") # else , FontUnderlinePosition(_base()) # endif #endif #if defined GL_FONT_UNDERLINE_THICKNESS_BIT_NV # if defined FontUnderlineThickness # pragma push_macro("FontUnderlineThickness") # undef FontUnderlineThickness , FontUnderlineThickness(_base()) # pragma pop_macro("FontUnderlineThickness") # else , FontUnderlineThickness(_base()) # endif #endif #if defined GL_FONT_HAS_KERNING_BIT_NV # if defined FontHasKerning # pragma push_macro("FontHasKerning") # undef FontHasKerning , FontHasKerning(_base()) # pragma pop_macro("FontHasKerning") # else , FontHasKerning(_base()) # endif #endif { } }; } // namespace enums
30.391489
91
0.810067
Extrunder
a8e1b70c01acc3aea8a195d5fd755ddd493f8e7b
33,182
cpp
C++
benchmark/create_complex/fruit.cpp
dan-42/di
3253bfd841d03d75f7b70c05ac3789b605337deb
[ "BSL-1.0" ]
null
null
null
benchmark/create_complex/fruit.cpp
dan-42/di
3253bfd841d03d75f7b70c05ac3789b605337deb
[ "BSL-1.0" ]
null
null
null
benchmark/create_complex/fruit.cpp
dan-42/di
3253bfd841d03d75f7b70c05ac3789b605337deb
[ "BSL-1.0" ]
null
null
null
// // Copyright (c) 2012-2019 Kris Jusiak (kris at jusiak dot net) // // 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) // #include <memory> #include <fruit/fruit.h> // clang-format off struct X00 { INJECT(X00()) { } }; struct X01 { INJECT(X01(X00)) { } }; struct X02 { INJECT(X02(X00, X01)) { } }; struct X03 { INJECT(X03(X00, X01, X02)) { } }; struct X04 { INJECT(X04(X00, X01, X02, X03)) { } }; struct X05 { INJECT(X05(X00, X01, X02, X03, X04)) { } }; struct X06 { INJECT(X06(X00, X01, X02, X03, X04, X05)) { } }; struct X07 { INJECT(X07(X00, X01, X02, X03, X04, X05, X06)) { } }; struct X08 { INJECT(X08(X00, X01, X02, X03, X04, X05, X06, X07)) { } }; struct X09 { INJECT(X09(X00, X01, X02, X03, X04, X05, X06, X07, X08)) { } }; struct X10 { INJECT(X10(X00, X01, X02, X03, X04, X05, X06, X07, X08, X09)) { } }; struct X11 { INJECT(X11(X01, X02, X03, X04, X05, X06, X07, X08, X09, X10)) { } }; struct X12 { INJECT(X12(X02, X03, X04, X05, X06, X07, X08, X09, X10, X11)) { } }; struct X13 { INJECT(X13(X03, X04, X05, X06, X07, X08, X09, X10, X11, X12)) { } }; struct X14 { INJECT(X14(X04, X05, X06, X07, X08, X09, X10, X11, X12, X13)) { } }; struct X15 { INJECT(X15(X05, X06, X07, X08, X09, X10, X11, X12, X13, X14)) { } }; struct X16 { INJECT(X16(X06, X07, X08, X09, X10, X11, X12, X13, X14, X15)) { } }; struct X17 { INJECT(X17(X07, X08, X09, X10, X11, X12, X13, X14, X15, X16)) { } }; struct X18 { INJECT(X18(X08, X09, X10, X11, X12, X13, X14, X15, X16, X17)) { } }; struct X19 { INJECT(X19(X09, X10, X11, X12, X13, X14, X15, X16, X17, X18)) { } }; struct X20 { INJECT(X20(X10, X11, X12, X13, X14, X15, X16, X17, X18, X19)) { } }; struct X21 { INJECT(X21(X11, X12, X13, X14, X15, X16, X17, X18, X19, X20)) { } }; struct X22 { INJECT(X22(X12, X13, X14, X15, X16, X17, X18, X19, X20, X21)) { } }; struct X23 { INJECT(X23(X13, X14, X15, X16, X17, X18, X19, X20, X21, X22)) { } }; struct X24 { INJECT(X24(X14, X15, X16, X17, X18, X19, X20, X21, X22, X23)) { } }; struct X25 { INJECT(X25(X15, X16, X17, X18, X19, X20, X21, X22, X23, X24)) { } }; struct X26 { INJECT(X26(X16, X17, X18, X19, X20, X21, X22, X23, X24, X25)) { } }; struct X27 { INJECT(X27(X17, X18, X19, X20, X21, X22, X23, X24, X25, X26)) { } }; struct X28 { INJECT(X28(X18, X19, X20, X21, X22, X23, X24, X25, X26, X27)) { } }; struct X29 { INJECT(X29(X19, X20, X21, X22, X23, X24, X25, X26, X27, X28)) { } }; struct X30 { INJECT(X30(X20, X21, X22, X23, X24, X25, X26, X27, X28, X29)) { } }; struct X31 { INJECT(X31(X21, X22, X23, X24, X25, X26, X27, X28, X29, X30)) { } }; struct X32 { INJECT(X32(X22, X23, X24, X25, X26, X27, X28, X29, X30, X31)) { } }; struct X33 { INJECT(X33(X23, X24, X25, X26, X27, X28, X29, X30, X31, X32)) { } }; struct X34 { INJECT(X34(X24, X25, X26, X27, X28, X29, X30, X31, X32, X33)) { } }; struct X35 { INJECT(X35(X25, X26, X27, X28, X29, X30, X31, X32, X33, X34)) { } }; struct X36 { INJECT(X36(X26, X27, X28, X29, X30, X31, X32, X33, X34, X35)) { } }; struct X37 { INJECT(X37(X27, X28, X29, X30, X31, X32, X33, X34, X35, X36)) { } }; struct X38 { INJECT(X38(X28, X29, X30, X31, X32, X33, X34, X35, X36, X37)) { } }; struct X39 { INJECT(X39(X29, X30, X31, X32, X33, X34, X35, X36, X37, X38)) { } }; struct X40 { INJECT(X40(X30, X31, X32, X33, X34, X35, X36, X37, X38, X39)) { } }; struct X41 { INJECT(X41(X31, X32, X33, X34, X35, X36, X37, X38, X39, X40)) { } }; struct X42 { INJECT(X42(X32, X33, X34, X35, X36, X37, X38, X39, X40, X41)) { } }; struct X43 { INJECT(X43(X33, X34, X35, X36, X37, X38, X39, X40, X41, X42)) { } }; struct X44 { INJECT(X44(X34, X35, X36, X37, X38, X39, X40, X41, X42, X43)) { } }; struct X45 { INJECT(X45(X35, X36, X37, X38, X39, X40, X41, X42, X43, X44)) { } }; struct X46 { INJECT(X46(X36, X37, X38, X39, X40, X41, X42, X43, X44, X45)) { } }; struct X47 { INJECT(X47(X37, X38, X39, X40, X41, X42, X43, X44, X45, X46)) { } }; struct X48 { INJECT(X48(X38, X39, X40, X41, X42, X43, X44, X45, X46, X47)) { } }; struct X49 { INJECT(X49(X39, X40, X41, X42, X43, X44, X45, X46, X47, X48)) { } }; struct X50 { INJECT(X50(X40, X41, X42, X43, X44, X45, X46, X47, X48, X49)) { } }; struct X51 { INJECT(X51(X41, X42, X43, X44, X45, X46, X47, X48, X49, X50)) { } }; struct X52 { INJECT(X52(X42, X43, X44, X45, X46, X47, X48, X49, X50, X51)) { } }; struct X53 { INJECT(X53(X43, X44, X45, X46, X47, X48, X49, X50, X51, X52)) { } }; struct X54 { INJECT(X54(X44, X45, X46, X47, X48, X49, X50, X51, X52, X53)) { } }; struct X55 { INJECT(X55(X45, X46, X47, X48, X49, X50, X51, X52, X53, X54)) { } }; struct X56 { INJECT(X56(X46, X47, X48, X49, X50, X51, X52, X53, X54, X55)) { } }; struct X57 { INJECT(X57(X47, X48, X49, X50, X51, X52, X53, X54, X55, X56)) { } }; struct X58 { INJECT(X58(X48, X49, X50, X51, X52, X53, X54, X55, X56, X57)) { } }; struct X59 { INJECT(X59(X49, X50, X51, X52, X53, X54, X55, X56, X57, X58)) { } }; struct X60 { INJECT(X60(X50, X51, X52, X53, X54, X55, X56, X57, X58, X59)) { } }; struct X61 { INJECT(X61(X51, X52, X53, X54, X55, X56, X57, X58, X59, X60)) { } }; struct X62 { INJECT(X62(X52, X53, X54, X55, X56, X57, X58, X59, X60, X61)) { } }; struct X63 { INJECT(X63(X53, X54, X55, X56, X57, X58, X59, X60, X61, X62)) { } }; struct X64 { INJECT(X64(X54, X55, X56, X57, X58, X59, X60, X61, X62, X63)) { } }; struct X65 { INJECT(X65(X55, X56, X57, X58, X59, X60, X61, X62, X63, X64)) { } }; struct X66 { INJECT(X66(X56, X57, X58, X59, X60, X61, X62, X63, X64, X65)) { } }; struct X67 { INJECT(X67(X57, X58, X59, X60, X61, X62, X63, X64, X65, X66)) { } }; struct X68 { INJECT(X68(X58, X59, X60, X61, X62, X63, X64, X65, X66, X67)) { } }; struct X69 { INJECT(X69(X59, X60, X61, X62, X63, X64, X65, X66, X67, X68)) { } }; struct X70 { INJECT(X70(X60, X61, X62, X63, X64, X65, X66, X67, X68, X69)) { } }; struct X71 { INJECT(X71(X61, X62, X63, X64, X65, X66, X67, X68, X69, X70)) { } }; struct X72 { INJECT(X72(X62, X63, X64, X65, X66, X67, X68, X69, X70, X71)) { } }; struct X73 { INJECT(X73(X63, X64, X65, X66, X67, X68, X69, X70, X71, X72)) { } }; struct X74 { INJECT(X74(X64, X65, X66, X67, X68, X69, X70, X71, X72, X73)) { } }; struct X75 { INJECT(X75(X65, X66, X67, X68, X69, X70, X71, X72, X73, X74)) { } }; struct X76 { INJECT(X76(X66, X67, X68, X69, X70, X71, X72, X73, X74, X75)) { } }; struct X77 { INJECT(X77(X67, X68, X69, X70, X71, X72, X73, X74, X75, X76)) { } }; struct X78 { INJECT(X78(X68, X69, X70, X71, X72, X73, X74, X75, X76, X77)) { } }; struct X79 { INJECT(X79(X69, X70, X71, X72, X73, X74, X75, X76, X77, X78)) { } }; struct X80 { INJECT(X80(X70, X71, X72, X73, X74, X75, X76, X77, X78, X79)) { } }; struct X81 { INJECT(X81(X71, X72, X73, X74, X75, X76, X77, X78, X79, X80)) { } }; struct X82 { INJECT(X82(X72, X73, X74, X75, X76, X77, X78, X79, X80, X81)) { } }; struct X83 { INJECT(X83(X73, X74, X75, X76, X77, X78, X79, X80, X81, X82)) { } }; struct X84 { INJECT(X84(X74, X75, X76, X77, X78, X79, X80, X81, X82, X83)) { } }; struct X85 { INJECT(X85(X75, X76, X77, X78, X79, X80, X81, X82, X83, X84)) { } }; struct X86 { INJECT(X86(X76, X77, X78, X79, X80, X81, X82, X83, X84, X85)) { } }; struct X87 { INJECT(X87(X77, X78, X79, X80, X81, X82, X83, X84, X85, X86)) { } }; struct X88 { INJECT(X88(X78, X79, X80, X81, X82, X83, X84, X85, X86, X87)) { } }; struct X89 { INJECT(X89(X79, X80, X81, X82, X83, X84, X85, X86, X87, X88)) { } }; struct X90 { INJECT(X90(X80, X81, X82, X83, X84, X85, X86, X87, X88, X89)) { } }; struct X91 { INJECT(X91(X81, X82, X83, X84, X85, X86, X87, X88, X89, X90)) { } }; struct X92 { INJECT(X92(X82, X83, X84, X85, X86, X87, X88, X89, X90, X91)) { } }; struct X93 { INJECT(X93(X83, X84, X85, X86, X87, X88, X89, X90, X91, X92)) { } }; struct X94 { INJECT(X94(X84, X85, X86, X87, X88, X89, X90, X91, X92, X93)) { } }; struct X95 { INJECT(X95(X85, X86, X87, X88, X89, X90, X91, X92, X93, X94)) { } }; struct X96 { INJECT(X96(X86, X87, X88, X89, X90, X91, X92, X93, X94, X95)) { } }; struct X97 { INJECT(X97(X87, X88, X89, X90, X91, X92, X93, X94, X95, X96)) { } }; struct X98 { INJECT(X98(X88, X89, X90, X91, X92, X93, X94, X95, X96, X97)) { } }; struct X99 { INJECT(X99(X89, X90, X91, X92, X93, X94, X95, X96, X97, X98)) { } }; struct I00 { virtual ~I00() noexcept = default; virtual void dummy() = 0; }; struct Impl00 : I00 { INJECT(Impl00(X00, X01, X02, X03, X04, X05, X06, X07, X08, X09)) { } void dummy() override { } }; struct I01 { virtual ~I01() noexcept = default; virtual void dummy() = 0; }; struct Impl01 : I01 { INJECT(Impl01(X01, X02, X03, X04, X05, X06, X07, X08, X09, X10)) { } void dummy() override { } }; struct I02 { virtual ~I02() noexcept = default; virtual void dummy() = 0; }; struct Impl02 : I02 { INJECT(Impl02(X02, X03, X04, X05, X06, X07, X08, X09, X10, X11)) { } void dummy() override { } }; struct I03 { virtual ~I03() noexcept = default; virtual void dummy() = 0; }; struct Impl03 : I03 { INJECT(Impl03(X03, X04, X05, X06, X07, X08, X09, X10, X11, X12)) { } void dummy() override { } }; struct I04 { virtual ~I04() noexcept = default; virtual void dummy() = 0; }; struct Impl04 : I04 { INJECT(Impl04(X04, X05, X06, X07, X08, X09, X10, X11, X12, X13)) { } void dummy() override { } }; struct I05 { virtual ~I05() noexcept = default; virtual void dummy() = 0; }; struct Impl05 : I05 { INJECT(Impl05(X05, X06, X07, X08, X09, X10, X11, X12, X13, X14)) { } void dummy() override { } }; struct I06 { virtual ~I06() noexcept = default; virtual void dummy() = 0; }; struct Impl06 : I06 { INJECT(Impl06(X06, X07, X08, X09, X10, X11, X12, X13, X14, X15)) { } void dummy() override { } }; struct I07 { virtual ~I07() noexcept = default; virtual void dummy() = 0; }; struct Impl07 : I07 { INJECT(Impl07(X07, X08, X09, X10, X11, X12, X13, X14, X15, X16)) { } void dummy() override { } }; struct I08 { virtual ~I08() noexcept = default; virtual void dummy() = 0; }; struct Impl08 : I08 { INJECT(Impl08(X08, X09, X10, X11, X12, X13, X14, X15, X16, X17)) { } void dummy() override { } }; struct I09 { virtual ~I09() noexcept = default; virtual void dummy() = 0; }; struct Impl09 : I09 { INJECT(Impl09(X09, X10, X11, X12, X13, X14, X15, X16, X17, X18)) { } void dummy() override { } }; struct I10 { virtual ~I10() noexcept = default; virtual void dummy() = 0; }; struct Impl10 : I10 { INJECT(Impl10(X10, X11, X12, X13, X14, X15, X16, X17, X18, X19)) { } void dummy() override { } }; struct I11 { virtual ~I11() noexcept = default; virtual void dummy() = 0; }; struct Impl11 : I11 { INJECT(Impl11(X11, X12, X13, X14, X15, X16, X17, X18, X19, X20)) { } void dummy() override { } }; struct I12 { virtual ~I12() noexcept = default; virtual void dummy() = 0; }; struct Impl12 : I12 { INJECT(Impl12(X12, X13, X14, X15, X16, X17, X18, X19, X20, X21)) { } void dummy() override { } }; struct I13 { virtual ~I13() noexcept = default; virtual void dummy() = 0; }; struct Impl13 : I13 { INJECT(Impl13(X13, X14, X15, X16, X17, X18, X19, X20, X21, X22)) { } void dummy() override { } }; struct I14 { virtual ~I14() noexcept = default; virtual void dummy() = 0; }; struct Impl14 : I14 { INJECT(Impl14(X14, X15, X16, X17, X18, X19, X20, X21, X22, X23)) { } void dummy() override { } }; struct I15 { virtual ~I15() noexcept = default; virtual void dummy() = 0; }; struct Impl15 : I15 { INJECT(Impl15(X15, X16, X17, X18, X19, X20, X21, X22, X23, X24)) { } void dummy() override { } }; struct I16 { virtual ~I16() noexcept = default; virtual void dummy() = 0; }; struct Impl16 : I16 { INJECT(Impl16(X16, X17, X18, X19, X20, X21, X22, X23, X24, X25)) { } void dummy() override { } }; struct I17 { virtual ~I17() noexcept = default; virtual void dummy() = 0; }; struct Impl17 : I17 { INJECT(Impl17(X17, X18, X19, X20, X21, X22, X23, X24, X25, X26)) { } void dummy() override { } }; struct I18 { virtual ~I18() noexcept = default; virtual void dummy() = 0; }; struct Impl18 : I18 { INJECT(Impl18(X18, X19, X20, X21, X22, X23, X24, X25, X26, X27)) { } void dummy() override { } }; struct I19 { virtual ~I19() noexcept = default; virtual void dummy() = 0; }; struct Impl19 : I19 { INJECT(Impl19(X19, X20, X21, X22, X23, X24, X25, X26, X27, X28)) { } void dummy() override { } }; struct I20 { virtual ~I20() noexcept = default; virtual void dummy() = 0; }; struct Impl20 : I20 { INJECT(Impl20(X20, X21, X22, X23, X24, X25, X26, X27, X28, X29)) { } void dummy() override { } }; struct I21 { virtual ~I21() noexcept = default; virtual void dummy() = 0; }; struct Impl21 : I21 { INJECT(Impl21(X21, X22, X23, X24, X25, X26, X27, X28, X29, X30)) { } void dummy() override { } }; struct I22 { virtual ~I22() noexcept = default; virtual void dummy() = 0; }; struct Impl22 : I22 { INJECT(Impl22(X22, X23, X24, X25, X26, X27, X28, X29, X30, X31)) { } void dummy() override { } }; struct I23 { virtual ~I23() noexcept = default; virtual void dummy() = 0; }; struct Impl23 : I23 { INJECT(Impl23(X23, X24, X25, X26, X27, X28, X29, X30, X31, X32)) { } void dummy() override { } }; struct I24 { virtual ~I24() noexcept = default; virtual void dummy() = 0; }; struct Impl24 : I24 { INJECT(Impl24(X24, X25, X26, X27, X28, X29, X30, X31, X32, X33)) { } void dummy() override { } }; struct I25 { virtual ~I25() noexcept = default; virtual void dummy() = 0; }; struct Impl25 : I25 { INJECT(Impl25(X25, X26, X27, X28, X29, X30, X31, X32, X33, X34)) { } void dummy() override { } }; struct I26 { virtual ~I26() noexcept = default; virtual void dummy() = 0; }; struct Impl26 : I26 { INJECT(Impl26(X26, X27, X28, X29, X30, X31, X32, X33, X34, X35)) { } void dummy() override { } }; struct I27 { virtual ~I27() noexcept = default; virtual void dummy() = 0; }; struct Impl27 : I27 { INJECT(Impl27(X27, X28, X29, X30, X31, X32, X33, X34, X35, X36)) { } void dummy() override { } }; struct I28 { virtual ~I28() noexcept = default; virtual void dummy() = 0; }; struct Impl28 : I28 { INJECT(Impl28(X28, X29, X30, X31, X32, X33, X34, X35, X36, X37)) { } void dummy() override { } }; struct I29 { virtual ~I29() noexcept = default; virtual void dummy() = 0; }; struct Impl29 : I29 { INJECT(Impl29(X29, X30, X31, X32, X33, X34, X35, X36, X37, X38)) { } void dummy() override { } }; struct I30 { virtual ~I30() noexcept = default; virtual void dummy() = 0; }; struct Impl30 : I30 { INJECT(Impl30(X30, X31, X32, X33, X34, X35, X36, X37, X38, X39)) { } void dummy() override { } }; struct I31 { virtual ~I31() noexcept = default; virtual void dummy() = 0; }; struct Impl31 : I31 { INJECT(Impl31(X31, X32, X33, X34, X35, X36, X37, X38, X39, X40)) { } void dummy() override { } }; struct I32 { virtual ~I32() noexcept = default; virtual void dummy() = 0; }; struct Impl32 : I32 { INJECT(Impl32(X32, X33, X34, X35, X36, X37, X38, X39, X40, X41)) { } void dummy() override { } }; struct I33 { virtual ~I33() noexcept = default; virtual void dummy() = 0; }; struct Impl33 : I33 { INJECT(Impl33(X33, X34, X35, X36, X37, X38, X39, X40, X41, X42)) { } void dummy() override { } }; struct I34 { virtual ~I34() noexcept = default; virtual void dummy() = 0; }; struct Impl34 : I34 { INJECT(Impl34(X34, X35, X36, X37, X38, X39, X40, X41, X42, X43)) { } void dummy() override { } }; struct I35 { virtual ~I35() noexcept = default; virtual void dummy() = 0; }; struct Impl35 : I35 { INJECT(Impl35(X35, X36, X37, X38, X39, X40, X41, X42, X43, X44)) { } void dummy() override { } }; struct I36 { virtual ~I36() noexcept = default; virtual void dummy() = 0; }; struct Impl36 : I36 { INJECT(Impl36(X36, X37, X38, X39, X40, X41, X42, X43, X44, X45)) { } void dummy() override { } }; struct I37 { virtual ~I37() noexcept = default; virtual void dummy() = 0; }; struct Impl37 : I37 { INJECT(Impl37(X37, X38, X39, X40, X41, X42, X43, X44, X45, X46)) { } void dummy() override { } }; struct I38 { virtual ~I38() noexcept = default; virtual void dummy() = 0; }; struct Impl38 : I38 { INJECT(Impl38(X38, X39, X40, X41, X42, X43, X44, X45, X46, X47)) { } void dummy() override { } }; struct I39 { virtual ~I39() noexcept = default; virtual void dummy() = 0; }; struct Impl39 : I39 { INJECT(Impl39(X39, X40, X41, X42, X43, X44, X45, X46, X47, X48)) { } void dummy() override { } }; struct I40 { virtual ~I40() noexcept = default; virtual void dummy() = 0; }; struct Impl40 : I40 { INJECT(Impl40(X40, X41, X42, X43, X44, X45, X46, X47, X48, X49)) { } void dummy() override { } }; struct I41 { virtual ~I41() noexcept = default; virtual void dummy() = 0; }; struct Impl41 : I41 { INJECT(Impl41(X41, X42, X43, X44, X45, X46, X47, X48, X49, X50)) { } void dummy() override { } }; struct I42 { virtual ~I42() noexcept = default; virtual void dummy() = 0; }; struct Impl42 : I42 { INJECT(Impl42(X42, X43, X44, X45, X46, X47, X48, X49, X50, X51)) { } void dummy() override { } }; struct I43 { virtual ~I43() noexcept = default; virtual void dummy() = 0; }; struct Impl43 : I43 { INJECT(Impl43(X43, X44, X45, X46, X47, X48, X49, X50, X51, X52)) { } void dummy() override { } }; struct I44 { virtual ~I44() noexcept = default; virtual void dummy() = 0; }; struct Impl44 : I44 { INJECT(Impl44(X44, X45, X46, X47, X48, X49, X50, X51, X52, X53)) { } void dummy() override { } }; struct I45 { virtual ~I45() noexcept = default; virtual void dummy() = 0; }; struct Impl45 : I45 { INJECT(Impl45(X45, X46, X47, X48, X49, X50, X51, X52, X53, X54)) { } void dummy() override { } }; struct I46 { virtual ~I46() noexcept = default; virtual void dummy() = 0; }; struct Impl46 : I46 { INJECT(Impl46(X46, X47, X48, X49, X50, X51, X52, X53, X54, X55)) { } void dummy() override { } }; struct I47 { virtual ~I47() noexcept = default; virtual void dummy() = 0; }; struct Impl47 : I47 { INJECT(Impl47(X47, X48, X49, X50, X51, X52, X53, X54, X55, X56)) { } void dummy() override { } }; struct I48 { virtual ~I48() noexcept = default; virtual void dummy() = 0; }; struct Impl48 : I48 { INJECT(Impl48(X48, X49, X50, X51, X52, X53, X54, X55, X56, X57)) { } void dummy() override { } }; struct I49 { virtual ~I49() noexcept = default; virtual void dummy() = 0; }; struct Impl49 : I49 { INJECT(Impl49(X49, X50, X51, X52, X53, X54, X55, X56, X57, X58)) { } void dummy() override { } }; struct I50 { virtual ~I50() noexcept = default; virtual void dummy() = 0; }; struct Impl50 : I50 { INJECT(Impl50(X50, X51, X52, X53, X54, X55, X56, X57, X58, X59)) { } void dummy() override { } }; struct I51 { virtual ~I51() noexcept = default; virtual void dummy() = 0; }; struct Impl51 : I51 { INJECT(Impl51(X51, X52, X53, X54, X55, X56, X57, X58, X59, X60)) { } void dummy() override { } }; struct I52 { virtual ~I52() noexcept = default; virtual void dummy() = 0; }; struct Impl52 : I52 { INJECT(Impl52(X52, X53, X54, X55, X56, X57, X58, X59, X60, X61)) { } void dummy() override { } }; struct I53 { virtual ~I53() noexcept = default; virtual void dummy() = 0; }; struct Impl53 : I53 { INJECT(Impl53(X53, X54, X55, X56, X57, X58, X59, X60, X61, X62)) { } void dummy() override { } }; struct I54 { virtual ~I54() noexcept = default; virtual void dummy() = 0; }; struct Impl54 : I54 { INJECT(Impl54(X54, X55, X56, X57, X58, X59, X60, X61, X62, X63)) { } void dummy() override { } }; struct I55 { virtual ~I55() noexcept = default; virtual void dummy() = 0; }; struct Impl55 : I55 { INJECT(Impl55(X55, X56, X57, X58, X59, X60, X61, X62, X63, X64)) { } void dummy() override { } }; struct I56 { virtual ~I56() noexcept = default; virtual void dummy() = 0; }; struct Impl56 : I56 { INJECT(Impl56(X56, X57, X58, X59, X60, X61, X62, X63, X64, X65)) { } void dummy() override { } }; struct I57 { virtual ~I57() noexcept = default; virtual void dummy() = 0; }; struct Impl57 : I57 { INJECT(Impl57(X57, X58, X59, X60, X61, X62, X63, X64, X65, X66)) { } void dummy() override { } }; struct I58 { virtual ~I58() noexcept = default; virtual void dummy() = 0; }; struct Impl58 : I58 { INJECT(Impl58(X58, X59, X60, X61, X62, X63, X64, X65, X66, X67)) { } void dummy() override { } }; struct I59 { virtual ~I59() noexcept = default; virtual void dummy() = 0; }; struct Impl59 : I59 { INJECT(Impl59(X59, X60, X61, X62, X63, X64, X65, X66, X67, X68)) { } void dummy() override { } }; struct I60 { virtual ~I60() noexcept = default; virtual void dummy() = 0; }; struct Impl60 : I60 { INJECT(Impl60(X60, X61, X62, X63, X64, X65, X66, X67, X68, X69)) { } void dummy() override { } }; struct I61 { virtual ~I61() noexcept = default; virtual void dummy() = 0; }; struct Impl61 : I61 { INJECT(Impl61(X61, X62, X63, X64, X65, X66, X67, X68, X69, X70)) { } void dummy() override { } }; struct I62 { virtual ~I62() noexcept = default; virtual void dummy() = 0; }; struct Impl62 : I62 { INJECT(Impl62(X62, X63, X64, X65, X66, X67, X68, X69, X70, X71)) { } void dummy() override { } }; struct I63 { virtual ~I63() noexcept = default; virtual void dummy() = 0; }; struct Impl63 : I63 { INJECT(Impl63(X63, X64, X65, X66, X67, X68, X69, X70, X71, X72)) { } void dummy() override { } }; struct I64 { virtual ~I64() noexcept = default; virtual void dummy() = 0; }; struct Impl64 : I64 { INJECT(Impl64(X64, X65, X66, X67, X68, X69, X70, X71, X72, X73)) { } void dummy() override { } }; struct I65 { virtual ~I65() noexcept = default; virtual void dummy() = 0; }; struct Impl65 : I65 { INJECT(Impl65(X65, X66, X67, X68, X69, X70, X71, X72, X73, X74)) { } void dummy() override { } }; struct I66 { virtual ~I66() noexcept = default; virtual void dummy() = 0; }; struct Impl66 : I66 { INJECT(Impl66(X66, X67, X68, X69, X70, X71, X72, X73, X74, X75)) { } void dummy() override { } }; struct I67 { virtual ~I67() noexcept = default; virtual void dummy() = 0; }; struct Impl67 : I67 { INJECT(Impl67(X67, X68, X69, X70, X71, X72, X73, X74, X75, X76)) { } void dummy() override { } }; struct I68 { virtual ~I68() noexcept = default; virtual void dummy() = 0; }; struct Impl68 : I68 { INJECT(Impl68(X68, X69, X70, X71, X72, X73, X74, X75, X76, X77)) { } void dummy() override { } }; struct I69 { virtual ~I69() noexcept = default; virtual void dummy() = 0; }; struct Impl69 : I69 { INJECT(Impl69(X69, X70, X71, X72, X73, X74, X75, X76, X77, X78)) { } void dummy() override { } }; struct I70 { virtual ~I70() noexcept = default; virtual void dummy() = 0; }; struct Impl70 : I70 { INJECT(Impl70(X70, X71, X72, X73, X74, X75, X76, X77, X78, X79)) { } void dummy() override { } }; struct I71 { virtual ~I71() noexcept = default; virtual void dummy() = 0; }; struct Impl71 : I71 { INJECT(Impl71(X71, X72, X73, X74, X75, X76, X77, X78, X79, X80)) { } void dummy() override { } }; struct I72 { virtual ~I72() noexcept = default; virtual void dummy() = 0; }; struct Impl72 : I72 { INJECT(Impl72(X72, X73, X74, X75, X76, X77, X78, X79, X80, X81)) { } void dummy() override { } }; struct I73 { virtual ~I73() noexcept = default; virtual void dummy() = 0; }; struct Impl73 : I73 { INJECT(Impl73(X73, X74, X75, X76, X77, X78, X79, X80, X81, X82)) { } void dummy() override { } }; struct I74 { virtual ~I74() noexcept = default; virtual void dummy() = 0; }; struct Impl74 : I74 { INJECT(Impl74(X74, X75, X76, X77, X78, X79, X80, X81, X82, X83)) { } void dummy() override { } }; struct I75 { virtual ~I75() noexcept = default; virtual void dummy() = 0; }; struct Impl75 : I75 { INJECT(Impl75(X75, X76, X77, X78, X79, X80, X81, X82, X83, X84)) { } void dummy() override { } }; struct I76 { virtual ~I76() noexcept = default; virtual void dummy() = 0; }; struct Impl76 : I76 { INJECT(Impl76(X76, X77, X78, X79, X80, X81, X82, X83, X84, X85)) { } void dummy() override { } }; struct I77 { virtual ~I77() noexcept = default; virtual void dummy() = 0; }; struct Impl77 : I77 { INJECT(Impl77(X77, X78, X79, X80, X81, X82, X83, X84, X85, X86)) { } void dummy() override { } }; struct I78 { virtual ~I78() noexcept = default; virtual void dummy() = 0; }; struct Impl78 : I78 { INJECT(Impl78(X78, X79, X80, X81, X82, X83, X84, X85, X86, X87)) { } void dummy() override { } }; struct I79 { virtual ~I79() noexcept = default; virtual void dummy() = 0; }; struct Impl79 : I79 { INJECT(Impl79(X79, X80, X81, X82, X83, X84, X85, X86, X87, X88)) { } void dummy() override { } }; struct I80 { virtual ~I80() noexcept = default; virtual void dummy() = 0; }; struct Impl80 : I80 { INJECT(Impl80(X80, X81, X82, X83, X84, X85, X86, X87, X88, X89)) { } void dummy() override { } }; struct I81 { virtual ~I81() noexcept = default; virtual void dummy() = 0; }; struct Impl81 : I81 { INJECT(Impl81(X81, X82, X83, X84, X85, X86, X87, X88, X89, X90)) { } void dummy() override { } }; struct I82 { virtual ~I82() noexcept = default; virtual void dummy() = 0; }; struct Impl82 : I82 { INJECT(Impl82(X82, X83, X84, X85, X86, X87, X88, X89, X90, X91)) { } void dummy() override { } }; struct I83 { virtual ~I83() noexcept = default; virtual void dummy() = 0; }; struct Impl83 : I83 { INJECT(Impl83(X83, X84, X85, X86, X87, X88, X89, X90, X91, X92)) { } void dummy() override { } }; struct I84 { virtual ~I84() noexcept = default; virtual void dummy() = 0; }; struct Impl84 : I84 { INJECT(Impl84(X84, X85, X86, X87, X88, X89, X90, X91, X92, X93)) { } void dummy() override { } }; struct I85 { virtual ~I85() noexcept = default; virtual void dummy() = 0; }; struct Impl85 : I85 { INJECT(Impl85(X85, X86, X87, X88, X89, X90, X91, X92, X93, X94)) { } void dummy() override { } }; struct I86 { virtual ~I86() noexcept = default; virtual void dummy() = 0; }; struct Impl86 : I86 { INJECT(Impl86(X86, X87, X88, X89, X90, X91, X92, X93, X94, X95)) { } void dummy() override { } }; struct I87 { virtual ~I87() noexcept = default; virtual void dummy() = 0; }; struct Impl87 : I87 { INJECT(Impl87(X87, X88, X89, X90, X91, X92, X93, X94, X95, X96)) { } void dummy() override { } }; struct I88 { virtual ~I88() noexcept = default; virtual void dummy() = 0; }; struct Impl88 : I88 { INJECT(Impl88(X88, X89, X90, X91, X92, X93, X94, X95, X96, X97)) { } void dummy() override { } }; struct I89 { virtual ~I89() noexcept = default; virtual void dummy() = 0; }; struct Impl89 : I89 { INJECT(Impl89(X89, X90, X91, X92, X93, X94, X95, X96, X97, X98)) { } void dummy() override { } }; struct I90 { virtual ~I90() noexcept = default; virtual void dummy() = 0; }; struct Impl90 : I90 { INJECT(Impl90(X90, X91, X92, X93, X94, X95, X96, X97, X98, X99)) { } void dummy() override { } }; struct I91 { virtual ~I91() noexcept = default; virtual void dummy() = 0; }; struct Impl91 : I91 { INJECT(Impl91(X91, X92, X93, X94, X95, X96, X97, X98, X99, X00)) { } void dummy() override { } }; struct I92 { virtual ~I92() noexcept = default; virtual void dummy() = 0; }; struct Impl92 : I92 { INJECT(Impl92(X92, X93, X94, X95, X96, X97, X98, X99, X00, X01)) { } void dummy() override { } }; struct I93 { virtual ~I93() noexcept = default; virtual void dummy() = 0; }; struct Impl93 : I93 { INJECT(Impl93(X93, X94, X95, X96, X97, X98, X99, X00, X01, X02)) { } void dummy() override { } }; struct I94 { virtual ~I94() noexcept = default; virtual void dummy() = 0; }; struct Impl94 : I94 { INJECT(Impl94(X94, X95, X96, X97, X98, X99, X00, X01, X02, X03)) { } void dummy() override { } }; struct I95 { virtual ~I95() noexcept = default; virtual void dummy() = 0; }; struct Impl95 : I95 { INJECT(Impl95(X95, X96, X97, X98, X99, X00, X01, X02, X03, X04)) { } void dummy() override { } }; struct I96 { virtual ~I96() noexcept = default; virtual void dummy() = 0; }; struct Impl96 : I96 { INJECT(Impl96(X96, X97, X98, X99, X00, X01, X02, X03, X04, X05)) { } void dummy() override { } }; struct I97 { virtual ~I97() noexcept = default; virtual void dummy() = 0; }; struct Impl97 : I97 { INJECT(Impl97(X97, X98, X99, X00, X01, X02, X03, X04, X05, X06)) { } void dummy() override { } }; struct I98 { virtual ~I98() noexcept = default; virtual void dummy() = 0; }; struct Impl98 : I98 { INJECT(Impl98(X98, X99, X00, X01, X02, X03, X04, X05, X06, X07)) { } void dummy() override { } }; struct I99 { virtual ~I99() noexcept = default; virtual void dummy() = 0; }; struct Impl99 : I99 { INJECT(Impl99(X99, X00, X01, X02, X03, X04, X05, X06, X07, X08)) { } void dummy() override { } }; struct C0 { INJECT(C0(std::shared_ptr<I00>, std::shared_ptr<I01>, std::shared_ptr<I02>, std::shared_ptr<I03>, std::shared_ptr<I04>, std::shared_ptr<I05>, std::shared_ptr<I06>, std::shared_ptr<I07>, std::shared_ptr<I08>, std::shared_ptr<I09>)) { } }; struct C1 { INJECT(C1(std::shared_ptr<I10>, std::shared_ptr<I11>, std::shared_ptr<I12>, std::shared_ptr<I13>, std::shared_ptr<I14>, std::shared_ptr<I15>, std::shared_ptr<I16>, std::shared_ptr<I17>, std::shared_ptr<I18>, std::shared_ptr<I19>)) { } }; struct C2 { INJECT(C2(std::shared_ptr<I20>, std::shared_ptr<I21>, std::shared_ptr<I22>, std::shared_ptr<I23>, std::shared_ptr<I24>, std::shared_ptr<I25>, std::shared_ptr<I26>, std::shared_ptr<I27>, std::shared_ptr<I28>, std::shared_ptr<I29>)) { } }; struct C3 { INJECT(C3(std::shared_ptr<I30>, std::shared_ptr<I31>, std::shared_ptr<I32>, std::shared_ptr<I33>, std::shared_ptr<I34>, std::shared_ptr<I35>, std::shared_ptr<I36>, std::shared_ptr<I37>, std::shared_ptr<I38>, std::shared_ptr<I39>)) { } }; struct C4 { INJECT(C4(std::shared_ptr<I40>, std::shared_ptr<I41>, std::shared_ptr<I42>, std::shared_ptr<I43>, std::shared_ptr<I44>, std::shared_ptr<I45>, std::shared_ptr<I46>, std::shared_ptr<I47>, std::shared_ptr<I48>, std::shared_ptr<I49>)) { } }; struct C5 { INJECT(C5(std::shared_ptr<I50>, std::shared_ptr<I51>, std::shared_ptr<I52>, std::shared_ptr<I53>, std::shared_ptr<I54>, std::shared_ptr<I55>, std::shared_ptr<I56>, std::shared_ptr<I57>, std::shared_ptr<I58>, std::shared_ptr<I59>)) { } }; struct C6 { INJECT(C6(std::shared_ptr<I60>, std::shared_ptr<I61>, std::shared_ptr<I62>, std::shared_ptr<I63>, std::shared_ptr<I64>, std::shared_ptr<I65>, std::shared_ptr<I66>, std::shared_ptr<I67>, std::shared_ptr<I68>, std::shared_ptr<I69>)) { } }; struct C7 { INJECT(C7(std::shared_ptr<I70>, std::shared_ptr<I71>, std::shared_ptr<I72>, std::shared_ptr<I73>, std::shared_ptr<I74>, std::shared_ptr<I75>, std::shared_ptr<I76>, std::shared_ptr<I77>, std::shared_ptr<I78>, std::shared_ptr<I79>)) { } }; struct C8 { INJECT(C8(std::shared_ptr<I80>, std::shared_ptr<I81>, std::shared_ptr<I82>, std::shared_ptr<I83>, std::shared_ptr<I84>, std::shared_ptr<I85>, std::shared_ptr<I86>, std::shared_ptr<I87>, std::shared_ptr<I88>, std::shared_ptr<I89>)) { } }; struct C9 { INJECT(C9(std::shared_ptr<I90>, std::shared_ptr<I91>, std::shared_ptr<I92>, std::shared_ptr<I93>, std::shared_ptr<I94>, std::shared_ptr<I95>, std::shared_ptr<I96>, std::shared_ptr<I97>, std::shared_ptr<I98>, std::shared_ptr<I99>)) { } }; struct Complex { INJECT(Complex(C0, C1, C2, C3, C4, C5, C6, C7, C8, C9)) { } }; // clang-format off fruit::Component<Complex> module() { return fruit::createComponent() .bind<I00, Impl00>() .bind<I01, Impl01>() .bind<I02, Impl02>() .bind<I03, Impl03>() .bind<I04, Impl04>() .bind<I05, Impl05>() .bind<I06, Impl06>() .bind<I07, Impl07>() .bind<I08, Impl08>() .bind<I09, Impl09>() .bind<I10, Impl10>() .bind<I11, Impl11>() .bind<I12, Impl12>() .bind<I13, Impl13>() .bind<I14, Impl14>() .bind<I15, Impl15>() .bind<I16, Impl16>() .bind<I17, Impl17>() .bind<I18, Impl18>() .bind<I19, Impl19>() .bind<I20, Impl20>() .bind<I21, Impl21>() .bind<I22, Impl22>() .bind<I23, Impl23>() .bind<I24, Impl24>() .bind<I25, Impl25>() .bind<I26, Impl26>() .bind<I27, Impl27>() .bind<I28, Impl28>() .bind<I29, Impl29>() .bind<I30, Impl30>() .bind<I31, Impl31>() .bind<I32, Impl32>() .bind<I33, Impl33>() .bind<I34, Impl34>() .bind<I35, Impl35>() .bind<I36, Impl36>() .bind<I37, Impl37>() .bind<I38, Impl38>() .bind<I39, Impl39>() .bind<I40, Impl40>() .bind<I41, Impl41>() .bind<I42, Impl42>() .bind<I43, Impl43>() .bind<I44, Impl44>() .bind<I45, Impl45>() .bind<I46, Impl46>() .bind<I47, Impl47>() .bind<I48, Impl48>() .bind<I49, Impl49>() .bind<I50, Impl50>() .bind<I51, Impl51>() .bind<I52, Impl52>() .bind<I53, Impl53>() .bind<I54, Impl54>() .bind<I55, Impl55>() .bind<I56, Impl56>() .bind<I57, Impl57>() .bind<I58, Impl58>() .bind<I59, Impl59>() .bind<I60, Impl60>() .bind<I61, Impl61>() .bind<I62, Impl62>() .bind<I63, Impl63>() .bind<I64, Impl64>() .bind<I65, Impl65>() .bind<I66, Impl66>() .bind<I67, Impl67>() .bind<I68, Impl68>() .bind<I69, Impl69>() .bind<I70, Impl70>() .bind<I71, Impl71>() .bind<I72, Impl72>() .bind<I73, Impl73>() .bind<I74, Impl74>() .bind<I75, Impl75>() .bind<I76, Impl76>() .bind<I77, Impl77>() .bind<I78, Impl78>() .bind<I79, Impl79>() .bind<I80, Impl80>() .bind<I81, Impl81>() .bind<I82, Impl82>() .bind<I83, Impl83>() .bind<I84, Impl84>() .bind<I85, Impl85>() .bind<I86, Impl86>() .bind<I87, Impl87>() .bind<I88, Impl88>() .bind<I89, Impl89>() .bind<I90, Impl90>() .bind<I91, Impl91>() .bind<I92, Impl92>() .bind<I93, Impl93>() .bind<I94, Impl94>() .bind<I95, Impl95>() .bind<I96, Impl96>() .bind<I97, Impl97>() .bind<I98, Impl98>() .bind<I99, Impl99>(); } int main() { fruit::Injector<Complex> injector{module()}; injector.get<Complex>(); }
99.945783
249
0.620095
dan-42
a8e4cd59a6da425b7242290c995ccb6a98b1cd8e
29,663
cpp
C++
core/src/main/java/site/ycsb/data_gen/Graph_gen/Graph_gen/test/test-TUndirNet.cpp
qiuhere/Bench
80f15facb81120b754547586cf3a7e5f46ca1551
[ "Apache-2.0" ]
1,805
2015-01-06T20:01:35.000Z
2022-03-29T16:12:51.000Z
test/test-TUndirNet.cpp
lizhaoqing/snap
907c34aac6bcddc7c2f8efb64be76e87dd7e4ea5
[ "BSD-3-Clause" ]
168
2015-01-07T22:57:29.000Z
2022-03-15T01:20:24.000Z
test/test-TUndirNet.cpp
lizhaoqing/snap
907c34aac6bcddc7c2f8efb64be76e87dd7e4ea5
[ "BSD-3-Clause" ]
768
2015-01-09T02:28:45.000Z
2022-03-30T00:53:46.000Z
#include <gtest/gtest.h> #include "Snap.h" // Test the default constructor TEST(TUndirNet, DefaultConstructor) { PUndirNet Graph; Graph = TUndirNet::New(); EXPECT_EQ(0,Graph->GetNodes()); EXPECT_EQ(0,Graph->GetEdges()); EXPECT_EQ(1,Graph->IsOk()); EXPECT_EQ(1,Graph->Empty()); EXPECT_EQ(0,Graph->HasFlag(gfDirected)); } // Test node, edge creation TEST(TUndirNet, ManipulateNodesEdges) { int NNodes = 10000; int NEdges = 100000; const char *FName = "test.graph.dat"; PUndirNet Graph; PUndirNet Graph1; PUndirNet Graph2; int i; int n; int NCount; int LCount; int x,y; int Deg, InDeg, OutDeg; Graph = TUndirNet::New(); EXPECT_EQ(1,Graph->Empty()); // create the nodes for (i = 0; i < NNodes; i++) { Graph->AddNode(i); } EXPECT_EQ(0,Graph->Empty()); EXPECT_EQ(NNodes,Graph->GetNodes()); // create random edges NCount = NEdges; LCount = 0; while (NCount > 0) { x = (long) (drand48() * NNodes); y = (long) (drand48() * NNodes); if (!Graph->IsEdge(x,y)) { n = Graph->AddEdge(x, y); NCount--; if (x == y) { LCount++; } } } EXPECT_EQ(NEdges,Graph->GetEdges()); EXPECT_EQ(0,Graph->Empty()); EXPECT_EQ(1,Graph->IsOk()); for (i = 0; i < NNodes; i++) { EXPECT_EQ(1,Graph->IsNode(i)); } EXPECT_EQ(0,Graph->IsNode(NNodes)); EXPECT_EQ(0,Graph->IsNode(NNodes+1)); EXPECT_EQ(0,Graph->IsNode(2*NNodes)); // nodes iterator NCount = 0; for (TUndirNet::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) { NCount++; } EXPECT_EQ(NNodes,NCount); // edges per node iterator, each non-loop is visited twice, each loop once NCount = 0; for (TUndirNet::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) { for (int e = 0; e < NI.GetOutDeg(); e++) { NCount++; } } EXPECT_EQ(NEdges*2-LCount,NCount); // edges iterator, each edge is visited once NCount = 0; for (TUndirNet::TEdgeI EI = Graph->BegEI(); EI < Graph->EndEI(); EI++) { NCount++; } EXPECT_EQ(NEdges,NCount); // node degree for (TUndirNet::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) { Deg = NI.GetDeg(); InDeg = NI.GetInDeg(); OutDeg = NI.GetOutDeg(); EXPECT_EQ(Deg,InDeg); EXPECT_EQ(Deg,OutDeg); } // assignment Graph1 = TUndirNet::New(); *Graph1 = *Graph; EXPECT_EQ(NNodes,Graph1->GetNodes()); EXPECT_EQ(NEdges,Graph1->GetEdges()); EXPECT_EQ(0,Graph1->Empty()); EXPECT_EQ(1,Graph1->IsOk()); // saving and loading { TFOut FOut(FName); Graph->Save(FOut); FOut.Flush(); } { TFIn FIn(FName); Graph2 = TUndirNet::Load(FIn); } EXPECT_EQ(NNodes,Graph2->GetNodes()); EXPECT_EQ(NEdges,Graph2->GetEdges()); EXPECT_EQ(0,Graph2->Empty()); EXPECT_EQ(1,Graph2->IsOk()); // remove all the nodes and edges for (i = 0; i < NNodes; i++) { n = Graph->GetRndNId(); Graph->DelNode(n); } EXPECT_EQ(0,Graph->GetNodes()); EXPECT_EQ(0,Graph->GetEdges()); EXPECT_EQ(1,Graph->IsOk()); EXPECT_EQ(1,Graph->Empty()); Graph1->Clr(); EXPECT_EQ(0,Graph1->GetNodes()); EXPECT_EQ(0,Graph1->GetEdges()); EXPECT_EQ(1,Graph1->IsOk()); EXPECT_EQ(1,Graph1->Empty()); } // Test edge iterator, manipulate edges TEST(TUndirNet, ManipulateEdges) { int Iterations = 100; int NNodes; int NNodesStart = 8; int NNodesEnd = 25; int NEdges; int NEdgesStart = 0; int NEdgesEnd = 50; PUndirNet Graph; PUndirNet Graph1; PUndirNet Graph2; int NCount, ECount; int x,y; TIntV NodeIds; THashSet<TIntPr> EdgeSet; TInt::Rnd.PutSeed(0); for (int i = 0; i < Iterations; i++) { for (NEdges = NEdgesStart; NEdges <= NEdgesEnd; NEdges++) { for (NNodes = NNodesStart; NNodes <= NNodesEnd; NNodes++) { // Skip if too many edges required per NNodes (n*(n+1)/2) if (NEdges > (NNodes * (NNodes+1)/2)) { continue; } Graph = TUndirNet::New(); EXPECT_TRUE(Graph->Empty()); // Generate NNodes NodeIds.Gen(NNodes); for (int n = 0; n < NNodes; n++) { NodeIds[n] = n; } // Add the nodes in random order NodeIds.Shuffle(TInt::Rnd); for (int n = 0; n < NodeIds.Len(); n++) { Graph->AddNode(NodeIds[n]); } EXPECT_FALSE(Graph->Empty()); // Create random edges EdgeSet.Clr(); NCount = NEdges; while (NCount > 0) { x = (long) (drand48() * NNodes); y = (long) (drand48() * NNodes); if (!Graph->IsEdge(x,y)) { Graph->AddEdge(x, y); EdgeSet.AddKey(TIntPr(x, y)); EdgeSet.AddKey(TIntPr(y, x)); NCount--; } } // Check edge iterator to make sure all edges are valid and no more (in hash set) TIntPrV DelEdgeV; for (TUndirNet::TEdgeI EI = Graph->BegEI(); EI < Graph->EndEI(); EI++) { TIntPr Edge(EI.GetSrcNId(), EI.GetDstNId()); TIntPr EdgeR(EI.GetDstNId(), EI.GetSrcNId()); EXPECT_TRUE(EdgeSet.IsKey(Edge) || EdgeSet.IsKey(EdgeR)); if (EdgeSet.IsKey(Edge)) { EdgeSet.DelKey(Edge); } if (EdgeSet.IsKey(EdgeR)) { EdgeSet.DelKey(EdgeR); } DelEdgeV.Add(Edge); } EXPECT_TRUE(EdgeSet.Empty()); EXPECT_TRUE(DelEdgeV.Len() == NEdges); // Randomly delete node, check to make sure edges were deleted NodeIds.Shuffle(TInt::Rnd); for (int n = 0; n < NNodes; n++) { TIntPrV DelEdgeNodeV; int DelNodeId = NodeIds[n]; // Get edges for node to be deleted (to verify all deleted) int EdgesBeforeDel; EdgesBeforeDel = Graph->GetEdges(); for (TUndirNet::TEdgeI EI = Graph->BegEI(); EI < Graph->EndEI(); EI++) { if (EI.GetSrcNId() == DelNodeId || EI.GetDstNId() == DelNodeId) { DelEdgeNodeV.Add(TIntPr(EI.GetSrcNId(), EI.GetDstNId())); } } Graph->DelNode(DelNodeId); EXPECT_TRUE(EdgesBeforeDel == DelEdgeNodeV.Len() + Graph->GetEdges()); EXPECT_FALSE(Graph->IsNode(DelNodeId)); EXPECT_TRUE(Graph->IsOk()); // Make sure all the edges to deleted node are gone for (int e = 0; e < DelEdgeNodeV.Len(); e++) { EXPECT_FALSE(Graph->IsEdge(DelEdgeNodeV[e].Val1, DelEdgeNodeV[e].Val2)); } // Make sure no edge on graph is connected to deleted node ECount = 0; for (TUndirNet::TEdgeI EI = Graph->BegEI(); EI < Graph->EndEI(); EI++) { EXPECT_FALSE(EI.GetSrcNId() == DelNodeId || EI.GetDstNId() == DelNodeId); ECount++; } // Make sure iterator returns all of the edges EXPECT_TRUE(ECount == Graph->GetEdges()); } EXPECT_TRUE(0 == Graph->GetEdges()); Graph->Clr(); EXPECT_TRUE(Graph->Empty()); } } } } // Test small graph TEST(TUndirNet, GetSmallGraph) { PUndirNet Graph; Graph = TUndirNet::GetSmallGraph(); EXPECT_EQ(5,Graph->GetNodes()); EXPECT_EQ(5,Graph->GetEdges()); EXPECT_EQ(1,Graph->IsOk()); EXPECT_EQ(0,Graph->Empty()); EXPECT_EQ(0,Graph->HasFlag(gfDirected)); } TEST(TUndirNet, AddSAttrN) { PUndirNet Graph; Graph = TUndirNet::New(); TInt AttrId; int status = Graph->AddSAttrN("TestInt", atInt, AttrId); EXPECT_EQ(0, status); EXPECT_EQ(0, AttrId.Val); status = Graph->AddSAttrN("TestFlt", atFlt, AttrId); EXPECT_EQ(0, status); EXPECT_EQ(1, AttrId.Val); status = Graph->AddSAttrN("TestStr", atStr, AttrId); EXPECT_EQ(0, status); EXPECT_EQ(2, AttrId.Val); //status = Graph->AddSAttrN("TestAny", atAny, AttrId); //EXPECT_EQ(-1, status); } TEST(TUndirNet, GetSAttrIdN) { PUndirNet Graph; Graph = TUndirNet::New(); TInt AttrId; Graph->AddSAttrN("TestInt", atInt, AttrId); Graph->AddSAttrN("TestFlt", atFlt, AttrId); Graph->AddSAttrN("TestStr", atStr, AttrId); TAttrType AttrType; int status = Graph->GetSAttrIdN(TStr("TestInt"), AttrId, AttrType); EXPECT_EQ(0, status); EXPECT_EQ(atInt, AttrType); EXPECT_EQ(0, AttrId.Val); status = Graph->GetSAttrIdN(TStr("TestFlt"), AttrId, AttrType); EXPECT_EQ(0, status); EXPECT_EQ(atFlt, AttrType); EXPECT_EQ(1, AttrId.Val); status = Graph->GetSAttrIdN(TStr("TestStr"), AttrId, AttrType); EXPECT_EQ(0, status); EXPECT_EQ(atStr, AttrType); EXPECT_EQ(2, AttrId.Val); status = Graph->GetSAttrIdN(TStr("TestError"), AttrId, AttrType); EXPECT_EQ(-1, status); } TEST(TUndirNet, GetSAttrNameN) { PUndirNet Graph; Graph = TUndirNet::New(); TInt AttrId; Graph->AddSAttrN("TestInt", atInt, AttrId); Graph->AddSAttrN("TestFlt", atFlt, AttrId); Graph->AddSAttrN("TestStr", atStr, AttrId); TAttrType AttrType; TStr Name; int status = Graph->GetSAttrNameN(0, Name, AttrType); EXPECT_EQ(0, status); EXPECT_EQ(atInt, AttrType); EXPECT_STREQ("TestInt", Name.CStr()); status = Graph->GetSAttrNameN(1, Name, AttrType); EXPECT_EQ(0, status); EXPECT_EQ(atFlt, AttrType); EXPECT_STREQ("TestFlt", Name.CStr()); status = Graph->GetSAttrNameN(2, Name, AttrType); EXPECT_EQ(0, status); EXPECT_EQ(atStr, AttrType); EXPECT_STREQ("TestStr", Name.CStr()); status = Graph->GetSAttrNameN(3, Name, AttrType); EXPECT_EQ(-1, status); } TEST(TUndirNet, AddSAttrDatN_int) { PUndirNet Graph; Graph = TUndirNet::New(); Graph->AddNode(0); TInt Val(5); TInt Id(0); int status = Graph->AddSAttrDatN(Id, 1, Val); EXPECT_EQ(-1, status); TInt AttrId; TStr AttrName("TestInt"); Graph->AddSAttrN(AttrName, atInt, AttrId); TFlt ErrorVal(1); status = Graph->AddSAttrDatN(Id, AttrId, ErrorVal); EXPECT_EQ(-2, status); status = Graph->AddSAttrDatN(Id, AttrId, Val); EXPECT_EQ(0, status); status = Graph->AddSAttrDatN(Id, AttrName, Val); EXPECT_EQ(0, status); TStr NewName("TestInt2"); status = Graph->AddSAttrDatN(Id, NewName, Val); EXPECT_EQ(0, status); TInt ErrorId(1); status = Graph->AddSAttrDatN(ErrorId, AttrId, Val); EXPECT_EQ(-1, status); } TEST(TUndirNet, AddSAttrDatN_flt) { PUndirNet Graph; Graph = TUndirNet::New(); Graph->AddNode(0); TFlt Val(5.0); TInt Id(0); int status = Graph->AddSAttrDatN(Id, 1, Val); EXPECT_EQ(-1, status); TInt AttrId; TStr AttrName("TestFlt"); Graph->AddSAttrN(AttrName, atFlt, AttrId); TInt ErrorVal(1); status = Graph->AddSAttrDatN(Id, AttrId, ErrorVal); EXPECT_EQ(-2, status); status = Graph->AddSAttrDatN(Id, AttrId, Val); EXPECT_EQ(0, status); status = Graph->AddSAttrDatN(Id, AttrName, Val); EXPECT_EQ(0, status); TStr NewName("TestFlt2"); status = Graph->AddSAttrDatN(Id, NewName, Val); EXPECT_EQ(0, status); TInt ErrorId(1); status = Graph->AddSAttrDatN(ErrorId, AttrId, Val); EXPECT_EQ(-1, status); } TEST(TUndirNet, AddSAttrDatN_str) { PUndirNet Graph; Graph = TUndirNet::New(); Graph->AddNode(0); TStr Val("5"); TInt Id(0); int status = Graph->AddSAttrDatN(Id, 1, Val); EXPECT_EQ(-1, status); TInt AttrId; TStr AttrName("TestFlt"); Graph->AddSAttrN(AttrName, atStr, AttrId); TInt ErrorVal(1); status = Graph->AddSAttrDatN(Id, AttrId, ErrorVal); EXPECT_EQ(-2, status); status = Graph->AddSAttrDatN(Id, AttrId, Val); EXPECT_EQ(0, status); status = Graph->AddSAttrDatN(Id, AttrName, Val); EXPECT_EQ(0, status); TStr NewName("TestStr2"); status = Graph->AddSAttrDatN(Id, NewName, Val); EXPECT_EQ(0, status); TInt ErrorId(1); status = Graph->AddSAttrDatN(ErrorId, AttrId, Val); EXPECT_EQ(-1, status); } TEST(TUndirNet, GetSAttrDatN_int) { PUndirNet Graph; Graph = TUndirNet::New(); Graph->AddNode(0); TInt Val; TInt AttrId(0); TStr AttrName("TestInt"); TInt NId(0); int status = Graph->GetSAttrDatN(NId, AttrName, Val); EXPECT_EQ(-1, status); status = Graph->GetSAttrDatN(NId, AttrId, Val); EXPECT_EQ(-1, status); Graph->AddSAttrN(AttrName, atInt, AttrId); TInt TestVal(5); Graph->AddSAttrDatN(NId, AttrId, TestVal); status = Graph->GetSAttrDatN(NId, AttrId, Val); EXPECT_EQ(0, status); EXPECT_EQ(TestVal.Val, Val.Val); status = Graph->GetSAttrDatN(NId, AttrName, Val); EXPECT_EQ(0, status); EXPECT_EQ(TestVal.Val, Val.Val); TInt ErrorId(1); status = Graph->GetSAttrDatN(ErrorId, AttrId, Val); EXPECT_EQ(-1, status); } TEST(TUndirNet, GetSAttrDatN_flt) { PUndirNet Graph; Graph = TUndirNet::New(); Graph->AddNode(0); TFlt Val; TInt AttrId(0); TStr AttrName("TestInt"); TInt NId(0); int status = Graph->GetSAttrDatN(NId, AttrName, Val); EXPECT_EQ(-1, status); status = Graph->GetSAttrDatN(NId, AttrId, Val); EXPECT_EQ(-1, status); Graph->AddSAttrN(AttrName, atFlt, AttrId); TFlt TestVal(5.0); Graph->AddSAttrDatN(NId, AttrId, TestVal); status = Graph->GetSAttrDatN(NId, AttrId, Val); EXPECT_EQ(0, status); EXPECT_EQ(TestVal.Val, Val.Val); status = Graph->GetSAttrDatN(NId, AttrName, Val); EXPECT_EQ(0, status); EXPECT_EQ(TestVal.Val, Val.Val); TInt ErrorId(1); status = Graph->GetSAttrDatN(ErrorId, AttrId, Val); EXPECT_EQ(-1, status); } TEST(TUndirNet, GetSAttrDatN_str) { PUndirNet Graph; Graph = TUndirNet::New(); Graph->AddNode(0); TStr Val; TInt AttrId(0); TStr AttrName("TestInt"); TInt NId(0); int status = Graph->GetSAttrDatN(NId, AttrName, Val); EXPECT_EQ(-1, status); status = Graph->GetSAttrDatN(NId, AttrId, Val); EXPECT_EQ(-1, status); Graph->AddSAttrN(AttrName, atStr, AttrId); TStr TestVal("5"); Graph->AddSAttrDatN(NId, AttrId, TestVal); status = Graph->GetSAttrDatN(NId, AttrId, Val); EXPECT_EQ(0, status); EXPECT_STREQ(TestVal.CStr(), Val.CStr()); status = Graph->GetSAttrDatN(NId, AttrName, Val); EXPECT_EQ(0, status); EXPECT_STREQ(TestVal.CStr(), Val.CStr()); TInt ErrorId(1); status = Graph->GetSAttrDatN(ErrorId, AttrId, Val); EXPECT_EQ(-1, status); } TEST(TUndirNet, DelSAttrDatN) { PUndirNet Graph; Graph = TUndirNet::New(); Graph->AddNode(0); TStr IntAttr("TestInt"); TInt IntId; Graph->AddSAttrN(IntAttr, atInt, IntId); TStr FltAttr("TestFlt"); TInt FltId; Graph->AddSAttrN(FltAttr, atFlt, FltId); TStr StrAttr("TestStr"); TInt StrId; Graph->AddSAttrN(StrAttr, atStr, StrId); TInt Id(0); int status = Graph->DelSAttrDatN(Id, IntAttr); EXPECT_EQ(-1, status); status = Graph->DelSAttrDatN(Id, IntId); EXPECT_EQ(-1, status); TInt IntVal(5); Graph->AddSAttrDatN(Id, IntId, IntVal); status = Graph->DelSAttrDatN(Id, IntAttr); EXPECT_EQ(0, status); Graph->AddSAttrDatN(Id, IntId, IntVal); status = Graph->DelSAttrDatN(Id, IntId); EXPECT_EQ(0, status); status = Graph->DelSAttrDatN(Id, IntId); EXPECT_EQ(-1, status); TInt ErrorId(1); status = Graph->DelSAttrDatN(ErrorId, IntId); EXPECT_EQ(-1, status); TFlt FltVal(5.0); Graph->AddSAttrDatN(Id, FltId, FltVal); status = Graph->DelSAttrDatN(Id, FltAttr); EXPECT_EQ(0, status); Graph->AddSAttrDatN(Id, FltId, FltVal); status = Graph->DelSAttrDatN(Id, FltId); EXPECT_EQ(0, status); status = Graph->DelSAttrDatN(Id, FltId); EXPECT_EQ(-1, status); status = Graph->DelSAttrDatN(ErrorId, FltId); EXPECT_EQ(-1, status); TStr StrVal("5"); Graph->AddSAttrDatN(Id, StrId, StrVal); status = Graph->DelSAttrDatN(Id, StrAttr); EXPECT_EQ(0, status); Graph->AddSAttrDatN(Id, StrId, StrVal); status = Graph->DelSAttrDatN(Id, StrId); EXPECT_EQ(0, status); status = Graph->DelSAttrDatN(Id, StrId); EXPECT_EQ(-1, status); status = Graph->DelSAttrDatN(ErrorId, StrId); EXPECT_EQ(-1, status); } TEST(TUndirNet, GetSAttrVN) { PUndirNet Graph; Graph = TUndirNet::New(); Graph->AddNode(0); TStr IntAttr("TestInt"); TInt IntId; Graph->AddSAttrN(IntAttr, atInt, IntId); TStr FltAttr("TestFlt"); TInt FltId; Graph->AddSAttrN(FltAttr, atFlt, FltId); TStr StrAttr("TestStr"); TInt StrId; Graph->AddSAttrN(StrAttr, atStr, StrId); TInt Id(0); TInt IntVal(5); Graph->AddSAttrDatN(Id, IntId, IntVal); TFlt FltVal(5.0); Graph->AddSAttrDatN(Id, FltId, FltVal); TStr StrVal("5"); Graph->AddSAttrDatN(Id, StrId, StrVal); TAttrPrV AttrV; int status = Graph->GetSAttrVN(Id, atInt, AttrV); EXPECT_EQ(0, status); EXPECT_EQ(1, AttrV.Len()); status = Graph->GetSAttrVN(Id, atFlt, AttrV); EXPECT_EQ(0, status); EXPECT_EQ(1, AttrV.Len()); status = Graph->GetSAttrVN(Id, atStr, AttrV); EXPECT_EQ(0, status); EXPECT_EQ(1, AttrV.Len()); //status = Graph->GetSAttrVN(Id, atAny, AttrV); //EXPECT_EQ(0, status); //EXPECT_EQ(3, AttrV.Len()); //status = Graph->GetSAttrVN(Id, atUndef, AttrV); //EXPECT_EQ(0, status); //EXPECT_EQ(0, AttrV.Len()); //TInt ErrorId(1); //status = Graph->GetSAttrVN(ErrorId, atUndef, AttrV); //EXPECT_EQ(-1, status); } TEST(TUndirNet, GetIdVSAttrN) { PUndirNet Graph; Graph = TUndirNet::New(); TStr IntAttr("TestInt"); TInt IntId; Graph->AddSAttrN(IntAttr, atInt, IntId); TStr FltAttr("TestFlt"); TInt FltId; Graph->AddSAttrN(FltAttr, atFlt, FltId); TStr StrAttr("TestStr"); TInt StrId; Graph->AddSAttrN(StrAttr, atStr, StrId); TInt IntVal(0); TFlt FltVal(0); TStr StrVal("test"); for (int i = 0; i < 10; i++) { Graph->AddNode(i); TInt Id(i); Graph->AddSAttrDatN(Id, IntId, IntVal); if (i%2 == 0) { Graph->AddSAttrDatN(Id, FltId, FltVal); } } Graph->AddSAttrDatN(0, StrId, StrVal); TIntV IdV; Graph->GetIdVSAttrN(IntAttr, IdV); EXPECT_EQ(10, IdV.Len()); Graph->GetIdVSAttrN(IntId, IdV); EXPECT_EQ(10, IdV.Len()); Graph->GetIdVSAttrN(FltAttr, IdV); EXPECT_EQ(5, IdV.Len()); Graph->GetIdVSAttrN(FltId, IdV); EXPECT_EQ(5, IdV.Len()); Graph->GetIdVSAttrN(StrAttr, IdV); EXPECT_EQ(1, IdV.Len()); Graph->GetIdVSAttrN(StrId, IdV); EXPECT_EQ(1, IdV.Len()); } TEST(TUndirNet, AddSAttrE) { PUndirNet Graph; Graph = TUndirNet::New(); TInt AttrId; int status = Graph->AddSAttrE("TestInt", atInt, AttrId); EXPECT_EQ(0, status); EXPECT_EQ(0, AttrId.Val); status = Graph->AddSAttrE("TestFlt", atFlt, AttrId); EXPECT_EQ(0, status); EXPECT_EQ(1, AttrId.Val); status = Graph->AddSAttrE("TestStr", atStr, AttrId); EXPECT_EQ(0, status); EXPECT_EQ(2, AttrId.Val); //status = Graph->AddSAttrE("TestAny", atAny, AttrId); //EXPECT_EQ(-1, status); } TEST(TUndirNet, GetSAttrIdE) { PUndirNet Graph; Graph = TUndirNet::New(); TInt AttrId; Graph->AddSAttrE("TestInt", atInt, AttrId); Graph->AddSAttrE("TestFlt", atFlt, AttrId); Graph->AddSAttrE("TestStr", atStr, AttrId); TAttrType AttrType; int status = Graph->GetSAttrIdE(TStr("TestInt"), AttrId, AttrType); EXPECT_EQ(0, status); EXPECT_EQ(atInt, AttrType); EXPECT_EQ(0, AttrId.Val); status = Graph->GetSAttrIdE(TStr("TestFlt"), AttrId, AttrType); EXPECT_EQ(0, status); EXPECT_EQ(atFlt, AttrType); EXPECT_EQ(1, AttrId.Val); status = Graph->GetSAttrIdE(TStr("TestStr"), AttrId, AttrType); EXPECT_EQ(0, status); EXPECT_EQ(atStr, AttrType); EXPECT_EQ(2, AttrId.Val); status = Graph->GetSAttrIdE(TStr("TestError"), AttrId, AttrType); EXPECT_EQ(-1, status); } TEST(TUndirNet, GetSAttrNameE) { PUndirNet Graph; Graph = TUndirNet::New(); TInt AttrId; Graph->AddSAttrE("TestInt", atInt, AttrId); Graph->AddSAttrE("TestFlt", atFlt, AttrId); Graph->AddSAttrE("TestStr", atStr, AttrId); TAttrType AttrType; TStr Name; int status = Graph->GetSAttrNameE(0, Name, AttrType); EXPECT_EQ(0, status); EXPECT_EQ(atInt, AttrType); EXPECT_STREQ("TestInt", Name.CStr()); status = Graph->GetSAttrNameE(1, Name, AttrType); EXPECT_EQ(0, status); EXPECT_EQ(atFlt, AttrType); EXPECT_STREQ("TestFlt", Name.CStr()); status = Graph->GetSAttrNameE(2, Name, AttrType); EXPECT_EQ(0, status); EXPECT_EQ(atStr, AttrType); EXPECT_STREQ("TestStr", Name.CStr()); status = Graph->GetSAttrNameE(3, Name, AttrType); EXPECT_EQ(-1, status); } TEST(TUndirNet, AddSAttrDatE_int) { PUndirNet Graph; Graph = TUndirNet::New(); Graph->AddNode(0); Graph->AddNode(1); Graph->AddEdge(0, 1); TInt Val(5); int SrcId = 0; int DstId = 1; int status = Graph->AddSAttrDatE(SrcId, DstId, 1, Val); EXPECT_EQ(-1, status); TInt AttrId; TStr AttrName("TestInt"); Graph->AddSAttrE(AttrName, atInt, AttrId); TFlt ErrorVal(1); status = Graph->AddSAttrDatE(SrcId, DstId, AttrId, ErrorVal); EXPECT_EQ(-2, status); status = Graph->AddSAttrDatE(SrcId, DstId, AttrId, Val); EXPECT_EQ(0, status); status = Graph->AddSAttrDatE(SrcId, DstId, AttrName, Val); EXPECT_EQ(0, status); TStr NewName("TestInt2"); status = Graph->AddSAttrDatE(SrcId, DstId, NewName, Val); EXPECT_EQ(0, status); int ErrorId = 5; status = Graph->AddSAttrDatE(SrcId, ErrorId, AttrId, Val); EXPECT_EQ(-1, status); } TEST(TUndirNet, AddSAttrDatE_flt) { PUndirNet Graph; Graph = TUndirNet::New(); Graph->AddNode(0); Graph->AddNode(1); Graph->AddEdge(0, 1); TFlt Val(5.0); int SrcId = 0; int DstId = 1; int status = Graph->AddSAttrDatE(SrcId, DstId, 1, Val); EXPECT_EQ(-1, status); TInt AttrId; TStr AttrName("TestFlt"); Graph->AddSAttrE(AttrName, atFlt, AttrId); TInt ErrorVal(1); status = Graph->AddSAttrDatE(SrcId, DstId, AttrId, ErrorVal); EXPECT_EQ(-2, status); status = Graph->AddSAttrDatE(SrcId, DstId, AttrId, Val); EXPECT_EQ(0, status); status = Graph->AddSAttrDatE(SrcId, DstId, AttrName, Val); EXPECT_EQ(0, status); TStr NewName("TestFlt2"); status = Graph->AddSAttrDatE(SrcId, DstId, NewName, Val); EXPECT_EQ(0, status); int ErrorId = 5; status = Graph->AddSAttrDatE(SrcId, ErrorId, AttrId, Val); EXPECT_EQ(-1, status); } TEST(TUndirNet, AddSAttrDatE_str) { PUndirNet Graph; Graph = TUndirNet::New(); Graph->AddNode(0); Graph->AddNode(1); Graph->AddEdge(0, 1); TStr Val("5"); int SrcId = 0; int DstId = 1; int status = Graph->AddSAttrDatE(SrcId, DstId, 1, Val); EXPECT_EQ(-1, status); TInt AttrId; TStr AttrName("TestFlt"); Graph->AddSAttrE(AttrName, atStr, AttrId); TInt ErrorVal(1); status = Graph->AddSAttrDatE(SrcId, DstId, AttrId, ErrorVal); EXPECT_EQ(-2, status); status = Graph->AddSAttrDatE(SrcId, DstId, AttrId, Val); EXPECT_EQ(0, status); status = Graph->AddSAttrDatE(SrcId, DstId, AttrName, Val); EXPECT_EQ(0, status); TStr NewName("TestStr2"); status = Graph->AddSAttrDatE(SrcId, DstId, NewName, Val); EXPECT_EQ(0, status); int ErrorId = 5; status = Graph->AddSAttrDatE(SrcId, ErrorId, AttrId, Val); EXPECT_EQ(-1, status); } TEST(TUndirNet, GetSAttrDatE_int) { PUndirNet Graph; Graph = TUndirNet::New(); Graph->AddNode(0); Graph->AddNode(1); Graph->AddEdge(0, 1); TInt Val; TInt AttrId(0); TStr AttrName("TestInt"); int SrcId = 0; int DstId = 1; int status = Graph->GetSAttrDatE(SrcId, DstId, AttrName, Val); EXPECT_EQ(-1, status); status = Graph->GetSAttrDatE(SrcId, DstId, AttrId, Val); EXPECT_EQ(-1, status); Graph->AddSAttrE(AttrName, atInt, AttrId); TInt TestVal(5); Graph->AddSAttrDatE(SrcId, DstId, AttrId, TestVal); status = Graph->GetSAttrDatE(SrcId, DstId, AttrId, Val); EXPECT_EQ(0, status); EXPECT_EQ(TestVal.Val, Val.Val); status = Graph->GetSAttrDatE(SrcId, DstId, AttrName, Val); EXPECT_EQ(0, status); EXPECT_EQ(TestVal.Val, Val.Val); int ErrorId = 5; status = Graph->GetSAttrDatE(SrcId, ErrorId, AttrId, Val); EXPECT_EQ(-1, status); } TEST(TUndirNet, GetSAttrDatE_flt) { PUndirNet Graph; Graph = TUndirNet::New(); Graph->AddNode(0); Graph->AddNode(1); Graph->AddEdge(0, 1); TFlt Val; TInt AttrId(0); TStr AttrName("TestInt"); int SrcId = 0; int DstId = 1; int status = Graph->GetSAttrDatE(SrcId, DstId, AttrName, Val); EXPECT_EQ(-1, status); status = Graph->GetSAttrDatE(SrcId, DstId, AttrId, Val); EXPECT_EQ(-1, status); Graph->AddSAttrE(AttrName, atFlt, AttrId); TFlt TestVal(5.0); Graph->AddSAttrDatE(SrcId, DstId, AttrId, TestVal); status = Graph->GetSAttrDatE(SrcId, DstId, AttrId, Val); EXPECT_EQ(0, status); EXPECT_EQ(TestVal.Val, Val.Val); status = Graph->GetSAttrDatE(SrcId, DstId, AttrName, Val); EXPECT_EQ(0, status); EXPECT_EQ(TestVal.Val, Val.Val); int ErrorId = 5; status = Graph->GetSAttrDatE(SrcId, ErrorId, AttrId, Val); EXPECT_EQ(-1, status); } TEST(TUndirNet, GetSAttrDatE_str) { PUndirNet Graph; Graph = TUndirNet::New(); Graph->AddNode(0); Graph->AddNode(1); Graph->AddEdge(0, 1); TStr Val; TInt AttrId(0); TStr AttrName("TestInt"); int SrcId = 0; int DstId = 1; int status = Graph->GetSAttrDatE(SrcId, DstId, AttrName, Val); EXPECT_EQ(-1, status); status = Graph->GetSAttrDatE(SrcId, DstId, AttrId, Val); EXPECT_EQ(-1, status); Graph->AddSAttrE(AttrName, atStr, AttrId); TStr TestVal("5"); Graph->AddSAttrDatE(SrcId, DstId, AttrId, TestVal); status = Graph->GetSAttrDatE(SrcId, DstId, AttrId, Val); EXPECT_EQ(0, status); EXPECT_STREQ(TestVal.CStr(), Val.CStr()); status = Graph->GetSAttrDatE(SrcId, DstId, AttrName, Val); EXPECT_EQ(0, status); EXPECT_STREQ(TestVal.CStr(), Val.CStr()); int ErrorId = 5; status = Graph->GetSAttrDatE(SrcId, ErrorId, AttrId, Val); EXPECT_EQ(-1, status); } TEST(TUndirNet, DelSAttrDatE) { PUndirNet Graph; Graph = TUndirNet::New(); Graph->AddNode(0); Graph->AddNode(1); Graph->AddEdge(0, 1); TStr IntAttr("TestInt"); TInt IntId; Graph->AddSAttrE(IntAttr, atInt, IntId); TStr FltAttr("TestFlt"); TInt FltId; Graph->AddSAttrE(FltAttr, atFlt, FltId); TStr StrAttr("TestStr"); TInt StrId; Graph->AddSAttrE(StrAttr, atStr, StrId); int SrcId = 0; int DstId = 1; int status = Graph->DelSAttrDatE(SrcId, DstId, IntAttr); EXPECT_EQ(-1, status); status = Graph->DelSAttrDatE(SrcId, DstId, IntId); EXPECT_EQ(-1, status); TInt IntVal(5); Graph->AddSAttrDatE(SrcId, DstId, IntId, IntVal); status = Graph->DelSAttrDatE(SrcId, DstId, IntAttr); EXPECT_EQ(0, status); Graph->AddSAttrDatE(SrcId, DstId, IntId, IntVal); status = Graph->DelSAttrDatE(SrcId, DstId, IntId); EXPECT_EQ(0, status); status = Graph->DelSAttrDatE(SrcId, DstId, IntId); EXPECT_EQ(-1, status); int ErrorId = 5; status = Graph->DelSAttrDatE(SrcId, ErrorId, IntId); EXPECT_EQ(-1, status); TFlt FltVal(5.0); Graph->AddSAttrDatE(SrcId, DstId, FltId, FltVal); status = Graph->DelSAttrDatE(SrcId, DstId, FltAttr); EXPECT_EQ(0, status); Graph->AddSAttrDatE(SrcId, DstId, FltId, FltVal); status = Graph->DelSAttrDatE(SrcId, DstId, FltId); EXPECT_EQ(0, status); status = Graph->DelSAttrDatE(SrcId, DstId, FltId); EXPECT_EQ(-1, status); status = Graph->DelSAttrDatE(SrcId, ErrorId, FltId); EXPECT_EQ(-1, status); TStr StrVal("5"); Graph->AddSAttrDatE(SrcId, DstId, StrId, StrVal); status = Graph->DelSAttrDatE(SrcId, DstId, StrAttr); EXPECT_EQ(0, status); Graph->AddSAttrDatE(SrcId, DstId, StrId, StrVal); status = Graph->DelSAttrDatE(SrcId, DstId, StrId); EXPECT_EQ(0, status); status = Graph->DelSAttrDatE(SrcId, DstId, StrId); EXPECT_EQ(-1, status); status = Graph->DelSAttrDatE(SrcId, ErrorId, StrId); EXPECT_EQ(-1, status); } TEST(TUndirNet, GetSAttrVE) { PUndirNet Graph; Graph = TUndirNet::New(); Graph->AddNode(0); Graph->AddNode(1); Graph->AddEdge(0, 1); TStr IntAttr("TestInt"); TInt IntId; Graph->AddSAttrE(IntAttr, atInt, IntId); TStr FltAttr("TestFlt"); TInt FltId; Graph->AddSAttrE(FltAttr, atFlt, FltId); TStr StrAttr("TestStr"); TInt StrId; Graph->AddSAttrE(StrAttr, atStr, StrId); int SrcId = 0; int DstId = 1; TInt IntVal(5); Graph->AddSAttrDatE(SrcId, DstId, IntId, IntVal); TFlt FltVal(5.0); Graph->AddSAttrDatE(SrcId, DstId, FltId, FltVal); TStr StrVal("5"); Graph->AddSAttrDatE(SrcId, DstId, StrId, StrVal); TAttrPrV AttrV; int status = Graph->GetSAttrVE(SrcId, DstId, atInt, AttrV); EXPECT_EQ(0, status); EXPECT_EQ(1, AttrV.Len()); status = Graph->GetSAttrVE(SrcId, DstId, atFlt, AttrV); EXPECT_EQ(0, status); EXPECT_EQ(1, AttrV.Len()); status = Graph->GetSAttrVE(SrcId, DstId, atStr, AttrV); EXPECT_EQ(0, status); EXPECT_EQ(1, AttrV.Len()); //status = Graph->GetSAttrVE(SrcId, DstId, atAny, AttrV); //EXPECT_EQ(0, status); //EXPECT_EQ(3, AttrV.Len()); //status = Graph->GetSAttrVE(SrcId, DstId, atUndef, AttrV); //EXPECT_EQ(0, status); //EXPECT_EQ(0, AttrV.Len()); //int ErrorId = 5; //status = Graph->GetSAttrVE(SrcId, ErrorId, atUndef, AttrV); //EXPECT_EQ(-1, status); } TEST(TUndirNet, GetIdVSAttrE) { PUndirNet Graph; Graph = TUndirNet::New(); TStr IntAttr("TestInt"); TInt IntId; Graph->AddSAttrE(IntAttr, atInt, IntId); TStr FltAttr("TestFlt"); TInt FltId; Graph->AddSAttrE(FltAttr, atFlt, FltId); TStr StrAttr("TestStr"); TInt StrId; Graph->AddSAttrE(StrAttr, atStr, StrId); TInt IntVal(0); TFlt FltVal(0); TStr StrVal("test"); Graph->AddNode(0); for (int i = 0; i < 10; i++) { Graph->AddNode(i+1); Graph->AddEdge(i, i+1); Graph->AddSAttrDatE(i, i+1, IntId, IntVal); if (i%2 == 0) { Graph->AddSAttrDatE(i, i+1, FltId, FltVal); } } Graph->AddSAttrDatE(0, 1, StrId, StrVal); TIntPrV IdV; Graph->GetIdVSAttrE(IntAttr, IdV); EXPECT_EQ(10, IdV.Len()); Graph->GetIdVSAttrE(IntId, IdV); EXPECT_EQ(10, IdV.Len()); Graph->GetIdVSAttrE(FltAttr, IdV); EXPECT_EQ(5, IdV.Len()); Graph->GetIdVSAttrE(FltId, IdV); EXPECT_EQ(5, IdV.Len()); Graph->GetIdVSAttrE(StrAttr, IdV); EXPECT_EQ(1, IdV.Len()); Graph->GetIdVSAttrE(StrId, IdV); EXPECT_EQ(1, IdV.Len()); }
28.304389
89
0.648721
qiuhere
a8e53b1094cd5350671cc22b23ca5586157c2e8a
3,698
cpp
C++
src/common/test/ProducerTest.cpp
geishm-ansto/event-formation-unit
bab9f211913ee9e633eae627ec2c2ed96ae380b4
[ "BSD-2-Clause" ]
null
null
null
src/common/test/ProducerTest.cpp
geishm-ansto/event-formation-unit
bab9f211913ee9e633eae627ec2c2ed96ae380b4
[ "BSD-2-Clause" ]
null
null
null
src/common/test/ProducerTest.cpp
geishm-ansto/event-formation-unit
bab9f211913ee9e633eae627ec2c2ed96ae380b4
[ "BSD-2-Clause" ]
null
null
null
/** Copyright (C) 2016, 2017 European Spallation Source ERIC */ #include "KafkaMocks.h" #include <common/Producer.h> #include <cstring> #include <dlfcn.h> #include <librdkafka/rdkafkacpp.h> #include <test/TestBase.h> #include <trompeloeil.hpp> using trompeloeil::_; namespace trompeloeil { template <> void reporter<specialized>::send(severity s, char const *file, unsigned long line, const char *msg) { if (s == severity::fatal) { std::ostringstream os; if (line != 0U) { os << file << ':' << line << '\n'; } throw expectation_violation(os.str() + msg); } ADD_FAILURE_AT(file, line) << msg; } } // namespace trompeloeil class ProducerStandIn : public Producer { public: ProducerStandIn(std::string Broker, std::string Topic) : Producer(Broker, Topic) {} using Producer::Config; using Producer::TopicConfig; using Producer::KafkaTopic; using Producer::KafkaProducer; }; class ProducerTest : public TestBase { void SetUp() override {} void TearDown() override {} }; TEST_F(ProducerTest, ConstructorOK) { ProducerStandIn prod{"nobroker", "notopic"}; std::vector<unsigned char> DataBuffer(10); int ret = prod.produce(DataBuffer, time(nullptr) * 1000); ASSERT_NE(prod.Config, nullptr); ASSERT_NE(prod.TopicConfig, nullptr); ASSERT_NE(prod.KafkaTopic, nullptr); ASSERT_NE(prod.KafkaProducer, nullptr); ASSERT_EQ(ret, RdKafka::ERR_NO_ERROR); ASSERT_EQ(prod.stats.dr_errors, 0); ASSERT_EQ(prod.stats.dr_noerrors, 0); ASSERT_EQ(prod.stats.ev_errors, 0); ASSERT_EQ(prod.stats.ev_others, 0); ASSERT_EQ(prod.stats.produce_fails, 0); } TEST_F(ProducerTest, CreateConfFail1) { ProducerStandIn prod{"nobroker", "notopic"}; prod.KafkaProducer.reset(nullptr); std::array<uint8_t, 10> Data; int ret = prod.produce(Data, 10); ASSERT_EQ(ret, RdKafka::ERR_UNKNOWN); } TEST_F(ProducerTest, CreateConfFail2) { ProducerStandIn prod{"nobroker", "notopic"}; prod.KafkaTopic.reset(nullptr); std::array<uint8_t, 10> Data; int ret = prod.produce(Data, 10); ASSERT_EQ(ret, RdKafka::ERR_UNKNOWN); } TEST_F(ProducerTest, ProducerFail) { ProducerStandIn prod{"nobroker", "notopic"}; auto *TempProducer = new MockProducer; RdKafka::ErrorCode ReturnValue = RdKafka::ERR__STATE; REQUIRE_CALL(*TempProducer, produce(_, _, _, _, _, _, _, _, _)) .TIMES(1) .RETURN(ReturnValue); REQUIRE_CALL(*TempProducer, poll(_)).TIMES(1).RETURN(0); prod.KafkaProducer.reset(TempProducer); std::uint8_t SomeData[20]; ASSERT_EQ(prod.stats.produce_fails, 0); int ret = prod.produce(SomeData, 999); ASSERT_EQ(ret, ReturnValue); ASSERT_EQ(prod.stats.produce_fails, 1); } TEST_F(ProducerTest, ProducerSuccess) { ProducerStandIn prod{"nobroker", "notopic"}; auto *TempProducer = new MockProducer; RdKafka::ErrorCode ReturnValue = RdKafka::ERR_NO_ERROR; REQUIRE_CALL(*TempProducer, produce(_, _, _, _, _, _, _, _, _)) .TIMES(1) .RETURN(ReturnValue); REQUIRE_CALL(*TempProducer, poll(_)).TIMES(1).RETURN(0); prod.KafkaProducer.reset(TempProducer); int NrOfBytes{200}; auto SomeData = std::make_unique<unsigned char[]>(NrOfBytes); ASSERT_EQ(prod.stats.produce_fails, 0); int ret = prod.produce({SomeData.get(), NrOfBytes}, 999); ASSERT_EQ(ret, ReturnValue); ASSERT_EQ(prod.stats.produce_fails, 0); } TEST_F(ProducerTest, ProducerFailDueToSize) { Producer prod{"nobroker", "notopic"}; auto DataPtr = std::make_unique<unsigned char>(); int ret = prod.produce({DataPtr.get(), 100000000}, 1); ASSERT_EQ(ret, RdKafka::ERR_MSG_SIZE_TOO_LARGE); } int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
30.816667
71
0.705516
geishm-ansto
a8e93e2a4975a9d849ee4be319727caeecac4483
2,279
hpp
C++
stapl_release/stapl/skeletons/transformations/coarse/reduce.hpp
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
stapl_release/stapl/skeletons/transformations/coarse/reduce.hpp
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
stapl_release/stapl/skeletons/transformations/coarse/reduce.hpp
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
/* // Copyright (c) 2000-2009, Texas Engineering Experiment Station (TEES), a // component of the Texas A&M University System. // All rights reserved. // The information and source code contained herein is the exclusive // property of TEES and may not be disclosed, examined or reproduced // in whole or in part without explicit written authorization from TEES. */ #ifndef STAPL_SKELETONS_TRANSFORMATIONS_COARSE_REDUCE_HPP #define STAPL_SKELETONS_TRANSFORMATIONS_COARSE_REDUCE_HPP #include <stapl/utility/utility.hpp> #include <stapl/skeletons/utility/tags.hpp> #include <stapl/skeletons/transformations/wrapped_skeleton.hpp> #include <stapl/skeletons/transformations/transform.hpp> #include <stapl/skeletons/transformations/optimizers/reduce.hpp> #include <stapl/skeletons/operators/compose.hpp> #include <stapl/skeletons/functional/map.hpp> namespace stapl { namespace skeletons { namespace transformations { template <typename S, typename SkeletonTag, typename CoarseTag> struct transform; ////////////////////////////////////////////////////////////////////// /// @brief A simple coarse-grain reduce can be created by first /// computing local reduction on each location and applying reduction /// on the outcome of those local reductions. /// /// @tparam S the reduce skeleton to be coarsened /// @tparam Tag type of the reduce skeleton passed in /// @tparam CoarseTag a tag to specify the required specialization for /// coarsening /// @tparam ExecutionTag a tag to specify the execution method used for /// the coarsened chunks /// /// @see skeletonsTagsCoarse /// @see skeletonsTagsExecution /// /// @ingroup skeletonsTransformationsCoarse ////////////////////////////////////////////////////////////////////// template<typename S, typename Tag, typename CoarseTag, typename ExecutionTag> struct transform<S, tags::reduce<Tag>, tags::coarse<CoarseTag, ExecutionTag>> { static auto call(S const& skeleton) STAPL_AUTO_RETURN(( skeletons::compose( skeletons::map(skeletons::wrap<ExecutionTag>(skeleton)), skeleton) )) }; } // namespace transformations } // namespace skeletons } // namespace stapl #endif // STAPL_SKELETONS_TRANSFORMATIONS_COARSE_REDUCE_HPP
34.014925
77
0.702062
parasol-ppl
a8eac0177b14ec61d8697ba1dd9f9bb537287e7b
28,744
cpp
C++
src/master/arducom-ftp.cpp
leomeyer/Arducom
b3570f14dda98da8d04a365eba1979831deb3c91
[ "MIT" ]
null
null
null
src/master/arducom-ftp.cpp
leomeyer/Arducom
b3570f14dda98da8d04a365eba1979831deb3c91
[ "MIT" ]
null
null
null
src/master/arducom-ftp.cpp
leomeyer/Arducom
b3570f14dda98da8d04a365eba1979831deb3c91
[ "MIT" ]
null
null
null
// arducom-ftp // Arducom file transfer ("FTP") master implementation // // Copyright (c) 2016 Leo Meyer, leo@leomeyer.de // Arduino communications library // Project page: https://github.com/leomeyer/Arducom // License: MIT License. For details see the project page. // required for non-ANSI function fileno #define _POSIX_C_SOURCE 200809L #include <iostream> #include <string> #include <sstream> #include <vector> #include <stdio.h> #include <exception> #include <stdexcept> #include <cstdint> #include <unistd.h> #include <algorithm> #include <functional> #include <cctype> #include <locale> #include <iomanip> #include <cstring> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <time.h> #include "../slave/lib/Arducom/Arducom.h" #include "../slave/lib/Arducom/ArducomFTP.h" #include "ArducomMaster.h" #include "ArducomMasterI2C.h" #include "ArducomMasterSerial.h" /* Trim from start */ static inline std::string& ltrim(std::string& s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace)))); return s; } /* Trim from end */ static inline std::string& rtrim(std::string& s) { s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end()); return s; } /* Trim from both ends */ static inline std::string& trim(std::string& s) { return ltrim(rtrim(s)); } /* Split string into parts at specified delimiter */ std::vector<std::string>& split(const std::string& s, char delim, std::vector<std::string>& elems) { std::stringstream ss(s); std::string item; while (std::getline(ss, item, delim)) { elems.push_back(item); } return elems; } /* Specialized parameters class */ class ArducomFTPParameters : public ArducomBaseParameters { public: uint8_t commandBase; bool continueFile; bool allowDelete; ArducomFTPParameters() : ArducomBaseParameters() { commandBase = ARDUCOM_FTP_DEFAULT_COMMANDBASE; continueFile = true; allowDelete = false; // increase the default command delay because SD card operations may be slow delayMs = 25; // set default number of retries retries = 3; } void evaluateArgument(std::vector<std::string>& args, size_t* i) override { if (args.at(*i) == "--no-continue") { continueFile = false; } else if (args.at(*i) == "--allow-delete") { allowDelete = true; } else ArducomBaseParameters::evaluateArgument(args, i); }; ArducomMasterTransport* validate() { ArducomMasterTransport* transport = ArducomBaseParameters::validate(); return transport; }; void showVersion(void) override { std::cout << this->getVersion(); exit(0); }; void showHelp(void) override { std::cout << this->getHelp(); exit(0); }; /** Returns the parameter help for this object. */ virtual std::string getHelp(void) override { std::string result; result.append(this->getVersion()); result.append("\n"); result.append(ArducomBaseParameters::getHelp()); result.append("\n"); result.append("FTP tool parameters:\n"); result.append(" --no-continue: Always overwrite existing files.\n"); result.append(" --allow-delete: Allow the (experimental) deletion of files.\n"); result.append("\n"); result.append("Examples:\n"); result.append("\n"); result.append("./arducom-ftp -t serial -d /dev/ttyUSB0 -b 115200\n"); result.append(" Connects to the Arduino at /dev/ttyUSB0.\n"); result.append(" If this command fails you perhaps need to add --initDelay 3000\n"); result.append(" to give the Arduino time to start up after the serial connect.\n"); result.append("\n"); result.append("./arducom-ftp -t i2c -d /dev/i2c-1 -a 5 -c 0\n"); result.append(" Connects to an Arduino at slave address 5 over I2C bus 1.\n"); result.append("\n"); result.append("Usage:\n"); result.append("\n"); result.append(" Enter ? on the FTP tool prompt to get help."); result.append("\n"); return result; } virtual std::string getVersion(void) { std::string result; result.append("Arducom FTP tool version 1.0\n"); result.append("Copyright (c) Leo Meyer 2015-16\n"); result.append("Build: " __DATE__ " " __TIME__ "\n"); return result; } }; /********************************************************************************/ ArducomFTPParameters parameters; std::vector<std::string> pathComponents; bool needEndl = false; // flag: cout << endl before printing messages bool interactive; // if false (piping input) errors cause immediate exit /********************************************************************************/ void execute(ArducomMaster& master, uint8_t command, std::vector<uint8_t>& payload, uint8_t expectedBytes, std::vector<uint8_t>& result, bool canRetry = false) { int8_t retries = parameters.retries; uint8_t errorInfo; while (retries >= 0) { try { uint8_t buffer[255]; uint8_t size = payload.size(); errorInfo = 0; master.execute(parameters, parameters.commandBase + command, payload.data(), &size, expectedBytes, buffer, &errorInfo); // everything ok, copy response result.clear(); for (size_t i = 0; i < size; i++) result.push_back(buffer[i]); return; } catch (const std::exception& e) { // function error (errorInfo > 0)? if (errorInfo > 0) { // convert info code to string char errorInfoStr[21]; sprintf(errorInfoStr, "%d", errorInfo); switch (errorInfo) { case ARDUCOM_FTP_SDCARD_ERROR: throw std::runtime_error((std::string("FTP error ") + errorInfoStr + ": SD card unavailable").c_str()); case ARDUCOM_FTP_SDCARD_TYPE_UNKNOWN: throw std::runtime_error((std::string("FTP error ") + errorInfoStr + ": SD card type unknown").c_str()); case ARDUCOM_FTP_FILESYSTEM_ERROR: throw std::runtime_error((std::string("FTP error ") + errorInfoStr + ": SD card file system error").c_str()); case ARDUCOM_FTP_NOT_INITIALIZED: throw std::runtime_error((std::string("FTP error ") + errorInfoStr + ": FTP system not initialized").c_str()); case ARDUCOM_FTP_MISSING_FILENAME: throw std::runtime_error((std::string("FTP error ") + errorInfoStr + ": Required file name is missing").c_str()); case ARDUCOM_FTP_NOT_A_DIRECTORY: throw std::runtime_error((std::string("FTP error ") + errorInfoStr + ": Not a directory").c_str()); case ARDUCOM_FTP_FILE_OPEN_ERROR: throw std::runtime_error((std::string("FTP error ") + errorInfoStr + ": Error opening file").c_str()); case ARDUCOM_FTP_READ_ERROR: throw std::runtime_error((std::string("FTP error ") + errorInfoStr + ": Read error").c_str()); case ARDUCOM_FTP_FILE_NOT_OPEN: throw std::runtime_error((std::string("FTP error ") + errorInfoStr + ": File not open").c_str()); case ARDUCOM_FTP_POSITION_INVALID: throw std::runtime_error((std::string("FTP error ") + errorInfoStr + ": File seek position invalid").c_str()); case ARDUCOM_FTP_CANNOT_DELETE: throw std::runtime_error((std::string("FTP error ") + errorInfoStr + ": Cannot delete this file or folder (long file name?)").c_str()); default: throw std::runtime_error((std::string("FTP error ") + errorInfoStr + ": Unknown error").c_str()); } } else { if (master.lastError == ARDUCOM_COMMAND_UNKNOWN) { throw std::runtime_error("FTP is not supported by the slave"); } } if (canRetry && (retries > 0)) { retries--; // do not print retry messages except in verbose mode if (parameters.verbose) { print_what(e); std::cout << "Retrying, " << (int)retries << " " << (retries == 1 ? "retry" : "retries") << " left..." << std::endl; } continue; } else std::throw_with_nested(std::runtime_error("Error during FTP operation")); } } // while (retries) } void printPathComponents(void) { std::vector<std::string>::const_iterator it = pathComponents.cbegin(); std::vector<std::string>::const_iterator ite = pathComponents.cend(); while (it != ite) { std::cout << *it; std::vector<std::string>::const_iterator prev_it = it; ++it; if (*prev_it != "/") std::cout << "/"; } } void prompt(void) { printPathComponents(); std::cout << "> "; } void initSlaveFAT(ArducomMaster& master, ArducomMasterTransport* transport) { std::vector<uint8_t> payload; std::vector<uint8_t> result; // send INIT message execute(master, ARDUCOM_FTP_COMMAND_INIT, payload, transport->getDefaultExpectedBytes(), result, true); struct __attribute__((packed)) CardInfo { char cardType[4]; uint8_t fatType; uint8_t size1; // size is little-endian uint8_t size2; uint8_t size3; uint8_t size4; } cardInfo; memcpy(&cardInfo, result.data(), sizeof(cardInfo)); // show card information char cardType[5]; memcpy(&cardType, &cardInfo.cardType, 4); cardType[4] = '\0'; uint32_t cardSize = (cardInfo.size1 + (cardInfo.size2 << 8) + (cardInfo.size3 << 16) + (cardInfo.size4 << 24)); std::cout << "Connected. SD card type: " << cardType << " FAT" << (int)cardInfo.fatType << " Size: " << cardSize << " MB" << std::endl; // root path component pathComponents.clear(); pathComponents.push_back("/"); } void printProgress(uint32_t total, uint32_t current, uint8_t width) { std::cout << '\r'; float val = current / (float)total; int percent = (int)(val * 100.0); std::cout << std::setw(3) << std::right << percent << "% ["; for (uint8_t i = 0; i < width; i++) { float iCur = i / (float)width; if (iCur < val) std::cout << '#'; else std::cout << ' '; } std::cout << ']'; fflush(stdout); needEndl = true; } void setParameter(std::vector<std::string> parts, bool print = true) { bool printOnly = false; if (parts.size() < 2) { printOnly = true; parts.push_back(""); // push dummy } bool found = false; if (parts.at(1) == "verbose" || printOnly) { if (parts.size() > 2) { if (parts.at(2) == "on") parameters.verbose = true; else if (parts.at(2) == "off") { parameters.verbose = false; parameters.debug = false; } else throw std::invalid_argument("Expected 'on' or 'off'"); } if (print) std::cout << "set verbose " << (parameters.verbose ? "on" : "off") << std::endl; found = true; } if (parts.at(1) == "debug" || printOnly) { if (parts.size() > 2) { if (parts.at(2) == "on") { parameters.verbose = true; parameters.debug = true; } else if (parts.at(2) == "off") parameters.debug = false; else throw std::invalid_argument("Expected 'on' or 'off'"); } if (print) std::cout << "set debug " << (parameters.debug ? "on" : "off") << std::endl; found = true; } if (parts.at(1) == "allowdelete" || printOnly) { if (parts.size() > 2) { if (parts.at(2) == "on") parameters.allowDelete = true; else if (parts.at(2) == "off") parameters.allowDelete = false; else throw std::invalid_argument("Expected 'on' or 'off'"); } if (print) std::cout << "set allowdelete " << (parameters.allowDelete ? "on" : "off") << std::endl; found = true; } if (parts.at(1) == "interactive" || printOnly) { if (parts.size() > 2) { if (parts.at(2) == "on") interactive = true; else if (parts.at(2) == "off") interactive = false; else throw std::invalid_argument("Expected 'on' or 'off'"); } if (print) std::cout << "set interactive " << (interactive ? "on" : "off") << std::endl; found = true; } if (parts.at(1) == "continue" || printOnly) { if (parts.size() > 2) { if (parts.at(2) == "on") parameters.continueFile = true; else if (parts.at(2) == "off") parameters.continueFile = false; else throw std::invalid_argument("Expected 'on' or 'off'"); } if (print) std::cout << "set continue " << (parameters.continueFile ? "on" : "off") << std::endl; found = true; } if (parts.at(1) == "retries" || printOnly) { if (parts.size() > 2) { try { int m_retries = std::stoi(parts.at(2)); if (m_retries < 0) throw std::invalid_argument(""); parameters.retries = m_retries; } catch (std::exception& e) { throw std::invalid_argument("Expected non-negative number of retries"); } } if (print) std::cout << "set retries " << parameters.retries << std::endl; found = true; } if (parts.at(1) == "delay" || printOnly) { if (parts.size() > 2) { try { long m_delayMs = std::stol(parts.at(2)); if (m_delayMs < 0) throw std::invalid_argument(""); parameters.delayMs = m_delayMs; } catch (std::exception& e) { throw std::invalid_argument("Expected non-negative delay in ms"); } } if (print) std::cout << "set delay " << parameters.delayMs << std::endl; found = true; } if (!found) throw std::invalid_argument("Parameter name unknown: " + parts.at(1)); } void printUsageHelp() { std::string result; result.append(parameters.getVersion()); result.append("\n"); result.append("FTP tool commands:\n"); result.append(" 'exit' or 'quit': Terminates the program.\n"); result.append(" 'help' or '?': Displays tool command help.\n"); result.append(" 'reset': Resets the FTP system on the device.\n"); result.append(" 'dir' or 'ls': Retrieves a list of files from the device.\n"); result.append(" 'cd <DIR>': Changes the directory. <DIR> may also be .. or /.\n"); result.append(" 'get <FILE>': Retrieves the file <FILE> from the device.\n"); result.append(" 'rm <FILE>' or 'del <FILE>': Deletes the file <FILE> from the device.\n"); result.append(" File deletion is experimental and may corrupt the file system on the device.\n"); result.append(" 'set': Displays a list of variables and their values.\n"); result.append(" 'set <VAR>': Displays the value of variable <VAR>.\n"); result.append(" 'set <VAR> <VALUE>': Sets the variable <VAR> to <VALUE>.\n"); result.append("\n"); result.append("FTP tool variables:\n"); result.append(" 'verbose': Output internal information. Corresponds to command setting -v.\n"); result.append(" 'debug': Output technical information. Corresponds to command setting -vv.\n"); result.append(" 'retries': Number of retries on error. Corresponds to command setting -x.\n"); result.append(" 'delay': Command delay in milliseconds. Corresponds to command setting -l.\n"); result.append(" 'allowdelete': If 'on', allows the experimental deletion of files.\n"); result.append(" 'continue': If 'on', appends content to partially downloaded files.\n"); result.append(" If 'off', files are always overwritten completely.\n"); result.append(" 'interactive': Specifies program behavior for batch or interactive mode.\n"); result.append(" This flag is set to 'on' if the program is started from a TTY, and to 'off'\n"); result.append(" if input is being piped to the program. Normally you should not change this.\n"); std::cout << result; } int main(int argc, char *argv[]) { std::vector<std::string> args; ArducomBaseParameters::convertCmdLineArgs(argc, argv, args); try { interactive = isatty(fileno(stdin)); parameters.setFromArguments(args); ArducomMasterTransport* transport = parameters.validate(); // initialize protocol ArducomMaster master(transport); std::vector<uint8_t> payload; std::vector<uint8_t> result; initSlaveFAT(master, transport); // command loop while (std::cin.good()) { prompt(); try { std::string command; getline(std::cin, command); // stdin is a file or a pipe? if (!isatty(fileno(stdin))) // print non-interactive command (for debugging) std::cout << command << std::endl; command = trim(command); // split command std::vector<std::string> parts; split(command, ' ', parts); if (parts.size() == 0) continue; else if ((parts.at(0) == "help") || (parts.at(0) == "?")) printUsageHelp(); else if ((parts.at(0) == "quit") || (parts.at(0) == "exit")) break; else if (parts.at(0) == "reset") { initSlaveFAT(master, transport); } else if ((parts.at(0) == "ls") || (parts.at(0) == "dir")) { // directory listing data structure struct __attribute__((packed)) FileInfo { char name[13]; uint8_t isDir; uint8_t size1; // size is little-endian uint8_t size2; uint8_t size3; uint8_t size4; uint8_t lastWriteDate1; uint8_t lastWriteDate2; uint8_t lastWriteTime1; uint8_t lastWriteTime2; } fileInfo; std::vector<FileInfo> fileInfos; payload.clear(); // no payload // rewind directory execute(master, ARDUCOM_FTP_COMMAND_REWIND, payload, transport->getDefaultExpectedBytes(), result, true); while (true) { // list next file execute(master, ARDUCOM_FTP_COMMAND_LISTFILES, payload, transport->getDefaultExpectedBytes(), result); // record received? if (result.size() > 0) { memcpy(&fileInfo, result.data(), sizeof(fileInfo)); fileInfos.push_back(fileInfo); } else // no data - end of list break; } std::cout << std::endl; size_t totalDirs = 0; size_t totalFiles = 0; uint32_t totalSize = 0; // display file infos std::vector<FileInfo>::iterator it = fileInfos.begin(); std::vector<FileInfo>::iterator ite = fileInfos.end(); while (it != ite) { fileInfo = *it; fileInfo.name[12] = '\0'; // make sure there's no garbage std::cout << std::setfill(' ') << std::setw(16) << std::left << fileInfo.name; std::cout << std::setw(16) << std::right; if (fileInfo.isDir) { std::cout << "<DIR>"; totalDirs++; } else { uint32_t fileSize = (fileInfo.size1 + (fileInfo.size2 << 8) + (fileInfo.size3 << 16) + (fileInfo.size4 << 24)); std::cout << fileSize; totalFiles++; totalSize += fileSize; } int fatDate = fileInfo.lastWriteDate1 + (fileInfo.lastWriteDate2 << 8); int fatTime = fileInfo.lastWriteTime1 + (fileInfo.lastWriteTime2 << 8); int year = 1980 + (fatDate >> 9); int month = (fatDate >> 5) & 0XF; int day = fatDate & 0X1F; int hour = fatTime >> 11; int minute = (fatTime >> 5) & 0X3F; int second = 2*(fatTime & 0X1F); std::string timezoneName = "UTC"; // convert time to UTC timestamp struct tm utc_tm; utc_tm.tm_year = year; utc_tm.tm_mon = month; utc_tm.tm_mday = day; utc_tm.tm_hour = hour; utc_tm.tm_min = minute; utc_tm.tm_sec = second; utc_tm.tm_isdst = 0; time_t utc_time = mktime(&utc_tm); if (utc_time >= 0) { // convert to local time struct tm local_tm = *gmtime(&utc_time); year = local_tm.tm_year; month = local_tm.tm_mon; day = local_tm.tm_mday; hour = local_tm.tm_hour; minute = local_tm.tm_min; second = local_tm.tm_sec; timezoneName = "local"; } std::cout << " " << std::setfill('0') << std::setw(4) << year; std::cout << "-" << std::setfill('0') << std::setw(2) << month; std::cout << "-" << std::setfill('0') << std::setw(2) << day; std::cout << " " << std::setfill('0') << std::setw(2) << hour; std::cout << ":" << std::setfill('0') << std::setw(2) << minute; std::cout << ":" << std::setfill('0') << std::setw(2) << second; std::cout << " " << timezoneName << std::endl; ++it; } std::cout << std::setfill(' ') << std::endl; std::cout << std::setw(8) << std::right << totalFiles << " file(s),"; std::cout << std::setw(15) << std::right << totalSize << " bytes total" << std::endl; std::cout << std::setw(8) << std::right << totalDirs << " folder(s) " << std::endl; } else if (parts.at(0) == "set") { setParameter(parts); } else if (parts.at(0) == "cd") { if (parts.size() == 1) { printPathComponents(); std::cout << std::endl; } else if (parts.size() > 2) { std::cout << "Invalid input: cd expects only one argument" << std::endl; } else { bool exec = true; // cd into root? if (parts.at(1)[0] == '/') { pathComponents.clear(); } else // cd up? if (parts.at(1) == "..") { exec = false; // only if we're at least one level down if (pathComponents.size() > 1) { // start at root, cd into sub directories std::vector<std::string> pathComps = pathComponents; pathComponents.clear(); for (size_t p = 0; p < pathComps.size() - 1; p++) { payload.clear(); // send command to change directory for (size_t i = 0; i < pathComps.at(p).length(); i++) payload.push_back(pathComps.at(p)[i]); execute(master, ARDUCOM_FTP_COMMAND_CHDIR, payload, transport->getDefaultExpectedBytes(), result); pathComponents.push_back(pathComps.at(p)); } } } else // cd to local directory? if (parts.at(1) == ".") { // no need to execute exec = false; } if (exec) { payload.clear(); // send command to change directory for (size_t i = 0; i < parts.at(1).length(); i++) payload.push_back(parts.at(1)[i]); execute(master, ARDUCOM_FTP_COMMAND_CHDIR, payload, transport->getDefaultExpectedBytes(), result); /* char dirname[13]; size_t dirlen = result.size(); if (dirlen > 12) dirlen = 12; std::cout << dirlen << std::endl; memcpy(dirname, result.data(), dirlen); dirname[dirlen] = '\0'; */ // store current directory name pathComponents.push_back(parts.at(1)); } } } else if (parts.at(0) == "get") { if (parts.size() == 1) { std::cout << "Invalid input: get expects a file name as argument" << std::endl; } else if (parts.size() > 2) { std::cout << "Invalid input: get expects only one argument" << std::endl; } else { payload.clear(); // send command to open the file for (size_t i = 0; i < parts.at(1).length(); i++) payload.push_back(parts.at(1)[i]); execute(master, ARDUCOM_FTP_COMMAND_OPENREAD, payload, transport->getDefaultExpectedBytes(), result, true); // the result is the file size if (result.size() < 4) { std::cout << "Error: device did not send a proper file size" << std::endl; } else { struct __attribute__((packed)) FileSize { uint8_t size1; // size is little-endian uint8_t size2; uint8_t size3; uint8_t size4; } fileSize; memcpy(&fileSize, result.data(), sizeof(fileSize)); int32_t totalSize = (fileSize.size1 + (fileSize.size2 << 8) + (fileSize.size3 << 16) + (fileSize.size4 << 24)); std::cout << "File size: " << totalSize << " bytes" << std::endl; if (totalSize < 0) { std::cout << "File size is negative, cannot download" << std::endl; continue; // next command } int fd; int32_t position = -1; bool fileExists = false; // check whether the file already exists on the master if (access(parts.at(1).c_str(), F_OK) != -1) { fileExists = true; // open local file for reading fd = open(parts.at(1).c_str(), O_RDONLY); if (fd < 0) { throw std::runtime_error((std::string("Unable to read output file: ") + parts.at(1)).c_str()); } // get file size; this is the position to continue reading from struct stat st; if (stat(parts.at(1).c_str(), &st) == 0) position = st.st_size; else { throw std::runtime_error((std::string("Unable to get file size: ") + parts.at(1)).c_str()); } close(fd); } // overwrite or continue? if (parameters.continueFile && (position >= 0) && (position < totalSize)) { std::cout << "Appending data to existing file (to overwrite, use 'set continue off')" << std::endl; // open local file for appending fd = open(parts.at(1).c_str(), O_APPEND | O_WRONLY, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); if (fd < 0) { throw std::runtime_error((std::string("Unable to create output file: ") + parts.at(1)).c_str()); } } else { if (fileExists) { if (!interactive) { std::cout << "Cannot overwrite in non-interactive mode; cancelling" << std::endl; continue; } else { // interactive std::cout << "Overwrite existing file y/N (to append data, use 'set continue on')? "; std::string input; getline(std::cin, input); if (input != "y") { std::cout << "Download cancelled" << std::endl; continue; } } } // open local file for writing; create from scratch fd = open(parts.at(1).c_str(), O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); if (fd < 0) { throw std::runtime_error((std::string("Unable to create output file: ") + parts.at(1)).c_str()); } // start downloading from beginning position = 0; } std::cout << "Remaining: " << totalSize - position << " bytes" << std::endl; if (totalSize - position == 0) { std::cout << "File seems to be complete" << std::endl; continue; // next command } // file read loop while (true) { // send current seek position payload.clear(); payload.push_back((uint8_t)position); payload.push_back((uint8_t)(position >> 8)); payload.push_back((uint8_t)(position >> 16)); payload.push_back((uint8_t)(position >> 24)); // this command can be resent in case of errors (idempotent) execute(master, ARDUCOM_FTP_COMMAND_READFILE, payload, transport->getDefaultExpectedBytes(), result, true); position += result.size(); // write data to local file write(fd, result.data(), result.size()); // show "progress bar" only in interactive mode if (interactive) printProgress(totalSize, position, 50); if (position >= totalSize) break; } std::cout << std::endl; needEndl = false; // send command to close the file payload.clear(); execute(master, ARDUCOM_FTP_COMMAND_CLOSEFILE, payload, transport->getDefaultExpectedBytes(), result, true); // close local file close(fd); std::cout << "Download complete." << std::endl; } } } else if ((parts.at(0) == "rm") || (parts.at(0) == "del")) { if (parts.size() == 1) { std::cout << "Invalid input: rm and del expect a file name as argument" << std::endl; } else if (parts.size() > 2) { std::cout << "Invalid input: rm and del expect only one argument" << std::endl; } else { if (!parameters.allowDelete) { std::cout << "Warning: Deleting files is possibly buggy and can corrupt your SD card!" << std::endl; std::cout << "'Type 'set allowdelete on' if you want to delete anyway." << std::endl; } else { payload.clear(); // send command to delete the file for (size_t i = 0; i < parts.at(1).length(); i++) payload.push_back(parts.at(1)[i]); execute(master, ARDUCOM_FTP_COMMAND_DELETE, payload, transport->getDefaultExpectedBytes(), result); } } } else { std::cout << "Unknown command: " << parts.at(0) << std::endl; } } catch (const std::exception& e) { if (needEndl) std::cout << std::endl; needEndl = false; print_what(e); // non-interactive mode causes immediate exit on errors // this way an exit code can be queried by scripts if (!interactive) exit(master.lastError); } } // while (true) } catch (const std::exception& e) { if (needEndl) std::cout << std::endl; needEndl = false; print_what(e); exit(1); } return 0; }
34.883495
172
0.590141
leomeyer
a8ee46ac398124846ee24f2ebb561886f50299ed
1,652
cpp
C++
src/cylbot_map_creator/src/likelihood_field_server.cpp
rhololkeolke/eecs_600_robot_project1
8a4a567f436d2d26311b53cc2dcfde61d98e45e0
[ "BSD-3-Clause" ]
null
null
null
src/cylbot_map_creator/src/likelihood_field_server.cpp
rhololkeolke/eecs_600_robot_project1
8a4a567f436d2d26311b53cc2dcfde61d98e45e0
[ "BSD-3-Clause" ]
1
2015-08-22T13:33:39.000Z
2015-08-23T23:01:57.000Z
src/cylbot_map_creator/src/likelihood_field_server.cpp
rhololkeolke/eecs_600_robot_project1
8a4a567f436d2d26311b53cc2dcfde61d98e45e0
[ "BSD-3-Clause" ]
null
null
null
#include <ros/ros.h> #include <cylbot_map_creator/LikelihoodField.h> #include <yaml-cpp/yaml.h> #include <vector> #include <string> int main(int argc, char** argv) { ros::init(argc, argv, "likelihood_field_server"); ros::NodeHandle nh; ros::NodeHandle priv_nh("~"); std::string field_file = ""; priv_nh.getParam("field_file", field_file); ros::Publisher field_pub = nh.advertise<cylbot_map_creator::LikelihoodField>("/likelihood_field", 1, true); cylbot_map_creator::LikelihoodField field_msg; field_msg.header.frame_id = "/map"; field_msg.header.stamp = ros::Time::now(); YAML::Node yaml_file = YAML::LoadFile(field_file.c_str()); field_msg.info.resolution = yaml_file["info"]["resolution"].as<double>(); field_msg.info.width = yaml_file["info"]["width"].as<int>(); field_msg.info.height = yaml_file["info"]["height"].as<int>(); field_msg.info.origin.position.x = yaml_file["info"]["origin"]["position"]["x"].as<double>(); field_msg.info.origin.position.y = yaml_file["info"]["origin"]["position"]["y"].as<double>(); field_msg.info.origin.position.z = yaml_file["info"]["origin"]["position"]["z"].as<double>(); field_msg.info.origin.orientation.x = yaml_file["info"]["origin"]["orientation"]["x"].as<double>(); field_msg.info.origin.orientation.y = yaml_file["info"]["origin"]["orientation"]["y"].as<double>(); field_msg.info.origin.orientation.z = yaml_file["info"]["origin"]["orientation"]["z"].as<double>(); field_msg.info.origin.orientation.w = yaml_file["info"]["origin"]["orientation"]["w"].as<double>(); field_msg.data = yaml_file["data"].as<std::vector<double> >(); field_pub.publish(field_msg); ros::spin(); }
41.3
108
0.70339
rhololkeolke
a8f2015b9985470a086cc872834690a361108657
4,570
cpp
C++
apps/2d/mhd/rotated_alfven/SetBndValues.cpp
dcseal/finess
766e583ae9e84480640c7c3b3c157bf40ab87fe4
[ "BSD-3-Clause" ]
null
null
null
apps/2d/mhd/rotated_alfven/SetBndValues.cpp
dcseal/finess
766e583ae9e84480640c7c3b3c157bf40ab87fe4
[ "BSD-3-Clause" ]
null
null
null
apps/2d/mhd/rotated_alfven/SetBndValues.cpp
dcseal/finess
766e583ae9e84480640c7c3b3c157bf40ab87fe4
[ "BSD-3-Clause" ]
null
null
null
#include <cmath> #include "IniParams.h" #include "tensors.h" #include "StateVars.h" #include "app_util.h" inline double A3_original_to_periodic(int i, int j, double A3_original){ using std::sin; using std::cos; double xlow = global_ini_params.get_xlow(); double ylow = global_ini_params.get_ylow(); double dx = global_ini_params.get_dx(); double dy = global_ini_params.get_dy(); double angle = global_ini_params.get_angle(); double x, y; ij_to_xy(xlow, ylow, dx, dy, i, j, x, y); return A3_original - (-x * sin(angle) + y * cos(angle)); } inline double A3_periodic_to_original(int i, int j, double A3_periodic){ using std::sin; using std::cos; double xlow = global_ini_params.get_xlow(); double ylow = global_ini_params.get_ylow(); double dx = global_ini_params.get_dx(); double dy = global_ini_params.get_dy(); double angle = global_ini_params.get_angle(); double x, y; ij_to_xy(xlow, ylow, dx, dy, i, j, x, y); return A3_periodic + (-x * sin(angle) + y * cos(angle)); } // This is a user-supplied routine that sets the the boundary conditions // // Double periodic // void SetBndValues( StateVars& Q ) { using std::cos; using std::sin; dTensorBC3& q = Q.ref_q(); dTensorBC3& aux = Q.ref_aux(); const int mx = q.getsize(1); const int my = q.getsize(2); const int meqn = q.getsize(3); const int mbc = q.getmbc(); const int maux = aux.getsize(3); double xlow = global_ini_params.get_xlow(); double ylow = global_ini_params.get_ylow(); double dx = global_ini_params.get_dx(); double dy = global_ini_params.get_dy(); double angle = global_ini_params.get_angle(); double t = Q.get_t(); // ----------------------- // BOUNDARY CONDITION LOOP // ----------------------- // *********************************************** // LEFT BOUNDARY // *********************************************** for(int i=0; i>=(1-mbc); i--) { for(int j=1; j<=my; j++) { // q values for(int m=1; m<=meqn; m++) { double tmp = q.get(mx + i,j,m); q.set(i,j,m, tmp ); } aux.set(i, j, 1, A3_periodic_to_original(i, j, A3_original_to_periodic(mx + i, j, aux.get(mx + i, j, 1)))); } } // *********************************************** // *********************************************** // RIGHT BOUNDARY // *********************************************** for(int i=(mx+1); i<=(mx+mbc); i++) { for(int j=1; j<=my; j++) { // q values for(int m=1; m<=meqn; m++) { double tmp = q.get(i - mx,j,m); q.set(i,j,m, tmp ); } aux.set(i, j, 1, A3_periodic_to_original(i, j, A3_original_to_periodic(i - mx, j, aux.get(i - mx, j, 1)))); } } // *********************************************** // *********************************************** // BOTTOM BOUNDARY // *********************************************** for(int j=0; j>=(1-mbc); j--) { for(int i=1-mbc; i<=mx+mbc; i++) { // q values for(int m=1; m<=meqn; m++) { double tmp = q.get(i,my + j,m); q.set(i,j,m, tmp ); } aux.set(i, j, 1, A3_periodic_to_original(i, j, A3_original_to_periodic(i, my + j, aux.get(i, my + j, 1)))); } } // *********************************************** // *********************************************** // TOP BOUNDARY // *********************************************** for(int j=(my+1); j<=(my+mbc); j++) { for(int i=1-mbc; i<=mx+mbc; i++) { // q values for(int m=1; m<=meqn; m++) { double tmp = q.get(i,j - my,m); q.set(i,j,m, tmp ); } aux.set(i, j, 1, A3_periodic_to_original(i, j, A3_original_to_periodic(i, j - my, aux.get(i, j - my, 1)))); } } // *********************************************** } void SetBndValuesX( StateVars& Q ) {SetBndValues(Q);} void SetBndValuesY( StateVars& Q ) {SetBndValues(Q);}
27.365269
84
0.417943
dcseal
5ef22ff91aec9f8c9a014c91b8f85944407c0115
893
cpp
C++
src/storage/appstatedb.cpp
nunchuk-io/libnunchuk
4d29efe25b5ba3b392ebebc31e58b43daa96560e
[ "MIT" ]
44
2020-11-13T19:34:31.000Z
2022-03-03T18:06:45.000Z
src/storage/appstatedb.cpp
nunchuk-io/libnunchuk
4d29efe25b5ba3b392ebebc31e58b43daa96560e
[ "MIT" ]
13
2020-12-03T17:27:23.000Z
2022-03-01T02:16:28.000Z
src/storage/appstatedb.cpp
nunchuk-io/libnunchuk
4d29efe25b5ba3b392ebebc31e58b43daa96560e
[ "MIT" ]
7
2020-11-25T08:23:48.000Z
2022-02-22T10:36:42.000Z
// Copyright (c) 2020 Enigmo // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "appstatedb.h" namespace nunchuk { void NunchukAppStateDb::Init() { CreateTable(); } int NunchukAppStateDb::GetChainTip() const { return GetInt(DbKeys::CHAIN_TIP); } bool NunchukAppStateDb::SetChainTip(int value) { return PutInt(DbKeys::CHAIN_TIP, value); } std::string NunchukAppStateDb::GetSelectedWallet() const { return GetString(DbKeys::SELECTED_WALLET); } bool NunchukAppStateDb::SetSelectedWallet(const std::string& value) { return PutString(DbKeys::SELECTED_WALLET, value); } int64_t NunchukAppStateDb::GetStorageVersion() const { return GetInt(DbKeys::VERSION); } bool NunchukAppStateDb::SetStorageVersion(int64_t value) { return PutInt(DbKeys::VERSION, value); } } // namespace nunchuk
27.060606
80
0.764838
nunchuk-io
5ef539e73db3d1a9fe40c316b995530498fb6af3
194
cpp
C++
atcoder/abc116_a.cpp
cosmicray001/Online_judge_Solutions-
5dc6f90d3848eb192e6edea8e8c731f41a1761dd
[ "MIT" ]
3
2018-01-08T02:52:51.000Z
2021-03-03T01:08:44.000Z
atcoder/abc116_a.cpp
cosmicray001/Online_judge_Solutions-
5dc6f90d3848eb192e6edea8e8c731f41a1761dd
[ "MIT" ]
null
null
null
atcoder/abc116_a.cpp
cosmicray001/Online_judge_Solutions-
5dc6f90d3848eb192e6edea8e8c731f41a1761dd
[ "MIT" ]
1
2020-08-13T18:07:35.000Z
2020-08-13T18:07:35.000Z
#include <bits/stdc++.h> using namespace std; int n[4]; int main(){ for(int i= 0; i < 3; i++){ scanf("%d", &n[i]); } sort(n, n + 3); cout << (n[0] * n[1]) / 2 << endl; return 0; }
16.166667
36
0.469072
cosmicray001
5efa6dc76165da7ec08042ea40e80f0cef03ceb1
568
cpp
C++
leetcode/968. Binary Tree Cameras/s2.cpp
zhuohuwu0603/leetcode_cpp_lzl124631x
6a579328810ef4651de00fde0505934d3028d9c7
[ "Fair" ]
787
2017-05-12T05:19:57.000Z
2022-03-30T12:19:52.000Z
leetcode/968. Binary Tree Cameras/s2.cpp
aerlokesh494/LeetCode
0f2cbb28d5a9825b51a8d3b3a0ae0c30d7ff155f
[ "Fair" ]
8
2020-03-16T05:55:38.000Z
2022-03-09T17:19:17.000Z
leetcode/968. Binary Tree Cameras/s2.cpp
aerlokesh494/LeetCode
0f2cbb28d5a9825b51a8d3b3a0ae0c30d7ff155f
[ "Fair" ]
247
2017-04-30T15:07:50.000Z
2022-03-30T09:58:57.000Z
// OJ: https://leetcode.com/problems/binary-tree-cameras/ // Author: github.com/lzl124631x // Time: O(N) // Space: O(logN) class Solution { private: int ans = 0; int postorder(TreeNode *root) { if (!root) return 1; int left = postorder(root->left); int right = postorder(root->right); if (left == 0 || right == 0) { ++ans; return 2; } else return left == 2 || right == 2 ? 1 : 0; } public: int minCameraCover(TreeNode* root) { return postorder(root) == 0 ? ans + 1 : ans; } };
27.047619
57
0.538732
zhuohuwu0603
5efdd863cb351fa9f374bb229d969fbde03ea2cd
2,918
cc
C++
src/third_party/starboard/rdk/shared/main_rdk.cc
rmaddali991/rdk-cobalt
b2f08a80c136be75295338aeb71895d06bb6d374
[ "Apache-2.0" ]
1
2022-01-25T21:22:47.000Z
2022-01-25T21:22:47.000Z
src/third_party/starboard/rdk/shared/main_rdk.cc
rmaddali991/rdk-cobalt
b2f08a80c136be75295338aeb71895d06bb6d374
[ "Apache-2.0" ]
null
null
null
src/third_party/starboard/rdk/shared/main_rdk.cc
rmaddali991/rdk-cobalt
b2f08a80c136be75295338aeb71895d06bb6d374
[ "Apache-2.0" ]
1
2021-09-14T22:35:29.000Z
2021-09-14T22:35:29.000Z
// // Copyright 2020 Comcast Cable Communications Management, LLC // // 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. // // SPDX-License-Identifier: Apache-2.0 // // Copyright 2016 The Cobalt 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 <gst/gst.h> #include <signal.h> #include "starboard/configuration.h" #include "starboard/shared/signal/crash_signals.h" #include "starboard/shared/signal/suspend_signals.h" #include "third_party/starboard/rdk/shared/application_rdk.h" namespace third_party { namespace starboard { namespace rdk { namespace shared { static struct sigaction old_actions[2]; static void RequestStop(int signal_id) { SbSystemRequestStop(0); } static void InstallStopSignalHandlers() { struct sigaction action = {0}; action.sa_handler = RequestStop; action.sa_flags = 0; ::sigemptyset(&action.sa_mask); ::sigaction(SIGINT, &action, &old_actions[0]); ::sigaction(SIGTERM, &action, &old_actions[1]); } static void UninstallStopSignalHandlers() { ::sigaction(SIGINT, &old_actions[0], NULL); ::sigaction(SIGTERM, &old_actions[1], NULL); } } // namespace shared } // namespace rdk } // namespace starboard } // namespace third_party extern "C" SB_EXPORT_PLATFORM int main(int argc, char** argv) { tzset(); GError* error = NULL; gst_init_check(NULL, NULL, &error); g_free(error); // starboard::shared::signal::InstallCrashSignalHandlers(); starboard::shared::signal::InstallSuspendSignalHandlers(); third_party::starboard::rdk::shared::InstallStopSignalHandlers(); third_party::starboard::rdk::shared::Application application; int result = application.Run(argc, argv); third_party::starboard::rdk::shared::UninstallStopSignalHandlers(); // starboard::shared::signal::UninstallCrashSignalHandlers(); starboard::shared::signal::UninstallSuspendSignalHandlers(); gst_deinit(); return result; }
31.717391
75
0.745716
rmaddali991
6f01fdd29d35bd789567ccff1060a27e0f159cca
1,735
cpp
C++
mycontainer1.cpp
bruennijs/ise.cppworkshop
c54a60ad3468f83aeb45b347657b3f246d7190cc
[ "MIT" ]
null
null
null
mycontainer1.cpp
bruennijs/ise.cppworkshop
c54a60ad3468f83aeb45b347657b3f246d7190cc
[ "MIT" ]
null
null
null
mycontainer1.cpp
bruennijs/ise.cppworkshop
c54a60ad3468f83aeb45b347657b3f246d7190cc
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <list> class MoveableString { public: MoveableString() { } ~MoveableString() { } std::string m_data; }; class Moveable { public: Moveable() { std::cout << "Moveable" << std::endl; this->m_data = new char[1024]; } ~Moveable() { std::cout << "~Moveable" << std::endl; if (this->m_data != nullptr) { delete this->m_data; } } Moveable& operator=(const Moveable& assign) { std::cout << "Moveable lvalue assigmnent" << std::endl; } /* Moveable& operator=(Moveable&& assign) { std::cout << "Moveable rvalue assigmnent" << std::endl; } */ char* m_data; }; /* template<typename E> class MyVector { public: MyVector() {} ~MyVector() { std::cout << "~MyVector" << std::endl; } MyVector(const MyVector<E>& v) : m_val(v.m_val) std::cout << "MyVector(copy)" << std::endl; } MyVector<E>& operator=(const MyVector<E> && v) { std::cout << "MyVector(copy)" << std::endl; } MyVector<E>& operator+(const MyVector<E>& obj) { std::cout << "operator+" << std::endl; this->m_val += obj.m_val; } std::list<Moveable> m_dl; }; */ template<typename E> class MyContainer { public: MyContainer() { std::cout << "MyContainer" << std::endl; } ~MyContainer() { std::cout << "~MyContainer" << std::endl; } MyContainer(const MyContainer<E>& v) : m_data(v.m_data) { std::cout << "MyContainer(copy)" << std::endl; } MyContainer<E>& operator=(const MyContainer<E> & v) { std::cout << "MyContainer assignment" << std::endl; this->m_data = v.m_data; } /* data */ E m_data; }; int main() { MyContainer<Moveable> v1; MyContainer<Moveable> v3; MyContainer<Moveable> v2 = v1; //MyVector<Moveable> v3 = v1 + v2; }
14.338843
57
0.607493
bruennijs
6f0583fb92fc213e0c3ef6a0da283695a4f5f0ce
813
cpp
C++
sample/read_async_temperature.cpp
uilianries/BeagleBoneBlackGPIO
bbd4137ca2b5b2e506321bf440ba87370764646b
[ "MIT" ]
6
2016-03-11T16:48:16.000Z
2021-06-05T11:38:48.000Z
sample/read_async_temperature.cpp
uilianries/BeagleBoneBlackGPIO
bbd4137ca2b5b2e506321bf440ba87370764646b
[ "MIT" ]
9
2016-03-03T17:31:57.000Z
2018-01-11T23:00:55.000Z
sample/read_async_temperature.cpp
uilianries/BeagleBoneBlackGPIO
bbd4137ca2b5b2e506321bf440ba87370764646b
[ "MIT" ]
null
null
null
/** * \file * \brief Give DS1820 thermal sensor as stream * * \author Uilian Ries <uilianries@gmail.com> */ #include <iostream> #include <string> #include <chrono> #include <thread> #include "bbbgpio/stream.hpp" /** * \brief Get temperature events */ struct observer { /** * \brief Callback to read the temperature level * \param level current temperature */ void operator()(const bbb::gpio::thermal_level_type& level) const { std::cout << "TEMPERATURE LEVEL: " << level << std::endl; } }; /** * \brief Main */ int main() { bbb::gpio::thermal_stream thermal_stream; observer local_observer; thermal_stream.delegate_event(local_observer); auto limit = std::chrono::seconds(10); std::this_thread::sleep_for(limit); return EXIT_SUCCESS; }
19.357143
69
0.653137
uilianries
6f08ad7f772de4bac4598f6d7ae02cd456c0dc62
1,057
cpp
C++
TicTacToeMinMax/Field.cpp
SzymonOzog/TicTacToeCustomSizeMinMax
095cf6037c23a421c1d97b93901f17d0c3562137
[ "CC0-1.0" ]
null
null
null
TicTacToeMinMax/Field.cpp
SzymonOzog/TicTacToeCustomSizeMinMax
095cf6037c23a421c1d97b93901f17d0c3562137
[ "CC0-1.0" ]
null
null
null
TicTacToeMinMax/Field.cpp
SzymonOzog/TicTacToeCustomSizeMinMax
095cf6037c23a421c1d97b93901f17d0c3562137
[ "CC0-1.0" ]
null
null
null
#include "Field.h" #include "WinChecker.h" #include <cmath> Field::Field(int side) { pointsNeededToWin = side < 4 ? side : 4; fieldSide = side; winCheckers.push_back(new RowChecker(this)); winCheckers.push_back(new ColumnChecker(this)); winCheckers.push_back(new ForwardDiagonalChecker(this)); winCheckers.push_back(new BackwardDiagonalChecker(this)); int size = side * side; vecField.reserve(size); while (size--) vecField.emplace_back(player::None); } bool Field::isCoordWorthChecking(int coord) { int row = getRow(coord); int column = getColumn(coord); for (int y = row - 2; y <= row + 2; y++) for (int x = column - 2; x <= column + 2; x++) if (isCoordTaken(y, x)) return true; return false; } bool Field::hasWon() { for (auto winChecker : winCheckers) if (winChecker->checkAllLines()) return true; return false; } bool Field::hasWon(int i) { for (auto winChecker : winCheckers) if (winChecker->checkForWin(i)) return true; return false; } void Field::nullify() { for (auto& p : vecField) p = player::None; }
21.14
58
0.687796
SzymonOzog
6f0a32403df1da2bd17ecb83d1fd18c84ac0d6c1
13,696
cpp
C++
Src/MainLib/InterceptPluginInstance.cpp
vinjn/glintercept
f82166d3a774bfb02459f6b3ae2a03d4c9eaf64f
[ "MIT" ]
468
2015-04-13T19:03:57.000Z
2022-03-23T00:11:24.000Z
Src/MainLib/InterceptPluginInstance.cpp
vinjn/glintercept
f82166d3a774bfb02459f6b3ae2a03d4c9eaf64f
[ "MIT" ]
12
2015-05-25T11:15:21.000Z
2020-10-26T02:46:50.000Z
Src/MainLib/InterceptPluginInstance.cpp
vinjn/glintercept
f82166d3a774bfb02459f6b3ae2a03d4c9eaf64f
[ "MIT" ]
67
2015-04-22T13:22:48.000Z
2022-03-05T01:11:02.000Z
/*============================================================================= GLIntercept - OpenGL intercept/debugging tool Copyright (C) 2004 Damian Trebilco Licensed under the MIT license - See Docs\license.txt for details. =============================================================================*/ #include "InterceptPluginInstance.h" #include "InterceptPluginManager.h" #include "InterceptPluginDLLInstance.h" #include "GLDriver.h" #include <stdarg.h> #include <string.h> //The real OpenGL driver extern GLCoreDriver GLV; extern WGLDriver GLW; USING_ERRORLOG //A dummy interface - assigned when the plugin has to be unloaded but the // interface cannot be destroyed. class DummyPluginInterface : public InterceptPluginInterface { public: DummyPluginInterface(){}; virtual void GLIAPI GLFunctionPre (uint userIndex, const char *funcName, uint funcIndex, const FunctionArgs & args ) {}; virtual void GLIAPI GLFunctionPost(uint userIndex, const char *funcName, uint funcIndex, const FunctionRetValue & retVal) {}; virtual void GLIAPI GLFrameEndPre(const char *funcName, uint funcIndex, const FunctionArgs & args ) {}; virtual void GLIAPI GLFrameEndPost(const char *funcName, uint funcIndex, const FunctionRetValue & retVal) {}; virtual void GLIAPI GLRenderPre (const char *funcName, uint funcIndex, const FunctionArgs & args ) {}; virtual void GLIAPI GLRenderPost(const char *funcName, uint funcIndex, const FunctionRetValue & retVal) {}; virtual void GLIAPI OnGLError(const char *funcName, uint funcIndex) {}; virtual void GLIAPI OnGLContextCreate(HGLRC rcHandle) {}; virtual void GLIAPI OnGLContextDelete(HGLRC rcHandle) {}; virtual void GLIAPI OnGLContextSet(HGLRC oldRCHandle, HGLRC newRCHandle) {}; virtual void GLIAPI OnGLContextShareLists(HGLRC srcHandle, HGLRC dstHandle) {}; virtual void GLIAPI Destroy() { delete this; } }; /////////////////////////////////////////////////////////////////////////////// // InterceptPluginInstance::InterceptPluginInstance(InterceptPluginManager *manager, GLDriver *ogldriver,InterceptPluginDLLInstance *newDLLInstance): driver(ogldriver), pluginManager(manager), contextFunctionCalls(true), hasRegisteredFunctions(false), gliPlugin(NULL), dllInstance(newDLLInstance) { } /////////////////////////////////////////////////////////////////////////////// // InterceptPluginInstance::~InterceptPluginInstance() { //Destroy the plugin if(gliPlugin) { //Ensure destroy is not called twice InterceptPluginInterface *destroyPlugin = gliPlugin; gliPlugin = NULL; destroyPlugin->Destroy(); } //Destroy the plugin loader (needs to be done after the plugin is destroyed) if(dllInstance) { dllInstance->ReleaseReference(); } } /////////////////////////////////////////////////////////////////////////////// // bool InterceptPluginInstance::Init(const char *pluginName, const string &newConfigString) { //Assign the configuration string configString = newConfigString; //Init the plugin gliPlugin = dllInstance->CreateLogPlugin(pluginName, this); if(gliPlugin == NULL) { LOGERR(("InterceptPluginInstance::Init - Unable to init plugin %s in %s",pluginName,dllInstance->GetDLLFileName().c_str())); return false; } //Do not do anything here that the plugin needs // (do before init so plugin can access in constructor) return true; } /////////////////////////////////////////////////////////////////////////////// // const char * InterceptPluginInstance::GetConfigString() { return configString.c_str(); } /////////////////////////////////////////////////////////////////////////////// // float InterceptPluginInstance::GetGLVersion() { return driver->GetOpenGLVersion(); } /////////////////////////////////////////////////////////////////////////////// // bool InterceptPluginInstance::IsGLExtensionSupported(const char *extensionName) { return driver->IsExtensionSupported(extensionName); } /////////////////////////////////////////////////////////////////////////////// // void *InterceptPluginInstance::GetGLFunction(const char *functionName) { //Ensure OpenGL calls can be made if(driver->GetInternalGLCallMode()) { return GLW.glGetProcAddress(functionName); } return NULL; } /////////////////////////////////////////////////////////////////////////////// // void InterceptPluginInstance::RegisterGLFunction(const char *functionName) { pluginManager->RegisterGLFunction(this,functionName); } /////////////////////////////////////////////////////////////////////////////// // void InterceptPluginInstance::UnRegisterGLFunction(const char *functionName) { pluginManager->UnRegisterGLFunction(this,functionName); } /////////////////////////////////////////////////////////////////////////////// // bool InterceptPluginInstance::SetFunctionID(const char *functionName, uint newID) { return pluginManager->SetFunctionID(this,functionName,newID); } /////////////////////////////////////////////////////////////////////////////// // void InterceptPluginInstance::SetContextFunctionCalls(bool enable) { //Assign the flag contextFunctionCalls = enable; } /////////////////////////////////////////////////////////////////////////////// // bool InterceptPluginInstance::GetGLArgString(uint funcIndex, const FunctionArgs & args, uint strLength, char *retString) { return pluginManager->GetGLArgString(funcIndex, args, strLength, retString); } /////////////////////////////////////////////////////////////////////////////// // bool InterceptPluginInstance::GetGLReturnString(uint funcIndex, const FunctionRetValue & retVal, uint strLength, char *retString) { return pluginManager->GetGLReturnString(funcIndex, retVal, strLength, retString); } /////////////////////////////////////////////////////////////////////////////// // bool InterceptPluginInstance::GetGLInternalCallState() { return driver->GetInternalGLCallMode(); } /////////////////////////////////////////////////////////////////////////////// // uint InterceptPluginInstance::GetFrameNumber() { return driver->GetFrameNumber(); } /////////////////////////////////////////////////////////////////////////////// // uintptr_t InterceptPluginInstance::GetThreadID() { return GetActiveThreadID(); } /////////////////////////////////////////////////////////////////////////////// // HGLRC InterceptPluginInstance::GetGLContextID() { GLContext *currContext = driver->GetCurrentContext(); //If there is a current context if(currContext) { return currContext->GetRCHandle(); } return NULL; } /////////////////////////////////////////////////////////////////////////////// // void GLI_CDECL PluginLogErrorMessage(const char *errorMessage,...) { //Global function to handle plugin error messages if(gliLog) { //Get the variable list va_list marker; va_start(marker,errorMessage); //Call the error log gliLog->LogErrorArgs(errorMessage,marker); va_end( marker ); }; } /////////////////////////////////////////////////////////////////////////////// // LOGERRPROC InterceptPluginInstance::GetLogErrorFunction() { return PluginLogErrorMessage; } /////////////////////////////////////////////////////////////////////////////// // const GLCoreDriver * InterceptPluginInstance::GetCoreGLFunctions() { return &GLV; } /////////////////////////////////////////////////////////////////////////////// // const WGLDriver * InterceptPluginInstance::GetWGLFunctions() { return &GLW; } /////////////////////////////////////////////////////////////////////////////// // const InputUtils * InterceptPluginInstance::GetInputUtils() { return driver->GetInputUtils(); } /////////////////////////////////////////////////////////////////////////////// // bool InterceptPluginInstance::AddOverrideFunction(const char * funcName, void * overrideFunctionPtr, void *origFuncPtr) { //Flag to not unload the DLL until shutdown hasRegisteredFunctions = true; return driver->AddOverrideFunction(funcName, overrideFunctionPtr, origFuncPtr); } /////////////////////////////////////////////////////////////////////////////// // LoggerMode InterceptPluginInstance::GetLoggerMode() const { return driver->GetLoggerMode(); } /////////////////////////////////////////////////////////////////////////////// // bool InterceptPluginInstance::GetLoggerPath(uint strLength, char *retString) { //If no logging is on, return now if(driver->GetLoggerMode() == LM_None) { return false; } //Get the current log path (and check that there is enough write space) string currentPath = driver->GetLoggerPath(); if(currentPath.length()+1 > strLength) { return false; } //Assign the string strncpy(retString, currentPath.c_str(), currentPath.length()); retString[currentPath.length()] = '\0'; return true; } /////////////////////////////////////////////////////////////////////////////// // bool InterceptPluginInstance::GetLogResourceFilename(LogResourceType type, uint typeID, uint strLength, char *retString) { //If no logging is on, return now if(driver->GetLoggerMode() == LM_None) { return false; } //Ensure there is a current context GLContext *currContext = driver->GetCurrentContext(); if(!currContext) { return false; } //Get the string based on the type string resourceFilename; switch(type) { case(LRT_Texture): { ImageSaveFiles imageFileNames; //Get the filenames for the image if(currContext->GetTextureFileNames(typeID, imageFileNames) && imageFileNames.imageFileNames.size() > 0) { //Just use the primary filename resourceFilename = imageFileNames.imageFileNames[0]; } } break; case(LRT_ShaderASM): currContext->GetShaderFileName(typeID, resourceFilename); break; case(LRT_ShaderGLSL): currContext->GetShaderGLSLFileName(typeID, InterceptShaderGLSL::GLSLRT_GLSL_Shader, resourceFilename); break; case(LRT_ProgramGLSL): currContext->GetShaderGLSLFileName(typeID, InterceptShaderGLSL::GLSLRT_GLSL_Program, resourceFilename); break; case(LRT_DisplayList): currContext->GetDisplayListFileName(typeID, resourceFilename); break; case(LRT_ColorBuffer): { FrameInterceptFileNames frameFileNames; //Get all the frame filenames if(currContext->GetFrameFileNames(frameFileNames)) { //Just return the "post" filename for now (add new enums if needed) if(typeID < frameFileNames.numColorBuffers) { resourceFilename = frameFileNames.colorBufNames[typeID][FIDT_POST_FRAME]; } } } break; case(LRT_StencilBuffer): { FrameInterceptFileNames frameFileNames; //Get all the frame filenames if(currContext->GetFrameFileNames(frameFileNames)) { //Just return the "post" filename for now (add new enums if needed) resourceFilename = frameFileNames.stencilBufNames[FIDT_POST_FRAME]; } } break; case(LRT_DepthBuffer): { FrameInterceptFileNames frameFileNames; //Get all the frame filenames if(currContext->GetFrameFileNames(frameFileNames)) { //Just return the "post" filename for now (add new enums if needed) resourceFilename = frameFileNames.depthBufNames[FIDT_POST_FRAME]; } } break; } //Strip the path string filePath = driver->GetLoggerPath(); if(resourceFilename.find(filePath,0) == 0) { //Strip the path resourceFilename.erase(0,filePath.size()); } //If there is no resource, (or there is no room to store it) return if(resourceFilename.length() == 0 || resourceFilename.length()+1 > strLength) { return false; } //Assign the string strncpy(retString, resourceFilename.c_str(), resourceFilename.length()); retString[resourceFilename.length()] = '\0'; return true; } /////////////////////////////////////////////////////////////////////////////// // void InterceptPluginInstance::AddLoggerString(const char *addString) { driver->AddLoggerString(addString); } /////////////////////////////////////////////////////////////////////////////// // bool InterceptPluginInstance::DestroyPlugin() { //Delete the interface if(gliPlugin) { //Ensure destroy is not called twice InterceptPluginInterface *destroyPlugin = gliPlugin; //Assign a dummy interface gliPlugin = new DummyPluginInterface; //Destroy the old plugin destroyPlugin->Destroy(); } //Only fully delete the DLL if there are no registered functions contained within it if(!hasRegisteredFunctions) { //Flag to the manager to remove this plugin. // (This will happen in the future as it is likely this method is // called during the plugin array iteration) return pluginManager->FlagPluginRemoval(this); } return true; } /////////////////////////////////////////////////////////////////////////////// // void InterceptPluginInstance::OnDLLUnload(InterceptPluginDLLInstance *deleteDLLInstance) { //Return now if the instance is not "this" plugins' dll if(deleteDLLInstance != dllInstance) { return; } //Delete the interface if(gliPlugin) { //Ensure destroy is not called twice InterceptPluginInterface *destroyPlugin = gliPlugin; //Assign a dummy interface gliPlugin = new DummyPluginInterface; //Destroy the old plugin destroyPlugin->Destroy(); } //Flag for removal pluginManager->FlagPluginRemoval(this); }
28.00818
146
0.58915
vinjn
6f0c795ecd8049a76dcd0c5679935daf5e69d2b6
36,870
cpp
C++
Code/Framework/AzToolsFramework/AzToolsFramework/UI/DocumentPropertyEditor/DocumentPropertyEditor.cpp
psy-repos-c/o3de
42d917e4726b1cae8c39c10834b0e621c9e8300d
[ "Apache-2.0", "MIT" ]
null
null
null
Code/Framework/AzToolsFramework/AzToolsFramework/UI/DocumentPropertyEditor/DocumentPropertyEditor.cpp
psy-repos-c/o3de
42d917e4726b1cae8c39c10834b0e621c9e8300d
[ "Apache-2.0", "MIT" ]
null
null
null
Code/Framework/AzToolsFramework/AzToolsFramework/UI/DocumentPropertyEditor/DocumentPropertyEditor.cpp
psy-repos-c/o3de
42d917e4726b1cae8c39c10834b0e621c9e8300d
[ "Apache-2.0", "MIT" ]
null
null
null
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include "DocumentPropertyEditor.h" #include <AzQtComponents/Components/Widgets/ElidingLabel.h> #include <QCheckBox> #include <QLineEdit> #include <QTimer> #include <QVBoxLayout> #include <AzCore/Console/IConsole.h> #include <AzCore/DOM/DomUtils.h> #include <AzFramework/DocumentPropertyEditor/PropertyEditorNodes.h> #include <AzQtComponents/Components/Widgets/CheckBox.h> #include <AzToolsFramework/UI/DocumentPropertyEditor/PropertyEditorToolsSystemInterface.h> #include <AzToolsFramework/UI/DPEDebugViewer/DPEDebugModel.h> #include <AzToolsFramework/UI/DPEDebugViewer/DPEDebugWindow.h> AZ_CVAR( bool, ed_showDPEDebugView, false, nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "If set, instances of the DPE also spawn a DPE debug view window, which allows users inspect the hierarchy and the DOM in pseudo XML " "format"); namespace AzToolsFramework { // helper method used by both the view and row widgets to empty layouts static void DestroyLayoutContents(QLayout* layout) { while (auto layoutItem = layout->takeAt(0)) { auto subWidget = layoutItem->widget(); if (subWidget) { subWidget->deleteLater(); } delete layoutItem; } } DPELayout::DPELayout(int depth, QWidget* parentWidget) : QHBoxLayout(parentWidget) , m_depth(depth) { } DPELayout::~DPELayout() { if (m_expanderWidget) { delete m_expanderWidget; m_expanderWidget = nullptr; } } void DPELayout::SetExpanderShown(bool shouldShow) { if (m_showExpander != shouldShow) { m_showExpander = shouldShow; if (m_expanderWidget && !shouldShow) { delete m_expanderWidget; m_expanderWidget = nullptr; } update(); } } void DPELayout::SetExpanded(bool expanded) { if (m_expanded != expanded) { m_expanded = expanded; if (m_expanderWidget) { Qt::CheckState newCheckState = (expanded ? Qt::Checked : Qt::Unchecked); if (m_expanderWidget->checkState() != newCheckState) { m_expanderWidget->setCheckState(newCheckState); } } emit expanderChanged(expanded); } } bool DPELayout::IsExpanded() const { return m_expanded; } QSize DPELayout::sizeHint() const { int cumulativeWidth = 0; int preferredHeight = 0; // sizeHint for this horizontal layout is the sum of the preferred widths, // and the maximum of the preferred heights for (int layoutIndex = 0; layoutIndex < count(); ++layoutIndex) { auto widgetSizeHint = itemAt(layoutIndex)->sizeHint(); cumulativeWidth += widgetSizeHint.width(); preferredHeight = AZStd::max(widgetSizeHint.height(), preferredHeight); } return { cumulativeWidth, preferredHeight }; } QSize DPELayout::minimumSize() const { int cumulativeWidth = 0; int minimumHeight = 0; // minimumSize for this horizontal layout is the sum of the min widths, // and the maximum of the preferred heights for (int layoutIndex = 0; layoutIndex < count(); ++layoutIndex) { QWidget* widgetChild = itemAt(layoutIndex)->widget(); if (widgetChild) { const auto minWidth = widgetChild->minimumSizeHint().width(); if (minWidth > 0) { cumulativeWidth += minWidth; } minimumHeight = AZStd::max(widgetChild->sizeHint().height(), minimumHeight); } } return { cumulativeWidth, minimumHeight }; } void DPELayout::setGeometry(const QRect& rect) { QLayout::setGeometry(rect); // todo: implement QSplitter-like functionality to allow the user to resize columns within a DPE const int itemCount = count(); if (itemCount > 0) { // divide evenly, unless there are 2 columns, in which case follow the 2/5ths rule here: // https://www.o3de.org/docs/tools-ui/ux-patterns/component-card/overview/ int perItemWidth = (itemCount == 2 ? (rect.width() * 3) / 5 : rect.width() / itemCount); // special case the first item to handle indent and the 2/5ths rule constexpr int indentSize = 15; // child indent of first item, in pixels QRect itemGeometry(rect); itemGeometry.setRight(itemCount == 2 ? itemGeometry.width() - perItemWidth : perItemWidth); itemGeometry.setLeft(itemGeometry.left() + (m_depth * indentSize)); if (m_showExpander) { if (!m_expanderWidget) { CreateExpanderWidget(); } m_expanderWidget->move(itemGeometry.topLeft()); m_expanderWidget->show(); } // space to leave for expander, whether it's there or not constexpr int expanderSpace = 16; itemGeometry.setLeft(itemGeometry.left() + expanderSpace); itemAt(0)->setGeometry(itemGeometry); // iterate over the remaining items, laying them left to right for (int layoutIndex = 1; layoutIndex < itemCount; ++layoutIndex) { itemGeometry.setLeft(itemGeometry.right() + 1); itemGeometry.setRight(itemGeometry.left() + perItemWidth); itemAt(layoutIndex)->setGeometry(itemGeometry); } } } Qt::Orientations DPELayout::expandingDirections() const { return Qt::Vertical | Qt::Horizontal; } void DPELayout::onCheckstateChanged(int expanderState) { SetExpanded(expanderState == Qt::Checked); } DocumentPropertyEditor* DPELayout::GetDPE() const { DocumentPropertyEditor* dpe = nullptr; const auto parent = parentWidget(); if (parent) { dpe = qobject_cast<DocumentPropertyEditor*>(parent->parentWidget()); AZ_Assert(dpe, "A DPELayout must be the child of a DPERowWidget, which must be the child of a DocumentPropertyEditor!"); } return dpe; } void DPELayout::CreateExpanderWidget() { m_expanderWidget = new QCheckBox(parentWidget()); m_expanderWidget->setCheckState(m_expanded ? Qt::Checked : Qt::Unchecked); AzQtComponents::CheckBox::applyExpanderStyle(m_expanderWidget); connect(m_expanderWidget, &QCheckBox::stateChanged, this, &DPELayout::onCheckstateChanged); } DPERowWidget::DPERowWidget(int depth, DPERowWidget* parentRow) : QWidget(nullptr) // parent will be set when the row is added to its layout , m_parentRow(parentRow) , m_depth(depth) , m_columnLayout(new DPELayout(depth, this)) { // allow horizontal stretching, but use the vertical size hint exactly setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); QObject::connect(m_columnLayout, &DPELayout::expanderChanged, this, &DPERowWidget::onExpanderChanged); } DPERowWidget::~DPERowWidget() { Clear(); } void DPERowWidget::Clear() { DocumentPropertyEditor* dpe = GetDPE(); // propertyHandlers own their widgets, so don't destroy them here. Set them free! for (auto propertyWidgetIter = m_widgetToPropertyHandler.begin(), endIter = m_widgetToPropertyHandler.end(); propertyWidgetIter != endIter; ++propertyWidgetIter) { QWidget* propertyWidget = propertyWidgetIter->first; auto toRemove = AZStd::remove(m_domOrderedChildren.begin(), m_domOrderedChildren.end(), propertyWidget); m_domOrderedChildren.erase(toRemove, m_domOrderedChildren.end()); m_columnLayout->removeWidget(propertyWidget); propertyWidgetIter->first->setParent(nullptr); if (dpe) { dpe->ReleaseHandler(AZStd::move(propertyWidgetIter->second)); } } m_widgetToPropertyHandler.clear(); // delete all remaining child widgets, this will also remove them from their layout for (auto entry : m_domOrderedChildren) { if (entry) { delete entry; } } m_domOrderedChildren.clear(); } void DPERowWidget::AddChildFromDomValue(const AZ::Dom::Value& childValue, int domIndex) { // create a child widget from the given DOM value and add it to the correct layout auto childType = childValue.GetNodeName(); if (childType == AZ::Dpe::GetNodeName<AZ::Dpe::Nodes::Row>()) { m_columnLayout->SetExpanderShown(true); if (IsExpanded()) { // determine where to put this new row in the main DPE layout auto newRow = new DPERowWidget(m_depth + 1, this); DPERowWidget* priorWidgetInLayout = nullptr; // search for an existing row sibling with a lower dom index for (int priorWidgetIndex = domIndex - 1; priorWidgetInLayout == nullptr && priorWidgetIndex >= 0; --priorWidgetIndex) { priorWidgetInLayout = qobject_cast<DPERowWidget*>(m_domOrderedChildren[priorWidgetIndex]); } // if we found a prior DPERowWidget, put this one after the last of its children, // if not, put this new row immediately after its parent -- this if (priorWidgetInLayout) { priorWidgetInLayout = priorWidgetInLayout->GetLastDescendantInLayout(); } else { priorWidgetInLayout = this; } if (domIndex >= 0 && m_domOrderedChildren.size() > domIndex) { delete m_domOrderedChildren[domIndex]; m_domOrderedChildren[domIndex] = newRow; } else if (m_domOrderedChildren.size() == domIndex) { m_domOrderedChildren.push_back(newRow); } else { AZ_Assert(0, "error: trying to add an out of bounds index"); return; } GetDPE()->AddAfterWidget(priorWidgetInLayout, newRow); // if it's a row, recursively populate the children from the DOM array in the passed value newRow->SetValueFromDom(childValue); } else { // this row isn't expanded, don't create any row children, just log that there's a null widget at // the given DOM index m_domOrderedChildren.insert(m_domOrderedChildren.begin() + domIndex, nullptr); } } else { QWidget* addedWidget = nullptr; if (childType == AZ::Dpe::GetNodeName<AZ::Dpe::Nodes::Label>()) { auto labelString = AZ::Dpe::Nodes::Label::Value.ExtractFromDomNode(childValue).value_or(""); addedWidget = new AzQtComponents::ElidingLabel(QString::fromUtf8(labelString.data(), aznumeric_cast<int>(labelString.size())), this); } else if (childType == AZ::Dpe::GetNodeName<AZ::Dpe::Nodes::PropertyEditor>()) { auto dpeSystem = AZ::Interface<AzToolsFramework::PropertyEditorToolsSystemInterface>::Get(); auto handlerId = dpeSystem->GetPropertyHandlerForNode(childValue); // if we found a valid handler, grab its widget to add to the column layout if (handlerId) { // store, then reference the unique_ptr that will manage the handler's lifetime auto handler = dpeSystem->CreateHandlerInstance(handlerId); handler->SetValueFromDom(childValue); addedWidget = handler->GetWidget(); m_widgetToPropertyHandler[addedWidget] = AZStd::move(handler); } else { addedWidget = new QLabel("Missing handler for dom node!"); } } else { AZ_Assert(0, "unknown node type for DPE"); return; } addedWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); // search for an existing column sibling with a lower dom index int priorColumnIndex = -1; for (int searchIndex = domIndex - 1; (priorColumnIndex == -1 && searchIndex >= 0); --searchIndex) { priorColumnIndex = m_columnLayout->indexOf(m_domOrderedChildren[searchIndex]); } // insert after the found index; even if nothing were found and priorIndex is still -1, // still insert one after it, at position 0 m_columnLayout->insertWidget(priorColumnIndex + 1, addedWidget); m_domOrderedChildren.insert(m_domOrderedChildren.begin() + domIndex, addedWidget); } } void DPERowWidget::SetValueFromDom(const AZ::Dom::Value& domArray) { Clear(); // determine whether this node should be expanded auto forceExpandAttribute = AZ::Dpe::Nodes::Row::ForceAutoExpand.ExtractFromDomNode(domArray); if (forceExpandAttribute.has_value()) { // forced attribute always wins, set the expansion state m_columnLayout->SetExpanded(forceExpandAttribute.value()); } else { // nothing forced, so the user's saved expansion state, if it exists, should be used auto savedState = GetDPE()->GetSavedExpanderStateForRow(this); if (savedState != DocumentPropertyEditor::ExpanderState::NotSet) { m_columnLayout->SetExpanded(savedState == DocumentPropertyEditor::ExpanderState::Expanded); } else { // no prior expansion state set, use the AutoExpand attribute, if it's set auto autoExpandAttribute = AZ::Dpe::Nodes::Row::AutoExpand.ExtractFromDomNode(domArray); if (autoExpandAttribute.has_value()) { m_columnLayout->SetExpanded(autoExpandAttribute.value()); } else { // expander state is not explicitly set or saved anywhere, default to expanded m_columnLayout->SetExpanded(true); } } } // populate all direct children of this row for (size_t arrayIndex = 0, numIndices = domArray.ArraySize(); arrayIndex < numIndices; ++arrayIndex) { auto& childValue = domArray[arrayIndex]; AddChildFromDomValue(childValue, aznumeric_cast<int>(arrayIndex)); } } void DPERowWidget::HandleOperationAtPath(const AZ::Dom::PatchOperation& domOperation, size_t pathIndex) { const auto& fullPath = domOperation.GetDestinationPath(); auto pathEntry = fullPath[pathIndex]; AZ_Assert(pathEntry.IsIndex() || pathEntry.IsEndOfArray(), "the direct children of a row must be referenced by index"); auto childCount = m_domOrderedChildren.size(); // if we're on the last entry in the path, this row widget is the direct owner if (pathIndex == fullPath.Size() - 1) { size_t childIndex = 0; if (pathEntry.IsIndex()) { // remove and replace operations must match an existing index. Add operations can be one past the current end. AZ_Assert( (domOperation.GetType() == AZ::Dom::PatchOperation::Type::Add ? childIndex <= childCount : childIndex < childCount), "patch index is beyond the array bounds!"); childIndex = aznumeric_cast<int>(pathEntry.GetIndex()); } else if (domOperation.GetType() == AZ::Dom::PatchOperation::Type::Add) { childIndex = childCount; } else // must be IsEndOfArray and a replace or remove, use the last existing index { childIndex = childCount - 1; } // if this is a remove or replace, remove the existing entry first, // then, if this is a replace or add, add the new entry if (domOperation.GetType() == AZ::Dom::PatchOperation::Type::Remove || domOperation.GetType() == AZ::Dom::PatchOperation::Type::Replace) { const auto childIterator = m_domOrderedChildren.begin() + childIndex; DPERowWidget* rowToRemove = qobject_cast<DPERowWidget*>(*childIterator); if (rowToRemove) { // we're removing a row, remove any associated saved expander state GetDPE()->RemoveExpanderStateForRow(rowToRemove); } (*childIterator)->deleteLater(); // deleting the widget also automatically removes it from the layout m_domOrderedChildren.erase(childIterator); // check if the last row widget child was removed, and hide the expander if necessary auto isDPERow = [](auto* widget) { return qobject_cast<DPERowWidget*>(widget) != nullptr; }; if (AZStd::find_if(m_domOrderedChildren.begin(), m_domOrderedChildren.end(), isDPERow) == m_domOrderedChildren.end()) { m_columnLayout->SetExpanderShown(false); } } if (domOperation.GetType() == AZ::Dom::PatchOperation::Type::Replace || domOperation.GetType() == AZ::Dom::PatchOperation::Type::Add) { AddChildFromDomValue(domOperation.GetValue(), aznumeric_cast<int>(childIndex)); } } else // not the direct owner of the entry to patch { // find the next widget in the path and delegate the operation to them auto childIndex = (pathEntry.IsIndex() ? pathEntry.GetIndex() : childCount - 1); AZ_Assert(childIndex <= childCount, "DPE: Patch failed to apply, invalid child index specified"); if (childIndex > childCount) { return; } QWidget* childWidget = m_domOrderedChildren[childIndex]; if (!childWidget) { // if there's a null entry in the current place for m_domOrderedChildren, // this entry isn't expanded to that depth and need not follow the change any further AZ_Assert(!IsExpanded(), "m_domOrderedChildren should only contain null entries when collapsed!"); return; } DPERowWidget* widgetAsDpeRow = qobject_cast<DPERowWidget*>(childWidget); if (widgetAsDpeRow) { // child is a DPERowWidget, pass patch processing to it widgetAsDpeRow->HandleOperationAtPath(domOperation, pathIndex + 1); } else // child must be a label or a PropertyEditor { // pare down the path to this node, then look up and set the value from the DOM auto subPath = fullPath; for (size_t pathEntryIndex = fullPath.size() - 1; pathEntryIndex > pathIndex; --pathEntryIndex) { subPath.Pop(); } const auto valueAtSubPath = GetDPE()->GetAdapter()->GetContents()[subPath]; // check if it's a PropertyHandler; if it is, just set it from the DOM directly auto foundEntry = m_widgetToPropertyHandler.find(childWidget); if (foundEntry != m_widgetToPropertyHandler.end()) { foundEntry->second->SetValueFromDom(valueAtSubPath); } else { QLabel* changedLabel = qobject_cast<QLabel*>(childWidget); AZ_Assert(changedLabel, "not a label, unknown widget discovered!"); if (changedLabel) { auto labelString = AZ::Dpe::Nodes::Label::Value.ExtractFromDomNode(valueAtSubPath).value_or(""); changedLabel->setText(QString::fromUtf8(labelString.data())); } } } } } DocumentPropertyEditor* DPERowWidget::GetDPE() const { DocumentPropertyEditor* theDPE = nullptr; QWidget* ancestorWidget = parentWidget(); while (ancestorWidget && !theDPE) { theDPE = qobject_cast<DocumentPropertyEditor*>(ancestorWidget); ancestorWidget = ancestorWidget->parentWidget(); } AZ_Assert(theDPE, "the top level widget in any DPE hierarchy must be the DocumentPropertyEditor itself!"); return theDPE; } DPERowWidget* DPERowWidget::GetLastDescendantInLayout() { DPERowWidget* lastDescendant = nullptr; for (auto childIter = m_domOrderedChildren.rbegin(); (lastDescendant == nullptr && childIter != m_domOrderedChildren.rend()); ++childIter) { lastDescendant = qobject_cast<DPERowWidget*>(*childIter); } if (lastDescendant) { lastDescendant = lastDescendant->GetLastDescendantInLayout(); } else { // didn't find any relevant children, this row widget is the last descendant lastDescendant = this; } return lastDescendant; } bool DPERowWidget::IsExpanded() const { return m_columnLayout->IsExpanded(); } void DPERowWidget::onExpanderChanged(int expanderState) { if (expanderState == Qt::Unchecked) { // expander is collapsed; search for row children and delete them, // which will zero out their QPointer in the deque, and remove them from the layout for (auto& currentChild : m_domOrderedChildren) { DPERowWidget* rowChild = qobject_cast<DPERowWidget*>(currentChild); if (rowChild) { delete rowChild; currentChild = nullptr; } } } else { auto myValue = GetDPE()->GetDomValueForRow(this); AZ_Assert(myValue.ArraySize() == m_domOrderedChildren.size(), "known child count does not match child count!"); for (int valueIndex = 0; valueIndex < m_domOrderedChildren.size(); ++valueIndex) { if (m_domOrderedChildren[valueIndex] == nullptr) { AddChildFromDomValue(myValue[valueIndex], valueIndex); } } } GetDPE()->SetSavedExpanderStateForRow( this, (expanderState == Qt::Unchecked ? DocumentPropertyEditor::ExpanderState::Collapsed : DocumentPropertyEditor::ExpanderState::Expanded)); } DocumentPropertyEditor::DocumentPropertyEditor(QWidget* parentWidget) : QScrollArea(parentWidget) { QWidget* scrollSurface = new QWidget(this); m_layout = new QVBoxLayout(scrollSurface); setWidget(scrollSurface); setWidgetResizable(true); m_handlerCleanupTimer = new QTimer(this); m_handlerCleanupTimer->setSingleShot(true); m_handlerCleanupTimer->setInterval(0); connect(m_handlerCleanupTimer, &QTimer::timeout, this, &DocumentPropertyEditor::CleanupReleasedHandlers); m_spawnDebugView = ed_showDPEDebugView; } DocumentPropertyEditor::~DocumentPropertyEditor() { } void DocumentPropertyEditor::SetAdapter(AZ::DocumentPropertyEditor::DocumentAdapterPtr theAdapter) { if (m_spawnDebugView) { QPointer<AzToolsFramework::DPEDebugWindow> theWindow = new AzToolsFramework::DPEDebugWindow(nullptr); theWindow->SetAdapter(theAdapter); theWindow->show(); } m_adapter = theAdapter; m_resetHandler = AZ::DocumentPropertyEditor::DocumentAdapter::ResetEvent::Handler( [this]() { this->HandleReset(); }); m_adapter->ConnectResetHandler(m_resetHandler); m_changedHandler = AZ::DocumentPropertyEditor::DocumentAdapter::ChangedEvent::Handler( [this](const AZ::Dom::Patch& patch) { this->HandleDomChange(patch); }); m_adapter->ConnectChangedHandler(m_changedHandler); // populate the view from the full adapter contents, just like a reset HandleReset(); } void DocumentPropertyEditor::AddAfterWidget(QWidget* precursor, QWidget* widgetToAdd) { int foundIndex = m_layout->indexOf(precursor); if (foundIndex >= 0) { m_layout->insertWidget(foundIndex + 1, widgetToAdd); } } void DocumentPropertyEditor::SetSavedExpanderStateForRow(DPERowWidget* row, DocumentPropertyEditor::ExpanderState expanderState) { // Get the index of each dom child going up the chain. We can then reverse this // and use these indices to mark a path to expanded/collapsed nodes AZStd::vector<size_t> reversePath = GetPathToRoot(row); if (!reversePath.empty()) { // create new pathNodes when necessary implicitly by indexing into each map, // then set the expander state on the final node auto reverseIter = reversePath.rbegin(); auto* currPathNode = &m_expanderPaths[*(reverseIter++)]; while (reverseIter != reversePath.rend()) { currPathNode = &currPathNode->nextNode[*(reverseIter++)]; } currPathNode->expanderState = expanderState; } } DocumentPropertyEditor::ExpanderState DocumentPropertyEditor::GetSavedExpanderStateForRow(DPERowWidget* row) const { // default to NotSet; if a particular index is not recorded in m_expanderPaths, // it is considered not set ExpanderState retval = ExpanderState::NotSet; AZStd::vector<size_t> reversePath = GetPathToRoot(row); auto reverseIter = reversePath.rbegin(); if (!reversePath.empty()) { auto firstNodeIter = m_expanderPaths.find(*(reverseIter++)); if (firstNodeIter != m_expanderPaths.end()) { const ExpanderPathNode* currPathNode = &firstNodeIter->second; // search the existing path tree to see if there's an expander entry for the given node while (currPathNode && reverseIter != reversePath.rend()) { auto nextPathNodeIter = currPathNode->nextNode.find((*reverseIter++)); if (nextPathNodeIter != currPathNode->nextNode.end()) { currPathNode = &(nextPathNodeIter->second); } else { currPathNode = nullptr; } } if (currPathNode) { // full path exists in the tree, return its expander state retval = currPathNode->expanderState; } } } return retval; } void DocumentPropertyEditor::RemoveExpanderStateForRow(DPERowWidget* row) { AZStd::vector<size_t> reversePath = GetPathToRoot(row); const auto pathLength = reversePath.size(); auto reverseIter = reversePath.rbegin(); if (pathLength > 0) { auto firstNodeIter = m_expanderPaths.find(*(reverseIter++)); if (firstNodeIter != m_expanderPaths.end()) { if (pathLength == 1) { m_expanderPaths.erase(firstNodeIter); } else { ExpanderPathNode* currPathNode = &firstNodeIter->second; auto nextPathNodeIter = currPathNode->nextNode.find((*reverseIter++)); while (reverseIter != reversePath.rend() && nextPathNodeIter != currPathNode->nextNode.end()) { currPathNode = &(nextPathNodeIter->second); nextPathNodeIter = currPathNode->nextNode.find((*reverseIter++)); } // if we reached the end of the row path, and have valid expander state at that location, // prune the entry and all its children from the expander tree if (reverseIter == reversePath.rend() && nextPathNodeIter != currPathNode->nextNode.end()) { currPathNode->nextNode.erase(nextPathNodeIter); } } } } } AZ::Dom::Value DocumentPropertyEditor::GetDomValueForRow(DPERowWidget* row) const { // Get the index of each dom child going up the chain. We can then reverse this // and use these indices to walk the adapter tree and get the Value for the node at this path AZStd::vector<size_t> reversePath = GetPathToRoot(row); // full index path is built, now get the value from the adapter auto returnValue = m_adapter->GetContents(); for (auto reverseIter = reversePath.rbegin(); reverseIter != reversePath.rend(); ++reverseIter) { returnValue = returnValue[*reverseIter]; } return returnValue; } void DocumentPropertyEditor::ReleaseHandler(AZStd::unique_ptr<PropertyHandlerWidgetInterface>&& handler) { m_unusedHandlers.emplace_back(AZStd::move(handler)); m_handlerCleanupTimer->start(); } void DocumentPropertyEditor::SetSpawnDebugView(bool shouldSpawn) { m_spawnDebugView = shouldSpawn; } QVBoxLayout* DocumentPropertyEditor::GetVerticalLayout() { return m_layout; } void DocumentPropertyEditor::AddRowFromValue(const AZ::Dom::Value& domValue, int rowIndex) { const bool indexInRange = (rowIndex <= m_domOrderedRows.size()); AZ_Assert(indexInRange, "rowIndex cannot be more than one past the existing end!") if (indexInRange) { auto newRow = new DPERowWidget(0, nullptr); if (rowIndex == 0) { m_domOrderedRows.push_front(newRow); m_layout->insertWidget(0, newRow); } else { auto priorRowPosition = m_domOrderedRows.begin() + (rowIndex - 1); AddAfterWidget((*priorRowPosition)->GetLastDescendantInLayout(), newRow); m_domOrderedRows.insert(priorRowPosition + 1, newRow); } newRow->SetValueFromDom(domValue); } } AZStd::vector<size_t> DocumentPropertyEditor::GetPathToRoot(DPERowWidget* row) const { AZStd::vector<size_t> pathToRoot; const DPERowWidget* thisRow = row; const DPERowWidget* parentRow = thisRow->m_parentRow; // little lambda for reuse in two different container settings auto pushPathPiece = [&pathToRoot](auto container, const auto& element) { auto pathPiece = AZStd::find(container.begin(), container.end(), element); AZ_Assert(pathPiece != container.end(), "these path indices should always be found!"); pathToRoot.push_back(pathPiece - container.begin()); }; // search upwards and get the index of each dom child going up the chain while (parentRow) { pushPathPiece(parentRow->m_domOrderedChildren, thisRow); thisRow = parentRow; parentRow = parentRow->m_parentRow; } // we've reached the top of the DPERowWidget chain, now we need to get that first row's index from the m_domOrderedRows pushPathPiece(m_domOrderedRows, thisRow); return pathToRoot; } void DocumentPropertyEditor::HandleReset() { // clear any pre-existing DPERowWidgets DestroyLayoutContents(m_layout); m_domOrderedRows.clear(); m_expanderPaths.clear(); auto topContents = m_adapter->GetContents(); for (size_t arrayIndex = 0, numIndices = topContents.ArraySize(); arrayIndex < numIndices; ++arrayIndex) { auto& rowValue = topContents[arrayIndex]; auto domName = rowValue.GetNodeName().GetStringView(); const bool isRow = (domName == AZ::DocumentPropertyEditor::Nodes::Row::Name); AZ_Assert(isRow, "adapters must only have rows as direct children!"); if (isRow) { AddRowFromValue(rowValue, aznumeric_cast<int>(arrayIndex)); } } m_layout->addStretch(); } void DocumentPropertyEditor::HandleDomChange(const AZ::Dom::Patch& patch) { for (auto operationIterator = patch.begin(), endIterator = patch.end(); operationIterator != endIterator; ++operationIterator) { const auto& patchPath = operationIterator->GetDestinationPath(); if (patchPath.Size() == 0) { // If we're operating on the entire tree, go ahead and just reset HandleReset(); return; } auto firstAddressEntry = patchPath[0]; AZ_Assert( firstAddressEntry.IsIndex() || firstAddressEntry.IsEndOfArray(), "first entry in a DPE patch must be the index of the first row"); auto rowIndex = (firstAddressEntry.IsIndex() ? firstAddressEntry.GetIndex() : m_domOrderedRows.size()); AZ_Assert( rowIndex < m_domOrderedRows.size() || (rowIndex <= m_domOrderedRows.size() && operationIterator->GetType() == AZ::Dom::PatchOperation::Type::Add), "received a patch for a row that doesn't exist"); // if the patch points at our root, this operation is for the top level layout if (patchPath.IsEmpty()) { if (operationIterator->GetType() == AZ::Dom::PatchOperation::Type::Add) { AddRowFromValue(operationIterator->GetValue(), aznumeric_cast<int>(rowIndex)); } else { auto& rowWidget = m_domOrderedRows[aznumeric_cast<int>(firstAddressEntry.GetIndex())]; if (operationIterator->GetType() == AZ::Dom::PatchOperation::Type::Replace) { rowWidget->SetValueFromDom(operationIterator->GetValue()); } else if (operationIterator->GetType() == AZ::Dom::PatchOperation::Type::Remove) { delete rowWidget; rowWidget = nullptr; } } } else { // delegate the action to the rowWidget, which will, in turn, delegate to the next row in the path, if available auto rowWidget = m_domOrderedRows[aznumeric_cast<int>(firstAddressEntry.GetIndex())]; constexpr size_t pathDepth = 1; // top level has been handled, start the next operation at path depth 1 rowWidget->HandleOperationAtPath(*operationIterator, pathDepth); } } } void DocumentPropertyEditor::CleanupReleasedHandlers() { // Release unused handlers from the pool, thereby destroying them and their associated widgets m_unusedHandlers.clear(); } } // namespace AzToolsFramework
40.295082
139
0.581747
psy-repos-c
6f0cf0a401c181ae1522a363c994f5dbe8b911a3
28,915
cpp
C++
src/mesh/meshblock.cpp
cnstahl/athena
52a7ead1ee9000fe0fcc61824e26adae93fac227
[ "BSD-3-Clause" ]
null
null
null
src/mesh/meshblock.cpp
cnstahl/athena
52a7ead1ee9000fe0fcc61824e26adae93fac227
[ "BSD-3-Clause" ]
null
null
null
src/mesh/meshblock.cpp
cnstahl/athena
52a7ead1ee9000fe0fcc61824e26adae93fac227
[ "BSD-3-Clause" ]
null
null
null
//======================================================================================== // Athena++ astrophysical MHD code // Copyright(C) 2014 James M. Stone <jmstone@princeton.edu> and other code contributors // Licensed under the 3-clause BSD License, see LICENSE file for details //======================================================================================== //! \file mesh.cpp // \brief implementation of functions in MeshBlock class // C/C++ headers #include <iostream> #include <sstream> #include <stdexcept> // runtime_error #include <string> // c_str() #include <algorithm> // sort #include <iomanip> #include <stdlib.h> #include <string.h> // memcpy // Athena++ classes headers #include "../athena.hpp" #include "../globals.hpp" #include "../athena_arrays.hpp" #include "../coordinates/coordinates.hpp" #include "../hydro/hydro.hpp" #include "../field/field.hpp" #include "../bvals/bvals.hpp" #include "../eos/eos.hpp" #include "../parameter_input.hpp" #include "../utils/buffer_utils.hpp" #include "../reconstruct/reconstruction.hpp" #include "mesh_refinement.hpp" #include "meshblock_tree.hpp" #include "mesh.hpp" //---------------------------------------------------------------------------------------- // MeshBlock constructor: constructs coordinate, boundary condition, hydro, field // and mesh refinement objects. MeshBlock::MeshBlock(int igid, int ilid, LogicalLocation iloc, RegionSize input_block, enum BoundaryFlag *input_bcs, Mesh *pm, ParameterInput *pin, bool ref_flag) { std::stringstream msg; int root_level; pmy_mesh = pm; root_level = pm->root_level; block_size = input_block; for(int i=0; i<6; i++) block_bcs[i] = input_bcs[i]; prev=NULL; next=NULL; gid=igid; lid=ilid; loc=iloc; cost=1.0; nuser_out_var = 0; nreal_user_meshblock_data_ = 0; nint_user_meshblock_data_ = 0; // initialize grid indices is = NGHOST; ie = is + block_size.nx1 - 1; if (block_size.nx2 > 1) { js = NGHOST; je = js + block_size.nx2 - 1; } else { js = je = 0; } if (block_size.nx3 > 1) { ks = NGHOST; ke = ks + block_size.nx3 - 1; } else { ks = ke = 0; } if(pm->multilevel==true) { cnghost=(NGHOST+1)/2+1; cis=cnghost; cie=cis+block_size.nx1/2-1; cjs=cje=cks=cke=0; if(block_size.nx2>1) // 2D or 3D cjs=cnghost, cje=cjs+block_size.nx2/2-1; if(block_size.nx3>1) // 3D cks=cnghost, cke=cks+block_size.nx3/2-1; } // construct objects stored in MeshBlock class. Note in particular that the initial // conditions for the simulation are set in problem generator called from main, not // in the Hydro constructor // mesh-related objects if (COORDINATE_SYSTEM == "cartesian") { pcoord = new Cartesian(this, pin, false); } else if (COORDINATE_SYSTEM == "cylindrical") { pcoord = new Cylindrical(this, pin, false); } else if (COORDINATE_SYSTEM == "spherical_polar") { pcoord = new SphericalPolar(this, pin, false); } else if (COORDINATE_SYSTEM == "minkowski") { pcoord = new Minkowski(this, pin, false); } else if (COORDINATE_SYSTEM == "schwarzschild") { pcoord = new Schwarzschild(this, pin, false); } else if (COORDINATE_SYSTEM == "kerr-schild") { pcoord = new KerrSchild(this, pin, false); } else if (COORDINATE_SYSTEM == "gr_user") { pcoord = new GRUser(this, pin, false); } pbval = new BoundaryValues(this, pin); if (block_bcs[INNER_X2] == POLAR_BNDRY||block_bcs[INNER_X2] == POLAR_BNDRY_WEDGE) { int level = loc.level - pmy_mesh->root_level; int num_north_polar_blocks = pmy_mesh->nrbx3 * (1 << level); polar_neighbor_north = new PolarNeighborBlock[num_north_polar_blocks]; } if (block_bcs[OUTER_X2] == POLAR_BNDRY||block_bcs[OUTER_X2] == POLAR_BNDRY_WEDGE) { int level = loc.level - pmy_mesh->root_level; int num_south_polar_blocks = pmy_mesh->nrbx3 * (1 << level); polar_neighbor_south = new PolarNeighborBlock[num_south_polar_blocks]; } precon = new Reconstruction(this, pin); if(pm->multilevel==true) pmr = new MeshRefinement(this, pin); // physics-related objects phydro = new Hydro(this, pin); if (MAGNETIC_FIELDS_ENABLED) pfield = new Field(this, pin); peos = new EquationOfState(this, pin); // Create user mesh data InitUserMeshBlockData(pin); return; } //---------------------------------------------------------------------------------------- // MeshBlock constructor for restarts MeshBlock::MeshBlock(int igid, int ilid, Mesh *pm, ParameterInput *pin, LogicalLocation iloc, RegionSize input_block, enum BoundaryFlag *input_bcs, Real icost, char *mbdata) { std::stringstream msg; pmy_mesh = pm; prev=NULL; next=NULL; gid=igid; lid=ilid; loc=iloc; cost=icost; block_size = input_block; for(int i=0; i<6; i++) block_bcs[i] = input_bcs[i]; nuser_out_var = 0; nreal_user_meshblock_data_ = 0; nint_user_meshblock_data_ = 0; // initialize grid indices is = NGHOST; ie = is + block_size.nx1 - 1; if (block_size.nx2 > 1) { js = NGHOST; je = js + block_size.nx2 - 1; } else { js = je = 0; } if (block_size.nx3 > 1) { ks = NGHOST; ke = ks + block_size.nx3 - 1; } else { ks = ke = 0; } if(pm->multilevel==true) { cnghost=(NGHOST+1)/2+1; cis=cnghost; cie=cis+block_size.nx1/2-1; cjs=cje=cks=cke=0; if(block_size.nx2>1) // 2D or 3D cjs=cnghost, cje=cjs+block_size.nx2/2-1; if(block_size.nx3>1) // 3D cks=cnghost, cke=cks+block_size.nx3/2-1; } // (re-)create mesh-related objects in MeshBlock if (COORDINATE_SYSTEM == "cartesian") { pcoord = new Cartesian(this, pin, false); } else if (COORDINATE_SYSTEM == "cylindrical") { pcoord = new Cylindrical(this, pin, false); } else if (COORDINATE_SYSTEM == "spherical_polar") { pcoord = new SphericalPolar(this, pin, false); } else if (COORDINATE_SYSTEM == "minkowski") { pcoord = new Minkowski(this, pin, false); } else if (COORDINATE_SYSTEM == "schwarzschild") { pcoord = new Schwarzschild(this, pin, false); } else if (COORDINATE_SYSTEM == "kerr-schild") { pcoord = new KerrSchild(this, pin, false); } else if (COORDINATE_SYSTEM == "gr_user") { pcoord = new GRUser(this, pin, false); } pbval = new BoundaryValues(this, pin); if (block_bcs[INNER_X2] == POLAR_BNDRY||block_bcs[INNER_X2] == POLAR_BNDRY_WEDGE) { int level = loc.level - pmy_mesh->root_level; int num_north_polar_blocks = pmy_mesh->nrbx3 * (1 << level); polar_neighbor_north = new PolarNeighborBlock[num_north_polar_blocks]; } if (block_bcs[OUTER_X2] == POLAR_BNDRY||block_bcs[OUTER_X2] == POLAR_BNDRY_WEDGE) { int level = loc.level - pmy_mesh->root_level; int num_south_polar_blocks = pmy_mesh->nrbx3 * (1 << level); polar_neighbor_south = new PolarNeighborBlock[num_south_polar_blocks]; } precon = new Reconstruction(this, pin); if(pm->multilevel==true) pmr = new MeshRefinement(this, pin); // (re-)create physics-related objects in MeshBlock phydro = new Hydro(this, pin); if (MAGNETIC_FIELDS_ENABLED) pfield = new Field(this, pin); peos = new EquationOfState(this, pin); InitUserMeshBlockData(pin); // load hydro and field data int os=0; memcpy(phydro->u.data(), &(mbdata[os]), phydro->u.GetSizeInBytes()); // load it into the half-step arrays too memcpy(phydro->u1.data(), &(mbdata[os]), phydro->u1.GetSizeInBytes()); os += phydro->u.GetSizeInBytes(); if (GENERAL_RELATIVITY) { memcpy(phydro->w.data(), &(mbdata[os]), phydro->w.GetSizeInBytes()); os += phydro->w.GetSizeInBytes(); memcpy(phydro->w1.data(), &(mbdata[os]), phydro->w1.GetSizeInBytes()); os += phydro->w1.GetSizeInBytes(); } if (MAGNETIC_FIELDS_ENABLED) { memcpy(pfield->b.x1f.data(), &(mbdata[os]), pfield->b.x1f.GetSizeInBytes()); memcpy(pfield->b1.x1f.data(), &(mbdata[os]), pfield->b1.x1f.GetSizeInBytes()); os += pfield->b.x1f.GetSizeInBytes(); memcpy(pfield->b.x2f.data(), &(mbdata[os]), pfield->b.x2f.GetSizeInBytes()); memcpy(pfield->b1.x2f.data(), &(mbdata[os]), pfield->b1.x2f.GetSizeInBytes()); os += pfield->b.x2f.GetSizeInBytes(); memcpy(pfield->b.x3f.data(), &(mbdata[os]), pfield->b.x3f.GetSizeInBytes()); memcpy(pfield->b1.x3f.data(), &(mbdata[os]), pfield->b1.x3f.GetSizeInBytes()); os += pfield->b.x3f.GetSizeInBytes(); } // NEW_PHYSICS: add load of new physics from restart file here // load user MeshBlock data for(int n=0; n<nint_user_meshblock_data_; n++) { memcpy(iuser_meshblock_data[n].data(), &(mbdata[os]), iuser_meshblock_data[n].GetSizeInBytes()); os+=iuser_meshblock_data[n].GetSizeInBytes(); } for(int n=0; n<nreal_user_meshblock_data_; n++) { memcpy(ruser_meshblock_data[n].data(), &(mbdata[os]), ruser_meshblock_data[n].GetSizeInBytes()); os+=ruser_meshblock_data[n].GetSizeInBytes(); } return; } //---------------------------------------------------------------------------------------- // MeshBlock destructor MeshBlock::~MeshBlock() { if(prev!=NULL) prev->next=next; if(next!=NULL) next->prev=prev; delete pcoord; if (block_bcs[INNER_X2] == POLAR_BNDRY||block_bcs[INNER_X2] == POLAR_BNDRY_WEDGE) delete[] polar_neighbor_north; if (block_bcs[OUTER_X2] == POLAR_BNDRY||block_bcs[OUTER_X2] == POLAR_BNDRY_WEDGE) delete[] polar_neighbor_south; delete pbval; delete precon; if (pmy_mesh->multilevel == true) delete pmr; delete phydro; if (MAGNETIC_FIELDS_ENABLED) delete pfield; delete peos; // delete user output variables array if(nuser_out_var > 0) { user_out_var.DeleteAthenaArray(); delete [] user_out_var_names_; } // delete user MeshBlock data for(int n=0; n<nreal_user_meshblock_data_; n++) ruser_meshblock_data[n].DeleteAthenaArray(); if(nreal_user_meshblock_data_>0) delete [] ruser_meshblock_data; for(int n=0; n<nint_user_meshblock_data_; n++) iuser_meshblock_data[n].DeleteAthenaArray(); if(nint_user_meshblock_data_>0) delete [] iuser_meshblock_data; } //---------------------------------------------------------------------------------------- //! \fn void MeshBlock::AllocateRealUserMeshBlockDataField(int n) // \brief Allocate Real AthenaArrays for user-defned data in MeshBlock void MeshBlock::AllocateRealUserMeshBlockDataField(int n) { if(nreal_user_meshblock_data_!=0) { std::stringstream msg; msg << "### FATAL ERROR in MeshBlock::AllocateRealUserMeshBlockDataField" << std::endl << "User MeshBlock data arrays are already allocated" << std::endl; throw std::runtime_error(msg.str().c_str()); } nreal_user_meshblock_data_=n; ruser_meshblock_data = new AthenaArray<Real>[n]; return; } //---------------------------------------------------------------------------------------- //! \fn void MeshBlock::AllocateIntUserMeshBlockDataField(int n) // \brief Allocate integer AthenaArrays for user-defned data in MeshBlock void MeshBlock::AllocateIntUserMeshBlockDataField(int n) { if(nint_user_meshblock_data_!=0) { std::stringstream msg; msg << "### FATAL ERROR in MeshBlock::AllocateIntusermeshblockDataField" << std::endl << "User MeshBlock data arrays are already allocated" << std::endl; throw std::runtime_error(msg.str().c_str()); return; } nint_user_meshblock_data_=n; iuser_meshblock_data = new AthenaArray<int>[n]; return; } //---------------------------------------------------------------------------------------- //! \fn void MeshBlock::AllocateUserOutputVariables(int n) // \brief Allocate user-defined output variables void MeshBlock::AllocateUserOutputVariables(int n) { if(n<=0) return; if(nuser_out_var!=0) { std::stringstream msg; msg << "### FATAL ERROR in MeshBlock::AllocateUserOutputVariables" << std::endl << "User output variables are already allocated." << std::endl; throw std::runtime_error(msg.str().c_str()); return; } nuser_out_var=n; int ncells1 = block_size.nx1 + 2*(NGHOST); int ncells2 = 1, ncells3 = 1; if (block_size.nx2 > 1) ncells2 = block_size.nx2 + 2*(NGHOST); if (block_size.nx3 > 1) ncells3 = block_size.nx3 + 2*(NGHOST); user_out_var.NewAthenaArray(nuser_out_var,ncells3,ncells2,ncells1); user_out_var_names_ = new std::string[n]; return; } //---------------------------------------------------------------------------------------- //! \fn void MeshBlock::SetUserOutputVariableName(int n, const char *name) // \brief set the user-defined output variable name void MeshBlock::SetUserOutputVariableName(int n, const char *name) { if(n>=nuser_out_var) { std::stringstream msg; msg << "### FATAL ERROR in MeshBlock::SetUserOutputVariableName" << std::endl << "User output variable is not allocated." << std::endl; throw std::runtime_error(msg.str().c_str()); return; } user_out_var_names_[n]=name; return; } //---------------------------------------------------------------------------------------- //! \fn size_t MeshBlock::GetBlockSizeInBytes(void) // \brief Calculate the block data size required for restart. size_t MeshBlock::GetBlockSizeInBytes(void) { size_t size; size=phydro->u.GetSizeInBytes(); if (GENERAL_RELATIVITY) { size+=phydro->w.GetSizeInBytes(); size+=phydro->w1.GetSizeInBytes(); } if (MAGNETIC_FIELDS_ENABLED) size+=(pfield->b.x1f.GetSizeInBytes()+pfield->b.x2f.GetSizeInBytes() +pfield->b.x3f.GetSizeInBytes()); // NEW_PHYSICS: modify the size counter here when new physics is introduced // calculate user MeshBlock data size for(int n=0; n<nint_user_meshblock_data_; n++) size+=iuser_meshblock_data[n].GetSizeInBytes(); for(int n=0; n<nreal_user_meshblock_data_; n++) size+=ruser_meshblock_data[n].GetSizeInBytes(); return size; } //---------------------------------------------------------------------------------------- // \!fn void NeighborBlock::SetNeighbor(int irank, int ilevel, int igid, int ilid, // int iox1, int iox2, int iox3, enum NeighborType itype, // int ibid, int itargetid, int ifi1=0, int ifi2=0, // bool ipolar=false) // \brief Set neighbor information void NeighborBlock::SetNeighbor(int irank, int ilevel, int igid, int ilid, int iox1, int iox2, int iox3, enum NeighborType itype, int ibid, int itargetid, bool ipolar, int ifi1=0, int ifi2=0) { rank=irank; level=ilevel; gid=igid; lid=ilid; ox1=iox1; ox2=iox2; ox3=iox3; type=itype; bufid=ibid; targetid=itargetid; polar=ipolar; fi1=ifi1; fi2=ifi2; if(type==NEIGHBOR_FACE) { if(ox1==-1) fid=INNER_X1; else if(ox1==1) fid=OUTER_X1; else if(ox2==-1) fid=INNER_X2; else if(ox2==1) fid=OUTER_X2; else if(ox3==-1) fid=INNER_X3; else if(ox3==1) fid=OUTER_X3; } if(type==NEIGHBOR_EDGE) { if(ox3==0) eid=( ((ox1+1)>>1) | ((ox2+1)&2)); else if(ox2==0) eid=(4+(((ox1+1)>>1) | ((ox3+1)&2))); else if(ox1==0) eid=(8+(((ox2+1)>>1) | ((ox3+1)&2))); } return; } //---------------------------------------------------------------------------------------- // \!fn void MeshBlock::SearchAndSetNeighbors(MeshBlockTree &tree, int *ranklist, int *nslist) // \brief Search and set all the neighbor blocks void MeshBlock::SearchAndSetNeighbors(MeshBlockTree &tree, int *ranklist, int *nslist) { MeshBlockTree* neibt; int myox1, myox2=0, myox3=0, myfx1, myfx2, myfx3; myfx1=(int)(loc.lx1&1L); myfx2=(int)(loc.lx2&1L); myfx3=(int)(loc.lx3&1L); myox1=((int)(loc.lx1&1L))*2-1; if(block_size.nx2>1) myox2=((int)(loc.lx2&1L))*2-1; if(block_size.nx3>1) myox3=((int)(loc.lx3&1L))*2-1; long int nrbx1=pmy_mesh->nrbx1, nrbx2=pmy_mesh->nrbx2, nrbx3=pmy_mesh->nrbx3; int nf1=1, nf2=1; if(pmy_mesh->multilevel==true) { if(block_size.nx2>1) nf1=2; if(block_size.nx3>1) nf2=2; } int bufid=0; nneighbor=0; for(int k=0; k<=2; k++) { for(int j=0; j<=2; j++) { for(int i=0; i<=2; i++) nblevel[k][j][i]=-1; } } nblevel[1][1][1]=loc.level; // x1 face for(int n=-1; n<=1; n+=2) { neibt=tree.FindNeighbor(loc,n,0,0,block_bcs,nrbx1,nrbx2,nrbx3,pmy_mesh->root_level); if(neibt==NULL) { bufid+=nf1*nf2; continue;} if(neibt->flag==false) { // neighbor at finer level int fface=1-(n+1)/2; // 0 for OUTER_X1, 1 for INNER_X1 nblevel[1][1][n+1]=neibt->loc.level+1; for(int f2=0;f2<nf2;f2++) { for(int f1=0;f1<nf1;f1++) { MeshBlockTree* nf=neibt->GetLeaf(fface,f1,f2); int fid = nf->gid; int nlevel=nf->loc.level; int tbid=FindBufferID(-n,0,0,0,0,pmy_mesh->maxneighbor_); neighbor[nneighbor].SetNeighbor(ranklist[fid], nlevel, fid, fid-nslist[ranklist[fid]], n, 0, 0, NEIGHBOR_FACE, bufid, tbid, false, f1, f2); bufid++; nneighbor++; } } } else { // neighbor at same or coarser level int nlevel=neibt->loc.level; int nid=neibt->gid; nblevel[1][1][n+1]=nlevel; int tbid; if(nlevel==loc.level) { // neighbor at same level tbid=FindBufferID(-n,0,0,0,0,pmy_mesh->maxneighbor_); } else { // neighbor at coarser level tbid=FindBufferID(-n,0,0,myfx2,myfx3,pmy_mesh->maxneighbor_); } neighbor[nneighbor].SetNeighbor(ranklist[nid], nlevel, nid, nid-nslist[ranklist[nid]], n, 0, 0, NEIGHBOR_FACE, bufid, tbid, false); bufid+=nf1*nf2; nneighbor++; } } if(block_size.nx2==1) return; // x2 face for(int n=-1; n<=1; n+=2) { neibt=tree.FindNeighbor(loc,0,n,0,block_bcs,nrbx1,nrbx2,nrbx3,pmy_mesh->root_level); if(neibt==NULL) { bufid+=nf1*nf2; continue;} if(neibt->flag==false) { // neighbor at finer level int fface=1-(n+1)/2; // 0 for OUTER_X2, 1 for INNER_X2 nblevel[1][n+1][1]=neibt->loc.level+1; for(int f2=0;f2<nf2;f2++) { for(int f1=0;f1<nf1;f1++) { MeshBlockTree* nf=neibt->GetLeaf(f1,fface,f2); int fid = nf->gid; int nlevel=nf->loc.level; int tbid=FindBufferID(0,-n,0,0,0,pmy_mesh->maxneighbor_); neighbor[nneighbor].SetNeighbor(ranklist[fid], nlevel, fid, fid-nslist[ranklist[fid]], 0, n, 0, NEIGHBOR_FACE, bufid, tbid, false, f1, f2); bufid++; nneighbor++; } } } else { // neighbor at same or coarser level int nlevel=neibt->loc.level; int nid=neibt->gid; nblevel[1][n+1][1]=nlevel; int tbid; bool polar=false; if(nlevel==loc.level) { // neighbor at same level if ((n == -1 and block_bcs[INNER_X2] == POLAR_BNDRY) or (n == 1 and block_bcs[OUTER_X2] == POLAR_BNDRY)) { polar = true; // neighbor is across top or bottom pole } tbid=FindBufferID(0,polar?n:-n,0,0,0,pmy_mesh->maxneighbor_); } else { // neighbor at coarser level tbid=FindBufferID(0,-n,0,myfx1,myfx3,pmy_mesh->maxneighbor_); } neighbor[nneighbor].SetNeighbor(ranklist[nid], nlevel, nid, nid-nslist[ranklist[nid]], 0, n, 0, NEIGHBOR_FACE, bufid, tbid, polar); bufid+=nf1*nf2; nneighbor++; } } // x3 face if(block_size.nx3>1) { for(int n=-1; n<=1; n+=2) { neibt=tree.FindNeighbor(loc,0,0,n,block_bcs,nrbx1,nrbx2,nrbx3,pmy_mesh->root_level); if(neibt==NULL) { bufid+=nf1*nf2; continue;} if(neibt->flag==false) { // neighbor at finer level int fface=1-(n+1)/2; // 0 for OUTER_X3, 1 for INNER_X3 nblevel[n+1][1][1]=neibt->loc.level+1; for(int f2=0;f2<nf2;f2++) { for(int f1=0;f1<nf1;f1++) { MeshBlockTree* nf=neibt->GetLeaf(f1,f2,fface); int fid = nf->gid; int nlevel=nf->loc.level; int tbid=FindBufferID(0,0,-n,0,0,pmy_mesh->maxneighbor_); neighbor[nneighbor].SetNeighbor(ranklist[fid], nlevel, fid, fid-nslist[ranklist[fid]], 0, 0, n, NEIGHBOR_FACE, bufid, tbid, false, f1, f2); bufid++; nneighbor++; } } } else { // neighbor at same or coarser level int nlevel=neibt->loc.level; int nid=neibt->gid; nblevel[n+1][1][1]=nlevel; int tbid; if(nlevel==loc.level) { // neighbor at same level tbid=FindBufferID(0,0,-n,0,0,pmy_mesh->maxneighbor_); } else { // neighbor at coarser level tbid=FindBufferID(0,0,-n,myfx1,myfx2,pmy_mesh->maxneighbor_); } neighbor[nneighbor].SetNeighbor(ranklist[nid], nlevel, nid, nid-nslist[ranklist[nid]], 0, 0, n, NEIGHBOR_FACE, bufid, tbid, false); bufid+=nf1*nf2; nneighbor++; } } } // x1x2 edge for(int m=-1; m<=1; m+=2) { for(int n=-1; n<=1; n+=2) { neibt=tree.FindNeighbor(loc,n,m,0,block_bcs,nrbx1,nrbx2,nrbx3,pmy_mesh->root_level); if(neibt==NULL) { bufid+=nf2; continue;} if(neibt->flag==false) { // neighbor at finer level int ff1=1-(n+1)/2; // 0 for OUTER_X1, 1 for INNER_X1 int ff2=1-(m+1)/2; // 0 for OUTER_X2, 1 for INNER_X2 nblevel[1][m+1][n+1]=neibt->loc.level+1; for(int f1=0;f1<nf2;f1++) { MeshBlockTree* nf=neibt->GetLeaf(ff1,ff2,f1); int fid = nf->gid; int nlevel=nf->loc.level; int tbid=FindBufferID(-n,-m,0,0,0,pmy_mesh->maxneighbor_); neighbor[nneighbor].SetNeighbor(ranklist[fid], nlevel, fid, fid-nslist[ranklist[fid]], n, m, 0, NEIGHBOR_EDGE, bufid, tbid, false, f1, 0); bufid++; nneighbor++; } } else { // neighbor at same or coarser level int nlevel=neibt->loc.level; int nid=neibt->gid; nblevel[1][m+1][n+1]=nlevel; int tbid; bool polar=false; if(nlevel==loc.level) { // neighbor at same level if ((m == -1 and block_bcs[INNER_X2] == POLAR_BNDRY) or (m == 1 and block_bcs[OUTER_X2] == POLAR_BNDRY)) { polar = true; // neighbor is across top or bottom pole } tbid=FindBufferID(-n,polar?m:-m,0,0,0,pmy_mesh->maxneighbor_); } else { // neighbor at coarser level tbid=FindBufferID(-n,polar?m:-m,0,myfx3,0,pmy_mesh->maxneighbor_); } if(nlevel>=loc.level || (myox1==n && myox2==m)) { neighbor[nneighbor].SetNeighbor(ranklist[nid], nlevel, nid, nid-nslist[ranklist[nid]], n, m, 0, NEIGHBOR_EDGE, bufid, tbid, polar); nneighbor++; } bufid+=nf2; } } } // polar neighbors if (block_bcs[INNER_X2] == POLAR_BNDRY||block_bcs[INNER_X2] == POLAR_BNDRY_WEDGE) { int level = loc.level - pmy_mesh->root_level; int num_north_polar_blocks = nrbx3 * (1 << level); for (int n = 0; n < num_north_polar_blocks; ++n) { LogicalLocation neighbor_loc; neighbor_loc.lx1 = loc.lx1; neighbor_loc.lx2 = loc.lx2; neighbor_loc.lx3 = n; neighbor_loc.level = loc.level; neibt = tree.FindMeshBlock(neighbor_loc); int nid = neibt->gid; polar_neighbor_north[neibt->loc.lx3].rank = ranklist[nid]; polar_neighbor_north[neibt->loc.lx3].lid = nid - nslist[ranklist[nid]]; polar_neighbor_north[neibt->loc.lx3].gid = nid; polar_neighbor_north[neibt->loc.lx3].north = true; } } if (block_bcs[OUTER_X2] == POLAR_BNDRY||block_bcs[OUTER_X2] == POLAR_BNDRY_WEDGE) { int level = loc.level - pmy_mesh->root_level; int num_south_polar_blocks = nrbx3 * (1 << level); for (int n = 0; n < num_south_polar_blocks; ++n) { LogicalLocation neighbor_loc; neighbor_loc.lx1 = loc.lx1; neighbor_loc.lx2 = loc.lx2; neighbor_loc.lx3 = n; neighbor_loc.level = loc.level; neibt = tree.FindMeshBlock(neighbor_loc); int nid = neibt->gid; polar_neighbor_south[neibt->loc.lx3].rank = ranklist[nid]; polar_neighbor_south[neibt->loc.lx3].lid = nid - nslist[ranklist[nid]]; polar_neighbor_south[neibt->loc.lx3].gid = nid; polar_neighbor_south[neibt->loc.lx3].north = false; } } if(block_size.nx3==1) return; // x1x3 edge for(int m=-1; m<=1; m+=2) { for(int n=-1; n<=1; n+=2) { neibt=tree.FindNeighbor(loc,n,0,m,block_bcs,nrbx1,nrbx2,nrbx3,pmy_mesh->root_level); if(neibt==NULL) { bufid+=nf1; continue;} if(neibt->flag==false) { // neighbor at finer level int ff1=1-(n+1)/2; // 0 for OUTER_X1, 1 for INNER_X1 int ff2=1-(m+1)/2; // 0 for OUTER_X3, 1 for INNER_X3 nblevel[m+1][1][n+1]=neibt->loc.level+1; for(int f1=0;f1<nf1;f1++) { MeshBlockTree* nf=neibt->GetLeaf(ff1,f1,ff2); int fid = nf->gid; int nlevel=nf->loc.level; int tbid=FindBufferID(-n,0,-m,0,0,pmy_mesh->maxneighbor_); neighbor[nneighbor].SetNeighbor(ranklist[fid], nlevel, fid, fid-nslist[ranklist[fid]], n, 0, m, NEIGHBOR_EDGE, bufid, tbid, false, f1, 0); bufid++; nneighbor++; } } else { // neighbor at same or coarser level int nlevel=neibt->loc.level; int nid=neibt->gid; nblevel[m+1][1][n+1]=nlevel; int tbid; if(nlevel==loc.level) { // neighbor at same level tbid=FindBufferID(-n,0,-m,0,0,pmy_mesh->maxneighbor_); } else { // neighbor at coarser level tbid=FindBufferID(-n,0,-m,myfx2,0,pmy_mesh->maxneighbor_); } if(nlevel>=loc.level || (myox1==n && myox3==m)) { neighbor[nneighbor].SetNeighbor(ranklist[nid], nlevel, nid, nid-nslist[ranklist[nid]], n, 0, m, NEIGHBOR_EDGE, bufid, tbid, false); nneighbor++; } bufid+=nf1; } } } // x2x3 edge for(int m=-1; m<=1; m+=2) { for(int n=-1; n<=1; n+=2) { neibt=tree.FindNeighbor(loc,0,n,m,block_bcs,nrbx1,nrbx2,nrbx3,pmy_mesh->root_level); if(neibt==NULL) { bufid+=nf1; continue;} if(neibt->flag==false) { // neighbor at finer level int ff1=1-(n+1)/2; // 0 for OUTER_X2, 1 for INNER_X2 int ff2=1-(m+1)/2; // 0 for OUTER_X3, 1 for INNER_X3 nblevel[m+1][n+1][1]=neibt->loc.level+1; for(int f1=0;f1<nf1;f1++) { MeshBlockTree* nf=neibt->GetLeaf(f1,ff1,ff2); int fid = nf->gid; int nlevel=nf->loc.level; int tbid=FindBufferID(0,-n,-m,0,0,pmy_mesh->maxneighbor_); neighbor[nneighbor].SetNeighbor(ranklist[fid], nlevel, fid, fid-nslist[ranklist[fid]], 0, n, m, NEIGHBOR_EDGE, bufid, tbid, false, f1, 0); bufid++; nneighbor++; } } else { // neighbor at same or coarser level int nlevel=neibt->loc.level; int nid=neibt->gid; nblevel[m+1][n+1][1]=nlevel; int tbid; bool polar=false; if(nlevel==loc.level) { // neighbor at same level if ((n == -1 and block_bcs[INNER_X2] == POLAR_BNDRY) or (n == 1 and block_bcs[OUTER_X2] == POLAR_BNDRY)) { polar = true; // neighbor is across top or bottom pole } tbid=FindBufferID(0,polar?n:-n,-m,0,0,pmy_mesh->maxneighbor_); } else { // neighbor at coarser level tbid=FindBufferID(0,-n,-m,myfx1,0,pmy_mesh->maxneighbor_); } if(nlevel>=loc.level || (myox2==n && myox3==m)) { neighbor[nneighbor].SetNeighbor(ranklist[nid], nlevel, nid, nid-nslist[ranklist[nid]], 0, n, m, NEIGHBOR_EDGE, bufid, tbid, polar); nneighbor++; } bufid+=nf1; } } } // corners for(int l=-1; l<=1; l+=2) { for(int m=-1; m<=1; m+=2) { for(int n=-1; n<=1; n+=2) { neibt=tree.FindNeighbor(loc,n,m,l,block_bcs,nrbx1,nrbx2,nrbx3,pmy_mesh->root_level); if(neibt==NULL) { bufid++; continue;} bool polar=false; if ((m == -1 and block_bcs[INNER_X2] == POLAR_BNDRY) or (m == 1 and block_bcs[OUTER_X2] == POLAR_BNDRY)) { polar = true; // neighbor is across top or bottom pole } if(neibt->flag==false) { // neighbor at finer level int ff1=1-(n+1)/2; // 0 for OUTER_X1, 1 for INNER_X1 int ff2=1-(m+1)/2; // 0 for OUTER_X2, 1 for INNER_X2 int ff3=1-(l+1)/2; // 0 for OUTER_X3, 1 for INNER_X3 neibt=neibt->GetLeaf(ff1,ff2,ff3); } int nlevel=neibt->loc.level; nblevel[l+1][m+1][n+1]=nlevel; if(nlevel>=loc.level || (myox1==n && myox2==m && myox3==l)) { int nid=neibt->gid; int tbid=FindBufferID(-n,polar?m:-m,-l,0,0,pmy_mesh->maxneighbor_); neighbor[nneighbor].SetNeighbor(ranklist[nid], nlevel, nid, nid-nslist[ranklist[nid]], n, m, l, NEIGHBOR_CORNER, bufid, tbid, polar); nneighbor++; } bufid++; } } } return; }
36.92848
114
0.602628
cnstahl
6f0e1bb310c5c9f5987dbe30127e725c4f8edb79
782
cpp
C++
Contests/_Archived/Old-Lab/lg1691.cpp
DCTewi/My-Codes
9904f8057ec96e21cbc8cf9c62a49658a0f6d392
[ "MIT" ]
null
null
null
Contests/_Archived/Old-Lab/lg1691.cpp
DCTewi/My-Codes
9904f8057ec96e21cbc8cf9c62a49658a0f6d392
[ "MIT" ]
null
null
null
Contests/_Archived/Old-Lab/lg1691.cpp
DCTewi/My-Codes
9904f8057ec96e21cbc8cf9c62a49658a0f6d392
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int ans = 0; void print_permutation(int n, char* P, char* A, int cur) { if (cur == n) { for (int i = 0; i < n; i++) { printf("%c", A[i]); } printf("\n"); ans++; } else { for (int i = 0; i < n; i++) { if (P[i] != P[i - 1]) { int cp = 0, ca = 0; for (int j = 0; j < cur; j++) if (A[j] == P[i]) ca++; for (int j = 0; j < n; j++) if (P[i] == P[j]) cp++; if (ca < cp) { A[cur] = P[i]; print_permutation(n, P, A, cur + 1); } } } } return ; } int main(int argc, char const *argv[]) { int n; scanf("%d", &n); char A[n + 5], P[n + 5]; for (int i = 0; i < n; i++) { cin>>P[i]; } sort(P, P + n); print_permutation(n, P, A, 0); printf("%d\n", ans); return 0; }
14.481481
57
0.434783
DCTewi
6f10b13e822c9a8c2e32cd055d52134216d77cbb
4,190
cc
C++
content/shell/shell_download_manager_delegate.cc
Scopetta197/chromium
b7bf8e39baadfd9089de2ebdc0c5d982de4a9820
[ "BSD-3-Clause" ]
212
2015-01-31T11:55:58.000Z
2022-02-22T06:35:11.000Z
content/shell/shell_download_manager_delegate.cc
Scopetta197/chromium
b7bf8e39baadfd9089de2ebdc0c5d982de4a9820
[ "BSD-3-Clause" ]
5
2015-03-27T14:29:23.000Z
2019-09-25T13:23:12.000Z
content/shell/shell_download_manager_delegate.cc
Scopetta197/chromium
b7bf8e39baadfd9089de2ebdc0c5d982de4a9820
[ "BSD-3-Clause" ]
221
2015-01-07T06:21:24.000Z
2022-02-11T02:51:12.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/shell/shell_download_manager_delegate.h" #if defined(OS_WIN) #include <windows.h> #include <commdlg.h> #endif #include "base/bind.h" #include "base/file_util.h" #include "base/logging.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/download_manager.h" #include "content/public/browser/web_contents.h" #include "net/base/net_util.h" namespace content { ShellDownloadManagerDelegate::ShellDownloadManagerDelegate() : download_manager_(NULL) { } ShellDownloadManagerDelegate::~ShellDownloadManagerDelegate(){ } void ShellDownloadManagerDelegate::SetDownloadManager( DownloadManager* download_manager) { download_manager_ = download_manager; } DownloadId ShellDownloadManagerDelegate::GetNextId() { static int next_id; return DownloadId(this, ++next_id); } bool ShellDownloadManagerDelegate::ShouldStartDownload(int32 download_id) { DownloadItem* download = download_manager_->GetActiveDownloadItem(download_id); DownloadStateInfo state = download->GetStateInfo(); if (!state.force_file_name.empty()) return true; FilePath generated_name = net::GenerateFileName( download->GetURL(), download->GetContentDisposition(), download->GetReferrerCharset(), download->GetSuggestedFilename(), download->GetMimeType(), "download"); // Since we have no download UI, show the user a dialog always. state.prompt_user_for_save_location = true; BrowserThread::PostTask( BrowserThread::FILE, FROM_HERE, base::Bind( &ShellDownloadManagerDelegate::GenerateFilename, this, download_id, state, generated_name)); return false; } void ShellDownloadManagerDelegate::GenerateFilename( int32 download_id, DownloadStateInfo state, const FilePath& generated_name) { if (state.suggested_path.empty()) { state.suggested_path = download_manager_->GetBrowserContext()->GetPath(). Append(FILE_PATH_LITERAL("Downloads")); if (!file_util::PathExists(state.suggested_path)) file_util::CreateDirectory(state.suggested_path); } state.suggested_path = state.suggested_path.Append(generated_name); BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind( &ShellDownloadManagerDelegate::RestartDownload, this, download_id, state)); } void ShellDownloadManagerDelegate::RestartDownload( int32 download_id, DownloadStateInfo state) { DownloadItem* download = download_manager_->GetActiveDownloadItem(download_id); if (!download) return; download->SetFileCheckResults(state); download_manager_->RestartDownload(download_id); } void ShellDownloadManagerDelegate::ChooseDownloadPath( WebContents* web_contents, const FilePath& suggested_path, int32 download_id) { FilePath result; #if defined(OS_WIN) && !defined(USE_AURA) std::wstring file_part = FilePath(suggested_path).BaseName().value(); wchar_t file_name[MAX_PATH]; base::wcslcpy(file_name, file_part.c_str(), arraysize(file_name)); OPENFILENAME save_as; ZeroMemory(&save_as, sizeof(save_as)); save_as.lStructSize = sizeof(OPENFILENAME); save_as.hwndOwner = web_contents->GetNativeView(); save_as.lpstrFile = file_name; save_as.nMaxFile = arraysize(file_name); std::wstring directory; if (!suggested_path.empty()) directory = suggested_path.DirName().value(); save_as.lpstrInitialDir = directory.c_str(); save_as.Flags = OFN_OVERWRITEPROMPT | OFN_EXPLORER | OFN_ENABLESIZING | OFN_NOCHANGEDIR | OFN_PATHMUSTEXIST; if (GetSaveFileName(&save_as)) result = FilePath(std::wstring(save_as.lpstrFile)); #else NOTIMPLEMENTED(); #endif if (result.empty()) { download_manager_->FileSelectionCanceled(download_id); } else { download_manager_->FileSelected(result, download_id); } } } // namespace content
29.716312
77
0.744153
Scopetta197
6f115aa6fcd24a9e111e7cdca5e2adbf6d61a756
2,854
hpp
C++
Code/SMReaders/PrefabReader.hpp
QuestionableM/Tile-Converter
28e86e0e3f6df5872721a7903c5e8bc2e8e73dde
[ "MIT" ]
2
2022-01-08T19:12:12.000Z
2022-01-24T09:31:08.000Z
Code/SMReaders/PrefabReader.hpp
QuestionableM/Tile-Converter
28e86e0e3f6df5872721a7903c5e8bc2e8e73dde
[ "MIT" ]
null
null
null
Code/SMReaders/PrefabReader.hpp
QuestionableM/Tile-Converter
28e86e0e3f6df5872721a7903c5e8bc2e8e73dde
[ "MIT" ]
1
2022-01-08T19:12:16.000Z
2022-01-08T19:12:16.000Z
#pragma once #include "Tile/CellHeader.hpp" #include "Tile/TilePart.hpp" #include "Tile/Tile.hpp" #include "Tile/Object/Prefab.h" #include "Utils/Memory.hpp" #include "SMReaders/PrefabFileReader.hpp" #include "ObjectDatabase/KeywordReplacer.hpp" #include <lz4/lz4.h> class PrefabReader { PrefabReader() = default; public: #pragma warning(push) #pragma warning(disable : 4996) static void Read(CellHeader* header, MemoryWrapper& reader, TilePart* part, ConvertError& cError) { if (cError || !ConvertSettings::ExportPrefabs) return; if (header->prefabCount == 0 || header->prefabIndex == 0) return; DebugOutL("Prefab: ", header->prefabSize, " / ", header->prefabCompressedSize); std::vector<Byte> compressed = reader.Objects<Byte>(header->prefabIndex, header->prefabCompressedSize); std::vector<Byte> bytes = {}; bytes.resize(header->prefabSize); int debugSize = LZ4_decompress_fast((char*)compressed.data(), (char*)bytes.data(), header->prefabSize); if (debugSize != header->prefabCompressedSize) { cError = ConvertError(1, L"PrefabReader::Read -> debugSize != header->prefabCompressedSize"); return; } debugSize = PrefabReader::Read(bytes, header->prefabCount, part); if (debugSize != header->prefabSize) { cError = ConvertError(1, L"PrefabReader::Read -> debugSize != header->prefabSize"); return; } } #pragma warning(pop) static int Read(const std::vector<Byte>& bytes, const int& prefabCount, TilePart* part) { int index = 0; MemoryWrapper memory(bytes); const int version = part->GetParent()->GetVersion(); for (int a = 0; a < prefabCount; a++) { const glm::vec3 f_pos = memory.Object<glm::vec3>(index); const glm::quat f_quat = memory.GetQuat(index + 0xc); glm::vec3 f_size; if (version < 9) { f_size = glm::vec3(1.0f); index += 0x1c; } else { f_size = memory.Object<glm::vec3>(index + 0x1c); index += 0x28; } const int string_length = memory.Object<int>(index); index += 4; const std::vector<char> path = memory.Objects<char>(index, string_length); index += string_length; const int bVar2 = (int)memory.Object<Byte>(index) & 0xff; index += 1; const std::vector<char> flag = memory.Objects<char>(index, bVar2); index += bVar2; index += 4; const std::wstring wide_path = String::ToWide(std::string(path.begin(), path.end())); const std::wstring pref_path = KeywordReplacer::ReplaceKey(wide_path); const std::wstring pref_flag = String::ToWide(std::string(flag.begin(), flag.end())); DebugOutL("Prefab Path: ", pref_path); Prefab* pNewPrefab = PrefabFileReader::Read(pref_path, pref_flag); if (!pNewPrefab) continue; pNewPrefab->SetPosition(f_pos); pNewPrefab->SetRotation(f_quat); pNewPrefab->SetSize(f_size); part->AddObject(pNewPrefab); } return index; } };
27.180952
105
0.684303
QuestionableM
6f11b5c3d27f96940e8d7068c184eff7b7837b47
211
cpp
C++
CPPprogrammnng_code/C++_Code/string_to_number.cpp
Glenn-Po/LearningCandCPP
4cd2d3386dbe6691a007c42036fb9ebe932e011e
[ "Apache-2.0" ]
null
null
null
CPPprogrammnng_code/C++_Code/string_to_number.cpp
Glenn-Po/LearningCandCPP
4cd2d3386dbe6691a007c42036fb9ebe932e011e
[ "Apache-2.0" ]
null
null
null
CPPprogrammnng_code/C++_Code/string_to_number.cpp
Glenn-Po/LearningCandCPP
4cd2d3386dbe6691a007c42036fb9ebe932e011e
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <conio.h> // implements functions similar to atoi, stod, stol, atof, int to_int(const char[]) int to_int(stringconst); main(){ cout << "Enter a string to convert to number : \n" }
21.1
58
0.701422
Glenn-Po
6f12f5908053b9a391a068d373417fe3ac08cb86
13,608
cpp
C++
sesame2spiner/generate_files.cpp
lanl/singularity-eos
c35669b93a492903ad4ce7a15211bd42b7c88d37
[ "BSD-3-Clause" ]
3
2021-04-14T15:08:37.000Z
2021-06-28T16:32:19.000Z
sesame2spiner/generate_files.cpp
lanl/singularity-eos
c35669b93a492903ad4ce7a15211bd42b7c88d37
[ "BSD-3-Clause" ]
70
2021-04-15T23:08:34.000Z
2022-03-31T17:43:18.000Z
sesame2spiner/generate_files.cpp
lanl/singularity-eos
c35669b93a492903ad4ce7a15211bd42b7c88d37
[ "BSD-3-Clause" ]
2
2021-05-21T16:59:30.000Z
2021-08-17T20:52:38.000Z
//====================================================================== // sesame2spiner tool for converting eospac to spiner // Author: Jonah Miller (jonahm@lanl.gov) // © 2021. Triad National Security, LLC. All rights reserved. This // program was produced under U.S. Government contract 89233218CNA000001 // for Los Alamos National Laboratory (LANL), which is operated by Triad // National Security, LLC for the U.S. Department of Energy/National // Nuclear Security Administration. All rights in the program are // reserved by Triad National Security, LLC, and the U.S. Department of // Energy/National Nuclear Security Administration. The Government is // granted for itself and others acting on its behalf a nonexclusive, // paid-up, irrevocable worldwide license in this material to reproduce, // prepare derivative works, distribute copies to the public, perform // publicly and display publicly, and to permit others to do so. //====================================================================== #include <cmath> #include <cstdlib> #include <limits> #include <string> #include <unordered_map> #include <unordered_set> #include <vector> #include <hdf5.h> #include <hdf5_hl.h> #ifndef SPINER_USE_HDF #error "HDF5 must be enabled" #endif // SPINER_USE_HDF #include <eospac-wrapper/eospac_wrapper.hpp> #include <sp5/singularity_eos_sp5.hpp> #include <spiner/databox.hpp> #include <spiner/interpolation.hpp> #include <spiner/ports-of-call/portability.hpp> #include <spiner/sp5.hpp> #include "generate_files.hpp" #include "io_eospac.hpp" #include "parse_cli.hpp" #include "parser.hpp" using namespace EospacWrapper; herr_t saveMaterial(hid_t loc, const SesameMetadata &metadata, const Bounds &lRhoBounds, const Bounds &lTBounds, const Bounds &leBounds, const std::string &name, Verbosity eospacWarn) { const int matid = metadata.matid; std::string sMatid = std::to_string(matid); herr_t status = 0; hid_t matGroup, lTGroup, leGroup, coldGroup; matGroup = H5Gcreate(loc, sMatid.c_str(), H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); status += H5Lcreate_soft(sMatid.c_str(), loc, name.c_str(), H5P_DEFAULT, H5P_DEFAULT); // Dependent variables metadata status += H5LTset_attribute_string(loc, sMatid.c_str(), SP5::Offsets::messageName, SP5::Offsets::message); status += H5LTset_attribute_double(loc, sMatid.c_str(), SP5::Offsets::rho, &lRhoBounds.offset, 1); status += H5LTset_attribute_double(loc, sMatid.c_str(), SP5::Offsets::T, &lTBounds.offset, 1); status += H5LTset_attribute_double(loc, sMatid.c_str(), SP5::Offsets::sie, &leBounds.offset, 1); // Material metadata status += H5LTset_attribute_double(loc, sMatid.c_str(), SP5::Material::exchangeCoefficient, &metadata.exchangeCoefficient, 1); status += H5LTset_attribute_double(loc, sMatid.c_str(), SP5::Material::meanAtomicMass, &metadata.meanAtomicMass, 1); status += H5LTset_attribute_double(loc, sMatid.c_str(), SP5::Material::meanAtomicNumber, &metadata.meanAtomicNumber, 1); status += H5LTset_attribute_double(loc, sMatid.c_str(), SP5::Material::solidBulkModulus, &metadata.solidBulkModulus, 1); status += H5LTset_attribute_double(loc, sMatid.c_str(), SP5::Material::normalDensity, &metadata.normalDensity, 1); status += H5LTset_attribute_string(loc, sMatid.c_str(), SP5::Material::comments, metadata.comments.c_str()); status += H5LTset_attribute_int(loc, sMatid.c_str(), SP5::Material::matid, &metadata.matid, 1); status += H5LTset_attribute_string(loc, sMatid.c_str(), SP5::Material::name, metadata.name.c_str()); lTGroup = H5Gcreate(matGroup, SP5::Depends::logRhoLogT, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); leGroup = H5Gcreate(matGroup, SP5::Depends::logRhoLogSie, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); coldGroup = H5Gcreate(matGroup, SP5::Depends::coldCurve, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); { DataBox P, sie, T, bMod, dPdRho, dPdE, dTdRho, dTdE, dEdRho, mask; eosDataOfRhoSie(matid, lRhoBounds, leBounds, P, T, bMod, dPdRho, dPdE, dTdRho, dTdE, dEdRho, mask, eospacWarn); status += P.saveHDF(leGroup, SP5::Fields::P); status += T.saveHDF(leGroup, SP5::Fields::T); status += bMod.saveHDF(leGroup, SP5::Fields::bMod); status += dPdRho.saveHDF(leGroup, SP5::Fields::dPdRho); status += dPdE.saveHDF(leGroup, SP5::Fields::dPdE); status += dTdRho.saveHDF(leGroup, SP5::Fields::dTdRho); status += dTdE.saveHDF(leGroup, SP5::Fields::dTdE); status += dEdRho.saveHDF(leGroup, SP5::Fields::dEdRho); status += mask.saveHDF(leGroup, SP5::Fields::mask); } { DataBox P, sie, T, bMod, dPdRho, dPdE, dTdRho, dTdE, dEdRho, dEdT, mask; eosDataOfRhoT(matid, lRhoBounds, lTBounds, P, sie, bMod, dPdRho, dPdE, dTdRho, dTdE, dEdRho, dEdT, mask, eospacWarn); status += P.saveHDF(lTGroup, SP5::Fields::P); status += sie.saveHDF(lTGroup, SP5::Fields::sie); status += bMod.saveHDF(lTGroup, SP5::Fields::bMod); status += dPdRho.saveHDF(lTGroup, SP5::Fields::dPdRho); status += dPdE.saveHDF(lTGroup, SP5::Fields::dPdE); status += dTdRho.saveHDF(lTGroup, SP5::Fields::dTdRho); status += dTdE.saveHDF(lTGroup, SP5::Fields::dTdE); status += dEdRho.saveHDF(lTGroup, SP5::Fields::dEdRho); status += dEdT.saveHDF(lTGroup, SP5::Fields::dEdT); status += mask.saveHDF(lTGroup, SP5::Fields::mask); } { DataBox P, sie, dPdRho, dEdRho, bMod, mask, transitionMask; eosColdCurves(matid, lRhoBounds, P, sie, dPdRho, dEdRho, bMod, mask, eospacWarn); eosColdCurveMask(matid, lRhoBounds, leBounds.grid.nPoints(), sie, transitionMask, eospacWarn); status += P.saveHDF(coldGroup, SP5::Fields::P); status += sie.saveHDF(coldGroup, SP5::Fields::sie); status += bMod.saveHDF(coldGroup, SP5::Fields::bMod); status += dPdRho.saveHDF(coldGroup, SP5::Fields::dPdRho); status += dEdRho.saveHDF(coldGroup, SP5::Fields::dEdRho); status += mask.saveHDF(coldGroup, SP5::Fields::mask); status += transitionMask.saveHDF(coldGroup, SP5::Fields::transitionMask); } status += H5Gclose(leGroup); status += H5Gclose(lTGroup); status += H5Gclose(coldGroup); status += H5Gclose(matGroup); return status; } herr_t saveAllMaterials(const std::string &savename, const std::vector<std::string> &filenames, bool printMetadata, Verbosity eospacWarn) { std::vector<Params> params; std::vector<int> matids; std::unordered_map<std::string, int> used_names; std::unordered_set<int> used_matids; SesameMetadata metadata; hid_t file; herr_t status = H5_SUCCESS; for (auto const &filename : filenames) { Params p(filename); if (!p.Contains("matid")) { std::cerr << "Material file " << filename << "is missing matid.\n" << "Example input files:\n" << EXAMPLESTRING << std::endl; std::exit(1); } matids.push_back(p.Get<int>("matid")); params.push_back(p); } std::cout << "Saving to file " << savename << std::endl; file = H5Fcreate(savename.c_str(), H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT); std::cout << "Processing " << matids.size() << " materials..." << std::endl; for (size_t i = 0; i < matids.size(); i++) { int matid = matids[i]; if (used_matids.count(matid) > 0) { std::cerr << "...Duplicate matid " << matid << " detected. Skipping." << std::endl; continue; } used_matids.insert(matid); std::cout << "..." << matid << std::endl; eosGetMetadata(matid, metadata, Verbosity::Debug); if (printMetadata) std::cout << metadata << std::endl; std::string name = params[i].Get("name", metadata.name); if (name == "-1" || name == "") { std::string new_name = "material_" + std::to_string(i); std::cerr << "...WARNING: no reasonable name found. " << "Using a default name: " << new_name << std::endl; name = new_name; } if (used_names.count(name) > 0) { used_names[name] += 1; std::string new_name = name + "_" + std::to_string(used_names[name]); std::cerr << "...WARNING: Name " << name << " already used. " << "Using name: " << new_name << std::endl; name = new_name; } else { used_names[name] = 1; } Bounds lRhoBounds, lTBounds, leBounds; getMatBounds(i, matid, metadata, params[i], lRhoBounds, lTBounds, leBounds); if (eospacWarn == Verbosity::Debug) { std::cout << "bounds for log(rho), log(T), log(sie) are:\n" << lRhoBounds << lTBounds << leBounds << std::endl; } status += saveMaterial(file, metadata, lRhoBounds, lTBounds, leBounds, name, eospacWarn); if (status != H5_SUCCESS) { std::cerr << "WARNING: problem with HDf5" << std::endl; } } std::cout << "Cleaning up." << std::endl; status += H5Fclose(file); if (status != H5_SUCCESS) { std::cerr << "WARNING: problem with HDf5" << std::endl; } return status; } void getMatBounds(int i, int matid, const SesameMetadata &metadata, const Params &params, Bounds &lRhoBounds, Bounds &lTBounds, Bounds &leBounds) { // The "epsilon" shifts here are required to avoid eospac // extrapolation errors at table bounds constexpr Real TINY = std::numeric_limits<Real>::epsilon(); auto TinyShift = [=](Real val, int sign) { Real shift = std::abs(std::min(10 * val * TINY, TINY)); return val + sign * shift; }; Real rhoMin = params.Get("rhomin", TinyShift(metadata.rhoMin, 1)); Real rhoMax = params.Get("rhomax", metadata.rhoMax); Real TMin = params.Get("Tmin", TinyShift(metadata.TMin, 1)); Real TMax = params.Get("Tmax", metadata.TMax); Real sieMin = params.Get("siemin", TinyShift(metadata.sieMin, 1)); Real sieMax = params.Get("siemax", metadata.sieMax); checkValInMatBounds(matid, "rhoMin", rhoMin, metadata.rhoMin, metadata.rhoMax); checkValInMatBounds(matid, "rhoMax", rhoMax, metadata.rhoMin, metadata.rhoMax); checkValInMatBounds(matid, "TMin", TMin, metadata.TMin, metadata.TMax); checkValInMatBounds(matid, "TMax", TMax, metadata.TMin, metadata.TMax); checkValInMatBounds(matid, "sieMin", sieMin, metadata.sieMin, metadata.sieMax); checkValInMatBounds(matid, "sieMax", sieMax, metadata.sieMin, metadata.sieMax); Real shrinklRhoBounds = params.Get("shrinklRhoBounds", 0.0); Real shrinklTBounds = params.Get("shrinklTBounds", 0.0); Real shrinkleBounds = params.Get("shrinkleBounds", 0.0); shrinklRhoBounds = std::min(1., std::max(shrinklRhoBounds, 0.)); shrinklTBounds = std::min(1., std::max(shrinklTBounds, 0.)); shrinkleBounds = std::min(1., std::max(shrinkleBounds, 0.)); if (shrinklRhoBounds > 0 && (params.Contains("rhomin") || params.Contains("rhomax"))) { std::cerr << "WARNING [" << matid << "]: " << "shrinklRhoBounds > 0 and rhomin or rhomax set" << std::endl; } if (shrinklTBounds > 0 && (params.Contains("Tmin") || params.Contains("Tmax"))) { std::cerr << "WARNING [" << matid << "]: " << "shrinklTBounds > 0 and Tmin or Tmax set" << std::endl; } if (shrinkleBounds > 0 && (params.Contains("siemin") || params.Contains("siemax"))) { std::cerr << "WARNING [" << matid << "]: " << "shrinkleBounds > 0 and siemin or siemax set" << std::endl; } int ppdRho = params.Get("numrho/decade", PPD_DEFAULT); int numRhoDefault = getNumPointsFromPPD(rhoMin, rhoMax, ppdRho); int ppdT = params.Get("numT/decade", PPD_DEFAULT); int numTDefault = getNumPointsFromPPD(TMin, TMax, ppdT); int ppdSie = params.Get("numSie/decade", PPD_DEFAULT); int numSieDefault = getNumPointsFromPPD(sieMin, sieMax, ppdSie); int numRho = params.Get("numrho", numRhoDefault); int numT = params.Get("numT", numTDefault); int numSie = params.Get("numsie", numSieDefault); Real rhoAnchor = metadata.normalDensity; Real TAnchor = 298.15; // Forces density and temperature to be in a region where an offset // is not needed. This improves resolution at low densities and // temperatures. // Extrapolation and other resolution tricks will be explored in the // future. if (rhoMin < STRICTLY_POS_MIN) rhoMin = STRICTLY_POS_MIN; if (TMin < STRICTLY_POS_MIN) TMin = STRICTLY_POS_MIN; lRhoBounds = Bounds(rhoMin, rhoMax, numRho, true, shrinklRhoBounds, rhoAnchor); lTBounds = Bounds(TMin, TMax, numT, true, shrinklTBounds, TAnchor); leBounds = Bounds(sieMin, sieMax, numSie, true, shrinkleBounds); return; } bool checkValInMatBounds(int matid, const std::string &name, Real val, Real vmin, Real vmax) { if (val < vmin || val > vmax) { std::cerr << "WARNING [" << matid << "]: " << name << " out of sesame table bounds. Consider changing this.\n" << "\t" << name << ", [bounds] = " << val << ", [" << vmin << ", " << vmax << "]" << std::endl; return false; } return true; } int getNumPointsFromPPD(Real min, Real max, int ppd) { Bounds b(min, max, 3, true); Real ndecades = b.grid.max() - b.grid.min(); return static_cast<int>(std::ceil(ppd * ndecades)); }
41.870769
90
0.639697
lanl
6f190c690e6104dc25b2a3f14b4035a8f6fdaf30
5,486
hpp
C++
bst/inc/RBT.hpp
kraylas/shit-code
d0565116deacd91497722659e0151112361d90f7
[ "MIT" ]
null
null
null
bst/inc/RBT.hpp
kraylas/shit-code
d0565116deacd91497722659e0151112361d90f7
[ "MIT" ]
null
null
null
bst/inc/RBT.hpp
kraylas/shit-code
d0565116deacd91497722659e0151112361d90f7
[ "MIT" ]
null
null
null
#pragma once #include <algorithm> #include <cassert> #include <compare> #include <cstddef> #include <cstdint> #include <cstdlib> #include <functional> #include <type_traits> #include <utility> #include <iostream> #include "utils.hpp" namespace RBT { enum class Color : std::uint8_t { RED, BLACK }; template <typename KeyType, typename ValueType> struct RBTNode { using ptr_RBTNode = RBTNode<KeyType, ValueType> *; KeyType key; ValueType value; ptr_RBTNode ch[2], fa; Color col{Color::RED}; template <typename K, typename V> requires KUtils::is_rmcvref_same_v<K, KeyType> && KUtils::is_rmcvref_same_v<V, ValueType> RBTNode(K &&key, V &&value) : fa{nullptr}, key{std::forward<K>(key)}, value{std::forward<V>(value)} { ch[0] = ch[1] = nullptr; } bool d() { return fa->ch[1] == this; } // void up() { // std::cout << "up" << std::endl; //} }; template <typename KeyType, typename ValueType, typename CompType = std::less<KeyType>> requires KUtils::Ops<KeyType, CompType> class RBTreeMap { public: using Node = RBTNode<KeyType, ValueType>; using ptr_Node = Node *; ptr_Node root{nullptr}; void rot(ptr_Node x, bool d) { ptr_Node y = x->ch[!d], z = x->fa; x->ch[!d] = y->ch[d]; if (y->ch[d] != NULL) y->ch[d]->fa = x; y->fa = z; if (z == NULL) root = y; else z->ch[x->d()] = y; y->ch[d] = x; x->fa = y; if constexpr (requires { x->up(); }) { x->up(); y->up(); } } template <typename K, typename V> requires KUtils::is_rmcvref_same_v<K, KeyType> && KUtils::is_rmcvref_same_v<V, ValueType> static ptr_Node getNode(K &&key, V &&value) { return new Node(std::forward<K>(key), std::forward<V>(value)); } static void destroyNode(ptr_Node p) { // std::cout << "destroy :{" << p->key << ", " << p->value << "}" << std::endl; delete p; } template <typename K, typename V> requires KUtils::is_rmcvref_same_v<K, KeyType> && KUtils::is_rmcvref_same_v<V, ValueType> void insert(K &&key, V &&value) { if (root == nullptr) { root = getNode(std::forward<K>(key), std::forward<V>(value)); root->col = Color::BLACK; return; } ptr_Node t = root, p = getNode(std::forward<K>(key), std::forward<V>(value)), z = nullptr; bool d; while (!eq(t->key, p->key) && t->ch[d = CompType{}(t->key, p->key)]) t = t->ch[d]; if (eq(t->key, p->key)) { t->value = std::move(p->value); return; } p->fa = t; t->ch[d] = p; if constexpr (requires { t->up(); }) { t->up(); } while ((t = p->fa) && (t->col == Color::RED)) { z = t->fa; bool d1 = t->d(), d2 = p->d(); ptr_Node u = z->ch[!d1]; if (u && u->col == Color::RED) { u->col = Color::BLACK; t->col = Color::BLACK; z->col = Color::RED; p = z; continue; } if (d1 ^ d2) { rot(t, d1); std::swap(p, t); } t->col = Color::BLACK; z->col = Color::RED; rot(z, !d1); } root->col = Color::BLACK; } static bool eq(const KeyType &l, const KeyType &r) { return (!CompType{}(l, r)) && (!CompType{}(r, l)); } ptr_Node search(const KeyType &key) { ptr_Node t = root; while (t && !eq(key, t->key)) t = t->ch[CompType{}(t->key, key)]; return t; } ValueType *get(const KeyType &key) { auto p = search(key); return p ? &p->value : nullptr; } void fixup(ptr_Node t, ptr_Node z) { ptr_Node b; while ((!t || t->col == Color::BLACK) && t != root) { int d = z->ch[1] == t; b = z->ch[!d]; if (b->col == Color::RED) { b->col = Color::BLACK; z->col = Color::RED; rot(z, d); b = z->ch[!d]; } if ((b->ch[0] == NULL || b->ch[0]->col == Color::BLACK) && (b->ch[1] == NULL || b->ch[1]->col == Color::BLACK)) { b->col = Color::RED; t = z; z = t->fa; } else { if (!b->ch[!d] || b->ch[!d]->col == Color::BLACK) { b->ch[d]->col = Color::BLACK; b->col = Color::RED; rot(b, !d); b = z->ch[!d]; } b->col = z->col; z->col = Color::BLACK; b->ch[!d]->col = Color::BLACK; rot(z, d); t = root; break; } } if (t) t->col = Color::BLACK; } void remove(const KeyType &key) { ptr_Node t = root, p, z, b, g; Color Tmp; if ((t = search(key)) == nullptr) { // std::cout << "rm :" << key << " Unsuccess" << std::endl; return; } if (t->ch[0] && t->ch[1]) { p = t->ch[1], z = t->fa; while (p->ch[0] != NULL) p = p->ch[0]; if (z != NULL) z->ch[t->d()] = p; else root = p; g = p->ch[1]; b = p->fa; Tmp = p->col; if (b == t) b = p; else { if (g) g->fa = b; b->ch[0] = g; p->ch[1] = t->ch[1]; t->ch[1]->fa = p; if constexpr (requires { b->up(); }) { b->up(); } } p->fa = z; p->col = t->col; p->ch[0] = t->ch[0]; t->ch[0]->fa = p; if (Tmp == Color::BLACK) fixup(g, b); destroyNode(t); return; } p = t->ch[t->ch[1] != nullptr]; z = t->fa; Tmp = t->col; if (p) p->fa = z; if (z) z->ch[t->d()] = p; else root = p; if (Tmp == Color::BLACK) fixup(p, z); destroyNode(t); } static void destroyTree(ptr_Node p) { if (p == nullptr) return; if (p->ch[0]) destroyTree(p->ch[0]); if (p->ch[1]) destroyTree(p->ch[1]); destroyNode(p); } // void dfs(ptr_Node x, int dep) { // if (x == nullptr) return; // dfs(x->ch[0], dep + 1); // // std::cout << "dep:" << dep << " {" << x->key << ", " << x->value << "} "; // dfs(x->ch[1], dep + 1); // } // void travel() { // dfs(root, 1); // std::cout << std::endl; // } ~RBTreeMap() { destroyTree(root); } }; } // namespace RBT
24.274336
116
0.52479
kraylas
6f1d24ded8c40501fe66e1e7ad5b85884940a93f
7,089
cpp
C++
src/std_sequence_containers.cpp
tyoungjr/Catch2Practice
6c602b0b57edaf2299043b4ef3c11d9507ce167b
[ "MIT" ]
null
null
null
src/std_sequence_containers.cpp
tyoungjr/Catch2Practice
6c602b0b57edaf2299043b4ef3c11d9507ce167b
[ "MIT" ]
null
null
null
src/std_sequence_containers.cpp
tyoungjr/Catch2Practice
6c602b0b57edaf2299043b4ef3c11d9507ce167b
[ "MIT" ]
null
null
null
// // Created by tyoun on 10/25/2021. // #include <catch2/catch.hpp> #include <array> #include <vector> #include <utility> #include <cstdint> #include <iostream> #include <unordered_set> #include "../include/print_std_library_containers.h" std::array<int, 10> static_array{}; // braced initialization will initialize array with zeroes TEST_CASE("std::array") { REQUIRE(static_array[0] == 0); SECTION("unitialized without braced initializers") { std::array<int, 10> local_array; REQUIRE(local_array[0] != 0); } SECTION("initialized with braced initializers") { std::array<int, 10> local_array { 1, 1,2, 3}; REQUIRE(local_array[0] == 1); REQUIRE(local_array[1] == 1); REQUIRE(local_array[2] == 2); REQUIRE(local_array[3] == 3); REQUIRE(local_array[4] == 0); } } // size_t object guarantees that its maximum value is sufficient to represent // the maximum size in bytes of all objects TEST_CASE("std::array access") { std::array<int, 4> fib { 1, 1, 0, 3}; SECTION("operator[] can get and set elemetns") { fib[2] = 2; REQUIRE(fib[2] == 2); // fib[4] = 5; } SECTION("at() can get and set elements") { fib.at(2) = 2; REQUIRE(fib.at(2) == 2); REQUIRE_THROWS_AS(fib.at(4), std::out_of_range); } SECTION("get can get and set elements") { std::get<2>(fib) = 2; REQUIRE(std::get<2>(fib) == 2); } SECTION(" sexy fibbers") { std::array fibonacci{1, 1, 2, 3, 5}; std::cout << fibonacci[4] << "\n"; } } TEST_CASE("std::array has convienence methods" ) { std::array<int, 4> fib { 0, 1, 2, 0}; SECTION("front") { fib.front() = 1; REQUIRE(fib.front() == 1); REQUIRE(fib.front() == fib[0]); } SECTION("back") { fib.front() = 1; REQUIRE(fib.front() == 1); REQUIRE(fib.front() == fib[0]); } } TEST_CASE("We can obtain a pointer to the first element using") { std::array<char, 9> color { 'o', 'c', 't', 'a', 'r','i','n','e'}; const auto* color_ptr = color.data(); SECTION("data") { REQUIRE(*color_ptr == 'o'); } SECTION("address-of front") { REQUIRE(&color.front() == color_ptr); } SECTION("address-of at(0)") { REQUIRE(&color.at(0) == color_ptr); } SECTION("address-of [0]") { REQUIRE(&color[0] == color_ptr); } } //ITERATORS TEST_CASE("std::array begin/end form a half open range") { std::array<int, 0> e{}; REQUIRE(e.begin() == e.end()); } TEST_CASE("std::array iterators are pointer-like") { std::array<int, 3> easy_as { 1, 2, 3}; auto iter = easy_as.begin(); REQUIRE(*iter == 1); ++iter; REQUIRE(*iter == 2); ++iter; REQUIRE(*iter == 3); REQUIRE(iter == easy_as.end()); } TEST_CASE("std::array iterator can be used as a range expression ") { std::array<int, 5> fib{1,1,2,3,5}; int sum{}; for (const auto element: fib) sum += element; REQUIRE(sum == 12); } /****************************************************/ /* the big std vector */ TEST_CASE("std vector supports default construction") { std::vector<const char *> vec; REQUIRE(vec.empty()); } TEST_CASE("std::vector supports braced initialization") { std::vector<int> fib { 1,1,2,3, 5}; REQUIRE(fib[4] == 5); } TEST_CASE("std::vector supports") { SECTION("braced initialization") { std::vector<int> five_nine{ 5, 9}; REQUIRE(five_nine[0] == 5); REQUIRE(five_nine[1] == 9); } SECTION("fill constructor" ) { std::vector<int> five_nines(5, 9); REQUIRE(five_nines[0] == 9); REQUIRE(five_nines[4] == 9); } } TEST_CASE("std::vector supports construction from iterators") { std::array<int, 5> fib_arr{1, 1, 2,3 , 5}; std::vector<int> fib_vec(fib_arr.begin(), fib_arr.end()); REQUIRE(fib_vec[4] == 5); REQUIRE(fib_vec.size() == fib_arr.size()); } TEST_CASE("std::vector assign replaces existing elements") { std::vector<int> message { 13, 80, 110 , 114, 102,110, 101 }; REQUIRE(message.size() == 7); message.assign({67, 97, 101, 115, 97, 114}); REQUIRE(message[5] == 114); REQUIRE(message.size() == 6); } TEST_CASE("std::vector insert places new elements") { std::vector<int> zeros(3, 0); auto third_element = zeros.begin() + 2; zeros.insert(third_element, 10); REQUIRE(zeros[2] == 10); REQUIRE(zeros.size() == 4); } TEST_CASE("std::vector push_back places new element") { std::vector<int> zeros(3, 0); zeros.push_back(10); REQUIRE(zeros[3] == 10); } TEST_CASE("std::vector emplace methods forwards arguments") { std::vector<std::pair<int, int>> factors; factors.emplace_back(2, 30); factors.emplace_back(3, 20); factors.emplace_back(4, 15); factors.emplace(factors.begin(), 1, 60); REQUIRE(factors[0].first == 1); REQUIRE(factors[0].second == 60); } TEST_CASE("std::vector exposes size management methods") { std::vector<std::array<uint8_t, 1024>> kb_store; REQUIRE(kb_store.max_size() > 0); REQUIRE(kb_store.empty()); size_t elements{ 1024}; kb_store.reserve(elements); REQUIRE(kb_store.empty()); REQUIRE(kb_store.empty() == elements); kb_store.emplace_back(); kb_store.emplace_back(); kb_store.emplace_back(); REQUIRE(kb_store.size() == 3); kb_store.shrink_to_fit(); REQUIRE(kb_store.capacity() >= 3); kb_store.clear(); REQUIRE(kb_store.empty()); REQUIRE(kb_store.capacity() >= 3); } TEST_CASE("OK I forgot the pop back ...") { std::vector<int> v; v.push_back(42); std::vector<int> u {1,2,3}; v.pop_back(); for(auto x: u) { std::cout << x << "\n"; } } // passing an array into a function using std::unordered_set; using std::array; using std::vector; unordered_set<int> unique(const array<int, 12>& numbers) { unordered_set<int> uniqueNumbers; for (auto n : numbers) { uniqueNumbers.insert(n); } return uniqueNumbers; } TEST_CASE("passing arrays into functions") { array numbers{1, 2, 42, 8, 0, -7, 2, 4, 10, 2, -100, 5}; auto uniqueNumbers = unique(numbers); std::cout << uniqueNumbers.size() << "\n"; } unordered_set<int> unique(const vector<int>& numbers) { unordered_set<int> uniqueNumbers; for (auto n : numbers) { uniqueNumbers.insert(n); } return uniqueNumbers; } TEST_CASE("passing vectors to functions") { vector numbers { 1, 2, 42, 8, 0,-7, 2, 5, 10, 2, 3, -100, 5}; auto uniqueNumbers = unique(numbers); std::cout << uniqueNumbers.size() << "\n"; } TEST_CASE("printing container template function") { vector vec{1.0f, 2.0f, 3.0f}; std::cout << vec << "\n"; } TEST_CASE("printing map template function") { std::map<std::string, float> planetDistances { { "Venus", 0.733f }, { "Earth", 1.0f}, { "Mars", 1.5}, }; std::cout << planetDistances << "\n"; }
24.277397
94
0.58217
tyoungjr
6f1dd9506205d4f86165f2477eb7d24aee7c6d15
4,176
cpp
C++
src/core/Window.cpp
AndrijaAda99/Bubo
662bb8e602f18a81ea6d8f367cb697c60b3e6670
[ "Apache-2.0" ]
null
null
null
src/core/Window.cpp
AndrijaAda99/Bubo
662bb8e602f18a81ea6d8f367cb697c60b3e6670
[ "Apache-2.0" ]
null
null
null
src/core/Window.cpp
AndrijaAda99/Bubo
662bb8e602f18a81ea6d8f367cb697c60b3e6670
[ "Apache-2.0" ]
null
null
null
#include "core/Window.h" #include "events/MouseEvent.h" #include "events/WindowEvent.h" #include "events/KeyEvent.h" namespace bubo { Window::Window(const WindowProperties_t &windowProperties) { init(windowProperties); BUBO_TRACE("Window initialized!"); } Window::~Window() { shutdown(); BUBO_TRACE("Window successfully closed."); } void Window::init(const WindowProperties_t &windowProperties) { int success = glfwInit(); BUBO_ASSERT(success, "Could not initialize GLFW!") glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_SAMPLES, 4); m_windowData.width = windowProperties.width; m_windowData.height = windowProperties.height; m_windowData.title = windowProperties.title; BUBO_INFO("Creating window: {0} ({1}, {2})", windowProperties.title, windowProperties.width, windowProperties.height); m_window = glfwCreateWindow((int) getWidth(), (int) getHeight(), m_windowData.title.c_str(), nullptr, nullptr); BUBO_ASSERT(m_window, "Could not create GLFW window!") m_mouse.xPos = getWidth() / 2.0f; m_mouse.yPos = getHeight() / 2.0f; glfwSetInputMode(m_window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glfwMakeContextCurrent(m_window); glfwSetWindowUserPointer(m_window, &m_windowData); success = gladLoadGLLoader((GLADloadproc) glfwGetProcAddress); BUBO_ASSERT(success, "Could not initialize GLAD!") glfwSetWindowSizeCallback(m_window, [](GLFWwindow* window, int width, int height){ WindowData_t& windowData = *(WindowData_t*) glfwGetWindowUserPointer(window); windowData.width = width; windowData.height = height; WindowResizeEvent event(width, height); windowData.callbackFunc(event); }); glfwSetWindowCloseCallback(m_window, [](GLFWwindow* window){ WindowData_t& windowData = *(WindowData_t*) glfwGetWindowUserPointer(window); WindowCloseEvent event; windowData.callbackFunc(event); }); glfwSetCursorPosCallback(m_window, [](GLFWwindow* window, double xPos, double yPos){ WindowData_t& windowData = *(WindowData_t*) glfwGetWindowUserPointer(window); MouseMovedEvent event((float) xPos, (float) yPos); windowData.callbackFunc(event); }); glfwSetMouseButtonCallback(m_window, [](GLFWwindow* window, int button, int action, int mods) { WindowData_t& windowData = *(WindowData_t*) glfwGetWindowUserPointer(window); if (action == GLFW_PRESS) { MouseButtonPressedEvent event((MouseKeycode(button))); windowData.callbackFunc(event); } else if (action == GLFW_RELEASE) { MouseButtonReleasedEvent event((MouseKeycode(button))); windowData.callbackFunc(event); } }); glfwSetKeyCallback(m_window, [](GLFWwindow* window, int key, int scancode, int action, int mods) { WindowData_t& windowData = *(WindowData_t*) glfwGetWindowUserPointer(window); if (action == GLFW_PRESS) { KeyPressedEvent event((Keycode(key))); windowData.callbackFunc(event); } else if (action == GLFW_RELEASE) { KeyReleasedEvent event((Keycode(key))); windowData.callbackFunc(event); } }); } void Window::shutdown() { glfwDestroyWindow(m_window); glfwTerminate(); } void Window::update() { glfwPollEvents(); glfwSwapBuffers(m_window); } void Window::setVSync(bool value) { if (value) { glfwSwapInterval(1); } else { glfwSwapInterval(0); } m_windowData.isVSync = value; } }
35.092437
106
0.610632
AndrijaAda99
6f20786568fe2281ac81029ef30223df8dc9b23e
1,665
hpp
C++
src/serialization/binary_or_text.hpp
blackberry/Wesnoth
8b307689158db568ecc6cc3b537e8d382ccea449
[ "Unlicense" ]
12
2015-03-04T15:07:00.000Z
2019-09-13T16:31:06.000Z
src/serialization/binary_or_text.hpp
blackberry/Wesnoth
8b307689158db568ecc6cc3b537e8d382ccea449
[ "Unlicense" ]
null
null
null
src/serialization/binary_or_text.hpp
blackberry/Wesnoth
8b307689158db568ecc6cc3b537e8d382ccea449
[ "Unlicense" ]
5
2017-04-22T08:16:48.000Z
2020-07-12T03:35:16.000Z
/* $Id: binary_or_text.hpp 48153 2011-01-01 15:57:50Z mordante $ */ /* Copyright (C) 2003 by David White <dave@whitevine.net> Copyright (C) 2005 - 2011 by Guillaume Melquiond <guillaume.melquiond@gmail.com> Part of the Battle for Wesnoth Project http://www.wesnoth.org/ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY. See the COPYING file for more details. */ /** @file */ #ifndef SERIALIZATION_BINARY_OR_TEXT_HPP_INCLUDED #define SERIALIZATION_BINARY_OR_TEXT_HPP_INCLUDED #include "preprocessor.hpp" #include <boost/iostreams/filtering_stream.hpp> class config; /** Class for writing a config out to a file in pieces. */ class config_writer { public: config_writer(std::ostream &out, bool compress, int level = -1); /** Default implementation, but defined out-of-line for efficiency reasons. */ ~config_writer(); void write(const config &cfg); void write_child(const std::string &key, const config &cfg); void write_key_val(const std::string &key, const std::string &value); void open_child(const std::string &key); void close_child(const std::string &key); bool good() const; private: boost::iostreams::filtering_stream<boost::iostreams::output> filter_; std::ostream *out_ptr_; std::ostream &out_; bool compress_; unsigned int level_; std::string textdomain_; }; #endif
30.833333
84
0.721321
blackberry
6f22c8dfd5a3231c0511fb03bebe73ec28be452f
170,693
cpp
C++
src/Pegasus/IndicationService/tests/Subscription/Subscription.cpp
ncultra/Pegasus-2.5
4a0b9a1b37e2eae5c8105fdea631582dc2333f9a
[ "MIT" ]
null
null
null
src/Pegasus/IndicationService/tests/Subscription/Subscription.cpp
ncultra/Pegasus-2.5
4a0b9a1b37e2eae5c8105fdea631582dc2333f9a
[ "MIT" ]
null
null
null
src/Pegasus/IndicationService/tests/Subscription/Subscription.cpp
ncultra/Pegasus-2.5
4a0b9a1b37e2eae5c8105fdea631582dc2333f9a
[ "MIT" ]
1
2022-03-07T22:54:02.000Z
2022-03-07T22:54:02.000Z
//%2005//////////////////////////////////////////////////////////////////////// // // Copyright (c) 2000, 2001, 2002 BMC Software; Hewlett-Packard Development // Company, L.P.; IBM Corp.; The Open Group; Tivoli Systems. // Copyright (c) 2003 BMC Software; Hewlett-Packard Development Company, L.P.; // IBM Corp.; EMC Corporation, The Open Group. // Copyright (c) 2004 BMC Software; Hewlett-Packard Development Company, L.P.; // IBM Corp.; EMC Corporation; VERITAS Software Corporation; The Open Group. // Copyright (c) 2005 Hewlett-Packard Development Company, L.P.; IBM Corp.; // EMC Corporation; VERITAS Software Corporation; The Open Group. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // THE ABOVE COPYRIGHT NOTICE AND THIS PERMISSION NOTICE SHALL BE INCLUDED IN // ALL COPIES OR SUBSTANTIAL PORTIONS OF THE SOFTWARE. THE SOFTWARE IS PROVIDED // "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT // LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // //============================================================================== // // Author: Carol Ann Krug Graves, Hewlett-Packard Company // (carolann_graves@hp.com) // //%///////////////////////////////////////////////////////////////////////////// #include <Pegasus/Common/Config.h> #include <Pegasus/Common/Constants.h> #include <Pegasus/Common/CIMType.h> #include <Pegasus/Common/CIMName.h> #include <Pegasus/Common/CIMInstance.h> #include <Pegasus/Common/CIMProperty.h> #include <Pegasus/Common/CIMValue.h> #include <Pegasus/Common/System.h> #include <Pegasus/Common/InternalException.h> #include <Pegasus/Client/CIMClient.h> PEGASUS_USING_PEGASUS; PEGASUS_USING_STD; const CIMNamespaceName NAMESPACE = CIMNamespaceName ("root/PG_InterOp"); const CIMNamespaceName NAMESPACE1 = CIMNamespaceName ("root/cimv2"); const CIMNamespaceName NAMESPACE2 = CIMNamespaceName ("test/TestProvider"); const CIMNamespaceName NAMESPACE3 = CIMNamespaceName ("root/SampleProvider"); const CIMNamespaceName SOURCENAMESPACE = CIMNamespaceName ("root/SampleProvider"); Boolean verbose; void _createModuleInstance (CIMClient & client, const String & name, const String & location) { CIMInstance moduleInstance (PEGASUS_CLASSNAME_PROVIDERMODULE); moduleInstance.addProperty (CIMProperty (CIMName ("Name"), name)); moduleInstance.addProperty (CIMProperty (CIMName ("Vendor"), String ("Hewlett-Packard Company"))); moduleInstance.addProperty (CIMProperty (CIMName ("Version"), String ("2.0"))); moduleInstance.addProperty (CIMProperty (CIMName ("InterfaceType"), String ("C++Default"))); moduleInstance.addProperty (CIMProperty (CIMName ("InterfaceVersion"), String ("2.2.0"))); moduleInstance.addProperty (CIMProperty (CIMName ("Location"), location)); CIMObjectPath path = client.createInstance (NAMESPACE, moduleInstance); } void _createProviderInstance (CIMClient & client, const String & name, const String & providerModuleName) { CIMInstance providerInstance (PEGASUS_CLASSNAME_PROVIDER); providerInstance.addProperty (CIMProperty (CIMName ("Name"), name)); providerInstance.addProperty (CIMProperty (CIMName ("ProviderModuleName"), providerModuleName)); CIMObjectPath path = client.createInstance (NAMESPACE, providerInstance); } void _createCapabilityInstance (CIMClient & client, const String & providerModuleName, const String & providerName, const String & capabilityID, const String & className, const Array <String> & namespaces, const Array <Uint16> & providerTypes, const CIMPropertyList & supportedProperties) { CIMInstance capabilityInstance (PEGASUS_CLASSNAME_PROVIDERCAPABILITIES); capabilityInstance.addProperty (CIMProperty (CIMName ("ProviderModuleName"), providerModuleName)); capabilityInstance.addProperty (CIMProperty (CIMName ("ProviderName"), providerName)); capabilityInstance.addProperty (CIMProperty (CIMName ("CapabilityID"), capabilityID)); capabilityInstance.addProperty (CIMProperty (CIMName ("ClassName"), className)); capabilityInstance.addProperty (CIMProperty (CIMName ("Namespaces"), namespaces)); capabilityInstance.addProperty (CIMProperty (CIMName ("ProviderType"), providerTypes)); if (!supportedProperties.isNull ()) { Array <String> propertyNameStrings; for (Uint32 i = 0; i < supportedProperties.size (); i++) { propertyNameStrings.append (supportedProperties [i].getString ()); } capabilityInstance.addProperty (CIMProperty (CIMName ("supportedProperties"), propertyNameStrings)); } CIMObjectPath path = client.createInstance (NAMESPACE, capabilityInstance); } void _modifyCapabilityInstance (CIMClient & client, const String & providerModuleName, const String & providerName, const String & capabilityID, const CIMPropertyList & supportedProperties) { CIMInstance capabilityInstance (PEGASUS_CLASSNAME_PROVIDERCAPABILITIES); if (!supportedProperties.isNull ()) { Array <String> propertyNameStrings; for (Uint32 i = 0; i < supportedProperties.size (); i++) { propertyNameStrings.append (supportedProperties [i].getString ()); } capabilityInstance.addProperty (CIMProperty (CIMName ("SupportedProperties"), propertyNameStrings)); } CIMObjectPath path; Array <CIMKeyBinding> keyBindings; keyBindings.append (CIMKeyBinding ("ProviderModuleName", providerModuleName, CIMKeyBinding::STRING)); keyBindings.append (CIMKeyBinding ("ProviderName", providerName, CIMKeyBinding::STRING)); keyBindings.append (CIMKeyBinding ("CapabilityID", capabilityID, CIMKeyBinding::STRING)); path.setClassName (PEGASUS_CLASSNAME_PROVIDERCAPABILITIES); path.setKeyBindings (keyBindings); capabilityInstance.setPath (path); Array <CIMName> propertyNames; propertyNames.append (CIMName ("SupportedProperties")); CIMPropertyList properties (propertyNames); client.modifyInstance (NAMESPACE, capabilityInstance, false, properties); } void _addStringProperty (CIMInstance & instance, const String & name, const String & value, Boolean null = false, Boolean isArray = false) { if (null) { instance.addProperty (CIMProperty (CIMName (name), CIMValue (CIMTYPE_STRING, false))); } else { if (isArray) { Array <String> values; values.append (value); instance.addProperty (CIMProperty (CIMName (name), values)); } else { instance.addProperty (CIMProperty (CIMName (name), value)); } } } void _addUint16Property (CIMInstance & instance, const String & name, Uint16 value, Boolean null = false, Boolean isArray = false) { if (null) { instance.addProperty (CIMProperty (CIMName (name), CIMValue (CIMTYPE_UINT16, false))); } else { if (isArray) { Array <Uint16> values; values.append (value); instance.addProperty (CIMProperty (CIMName (name), values)); } else { instance.addProperty (CIMProperty (CIMName (name), value)); } } } void _addUint32Property (CIMInstance & instance, const String & name, Uint32 value, Boolean null = false, Boolean isArray = false) { if (null) { instance.addProperty (CIMProperty (CIMName (name), CIMValue (CIMTYPE_UINT32, false))); } else { if (isArray) { Array <Uint32> values; values.append (value); instance.addProperty (CIMProperty (CIMName (name), values)); } else { instance.addProperty (CIMProperty (CIMName (name), value)); } } } void _addUint64Property (CIMInstance & instance, const String & name, Uint64 value, Boolean null = false, Boolean isArray = false) { if (null) { instance.addProperty (CIMProperty (CIMName (name), CIMValue (CIMTYPE_UINT64, false))); } else { if (isArray) { Array <Uint64> values; values.append (value); instance.addProperty (CIMProperty (CIMName (name), values)); } else { instance.addProperty (CIMProperty (CIMName (name), value)); } } } CIMObjectPath _buildFilterOrHandlerPath (const CIMName & className, const String & name, const String & host, const CIMNamespaceName & namespaceName = CIMNamespaceName ()) { CIMObjectPath path; Array <CIMKeyBinding> keyBindings; keyBindings.append (CIMKeyBinding ("SystemCreationClassName", System::getSystemCreationClassName (), CIMKeyBinding::STRING)); keyBindings.append (CIMKeyBinding ("SystemName", System::getFullyQualifiedHostName (), CIMKeyBinding::STRING)); keyBindings.append (CIMKeyBinding ("CreationClassName", className.getString(), CIMKeyBinding::STRING)); keyBindings.append (CIMKeyBinding ("Name", name, CIMKeyBinding::STRING)); path.setClassName (className); path.setKeyBindings (keyBindings); path.setNameSpace (namespaceName); path.setHost (host); return path; } CIMObjectPath _buildFilterOrHandlerPath (const CIMName & className, const String & name) { return _buildFilterOrHandlerPath (className, name, String::EMPTY, CIMNamespaceName ()); } CIMObjectPath _buildSubscriptionPath (const String & filterName, const CIMName & handlerClass, const String & handlerName, const String & filterHost, const String & handlerHost, const CIMNamespaceName & filterNS, const CIMNamespaceName & handlerNS) { CIMObjectPath filterPath = _buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDFILTER, filterName, filterHost, filterNS); CIMObjectPath handlerPath = _buildFilterOrHandlerPath (handlerClass, handlerName, handlerHost, handlerNS); Array<CIMKeyBinding> subscriptionKeyBindings; subscriptionKeyBindings.append (CIMKeyBinding ("Filter", filterPath.toString (), CIMKeyBinding::REFERENCE)); subscriptionKeyBindings.append (CIMKeyBinding ("Handler", handlerPath.toString (), CIMKeyBinding::REFERENCE)); CIMObjectPath subscriptionPath ("", CIMNamespaceName (), PEGASUS_CLASSNAME_INDSUBSCRIPTION, subscriptionKeyBindings); return subscriptionPath; } CIMObjectPath _buildSubscriptionPath (const String & filterName, const CIMName & handlerClass, const String & handlerName) { return _buildSubscriptionPath (filterName, handlerClass, handlerName, String::EMPTY, String::EMPTY, CIMNamespaceName (), CIMNamespaceName ()); } CIMInstance _buildSubscriptionInstance (const CIMObjectPath & filterPath, const CIMName & handlerClass, const CIMObjectPath & handlerPath) { CIMInstance subscriptionInstance (PEGASUS_CLASSNAME_INDSUBSCRIPTION); subscriptionInstance.addProperty (CIMProperty (CIMName ("Filter"), filterPath, 0, PEGASUS_CLASSNAME_INDFILTER)); subscriptionInstance.addProperty (CIMProperty (CIMName ("Handler"), handlerPath, 0, handlerClass)); return subscriptionInstance; } void _checkFilterOrHandlerPath (const CIMObjectPath & path, const CIMName & className, const String & name) { PEGASUS_ASSERT (path.getClassName () == className); Array <CIMKeyBinding> keyBindings = path.getKeyBindings (); Boolean SCCNfound = false; Boolean SNfound = false; Boolean CCNfound = false; Boolean Nfound = false; for (Uint32 i = 0; i < keyBindings.size (); i++) { if (keyBindings [i].getName ().equal ("SystemCreationClassName")) { SCCNfound = true; PEGASUS_ASSERT (keyBindings [i].getValue () == System::getSystemCreationClassName ()); } else if (keyBindings [i].getName ().equal ("SystemName")) { SNfound = true; PEGASUS_ASSERT (keyBindings [i].getValue () == System::getFullyQualifiedHostName ()); } else if (keyBindings [i].getName ().equal ("CreationClassName")) { CCNfound = true; PEGASUS_ASSERT (keyBindings [i].getValue () == className.getString ()); } else if (keyBindings [i].getName ().equal ("Name")) { Nfound = true; PEGASUS_ASSERT (keyBindings [i].getValue () == name); } else { PEGASUS_ASSERT (false); } } PEGASUS_ASSERT (SCCNfound); PEGASUS_ASSERT (SNfound); PEGASUS_ASSERT (CCNfound); PEGASUS_ASSERT (Nfound); } void _checkSubscriptionPath (const CIMObjectPath & path, const String & filterName, const CIMName & handlerClass, const String & handlerName, const String & filterHost, const String & handlerHost, const CIMNamespaceName & filterNS, const CIMNamespaceName & handlerNS) { PEGASUS_ASSERT (path.getClassName () == PEGASUS_CLASSNAME_INDSUBSCRIPTION); Array <CIMKeyBinding> keyBindings = path.getKeyBindings (); Boolean filterFound = false; Boolean handlerFound = false; for (Uint32 i = 0; i < keyBindings.size (); i++) { if (keyBindings [i].getName ().equal ("Filter")) { filterFound = true; CIMObjectPath filterPath = _buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDFILTER, filterName, filterHost, filterNS); PEGASUS_ASSERT (keyBindings [i].getValue () == filterPath.toString ()); } else if (keyBindings [i].getName ().equal ("Handler")) { handlerFound = true; CIMObjectPath handlerPath = _buildFilterOrHandlerPath (handlerClass, handlerName, handlerHost, handlerNS); PEGASUS_ASSERT (keyBindings [i].getValue () == handlerPath.toString ()); } else { PEGASUS_ASSERT (false); } } PEGASUS_ASSERT (filterFound); PEGASUS_ASSERT (handlerFound); } void _checkSubscriptionPath (const CIMObjectPath & path, const String & filterName, const CIMName & handlerClass, const String & handlerName) { _checkSubscriptionPath (path, filterName, handlerClass, handlerName, String::EMPTY, String::EMPTY, CIMNamespaceName (), CIMNamespaceName ()); } void _checkStringProperty (CIMInstance & instance, const String & name, const String & value, Boolean null = false) { Uint32 pos = instance.findProperty (name); PEGASUS_ASSERT (pos != PEG_NOT_FOUND); CIMProperty theProperty = instance.getProperty (pos); CIMValue theValue = theProperty.getValue (); PEGASUS_ASSERT (theValue.getType () == CIMTYPE_STRING); PEGASUS_ASSERT (!theValue.isArray ()); if (null) { PEGASUS_ASSERT (theValue.isNull ()); } else { PEGASUS_ASSERT (!theValue.isNull ()); String result; theValue.get (result); if (verbose) { if (result != value) { cerr << "Property value comparison failed. "; cerr << "Expected " << value << "; "; cerr << "Actual property value was " << result << "." << endl; } } PEGASUS_ASSERT (result == value); } } void _checkUint16Property (CIMInstance & instance, const String & name, Uint16 value) { Uint32 pos = instance.findProperty (name); PEGASUS_ASSERT (pos != PEG_NOT_FOUND); CIMProperty theProperty = instance.getProperty (pos); CIMValue theValue = theProperty.getValue (); PEGASUS_ASSERT (theValue.getType () == CIMTYPE_UINT16); PEGASUS_ASSERT (!theValue.isArray ()); PEGASUS_ASSERT (!theValue.isNull ()); Uint16 result; theValue.get (result); if (verbose) { if (result != value) { cerr << "Property value comparison failed. "; cerr << "Expected " << value << "; "; cerr << "Actual property value was " << result << "." << endl; } } PEGASUS_ASSERT (result == value); } void _checkUint32Property (CIMInstance & instance, const String & name, Uint32 value) { Uint32 pos = instance.findProperty (name); PEGASUS_ASSERT (pos != PEG_NOT_FOUND); CIMProperty theProperty = instance.getProperty (pos); CIMValue theValue = theProperty.getValue (); PEGASUS_ASSERT (theValue.getType () == CIMTYPE_UINT32); PEGASUS_ASSERT (!theValue.isArray ()); PEGASUS_ASSERT (!theValue.isNull ()); Uint32 result; theValue.get (result); if (verbose) { if (result != value) { cerr << "Property value comparison failed. "; cerr << "Expected " << value << "; "; cerr << "Actual property value was " << result << "." << endl; } } PEGASUS_ASSERT (result == value); } void _checkUint64Property (CIMInstance & instance, const String & name, Uint64 value) { Uint32 pos = instance.findProperty (name); PEGASUS_ASSERT (pos != PEG_NOT_FOUND); CIMProperty theProperty = instance.getProperty (pos); CIMValue theValue = theProperty.getValue (); PEGASUS_ASSERT (theValue.getType () == CIMTYPE_UINT64); PEGASUS_ASSERT (!theValue.isArray ()); PEGASUS_ASSERT (!theValue.isNull ()); Uint64 result; theValue.get (result); if (verbose) { if (result != value) { char buffer [32]; // Should need 21 chars max sprintf (buffer, "%" PEGASUS_64BIT_CONVERSION_WIDTH "u", value); cerr << "Property value comparison failed. "; cerr << "Expected " << buffer << "; "; sprintf (buffer, "%" PEGASUS_64BIT_CONVERSION_WIDTH "u", result); cerr << "Actual property value was " << buffer << "." << endl; } } PEGASUS_ASSERT (result == value); } void _checkExceptionCode (const CIMException & e, const CIMStatusCode expectedCode) { if (verbose) { if (e.getCode () != expectedCode) { cerr << "CIMException comparison failed. "; cerr << "Expected " << cimStatusCodeToString (expectedCode) << "; "; cerr << "Actual exception was " << e.getMessage () << "." << endl; } } PEGASUS_ASSERT (e.getCode () == expectedCode); } void _deleteSubscriptionInstance (CIMClient & client, const String & filterName, const CIMName & handlerClass, const String & handlerName, const String & filterHost, const String & handlerHost, const CIMNamespaceName & filterNS, const CIMNamespaceName & handlerNS, const CIMNamespaceName & subscriptionNS) { CIMObjectPath subscriptionPath = _buildSubscriptionPath (filterName, handlerClass, handlerName, filterHost, handlerHost, filterNS, handlerNS); client.deleteInstance (subscriptionNS, subscriptionPath); } void _deleteSubscriptionInstance (CIMClient & client, const String & filterName, const CIMName & handlerClass, const String & handlerName) { _deleteSubscriptionInstance (client, filterName, handlerClass, handlerName, String::EMPTY, String::EMPTY, CIMNamespaceName (), CIMNamespaceName (), NAMESPACE); } void _deleteHandlerInstance (CIMClient & client, const CIMName & className, const String & name, const CIMNamespaceName & nameSpace) { CIMObjectPath path = _buildFilterOrHandlerPath (className, name); client.deleteInstance (nameSpace, path); } void _deleteHandlerInstance (CIMClient & client, const CIMName & className, const String & name) { _deleteHandlerInstance (client, className, name, NAMESPACE); } void _deleteFilterInstance (CIMClient & client, const String & name, const CIMNamespaceName & nameSpace) { CIMObjectPath path = _buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDFILTER, name); client.deleteInstance (nameSpace, path); } void _deleteFilterInstance (CIMClient & client, const String & name) { _deleteFilterInstance (client, name, NAMESPACE); } void _deleteCapabilityInstance (CIMClient & client, const String & providerModuleName, const String & providerName, const String & capabilityID) { Array<CIMKeyBinding> keyBindings; keyBindings.append (CIMKeyBinding ("ProviderModuleName", providerModuleName, CIMKeyBinding::STRING)); keyBindings.append (CIMKeyBinding ("ProviderName", providerName, CIMKeyBinding::STRING)); keyBindings.append (CIMKeyBinding ("CapabilityID", capabilityID, CIMKeyBinding::STRING)); CIMObjectPath path ("", CIMNamespaceName (), CIMName ("PG_ProviderCapabilities"), keyBindings); client.deleteInstance (NAMESPACE, path); } void _deleteProviderInstance (CIMClient & client, const String & name, const String & providerModuleName) { Array<CIMKeyBinding> keyBindings; keyBindings.append (CIMKeyBinding ("Name", name, CIMKeyBinding::STRING)); keyBindings.append (CIMKeyBinding ("ProviderModuleName", providerModuleName, CIMKeyBinding::STRING)); CIMObjectPath path ("", CIMNamespaceName (), CIMName ("PG_Provider"), keyBindings); client.deleteInstance (NAMESPACE, path); } void _deleteModuleInstance (CIMClient & client, const String & name) { Array<CIMKeyBinding> keyBindings; keyBindings.append (CIMKeyBinding ("Name", name, CIMKeyBinding::STRING)); CIMObjectPath path ("", CIMNamespaceName (), CIMName ("PG_ProviderModule"), keyBindings); client.deleteInstance (NAMESPACE, path); } void _usage () { cerr << "Usage: TestSubscription " << "{register | test | unregister | cleanup }" << endl; } void _register (CIMClient & client) { try { Array <String> namespaces; Array <Uint16> providerTypes; namespaces.append (SOURCENAMESPACE.getString ()); providerTypes.append (4); // // Register the ProcessIndicationProvider // _createModuleInstance (client, String ("ProcessIndicationProviderModule"), String ("ProcessIndicationProvider")); _createProviderInstance (client, String ("ProcessIndicationProvider"), String ("ProcessIndicationProviderModule")); _createCapabilityInstance (client, String ("ProcessIndicationProviderModule"), String ("ProcessIndicationProvider"), String ("ProcessIndicationProviderCapability"), String ("CIM_ProcessIndication"), namespaces, providerTypes, CIMPropertyList ()); // // Register the AlertIndicationProvider // _createModuleInstance (client, String ("AlertIndicationProviderModule"), String ("AlertIndicationProvider")); _createProviderInstance (client, String ("AlertIndicationProvider"), String ("AlertIndicationProviderModule")); _createCapabilityInstance (client, String ("AlertIndicationProviderModule"), String ("AlertIndicationProvider"), String ("AlertIndicationProviderCapability"), String ("CIM_AlertIndication"), namespaces, providerTypes, CIMPropertyList ()); } catch (Exception & e) { cerr << "register failed: " << e.getMessage () << endl; exit (-1); } cout << "+++++ register completed successfully" << endl; } // // Valid test cases: create, get, enumerate, modify, delete operations // void _valid (CIMClient & client, String& qlang) { CIMObjectPath path; String query; CIMInstance retrievedInstance; Array <CIMInstance> instances; Array <CIMObjectPath> paths; // // Create filter that selects all properties from CIM_ProcessIndication // CIMInstance filter01 (PEGASUS_CLASSNAME_INDFILTER); query = "SELECT * FROM CIM_ProcessIndication"; _addStringProperty (filter01, "SystemCreationClassName", System::getSystemCreationClassName ()); _addStringProperty (filter01, "SystemName", System::getFullyQualifiedHostName ()); _addStringProperty (filter01, "CreationClassName", PEGASUS_CLASSNAME_INDFILTER.getString ()); _addStringProperty (filter01, "Name", "Filter01"); _addStringProperty (filter01, "SourceNamespace", SOURCENAMESPACE.getString ()); _addStringProperty (filter01, "Query", query); _addStringProperty (filter01, "QueryLanguage", qlang); path = client.createInstance (NAMESPACE, filter01); _checkFilterOrHandlerPath (path, PEGASUS_CLASSNAME_INDFILTER, "Filter01"); retrievedInstance = client.getInstance (NAMESPACE, path); _checkStringProperty (retrievedInstance, "SystemCreationClassName", System::getSystemCreationClassName ()); _checkStringProperty (retrievedInstance, "SystemName", System::getFullyQualifiedHostName ()); _checkStringProperty (retrievedInstance, "CreationClassName", PEGASUS_CLASSNAME_INDFILTER.getString ()); _checkStringProperty (retrievedInstance, "Name", "Filter01"); _checkStringProperty (retrievedInstance, "SourceNamespace", SOURCENAMESPACE.getString ()); _checkStringProperty (retrievedInstance, "Query", query); _checkStringProperty (retrievedInstance, "QueryLanguage", qlang); // // Enumerate filters // instances = client.enumerateInstances (NAMESPACE, PEGASUS_CLASSNAME_INDFILTER); PEGASUS_ASSERT (instances.size () == 1); _checkStringProperty (instances [0], "SystemCreationClassName", System::getSystemCreationClassName ()); _checkStringProperty (instances [0], "SystemName", System::getFullyQualifiedHostName ()); _checkStringProperty (instances [0], "CreationClassName", PEGASUS_CLASSNAME_INDFILTER.getString ()); _checkStringProperty (instances [0], "Name", "Filter01"); _checkStringProperty (instances [0], "SourceNamespace", SOURCENAMESPACE.getString ()); _checkStringProperty (instances [0], "Query", query); _checkStringProperty (instances [0], "QueryLanguage", qlang); paths = client.enumerateInstanceNames (NAMESPACE, PEGASUS_CLASSNAME_INDFILTER); PEGASUS_ASSERT (paths.size () == 1); _checkFilterOrHandlerPath (paths [0], PEGASUS_CLASSNAME_INDFILTER, "Filter01"); // // Create filter that selects some properties from // CIM_ProcessIndication // CIMInstance filter02 (PEGASUS_CLASSNAME_INDFILTER); query = "SELECT IndicationTime, IndicationIdentifier, " "CorrelatedIndications " "FROM CIM_ProcessIndication"; _addStringProperty (filter02, "Name", "Filter02"); _addStringProperty (filter02, "Query", query); _addStringProperty (filter02, "QueryLanguage", qlang); _addStringProperty (filter02, "SourceNamespace", SOURCENAMESPACE.getString ()); path = client.createInstance (NAMESPACE, filter02); _checkFilterOrHandlerPath (path, PEGASUS_CLASSNAME_INDFILTER, "Filter02"); retrievedInstance = client.getInstance (NAMESPACE, path); _checkStringProperty (retrievedInstance, "SystemCreationClassName", System::getSystemCreationClassName ()); _checkStringProperty (retrievedInstance, "SystemName", System::getFullyQualifiedHostName ()); _checkStringProperty (retrievedInstance, "CreationClassName", PEGASUS_CLASSNAME_INDFILTER.getString ()); _checkStringProperty (retrievedInstance, "Name", "Filter02"); _checkStringProperty (retrievedInstance, "SourceNamespace", SOURCENAMESPACE.getString ()); _checkStringProperty (retrievedInstance, "Query", query); _checkStringProperty (retrievedInstance, "QueryLanguage", qlang); // // Create filter that selects one property from CIM_ProcessIndication // CIMInstance filter03 (PEGASUS_CLASSNAME_INDFILTER); query = "SELECT IndicationTime FROM CIM_ProcessIndication"; _addStringProperty (filter03, "Name", "Filter03"); _addStringProperty (filter03, "Query", query); _addStringProperty (filter03, "QueryLanguage", qlang); _addStringProperty (filter03, "SourceNamespace", SOURCENAMESPACE.getString ()); path = client.createInstance (NAMESPACE, filter03); _checkFilterOrHandlerPath (path, PEGASUS_CLASSNAME_INDFILTER, "Filter03"); retrievedInstance = client.getInstance (NAMESPACE, path); _checkStringProperty (retrievedInstance, "SystemCreationClassName", System::getSystemCreationClassName ()); _checkStringProperty (retrievedInstance, "SystemName", System::getFullyQualifiedHostName ()); _checkStringProperty (retrievedInstance, "CreationClassName", PEGASUS_CLASSNAME_INDFILTER.getString ()); _checkStringProperty (retrievedInstance, "Name", "Filter03"); _checkStringProperty (retrievedInstance, "SourceNamespace", SOURCENAMESPACE.getString ()); _checkStringProperty (retrievedInstance, "Query", query); _checkStringProperty (retrievedInstance, "QueryLanguage", qlang); // // Create filter that selects properties from CIM_ProcessIndication // and has a where clause condition // CIMInstance filter04 (PEGASUS_CLASSNAME_INDFILTER); query = "SELECT IndicationTime, IndicationIdentifier " "FROM CIM_ProcessIndication " "WHERE IndicationTime IS NOT NULL"; _addStringProperty (filter04, "Name", "Filter04"); _addStringProperty (filter04, "Query", query); _addStringProperty (filter04, "QueryLanguage", qlang); _addStringProperty (filter04, "SourceNamespace", SOURCENAMESPACE.getString ()); path = client.createInstance (NAMESPACE, filter04); _checkFilterOrHandlerPath (path, PEGASUS_CLASSNAME_INDFILTER, "Filter04"); retrievedInstance = client.getInstance (NAMESPACE, path); _checkStringProperty (retrievedInstance, "SystemCreationClassName", System::getSystemCreationClassName ()); _checkStringProperty (retrievedInstance, "SystemName", System::getFullyQualifiedHostName ()); _checkStringProperty (retrievedInstance, "CreationClassName", PEGASUS_CLASSNAME_INDFILTER.getString ()); _checkStringProperty (retrievedInstance, "Name", "Filter04"); _checkStringProperty (retrievedInstance, "SourceNamespace", SOURCENAMESPACE.getString ()); _checkStringProperty (retrievedInstance, "Query", query); _checkStringProperty (retrievedInstance, "QueryLanguage", qlang); #ifndef PEGASUS_DISABLE_CQL // // Create filter that selects properties from CIM_ProcessIndication // and has a where clause condition that includes an array property. // Note: this is only allowed by CQL. // CIMInstance filter04a (PEGASUS_CLASSNAME_INDFILTER); query = "SELECT IndicationTime, IndicationIdentifier " "FROM CIM_ProcessIndication " "WHERE IndicationTime IS NOT NULL AND CorrelatedIndications IS NOT NULL"; _addStringProperty (filter04a, "Name", "Filter04a"); _addStringProperty (filter04a, "Query", query); _addStringProperty (filter04a, "QueryLanguage", "CIM:CQL"); // hardcode to CQL _addStringProperty (filter04a, "SourceNamespace", SOURCENAMESPACE.getString ()); path = client.createInstance (NAMESPACE, filter04a); _checkFilterOrHandlerPath (path, PEGASUS_CLASSNAME_INDFILTER, "Filter04a"); retrievedInstance = client.getInstance (NAMESPACE, path); _checkStringProperty (retrievedInstance, "SystemCreationClassName", System::getSystemCreationClassName ()); _checkStringProperty (retrievedInstance, "SystemName", System::getFullyQualifiedHostName ()); _checkStringProperty (retrievedInstance, "CreationClassName", PEGASUS_CLASSNAME_INDFILTER.getString ()); _checkStringProperty (retrievedInstance, "Name", "Filter04a"); _checkStringProperty (retrievedInstance, "SourceNamespace", SOURCENAMESPACE.getString ()); _checkStringProperty (retrievedInstance, "Query", query); _checkStringProperty (retrievedInstance, "QueryLanguage", "CIM:CQL"); // hardcode to CQL #endif // // Create filter that selects all properties from CIM_ProcessIndication // and has a where clause condition // CIMInstance filter05 (PEGASUS_CLASSNAME_INDFILTER); query = "SELECT * FROM CIM_ProcessIndication " "WHERE IndicationTime IS NOT NULL"; _addStringProperty (filter05, "Name", "Filter05"); _addStringProperty (filter05, "Query", query); _addStringProperty (filter05, "QueryLanguage", qlang); _addStringProperty (filter05, "SourceNamespace", SOURCENAMESPACE.getString ()); path = client.createInstance (NAMESPACE, filter05); _checkFilterOrHandlerPath (path, PEGASUS_CLASSNAME_INDFILTER, "Filter05"); retrievedInstance = client.getInstance (NAMESPACE, path); _checkStringProperty (retrievedInstance, "SystemCreationClassName", System::getSystemCreationClassName ()); _checkStringProperty (retrievedInstance, "SystemName", System::getFullyQualifiedHostName ()); _checkStringProperty (retrievedInstance, "CreationClassName", PEGASUS_CLASSNAME_INDFILTER.getString ()); _checkStringProperty (retrievedInstance, "Name", "Filter05"); _checkStringProperty (retrievedInstance, "SourceNamespace", SOURCENAMESPACE.getString ()); _checkStringProperty (retrievedInstance, "Query", query); _checkStringProperty (retrievedInstance, "QueryLanguage", qlang); // // Create filter that selects all properties from CIM_AlertIndication // and has a where clause condition // CIMInstance filter06 (PEGASUS_CLASSNAME_INDFILTER); query = "SELECT * FROM CIM_AlertIndication WHERE AlertType = 5"; _addStringProperty (filter06, "Name", "Filter06"); _addStringProperty (filter06, "Query", query); _addStringProperty (filter06, "QueryLanguage", qlang); _addStringProperty (filter06, "SourceNamespace", SOURCENAMESPACE.getString ()); path = client.createInstance (NAMESPACE, filter06); _checkFilterOrHandlerPath (path, PEGASUS_CLASSNAME_INDFILTER, "Filter06"); retrievedInstance = client.getInstance (NAMESPACE, path); _checkStringProperty (retrievedInstance, "SystemCreationClassName", System::getSystemCreationClassName ()); _checkStringProperty (retrievedInstance, "SystemName", System::getFullyQualifiedHostName ()); _checkStringProperty (retrievedInstance, "CreationClassName", PEGASUS_CLASSNAME_INDFILTER.getString ()); _checkStringProperty (retrievedInstance, "Name", "Filter06"); _checkStringProperty (retrievedInstance, "SourceNamespace", SOURCENAMESPACE.getString ()); _checkStringProperty (retrievedInstance, "Query", query); _checkStringProperty (retrievedInstance, "QueryLanguage", qlang); // // Create persistent CIMXML handler // CIMInstance handler01 (PEGASUS_CLASSNAME_INDHANDLER_CIMXML); _addStringProperty (handler01, "SystemCreationClassName", System::getSystemCreationClassName ()); _addStringProperty (handler01, "SystemName", System::getFullyQualifiedHostName ()); _addStringProperty (handler01, "CreationClassName", PEGASUS_CLASSNAME_INDHANDLER_CIMXML.getString ()); _addStringProperty (handler01, "Name", "Handler01"); _addStringProperty (handler01, "Owner", "an owner"); _addUint16Property (handler01, "PersistenceType", 2); _addStringProperty (handler01, "OtherPersistenceType", String::EMPTY, true); _addStringProperty (handler01, "Destination", "localhost/CIMListener/test1"); path = client.createInstance (NAMESPACE, handler01); _checkFilterOrHandlerPath (path, PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler01"); retrievedInstance = client.getInstance (NAMESPACE, path); _checkStringProperty (retrievedInstance, "SystemCreationClassName", System::getSystemCreationClassName ()); _checkStringProperty (retrievedInstance, "SystemName", System::getFullyQualifiedHostName ()); _checkStringProperty (retrievedInstance, "CreationClassName", PEGASUS_CLASSNAME_INDHANDLER_CIMXML.getString ()); _checkStringProperty (retrievedInstance, "Name", "Handler01"); _checkStringProperty (retrievedInstance, "Owner", "an owner"); _checkUint16Property (retrievedInstance, "PersistenceType", 2); _checkStringProperty (retrievedInstance, "OtherPersistenceType", String::EMPTY, true); _checkStringProperty (retrievedInstance, "Destination", "localhost/CIMListener/test1"); // // Enumerate handlers // instances = client.enumerateInstances (NAMESPACE, PEGASUS_CLASSNAME_INDHANDLER_CIMXML); PEGASUS_ASSERT (instances.size () == 1); _checkStringProperty (instances [0], "SystemCreationClassName", System::getSystemCreationClassName ()); _checkStringProperty (instances [0], "SystemName", System::getFullyQualifiedHostName ()); _checkStringProperty (instances [0], "CreationClassName", PEGASUS_CLASSNAME_INDHANDLER_CIMXML.getString ()); _checkStringProperty (instances [0], "Name", "Handler01"); _checkStringProperty (instances [0], "Owner", "an owner"); _checkUint16Property (instances [0], "PersistenceType", 2); _checkStringProperty (instances [0], "OtherPersistenceType", String::EMPTY, true); _checkStringProperty (instances [0], "Destination", "localhost/CIMListener/test1"); // // Create transient CIMXML handler // CIMInstance handler02 (PEGASUS_CLASSNAME_INDHANDLER_CIMXML); _addStringProperty (handler02, "Name", "Handler02"); _addUint16Property (handler02, "PersistenceType", 3); _addStringProperty (handler02, "Destination", "localhost/CIMListener/test2"); path = client.createInstance (NAMESPACE, handler02); _checkFilterOrHandlerPath (path, PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler02"); retrievedInstance = client.getInstance (NAMESPACE, path); _checkStringProperty (retrievedInstance, "SystemCreationClassName", System::getSystemCreationClassName ()); _checkStringProperty (retrievedInstance, "SystemName", System::getFullyQualifiedHostName ()); _checkStringProperty (retrievedInstance, "CreationClassName", PEGASUS_CLASSNAME_INDHANDLER_CIMXML.getString ()); _checkStringProperty (retrievedInstance, "Name", "Handler02"); _checkUint16Property (retrievedInstance, "PersistenceType", 3); _checkStringProperty (retrievedInstance, "Destination", "localhost/CIMListener/test2"); // // Create persistent SNMP handler // CIMInstance handler03 (PEGASUS_CLASSNAME_INDHANDLER_SNMP); _addStringProperty (handler03, "SystemCreationClassName", System::getSystemCreationClassName ()); _addStringProperty (handler03, "SystemName", System::getFullyQualifiedHostName ()); _addStringProperty (handler03, "CreationClassName", PEGASUS_CLASSNAME_INDHANDLER_SNMP.getString ()); _addStringProperty (handler03, "Name", "Handler03"); _addStringProperty (handler03, "Owner", "an owner"); _addUint16Property (handler03, "PersistenceType", 2); _addStringProperty (handler03, "OtherPersistenceType", String::EMPTY, true); _addStringProperty (handler03, "TargetHost", "localhost"); _addUint16Property (handler03, "TargetHostFormat", 2); _addUint32Property (handler03, "PortNumber", 162); _addUint16Property (handler03, "SNMPVersion", 3); _addStringProperty (handler03, "SNMPSecurityName", "a name"); _addStringProperty (handler03, "SNMPEngineID", "an ID"); path = client.createInstance (NAMESPACE, handler03); _checkFilterOrHandlerPath (path, PEGASUS_CLASSNAME_INDHANDLER_SNMP, "Handler03"); retrievedInstance = client.getInstance (NAMESPACE, path); _checkStringProperty (retrievedInstance, "SystemCreationClassName", System::getSystemCreationClassName ()); _checkStringProperty (retrievedInstance, "SystemName", System::getFullyQualifiedHostName ()); _checkStringProperty (retrievedInstance, "CreationClassName", PEGASUS_CLASSNAME_INDHANDLER_SNMP.getString ()); _checkStringProperty (retrievedInstance, "Name", "Handler03"); _checkStringProperty (retrievedInstance, "Owner", "an owner"); _checkUint16Property (retrievedInstance, "PersistenceType", 2); _checkStringProperty (retrievedInstance, "OtherPersistenceType", String::EMPTY, true); _checkStringProperty (retrievedInstance, "TargetHost", "localhost"); _checkUint16Property (retrievedInstance, "TargetHostFormat", 2); _checkUint32Property (retrievedInstance, "PortNumber", 162); _checkUint16Property (retrievedInstance, "SNMPVersion", 3); _checkStringProperty (retrievedInstance, "SNMPSecurityName", "a name"); _checkStringProperty (retrievedInstance, "SNMPEngineID", "an ID"); // // Enumerate handlers // instances = client.enumerateInstances (NAMESPACE, PEGASUS_CLASSNAME_INDHANDLER_SNMP); PEGASUS_ASSERT (instances.size () == 1); _checkStringProperty (instances [0], "SystemCreationClassName", System::getSystemCreationClassName ()); _checkStringProperty (instances [0], "SystemName", System::getFullyQualifiedHostName ()); _checkStringProperty (instances [0], "CreationClassName", PEGASUS_CLASSNAME_INDHANDLER_SNMP.getString ()); _checkStringProperty (instances [0], "Name", "Handler03"); _checkStringProperty (instances [0], "Owner", "an owner"); _checkUint16Property (instances [0], "PersistenceType", 2); _checkStringProperty (instances [0], "OtherPersistenceType", String::EMPTY, true); _checkStringProperty (instances [0], "TargetHost", "localhost"); _checkUint16Property (instances [0], "TargetHostFormat", 2); _checkUint32Property (instances [0], "PortNumber", 162); _checkUint16Property (instances [0], "SNMPVersion", 3); _checkStringProperty (instances [0], "SNMPSecurityName", "a name"); _checkStringProperty (instances [0], "SNMPEngineID", "an ID"); // // Create persistent CIMXML listener destination // CIMInstance listenerdestination01 (PEGASUS_CLASSNAME_LSTNRDST_CIMXML); _addStringProperty (listenerdestination01, "SystemCreationClassName", System::getSystemCreationClassName ()); _addStringProperty (listenerdestination01, "SystemName", System::getFullyQualifiedHostName ()); _addStringProperty (listenerdestination01, "CreationClassName", PEGASUS_CLASSNAME_LSTNRDST_CIMXML.getString ()); _addStringProperty (listenerdestination01, "Name", "ListenerDestination01"); _addUint16Property (listenerdestination01, "PersistenceType", 2); _addStringProperty (listenerdestination01, "OtherPersistenceType", String::EMPTY, true); _addStringProperty (listenerdestination01, "Destination", "localhost/CIMListener/test3"); path = client.createInstance (NAMESPACE, listenerdestination01); _checkFilterOrHandlerPath (path, PEGASUS_CLASSNAME_LSTNRDST_CIMXML, "ListenerDestination01"); retrievedInstance = client.getInstance (NAMESPACE, path); _checkStringProperty (retrievedInstance, "SystemCreationClassName", System::getSystemCreationClassName ()); _checkStringProperty (retrievedInstance, "SystemName", System::getFullyQualifiedHostName ()); _checkStringProperty (retrievedInstance, "CreationClassName", PEGASUS_CLASSNAME_LSTNRDST_CIMXML.getString ()); _checkStringProperty (retrievedInstance, "Name", "ListenerDestination01"); _checkUint16Property (retrievedInstance, "PersistenceType", 2); _checkStringProperty (retrievedInstance, "OtherPersistenceType", String::EMPTY, true); _checkStringProperty (retrievedInstance, "Destination", "localhost/CIMListener/test3"); // // Enumerate listener destinations // instances = client.enumerateInstances (NAMESPACE, PEGASUS_CLASSNAME_LSTNRDST_CIMXML); PEGASUS_ASSERT (instances.size () == 1); _checkStringProperty (instances [0], "SystemCreationClassName", System::getSystemCreationClassName ()); _checkStringProperty (instances [0], "SystemName", System::getFullyQualifiedHostName ()); _checkStringProperty (instances [0], "CreationClassName", PEGASUS_CLASSNAME_LSTNRDST_CIMXML.getString ()); _checkStringProperty (instances [0], "Name", "ListenerDestination01"); _checkUint16Property (instances [0], "PersistenceType", 2); _checkStringProperty (instances [0], "OtherPersistenceType", String::EMPTY, true); _checkStringProperty (instances [0], "Destination", "localhost/CIMListener/test3"); // // Create subscriptions // CIMInstance subscription01 = _buildSubscriptionInstance (_buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDFILTER, "Filter01"), PEGASUS_CLASSNAME_INDHANDLER_CIMXML, _buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler01")); _addUint16Property (subscription01, "OnFatalErrorPolicy", 2); _addStringProperty (subscription01, "OtherOnFatalErrorPolicy", String::EMPTY, true); _addUint64Property (subscription01, "FailureTriggerTimeInterval", 60); _addUint16Property (subscription01, "SubscriptionState", 2); _addStringProperty (subscription01, "OtherSubscriptionState", String::EMPTY, true); _addUint64Property (subscription01, "SubscriptionDuration", PEGASUS_UINT64_LITERAL(60000000000)); _addUint16Property (subscription01, "RepeatNotificationPolicy", 1); _addStringProperty (subscription01, "OtherRepeatNotificationPolicy", "another policy"); _addUint64Property (subscription01, "RepeatNotificationInterval", 60); _addUint64Property (subscription01, "RepeatNotificationGap", 30); _addUint16Property (subscription01, "RepeatNotificationCount", 5); path = client.createInstance (NAMESPACE, subscription01); _checkSubscriptionPath (path, "Filter01", PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler01"); retrievedInstance = client.getInstance (NAMESPACE, path); _checkUint16Property (retrievedInstance, "OnFatalErrorPolicy", 2); _checkStringProperty (retrievedInstance, "OtherOnFatalErrorPolicy", String::EMPTY, true); _checkUint64Property (retrievedInstance, "FailureTriggerTimeInterval", 60); _checkUint16Property (retrievedInstance, "SubscriptionState", 2); _checkStringProperty (retrievedInstance, "OtherSubscriptionState", String::EMPTY, true); _checkUint64Property (retrievedInstance, "SubscriptionDuration", PEGASUS_UINT64_LITERAL(60000000000)); _checkUint16Property (retrievedInstance, "RepeatNotificationPolicy", 1); _checkStringProperty (retrievedInstance, "OtherRepeatNotificationPolicy", "another policy"); _checkUint64Property (retrievedInstance, "RepeatNotificationInterval", 60); _checkUint64Property (retrievedInstance, "RepeatNotificationGap", 30); _checkUint16Property (retrievedInstance, "RepeatNotificationCount", 5); // // Enumerate subscriptions // instances = client.enumerateInstances (NAMESPACE, PEGASUS_CLASSNAME_INDSUBSCRIPTION); PEGASUS_ASSERT (instances.size () == 1); _checkUint16Property (instances [0], "OnFatalErrorPolicy", 2); _checkStringProperty (instances [0], "OtherOnFatalErrorPolicy", String::EMPTY, true); _checkUint64Property (instances [0], "FailureTriggerTimeInterval", 60); _checkUint16Property (instances [0], "SubscriptionState", 2); _checkStringProperty (instances [0], "OtherSubscriptionState", String::EMPTY, true); _checkUint64Property (instances [0], "SubscriptionDuration", PEGASUS_UINT64_LITERAL(60000000000)); _checkUint16Property (instances [0], "RepeatNotificationPolicy", 1); _checkStringProperty (instances [0], "OtherRepeatNotificationPolicy", "another policy"); _checkUint64Property (instances [0], "RepeatNotificationInterval", 60); _checkUint64Property (instances [0], "RepeatNotificationGap", 30); _checkUint16Property (instances [0], "RepeatNotificationCount", 5); paths = client.enumerateInstanceNames (NAMESPACE, PEGASUS_CLASSNAME_INDSUBSCRIPTION); PEGASUS_ASSERT (paths.size () == 1); _checkSubscriptionPath (path, "Filter01", PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler01"); CIMInstance subscription02 = _buildSubscriptionInstance (_buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDFILTER, "Filter02"), PEGASUS_CLASSNAME_INDHANDLER_CIMXML, _buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler01")); path = client.createInstance (NAMESPACE, subscription02); _checkSubscriptionPath (path, "Filter02", PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler01"); retrievedInstance = client.getInstance (NAMESPACE, path); _checkUint16Property (retrievedInstance, "OnFatalErrorPolicy", 2); _checkUint16Property (retrievedInstance, "SubscriptionState", 2); _checkUint16Property (retrievedInstance, "RepeatNotificationPolicy", 2); CIMInstance subscription03 = _buildSubscriptionInstance (_buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDFILTER, "Filter03"), PEGASUS_CLASSNAME_INDHANDLER_CIMXML, _buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler01")); path = client.createInstance (NAMESPACE, subscription03); _checkSubscriptionPath (path, "Filter03", PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler01"); retrievedInstance = client.getInstance (NAMESPACE, path); _checkUint16Property (retrievedInstance, "OnFatalErrorPolicy", 2); _checkUint16Property (retrievedInstance, "SubscriptionState", 2); _checkUint16Property (retrievedInstance, "RepeatNotificationPolicy", 2); CIMInstance subscription04 = _buildSubscriptionInstance (_buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDFILTER, "Filter04"), PEGASUS_CLASSNAME_INDHANDLER_CIMXML, _buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler01")); path = client.createInstance (NAMESPACE, subscription04); _checkSubscriptionPath (path, "Filter04", PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler01"); retrievedInstance = client.getInstance (NAMESPACE, path); _checkUint16Property (retrievedInstance, "OnFatalErrorPolicy", 2); _checkUint16Property (retrievedInstance, "SubscriptionState", 2); _checkUint16Property (retrievedInstance, "RepeatNotificationPolicy", 2); CIMInstance subscription05 = _buildSubscriptionInstance (_buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDFILTER, "Filter05"), PEGASUS_CLASSNAME_INDHANDLER_CIMXML, _buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler01")); path = client.createInstance (NAMESPACE, subscription05); _checkSubscriptionPath (path, "Filter05", PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler01"); retrievedInstance = client.getInstance (NAMESPACE, path); _checkUint16Property (retrievedInstance, "OnFatalErrorPolicy", 2); _checkUint16Property (retrievedInstance, "SubscriptionState", 2); _checkUint16Property (retrievedInstance, "RepeatNotificationPolicy", 2); CIMInstance subscription06 = _buildSubscriptionInstance (_buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDFILTER, "Filter06"), PEGASUS_CLASSNAME_INDHANDLER_CIMXML, _buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler01")); path = client.createInstance (NAMESPACE, subscription06); _checkSubscriptionPath (path, "Filter06", PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler01"); retrievedInstance = client.getInstance (NAMESPACE, path); _checkUint16Property (retrievedInstance, "OnFatalErrorPolicy", 2); _checkUint16Property (retrievedInstance, "SubscriptionState", 2); _checkUint16Property (retrievedInstance, "RepeatNotificationPolicy", 2); // // Create subscription with transient handler // CIMInstance subscription07 = _buildSubscriptionInstance (_buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDFILTER, "Filter01"), PEGASUS_CLASSNAME_INDHANDLER_CIMXML, _buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler02")); path = client.createInstance (NAMESPACE, subscription07); _checkSubscriptionPath (path, "Filter01", PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler02"); retrievedInstance = client.getInstance (NAMESPACE, path); _checkUint16Property (retrievedInstance, "OnFatalErrorPolicy", 2); _checkUint16Property (retrievedInstance, "SubscriptionState", 2); _checkUint16Property (retrievedInstance, "RepeatNotificationPolicy", 2); // // Delete transient handler - referencing subscription must be deleted // _deleteHandlerInstance (client, PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler02"); try { retrievedInstance = client.getInstance (NAMESPACE, path); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_NOT_FOUND); } // // Create subscription with SNMP handler // CIMInstance subscription08 = _buildSubscriptionInstance (_buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDFILTER, "Filter01"), PEGASUS_CLASSNAME_INDHANDLER_SNMP, _buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDHANDLER_SNMP, "Handler03")); path = client.createInstance (NAMESPACE, subscription08); _checkSubscriptionPath (path, "Filter01", PEGASUS_CLASSNAME_INDHANDLER_SNMP, "Handler03"); retrievedInstance = client.getInstance (NAMESPACE, path); _checkUint16Property (retrievedInstance, "OnFatalErrorPolicy", 2); _checkUint16Property (retrievedInstance, "SubscriptionState", 2); _checkUint16Property (retrievedInstance, "RepeatNotificationPolicy", 2); // // Create subscription with CIMXML Listener Destination // CIMInstance subscription09 = _buildSubscriptionInstance (_buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDFILTER, "Filter01"), PEGASUS_CLASSNAME_LSTNRDST_CIMXML, _buildFilterOrHandlerPath (PEGASUS_CLASSNAME_LSTNRDST_CIMXML, "ListenerDestination01")); path = client.createInstance (NAMESPACE, subscription09); _checkSubscriptionPath (path, "Filter01", PEGASUS_CLASSNAME_LSTNRDST_CIMXML, "ListenerDestination01"); retrievedInstance = client.getInstance (NAMESPACE, path); _checkUint16Property (retrievedInstance, "OnFatalErrorPolicy", 2); _checkUint16Property (retrievedInstance, "SubscriptionState", 2); _checkUint16Property (retrievedInstance, "RepeatNotificationPolicy", 2); // // Enumerate filters // instances = client.enumerateInstances (NAMESPACE, PEGASUS_CLASSNAME_INDFILTER); #ifndef PEGASUS_DISABLE_CQL PEGASUS_ASSERT (instances.size () == 7); #else PEGASUS_ASSERT (instances.size () == 6); #endif paths = client.enumerateInstanceNames (NAMESPACE, PEGASUS_CLASSNAME_INDFILTER); #ifndef PEGASUS_DISABLE_CQL PEGASUS_ASSERT (paths.size () == 7); #else PEGASUS_ASSERT (paths.size () == 6); #endif // // Enumerate handlers and listener destinations // Array <CIMInstance> handlers = client.enumerateInstances (NAMESPACE, PEGASUS_CLASSNAME_INDHANDLER); PEGASUS_ASSERT (handlers.size () == 2); Array <CIMInstance> listDests = client.enumerateInstances (NAMESPACE, PEGASUS_CLASSNAME_LSTNRDST); PEGASUS_ASSERT (listDests.size () == 3); Array <CIMObjectPath> cimxmlHandlerPaths = client.enumerateInstanceNames (NAMESPACE, PEGASUS_CLASSNAME_INDHANDLER_CIMXML); PEGASUS_ASSERT (cimxmlHandlerPaths.size () == 1); _checkFilterOrHandlerPath (cimxmlHandlerPaths [0], PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler01"); Array <CIMObjectPath> snmpHandlerPaths = client.enumerateInstanceNames (NAMESPACE, PEGASUS_CLASSNAME_INDHANDLER_SNMP); PEGASUS_ASSERT (snmpHandlerPaths.size () == 1); _checkFilterOrHandlerPath (snmpHandlerPaths [0], PEGASUS_CLASSNAME_INDHANDLER_SNMP, "Handler03"); Array <CIMObjectPath> handlerPaths = client.enumerateInstanceNames (NAMESPACE, PEGASUS_CLASSNAME_INDHANDLER); PEGASUS_ASSERT (handlerPaths.size () == 2); Array <CIMObjectPath> listDestPaths = client.enumerateInstanceNames (NAMESPACE, PEGASUS_CLASSNAME_LSTNRDST); PEGASUS_ASSERT (listDestPaths.size () == 3); Array <CIMObjectPath> cimxmlListDestPaths = client.enumerateInstanceNames (NAMESPACE, PEGASUS_CLASSNAME_LSTNRDST_CIMXML); PEGASUS_ASSERT (cimxmlListDestPaths.size () == 1); _checkFilterOrHandlerPath (cimxmlListDestPaths [0], PEGASUS_CLASSNAME_LSTNRDST_CIMXML, "ListenerDestination01"); // // Enumerate subscriptions // Array <CIMInstance> subscriptions = client.enumerateInstances (NAMESPACE, PEGASUS_CLASSNAME_INDSUBSCRIPTION); PEGASUS_ASSERT (subscriptions.size () == 8); Array <CIMObjectPath> subscriptionPaths = client.enumerateInstanceNames (NAMESPACE, PEGASUS_CLASSNAME_INDSUBSCRIPTION); PEGASUS_ASSERT (subscriptionPaths.size () == 8); // // Modify subscription: set state to disabled // CIMInstance modifiedInstance01 (PEGASUS_CLASSNAME_INDSUBSCRIPTION); _addUint16Property (modifiedInstance01, "SubscriptionState", 4); path = _buildSubscriptionPath ("Filter01", PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler01"); modifiedInstance01.setPath (path); Array <CIMName> propertyNames01; propertyNames01.append (CIMName ("SubscriptionState")); CIMPropertyList properties01 (propertyNames01); client.modifyInstance (NAMESPACE, modifiedInstance01, false, properties01); retrievedInstance = client.getInstance (NAMESPACE, path); _checkUint16Property (retrievedInstance, "SubscriptionState", 4); // // Modify subscription: specify 0 properties to be modified // CIMInstance modifiedInstance02 (PEGASUS_CLASSNAME_INDSUBSCRIPTION); _addUint16Property (modifiedInstance02, "SubscriptionState", 2); path = _buildSubscriptionPath ("Filter01", PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler01"); modifiedInstance02.setPath (path); Array <CIMName> propertyNames02; CIMPropertyList properties02 (propertyNames02); client.modifyInstance (NAMESPACE, modifiedInstance02, false, properties02); retrievedInstance = client.getInstance (NAMESPACE, path); _checkUint16Property (retrievedInstance, "SubscriptionState", 4); // // Provider registration changes: create, modify and delete operations // // // Create a new CIM_ProcessIndication provider that supports only the // IndicationTime property // Array <String> namespaces; Array <Uint16> providerTypes; Array <CIMName> propertyNames; namespaces.append (SOURCENAMESPACE.getString ()); providerTypes.append (4); propertyNames.append (CIMName ("IndicationTime")); CIMPropertyList properties (propertyNames); _createProviderInstance (client, String ("ProcessIndicationProvider2"), String ("ProcessIndicationProviderModule")); _createCapabilityInstance (client, String ("ProcessIndicationProviderModule"), String ("ProcessIndicationProvider2"), String ("ProcessIndicationProviderCapability2"), String ("CIM_ProcessIndication"), namespaces, providerTypes, properties); // // Modify the CIM_ProcessIndication provider to support both the // IndicationTime and IndicationIdentifier properties // propertyNames.clear (); propertyNames.append (CIMName ("IndicationTime")); propertyNames.append (CIMName ("IndicationIdentifier")); properties.clear (); properties.set (propertyNames); _modifyCapabilityInstance (client, String ("ProcessIndicationProviderModule"), String ("ProcessIndicationProvider2"), String ("ProcessIndicationProviderCapability2"), properties); // // Modify the CIM_ProcessIndication provider to again support only the // IndicationTime property // propertyNames.clear (); propertyNames.append (CIMName ("IndicationTime")); propertyNames.append (CIMName ("IndicationIdentifier")); properties.clear (); properties.set (propertyNames); _modifyCapabilityInstance (client, String ("ProcessIndicationProviderModule"), String ("ProcessIndicationProvider2"), String ("ProcessIndicationProviderCapability2"), properties); // // Delete the provider // _deleteCapabilityInstance (client, "ProcessIndicationProviderModule", "ProcessIndicationProvider2", "ProcessIndicationProviderCapability2"); _deleteProviderInstance (client, "ProcessIndicationProvider2", "ProcessIndicationProviderModule"); // // Create Subscription with correct Host and Namespace in Filter and // Handler reference property value // Verify Host and Namespace appear in Subscription instance name // returned from Create Instance operation // CIMObjectPath fPath; CIMObjectPath hPath; CIMObjectPath sPath; CIMInstance filter08 (PEGASUS_CLASSNAME_INDFILTER); query = "SELECT * FROM CIM_ProcessIndication"; _addStringProperty (filter08, "Name", "Filter08"); _addStringProperty (filter08, "SourceNamespace", SOURCENAMESPACE.getString ()); _addStringProperty (filter08, "Query", query); _addStringProperty (filter08, "QueryLanguage", qlang); fPath = client.createInstance (NAMESPACE, filter08); fPath.setHost (System::getFullyQualifiedHostName ()); fPath.setNameSpace (NAMESPACE); CIMInstance listenerdestination02 (PEGASUS_CLASSNAME_LSTNRDST_CIMXML); _addStringProperty (listenerdestination02, "Name", "ListenerDestination02"); _addStringProperty (listenerdestination02, "Destination", "localhost/CIMListener/test4"); hPath = client.createInstance (NAMESPACE, listenerdestination02); hPath.setHost (System::getFullyQualifiedHostName ()); hPath.setNameSpace (NAMESPACE); CIMInstance subscription10 = _buildSubscriptionInstance (fPath, PEGASUS_CLASSNAME_LSTNRDST_CIMXML, hPath); sPath = client.createInstance (NAMESPACE, subscription10); _checkSubscriptionPath (sPath, "Filter08", PEGASUS_CLASSNAME_LSTNRDST_CIMXML, "ListenerDestination02", System::getFullyQualifiedHostName (), System::getFullyQualifiedHostName (), NAMESPACE, NAMESPACE); _deleteSubscriptionInstance (client, "Filter08", PEGASUS_CLASSNAME_LSTNRDST_CIMXML, "ListenerDestination02", System::getFullyQualifiedHostName (), System::getFullyQualifiedHostName (), NAMESPACE, NAMESPACE, NAMESPACE); _deleteFilterInstance (client, "Filter08"); _deleteHandlerInstance (client, PEGASUS_CLASSNAME_LSTNRDST_CIMXML, "ListenerDestination02"); // // Create Subscription with correct Namespace in Filter and Handler // reference property value // Verify Namespace appears in Subscription instance name // returned from Create Instance operation // CIMInstance filter09 (PEGASUS_CLASSNAME_INDFILTER); query = "SELECT * FROM CIM_ProcessIndication"; _addStringProperty (filter09, "Name", "Filter09"); _addStringProperty (filter09, "SourceNamespace", SOURCENAMESPACE.getString ()); _addStringProperty (filter09, "Query", query); _addStringProperty (filter09, "QueryLanguage", qlang); fPath = client.createInstance (NAMESPACE, filter09); fPath.setNameSpace (NAMESPACE); CIMInstance listenerdestination03 (PEGASUS_CLASSNAME_LSTNRDST_CIMXML); _addStringProperty (listenerdestination03, "Name", "ListenerDestination03"); _addStringProperty (listenerdestination03, "Destination", "localhost/CIMListener/test5"); hPath = client.createInstance (NAMESPACE, listenerdestination03); hPath.setNameSpace (NAMESPACE); CIMInstance subscription11 = _buildSubscriptionInstance (fPath, PEGASUS_CLASSNAME_LSTNRDST_CIMXML, hPath); sPath = client.createInstance (NAMESPACE, subscription11); _checkSubscriptionPath (sPath, "Filter09", PEGASUS_CLASSNAME_LSTNRDST_CIMXML, "ListenerDestination03", String::EMPTY, String::EMPTY, NAMESPACE, NAMESPACE); _deleteSubscriptionInstance (client, "Filter09", PEGASUS_CLASSNAME_LSTNRDST_CIMXML, "ListenerDestination03", String::EMPTY, String::EMPTY, NAMESPACE, NAMESPACE, NAMESPACE); _deleteFilterInstance (client, "Filter09"); _deleteHandlerInstance (client, PEGASUS_CLASSNAME_LSTNRDST_CIMXML, "ListenerDestination03"); // // Create Subscription with Filter and Handler in different namespaces // CIMInstance filter11 (PEGASUS_CLASSNAME_INDFILTER); query = "SELECT * FROM CIM_ProcessIndication"; _addStringProperty (filter11, "Name", "Filter11"); _addStringProperty (filter11, "SourceNamespace", SOURCENAMESPACE.getString ()); _addStringProperty (filter11, "Query", query); _addStringProperty (filter11, "QueryLanguage", qlang); fPath = client.createInstance (NAMESPACE1, filter11); fPath.setNameSpace (NAMESPACE1); CIMInstance listenerdestination05 (PEGASUS_CLASSNAME_LSTNRDST_CIMXML); _addStringProperty (listenerdestination05, "Name", "ListenerDestination05"); _addStringProperty (listenerdestination05, "Destination", "localhost/CIMListener/test6"); hPath = client.createInstance (NAMESPACE2, listenerdestination05); hPath.setNameSpace (NAMESPACE2); CIMInstance subscription13 = _buildSubscriptionInstance (fPath, PEGASUS_CLASSNAME_LSTNRDST_CIMXML, hPath); sPath = client.createInstance (NAMESPACE3, subscription13); _checkSubscriptionPath (sPath, "Filter11", PEGASUS_CLASSNAME_LSTNRDST_CIMXML, "ListenerDestination05", String::EMPTY, String::EMPTY, NAMESPACE1, NAMESPACE2); // // Create a second filter in different namespace // CIMInstance filter11a (PEGASUS_CLASSNAME_INDFILTER); query = "SELECT * FROM CIM_ProcessIndication"; _addStringProperty (filter11a, "Name", "Filter11"); _addStringProperty (filter11a, "SourceNamespace", SOURCENAMESPACE.getString ()); _addStringProperty (filter11a, "Query", query); _addStringProperty (filter11a, "QueryLanguage", qlang); CIMObjectPath fPath2 = client.createInstance (NAMESPACE2, filter11a); fPath2.setNameSpace (NAMESPACE2); // // Create a second handler in different namespace // CIMInstance listenerdestination05a (PEGASUS_CLASSNAME_LSTNRDST_CIMXML); _addStringProperty (listenerdestination05a, "Name", "ListenerDestination05"); _addStringProperty (listenerdestination05a, "Destination", "localhost/CIMListener/test6"); CIMObjectPath hPath2 = client.createInstance (NAMESPACE1, listenerdestination05a); hPath2.setNameSpace (NAMESPACE1); // // Create transient CIMXML listener destination // CIMInstance listenerdestination06 (PEGASUS_CLASSNAME_LSTNRDST_CIMXML); _addStringProperty (listenerdestination06, "Name", "ListenerDestination06"); _addUint16Property (listenerdestination06, "PersistenceType", 3); _addStringProperty (listenerdestination06, "Destination", "localhost/CIMListener/test7"); hPath = client.createInstance (NAMESPACE2, listenerdestination06); hPath.setNameSpace (NAMESPACE2); // // Create subscription with transient handler // CIMInstance subscription14 = _buildSubscriptionInstance (fPath, PEGASUS_CLASSNAME_LSTNRDST_CIMXML, hPath); sPath = client.createInstance (NAMESPACE3, subscription14); _checkSubscriptionPath (sPath, "Filter11", PEGASUS_CLASSNAME_LSTNRDST_CIMXML, "ListenerDestination06", String::EMPTY, String::EMPTY, NAMESPACE1, NAMESPACE2); // // Create subscription in which Filter and Handler reference property // values differ only in Namespace // CIMInstance subscription16 = _buildSubscriptionInstance (fPath2, PEGASUS_CLASSNAME_LSTNRDST_CIMXML, hPath2); CIMObjectPath s16Path = client.createInstance (NAMESPACE3, subscription16); _checkSubscriptionPath (s16Path, "Filter11", PEGASUS_CLASSNAME_LSTNRDST_CIMXML, "ListenerDestination05", String::EMPTY, String::EMPTY, NAMESPACE2, NAMESPACE1); _deleteSubscriptionInstance (client, "Filter11", PEGASUS_CLASSNAME_LSTNRDST_CIMXML, "ListenerDestination05", String::EMPTY, String::EMPTY, NAMESPACE2, NAMESPACE1, NAMESPACE3); // // Create another transient CIMXML listener destination in a different // namespace // CIMInstance listenerdestination06a (PEGASUS_CLASSNAME_LSTNRDST_CIMXML); _addStringProperty (listenerdestination06a, "Name", "ListenerDestination06"); _addUint16Property (listenerdestination06a, "PersistenceType", 3); _addStringProperty (listenerdestination06a, "Destination", "localhost/CIMListener/test7"); hPath = client.createInstance (NAMESPACE3, listenerdestination06a); hPath.setNameSpace (NAMESPACE3); // // Create subscription with transient handler // CIMInstance subscription14a = _buildSubscriptionInstance (fPath, PEGASUS_CLASSNAME_LSTNRDST_CIMXML, hPath); CIMObjectPath sPath2 = client.createInstance (NAMESPACE2, subscription14a); _checkSubscriptionPath (sPath2, "Filter11", PEGASUS_CLASSNAME_LSTNRDST_CIMXML, "ListenerDestination06", String::EMPTY, String::EMPTY, NAMESPACE1, NAMESPACE3); // // Delete transient handler - referencing subscription must be deleted // // // Include Host and Namespace in object path of instance to be deleted // to ensure this case is handled correctly. // Host and Namespace are removed before request reaches IndicationService. // CIMObjectPath aPath = _buildFilterOrHandlerPath (PEGASUS_CLASSNAME_LSTNRDST_CIMXML, "ListenerDestination06"); aPath.setNameSpace (NAMESPACE2); aPath.setHost (System::getFullyQualifiedHostName ()); client.deleteInstance (NAMESPACE2, aPath); try { retrievedInstance = client.getInstance (NAMESPACE3, sPath); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_NOT_FOUND); } // // Subscription not referencing the deleted transient handler must not be // deleted // retrievedInstance = client.getInstance (NAMESPACE2, sPath2); // // Filter not referenced by a Subscription may be deleted // _deleteFilterInstance (client, "Filter11", NAMESPACE2); // // Handler not referenced by a Subscription may be deleted // _deleteHandlerInstance (client, PEGASUS_CLASSNAME_LSTNRDST_CIMXML, "ListenerDestination05", NAMESPACE1); _deleteSubscriptionInstance (client, "Filter11", PEGASUS_CLASSNAME_LSTNRDST_CIMXML, "ListenerDestination06", String::EMPTY, String::EMPTY, NAMESPACE1, NAMESPACE3, NAMESPACE2); _deleteHandlerInstance (client, PEGASUS_CLASSNAME_LSTNRDST_CIMXML, "ListenerDestination06", NAMESPACE3); _deleteSubscriptionInstance (client, "Filter11", PEGASUS_CLASSNAME_LSTNRDST_CIMXML, "ListenerDestination05", String::EMPTY, String::EMPTY, NAMESPACE1, NAMESPACE2, NAMESPACE3); _deleteFilterInstance (client, "Filter11", NAMESPACE1); _deleteHandlerInstance (client, PEGASUS_CLASSNAME_LSTNRDST_CIMXML, "ListenerDestination05", NAMESPACE2); } // // Default value test cases: create and modify requests // void _default (CIMClient & client) { // Note: since these testcases are used to test defaulted // properties on the filters, handlers, and subscriptions, // there is no need for CQL-specific tests. // // Filter: Missing SystemCreationClassName must get default value // Missing SystemName must get default value // Missing CreationClassName must get default value // Missing SourceNamespace must get default value // { CIMInstance filter (PEGASUS_CLASSNAME_INDFILTER); String query = "SELECT * FROM CIM_ProcessIndication"; _addStringProperty (filter, "Name", "Filter00"); _addStringProperty (filter, "Query", query); _addStringProperty (filter, "QueryLanguage", "WQL"); CIMObjectPath path = client.createInstance (NAMESPACE, filter); CIMInstance retrievedInstance = client.getInstance (NAMESPACE, path); _checkStringProperty (retrievedInstance, "SystemCreationClassName", System::getSystemCreationClassName ()); _checkStringProperty (retrievedInstance, "SystemName", System::getFullyQualifiedHostName ()); _checkStringProperty (retrievedInstance, "CreationClassName", PEGASUS_CLASSNAME_INDFILTER.getString ()); _checkStringProperty (retrievedInstance, "SourceNamespace", NAMESPACE.getString ()); _deleteFilterInstance (client, "Filter00"); } // // Filter: Null SystemCreationClassName must get default value // Null SystemName must get default value // Null CreationClassName must get default value // Null SourceNamespace must get default value // { CIMInstance filter (PEGASUS_CLASSNAME_INDFILTER); String query = "SELECT * FROM CIM_ProcessIndication"; _addStringProperty (filter, "Name", "Filter00"); _addStringProperty (filter, "Query", query); _addStringProperty (filter, "QueryLanguage", "WQL"); _addStringProperty (filter, "SourceNamespace", String::EMPTY, true); CIMObjectPath path = client.createInstance (NAMESPACE, filter); CIMInstance retrievedInstance = client.getInstance (NAMESPACE, path); _checkStringProperty (retrievedInstance, "SystemCreationClassName", System::getSystemCreationClassName ()); _checkStringProperty (retrievedInstance, "SystemName", System::getFullyQualifiedHostName ()); _checkStringProperty (retrievedInstance, "CreationClassName", PEGASUS_CLASSNAME_INDFILTER.getString ()); _checkStringProperty (retrievedInstance, "SourceNamespace", NAMESPACE.getString ()); _deleteFilterInstance (client, "Filter00"); } // // Handler: Missing SystemCreationClassName must get default value // Missing SystemName must get default value // Missing CreationClassName must get default value // Missing PersistenceType must get default value // { CIMInstance handler (PEGASUS_CLASSNAME_INDHANDLER_CIMXML); _addStringProperty (handler, "Name", "Handler00"); _addStringProperty (handler, "Destination", "localhost/CIMListener/test1", false); CIMObjectPath path = client.createInstance (NAMESPACE, handler); CIMInstance retrievedInstance = client.getInstance (NAMESPACE, path); _checkStringProperty (retrievedInstance, "SystemCreationClassName", System::getSystemCreationClassName ()); _checkStringProperty (retrievedInstance, "SystemName", System::getFullyQualifiedHostName ()); _checkStringProperty (retrievedInstance, "CreationClassName", PEGASUS_CLASSNAME_INDHANDLER_CIMXML.getString ()); _checkUint16Property (retrievedInstance, "PersistenceType", 2); _deleteHandlerInstance (client, PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler00"); } // // Handler: Null SystemCreationClassName must get default value // Null SystemName must get default value // Null CreationClassName must get default value // Null PersistenceType must get default value // { CIMInstance handler (PEGASUS_CLASSNAME_INDHANDLER_CIMXML); _addStringProperty (handler, "Name", "Handler00"); _addStringProperty (handler, "Destination", "localhost/CIMListener/test1", false); _addUint16Property (handler, "PersistenceType", 0, true); CIMObjectPath path = client.createInstance (NAMESPACE, handler); CIMInstance retrievedInstance = client.getInstance (NAMESPACE, path); _checkStringProperty (retrievedInstance, "SystemCreationClassName", System::getSystemCreationClassName ()); _checkStringProperty (retrievedInstance, "SystemName", System::getFullyQualifiedHostName ()); _checkStringProperty (retrievedInstance, "CreationClassName", PEGASUS_CLASSNAME_INDHANDLER_CIMXML.getString ()); _checkUint16Property (retrievedInstance, "PersistenceType", 2); _deleteHandlerInstance (client, PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler00"); } // // Create filter and handler for testing subscriptions // CIMInstance filter00 (PEGASUS_CLASSNAME_INDFILTER); String query = "SELECT * FROM CIM_ProcessIndication"; _addStringProperty (filter00, "Name", "Filter00"); _addStringProperty (filter00, "Query", query); _addStringProperty (filter00, "QueryLanguage", "WQL"); _addStringProperty (filter00, "SourceNamespace", SOURCENAMESPACE.getString ()); CIMObjectPath fPath = client.createInstance (NAMESPACE, filter00); CIMInstance handler00 (PEGASUS_CLASSNAME_INDHANDLER_CIMXML); _addStringProperty (handler00, "Name", "Handler00"); _addStringProperty (handler00, "Destination", "localhost/CIMListener/test0", false); CIMObjectPath hPath = client.createInstance (NAMESPACE, handler00); // // Subscription: missing SubscriptionState must get default value // missing OnFatalErrorPolicy must get default value // missing RepeatNotificationPolicy must get default value // { CIMInstance subscription = _buildSubscriptionInstance (fPath, PEGASUS_CLASSNAME_INDHANDLER_CIMXML, hPath); CIMObjectPath path = client.createInstance (NAMESPACE, subscription); CIMInstance retrievedInstance = client.getInstance (NAMESPACE, path); _checkUint16Property (retrievedInstance, "SubscriptionState", 2); _checkUint16Property (retrievedInstance, "OnFatalErrorPolicy", 2); _checkUint16Property (retrievedInstance, "RepeatNotificationPolicy", 2); _deleteSubscriptionInstance (client, "Filter00", PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler00"); } // // Subscription: null SubscriptionState must get default value // null OnFatalErrorPolicy must get default value // null RepeatNotificationPolicy must get default value // { CIMInstance subscription = _buildSubscriptionInstance (_buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDFILTER, "Filter00"), PEGASUS_CLASSNAME_INDHANDLER_CIMXML, _buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler00")); _addUint16Property (subscription, "SubscriptionState", 0, true); _addUint16Property (subscription, "OnFatalErrorPolicy", 0, true); _addUint16Property (subscription, "RepeatNotificationPolicy", 0, true); CIMObjectPath path = client.createInstance (NAMESPACE, subscription); CIMInstance retrievedInstance = client.getInstance (NAMESPACE, path); _checkUint16Property (retrievedInstance, "SubscriptionState", 2); _checkUint16Property (retrievedInstance, "OnFatalErrorPolicy", 2); _checkUint16Property (retrievedInstance, "RepeatNotificationPolicy", 2); _deleteSubscriptionInstance (client, "Filter00", PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler00"); } // // Modify subscription: null SubscriptionState must get default value // { CIMInstance modifiedInstance (PEGASUS_CLASSNAME_INDSUBSCRIPTION); _addUint16Property (modifiedInstance, "SubscriptionState", 0, true); CIMObjectPath path = _buildSubscriptionPath ("Filter01", PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler01"); modifiedInstance.setPath (path); Array <CIMName> propertyNames; propertyNames.append (CIMName ("SubscriptionState")); CIMPropertyList properties (propertyNames); client.modifyInstance (NAMESPACE, modifiedInstance, false, properties); CIMInstance retrievedInstance = client.getInstance (NAMESPACE, path); _checkUint16Property (retrievedInstance, "SubscriptionState", 2); } // // Delete filter and handler instances // _deleteFilterInstance (client, "Filter00"); _deleteHandlerInstance (client, PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler00"); } // // Error test cases: invalid queries // void _errorQueries (CIMClient & client, String& qlang) { // // Filter: Invalid query - invalid indication class name in FROM clause of // CIM_IndicationFilter Query property // try { CIMInstance filter (PEGASUS_CLASSNAME_INDFILTER); String query = "SELECT * FROM CIM_ManagedElement"; _addStringProperty (filter, "Name", "Filter00"); _addStringProperty (filter, "Query", query); _addStringProperty (filter, "QueryLanguage", qlang); _addStringProperty (filter, "SourceNamespace", SOURCENAMESPACE.getString ()); CIMObjectPath path = client.createInstance (NAMESPACE, filter); PEGASUS_ASSERT (false); } catch (CIMException & e) { #ifdef PEGASUS_DISABLE_CQL if (qlang == "CIM:CQL") { // If CQL is disabled, then a non-supported error // for invalid language is expected. _checkExceptionCode(e, CIM_ERR_NOT_SUPPORTED); return; } else { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } #else _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); #endif } // // Filter: Invalid query - parse error (join) // try { CIMInstance filter (PEGASUS_CLASSNAME_INDFILTER); String query = "SELECT * FROM CIM_ProcessIndication, CIM_AlertIndication"; _addStringProperty (filter, "Name", "Filter00"); _addStringProperty (filter, "Query", query); _addStringProperty (filter, "QueryLanguage", qlang); _addStringProperty (filter, "SourceNamespace", SOURCENAMESPACE.getString ()); CIMObjectPath path = client.createInstance (NAMESPACE, filter); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // Filter: Invalid query - Array property is not supported in the WQL // WHERE clause. // Note: CQL allows array properties in the WHERE clause. // try { CIMInstance filter (PEGASUS_CLASSNAME_INDFILTER); String query = "SELECT * FROM CIM_ProcessIndication " "WHERE CorrelatedIndications IS NOT NULL"; _addStringProperty (filter, "Name", "Filter00"); _addStringProperty (filter, "Query", query); _addStringProperty (filter, "QueryLanguage", "WQL"); // hardcode to WQL _addStringProperty (filter, "SourceNamespace", SOURCENAMESPACE.getString ()); CIMObjectPath path = client.createInstance (NAMESPACE, filter); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_NOT_SUPPORTED); } // // Filter: Invalid query - Property referenced in the WHERE clause not // found in the indication class in the FROM clause // try { CIMInstance filter (PEGASUS_CLASSNAME_INDFILTER); String query = "SELECT * FROM CIM_ProcessIndication " "WHERE AlertType = 3"; _addStringProperty (filter, "Name", "Filter00"); _addStringProperty (filter, "Query", query); _addStringProperty (filter, "QueryLanguage", qlang); _addStringProperty (filter, "SourceNamespace", SOURCENAMESPACE.getString ()); CIMObjectPath path = client.createInstance (NAMESPACE, filter); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // Filter: Invalid query - Property referenced in the SELECT clause // not found in the indication class in the FROM clause // try { CIMInstance filter (PEGASUS_CLASSNAME_INDFILTER); String query = "SELECT PerceivedSeverity FROM CIM_ProcessIndication"; _addStringProperty (filter, "Name", "Filter00"); _addStringProperty (filter, "Query", query); _addStringProperty (filter, "QueryLanguage", qlang); _addStringProperty (filter, "SourceNamespace", SOURCENAMESPACE.getString ()); CIMObjectPath path = client.createInstance (NAMESPACE, filter); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } } // // Error test cases: create, modify and delete requests // void _error (CIMClient & client) { // // Filter: Invalid SystemCreationClassName key property // try { CIMInstance filter (PEGASUS_CLASSNAME_INDFILTER); String query = "SELECT * FROM CIM_ProcessIndication"; _addStringProperty (filter, "SystemCreationClassName", "invalidName", false); _addStringProperty (filter, "Name", "Filter00"); _addStringProperty (filter, "Query", query); _addStringProperty (filter, "QueryLanguage", "WQL"); _addStringProperty (filter, "SourceNamespace", SOURCENAMESPACE.getString ()); CIMObjectPath path = client.createInstance (NAMESPACE, filter); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // Filter: SystemCreationClassName key property of incorrect type // try { CIMInstance filter (PEGASUS_CLASSNAME_INDFILTER); String query = "SELECT * FROM CIM_ProcessIndication"; _addUint16Property (filter, "SystemCreationClassName", 1); _addStringProperty (filter, "Name", "Filter00"); _addStringProperty (filter, "Query", query); _addStringProperty (filter, "QueryLanguage", "WQL"); _addStringProperty (filter, "SourceNamespace", SOURCENAMESPACE.getString ()); CIMObjectPath path = client.createInstance (NAMESPACE, filter); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // Filter: SystemCreationClassName key property of array type // try { CIMInstance filter (PEGASUS_CLASSNAME_INDFILTER); String query = "SELECT * FROM CIM_ProcessIndication"; _addStringProperty (filter, "SystemCreationClassName", System::getSystemCreationClassName (), false, true); _addStringProperty (filter, "Name", "Filter00"); _addStringProperty (filter, "Query", query); _addStringProperty (filter, "QueryLanguage", "WQL"); _addStringProperty (filter, "SourceNamespace", SOURCENAMESPACE.getString ()); CIMObjectPath path = client.createInstance (NAMESPACE, filter); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // Filter: Invalid SystemName key property // try { CIMInstance filter (PEGASUS_CLASSNAME_INDFILTER); String query = "SELECT * FROM CIM_ProcessIndication"; _addStringProperty (filter, "SystemName", "invalidName"); _addStringProperty (filter, "Name", "Filter00"); _addStringProperty (filter, "Query", query); _addStringProperty (filter, "QueryLanguage", "WQL"); _addStringProperty (filter, "SourceNamespace", SOURCENAMESPACE.getString ()); CIMObjectPath path = client.createInstance (NAMESPACE, filter); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // Filter: SystemName key property of incorrect type // try { CIMInstance filter (PEGASUS_CLASSNAME_INDFILTER); String query = "SELECT * FROM CIM_ProcessIndication"; _addUint16Property (filter, "SystemName", 1); _addStringProperty (filter, "Name", "Filter00"); _addStringProperty (filter, "Query", query); _addStringProperty (filter, "QueryLanguage", "WQL"); _addStringProperty (filter, "SourceNamespace", SOURCENAMESPACE.getString ()); CIMObjectPath path = client.createInstance (NAMESPACE, filter); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // Filter: Invalid CreationClassName key property // try { CIMInstance filter (PEGASUS_CLASSNAME_INDFILTER); String query = "SELECT * FROM CIM_ProcessIndication"; _addStringProperty (filter, "CreationClassName", "invalidName"); _addStringProperty (filter, "Name", "Filter00"); _addStringProperty (filter, "Query", query); _addStringProperty (filter, "QueryLanguage", "WQL"); _addStringProperty (filter, "SourceNamespace", SOURCENAMESPACE.getString ()); CIMObjectPath path = client.createInstance (NAMESPACE, filter); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // Filter: CreationClassName key property of incorrect type // try { CIMInstance filter (PEGASUS_CLASSNAME_INDFILTER); String query = "SELECT * FROM CIM_ProcessIndication"; _addUint16Property (filter, "CreationClassName", 1); _addStringProperty (filter, "Name", "Filter00"); _addStringProperty (filter, "Query", query); _addStringProperty (filter, "QueryLanguage", "WQL"); _addStringProperty (filter, "SourceNamespace", SOURCENAMESPACE.getString ()); CIMObjectPath path = client.createInstance (NAMESPACE, filter); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // Filter: Missing required Name key property // try { CIMInstance filter (PEGASUS_CLASSNAME_INDFILTER); String query = "SELECT * FROM CIM_ProcessIndication"; _addStringProperty (filter, "Query", query); _addStringProperty (filter, "QueryLanguage", "WQL"); _addStringProperty (filter, "SourceNamespace", SOURCENAMESPACE.getString ()); CIMObjectPath path = client.createInstance (NAMESPACE, filter); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // Filter: Null required Name key property // try { CIMInstance filter (PEGASUS_CLASSNAME_INDFILTER); String query = "SELECT * FROM CIM_ProcessIndication"; _addStringProperty (filter, "Name", String::EMPTY, true); _addStringProperty (filter, "Query", query); _addStringProperty (filter, "QueryLanguage", "WQL"); _addStringProperty (filter, "SourceNamespace", SOURCENAMESPACE.getString ()); CIMObjectPath path = client.createInstance (NAMESPACE, filter); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // Filter: Required Name key property of incorrect type // try { CIMInstance filter (PEGASUS_CLASSNAME_INDFILTER); String query = "SELECT * FROM CIM_ProcessIndication"; _addUint16Property (filter, "Name", 1); _addStringProperty (filter, "Query", query); _addStringProperty (filter, "QueryLanguage", "WQL"); _addStringProperty (filter, "SourceNamespace", SOURCENAMESPACE.getString ()); CIMObjectPath path = client.createInstance (NAMESPACE, filter); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // Filter: Required Name key property of array type // try { CIMInstance filter (PEGASUS_CLASSNAME_INDFILTER); String query = "SELECT * FROM CIM_ProcessIndication"; _addStringProperty (filter, "Name", "Filter00", false, true); _addStringProperty (filter, "Query", query); _addStringProperty (filter, "QueryLanguage", "WQL"); _addStringProperty (filter, "SourceNamespace", SOURCENAMESPACE.getString ()); CIMObjectPath path = client.createInstance (NAMESPACE, filter); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // Filter: SourceNamespace property of incorrect type // try { CIMInstance filter (PEGASUS_CLASSNAME_INDFILTER); String query = "SELECT * FROM CIM_ProcessIndication"; _addStringProperty (filter, "Name", "Filter00"); _addStringProperty (filter, "Query", query); _addStringProperty (filter, "QueryLanguage", "WQL"); _addUint16Property (filter, "SourceNamespace", 1); CIMObjectPath path = client.createInstance (NAMESPACE, filter); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // Filter: Missing required Query property // try { CIMInstance filter (PEGASUS_CLASSNAME_INDFILTER); _addStringProperty (filter, "Name", "Filter00"); _addStringProperty (filter, "QueryLanguage", "WQL"); _addStringProperty (filter, "SourceNamespace", SOURCENAMESPACE.getString ()); CIMObjectPath path = client.createInstance (NAMESPACE, filter); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // Filter: Null required Query property // try { CIMInstance filter (PEGASUS_CLASSNAME_INDFILTER); _addStringProperty (filter, "Name", "Filter00"); _addStringProperty (filter, "Query", String::EMPTY, true); _addStringProperty (filter, "QueryLanguage", "WQL"); _addStringProperty (filter, "SourceNamespace", SOURCENAMESPACE.getString ()); CIMObjectPath path = client.createInstance (NAMESPACE, filter); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // Filter: Required Query property of incorrect type // try { CIMInstance filter (PEGASUS_CLASSNAME_INDFILTER); _addStringProperty (filter, "Name", "Filter00"); _addUint16Property (filter, "Query", 1); _addStringProperty (filter, "QueryLanguage", "WQL"); _addStringProperty (filter, "SourceNamespace", SOURCENAMESPACE.getString ()); CIMObjectPath path = client.createInstance (NAMESPACE, filter); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // Filter: Missing required QueryLanguage property // try { CIMInstance filter (PEGASUS_CLASSNAME_INDFILTER); String query = "SELECT * FROM CIM_ProcessIndication"; _addStringProperty (filter, "Name", "Filter00"); _addStringProperty (filter, "Query", query); _addStringProperty (filter, "SourceNamespace", SOURCENAMESPACE.getString ()); CIMObjectPath path = client.createInstance (NAMESPACE, filter); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // Filter: Null required QueryLanguage property // try { CIMInstance filter (PEGASUS_CLASSNAME_INDFILTER); String query = "SELECT * FROM CIM_ProcessIndication"; _addStringProperty (filter, "Name", "Filter00"); _addStringProperty (filter, "Query", query); _addStringProperty (filter, "QueryLanguage", String::EMPTY, true); _addStringProperty (filter, "SourceNamespace", SOURCENAMESPACE.getString ()); CIMObjectPath path = client.createInstance (NAMESPACE, filter); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // Filter: Required QueryLanguage property unsupported value // try { CIMInstance filter (PEGASUS_CLASSNAME_INDFILTER); String query = "SELECT * FROM CIM_ProcessIndication"; _addStringProperty (filter, "Name", "Filter00"); _addStringProperty (filter, "Query", query); _addStringProperty (filter, "QueryLanguage", "unknownQueryLanguage"); _addStringProperty (filter, "SourceNamespace", SOURCENAMESPACE.getString ()); CIMObjectPath path = client.createInstance (NAMESPACE, filter); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_NOT_SUPPORTED); } // // Filter: Required QueryLanguage property of incorrect type // try { CIMInstance filter (PEGASUS_CLASSNAME_INDFILTER); String query = "SELECT * FROM CIM_ProcessIndication"; _addStringProperty (filter, "Name", "Filter00"); _addStringProperty (filter, "Query", query); _addUint16Property (filter, "QueryLanguage", 1); _addStringProperty (filter, "SourceNamespace", SOURCENAMESPACE.getString ()); CIMObjectPath path = client.createInstance (NAMESPACE, filter); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // Filter: Unsupported property // try { CIMInstance filter (PEGASUS_CLASSNAME_INDFILTER); String query = "SELECT * FROM CIM_ProcessIndication"; _addStringProperty (filter, "Name", "Filter00"); _addStringProperty (filter, "Query", query); _addStringProperty (filter, "QueryLanguage", "WQL"); _addStringProperty (filter, "SourceNamespace", SOURCENAMESPACE.getString ()); _addUint16Property (filter, "Unsupported", 1); CIMObjectPath path = client.createInstance (NAMESPACE, filter); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_NOT_SUPPORTED); } // // Filter: Attempt to delete a filter referenced by a subscription // A Filter referenced by a subscription may not be deleted // try { _deleteFilterInstance (client, "Filter01"); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_FAILED); } // // Handler: Invalid SystemCreationClassName key property // try { CIMInstance handler (PEGASUS_CLASSNAME_INDHANDLER_CIMXML); _addStringProperty (handler, "SystemCreationClassName", "invalidName", false); _addStringProperty (handler, "Name", "Handler00"); _addStringProperty (handler, "Destination", "localhost/CIMListener/test1"); CIMObjectPath path = client.createInstance (NAMESPACE, handler); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // Handler: SystemCreationClassName key property of incorrect type // try { CIMInstance handler (PEGASUS_CLASSNAME_INDHANDLER_CIMXML); _addUint16Property (handler, "SystemCreationClassName", 1); _addStringProperty (handler, "Name", "Handler00"); _addStringProperty (handler, "Destination", "localhost/CIMListener/test1"); CIMObjectPath path = client.createInstance (NAMESPACE, handler); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // Handler: Invalid SystemName key property // try { CIMInstance handler (PEGASUS_CLASSNAME_INDHANDLER_CIMXML); _addStringProperty (handler, "SystemName", "invalidName"); _addStringProperty (handler, "Name", "Handler00"); _addStringProperty (handler, "Destination", "localhost/CIMListener/test1"); CIMObjectPath path = client.createInstance (NAMESPACE, handler); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // Handler: SystemName key property of incorrect type // try { CIMInstance handler (PEGASUS_CLASSNAME_INDHANDLER_CIMXML); _addUint16Property (handler, "SystemName", 1); _addStringProperty (handler, "Name", "Handler00"); _addStringProperty (handler, "Destination", "localhost/CIMListener/test1"); CIMObjectPath path = client.createInstance (NAMESPACE, handler); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // Handler: Invalid CreationClassName key property // try { CIMInstance handler (PEGASUS_CLASSNAME_INDHANDLER_CIMXML); _addStringProperty (handler, "CreationClassName", "invalidName"); _addStringProperty (handler, "Name", "Handler00"); _addStringProperty (handler, "Destination", "localhost/CIMListener/test1"); CIMObjectPath path = client.createInstance (NAMESPACE, handler); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // Handler: CreationClassName key property of incorrect type // try { CIMInstance handler (PEGASUS_CLASSNAME_INDHANDLER_CIMXML); _addUint16Property (handler, "CreationClassName", 1); _addStringProperty (handler, "Name", "Handler00"); _addStringProperty (handler, "Destination", "localhost/CIMListener/test1"); CIMObjectPath path = client.createInstance (NAMESPACE, handler); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // Handler: Missing required Name key property // try { CIMInstance handler (PEGASUS_CLASSNAME_INDHANDLER_CIMXML); _addStringProperty (handler, "Destination", "localhost/CIMListener/test1"); CIMObjectPath path = client.createInstance (NAMESPACE, handler); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // Handler: Null required Name key property // try { CIMInstance handler (PEGASUS_CLASSNAME_INDHANDLER_CIMXML); _addStringProperty (handler, "Name", String::EMPTY, true); _addStringProperty (handler, "Destination", "localhost/CIMListener/test1"); CIMObjectPath path = client.createInstance (NAMESPACE, handler); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // Handler: Required Name key property of incorrect type // try { CIMInstance handler (PEGASUS_CLASSNAME_INDHANDLER_CIMXML); _addUint16Property (handler, "Name", 1); _addStringProperty (handler, "Destination", "localhost/CIMListener/test1"); CIMObjectPath path = client.createInstance (NAMESPACE, handler); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // Handler: Unsupported value 1 (Other) for property PersistenceType // try { CIMInstance handler (PEGASUS_CLASSNAME_INDHANDLER_CIMXML); _addStringProperty (handler, "Name", "Handler00"); _addStringProperty (handler, "Destination", "localhost/CIMListener/test1"); _addUint16Property (handler, "PersistenceType", 1); CIMObjectPath path = client.createInstance (NAMESPACE, handler); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_NOT_SUPPORTED); } // // Handler: OtherPersistenceType property present, but PersistenceType // value not 1 (Other) // try { CIMInstance handler (PEGASUS_CLASSNAME_INDHANDLER_CIMXML); _addStringProperty (handler, "Name", "Handler00"); _addStringProperty (handler, "Destination", "localhost/CIMListener/test1"); _addUint16Property (handler, "PersistenceType", 2); _addStringProperty (handler, "OtherPersistenceType", "another type", false); CIMObjectPath path = client.createInstance (NAMESPACE, handler); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // Handler: Invalid value 0 for property PersistenceType // try { CIMInstance handler (PEGASUS_CLASSNAME_INDHANDLER_CIMXML); _addStringProperty (handler, "Name", "Handler00"); _addStringProperty (handler, "Destination", "localhost/CIMListener/test1"); _addUint16Property (handler, "PersistenceType", 0); CIMObjectPath path = client.createInstance (NAMESPACE, handler); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // Handler: Invalid value 4 for property PersistenceType // try { CIMInstance handler (PEGASUS_CLASSNAME_INDHANDLER_CIMXML); _addStringProperty (handler, "Name", "Handler00"); _addStringProperty (handler, "Destination", "localhost/CIMListener/test1"); _addUint16Property (handler, "PersistenceType", 4); CIMObjectPath path = client.createInstance (NAMESPACE, handler); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // Handler: PersistenceType property of incorrect type // try { CIMInstance handler (PEGASUS_CLASSNAME_INDHANDLER_CIMXML); _addStringProperty (handler, "Name", "Handler00"); _addStringProperty (handler, "Destination", "localhost/CIMListener/test1"); _addStringProperty (handler, "PersistenceType", "invalid"); CIMObjectPath path = client.createInstance (NAMESPACE, handler); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // Handler: PersistenceType property of array type // try { CIMInstance handler (PEGASUS_CLASSNAME_INDHANDLER_CIMXML); _addStringProperty (handler, "Name", "Handler00"); _addStringProperty (handler, "Destination", "localhost/CIMListener/test1"); _addUint16Property (handler, "PersistenceType", 2, false, true); CIMObjectPath path = client.createInstance (NAMESPACE, handler); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // Handler: Owner property of incorrect type // try { CIMInstance handler (PEGASUS_CLASSNAME_INDHANDLER_CIMXML); _addStringProperty (handler, "Name", "Handler00"); _addStringProperty (handler, "Destination", "localhost/CIMListener/test1"); _addUint16Property (handler, "Owner", 1); CIMObjectPath path = client.createInstance (NAMESPACE, handler); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // Handler: Owner property of array type // try { CIMInstance handler (PEGASUS_CLASSNAME_INDHANDLER_CIMXML); _addStringProperty (handler, "Name", "Handler00"); _addStringProperty (handler, "Destination", "localhost/CIMListener/test1"); _addStringProperty (handler, "Owner", "arrayOwner", false, true); CIMObjectPath path = client.createInstance (NAMESPACE, handler); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // CIMXML Handler: Missing required Destination property // try { CIMInstance handler (PEGASUS_CLASSNAME_INDHANDLER_CIMXML); _addStringProperty (handler, "Name", "Handler00"); CIMObjectPath path = client.createInstance (NAMESPACE, handler); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // CIMXML Handler: Null required Destination property // try { CIMInstance handler (PEGASUS_CLASSNAME_INDHANDLER_CIMXML); _addStringProperty (handler, "Name", "Handler00"); _addStringProperty (handler, "Destination", String::EMPTY, true); CIMObjectPath path = client.createInstance (NAMESPACE, handler); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // CIMXML Handler: Required Destination property of incorrect type // try { CIMInstance handler (PEGASUS_CLASSNAME_INDHANDLER_CIMXML); _addStringProperty (handler, "Name", "Handler00"); _addUint16Property (handler, "Destination", 1); CIMObjectPath path = client.createInstance (NAMESPACE, handler); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // CIMXML Handler: Unsupported property // try { CIMInstance handler (PEGASUS_CLASSNAME_INDHANDLER_CIMXML); _addStringProperty (handler, "Name", "Handler00"); _addStringProperty (handler, "Destination", "localhost/CIMListener/test1"); _addStringProperty (handler, "Unsupported", "unknown"); CIMObjectPath path = client.createInstance (NAMESPACE, handler); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_NOT_SUPPORTED); } // // SNMP Handler: Missing required TargetHost property // try { CIMInstance handler (PEGASUS_CLASSNAME_INDHANDLER_SNMP); _addStringProperty (handler, "Name", "Handler00"); _addUint16Property (handler, "TargetHostFormat", 2); _addUint16Property (handler, "SNMPVersion", 3); CIMObjectPath path = client.createInstance (NAMESPACE, handler); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // SNMP Handler: Null required TargetHost property // try { CIMInstance handler (PEGASUS_CLASSNAME_INDHANDLER_SNMP); _addStringProperty (handler, "Name", "Handler00"); _addStringProperty (handler, "TargetHost", String::EMPTY, true); _addUint16Property (handler, "TargetHostFormat", 2); _addUint16Property (handler, "SNMPVersion", 3); CIMObjectPath path = client.createInstance (NAMESPACE, handler); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // SNMP Handler: Required TargetHost property of incorrect type // try { CIMInstance handler (PEGASUS_CLASSNAME_INDHANDLER_SNMP); _addStringProperty (handler, "Name", "Handler00"); _addUint16Property (handler, "TargetHost", 1); _addUint16Property (handler, "TargetHostFormat", 2); _addUint16Property (handler, "SNMPVersion", 3); CIMObjectPath path = client.createInstance (NAMESPACE, handler); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // SNMP Handler: Missing required TargetHostFormet property // try { CIMInstance handler (PEGASUS_CLASSNAME_INDHANDLER_SNMP); _addStringProperty (handler, "Name", "Handler00"); _addStringProperty (handler, "TargetHost", "localhost"); _addUint16Property (handler, "SNMPVersion", 3); CIMObjectPath path = client.createInstance (NAMESPACE, handler); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // SNMP Handler: Null required TargetHostFormet property // try { CIMInstance handler (PEGASUS_CLASSNAME_INDHANDLER_SNMP); _addStringProperty (handler, "Name", "Handler00"); _addStringProperty (handler, "TargetHost", "localhost"); _addUint16Property (handler, "TargetHostFormat", 0, true); _addUint16Property (handler, "SNMPVersion", 3); CIMObjectPath path = client.createInstance (NAMESPACE, handler); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // SNMP Handler: Required TargetHostFormet property of incorrect type // try { CIMInstance handler (PEGASUS_CLASSNAME_INDHANDLER_SNMP); _addStringProperty (handler, "Name", "Handler00"); _addStringProperty (handler, "TargetHost", "localhost"); _addStringProperty (handler, "TargetHostFormat", "invalid"); _addUint16Property (handler, "SNMPVersion", 3); CIMObjectPath path = client.createInstance (NAMESPACE, handler); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // SNMP Handler: Missing required SNMPVersion property // try { CIMInstance handler (PEGASUS_CLASSNAME_INDHANDLER_SNMP); _addStringProperty (handler, "Name", "Handler00"); _addStringProperty (handler, "TargetHost", "localhost"); _addUint16Property (handler, "TargetHostFormat", 2); CIMObjectPath path = client.createInstance (NAMESPACE, handler); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // SNMP Handler: Null required SNMPVersion property // try { CIMInstance handler (PEGASUS_CLASSNAME_INDHANDLER_SNMP); _addStringProperty (handler, "Name", "Handler00"); _addStringProperty (handler, "TargetHost", "localhost"); _addUint16Property (handler, "TargetHostFormat", 2); _addUint16Property (handler, "SNMPVersion", 0, true); CIMObjectPath path = client.createInstance (NAMESPACE, handler); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // SNMP Handler: Required SNMPVersion property of incorrect type // try { CIMInstance handler (PEGASUS_CLASSNAME_INDHANDLER_SNMP); _addStringProperty (handler, "Name", "Handler00"); _addStringProperty (handler, "TargetHost", "localhost"); _addUint16Property (handler, "TargetHostFormat", 2); _addStringProperty (handler, "SNMPVersion", "invalid"); CIMObjectPath path = client.createInstance (NAMESPACE, handler); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // SNMP Handler: PortNumber property of incorrect type // try { CIMInstance handler (PEGASUS_CLASSNAME_INDHANDLER_SNMP); _addStringProperty (handler, "Name", "Handler00"); _addStringProperty (handler, "TargetHost", "localhost"); _addUint16Property (handler, "TargetHostFormat", 2); _addUint16Property (handler, "SNMPVersion", 3); _addStringProperty (handler, "PortNumber", "invalid"); CIMObjectPath path = client.createInstance (NAMESPACE, handler); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // SNMP Handler: SNMPSecurityName property of incorrect type // try { CIMInstance handler (PEGASUS_CLASSNAME_INDHANDLER_SNMP); _addStringProperty (handler, "Name", "Handler00"); _addStringProperty (handler, "TargetHost", "localhost"); _addUint16Property (handler, "TargetHostFormat", 2); _addUint16Property (handler, "SNMPVersion", 3); _addUint16Property (handler, "SNMPSecurityName", 1); CIMObjectPath path = client.createInstance (NAMESPACE, handler); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // SNMP Handler: SNMPEngineID property of incorrect type // try { CIMInstance handler (PEGASUS_CLASSNAME_INDHANDLER_SNMP); _addStringProperty (handler, "Name", "Handler00"); _addStringProperty (handler, "TargetHost", "localhost"); _addUint16Property (handler, "TargetHostFormat", 2); _addUint16Property (handler, "SNMPVersion", 3); _addUint16Property (handler, "SNMPEngineID", 1); CIMObjectPath path = client.createInstance (NAMESPACE, handler); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // SNMP Handler: Unsupported property // try { CIMInstance handler (PEGASUS_CLASSNAME_INDHANDLER_SNMP); _addStringProperty (handler, "Name", "Handler00"); _addStringProperty (handler, "TargetHost", "localhost"); _addUint16Property (handler, "TargetHostFormat", 2); _addUint16Property (handler, "SNMPVersion", 3); _addUint32Property (handler, "Unsupported", 162); CIMObjectPath path = client.createInstance (NAMESPACE, handler); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_NOT_SUPPORTED); } // // Handler: Attempt to delete a handler referenced by a subscription // A Handler referenced by a subscription may not be deleted // try { _deleteHandlerInstance (client, PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler01"); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_FAILED); } // // Listener Destination: Unsupported property // try { CIMInstance handler (PEGASUS_CLASSNAME_LSTNRDST_CIMXML); _addStringProperty (handler, "Name", "Handler00"); _addStringProperty (handler, "Destination", "localhost/CIMListener/test1"); _addStringProperty (handler, "Owner", "an owner"); CIMObjectPath path = client.createInstance (NAMESPACE, handler); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_NOT_SUPPORTED); } // // Listener Destination: Attempt to delete a listener destination // referenced by a subscription // A Listener Destination referenced by a subscription may not be // deleted // try { _deleteHandlerInstance (client, PEGASUS_CLASSNAME_LSTNRDST_CIMXML, "ListenerDestination01"); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_FAILED); } // // Create Filter, Listener Destination, Subscription for testing // Create Subscription with correct Host and Namespace in Filter and // Handler reference property value // Verify Host and Namespace appear in Subscription instance name // returned from Create Instance operation // String query; CIMObjectPath fPath; CIMObjectPath hPath; CIMObjectPath sPath; CIMInstance filter10 (PEGASUS_CLASSNAME_INDFILTER); query = "SELECT * FROM CIM_ProcessIndication"; _addStringProperty (filter10, "Name", "Filter10"); _addStringProperty (filter10, "SourceNamespace", SOURCENAMESPACE.getString ()); _addStringProperty (filter10, "Query", query); _addStringProperty (filter10, "QueryLanguage", "WQL"); fPath = client.createInstance (NAMESPACE, filter10); fPath.setHost (System::getFullyQualifiedHostName ()); fPath.setNameSpace (NAMESPACE); CIMInstance listenerdestination04 (PEGASUS_CLASSNAME_LSTNRDST_CIMXML); _addStringProperty (listenerdestination04, "Name", "ListenerDestination04"); _addStringProperty (listenerdestination04, "Destination", "localhost/CIMListener/test6"); hPath = client.createInstance (NAMESPACE, listenerdestination04); hPath.setHost (System::getFullyQualifiedHostName ()); hPath.setNameSpace (NAMESPACE); CIMInstance subscription12 = _buildSubscriptionInstance (fPath, PEGASUS_CLASSNAME_LSTNRDST_CIMXML, hPath); sPath = client.createInstance (NAMESPACE, subscription12); _checkSubscriptionPath (sPath, "Filter10", PEGASUS_CLASSNAME_LSTNRDST_CIMXML, "ListenerDestination04", System::getFullyQualifiedHostName (), System::getFullyQualifiedHostName (), NAMESPACE, NAMESPACE); // // Filter: Attempt to delete a filter referenced by a subscription // A Filter referenced by a subscription may not be deleted // try { _deleteFilterInstance (client, "Filter10"); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_FAILED); } // // Listener Destination: Attempt to delete a listener destination // referenced by a subscription // A Listener Destination referenced by a subscription may not be // deleted // try { _deleteHandlerInstance (client, PEGASUS_CLASSNAME_LSTNRDST_CIMXML, "ListenerDestination04"); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_FAILED); } // // Once Subscription is deleted, Filter and Handler may also be deleted // _deleteSubscriptionInstance (client, "Filter10", PEGASUS_CLASSNAME_LSTNRDST_CIMXML, "ListenerDestination04", System::getFullyQualifiedHostName (), System::getFullyQualifiedHostName (), NAMESPACE, NAMESPACE, NAMESPACE); _deleteFilterInstance (client, "Filter10"); _deleteHandlerInstance (client, PEGASUS_CLASSNAME_LSTNRDST_CIMXML, "ListenerDestination04"); // // Create Subscription with Filter and Handler in different namespaces // CIMInstance filter12 (PEGASUS_CLASSNAME_INDFILTER); query = "SELECT * FROM CIM_ProcessIndication"; _addStringProperty (filter12, "Name", "Filter12"); _addStringProperty (filter12, "SourceNamespace", SOURCENAMESPACE.getString ()); _addStringProperty (filter12, "Query", query); _addStringProperty (filter12, "QueryLanguage", "WQL"); fPath = client.createInstance (NAMESPACE1, filter12); fPath.setNameSpace (NAMESPACE1); CIMInstance listenerdestination07 (PEGASUS_CLASSNAME_LSTNRDST_CIMXML); _addStringProperty (listenerdestination07, "Name", "ListenerDestination07"); _addStringProperty (listenerdestination07, "Destination", "localhost/CIMListener/test8"); hPath = client.createInstance (NAMESPACE2, listenerdestination07); hPath.setNameSpace (NAMESPACE2); CIMInstance subscription15 = _buildSubscriptionInstance (fPath, PEGASUS_CLASSNAME_LSTNRDST_CIMXML, hPath); sPath = client.createInstance (NAMESPACE3, subscription15); _checkSubscriptionPath (sPath, "Filter12", PEGASUS_CLASSNAME_LSTNRDST_CIMXML, "ListenerDestination07", String::EMPTY, String::EMPTY, NAMESPACE1, NAMESPACE2); // // Ensure a duplicate Subscription may not be created // try { CIMInstance subscription17 = _buildSubscriptionInstance (fPath, PEGASUS_CLASSNAME_LSTNRDST_CIMXML, hPath); CIMObjectPath s17Path = client.createInstance (NAMESPACE3, subscription17); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_ALREADY_EXISTS); } // // Filter: Attempt to delete a filter referenced by a subscription // A Filter referenced by a subscription may not be deleted // try { // // Include Host and Namespace in object path of instance to be deleted // to ensure this case is handled correctly. // Host and Namespace are removed before request reaches // IndicationService. // CIMObjectPath aPath = _buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDFILTER, "Filter12"); aPath.setNameSpace (NAMESPACE1); aPath.setHost (System::getFullyQualifiedHostName ()); client.deleteInstance (NAMESPACE1, aPath); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_FAILED); } // // Listener Destination: Attempt to delete a listener destination // referenced by a subscription // A Listener Destination referenced by a subscription may not be // deleted // try { // // Include Host and Namespace in object path of instance to be deleted // to ensure this case is handled correctly. // Host and Namespace are removed before request reaches // IndicationService. // CIMObjectPath aPath = _buildFilterOrHandlerPath (PEGASUS_CLASSNAME_LSTNRDST_CIMXML, "ListenerDestination07"); aPath.setNameSpace (NAMESPACE2); aPath.setHost (System::getFullyQualifiedHostName ()); client.deleteInstance (NAMESPACE2, aPath); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_FAILED); } // // Once Subscription is deleted, Filter and Handler may also be deleted // _deleteSubscriptionInstance (client, "Filter12", PEGASUS_CLASSNAME_LSTNRDST_CIMXML, "ListenerDestination07", String::EMPTY, String::EMPTY, NAMESPACE1, NAMESPACE2, NAMESPACE3); _deleteFilterInstance (client, "Filter12", NAMESPACE1); _deleteHandlerInstance (client, PEGASUS_CLASSNAME_LSTNRDST_CIMXML, "ListenerDestination07", NAMESPACE2); // // Create filter and handler for subscription testing // CIMObjectPath path; CIMInstance filter00 (PEGASUS_CLASSNAME_INDFILTER); query = "SELECT * FROM CIM_ProcessIndication"; _addStringProperty (filter00, "Name", "Filter00"); _addStringProperty (filter00, "Query", query); _addStringProperty (filter00, "QueryLanguage", "WQL"); _addStringProperty (filter00, "SourceNamespace", SOURCENAMESPACE.getString ()); path = client.createInstance (NAMESPACE, filter00); CIMInstance handler00 (PEGASUS_CLASSNAME_INDHANDLER_CIMXML); _addStringProperty (handler00, "Name", "Handler00"); _addStringProperty (handler00, "Destination", "localhost/CIMListener/test0", false); path = client.createInstance (NAMESPACE, handler00); // // Subscription: Missing required Filter key property // try { CIMInstance subscription (PEGASUS_CLASSNAME_INDSUBSCRIPTION); subscription.addProperty (CIMProperty (CIMName ("Handler"), _buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler00"), 0, PEGASUS_CLASSNAME_INDHANDLER_CIMXML)); path = client.createInstance (NAMESPACE, subscription); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // Subscription: Missing required Handler key property // try { CIMInstance subscription (PEGASUS_CLASSNAME_INDSUBSCRIPTION); subscription.addProperty (CIMProperty (CIMName ("Filter"), _buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDFILTER, "Filter00"), 0, PEGASUS_CLASSNAME_INDFILTER)); path = client.createInstance (NAMESPACE, subscription); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // Subscription: Incorrect Host and Namespace in Filter reference // try { CIMObjectPath fPath = _buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDFILTER, "Filter00"); fPath.setHost ("somehost"); fPath.setNameSpace (CIMNamespaceName ("root")); CIMInstance subscription = _buildSubscriptionInstance (fPath, PEGASUS_CLASSNAME_INDHANDLER_CIMXML, _buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler00")); path = client.createInstance (NAMESPACE, subscription); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_CLASS); } // // Subscription: Incorrect Host and Namespace in Handler reference // try { CIMObjectPath hPath = _buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler00"); hPath.setHost ("somehost"); hPath.setNameSpace (CIMNamespaceName ("root")); CIMInstance subscription = _buildSubscriptionInstance (_buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDFILTER, "Filter00"), PEGASUS_CLASSNAME_INDHANDLER_CIMXML, hPath); path = client.createInstance (NAMESPACE, subscription); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_CLASS); } // // Subscription: Incorrect Host in Filter reference property value // try { CIMObjectPath fPath = _buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDFILTER, "Filter00"); fPath.setHost ("ahost.region.acme.com"); fPath.setNameSpace (NAMESPACE); CIMInstance subscription = _buildSubscriptionInstance (fPath, PEGASUS_CLASSNAME_INDHANDLER_CIMXML, _buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler00")); path = client.createInstance (NAMESPACE, subscription); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // Subscription: Incorrect Namespace in Filter reference property value // try { CIMObjectPath fPath = _buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDFILTER, "Filter00"); fPath.setHost (System::getFullyQualifiedHostName ()); fPath.setNameSpace (CIMNamespaceName ("root")); CIMInstance subscription = _buildSubscriptionInstance (fPath, PEGASUS_CLASSNAME_INDHANDLER_CIMXML, _buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler00")); path = client.createInstance (NAMESPACE, subscription); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_CLASS); } // // Subscription: Incorrect Namespace in Filter reference property value // try { CIMObjectPath fPath = _buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDFILTER, "Filter00"); fPath.setNameSpace (CIMNamespaceName ("root")); CIMInstance subscription = _buildSubscriptionInstance (fPath, PEGASUS_CLASSNAME_INDHANDLER_CIMXML, _buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler00")); path = client.createInstance (NAMESPACE, subscription); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_CLASS); } // // Subscription: Incorrect Host in Handler reference property value // try { CIMObjectPath hPath = _buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler00"); hPath.setHost ("ahost.region.acme.com"); hPath.setNameSpace (NAMESPACE); CIMInstance subscription = _buildSubscriptionInstance (_buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDFILTER, "Filter00"), PEGASUS_CLASSNAME_INDHANDLER_CIMXML, hPath); path = client.createInstance (NAMESPACE, subscription); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // Subscription: Incorrect Namespace in Handler reference property value // try { CIMObjectPath hPath = _buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler00"); hPath.setHost (System::getFullyQualifiedHostName ()); hPath.setNameSpace (CIMNamespaceName ("root")); CIMInstance subscription = _buildSubscriptionInstance (_buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDFILTER, "Filter00"), PEGASUS_CLASSNAME_INDHANDLER_CIMXML, hPath); path = client.createInstance (NAMESPACE, subscription); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_CLASS); } // // Subscription: Incorrect Namespace in Handler reference property value // try { CIMObjectPath hPath = _buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler00"); hPath.setNameSpace (CIMNamespaceName ("root")); CIMInstance subscription = _buildSubscriptionInstance (_buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDFILTER, "Filter00"), PEGASUS_CLASSNAME_INDHANDLER_CIMXML, hPath); path = client.createInstance (NAMESPACE, subscription); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_CLASS); } // // Subscription: Unsupported value 1 for property SubscriptionState // try { CIMInstance subscription = _buildSubscriptionInstance (_buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDFILTER, "Filter00"), PEGASUS_CLASSNAME_INDHANDLER_CIMXML, _buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler00")); _addUint16Property (subscription, "SubscriptionState", 1); path = client.createInstance (NAMESPACE, subscription); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_NOT_SUPPORTED); } // // Subscription: OtherSubscriptionState property present, but // SubscriptionState value not 1 // try { CIMInstance subscription = _buildSubscriptionInstance (_buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDFILTER, "Filter00"), PEGASUS_CLASSNAME_INDHANDLER_CIMXML, _buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler00")); _addUint16Property (subscription, "SubscriptionState", 2); _addStringProperty (subscription, "OtherSubscriptionState", "another state"); path = client.createInstance (NAMESPACE, subscription); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // Subscription: Invalid value for property SubscriptionState // try { CIMInstance subscription = _buildSubscriptionInstance (_buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDFILTER, "Filter00"), PEGASUS_CLASSNAME_INDHANDLER_CIMXML, _buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler00")); _addUint16Property (subscription, "SubscriptionState", 5); path = client.createInstance (NAMESPACE, subscription); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // Subscription: Missing required OtherRepeatNotificationPolicy property // try { CIMInstance subscription = _buildSubscriptionInstance (_buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDFILTER, "Filter00"), PEGASUS_CLASSNAME_INDHANDLER_CIMXML, _buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler00")); _addUint16Property (subscription, "RepeatNotificationPolicy", 1); path = client.createInstance (NAMESPACE, subscription); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // Subscription: Null required OtherRepeatNotificationPolicy property // try { CIMInstance subscription = _buildSubscriptionInstance (_buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDFILTER, "Filter00"), PEGASUS_CLASSNAME_INDHANDLER_CIMXML, _buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler00")); _addUint16Property (subscription, "RepeatNotificationPolicy", 1); _addStringProperty (subscription, "OtherRepeatNotificationPolicy", String::EMPTY, true); path = client.createInstance (NAMESPACE, subscription); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // Subscription: OtherRepeatNotificationPolicy property present, but // RepeatNotificationPolicy value not 1 // try { CIMInstance subscription = _buildSubscriptionInstance (_buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDFILTER, "Filter00"), PEGASUS_CLASSNAME_INDHANDLER_CIMXML, _buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler00")); _addUint16Property (subscription, "RepeatNotificationPolicy", 2); _addStringProperty (subscription, "OtherRepeatNotificationPolicy", "another policy"); path = client.createInstance (NAMESPACE, subscription); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // Subscription: OtherRepeatNotificationPolicy property of incorrect type // try { CIMInstance subscription = _buildSubscriptionInstance (_buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDFILTER, "Filter00"), PEGASUS_CLASSNAME_INDHANDLER_CIMXML, _buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler00")); _addUint16Property (subscription, "RepeatNotificationPolicy", 1); _addUint16Property (subscription, "OtherRepeatNotificationPolicy", 1); path = client.createInstance (NAMESPACE, subscription); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // Subscription: Invalid value for property RepeatNotificationPolicy // try { CIMInstance subscription = _buildSubscriptionInstance (_buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDFILTER, "Filter00"), PEGASUS_CLASSNAME_INDHANDLER_CIMXML, _buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler00")); _addUint16Property (subscription, "RepeatNotificationPolicy", 5); path = client.createInstance (NAMESPACE, subscription); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // Subscription: Unsupported value 1 for property OnFatalErrorPolicy // try { CIMInstance subscription = _buildSubscriptionInstance (_buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDFILTER, "Filter00"), PEGASUS_CLASSNAME_INDHANDLER_CIMXML, _buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler00")); _addUint16Property (subscription, "OnFatalErrorPolicy", 1); path = client.createInstance (NAMESPACE, subscription); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_NOT_SUPPORTED); } // // Subscription: OtherOnFatalErrorPolicy property present, but // OnFatalErrorPolicy value not 1 // try { CIMInstance subscription = _buildSubscriptionInstance (_buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDFILTER, "Filter00"), PEGASUS_CLASSNAME_INDHANDLER_CIMXML, _buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler00")); _addUint16Property (subscription, "OnFatalErrorPolicy", 2); _addStringProperty (subscription, "OtherOnFatalErrorPolicy", "another policy"); path = client.createInstance (NAMESPACE, subscription); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // Subscription: Invalid value for property OnFatalErrorPolicy // try { CIMInstance subscription = _buildSubscriptionInstance (_buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDFILTER, "Filter00"), PEGASUS_CLASSNAME_INDHANDLER_CIMXML, _buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler00")); _addUint16Property (subscription, "OnFatalErrorPolicy", 0); path = client.createInstance (NAMESPACE, subscription); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // Subscription: Invalid value for property OnFatalErrorPolicy // try { CIMInstance subscription = _buildSubscriptionInstance (_buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDFILTER, "Filter00"), PEGASUS_CLASSNAME_INDHANDLER_CIMXML, _buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler00")); _addUint16Property (subscription, "OnFatalErrorPolicy", 5); path = client.createInstance (NAMESPACE, subscription); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // Subscription: FailureTriggerTimeInterval property of incorrect type // try { CIMInstance subscription = _buildSubscriptionInstance (_buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDFILTER, "Filter00"), PEGASUS_CLASSNAME_INDHANDLER_CIMXML, _buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler00")); _addStringProperty (subscription, "FailureTriggerTimeInterval", "incorrect type"); path = client.createInstance (NAMESPACE, subscription); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_INVALID_PARAMETER); } // // Subscription: Unsupported property // try { CIMInstance subscription = _buildSubscriptionInstance (_buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDFILTER, "Filter00"), PEGASUS_CLASSNAME_INDHANDLER_CIMXML, _buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler00")); _addUint16Property (subscription, "SubscriptionState", 1); _addUint64Property (subscription, "Unsupported", 60); path = client.createInstance (NAMESPACE, subscription); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_NOT_SUPPORTED); } // // Subscription: No providers for specified filter query // try { CIMInstance filter07 (PEGASUS_CLASSNAME_INDFILTER); query = "SELECT * FROM CIM_ClassIndication"; _addStringProperty (filter07, "Name", "Filter07"); _addStringProperty (filter07, "Query", query); _addStringProperty (filter07, "QueryLanguage", "WQL"); _addStringProperty (filter07, "SourceNamespace", SOURCENAMESPACE.getString ()); path = client.createInstance (NAMESPACE, filter07); CIMInstance subscription = _buildSubscriptionInstance (_buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDFILTER, "Filter07"), PEGASUS_CLASSNAME_INDHANDLER_CIMXML, _buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler00")); path = client.createInstance (NAMESPACE, subscription); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_NOT_SUPPORTED); } // // if the subscription state is disabled, the create should succeed // try { CIMInstance subscription = _buildSubscriptionInstance (_buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDFILTER, "Filter07"), PEGASUS_CLASSNAME_INDHANDLER_CIMXML, _buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler00")); _addUint16Property (subscription, "SubscriptionState", 4); _addUint64Property (subscription, "SubscriptionDuration", 60000); path = client.createInstance (NAMESPACE, subscription); CIMInstance retrievedInstance = client.getInstance (NAMESPACE, path); _checkUint16Property (retrievedInstance, "SubscriptionState", 4); _checkUint64Property (retrievedInstance, "SubscriptionDuration", 60000); _checkUint64Property (retrievedInstance, "SubscriptionTimeRemaining", 60000); _deleteSubscriptionInstance (client, "Filter07", PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler00"); } catch (CIMException &) { PEGASUS_ASSERT (false); } _deleteFilterInstance (client, "Filter07"); // // Attempt to modify filter or handler instance // Modification of filter or handler instances is not supported // try { CIMInstance modifiedInstance (PEGASUS_CLASSNAME_INDFILTER); _addStringProperty (modifiedInstance, "QueryLanguage", "WQL2"); CIMObjectPath path = _buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDFILTER, "Filter01"); modifiedInstance.setPath (path); Array <CIMName> propertyNames; propertyNames.append (CIMName ("QueryLanguage")); CIMPropertyList properties (propertyNames); client.modifyInstance (NAMESPACE, modifiedInstance, false, properties); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_NOT_SUPPORTED); } try { CIMInstance modifiedInstance (PEGASUS_CLASSNAME_INDHANDLER_CIMXML); _addStringProperty (modifiedInstance, "Destination", "localhost/CIMListener/test9"); CIMObjectPath path = _buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler01"); modifiedInstance.setPath (path); Array <CIMName> propertyNames; propertyNames.append (CIMName ("Destination")); CIMPropertyList properties (propertyNames); client.modifyInstance (NAMESPACE, modifiedInstance, false, properties); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_NOT_SUPPORTED); } // // Modify subscription: invalid value for SubscriptionState // try { CIMInstance modifiedInstance (PEGASUS_CLASSNAME_INDSUBSCRIPTION); _addUint16Property (modifiedInstance, "SubscriptionState", 3); CIMObjectPath path = _buildSubscriptionPath ("Filter01", PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler01"); modifiedInstance.setPath (path); Array <CIMName> propertyNames; propertyNames.append (CIMName ("SubscriptionState")); CIMPropertyList properties (propertyNames); client.modifyInstance (NAMESPACE, modifiedInstance, false, properties); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_NOT_SUPPORTED); } // // Modify subscription: property list with more than 1 property // try { CIMInstance modifiedInstance (PEGASUS_CLASSNAME_INDSUBSCRIPTION); _addUint16Property (modifiedInstance, "SubscriptionState", 2); CIMObjectPath path = _buildSubscriptionPath ("Filter01", PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler01"); modifiedInstance.setPath (path); Array <CIMName> propertyNames; propertyNames.append (CIMName ("SubscriptionState")); propertyNames.append (CIMName ("SubscriptionDuration")); CIMPropertyList properties (propertyNames); client.modifyInstance (NAMESPACE, modifiedInstance, false, properties); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_NOT_SUPPORTED); } // // Modify subscription: null property list (all properties) // try { CIMInstance modifiedInstance (PEGASUS_CLASSNAME_INDSUBSCRIPTION); _addUint16Property (modifiedInstance, "SubscriptionState", 2); CIMObjectPath path = _buildSubscriptionPath ("Filter01", PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler01"); modifiedInstance.setPath (path); client.modifyInstance (NAMESPACE, modifiedInstance, false, CIMPropertyList ()); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_NOT_SUPPORTED); } // // Modify subscription: includeQualifiers true // try { CIMInstance modifiedInstance (PEGASUS_CLASSNAME_INDSUBSCRIPTION); _addUint16Property (modifiedInstance, "SubscriptionState", 2); CIMObjectPath path = _buildSubscriptionPath ("Filter01", PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler01"); modifiedInstance.setPath (path); Array <CIMName> propertyNames; propertyNames.append (CIMName ("SubscriptionState")); CIMPropertyList properties (propertyNames); client.modifyInstance (NAMESPACE, modifiedInstance, true, properties); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_NOT_SUPPORTED); } // // Modify subscription: expired subscription // try { // // Create subscription with short SubscriptionDuration // CIMInstance subscription = _buildSubscriptionInstance (_buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDFILTER, "Filter00"), PEGASUS_CLASSNAME_INDHANDLER_CIMXML, _buildFilterOrHandlerPath (PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler00")); _addUint64Property (subscription, "SubscriptionDuration", 1); path = client.createInstance (NAMESPACE, subscription); // // Sleep long enough for the subscription to expire // System::sleep (2); // // Attempt to modify the expired subscription // CIMInstance modifiedInstance (PEGASUS_CLASSNAME_INDSUBSCRIPTION); _addUint16Property (modifiedInstance, "SubscriptionState", 4); modifiedInstance.setPath (path); Array <CIMName> propertyNames; propertyNames.append (CIMName ("SubscriptionState")); CIMPropertyList properties (propertyNames); client.modifyInstance (NAMESPACE, modifiedInstance, false, properties); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_FAILED); } // // Verify the expired subscription has been deleted // try { CIMInstance retrievedInstance = client.getInstance (NAMESPACE, path); PEGASUS_ASSERT (false); } catch (CIMException & e) { _checkExceptionCode (e, CIM_ERR_NOT_FOUND); } // // Delete filter and handler instances // _deleteFilterInstance (client, "Filter00"); _deleteHandlerInstance (client, PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler00"); } void _delete (CIMClient & client) { // // Delete subscription instances // _deleteSubscriptionInstance (client, "Filter01", PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler01"); _deleteSubscriptionInstance (client, "Filter02", PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler01"); _deleteSubscriptionInstance (client, "Filter03", PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler01"); _deleteSubscriptionInstance (client, "Filter04", PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler01"); _deleteSubscriptionInstance (client, "Filter05", PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler01"); _deleteSubscriptionInstance (client, "Filter06", PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler01"); _deleteSubscriptionInstance (client, "Filter01", PEGASUS_CLASSNAME_INDHANDLER_SNMP, "Handler03"); _deleteSubscriptionInstance (client, "Filter01", PEGASUS_CLASSNAME_LSTNRDST_CIMXML, "ListenerDestination01"); // // Delete handler instances // _deleteHandlerInstance (client, PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler01"); _deleteHandlerInstance (client, PEGASUS_CLASSNAME_INDHANDLER_SNMP, "Handler03"); _deleteHandlerInstance (client, PEGASUS_CLASSNAME_LSTNRDST_CIMXML, "ListenerDestination01"); // // Delete filter instances // _deleteFilterInstance (client, "Filter01"); _deleteFilterInstance (client, "Filter02"); _deleteFilterInstance (client, "Filter03"); _deleteFilterInstance (client, "Filter04"); #ifndef PEGASUS_DISABLE_CQL _deleteFilterInstance (client, "Filter04a"); #endif _deleteFilterInstance (client, "Filter05"); _deleteFilterInstance (client, "Filter06"); } void _test (CIMClient & client) { try { String wql("WQL"); String cql("CIM:CQL"); _valid (client, wql); _default (client); _errorQueries(client, wql); _error (client); _delete (client); #ifndef PEGASUS_DISABLE_CQL _valid (client, cql); #endif _errorQueries(client, cql); #ifndef PEGASUS_DISABLE_CQL _delete (client); #endif } catch (Exception & e) { cerr << "test failed: " << e.getMessage () << endl; exit (-1); } cout << "+++++ test completed successfully" << endl; } // // NOTE: the cleanup command line option is provided to clean up the // repository in case the test fails and not all objects created by // the test were deleted // This method attempts to delete each object that could have been created by // this test and that still exists in the repository // Since the repository could contain none, any or all of the objects, any // exceptions thrown are ignored and this method continues to attempt to // delete the objects // void _cleanup (CIMClient & client) { // // Delete subscription instances // try { _deleteSubscriptionInstance (client, "Filter00", PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler00"); } catch (...) { } try { _deleteSubscriptionInstance (client, "Filter01", PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler01"); } catch (...) { } try { _deleteSubscriptionInstance (client, "Filter02", PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler01"); } catch (...) { } try { _deleteSubscriptionInstance (client, "Filter03", PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler01"); } catch (...) { } try { _deleteSubscriptionInstance (client, "Filter04", PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler01"); } catch (...) { } try { _deleteSubscriptionInstance (client, "Filter05", PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler01"); } catch (...) { } try { _deleteSubscriptionInstance (client, "Filter06", PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler01"); } catch (...) { } try { _deleteSubscriptionInstance (client, "Filter07", PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler00"); } catch (...) { } try { _deleteSubscriptionInstance (client, "Filter01", PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler02"); } catch (...) { } try { _deleteSubscriptionInstance (client, "Filter01", PEGASUS_CLASSNAME_INDHANDLER_SNMP, "Handler03"); } catch (...) { } try { _deleteSubscriptionInstance (client, "Filter01", PEGASUS_CLASSNAME_LSTNRDST_CIMXML, "ListenerDestination01"); } catch (...) { } try { _deleteSubscriptionInstance (client, "Filter08", PEGASUS_CLASSNAME_LSTNRDST_CIMXML, "ListenerDestination02", System::getFullyQualifiedHostName (), System::getFullyQualifiedHostName (), NAMESPACE, NAMESPACE, NAMESPACE); } catch (...) { } try { _deleteSubscriptionInstance (client, "Filter09", PEGASUS_CLASSNAME_LSTNRDST_CIMXML, "ListenerDestination03", String::EMPTY, String::EMPTY, NAMESPACE, NAMESPACE, NAMESPACE); } catch (...) { } try { _deleteSubscriptionInstance (client, "Filter10", PEGASUS_CLASSNAME_LSTNRDST_CIMXML, "ListenerDestination04", System::getFullyQualifiedHostName (), System::getFullyQualifiedHostName (), NAMESPACE, NAMESPACE, NAMESPACE); } catch (...) { } try { _deleteSubscriptionInstance (client, "Filter11", PEGASUS_CLASSNAME_LSTNRDST_CIMXML, "ListenerDestination05", String::EMPTY, String::EMPTY, NAMESPACE1, NAMESPACE2, NAMESPACE3); } catch (...) { } try { _deleteSubscriptionInstance (client, "Filter11", PEGASUS_CLASSNAME_LSTNRDST_CIMXML, "ListenerDestination07", String::EMPTY, String::EMPTY, NAMESPACE1, NAMESPACE2, NAMESPACE3); } catch (...) { } try { _deleteSubscriptionInstance (client, "Filter12", PEGASUS_CLASSNAME_LSTNRDST_CIMXML, "ListenerDestination06", String::EMPTY, String::EMPTY, NAMESPACE1, NAMESPACE2, NAMESPACE3); } catch (...) { } try { _deleteSubscriptionInstance (client, "Filter12", PEGASUS_CLASSNAME_LSTNRDST_CIMXML, "ListenerDestination06", String::EMPTY, String::EMPTY, NAMESPACE1, NAMESPACE3, NAMESPACE2); } catch (...) { } try { _deleteSubscriptionInstance (client, "Filter11", PEGASUS_CLASSNAME_LSTNRDST_CIMXML, "ListenerDestination05", String::EMPTY, String::EMPTY, NAMESPACE2, NAMESPACE1, NAMESPACE3); } catch (...) { } // // Delete handler instances // try { _deleteHandlerInstance (client, PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler00"); } catch (...) { } try { _deleteHandlerInstance (client, PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler01"); } catch (...) { } try { _deleteHandlerInstance (client, PEGASUS_CLASSNAME_INDHANDLER_CIMXML, "Handler02"); } catch (...) { } try { _deleteHandlerInstance (client, PEGASUS_CLASSNAME_INDHANDLER_SNMP, "Handler03"); } catch (...) { } try { _deleteHandlerInstance (client, PEGASUS_CLASSNAME_LSTNRDST_CIMXML, "ListenerDestination01"); } catch (...) { } try { _deleteHandlerInstance (client, PEGASUS_CLASSNAME_LSTNRDST_CIMXML, "ListenerDestination02"); } catch (...) { } try { _deleteHandlerInstance (client, PEGASUS_CLASSNAME_LSTNRDST_CIMXML, "ListenerDestination03"); } catch (...) { } try { _deleteHandlerInstance (client, PEGASUS_CLASSNAME_LSTNRDST_CIMXML, "ListenerDestination04"); } catch (...) { } try { _deleteHandlerInstance (client, PEGASUS_CLASSNAME_LSTNRDST_CIMXML, "ListenerDestination05", NAMESPACE1); } catch (...) { } try { _deleteHandlerInstance (client, PEGASUS_CLASSNAME_LSTNRDST_CIMXML, "ListenerDestination05", NAMESPACE2); } catch (...) { } try { _deleteHandlerInstance (client, PEGASUS_CLASSNAME_LSTNRDST_CIMXML, "ListenerDestination06", NAMESPACE2); } catch (...) { } try { _deleteHandlerInstance (client, PEGASUS_CLASSNAME_LSTNRDST_CIMXML, "ListenerDestination06", NAMESPACE3); } catch (...) { } try { _deleteHandlerInstance (client, PEGASUS_CLASSNAME_LSTNRDST_CIMXML, "ListenerDestination07", NAMESPACE2); } catch (...) { } // // Delete filter instances // try { _deleteFilterInstance (client, "Filter00"); } catch (...) { } try { _deleteFilterInstance (client, "Filter01"); } catch (...) { } try { _deleteFilterInstance (client, "Filter02"); } catch (...) { } try { _deleteFilterInstance (client, "Filter03"); } catch (...) { } try { _deleteFilterInstance (client, "Filter04"); } catch (...) { } try { _deleteFilterInstance (client, "Filter04a"); } catch (...) { } try { _deleteFilterInstance (client, "Filter05"); } catch (...) { } try { _deleteFilterInstance (client, "Filter06"); } catch (...) { } try { _deleteFilterInstance (client, "Filter07"); } catch (...) { } try { _deleteFilterInstance (client, "Filter08"); } catch (...) { } try { _deleteFilterInstance (client, "Filter09"); } catch (...) { } try { _deleteFilterInstance (client, "Filter10"); } catch (...) { } try { _deleteFilterInstance (client, "Filter11", NAMESPACE1); } catch (...) { } try { _deleteFilterInstance (client, "Filter11", NAMESPACE2); } catch (...) { } try { _deleteFilterInstance (client, "Filter12", NAMESPACE1); } catch (...) { } // // Delete provider registration instances // try { _deleteCapabilityInstance (client, "AlertIndicationProviderModule", "AlertIndicationProvider", "AlertIndicationProviderCapability"); } catch (...) { } try { _deleteProviderInstance (client, "AlertIndicationProvider", "AlertIndicationProviderModule"); } catch (...) { } try { _deleteModuleInstance (client, "AlertIndicationProviderModule"); } catch (...) { } try { _deleteCapabilityInstance (client, "ProcessIndicationProviderModule", "ProcessIndicationProvider", "ProcessIndicationProviderCapability"); } catch (...) { } try { _deleteProviderInstance (client, "ProcessIndicationProvider", "ProcessIndicationProviderModule"); } catch (...) { } try { _deleteModuleInstance (client, "ProcessIndicationProviderModule"); } catch (...) { } cout << "+++++ cleanup completed successfully" << endl; } void _unregister (CIMClient & client) { try { _deleteCapabilityInstance (client, "AlertIndicationProviderModule", "AlertIndicationProvider", "AlertIndicationProviderCapability"); _deleteProviderInstance (client, "AlertIndicationProvider", "AlertIndicationProviderModule"); _deleteModuleInstance (client, "AlertIndicationProviderModule"); _deleteCapabilityInstance (client, "ProcessIndicationProviderModule", "ProcessIndicationProvider", "ProcessIndicationProviderCapability"); _deleteProviderInstance (client, "ProcessIndicationProvider", "ProcessIndicationProviderModule"); _deleteModuleInstance (client, "ProcessIndicationProviderModule"); } catch (Exception & e) { cerr << "unregister failed: " << e.getMessage () << endl; exit (-1); } cout << "+++++ unregister completed successfully" << endl; } int main (int argc, char** argv) { verbose = (getenv ("PEGASUS_TEST_VERBOSE")) ? true : false; CIMClient client; try { client.connectLocal (); } catch (Exception & e) { cerr << e.getMessage () << endl; return -1; } if (argc != 2) { _usage (); return 1; } else { const char * opt = argv [1]; if (String::equalNoCase (opt, "register")) { _register (client); } else if (String::equalNoCase (opt, "test")) { _test (client); } // // NOTE: the cleanup command line option is provided to clean up the // repository in case the test fails and not all objects created by // the test were deleted // else if (String::equalNoCase (opt, "cleanup")) { _cleanup (client); } else if (String::equalNoCase (opt, "unregister")) { _unregister (client); } else { cerr << "Invalid option: " << opt << endl; _usage (); return -1; } } return 0; }
35.006768
92
0.671176
ncultra
6f26716f8ce835e63dd95904ee486c940f3e90b7
4,378
cpp
C++
src/mod/debug/penetration.cpp
fugueinheels/sigsegv-mvm
092a69d44a3ed9aacd14886037f4093a27ff816b
[ "BSD-2-Clause" ]
33
2016-02-18T04:27:53.000Z
2022-01-15T18:59:53.000Z
src/mod/debug/penetration.cpp
fugueinheels/sigsegv-mvm
092a69d44a3ed9aacd14886037f4093a27ff816b
[ "BSD-2-Clause" ]
5
2018-01-10T18:41:38.000Z
2020-10-01T13:34:53.000Z
src/mod/debug/penetration.cpp
fugueinheels/sigsegv-mvm
092a69d44a3ed9aacd14886037f4093a27ff816b
[ "BSD-2-Clause" ]
14
2017-08-06T23:02:49.000Z
2021-08-24T00:24:16.000Z
#include "mod.h" #include "stub/tfplayer.h" #include "stub/tfweaponbase.h" #include "util/scope.h" namespace Mod::Debug::Penetration { struct penetrated_target_list { CBaseEntity *ent; // +0x00 float fraction; // +0x04 }; struct CBulletPenetrateEnum { void **vtable; // +0x00 Ray_t *ray; // +0x04 int pen_type; // +0x08 CTFPlayer *player; // +0x0c bool bool_0x10; // +0x10 CUtlVector<penetrated_target_list> vec; // +0x14, actually: CUtlSortVector<penetrated_target_list, PenetratedTargetLess> int dword_0x28; // +0x28 bool bool_0x2c; // +0x2c }; RefCount rc_CTFPlayer_FireBullet; DETOUR_DECL_MEMBER(void, CTFPlayer_FireBullet, CTFWeaponBase *weapon, const FireBulletsInfo_t& info, bool bDoEffects, int nDamageType, int nCustomDamageType) { DevMsg("\nCTFPlayer::FireBullet BEGIN\n"); DevMsg(" nCustomDamageType = %d\n", nCustomDamageType); int pen_type = nCustomDamageType; if (weapon != nullptr && weapon->GetPenetrateType() != 0) { pen_type = weapon->GetPenetrateType(); } DevMsg(" pen_type = %d\n", pen_type); bool has_pen = ((unsigned int)pen_type - 0xbu <= 1u); DevMsg(" has_pen = %s\n", (has_pen ? "true" : "false")); SCOPED_INCREMENT(rc_CTFPlayer_FireBullet); DETOUR_MEMBER_CALL(CTFPlayer_FireBullet)(weapon, info, bDoEffects, nDamageType, nCustomDamageType); DevMsg("CTFPlayer::FireBullet END\n"); } RefCount rc_IEngineTrace_EnumerateEntities; DETOUR_DECL_MEMBER(void, IEngineTrace_EnumerateEntities_ray, const Ray_t& ray, bool triggers, IEntityEnumerator *pEnumerator) { DevMsg(" IEngineTrace::EnumerateEntities BEGIN\n"); SCOPED_INCREMENT(rc_IEngineTrace_EnumerateEntities); DETOUR_MEMBER_CALL(IEngineTrace_EnumerateEntities_ray)(ray, triggers, pEnumerator); auto pen = reinterpret_cast<CBulletPenetrateEnum *>(pEnumerator); FOR_EACH_VEC(pen->vec, i) { DevMsg(" pen[%d]: %.2f #%d (class '%s' name '%s')\n", i, pen->vec[i].fraction, ENTINDEX(pen->vec[i].ent), pen->vec[i].ent->GetClassname(), STRING(pen->vec[i].ent->GetEntityName())); } DevMsg(" IEngineTrace::EnumerateEntities END\n"); } DETOUR_DECL_MEMBER(bool, CBulletPenetrateEnum_EnumEntity, IHandleEntity *pHandleEntity) { auto pen = reinterpret_cast<CBulletPenetrateEnum *>(this); auto ent = reinterpret_cast<CBaseEntity *>(pHandleEntity); int count_before = pen->vec.Count(); bool result = DETOUR_MEMBER_CALL(CBulletPenetrateEnum_EnumEntity)(pHandleEntity); if (rc_CTFPlayer_FireBullet > 0 && rc_IEngineTrace_EnumerateEntities > 0) { bool was_added = (pen->vec.Count() != count_before); if (was_added) { DevMsg(" CBulletPenetrateEnum::EnumEntity: ADDED #%d (class '%s' name '%s')\n", ENTINDEX(ent), ent->GetClassname(), STRING(ent->GetEntityName())); } else { DevMsg(" CBulletPenetrateEnum::EnumEntity: SKIPPED #%d (class '%s' name '%s')\n", ENTINDEX(ent), ent->GetClassname(), STRING(ent->GetEntityName())); } } return result; } class CDmgAccumulator; DETOUR_DECL_MEMBER(void, CBaseEntity_DispatchTraceAttack, const CTakeDamageInfo& info, const Vector& vecDir, trace_t *ptr, CDmgAccumulator *pAccumulator) { auto ent = reinterpret_cast<CBaseEntity *>(this); if (rc_CTFPlayer_FireBullet > 0) { DevMsg(" CBaseEntity::DispatchTraceAttack: ent #%d (m_iPlayerPenetrationCount = %d)\n", ENTINDEX(ent), info.GetPlayerPenetrationCount()); } DETOUR_MEMBER_CALL(CBaseEntity_DispatchTraceAttack)(info, vecDir, ptr, pAccumulator); } class CMod : public IMod { public: CMod() : IMod("Debug:Penetration") { MOD_ADD_DETOUR_MEMBER(CTFPlayer_FireBullet, "CTFPlayer::FireBullet"); MOD_ADD_DETOUR_MEMBER(IEngineTrace_EnumerateEntities_ray, "IEngineTrace::EnumerateEntities_ray"); MOD_ADD_DETOUR_MEMBER(CBulletPenetrateEnum_EnumEntity, "CBulletPenetrateEnum::EnumEntity"); MOD_ADD_DETOUR_MEMBER(CBaseEntity_DispatchTraceAttack, "CBaseEntity::DispatchTraceAttack"); } }; CMod s_Mod; ConVar cvar_enable("sig_debug_penetration", "0", FCVAR_NOTIFY, "Debug: penetration", [](IConVar *pConVar, const char *pOldValue, float flOldValue){ s_Mod.Toggle(static_cast<ConVar *>(pConVar)->GetBool()); }); }
34.746032
159
0.694838
fugueinheels