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
float64
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
float64
1
77k
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
float64
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
653k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
1
28d69e42f3993b3aef47de906eaa6b8a5745446d
153
cpp
C++
lib/source/mylib.cpp
Honeybunch/cpplibtemplate
23ea15343bb469198420f54eb3d87c4055468084
[ "MIT" ]
null
null
null
lib/source/mylib.cpp
Honeybunch/cpplibtemplate
23ea15343bb469198420f54eb3d87c4055468084
[ "MIT" ]
null
null
null
lib/source/mylib.cpp
Honeybunch/cpplibtemplate
23ea15343bb469198420f54eb3d87c4055468084
[ "MIT" ]
null
null
null
#include "mylib.h" int my_val = 0; void init_my_lib() { my_val = 10; } int get_my_lib_val() { return my_val; } void shutdown_my_lib() { my_val = 0; }
17
39
0.660131
28db93888191a41fd1097f3d2e69265cd481042d
11,791
cpp
C++
connectivity/FEATURE_BLE/source/generic/KVStoreSecurityDb.cpp
heuisam/mbed-os
eb32b25c8abb37f0aab505451074448e7e420517
[ "Apache-2.0" ]
1
2021-02-09T21:27:17.000Z
2021-02-09T21:27:17.000Z
connectivity/FEATURE_BLE/source/generic/KVStoreSecurityDb.cpp
heuisam/mbed-os
eb32b25c8abb37f0aab505451074448e7e420517
[ "Apache-2.0" ]
1
2021-12-13T14:33:09.000Z
2021-12-13T14:33:09.000Z
connectivity/FEATURE_BLE/source/generic/KVStoreSecurityDb.cpp
heuisam/mbed-os
eb32b25c8abb37f0aab505451074448e7e420517
[ "Apache-2.0" ]
null
null
null
/* mbed Microcontroller Library * Copyright (c) 2006-2020 ARM Limited * * SPDX-License-Identifier: Apache-2.0 * * 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. */ #if BLE_SECURITY_DATABASE_KVSTORE #include "KVStoreSecurityDb.h" namespace ble { #if BLE_SECURITY_DATABASE_MAX_ENTRIES > 9 #error "BLE_SECURITY_DATABASE_MAX_ENTRIES must be only one digit long" #endif #define ENTRY_INVALID (0xFF) constexpr uint8_t KVStoreSecurityDb::KVSTORESECURITYDB_VERSION; constexpr size_t KVStoreSecurityDb::DB_PREFIX_SIZE; constexpr size_t KVStoreSecurityDb::DB_KEY_SIZE; constexpr size_t KVStoreSecurityDb::DB_ENTRY_KEY_SIZE; constexpr size_t KVStoreSecurityDb::DB_FULL_KEY_SIZE; constexpr char KVStoreSecurityDb::DB_PREFIX[DB_PREFIX_SIZE+1]; constexpr char KVStoreSecurityDb::DB_ENTRIES[DB_KEY_SIZE]; constexpr char KVStoreSecurityDb::DB_ENTRY_PEER_IDENTITY[DB_ENTRY_KEY_SIZE]; constexpr char KVStoreSecurityDb::DB_ENTRY_LOCAL_KEYS[DB_ENTRY_KEY_SIZE]; constexpr char KVStoreSecurityDb::DB_ENTRY_PEER_KEYS[DB_ENTRY_KEY_SIZE]; constexpr char KVStoreSecurityDb::DB_ENTRY_PEER_SIGNING[DB_ENTRY_KEY_SIZE]; constexpr char KVStoreSecurityDb::DB_LOCAL_IDENTITY[DB_KEY_SIZE]; constexpr char KVStoreSecurityDb::DB_LOCAL_CSRK[DB_KEY_SIZE]; constexpr char KVStoreSecurityDb::DB_LOCAL_SIGN_COUNT[DB_KEY_SIZE]; constexpr char KVStoreSecurityDb::DB_VERSION[DB_KEY_SIZE]; constexpr char KVStoreSecurityDb::DB_RESTORE[DB_KEY_SIZE]; typedef SecurityDb::entry_handle_t entry_handle_t; KVStoreSecurityDb::KVStoreSecurityDb() : SecurityDb() { memset(_entries, 0, sizeof(_entries)); for (size_t i = 0; i < get_entry_count(); i++) { _entries[i].index = ENTRY_INVALID; } } KVStoreSecurityDb::~KVStoreSecurityDb() { } bool KVStoreSecurityDb::open_db() { uint8_t version = 0; char db_key[DB_FULL_KEY_SIZE]; create_key(db_key, DB_VERSION); size_t size; int ret = kv_get(db_key, &version, sizeof(uint8_t), &size); /* kvstore problem (check if it's been successfully initialised before this call) */ if (ret != MBED_ERROR_ITEM_NOT_FOUND && (ret != MBED_SUCCESS || size != sizeof(uint8_t))) { return false; } /* wipe the db if it's the wrong version or it doesn't exist */ if (version != KVSTORESECURITYDB_VERSION) { return erase_db(); } return true; } bool KVStoreSecurityDb::erase_db() { union zero_t { int dummy; /* we need a dummy for initialisation */ uint8_t buffer[sizeof(SecurityEntryKeys_t)]; entry_t entries[BLE_SECURITY_DATABASE_MAX_ENTRIES]; } zero = { 0 }; memset(&zero, 0, sizeof(zero)); /* we zero the database and make sure we can fit all our keys */ db_write(zero.entries, DB_ENTRIES); db_write((SecurityEntryIdentity_t*)zero.buffer, DB_LOCAL_IDENTITY); db_write((csrk_t*)zero.buffer, DB_LOCAL_CSRK); db_write((sign_count_t*)zero.buffer, DB_LOCAL_SIGN_COUNT); bool reload = false; db_write(&reload, DB_RESTORE); for (int index = 0; index < BLE_SECURITY_DATABASE_MAX_ENTRIES; ++index) { db_write_entry((SecurityEntryKeys_t*)zero.buffer, DB_ENTRY_LOCAL_KEYS, index); db_write_entry((SecurityEntryIdentity_t*)zero.buffer, DB_ENTRY_PEER_IDENTITY, index); db_write_entry((SecurityEntryKeys_t*)zero.buffer, DB_ENTRY_PEER_KEYS, index); db_write_entry((SecurityEntrySigning_t*)zero.buffer, DB_ENTRY_PEER_SIGNING, index); } /* now we write the version and read it back to see if was written succesfully */ uint8_t version = KVSTORESECURITYDB_VERSION; db_write(&version, DB_VERSION); version = 0; db_read(&version, DB_VERSION); return (version == KVSTORESECURITYDB_VERSION); } SecurityDistributionFlags_t* KVStoreSecurityDb::get_distribution_flags( entry_handle_t db_handle ) { return reinterpret_cast<SecurityDistributionFlags_t*>(db_handle); } /* local keys */ /* set */ void KVStoreSecurityDb::set_entry_local_ltk( entry_handle_t db_handle, const ltk_t &ltk ) { entry_t *entry = as_entry(db_handle); if (!entry) { return; } entry->flags.ltk_sent = true; SecurityEntryKeys_t* current_entry = read_in_entry_local_keys(db_handle); current_entry->ltk = ltk; db_write_entry(current_entry, DB_ENTRY_LOCAL_KEYS, entry->index); } void KVStoreSecurityDb::set_entry_local_ediv_rand( entry_handle_t db_handle, const ediv_t &ediv, const rand_t &rand ) { entry_t *entry = as_entry(db_handle); if (!entry) { return; } SecurityEntryKeys_t* current_entry = read_in_entry_local_keys(db_handle); current_entry->ediv = ediv; current_entry->rand = rand; db_write_entry(current_entry, DB_ENTRY_LOCAL_KEYS, entry->index); } /* peer's keys */ /* set */ void KVStoreSecurityDb::set_entry_peer_ltk( entry_handle_t db_handle, const ltk_t &ltk ) { entry_t *entry = as_entry(db_handle); if (!entry) { return; } entry->flags.ltk_stored = true; SecurityEntryKeys_t* current_entry = read_in_entry_peer_keys(db_handle); current_entry->ltk = ltk; db_write_entry(current_entry, DB_ENTRY_PEER_KEYS, entry->index); } void KVStoreSecurityDb::set_entry_peer_ediv_rand( entry_handle_t db_handle, const ediv_t &ediv, const rand_t &rand ) { entry_t *entry = as_entry(db_handle); if (!entry) { return; } SecurityEntryKeys_t* current_entry = read_in_entry_peer_keys(db_handle); current_entry->ediv = ediv; current_entry->rand = rand; db_write_entry(current_entry, DB_ENTRY_PEER_KEYS, entry->index); } void KVStoreSecurityDb::set_entry_peer_irk( entry_handle_t db_handle, const irk_t &irk ) { entry_t *entry = as_entry(db_handle); if (!entry) { return; } entry->flags.irk_stored = true; SecurityEntryIdentity_t* current_entry = read_in_entry_peer_identity(db_handle); current_entry->irk = irk; db_write_entry(current_entry, DB_ENTRY_PEER_IDENTITY, entry->index); } void KVStoreSecurityDb::set_entry_peer_bdaddr( entry_handle_t db_handle, bool address_is_public, const address_t &peer_address ) { entry_t *entry = as_entry(db_handle); if (!entry) { return; } SecurityEntryIdentity_t* current_entry = read_in_entry_peer_identity(db_handle); current_entry->identity_address = peer_address; current_entry->identity_address_is_public = address_is_public; db_write_entry(current_entry, DB_ENTRY_PEER_IDENTITY, entry->index); } void KVStoreSecurityDb::set_entry_peer_csrk( entry_handle_t db_handle, const csrk_t &csrk ) { entry_t *entry = as_entry(db_handle); if (!entry) { return; } entry->flags.csrk_stored = true; SecurityEntrySigning_t* current_entry = read_in_entry_peer_signing(db_handle); current_entry->csrk = csrk; db_write_entry(current_entry, DB_ENTRY_PEER_SIGNING, entry->index); } void KVStoreSecurityDb::set_entry_peer_sign_counter( entry_handle_t db_handle, sign_count_t sign_counter ) { entry_t *entry = as_entry(db_handle); if (entry) { entry->peer_sign_counter = sign_counter; } } void KVStoreSecurityDb::set_local_csrk( const csrk_t &csrk ) { this->SecurityDb::set_local_csrk(csrk); db_write(&_local_csrk, DB_LOCAL_CSRK); } void KVStoreSecurityDb::set_local_identity( const irk_t &irk, const address_t &identity_address, bool public_address ) { this->SecurityDb::set_local_identity(irk, identity_address, public_address); db_write(&_local_identity, DB_LOCAL_IDENTITY); } /* saving and loading from nvm */ void KVStoreSecurityDb::restore() { /* restore if requested */ bool restore_toggle = false; db_read(&restore_toggle, DB_RESTORE); if (!restore_toggle) { erase_db(); return; } db_read(&_entries, DB_ENTRIES); db_read(&_local_identity, DB_LOCAL_IDENTITY); db_read(&_local_csrk, DB_LOCAL_CSRK); db_read(&_local_sign_counter, DB_LOCAL_SIGN_COUNT); } void KVStoreSecurityDb::sync(entry_handle_t db_handle) { entry_t *entry = as_entry(db_handle); if (!entry) { return; } /* all entries are stored in a single key so we store them all*/ db_write(&_entries, DB_ENTRIES); db_write(&_local_identity, DB_LOCAL_IDENTITY); db_write(&_local_csrk, DB_LOCAL_CSRK); db_write(&_local_sign_counter, DB_LOCAL_SIGN_COUNT); } void KVStoreSecurityDb::set_restore(bool reload) { db_write(&reload, DB_RESTORE); } /* helper functions */ uint8_t KVStoreSecurityDb::get_entry_count() { return BLE_SECURITY_DATABASE_MAX_ENTRIES; } SecurityDistributionFlags_t* KVStoreSecurityDb::get_entry_handle_by_index(uint8_t index) { if (index < get_entry_count()) { return &_entries[index].flags; } else { return nullptr; } } void KVStoreSecurityDb::reset_entry(entry_handle_t db_handle) { entry_t *entry = as_entry(db_handle); if (!entry) { return; } if (entry->index != ENTRY_INVALID) { uint8_t zero_buffer[sizeof(SecurityEntryKeys_t)] = {0}; db_write_entry((SecurityEntryKeys_t*)zero_buffer, DB_ENTRY_LOCAL_KEYS, entry->index); db_write_entry((SecurityEntryIdentity_t*)zero_buffer, DB_ENTRY_PEER_IDENTITY, entry->index); db_write_entry((SecurityEntryKeys_t*)zero_buffer, DB_ENTRY_PEER_KEYS, entry->index); db_write_entry((SecurityEntrySigning_t*)zero_buffer, DB_ENTRY_PEER_SIGNING, entry->index); entry->index = ENTRY_INVALID; } entry->flags = SecurityDistributionFlags_t(); entry->peer_sign_counter = 0; } SecurityEntryIdentity_t* KVStoreSecurityDb::read_in_entry_peer_identity(entry_handle_t db_handle) { entry_t *entry = as_entry(db_handle); if (!entry) { return nullptr; } SecurityEntryIdentity_t* identity = reinterpret_cast<SecurityEntryIdentity_t*>(_buffer); db_read_entry(identity, DB_ENTRY_PEER_IDENTITY, entry->index); return identity; }; SecurityEntryKeys_t* KVStoreSecurityDb::read_in_entry_peer_keys(entry_handle_t db_handle) { entry_t *entry = as_entry(db_handle); if (!entry) { return nullptr; } SecurityEntryKeys_t* keys = reinterpret_cast<SecurityEntryKeys_t*>(_buffer); db_read_entry(keys, DB_ENTRY_PEER_KEYS, entry->index); return keys; }; SecurityEntryKeys_t* KVStoreSecurityDb::read_in_entry_local_keys(entry_handle_t db_handle) { entry_t *entry = as_entry(db_handle); if (!entry) { return nullptr; } SecurityEntryKeys_t* keys = reinterpret_cast<SecurityEntryKeys_t*>(_buffer); db_read_entry(keys, DB_ENTRY_LOCAL_KEYS, entry->index); return keys; }; SecurityEntrySigning_t* KVStoreSecurityDb::read_in_entry_peer_signing(entry_handle_t db_handle) { entry_t *entry = as_entry(db_handle); if (!entry) { return nullptr; } /* only read in the csrk */ csrk_t* csrk = reinterpret_cast<csrk_t*>(_buffer); db_read_entry(csrk, DB_ENTRY_PEER_SIGNING, entry->index); /* use the counter held in memory */ SecurityEntrySigning_t* signing = reinterpret_cast<SecurityEntrySigning_t*>(_buffer); signing->counter = entry->peer_sign_counter; return signing; }; } /* namespace generic */ #endif // BLE_SECURITY_DATABASE_KVSTORE
27.549065
100
0.728691
28dd794bd3fb67d5f127f478514de0bcf07f7257
13,299
cpp
C++
flashlight/app/objdet/nn/Transformer.cpp
snapbuy/flashlight
f6ebe7a3d22dc357fe36e19fcbf66d64c3a57356
[ "BSD-3-Clause" ]
1
2021-04-30T15:49:10.000Z
2021-04-30T15:49:10.000Z
flashlight/app/objdet/nn/Transformer.cpp
snapbuy/flashlight
f6ebe7a3d22dc357fe36e19fcbf66d64c3a57356
[ "BSD-3-Clause" ]
null
null
null
flashlight/app/objdet/nn/Transformer.cpp
snapbuy/flashlight
f6ebe7a3d22dc357fe36e19fcbf66d64c3a57356
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) Facebook, Inc. and its affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #include "flashlight/app/objdet/nn/Transformer.h" #include "flashlight/fl/nn/nn.h" using namespace fl; namespace { std::shared_ptr<fl::Linear> makeTransformerLinear(int inDim, int outDim, float gain = 1.0f) { int fanIn = inDim; int fanOut = outDim; float std = gain * std::sqrt(2.0 / (fanIn + fanOut)); float bound = std::sqrt(3.0) * std; auto w = fl::uniform(outDim, inDim, -bound, bound, f32, true); bound = std::sqrt(1.0 / fanIn); auto b = fl::uniform(af::dim4(outDim), -bound, bound, af::dtype::f32, true); return std::make_shared<fl::Linear>(w, b); } std::shared_ptr<fl::Linear> makeMultiheadedAttentionLinear(int inDim, int outDim, int fanOutMult = 1) { int fanIn = inDim; int fanOut = outDim * fanOutMult; float gain = 1.0; float std = gain * std::sqrt(2.0 / (fanIn + fanOut)); float bound = std::sqrt(3.0) * std; auto w = fl::uniform(outDim, inDim, -bound, bound, f32, true); auto b = fl::param(af::constant(0, af::dim4(outDim))); return std::make_shared<fl::Linear>(w, b); } } // namespace namespace fl { namespace app { namespace objdet { // query [ E X B X L ] // values and keys [ E X B X S ] fl::Variable transformerMultiheadAttention( const fl::Variable& query, const fl::Variable& key, const fl::Variable& value, const fl::Variable& keyPaddingMask, const int32_t nHead, const double pDropout) { int32_t bsz = query.dims(1); int32_t modelDim = query.dims(0); int32_t headDim = modelDim / nHead; int32_t tgtLen = query.dims(2); int32_t srcLen = key.dims(2); auto q = moddims(query, af::dim4(headDim, nHead, bsz, tgtLen)); auto v = moddims(value, af::dim4(headDim, nHead, bsz, srcLen)); auto k = moddims(key, af::dim4(headDim, nHead, bsz, srcLen)); // Reorder so that the "Sequence" is along the first dimension, // the embedding is along the zeroth dimension q = reorder(q, 0, 3, 1, 2); v = reorder(v, 0, 3, 1, 2); k = reorder(k, 0, 3, 1, 2); auto scores = matmulTN(q, k); if (!keyPaddingMask.isempty()) { scores = scores + tileAs(moddims(log(keyPaddingMask), {1, srcLen, 1, bsz}), scores); } auto attn = dropout(softmax(scores, 1), pDropout); auto result = matmulNT(attn, v); result = moddims(result, af::dim4(tgtLen, modelDim, bsz)); result = reorder(result, 1, 2, 0); return result; } MultiheadAttention::MultiheadAttention( int32_t modelDim, int32_t headDim, int32_t numHeads, float pDropout) : pDropout_(pDropout), numHeads_(numHeads) { wq_ = makeMultiheadedAttentionLinear(modelDim, headDim * numHeads, 3); wk_ = makeMultiheadedAttentionLinear(modelDim, headDim * numHeads, 3); wv_ = makeMultiheadedAttentionLinear(modelDim, headDim * numHeads, 3); wf_ = makeMultiheadedAttentionLinear(headDim * numHeads, modelDim); add(wq_); add(wk_); add(wv_); add(wf_); } std::vector<Variable> MultiheadAttention::forward( const Variable& queries, const Variable& keys, const Variable& values, const Variable& keyPaddingMask) { assert(queries.dims(0) == keys.dims(0)); assert(queries.dims(0) == values.dims(0)); assert(queries.dims(1) == keys.dims(1)); assert(queries.dims(1) == values.dims(1)); assert(values.dims(2) == keys.dims(2)); int32_t modelDim = queries.dims(0); int32_t headDim = modelDim / numHeads_; if (!keyPaddingMask.isempty()) { assert(keyPaddingMask.dims(0) == keys.dims(2)); assert(keyPaddingMask.dims(1) == keys.dims(1)); } auto q = wq_->forward(queries); auto k = wk_->forward(keys); auto v = wv_->forward(values); q = q / std::sqrt(float(headDim)); float dropout = train_ ? pDropout_ : 0.0f; auto result = transformerMultiheadAttention( q, k, v, keyPaddingMask, numHeads_, dropout); result = (*wf_)(result); assert(result.dims() == queries.dims()); std::vector<Variable> results = {result}; return results; }; std::vector<Variable> MultiheadAttention::forward( const std::vector<Variable>& input) { assert(input.size() == 4); return this->forward(input[0], input[1], input[2], input[3]); } std::string MultiheadAttention::prettyString() const { std::ostringstream ss; ss << "MultiheadAttention"; ss << Container::prettyString(); return ss.str(); } TransformerBaseLayer::TransformerBaseLayer( int32_t modelDim, int32_t mlpDim, int32_t nHeads, float pDropout) : self_attn_(std::make_shared<MultiheadAttention>( modelDim, modelDim / nHeads, nHeads, pDropout)), w1_(makeTransformerLinear(modelDim, mlpDim)), w2_(makeTransformerLinear(mlpDim, modelDim)), norm1_(std::make_shared<LayerNorm>( std::vector<int>{0}, 1e-5, true, modelDim)), norm2_(std::make_shared<LayerNorm>( std::vector<int>{0}, 1e-5, true, modelDim)), pDropout_(pDropout) { add(self_attn_); add(w1_); add(w2_); add(norm1_); add(norm2_); }; Variable TransformerBaseLayer::mlp(const Variable& in) { float pDropout = train_ ? pDropout_ : 0.0; return (*w2_)(dropout(relu((*w1_)(in)), pDropout)); } Variable TransformerBaseLayer::withPosEmbed( const Variable& input, const Variable& pos) { if (pos.isempty()) { return input; } return input + pos; } Variable TransformerBaseLayer::selfAttention( const Variable& input, const Variable& pos, const Variable& keyPaddingMask) { auto k = withPosEmbed(input, pos); auto q = withPosEmbed(input, pos); return self_attn_->forward(q, k, input, keyPaddingMask)[0]; } TransformerEncoderLayer::TransformerEncoderLayer( int32_t modelDim, int32_t mlpDim, int32_t nHeads, float pDropout) : TransformerBaseLayer(modelDim, mlpDim, nHeads, pDropout){}; std::vector<Variable> TransformerEncoderLayer::forward( const std::vector<Variable>& input) { auto src = input[0]; auto mask = input[1]; auto pos = input[2]; float pDropout = train_ ? pDropout_ : 0.0f; auto src2 = this->selfAttention(src, pos, mask); src = src + dropout(src2, pDropout); src = (*norm1_)(src); src2 = mlp(src); src = src + dropout(src2, pDropout); src = (*norm2_)(src); return {src, mask, pos}; } std::string TransformerEncoderLayer::prettyString() const { std::ostringstream ss; ss << "TransformerEncoderLayer"; ss << Container::prettyString(); return ss.str(); } TransformerDecoderLayer::TransformerDecoderLayer( int32_t modelDim, int32_t mlpDim, int32_t nHeads, float pDropout) : self_attn_(std::make_shared<MultiheadAttention>( modelDim, modelDim / nHeads, nHeads, pDropout)), encoder_attn_(std::make_shared<MultiheadAttention>( modelDim, modelDim / nHeads, nHeads, pDropout)), w1_(makeTransformerLinear(modelDim, mlpDim)), w2_(makeTransformerLinear(mlpDim, modelDim)), norm1_(std::make_shared<LayerNorm>( std::vector<int>{0}, 1e-5, true, modelDim)), norm2_(std::make_shared<LayerNorm>( std::vector<int>{0}, 1e-5, true, modelDim)), norm3_(std::make_shared<LayerNorm>( std::vector<int>{0}, 1e-5, true, modelDim)), pDropout_(pDropout) { add(self_attn_); add(encoder_attn_); add(w1_); add(w2_); add(norm1_); add(norm2_); add(norm3_); } Variable TransformerDecoderLayer::mlp(const Variable& in) { float pDropout = train_ ? pDropout_ : 0.0; return (*w2_)(dropout(relu((*w1_)(in)), pDropout)); } Variable TransformerDecoderLayer::withPosEmbed( const Variable& input, const Variable& pos) { if (pos.isempty()) { return input; } return input + pos; } Variable TransformerDecoderLayer::selfAttention( const Variable& input, const Variable& pos, const Variable& keyPaddingMask /* = Variable() */) { auto k = withPosEmbed(input, pos); auto q = withPosEmbed(input, pos); return self_attn_->forward(q, k, input, keyPaddingMask)[0]; } std::vector<Variable> TransformerDecoderLayer::forward( const std::vector<Variable>& input) { auto tgt = input[0]; auto memory = input[1]; auto pos = (input.size() > 2) ? input[2] : Variable(); auto queryPos = (input.size() > 3) ? input[3] : Variable(); auto memoryKeyPaddingMask = (input.size() > 4) ? input[4] : Variable(); float pDropout = train_ ? pDropout_ : 0.0f; auto tgt2 = this->selfAttention(tgt, queryPos); tgt = tgt + dropout(tgt2, pDropout); tgt = (*norm1_)(tgt); tgt2 = encoder_attn_->forward({ this->withPosEmbed(tgt, queryPos), // queries this->withPosEmbed(memory, pos), // keys memory, // values memoryKeyPaddingMask // mask })[0]; tgt = tgt + dropout(tgt2, pDropout); tgt = (*norm2_)(tgt); tgt2 = mlp(tgt); tgt = tgt + dropout(tgt2, pDropout); tgt = (*norm3_)(tgt); return {tgt}; } std::string TransformerDecoderLayer::prettyString() const { std::ostringstream ss; ss << "TransformerDecoderLayer"; ss << Container::prettyString(); return ss.str(); } TransformerDecoder::TransformerDecoder( int32_t modelDim, int32_t mlpDim, int32_t nHeads, int32_t layers, float pDropout) { // TODO add norm for (int i = 0; i < layers; i++) { add(TransformerDecoderLayer(modelDim, mlpDim, nHeads, pDropout)); } add(LayerNorm(std::vector<int>{0}, 1e-5, true, modelDim)); } std::vector<Variable> TransformerDecoder::forward( const std::vector<Variable>& input) { auto tgt = input[0]; auto memory = input[1]; auto pos = (input.size() > 2) ? input[2] : Variable(); auto query_pos = (input.size() > 3) ? input[3] : Variable(); auto mask = (input.size() > 4) ? input[4] : Variable(); fl::Variable output = tgt; auto mods = modules(); std::vector<Variable> intermediate; for (int i = 0; i < mods.size() - 1; i++) { output = mods[i]->forward({output, memory, pos, query_pos, mask})[0]; intermediate.push_back(mods.back()->forward({output})[0]); } return {concatenate(intermediate, 3)}; } std::string TransformerDecoder::prettyString() const { std::ostringstream ss; ss << "TransformerDecoder"; ss << Container::prettyString(); return ss.str(); } TransformerEncoder::TransformerEncoder( int32_t modelDim, int32_t mlpDim, int32_t nHeads, int32_t layers, float pDropout) { for (int i = 0; i < layers; i++) { add(TransformerEncoderLayer(modelDim, mlpDim, nHeads, pDropout)); } } std::vector<Variable> TransformerEncoder::forward( const std::vector<Variable>& input) { std::vector<Variable> output = input; auto mods = modules(); for (int i = 0; i < mods.size(); i++) { output = mods[i]->forward(output); } return output; } std::string TransformerEncoder::prettyString() const { std::ostringstream ss; ss << "TransformerDecoder"; ss << Container::prettyString(); return ss.str(); } Transformer::Transformer( int32_t modelDim, int32_t numHeads, int32_t numEncoderLayers, int32_t numDecoderLayers, int32_t mlpDim, float pDropout) : encoder_(std::make_shared<TransformerEncoder>( modelDim, mlpDim, numHeads, numEncoderLayers, pDropout)), decoder_(std::make_shared<TransformerDecoder>( modelDim, mlpDim, numHeads, numDecoderLayers, pDropout)) { add(encoder_); add(decoder_); }; std::vector<Variable> Transformer::forward( Variable src, Variable mask, Variable queryEmbed, Variable posEmbed) { assert(src.dims(2) == queryEmbed.dims(0)); int B = src.dims(3); // Reshape from [ W X H X C X B ] to [ WH X C X B ] src = flatten(src, 0, 1); // Flatten to C x B x WH src = reorder(src, 1, 2, 0); posEmbed = flatten(posEmbed, 0, 1); posEmbed = reorder(posEmbed, 1, 2, 0); mask = flatten(mask, 0, 2); // Tile object queries for each batch af::dim4 unsqueeze = {queryEmbed.dims(0), 1, queryEmbed.dims(1)}; queryEmbed = moddims(queryEmbed, unsqueeze); queryEmbed = tile(queryEmbed, {1, B, 1}); assert(queryEmbed.dims(1) == src.dims(1)); assert(queryEmbed.dims(0) == src.dims(0)); auto tgt = fl::Variable(af::constant(0, queryEmbed.dims()), false); auto memory = encoder_->forward({src, mask, posEmbed}); auto hs = decoder_->forward({tgt, memory[0], posEmbed, queryEmbed, mask})[0]; auto reordered = reorder(hs, 0, 2, 1); return {reordered}; } std::vector<Variable> Transformer::forward(const std::vector<Variable>& input) { assert(input.size() > 3); auto src = input[0]; auto mask = (input.size() > 1) ? input[1] : Variable(); auto query_embed = (input.size() > 2) ? input[2] : Variable(); auto pos_embed = (input.size() > 3) ? input[3] : Variable(); return forward(src, mask, query_embed, pos_embed); } std::string Transformer::prettyString() const { std::ostringstream ss; ss << "Transformer"; ss << Container::prettyString(); return ss.str(); } } // namespace objdet } // namespace app } // namespace fl
28.116279
80
0.646891
28df19f035b53278ef72263eb673ad9cdc3dd03a
9,143
hpp
C++
src/lib/clxx/info/platform_layer_info.hpp
ptomulik/clxx
9edfb0c39e6ab2f2d86afde0ac42c5e3f21e7ac8
[ "MIT" ]
1
2015-08-12T13:11:35.000Z
2015-08-12T13:11:35.000Z
src/lib/clxx/info/platform_layer_info.hpp
ptomulik/clxx
9edfb0c39e6ab2f2d86afde0ac42c5e3f21e7ac8
[ "MIT" ]
67
2015-01-03T10:11:13.000Z
2015-10-21T11:03:06.000Z
src/lib/clxx/info/platform_layer_info.hpp
ptomulik/clxx
9edfb0c39e6ab2f2d86afde0ac42c5e3f21e7ac8
[ "MIT" ]
null
null
null
// @COPYRIGHT@ // Licensed under MIT license (LICENSE.txt) // clxx/info/platform_layer_info.hpp /** // doc: clxx/info/platform_layer_info.hpp {{{ * \file clxx/info/platform_layer_info.hpp * \brief Defines \ref clxx::platform_layer_info "platform_layer_info" class */ // }}} #ifndef CLXX_INFO_PLATFORM_LAYER_INFO_HPP_INCLUDED #define CLXX_INFO_PLATFORM_LAYER_INFO_HPP_INCLUDED #include <clxx/info/platform_info_ptrs.hpp> #include <clxx/info/device_info_ptrs.hpp> #include <boost/bimap/bimap.hpp> #include <boost/bimap/vector_of.hpp> #include <boost/bimap/set_of.hpp> #include <vector> namespace clxx { /** // doc: class platform_layer_info {{{ * \ingroup clxx_info * \brief Platform layer info * * This object gathers together a couple of \ref clxx::platform_info * "platform_infos" and \ref clxx::device_info "device_infos" to represent * a complete information about an OpenCL platform layer (including, for * example, all locally available platforms together with their devices). * * It's possible to preserve the original layout of an OpenCL platform layer, * and browse through either platforms or devices. */ // }}} class platform_layer_info { template <class Archive> friend void _serialize(Archive&, platform_layer_info&, const unsigned int); public: /** // doc: class_version {{{ * \brief Class version number * * This is used by the serialization machinery (see \ref clxx_s11n) */ // }}} static constexpr unsigned int class_version = 0x000001; private: typedef boost::bimaps::vector_of<const_platform_info_ptr> Left_Set; typedef boost::bimaps::set_of<const_device_info_ptr> Right_Set; typedef boost::bimaps::bimap<Left_Set, Right_Set> bimap; public: /** // doc: platform_layer_info() {{{ * \brief Default constructor * * Initializes an empty platform_layer_info object. */ // }}} platform_layer_info(); /** // doc: ~platform_layer_info() {{{ * \brief Destructor */ // }}} virtual ~platform_layer_info(); /** // doc: clear() {{{ * \brief Clears the whole platform layer info * * This deletes all the platform and device infos contained in the object. */ // }}} void clear(); /** // doc: platforms() {{{ * \brief Retrieve all the platform infos * \returns A sequence of pointers to platform_info objects for the platform * layer described by this object */ // }}} platform_info_ptrs get_platforms(); /** // doc: platforms() {{{ * \brief Retrieve all the platform infos (const version) * \returns A sequence of pointers to platform_info objects for the platform * layer described by this object */ // }}} const_platform_info_ptrs get_platforms() const; /** // doc: get_platform() {{{ * \brief Get a platform info for given device * * The \em dev must belong to this platform layer, that is it must be stored * in this #platform_layer_info object. In short, it must be one of the * pointers returned by #get_devices(). * * \param dev A pointer to device info for which the platform has to be returned * \returns A pointer to the platform requested */ // }}} platform_info_ptr get_platform(const_device_info_ptr dev); /** // doc: get_platform() {{{ * \brief Get a platform info for given device (const version) * * The \em dev must belong to this platform layer, that is it must be stored * in this #platform_layer_info object. In short, it must be one of the * pointers returned by #get_devices() const. * * \param dev A pointer to device info for which the platform has to be returned * \returns A pointer to the platform requested */ // }}} const_platform_info_ptr get_platform(const_device_info_ptr dev) const; /** // doc: get_devices() {{{ * \brief Get devices that belong to this platform layer * \return A sequence of pointers to \ref clxx::device_info "device_infos" * that belong to this #platform_layer_info. */ // }}} device_info_ptrs get_devices(); /** // doc: get_devices() {{{ * \brief Get devices that belong to this platform layer * \return A sequence of pointers to \ref clxx::device_info "device_infos" * that belong to this #platform_layer_info. */ // }}} const_device_info_ptrs get_devices() const; /** // doc: get_devices(plat) {{{ * \brief Get devices that belong to a given platform * \param plat Platform info for the platform in question. * \return A sequence of pointers to \ref clxx::device_info "device_infos" * that belong to the platform \em plat. */ // }}} device_info_ptrs get_devices(const_platform_info_ptr plat); /** // doc: get_devices(plat) {{{ * \brief Get devices that belong to a given platform (const version) * \param plat Platform info for the platform in question. * \return A sequence of pointers to \ref clxx::device_info "device_infos" * that belong to the platform \em plat. */ // }}} const_device_info_ptrs get_devices(const_platform_info_ptr plat) const; /** // doc: push_back(dev) {{{// end namespace clxx * \brief Add device (together with its platform) to #platform_layer_info * \param dev Device to be included. * \param plat Platform, to which the device \em dev belongs. */ // }}} void push_back(device_info_ptr dev, platform_info_ptr plat); /** // doc: remove(dev) {{{ * \brief Remove a platform from the #platform_layer_info * * Together with platform, all their devices get removed from * #platform_layer_info. * * \param plat The platform to be removed */ // }}} void remove(const_platform_info_ptr plat); /** // doc: remove(dev) {{{ * \brief Remove a device from the #platform_layer_info * \param dev Device to be removed * * When last device of some platform gets removed, the platform gets * automatically removed from #platform_layer_info automatically. */ // }}} void remove(const_device_info_ptr dev); /** // doc: empty() {{{ * \brief Whether this object is empty * \returns \c true if there is no device nor platform infos in the object */ // }}} bool empty() const; /** // doc: cmp(p) {{{ * \brief Compare this object with an other one * \param other The other object to be compared with this one * * Two \ref clxx::platform_layer_info "platform_layer_infos" are equal if and * only if * * - they're equal in size (have same number of platforms/devices), and * - underlying platform layers they describe have same layout, and * - corresponding platform infos and device infos on both sides are equal. * * \returns \c true if this object equals the other or \c false otherwise */ // }}} bool cmp(platform_layer_info const& other) const; /** // doc: indices() {{{ * \brief Indices that describe mapping of devices to their platforms in * #platform_layer_info container * * The #platform_layer_info object contains a set of * \ref clxx::platform_info "platform_info" objects and a set of * \ref clxx::device_info "device_info" objects. Each device shall be related * to one of the platforms contained in the #platform_layer_info. The * sequence of \ref clxx::platform_info "platform_infos" can be retrieved * with #get_platforms() whereas the sequence of \ref clxx::device_info * "device_infos" may be obtained with #get_devices(). * * The indices returned by #indices() establish the mapping between devices * retrieved with #get_devices() and their platforms as obtained by * #get_platforms(). The notation * * \code * get_platforms()[indices()[i]] * \endcode * * returns a platform info for platform of device <tt>devices()[i]</tt>. * * \returns A vector of integer indices that define the mapping */ // }}} std::vector<int> indices() const; private: bimap _bimap; }; /** \addtogroup clxx_info * @{ */ /** // doc: operator==(l,r) {{{ * \brief Compare two \ref clxx::platform_layer_info "platform_layer_infos" * * See the \ref clxx::platform_layer_info::cmp() for definition of the * \ref clxx::platform_layer_info "platform_layer_info's" equality. * * \param a Left hand side operand to the comparison * \param b Right hand side operand to the comparison * \returns \c true if two infos are same or \c false otherwise */ // }}} inline bool operator==(platform_layer_info const& a, platform_layer_info const& b) { return a.cmp(b); } /** // doc: operator!=(l,r) {{{ * \brief Compare two \ref clxx::platform_layer_info "platform_layer_infos" * * See the \ref clxx::platform_layer_info::cmp() for definition of the * \ref clxx::platform_layer_info "platform_layer_info's" equality. * * \param a Left hand side operand to the comparison * \param b Right hand side operand to the comparison * \returns \c false if two infos are same or \c true otherwise */ // }}} inline bool operator!=(platform_layer_info const& a, platform_layer_info const& b) { return !a.cmp(b); } /** @} */ } // end namespace clxx #endif /* CLXX_INFO_PLATFORM_LAYER_INFO_HPP_INCLUDED */ // vim: set expandtab tabstop=2 shiftwidth=2: // vim: set foldmethod=marker foldcolumn=4:
39.07265
82
0.694849
28df54ef5b9d2ce9d90f25518306dd1d85e428b0
3,337
cpp
C++
modules/core/utils.cpp
yjmm10/ModernOCR
a7070c9801ecccbbc5ad66618ca86c830480c573
[ "MIT" ]
null
null
null
modules/core/utils.cpp
yjmm10/ModernOCR
a7070c9801ecccbbc5ad66618ca86c830480c573
[ "MIT" ]
null
null
null
modules/core/utils.cpp
yjmm10/ModernOCR
a7070c9801ecccbbc5ad66618ca86c830480c573
[ "MIT" ]
null
null
null
/* * @Author: Petrichor * @Date: 2022-03-11 11:40:37 * @LastEditTime: 2022-03-11 17:21:28 * @LastEditors: Petrichor * @Description: * @FilePath: \ModernOCR\modules\core\utils.cpp * 版权声明 */ #include "utils.h" namespace ModernOCR { namespace utils{ }; namespace image{ cv::Mat getRotateCropImage(const cv::Mat &src, std::vector<cv::Point> box) { cv::Mat image; src.copyTo(image); std::vector<cv::Point> points = box; int collectX[4] = {box[0].x, box[1].x, box[2].x, box[3].x}; int collectY[4] = {box[0].y, box[1].y, box[2].y, box[3].y}; int left = int(*std::min_element(collectX, collectX + 4)); int right = int(*std::max_element(collectX, collectX + 4)); int top = int(*std::min_element(collectY, collectY + 4)); int bottom = int(*std::max_element(collectY, collectY + 4)); cv::Mat imgCrop; image(cv::Rect(left, top, right - left, bottom - top)).copyTo(imgCrop); for (int i = 0; i < points.size(); i++) { points[i].x -= left; points[i].y -= top; } int imgCropWidth = int(sqrt(pow(points[0].x - points[1].x, 2) + pow(points[0].y - points[1].y, 2))); int imgCropHeight = int(sqrt(pow(points[0].x - points[3].x, 2) + pow(points[0].y - points[3].y, 2))); cv::Point2f ptsDst[4]; ptsDst[0] = cv::Point2f(0., 0.); ptsDst[1] = cv::Point2f(imgCropWidth, 0.); ptsDst[2] = cv::Point2f(imgCropWidth, imgCropHeight); ptsDst[3] = cv::Point2f(0.f, imgCropHeight); cv::Point2f ptsSrc[4]; ptsSrc[0] = cv::Point2f(points[0].x, points[0].y); ptsSrc[1] = cv::Point2f(points[1].x, points[1].y); ptsSrc[2] = cv::Point2f(points[2].x, points[2].y); ptsSrc[3] = cv::Point2f(points[3].x, points[3].y); cv::Mat M = cv::getPerspectiveTransform(ptsSrc, ptsDst); cv::Mat partImg; cv::warpPerspective(imgCrop, partImg, M, cv::Size(imgCropWidth, imgCropHeight), cv::BORDER_REPLICATE); if (float(partImg.rows) >= float(partImg.cols) * 1.5) { cv::Mat srcCopy = cv::Mat(partImg.rows, partImg.cols, partImg.depth()); cv::transpose(partImg, srcCopy); cv::flip(srcCopy, srcCopy, 0); return srcCopy; } else { return partImg; } } std::vector<cv::Mat> getPartImages(cv::Mat &src, std::vector<types::BoxInfo> &textBoxes) { std::vector<cv::Mat> partImages; for (int i = 0; i < textBoxes.size(); ++i) { cv::Mat partImg = getRotateCropImage(src, textBoxes[i].boxPoint); partImages.emplace_back(partImg); // //OutPut DebugImg if (true) { std::string debugImgFile = getDebugImgFilePath("", "hh", i, "-part-"); saveImg(partImg, debugImgFile.c_str()); } } return partImages; } }; namespace str{ }; };
34.760417
98
0.493857
28e03e1089b67d6a14a30b8a42ad7ab3cf575989
6,845
cpp
C++
src/qt/assettablemodel.cpp
yiya-core/yiya-core
54bdc5c72f6d760cb3ec840f202c289bccd03ccd
[ "MIT" ]
null
null
null
src/qt/assettablemodel.cpp
yiya-core/yiya-core
54bdc5c72f6d760cb3ec840f202c289bccd03ccd
[ "MIT" ]
null
null
null
src/qt/assettablemodel.cpp
yiya-core/yiya-core
54bdc5c72f6d760cb3ec840f202c289bccd03ccd
[ "MIT" ]
null
null
null
// Copyright (c) 2011-2016 The Bitcoin Core developers // Copyright (c) 2019 The Yiya Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "assettablemodel.h" #include "assetrecord.h" #include "guiconstants.h" #include "guiutil.h" #include "walletmodel.h" #include "wallet/wallet.h" #include "core_io.h" #include "amount.h" #include "assets/assets.h" #include "validation.h" #include "platformstyle.h" #include <QDebug> #include <QStringList> class AssetTablePriv { public: AssetTablePriv(AssetTableModel *_parent) : parent(_parent) { } AssetTableModel *parent; QList<AssetRecord> cachedBalances; // loads all current balances into cache void refreshWallet() { qDebug() << "AssetTablePriv::refreshWallet"; cachedBalances.clear(); auto currentActiveAssetCache = GetCurrentAssetCache(); if (currentActiveAssetCache) { { LOCK(cs_main); std::map<std::string, CAmount> balances; std::map<std::string, std::vector<COutput> > outputs; if (!GetAllMyAssetBalances(outputs, balances)) { qWarning("AssetTablePriv::refreshWallet: Error retrieving asset balances"); return; } std::set<std::string> setAssetsToSkip; auto bal = balances.begin(); for (; bal != balances.end(); bal++) { // retrieve units for asset uint8_t units = OWNER_UNITS; bool fIsAdministrator = true; if (setAssetsToSkip.count(bal->first)) continue; if (!IsAssetNameAnOwner(bal->first)) { // Asset is not an administrator asset CNewAsset assetData; if (!currentActiveAssetCache->GetAssetMetaDataIfExists(bal->first, assetData)) { qWarning("AssetTablePriv::refreshWallet: Error retrieving asset data"); return; } units = assetData.units; // If we have the administrator asset, add it to the skip listå if (balances.count(bal->first + OWNER_TAG)) { setAssetsToSkip.insert(bal->first + OWNER_TAG); } else { fIsAdministrator = false; } } else { // Asset is an administrator asset, if we own assets that is administrators, skip this balance std::string name = bal->first; name.pop_back(); if (balances.count(name)) { setAssetsToSkip.insert(bal->first); continue; } } cachedBalances.append(AssetRecord(bal->first, bal->second, units, fIsAdministrator)); } } } } int size() { return cachedBalances.size(); } AssetRecord *index(int idx) { if (idx >= 0 && idx < cachedBalances.size()) { return &cachedBalances[idx]; } return 0; } }; AssetTableModel::AssetTableModel(WalletModel *parent) : QAbstractTableModel(parent), walletModel(parent), priv(new AssetTablePriv(this)) { columns << tr("Name") << tr("Quantity"); priv->refreshWallet(); }; AssetTableModel::~AssetTableModel() { delete priv; }; void AssetTableModel::checkBalanceChanged() { qDebug() << "AssetTableModel::CheckBalanceChanged"; // TODO: optimize by 1) updating cache incrementally; and 2) emitting more specific dataChanged signals Q_EMIT layoutAboutToBeChanged(); priv->refreshWallet(); Q_EMIT dataChanged(index(0, 0, QModelIndex()), index(priv->size(), columns.length()-1, QModelIndex())); Q_EMIT layoutChanged(); } int AssetTableModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return priv->size(); } int AssetTableModel::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent); return columns.length(); } QVariant AssetTableModel::data(const QModelIndex &index, int role) const { Q_UNUSED(role); if(!index.isValid()) return QVariant(); AssetRecord *rec = static_cast<AssetRecord*>(index.internalPointer()); switch (role) { case AmountRole: return (unsigned long long) rec->quantity; case AssetNameRole: return QString::fromStdString(rec->name); case FormattedAmountRole: return QString::fromStdString(rec->formattedQuantity()); case AdministratorRole: { return rec->fIsAdministrator; } case Qt::DecorationRole: { QPixmap pixmap; if (!rec->fIsAdministrator) QVariant(); if (darkModeEnabled) pixmap = QPixmap::fromImage(QImage(":/icons/asset_administrator_dark")); else pixmap = QPixmap::fromImage(QImage(":/icons/asset_administrator")); return pixmap; } case Qt::ToolTipRole: return formatTooltip(rec); default: return QVariant(); } } QVariant AssetTableModel::headerData(int section, Qt::Orientation orientation, int role) const { if (role == Qt::DisplayRole) { if (section < columns.size()) return columns.at(section); } else if (role == Qt::SizeHintRole) { if (section == 0) return QSize(300, 50); else if (section == 1) return QSize(200, 50); } else if (role == Qt::TextAlignmentRole) { return Qt::AlignHCenter + Qt::AlignVCenter; } return QVariant(); } QModelIndex AssetTableModel::index(int row, int column, const QModelIndex &parent) const { Q_UNUSED(parent); AssetRecord *data = priv->index(row); if(data) { QModelIndex idx = createIndex(row, column, priv->index(row)); return idx; } return QModelIndex(); } QString AssetTableModel::formatTooltip(const AssetRecord *rec) const { QString tooltip = formatAssetName(rec) + QString("\n") + formatAssetQuantity(rec); return tooltip; } QString AssetTableModel::formatAssetName(const AssetRecord *wtx) const { return tr("Asset Name: ") + QString::fromStdString(wtx->name); } QString AssetTableModel::formatAssetQuantity(const AssetRecord *wtx) const { return tr("Asset Quantity: ") + QString::fromStdString(wtx->formattedQuantity()); }
30.422222
118
0.577794
28e37f5a3be244df1969dc1a5659a396b97c769d
1,344
hpp
C++
deps/boost/include/boost/geometry/algorithms/detail/normalize.hpp
kindlychung/mediasoup-sfu-cpp
f69d2f48f7edbf4f0c57244280a47bea985f39cf
[ "Apache-2.0" ]
995
2018-06-22T10:39:18.000Z
2022-03-25T01:22:14.000Z
deps/boost/include/boost/geometry/algorithms/detail/normalize.hpp
kindlychung/mediasoup-sfu-cpp
f69d2f48f7edbf4f0c57244280a47bea985f39cf
[ "Apache-2.0" ]
32
2018-06-23T14:19:37.000Z
2022-03-29T10:20:37.000Z
deps/boost/include/boost/geometry/algorithms/detail/normalize.hpp
kindlychung/mediasoup-sfu-cpp
f69d2f48f7edbf4f0c57244280a47bea985f39cf
[ "Apache-2.0" ]
172
2018-06-22T11:12:00.000Z
2022-03-29T07:44:33.000Z
// Boost.Geometry (aka GGL, Generic Geometry Library) // Copyright (c) 2015-2018, Oracle and/or its affiliates. // Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle // Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle // Licensed under the Boost Software License version 1.0. // http://www.boost.org/users/license.html #ifndef BOOST_GEOMETRY_ALGORITHMS_DETAIL_NORMALIZE_HPP #define BOOST_GEOMETRY_ALGORITHMS_DETAIL_NORMALIZE_HPP // For backward compatibility #include <boost/geometry/strategies/normalize.hpp> namespace boost { namespace geometry { #ifndef DOXYGEN_NO_DETAIL namespace detail { template <typename GeometryIn, typename GeometryOut, typename Strategy> inline void normalize(GeometryIn const& geometry_in, GeometryOut& geometry_out, Strategy const& ) { Strategy::apply(geometry_in, geometry_out); } template <typename GeometryOut, typename GeometryIn, typename Strategy> inline GeometryOut return_normalized(GeometryIn const& geometry_in, Strategy const& strategy) { GeometryOut geometry_out; detail::normalize(geometry_in, geometry_out, strategy); return geometry_out; } } // namespace detail #endif // DOXYGEN_NO_DETAIL }} // namespace boost::geometry #endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_NORMALIZE_HPP
27.428571
98
0.766369
28e42f59d897527a305c2e3a439854cb855e8a89
30,158
cpp
C++
other/bb_sudoku/bb_sudoku_solver.cpp
dobrichev/tdoku
cda2e52229656bd03db141e6405d50a2a80e2338
[ "BSD-2-Clause" ]
100
2019-07-01T20:16:33.000Z
2022-03-27T10:36:48.000Z
other/bb_sudoku/bb_sudoku_solver.cpp
doc22940/tdoku
63d190a9090d9dc8e613e48e4770c635a5b7e3c3
[ "BSD-2-Clause" ]
7
2019-12-18T09:07:58.000Z
2022-03-13T19:39:46.000Z
other/bb_sudoku/bb_sudoku_solver.cpp
doc22940/tdoku
63d190a9090d9dc8e613e48e4770c635a5b7e3c3
[ "BSD-2-Clause" ]
14
2019-06-18T05:47:28.000Z
2022-03-05T08:58:05.000Z
/****************************************************************\ ** BB_Sudoku Bit Based Sudoku Solver ** \****************************************************************/ /****************************************************************\ ** (c) Copyright Brian Turner, 2008-2009. This file may be ** ** freely used, modified, and copied for personal, ** ** educational, or non-commercial purposes provided this ** ** notice remains attached. ** \****************************************************************/ #include <cstdio> #include <cstring> #include "random.h" #include "bb_sudoku_tables.h" // moved here from driver program bb_sudoku.cpp bool InitTables() { int i, v; RND_Init(); for (i = 0; i < 512; i++) { B2V[i] = NSet[i] = 0; for (v = i; v; NSet[i]++) { NSetX[i][NSet[i]] = v & -v; v = v ^ NSetX[i][NSet[i]]; } } for (i = 1; i <= 9; i++) B2V[1 << (i-1)] = i; return true; } // G - Grid data structure // This contains everything needed for backtracking. // The larger this gets, the slower backtracking will be // since the entire structure is copied. struct Grid_Type { int CellsLeft; // Cells left to solve unsigned int Grid[81]; // Possibilities left for each cell unsigned int Grp[27]; // Values found in each group } G[64]; // Solution Grid, which will contain the answer after the puzzle is solved unsigned int SolGrid[81]; // Naked Singles FIFO stack - new singles found are stored here before char SingleCnt = 0; char SinglePos[128]; unsigned int SingleVal[128]; #define PushSingle(p, b) { SinglePos[SingleCnt] = p; SingleVal[SingleCnt] = b; SingleCnt++; Changed = 1; } // Changed Flags int Changed; // Flag to indicate Grid has changed char ChangedGroup[27]; // Marks which groups have changed char ChangedLC[27]; int SingleGroup[27]; #define MarkChanged(x) { ChangedGroup[C2Grp[x][0]] = ChangedGroup[C2Grp[x][1]] = ChangedGroup[C2Grp[x][2]] = Changed = 1; } // Guess structure char GuessPos[128]; int GuessVal[128]; int OneStepP[81], OneStepI; // Key global variables used throughout the solving long PuzzleCnt = 0; // Total puzzles tested long SolvedCnt = 0; // Total puzzles solved int PuzSolCnt; // Solutions for a single puzzle int No_Sol; // Flag to indicate there is no solution possible int PIdx; // Position Index, used for guessing and backtracking // Debug stats int SCnt = 0, HCnt = 0, GCnt = 0, LCCnt = 0, SSCnt = 0, FCnt = 0, OneCnt = 0, TwoCnt = 0; long TSCnt = 0, THCnt = 0, TGCnt = 0, TLCCnt = 0, TSSCnt = 0, TFCnt = 0, TOneCnt = 0, TTwoCnt = 0; int MaxDepth = 0, Givens = 0; // forward procedure declarations int DecodePuzzleString (int ret_puz, char* buffer); inline void InitGrid (); inline void ProcessInitSingles (void); inline void ProcessSingles (void); inline void FindHiddenSingles (void); inline void FindLockedCandidates (void); inline void FindSubsets (void); inline void FindFishies (void); void DoStep (int doing_2_step, int use_methods); inline void MakeGuess (void); /************\ ** Solver *****************************************************\ ** ** ** Solver runs the sudoku solver. Input puzzle is in the ** ** buffer array, and somewhat controlled by a number of ** ** globals (see the globals at the top of the main program ** ** for globals and meanings). ** ** ** \****************************************************************/ int Solver (char num_search, unsigned int use_methods, char ret_puzzle, int initp, char* buffer) { int i, PuzSolCnt = 0; if (!initp) use_methods |= DecodePuzzleString(ret_puzzle, buffer); // Load the Grid from the buffer // Loop through the puzzle solving routines until finished while (Changed) { // If No Solution possible, jump straight to the backtrack routine if (!No_Sol) { // Check if any Singles to be propogated if (SingleCnt) { SCnt++; if (SingleCnt > 2) // If multiple singles ProcessInitSingles(); // process them all at once if (SingleCnt) // otherwise ProcessSingles(); // process them one at a time if (!G[PIdx].CellsLeft) { if (!No_Sol) { if (!PuzSolCnt && ret_puzzle) for (i = 0; i < 81; i++) buffer[i] = '0' + B2V[SolGrid[i]]; if (PuzSolCnt && (ret_puzzle == 2)) for (i = 0; i < 81; i++) if (buffer[i] != ('0' + B2V[SolGrid[i]])) buffer[i] = '.'; PuzSolCnt++; if ((PuzSolCnt > 1) && (num_search == 2)) break; if (num_search == 1) break; } No_Sol = Changed = 1; continue; } } // If nothing has changed, apply the next solver if (Changed) { HCnt++; FindHiddenSingles(); if (SingleCnt) continue; if (use_methods & USE_LOCK_CAND) { LCCnt++; FindLockedCandidates(); if (Changed) continue; } if (use_methods & USE_SUBSETS) { SSCnt++; FindSubsets(); if (Changed) continue; } if (use_methods & USE_FISHIES) { FCnt++; FindFishies(); if (Changed) continue; } if (use_methods & USE_1_STEP) { OneCnt++; DoStep(0, use_methods); if (Changed) continue; } if (use_methods & USE_2_STEP) { TwoCnt++; DoStep(1, use_methods); if (Changed) continue; } } } //If nothing new found, just make a guess if (use_methods & USE_GUESSES) { GCnt++; MakeGuess(); } if (No_Sol) break; if (!initp && (MaxDepth < PIdx)) MaxDepth = PIdx; if (PIdx > 62) { printf ("Max Depth exceeded, recompile for more depth.\n\n"); exit(0); } } if (No_Sol && !initp && (ret_puzzle == 2) && !(use_methods & USE_GUESSES)) for (i = 0; i < 81; i++) buffer[i] = (G[0].Grid[i]) ? '.' : '0' + B2V[SolGrid[i]]; TSCnt += SCnt; // Update Stats THCnt += HCnt; TGCnt += GCnt; TLCCnt += LCCnt; TSSCnt += SSCnt; TFCnt += FCnt; TOneCnt += OneCnt; TTwoCnt += TwoCnt; return PuzSolCnt; } /************************\ ** DecodePuzzleString *****************************************\ ** ** ** DecodePuzzleString sets up the initial grid (along with ** ** InitGrid), and determine what variations are being used. ** ** ** \****************************************************************/ int DecodePuzzleString (int ret_puz, char* buffer) { int p=0, i=0, KillIdx = 0, CompIdx = 0, g, ret_methods = 0, cpos = 0; char b[500]; InitGrid(); p = 0; i = 2; b[0] = 'g'; b[1] = '='; while (buffer[p] > 0) // remove spaces and commas { if (buffer[p] == '#') { cpos = p; break; } if ((buffer[p] != ' ') && (buffer[p] != 9)) { b[i] = buffer[p]; i++;} p++; } if (ret_puz) { if (cpos) memmove(&buffer[81], &buffer[p], strlen(buffer)-p+1); else buffer[81] = 0; // end the buffer } b[i] = b[i+1] = b[i+2] = 0; p = 0; if (b[3] == '=') p = 2; while (b[p] > 0) { if (b[p+1] == '=') switch (b[p]) { case 'p' : // Puzzle size (needs to be defined first in used) case 'P' : printf ("Size variation are not supported in this version\n"); exit (0); break; case 'c' : // Comparison puzzle (Greater Than / Less Than) case 'C' : //p = Decode_GT_LT(p, b); //if (GT_LT[0][0] != GT_LT[0][1]) ret_methods |= GT_LT_PUZZLE; //break; case 'k' : // Killer Sudoku (Additive or Multiplicitive, and disjoint) case 'K' : //break; case 'j' : // Jigsaw Sudoku (plus additional groupings and disjoint) case 'J' : //break; case 'e' : // Even / Odd Sudoku case 'E' : //break; case 's' : // Subset puzzles case 'S' : //break; case 'a' : // Additional constraints (diagonals, etc) case 'A' : printf ("Variations are not supported in this version\n"); exit (0); break; case 'g' : // Givens (default puzzle) case 'G' : default : p += 2; g = i = 0; while (g < 81) { if ((b[i+p] == ':') || (b[i+p] == ';') || (b[i+p] == '#') || (b[i+p] == 0)) break; if ((b[i+p] == '/') || (b[i+p] == '\\')) g = g + 9 - (g % 9) - 1; if ((b[i+p] > '0') && (b[i+p] <= '9')) PushSingle((char)(g), V2B[b[i+p] - '0']); i++; g++; } Givens += SingleCnt; break; } p += i; } buffer[81] = 10; buffer[82] = 0; // end the buffer return ret_methods; } /**************\ ** InitGrid ***************************************************\ ** ** ** InitGrid takes the text string stored in the buffer and ** ** populates the solution grid. It assumes the text is ** ** properly formatted. ** ** ** \****************************************************************/ inline void InitGrid (void) { char i; // Initialize some key variables G[0].CellsLeft = 81; PIdx = 0; SingleCnt = 0; Changed = 1; No_Sol = 0; OneStepI = 0; Givens = 0; SCnt = HCnt = GCnt = LCCnt = SSCnt = FCnt = OneCnt = TwoCnt = 0; // Loop through the buffer and set the singles to be set for (i = 0; i < 81; i++) { G[0].Grid[i] = 0x1FF; SolGrid[i] = OneStepP[i] = 0; } // Clear the Groups Found values for (i = 0; i < 27; i++) G[0].Grp[i] = ChangedGroup[i] = ChangedLC[i] = SingleGroup[i] = 0; } /************************\ ** ProcessInitSingles *****************************************\ ** ** ** ProcessInitSingles takes a naked single and marks each ** ** cell in the 3 associated groups as not allowing that ** ** number. It also marks the groups as changed so we know ** ** to check for hidden singles in that group. ** ** ** ** This routines marks all the groups first, then marks the ** ** cells for each changed groups. ** ** ** \****************************************************************/ inline void ProcessInitSingles (void) { int i, t, g, t2, j; unsigned int b; while (SingleCnt > 2) { for (i = 0; i < SingleCnt; i++) { t = SinglePos[i]; // Get local copy of position b = SingleVal[i]; // Get local copy of the value if (G[PIdx].Grid[t] == 0) continue; // Check if we already processed this position if (!(G[PIdx].Grid[t] & b)) // Check for error conditions { No_Sol = 1; SingleCnt = Changed = 0; return; } SolGrid[SinglePos[i]] = SingleVal[i]; // Store the single in the solution grid G[PIdx].CellsLeft--; // mark one less empty space G[PIdx].Grid[t] = 0; // mark this position processed for (g = 0; g < 3; g++) // loop through all 3 groups { if (G[PIdx].Grp[C2Grp[t][g]] & b) { No_Sol = 1; SingleCnt = Changed = 0; return; } G[PIdx].Grp[C2Grp[t][g]] |= b; // mark the value as found in the group SingleGroup[C2Grp[t][g]] = 1; } } SingleCnt = 0; for (i = 0; i < 27; i++) if (SingleGroup[i]) { SingleGroup[i] = 0; for (j = 0; j < 9; j++) { t2 = Group[i][j]; // get temp copy of position b = G[PIdx].Grp[i]; if (G[PIdx].Grid[t2] & b) // check if removing a possibility { G[PIdx].Grid[t2] = G[PIdx].Grid[t2] & ~b; // remove possibility if (G[PIdx].Grid[t2] == 0) // check for error (no possibility) { No_Sol = 1; SingleCnt = 0; Changed = 0; return; } if (B2V[G[PIdx].Grid[t2]]) // Check if a naked single is found PushSingle(t2, G[PIdx].Grid[t2]); MarkChanged(t2); // Mark groups as changed } } } } } /********************\ ** ProcessSingles *********************************************\ ** ** ** ProcessSingles takes a naked single and marks each cell ** ** in the 3 associated groups as not allowing that number. ** ** It also marks the groups as changed so we know to check ** ** for hidden singles in that group. ** ** ** ** This routines marks cells changed as each single is ** ** processed. ** ** ** \****************************************************************/ inline void ProcessSingles (void) { int i, t, g, t2; unsigned int b; for (i = 0; i < SingleCnt; i++) { t = SinglePos[i]; // Get local copy of position b = SingleVal[i]; // Get local copy of the value if (G[PIdx].Grid[t] == 0) continue; // Check if we already processed this position if (!(G[PIdx].Grid[t] & b)) // Check for error conditions { No_Sol = 1; SingleCnt = Changed = 0; return; } SolGrid[SinglePos[i]] = SingleVal[i]; // Store the single in the solution grid G[PIdx].CellsLeft--; // mark one less empty space G[PIdx].Grid[t] = 0; // mark this position processed for (g = 0; g < 3; g++) // loop through all 3 groups G[PIdx].Grp[C2Grp[t][g]] |= b; // mark the value as found in the group for (g = 0; g < 20; g++) // loop through each cell in the groups { t2 = (int)In_Groups[t][g]; // get temp copy of position if (G[PIdx].Grid[t2] & b) // check if removing a possibility { G[PIdx].Grid[t2] = G[PIdx].Grid[t2] ^ b; // remove possibility if (G[PIdx].Grid[t2] == 0) // check for error (no possibility) { No_Sol = 1; SingleCnt = 0; Changed = 0; return; } if (B2V[G[PIdx].Grid[t2]]) // Check if a naked single is found PushSingle(t2, G[PIdx].Grid[t2]); MarkChanged(t2); // Mark groups as changed } } } SingleCnt = 0; // Clear the single count } /***********************\ ** FindHiddenSingles ******************************************\ ** ** ** FindHiddenSingles checks each grouping that has changed ** ** to see if they contain any hidden singles. If one is ** ** found, the routine adds it to the queue and exits. ** ** ** \****************************************************************/ inline void FindHiddenSingles (void) { unsigned int t1, t2, t3, b, t; int i, j; for (i = 0; i < 27; i++) if (ChangedGroup[i]) { ChangedLC[i] = 1; t1 = t2 = t3 = 0; for (j = 0; j < 9; j++) { b = G[PIdx].Grid[Group[i][j]]; t2 = t2 | (t1 & b); t1 = t1 | b; } if ((t1 | G[PIdx].Grp[i]) != 0x01FF) { No_Sol = 1; SingleCnt = 0; Changed = 0; return; } t3 = t2 ^ t1; if (t3) { for (j = 0; j < 9; j++) if (t3 & G[PIdx].Grid[Group[i][j]]) { t = t3 & G[PIdx].Grid[Group[i][j]]; if (!B2V[t]) { No_Sol = 1; SingleCnt = 0; Changed = 0; return; } PushSingle((char)Group[i][j], t); if (t3 == t) return; t3 = t3 ^ t; } } ChangedGroup[i] = 0; } Changed = 0; } /**************************\ ** FindLockedCandidates ***************************************\ ** ** ** FindLockedCandidates will scan through the grid to find ** ** any locked candidates. ** ** ** \****************************************************************/ inline void FindLockedCandidates (void) { unsigned int Seg[9], b; int i, j, k, x; int s, s1, s2, gp; for (i = 0; i < 18; i += 3) if (ChangedLC[i] || ChangedLC[i+1] || ChangedLC[i+2]) { ChangedLC[i] = ChangedLC[i+1] = ChangedLC[i+2] = 0; Seg[0] = G[PIdx].Grid[Group[i ][0]] | G[PIdx].Grid[Group[i ][1]] | G[PIdx].Grid[Group[i ][2]]; Seg[1] = G[PIdx].Grid[Group[i ][3]] | G[PIdx].Grid[Group[i ][4]] | G[PIdx].Grid[Group[i ][5]]; Seg[2] = G[PIdx].Grid[Group[i ][6]] | G[PIdx].Grid[Group[i ][7]] | G[PIdx].Grid[Group[i ][8]]; Seg[3] = G[PIdx].Grid[Group[i+1][0]] | G[PIdx].Grid[Group[i+1][1]] | G[PIdx].Grid[Group[i+1][2]]; Seg[4] = G[PIdx].Grid[Group[i+1][3]] | G[PIdx].Grid[Group[i+1][4]] | G[PIdx].Grid[Group[i+1][5]]; Seg[5] = G[PIdx].Grid[Group[i+1][6]] | G[PIdx].Grid[Group[i+1][7]] | G[PIdx].Grid[Group[i+1][8]]; Seg[6] = G[PIdx].Grid[Group[i+2][0]] | G[PIdx].Grid[Group[i+2][1]] | G[PIdx].Grid[Group[i+2][2]]; Seg[7] = G[PIdx].Grid[Group[i+2][3]] | G[PIdx].Grid[Group[i+2][4]] | G[PIdx].Grid[Group[i+2][5]]; Seg[8] = G[PIdx].Grid[Group[i+2][6]] | G[PIdx].Grid[Group[i+2][7]] | G[PIdx].Grid[Group[i+2][8]]; for (j = 0; j < 9; j++) { b = Seg[j] & ((Seg[LC_Segment[j][0]] | Seg[LC_Segment[j][1]]) ^ (Seg[LC_Segment[j][2]] | Seg[LC_Segment[j][3]])); if (b) { for (k = 0; k < 4; k++) { s = LC_Segment[j][k]; s1 = i+s/3; s2 = (s%3)*3; for (x = 0; x < 3; x++) { gp = Group[s1][s2+x]; if (G[PIdx].Grid[gp] & b) { G[PIdx].Grid[gp] = G[PIdx].Grid[gp] & ~b; MarkChanged(gp); if (!(G[PIdx].Grid[gp])) { No_Sol = 1; SingleCnt = 0; Changed = 0; return; } if (B2V[G[PIdx].Grid[gp]]) PushSingle(gp, G[PIdx].Grid[gp]); } } } return; } } } } /*****************\ ** FindSubsets ************************************************\ ** ** ** FindSubsets will find all disjoint subsets (Naked/Hidden ** ** Pairs/Triples/Quads). While this reduces the solving ** ** time on some puzzles, and reduces the numbers of guesses ** ** by around 18%, the overhead increases solving time for ** ** general puzzles by 100% (doubling the time). ** ** ** \****************************************************************/ inline void FindSubsets (void) { int i, g, p, m, t[8], v[8]; for (g = 0; g < 27; g++) { if (Changed) break; m = 7 - NSet[G[PIdx].Grp[g]]; if (m < 2) continue; p = 1; t[1] = -1; while(p > 0) { t[p]++; if (t[p] == 9) { p--; continue; } if (p == 1) { v[1] = G[PIdx].Grid[Group[g][t[p]]]; if ((!v[1]) || (NSet[v[1]] > m)) continue; p++; t[2] = t[1]; continue; } if (!G[PIdx].Grid[Group[g][t[p]]]) continue; v[p] = v[p-1] | G[PIdx].Grid[Group[g][t[p]]]; if (NSet[v[p]] > m) continue; if (NSet[v[p]] == p) { for (i = 0; i < 9; i++) if ((G[PIdx].Grid[Group[g][i]] & ~v[p]) && (G[PIdx].Grid[Group[g][i]] & v[p])) { G[PIdx].Grid[Group[g][i]] &= ~v[p]; if (B2V[G[PIdx].Grid[Group[g][i]]]) PushSingle(Group[g][i], G[PIdx].Grid[Group[g][i]]); MarkChanged(Group[g][i]); } p = 1; continue; } if (p < m) { p++; t[p] = t[p-1]; } } } } /*****************\ ** FindFishies ************************************************\ ** ** ** FindFishies finds the row / column subsets, such as ** ** X-Wing, Swordfish, and Jellyfish. ** ** ** \****************************************************************/ inline void FindFishies (void) { int b, i, g, p, m, t[10], v[10], grid[10], x, y; for (b = 1; b <= 9; b++) { if (Changed) break; for (g = 0; g < 9; g++) grid[g] = 0; for (g = 0; g < 9; g ++) for (i = 0; i < 9; i++) if (G[PIdx].Grid[(g*9)+i] & V2B[b]) grid[g] |= V2B[i+1]; for (g = m = 0; g < 9; g++) if (grid[g]) m++; if (m < 2) continue; m--; p = 1; t[1] = -1; t[0] = 0; while(p > 0) { t[p]++; if (t[p] == 9) { p--; continue; } if (p == 1) { v[1] = grid[t[p]]; if ((!v[1]) || (NSet[v[1]] > m)) continue; p++; t[2] = t[1]; continue; } if (!grid[t[p]]) continue; v[p] = v[p-1] | grid[t[p]]; if (NSet[v[p]] > m) continue; if (NSet[v[p]] == p) { for (i = 0; i < 9; i++) if (grid[i] & ~v[p]) { x = grid[i] & v[p]; while (x) { y = (i*9) + B2V[x & -x] - 1; if (G[PIdx].Grid[y] & V2B[b]) { G[PIdx].Grid[y] ^= V2B[b]; if (B2V[G[PIdx].Grid[y]]) PushSingle(y, G[PIdx].Grid[y]); MarkChanged(y); } x ^= (x & -x); } } p = 1; continue; } if (p < m) { p++; t[p] = t[p-1]; } } } } /************\ ** DoStep *****************************************************\ ** ** ** FindFishies finds the row / column subsets, such as ** ** X-Wing, Swordfish, and Jellyfish. ** ** ** \****************************************************************/ void DoStep (int doing_2_step, int use_methods) { static int LastPos = 0; int i, j, x1, x2, x3, mt, testcell, tested[81], testpidx, new_method; for (i = 0; i < 81; i++) tested[i] = 0; testpidx = PIdx; while (!Changed) { // Find next spot to check testcell = mt = x3 = 99; for (i = 0; i < 81; i++) if ((NSet[G[PIdx].Grid[i]] <= mt) && (NSet[G[PIdx].Grid[i]] > 1) && !tested[i]) { x1 = NSet[G[PIdx].Grp[C2Grp[i][0]]] + NSet[G[PIdx].Grp[C2Grp[i][1]]] + NSet[G[PIdx].Grp[C2Grp[i][2]]]; if ((NSet[G[PIdx].Grid[i]] < mt) || ((NSet[G[PIdx].Grid[i]] == mt) && (x1 <= x2) && (OneStepP[i] <= x3))) { x2 = x1; testcell = i; mt = NSet[G[PIdx].Grid[i]]; x3 = OneStepP[i]; } } if (testcell == 99) return; tested[testcell] = 1; OneStepI++; OneStepP[testcell] = OneStepI; for (j = 0; j < NSet[G[PIdx].Grid[testcell]]; j++) { G[PIdx+1+j] = G[PIdx]; PushSingle(testcell, NSetX[G[PIdx].Grid[testcell]][j]); PIdx = testpidx + 1 + j; if ((use_methods & USE_2_STEP) && doing_2_step) new_method = (use_methods | USE_1_STEP) & ~(USE_GUESSES | USE_2_STEP); else new_method = use_methods & ~(USE_GUESSES | USE_1_STEP | USE_2_STEP); Solver(1, new_method, 0, PIdx, NULL); PIdx = testpidx; if (No_Sol) for (i = 0; i < 81; i++) G[PIdx+1+j].Grid[i] = 0; else for (i = 0; i < 81; i++) if (!G[PIdx+1+j].Grid[i]) G[PIdx+1+j].Grid[i] = SolGrid[i]; No_Sol = 0; SingleCnt = 0; } for (j = 1; j < NSet[G[PIdx].Grid[testcell]]; j++) for (i = 0; i < 81; i++) G[PIdx+1].Grid[i] |= G[PIdx+1+j].Grid[i]; for (i = 0; i < 27; i++) ChangedGroup[i] = 0; Changed = 0; for (i = 0; i < 81; i++) if (G[PIdx].Grid[i] && (G[PIdx].Grid[i] != G[PIdx+1].Grid[i])) { G[PIdx].Grid[i] = G[PIdx+1].Grid[i]; if (B2V[G[PIdx].Grid[i]]) PushSingle(i, G[PIdx].Grid[i]); MarkChanged(i); } } } /***************\ ** MakeGuess **************************************************\ ** ** ** MakeGuess handles the guessing and backtracking used ** ** when solving puzzles. ** ** ** \****************************************************************/ inline void MakeGuess (void) { static int LastPos = 0; int i; int x1, x2; unsigned int v; int Found = 0; char mt; Changed = 1; SingleCnt = 0; // Check to see where the next guess should be if (No_Sol) while (No_Sol) { if (PIdx == 0) return; G[PIdx-1].Grid[GuessPos[PIdx]] ^= GuessVal[PIdx]; if (G[PIdx-1].Grid[GuessPos[PIdx]]) { if (B2V[G[PIdx-1].Grid[GuessPos[PIdx]]]) PushSingle(GuessPos[PIdx], G[PIdx-1].Grid[GuessPos[PIdx]]); No_Sol = 0; MarkChanged(GuessPos[PIdx]); PIdx--; return; } } // Populate the grid for the next guess G[PIdx+1] = G[PIdx]; PIdx++; // Find next spot to check if (!Found) { mt = 99; i = LastPos; do { if ((NSet[G[PIdx].Grid[i]] < mt) && (NSet[G[PIdx].Grid[i]] > 1)) { GuessPos[PIdx] = i; mt = NSet[G[PIdx].Grid[i]]; if (mt == 2) break; // if 2, then its the best it can get } if (++i >= 81) i = 0; } while (i != LastPos); LastPos = i; } // Mark the next guess in the position No_Sol = 1; v = G[PIdx].Grid[GuessPos[PIdx]]; if (v) { v = v & -v; GuessVal[PIdx] = v; PushSingle(GuessPos[PIdx], v); Changed = 1; No_Sol = 0; } } /****************\ ** RatePuzzle *************************************************\ ** ** ** RatePuzzle converts the status counts into a rating for a ** ** given puzzle. This should be called after the solver has ** ** been called. ** ** ** ** ok, I never got a formula I liked. So, if someone wants ** ** to play around with this and suggest something, please ** ** go ahead. ** ** ** ** One of the problems is that the soling routines are so ** ** generic. I treat X-Wings and Jellyfishes the sames way, ** ** same for naked pairs and hidden quads. Makes coming up ** ** with a rating difficult. ** ** ** \****************************************************************/ int RatePuzzle (void) { // Values available to manipulate into a puzzle are // SCnt, HCnt, GCnt, LCCnt, SSCnt, FCnt, OneCnt, TwoCnt, GCnt return 0; } /***************\ ** CatPuzzle **************************************************\ ** ** ** CatPuzzle returns a difficulty category, rather than a ** ** complete ratings. This is based entirely on the most ** ** difficult solving technique used. ** ** ** ** Categories are: ** ** - Invalid : No Solution, or Multiple Solutions ** ** - Easy : Naked / Hidden Single, Locked Candidate ** ** - Medium : Disjoint Subsets / Fishies ** ** - Hard : 1 Step Commonality ** ** - Expert : 2 Step Commonality ** ** - Insane : so far, none exist ** ** ** \****************************************************************/ int CatPuzzle (char *buf) { if (Solver(2, 0x01, 0, 0, buf) != 1) return 0; // Invalid (No Solution, or mulitples) if (Solver(1, 0x3E, 0, 0, buf) == 0) return 5; // Insane (none exist, that I know of) if (TwoCnt) return 4; // Expert (2 Step Commonality) if (OneCnt) return 3; // Hard (1 Step Commonality) if (FCnt || SCnt) return 2; // Medium (Disjoint Subsets / Fishies) return 1; // Easy (Naked/Hidden Single / Locked Candidate) }
38.320203
124
0.418463
28e45dbdbc5bf09ce27c548339c59ceff1d433bc
1,138
hpp
C++
core/src/jni/jni/Error.hpp
RomanWlm/lib-ledger-core
8c068fccb074c516096abb818a4e20786e02318b
[ "MIT" ]
92
2016-11-13T01:28:34.000Z
2022-03-25T01:11:37.000Z
core/src/jni/jni/Error.hpp
RomanWlm/lib-ledger-core
8c068fccb074c516096abb818a4e20786e02318b
[ "MIT" ]
242
2016-11-28T11:13:09.000Z
2022-03-04T13:02:53.000Z
core/src/jni/jni/Error.hpp
RomanWlm/lib-ledger-core
8c068fccb074c516096abb818a4e20786e02318b
[ "MIT" ]
91
2017-06-20T10:35:28.000Z
2022-03-09T14:15:40.000Z
// AUTOGENERATED FILE - DO NOT MODIFY! // This file generated by Djinni from errors.djinni #ifndef DJINNI_GENERATED_ERROR_HPP_JNI_ #define DJINNI_GENERATED_ERROR_HPP_JNI_ #include "../../api/Error.hpp" #include "djinni_support.hpp" namespace djinni_generated { class Error final { public: using CppType = ::ledger::core::api::Error; using JniType = jobject; using Boxed = Error; ~Error(); static CppType toCpp(JNIEnv* jniEnv, JniType j); static ::djinni::LocalRef<JniType> fromCpp(JNIEnv* jniEnv, const CppType& c); private: Error(); friend ::djinni::JniClass<Error>; const ::djinni::GlobalRef<jclass> clazz { ::djinni::jniFindClass("co/ledger/core/Error") }; const jmethodID jconstructor { ::djinni::jniGetMethodID(clazz.get(), "<init>", "(Lco/ledger/core/ErrorCode;Ljava/lang/String;)V") }; const jfieldID field_code { ::djinni::jniGetFieldID(clazz.get(), "code", "Lco/ledger/core/ErrorCode;") }; const jfieldID field_message { ::djinni::jniGetFieldID(clazz.get(), "message", "Ljava/lang/String;") }; }; } // namespace djinni_generated #endif //DJINNI_GENERATED_ERROR_HPP_JNI_
31.611111
136
0.710018
28e4a5dff6a2acf6e2e0efcd8f539a46a56c41dd
21,403
hpp
C++
include/slib/core/rc.hpp
syntheticgio/fda-hive
5e645c6a5b76b5a437635631819a1c934c7fd7fc
[ "Unlicense", "MIT" ]
null
null
null
include/slib/core/rc.hpp
syntheticgio/fda-hive
5e645c6a5b76b5a437635631819a1c934c7fd7fc
[ "Unlicense", "MIT" ]
null
null
null
include/slib/core/rc.hpp
syntheticgio/fda-hive
5e645c6a5b76b5a437635631819a1c934c7fd7fc
[ "Unlicense", "MIT" ]
null
null
null
/* * ::718604! * * Copyright(C) November 20, 2014 U.S. Food and Drug Administration * Authors: Dr. Vahan Simonyan (1), Dr. Raja Mazumder (2), et al * Affiliation: Food and Drug Administration (1), George Washington University (2) * * All rights Reserved. * * The MIT License (MIT) * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #pragma once #ifndef sLib_core_rc_hpp #define sLib_core_rc_hpp #define __STDC_LIMIT_MACROS #include <stdint.h> #include <slib/core/def.hpp> // macros allowing us to define enum names and corresponding description strings in one place #define SLIB_RC_OPERATION_ENTRIES \ SLIB_RC_ENTRY_WITH_VAL(eOperationNone, 0, 0), \ SLIB_RC_ENTRY(eAccessing, "accessing"), \ SLIB_RC_ENTRY(eAllocating, "allocating"), \ SLIB_RC_ENTRY(eAppending, "appending"), \ SLIB_RC_ENTRY(eArithmetic, "performing arithmetic"), \ SLIB_RC_ENTRY(eAttaching, "attaching"), \ SLIB_RC_ENTRY(eAuthenticating, "authenticating"), \ SLIB_RC_ENTRY(eAuthorizing, "authorizing"), \ SLIB_RC_ENTRY(eBackingUp, "backing up"), \ SLIB_RC_ENTRY(eBalancing, "balancing"), \ SLIB_RC_ENTRY(eCaching, "caching"), \ SLIB_RC_ENTRY(eCalling, "calling"), \ SLIB_RC_ENTRY(eChecking, "checking"), \ SLIB_RC_ENTRY(eCasting, "type-casting"), \ SLIB_RC_ENTRY(eClassifying, "classifying"), \ SLIB_RC_ENTRY(eCleaningUp, "cleaning up"), \ SLIB_RC_ENTRY(eClearing, "clearing"), \ SLIB_RC_ENTRY(eClosing, "closing"), \ SLIB_RC_ENTRY(eCommitting, "committing"), \ SLIB_RC_ENTRY(eComparing, "comparing"), \ SLIB_RC_ENTRY(eCompiling, "compiling"), \ SLIB_RC_ENTRY(eCompressing, "compressing"), \ SLIB_RC_ENTRY(eConcatenating, "concatenating"), \ SLIB_RC_ENTRY(eConnecting, "connecting"), \ SLIB_RC_ENTRY(eConstructing, "constructing"), \ SLIB_RC_ENTRY(eConverting, "converting"), \ SLIB_RC_ENTRY(eCopying, "copying"), \ SLIB_RC_ENTRY(eCreating, "creating"), \ SLIB_RC_ENTRY(eCutting, "cutting"), \ SLIB_RC_ENTRY(eDeallocating, "deallocating"), \ SLIB_RC_ENTRY(eDecrypting, "decrypting"), \ SLIB_RC_ENTRY(eDeleting, "deleting"), \ SLIB_RC_ENTRY(eDestroying, "destroying"), \ SLIB_RC_ENTRY(eDetaching, "detaching"), \ SLIB_RC_ENTRY(eDisconnecting, "disconnecting"), \ SLIB_RC_ENTRY(eEncrypting, "encrypting"), \ SLIB_RC_ENTRY(eEscaping, "escaping"), \ SLIB_RC_ENTRY(eEvaluating, "evaluating"), \ SLIB_RC_ENTRY(eExecuting, "executing"), \ SLIB_RC_ENTRY(eExpanding, "expanding"), \ SLIB_RC_ENTRY(eFinding, "finding"), \ SLIB_RC_ENTRY(eFlushing, "flushing"), \ SLIB_RC_ENTRY(eFormatting, "formatting"), \ SLIB_RC_ENTRY(eGrabbing, "grabbing"), \ SLIB_RC_ENTRY(eHashing, "hashing"), \ SLIB_RC_ENTRY(eIdentifying, "identifying"), \ SLIB_RC_ENTRY(eIndexing, "indexing"), \ SLIB_RC_ENTRY(eInitializing, "initializing"), \ SLIB_RC_ENTRY(eInserting, "inserting"), \ SLIB_RC_ENTRY(eInverting, "inverting"), \ SLIB_RC_ENTRY(eJoining, "joining"), \ SLIB_RC_ENTRY(eLaunching, "launching"), \ SLIB_RC_ENTRY(eLinking, "linking"), \ SLIB_RC_ENTRY(eLoading, "loading"), \ SLIB_RC_ENTRY(eLocking, "locking"), \ SLIB_RC_ENTRY(eLogging, "logging"), \ SLIB_RC_ENTRY(eMapping, "mapping"), \ SLIB_RC_ENTRY(eMoving, "moving"), \ SLIB_RC_ENTRY(eOpening, "opening"), \ SLIB_RC_ENTRY(ePacking, "packing"), \ SLIB_RC_ENTRY(eParsing, "parsing"), \ SLIB_RC_ENTRY(ePausing, "pausing"), \ SLIB_RC_ENTRY(ePopping, "popping"), \ SLIB_RC_ENTRY(ePositioning, "positioning"), \ SLIB_RC_ENTRY(ePreparing, "preparing"), \ SLIB_RC_ENTRY(ePrepending, "prepending"), \ SLIB_RC_ENTRY(ePrinting, "printing"), \ SLIB_RC_ENTRY(eProcessing, "processing"), \ SLIB_RC_ENTRY(ePurging, "purging"), \ SLIB_RC_ENTRY(ePushing, "pushing"), \ SLIB_RC_ENTRY(eReading, "reading"), \ SLIB_RC_ENTRY(eReceiving, "receiving"), \ SLIB_RC_ENTRY(eRegistering, "registering"), \ SLIB_RC_ENTRY(eReleasing, "releasing"), \ SLIB_RC_ENTRY(eRenaming, "renaming"), \ SLIB_RC_ENTRY(eRemoving, "removing"), \ SLIB_RC_ENTRY(eResetting, "resetting"), \ SLIB_RC_ENTRY(eResizing, "resizing"), \ SLIB_RC_ENTRY(eResolving, "resolving"), \ SLIB_RC_ENTRY(eRestarting, "restarting"), \ SLIB_RC_ENTRY(eResuming, "resuming"), \ SLIB_RC_ENTRY(eRetrying, "retrying"), \ SLIB_RC_ENTRY(eReversing, "reversing"), \ SLIB_RC_ENTRY(eReverting, "reverting"), \ SLIB_RC_ENTRY(eRunning, "running"), \ SLIB_RC_ENTRY(eSaving, "saving"), \ SLIB_RC_ENTRY(eScanning, "scanning"), \ SLIB_RC_ENTRY(eSearching, "searching"), \ SLIB_RC_ENTRY(eSelecting, "selecting"), \ SLIB_RC_ENTRY(eSending, "sending"), \ SLIB_RC_ENTRY(eSerializing, "serializing"), \ SLIB_RC_ENTRY(eSetting, "setting"), \ SLIB_RC_ENTRY(eShrinking, "shrinking"), \ SLIB_RC_ENTRY(eSignaling, "signaling"), \ SLIB_RC_ENTRY(eSleeping, "sleeping"), \ SLIB_RC_ENTRY(eSorting, "sorting"), \ SLIB_RC_ENTRY(eSplitting, "splitting"), \ SLIB_RC_ENTRY(eStarting, "starting"), \ SLIB_RC_ENTRY(eStopping, "stopping"), \ SLIB_RC_ENTRY(eTerminating, "terminating"), \ SLIB_RC_ENTRY(eTesting, "testing"), \ SLIB_RC_ENTRY(eTokenizing, "tokenizing"), \ SLIB_RC_ENTRY(eUncompressing, "uncompressing"), \ SLIB_RC_ENTRY(eUnescaping, "unescaping"), \ SLIB_RC_ENTRY(eUnlinking, "unlinking"), \ SLIB_RC_ENTRY(eUnlocking, "unlocking"), \ SLIB_RC_ENTRY(eUnpacking, "unpacking"), \ SLIB_RC_ENTRY(eUnregistering, "unregistering"), \ SLIB_RC_ENTRY(eUpdating, "updating"), \ SLIB_RC_ENTRY(eValidating, "validating"), \ SLIB_RC_ENTRY(eVisiting, "visiting"), \ SLIB_RC_ENTRY(eWaiting, "waiting"), \ SLIB_RC_ENTRY(eWriting, "writing"), \ SLIB_RC_ENTRY(eDownload, "downloading"), \ /* Insert new entries after existing ones and before this line */ \ SLIB_RC_ENTRY_WITH_VAL(eOperationOther, 255, "some operation on") #define SLIB_RC_ENTITY_ENTRIES \ SLIB_RC_ENTRY_WITH_VAL(eEntityNone, 0, 0), \ SLIB_RC_ENTRY(eAddress, "address"), \ SLIB_RC_ENTRY(eAlgorithm, "algorithm"), \ SLIB_RC_ENTRY(eAnnotation, "annotation"), \ SLIB_RC_ENTRY(eArchive, "archive"), \ SLIB_RC_ENTRY(eArray, "array"), \ SLIB_RC_ENTRY(eBlob, "blob"), \ SLIB_RC_ENTRY(eBranch, "branch"), \ SLIB_RC_ENTRY(eBuffer, "buffer"), \ SLIB_RC_ENTRY(eByteOrder, "byte order"), \ SLIB_RC_ENTRY(eCallback, "callback"), \ SLIB_RC_ENTRY(eCategory, "category"), \ SLIB_RC_ENTRY(eCell, "cell"), \ SLIB_RC_ENTRY(eChain, "chain"), \ SLIB_RC_ENTRY(eCharacter, "character"), \ SLIB_RC_ENTRY(eChecksum, "checksum"), \ SLIB_RC_ENTRY(eChild, "child"), \ SLIB_RC_ENTRY(eClass, "class"), \ SLIB_RC_ENTRY(eCode, "code"), \ SLIB_RC_ENTRY(eColumn, "column"), \ SLIB_RC_ENTRY(eCommand, "command"), \ SLIB_RC_ENTRY(eCommandLine, "command line"), \ SLIB_RC_ENTRY(eConfig, "configuration"), \ SLIB_RC_ENTRY(eConnection, "connection"), \ SLIB_RC_ENTRY(eConstraint, "constraint"), \ SLIB_RC_ENTRY(eContext, "context"), \ SLIB_RC_ENTRY(eCookie, "cookie"), \ SLIB_RC_ENTRY(eCount, "count"), \ SLIB_RC_ENTRY(eCSV, "CSV data"), \ SLIB_RC_ENTRY(eCursor, "cursor"), \ SLIB_RC_ENTRY(eData, "data"), \ SLIB_RC_ENTRY(eDatabase, "database"), \ SLIB_RC_ENTRY(eDescriptor, "descriptor"), \ SLIB_RC_ENTRY(eDestination, "destination"), \ SLIB_RC_ENTRY(eDictionary, "dictionary"), \ SLIB_RC_ENTRY(eDirectory, "directory"), \ SLIB_RC_ENTRY(eDiskSpace, "disk space"), \ SLIB_RC_ENTRY(eDistance, "distance"), \ SLIB_RC_ENTRY(eDocument, "document"), \ SLIB_RC_ENTRY(eDomain, "domain"), \ SLIB_RC_ENTRY(eElement, "element"), \ SLIB_RC_ENTRY(eEmail, "email"), \ SLIB_RC_ENTRY(eEncryption, "encryption"), \ SLIB_RC_ENTRY(eEnd, "end"), \ SLIB_RC_ENTRY(eEngine, "engine"), \ SLIB_RC_ENTRY(eEnvironment, "environment"), \ SLIB_RC_ENTRY(eExpression, "expression"), \ SLIB_RC_ENTRY(eExtension, "extension"), \ SLIB_RC_ENTRY(eFactory, "factory"), \ SLIB_RC_ENTRY(eFASTA, "FASTA data"), \ SLIB_RC_ENTRY(eField, "field"), \ SLIB_RC_ENTRY(eFile, "file"), \ SLIB_RC_ENTRY(eFileSystem, "filesystem"), \ SLIB_RC_ENTRY(eFlag, "flag"), \ SLIB_RC_ENTRY(eForm, "form"), \ SLIB_RC_ENTRY(eFormat, "format"), \ SLIB_RC_ENTRY(eFormula, "formula"), \ SLIB_RC_ENTRY(eFrame, "frame"), \ SLIB_RC_ENTRY(eFrequency, "frequency"), \ SLIB_RC_ENTRY(eFunction, "function"), \ SLIB_RC_ENTRY(eGroup, "group"), \ SLIB_RC_ENTRY(eHandle, "handle"), \ SLIB_RC_ENTRY(eHash, "hash"), \ SLIB_RC_ENTRY(eHeader, "header"), \ SLIB_RC_ENTRY(eHeap, "heap"), \ SLIB_RC_ENTRY(eHierarchy, "hierarchy"), \ SLIB_RC_ENTRY(eHost, "host"), \ SLIB_RC_ENTRY(eID, "ID"), \ SLIB_RC_ENTRY(eImage, "image"), \ SLIB_RC_ENTRY(eIndex, "index"), \ SLIB_RC_ENTRY(eInput, "input"), \ SLIB_RC_ENTRY(eInterface, "interface"), \ SLIB_RC_ENTRY(eIO, "I/O"), \ SLIB_RC_ENTRY(eIon, "Ion"), \ SLIB_RC_ENTRY(eItem, "item"), \ SLIB_RC_ENTRY(eIterator, "iterator"), \ SLIB_RC_ENTRY(eJob, "job"), \ SLIB_RC_ENTRY(eJSON, "JSON data"), \ SLIB_RC_ENTRY(eKey, "key"), \ SLIB_RC_ENTRY(eLength, "length"), \ SLIB_RC_ENTRY(eLetter, "letter"), \ SLIB_RC_ENTRY(eLevel, "level"), \ SLIB_RC_ENTRY(eLibrary, "library"), \ SLIB_RC_ENTRY(eLimit, "limit"), \ SLIB_RC_ENTRY(eLine, "line"), \ SLIB_RC_ENTRY(eList, "list"), \ SLIB_RC_ENTRY(eLocation, "location"), \ SLIB_RC_ENTRY(eLock, "lock"), \ SLIB_RC_ENTRY(eLog, "log"), \ SLIB_RC_ENTRY(eMap, "map"), \ SLIB_RC_ENTRY(eMatrix, "matrix"), \ SLIB_RC_ENTRY(eMemMap, "memmap"), \ SLIB_RC_ENTRY(eMemory, "memory"), \ SLIB_RC_ENTRY(eMessage, "message"), \ SLIB_RC_ENTRY(eMode, "mode"), \ SLIB_RC_ENTRY(eModule, "module"), \ SLIB_RC_ENTRY(eName, "name"), \ SLIB_RC_ENTRY(eNode, "node"), \ SLIB_RC_ENTRY(eNumber, "number"), \ SLIB_RC_ENTRY(eObject, "object"), \ SLIB_RC_ENTRY(eOffset, "offset"), \ SLIB_RC_ENTRY(eOperation, "operation"), \ SLIB_RC_ENTRY(eOrder, "order"), \ SLIB_RC_ENTRY(eOutput, "output"), \ SLIB_RC_ENTRY(eOwner, "owner"), \ SLIB_RC_ENTRY(eParameter, "parameter"), \ SLIB_RC_ENTRY(eParent, "parent"), \ SLIB_RC_ENTRY(eParser, "parser"), \ SLIB_RC_ENTRY(ePassword, "password"), \ SLIB_RC_ENTRY(ePath, "path"), \ SLIB_RC_ENTRY(ePattern, "pattern"), \ SLIB_RC_ENTRY(ePermission, "permission"), \ SLIB_RC_ENTRY(ePipe, "pipe"), \ SLIB_RC_ENTRY(ePlugin, "plugin"), \ SLIB_RC_ENTRY(ePointer, "pointer"), \ SLIB_RC_ENTRY(ePool, "pool"), \ SLIB_RC_ENTRY(ePosition, "position"), \ SLIB_RC_ENTRY(eProcess, "process"), \ SLIB_RC_ENTRY(eProperty, "property"), \ SLIB_RC_ENTRY(eProtocol, "protocol"), \ SLIB_RC_ENTRY(eQuery, "query"), \ SLIB_RC_ENTRY(eQueue, "queue"), \ SLIB_RC_ENTRY(eRange, "range"), \ SLIB_RC_ENTRY(eReference, "reference"), \ SLIB_RC_ENTRY(eReferenceCount, "reference count"), \ SLIB_RC_ENTRY(eRequest, "request"), \ SLIB_RC_ENTRY(eResource, "resource"), \ SLIB_RC_ENTRY(eResponse, "response"), \ SLIB_RC_ENTRY(eResult, "result"), \ SLIB_RC_ENTRY(eRow, "row"), \ SLIB_RC_ENTRY(eScope, "scope"), \ SLIB_RC_ENTRY(eSeed, "seed"), \ SLIB_RC_ENTRY(eSegment, "segment"), \ SLIB_RC_ENTRY(eSelection, "selection"), \ SLIB_RC_ENTRY(eSeparator, "separator"), \ SLIB_RC_ENTRY(eSequence, "sequence"), \ SLIB_RC_ENTRY(eService, "service"), \ SLIB_RC_ENTRY(eSession, "session"), \ SLIB_RC_ENTRY(eSignal, "signal"), \ SLIB_RC_ENTRY(eSize, "size"), \ SLIB_RC_ENTRY(eSocket, "socket"), \ SLIB_RC_ENTRY(eSource, "source"), \ SLIB_RC_ENTRY(eStack, "stack"), \ SLIB_RC_ENTRY(eStart, "start"), \ SLIB_RC_ENTRY(eString, "string"), \ SLIB_RC_ENTRY(eStructure, "structure"), \ SLIB_RC_ENTRY(eSubject, "subject"), \ SLIB_RC_ENTRY(eSymbol, "symbol"), \ SLIB_RC_ENTRY(eSymLink, "symlink"), \ SLIB_RC_ENTRY(eTable, "table"), \ SLIB_RC_ENTRY(eTarget, "target"), \ SLIB_RC_ENTRY(eTemplate, "template"), \ SLIB_RC_ENTRY(eText, "text"), \ SLIB_RC_ENTRY(eThread, "thread"), \ SLIB_RC_ENTRY(eTimeout, "timeout"), \ SLIB_RC_ENTRY(eTimeStamp, "time stamp"), \ SLIB_RC_ENTRY(eToken, "token"), \ SLIB_RC_ENTRY(eTree, "tree"), \ SLIB_RC_ENTRY(eType, "type"), \ SLIB_RC_ENTRY(eURL, "URL"), \ SLIB_RC_ENTRY(eUser, "user"), \ SLIB_RC_ENTRY(eValue, "value"), \ SLIB_RC_ENTRY(eVariable, "variable"), \ SLIB_RC_ENTRY(eVersion, "version"), \ SLIB_RC_ENTRY(eXML, "XML data"), \ SLIB_RC_ENTRY(eNetwork, "network"), \ SLIB_RC_ENTRY(eCertificate, "certificate"), \ SLIB_RC_ENTRY(eServer, "server"), \ SLIB_RC_ENTRY(eAuthentication, "authentication"), \ /* Insert new entries after existing ones and before this line */ \ SLIB_RC_ENTRY_WITH_VAL(eEntityOther, 255, "something") #define SLIB_RC_STATE_ENTRIES \ SLIB_RC_ENTRY_WITH_VAL(eStateOK, 0, 0), \ SLIB_RC_ENTRY(eAmbiguous, "ambiguous"), \ SLIB_RC_ENTRY(eBlocked, "blocked"), \ SLIB_RC_ENTRY(eBusy, "busy"), \ SLIB_RC_ENTRY(eCanceled, "canceled"), \ SLIB_RC_ENTRY(eChanged, "changed"), \ SLIB_RC_ENTRY(eCircularRef, "has a circular reference"), \ SLIB_RC_ENTRY(eClosed, "closed"), \ SLIB_RC_ENTRY(eCorrupt, "corrupt"), \ SLIB_RC_ENTRY(eDeadlocked, "deadlocked"), \ SLIB_RC_ENTRY(eDestroyed, "destroyed"), \ SLIB_RC_ENTRY(eDetached, "detached"), \ SLIB_RC_ENTRY(eDisabled, "disabled"), \ SLIB_RC_ENTRY(eDown, "down"), \ SLIB_RC_ENTRY(eDuplicate, "duplicate"), \ SLIB_RC_ENTRY(eEnabled, "enabled"), \ SLIB_RC_ENTRY(eEncrypted, "encrypted"), \ SLIB_RC_ENTRY(eEmpty, "empty"), \ SLIB_RC_ENTRY(eEqual, "equal"), \ SLIB_RC_ENTRY(eExcessive, "excessive"), \ SLIB_RC_ENTRY(eExhausted, "exhausted"), \ SLIB_RC_ENTRY(eExists, "already exists"), \ SLIB_RC_ENTRY(eExpired, "expired"), \ SLIB_RC_ENTRY(eFailed, "failed"), \ SLIB_RC_ENTRY(eIgnored, "ignored"), \ SLIB_RC_ENTRY(eIncompatible, "incompatible"), \ SLIB_RC_ENTRY(eIncomplete, "incomplete"), \ SLIB_RC_ENTRY(eInconsistent, "inconsistent"), \ SLIB_RC_ENTRY(eIncorrect, "incorrect"), \ SLIB_RC_ENTRY(eInsecure, "potentially insecure"), \ SLIB_RC_ENTRY(eInsufficient, "insufficient"), \ SLIB_RC_ENTRY(eInterrupted, "interrupted"), \ SLIB_RC_ENTRY(eInvalid, "invalid"), \ SLIB_RC_ENTRY(eKilled, "killed"), \ SLIB_RC_ENTRY(eLocked, "locked"), \ SLIB_RC_ENTRY(eNotAuthenticated, "not authenticated"), \ SLIB_RC_ENTRY(eNotAuthorized, "not authorized"), \ SLIB_RC_ENTRY(eNotEqual, "not equal"), \ SLIB_RC_ENTRY(eNotFinished, "not finished"), \ SLIB_RC_ENTRY(eNotFound, "not found"), \ SLIB_RC_ENTRY(eNotLocked, "not locked"), \ SLIB_RC_ENTRY(eNotMatched, "not matched"), \ SLIB_RC_ENTRY(eNotPermitted, "not permitted"), \ SLIB_RC_ENTRY(eNotSorted, "not sorted"), \ SLIB_RC_ENTRY(eNotSupported, "not supported"), \ SLIB_RC_ENTRY(eNull, "is null"), \ SLIB_RC_ENTRY(eObsolete, "obsolete"), \ SLIB_RC_ENTRY(eOpen, "open"), \ SLIB_RC_ENTRY(eOutOfRange, "out of range"), \ SLIB_RC_ENTRY(ePaused, "paused"), \ SLIB_RC_ENTRY(eProhibited, "prohibited"), \ SLIB_RC_ENTRY(eReadOnly, "read-only"), \ SLIB_RC_ENTRY(eRemoved, "removed"), \ SLIB_RC_ENTRY(eStarted, "started"), \ SLIB_RC_ENTRY(eStopped, "stopped"), \ SLIB_RC_ENTRY(eTerminated, "terminated"), \ SLIB_RC_ENTRY(eTimedOut, "timed out"), \ SLIB_RC_ENTRY(eTooBig, "too big"), \ SLIB_RC_ENTRY(eTooLong, "too long"), \ SLIB_RC_ENTRY(eTooShort, "too short"), \ SLIB_RC_ENTRY(eTooSmall, "too small"), \ SLIB_RC_ENTRY(eUnavailable, "unavailable"), \ SLIB_RC_ENTRY(eUndefined, "undefined"), \ SLIB_RC_ENTRY(eUnexpected, "unexpected"), \ SLIB_RC_ENTRY(eUninitialized, "uninitialized"), \ SLIB_RC_ENTRY(eUnknown, "unknown"), \ SLIB_RC_ENTRY(eUnreachable, "unreachable"), \ SLIB_RC_ENTRY(eUnrecognized, "unrecognized"), \ SLIB_RC_ENTRY(eViolated, "violated"), \ SLIB_RC_ENTRY(eVirtual, "only virtual"), \ SLIB_RC_ENTRY(eWriteOnly, "write-only"), \ SLIB_RC_ENTRY(eWrongFormat, "in wrong format"), \ SLIB_RC_ENTRY(eWrongOrder, "in wrong order"), \ SLIB_RC_ENTRY(eWrongType, "of wrong type"), \ SLIB_RC_ENTRY(eZero, "is zero"), \ /* Insert new entries after existing ones and before this line */ \ SLIB_RC_ENTRY_WITH_VAL(eStateOther, 255, "in some state") #define SLIB_RC_ENTRY(id, description) id #define SLIB_RC_ENTRY_WITH_VAL(id, val, description) id = val namespace slib { class sStr; // forward-declare //! 32-bit status code: operation A on target entity B failed because other entity C has unexpected state D struct sRC { // TODO: use scoped enums when we switch to c++11 : "enum EFoo: unsigned char" //! Operation performed on an entity enum EOperation { SLIB_RC_OPERATION_ENTRIES }; //! Entity that is either the target of an operation or whose bad status caused an operation to fail enum EEntity { SLIB_RC_ENTITY_ENTRIES }; //! Unexpected states of an entity enum EState { SLIB_RC_STATE_ENTRIES }; union { struct { //TODO: change members from unsigned char to scoped enums when we switch to c++11 unsigned char op; //!< sRC::EOperation value: what operation was attempted unsigned char op_target; //!< sRC::EEntity value: operation on what thing unsigned char bad_entity; //!< sRC::EEntity value: other thing with unexpected state that was encountered unsigned char state; //!< sRC::EState value: the unexpected state of bad_entity } parts; uint32_t whole; } val; static const sRC zero; //!< default unset RC value inline sRC() { val.whole = 0; } inline sRC(EOperation op_, EEntity op_target_, EEntity bad_entity_, EState state_) { set(op_, op_target_, bad_entity_, state_); } inline bool set(EOperation op_, EEntity op_target_, EEntity bad_entity_, EState state_) { val.parts.op = (unsigned char)op_; val.parts.op_target = (unsigned char)op_target_; val.parts.bad_entity = (unsigned char)bad_entity_; val.parts.state = (unsigned char)state_; return isSet(); } inline sRC(const sRC & rhs) { operator=(rhs); } inline sRC & operator=(const sRC & rhs) { val = rhs.val; return *this; } inline bool isSet() const { return val.whole; } inline bool isUnset() const { return !isSet(); } //! useful for the following pattern: <code> if( sRC rc = foobar(...) ) { /* foobar failed, error handled here */ } </code> inline operator bool() const { return isSet(); } static const char * operation2string(EOperation op, bool asEnumName=false); static const char * entity2string(EEntity entity, bool asEnumName=false); static const char * state2string(EState state, bool asEnumName=false); //! Print an sRC code /*! \param out where to print; if 0, prints to internal static buffer * \param asEnumNames if true, prints EOperation/EEntity/EState enum names ("eParsing eTable") * instead of corresponding descriptions ("parsing table") * \returns pointer to start of printed string */ const char * print(sStr * out=0, bool asEnumNames=false) const; }; }; #endif /* sLib_core_rc_hpp */
42.21499
135
0.658272
28e4c2089b979618e7976220fff29caa27869d48
104,500
cpp
C++
source/sfsbp/FDP.cpp
kali-allison/SCycle
0a81edfae8730acb44531e2c2b3f51f25ea193d2
[ "MIT" ]
14
2019-04-12T16:36:36.000Z
2022-03-16T00:35:03.000Z
source/sfsbp/FDP.cpp
kali-allison/SCycle
0a81edfae8730acb44531e2c2b3f51f25ea193d2
[ "MIT" ]
null
null
null
source/sfsbp/FDP.cpp
kali-allison/SCycle
0a81edfae8730acb44531e2c2b3f51f25ea193d2
[ "MIT" ]
6
2019-07-22T23:53:15.000Z
2022-03-10T03:30:50.000Z
/* FDP.cpp * ------- * ----------------------------- * Finite-Difference in Parallel * ----------------------------- * * Adding Linear Solve Functionality in the Solve_Linear_Equation function. * - It currently needs to be able to wrap MatMult in MyMatMult, using my Finite-Difference * Stencils to calculate the matrix-vector product between the vector and the 2nd derivative * matrix. * * The other main part of this program is the MMS Test. * - The first section of Globals allows the user to change the parameters of the MMS test. * - There are two sections of Globals for the MMS Test. * - The first section allows the user to define parameters for the 1-D MMS Test. * - The second allows the user to define parameters for the 2-D MMS Test. * - These parameters include a beginning point, and an end point (in each direction for 2-D) * - There is also another parameter for the number of grid points in each direction. * - Lastly, there is a parameter that dictates how many times the user wants the program to solve * each derivative. For example, changing the NUM_GRID_SPACE_CALCULATIONS will change the number of times * the program will solve the 1st derivative using finite-difference stencils in 1-D. */ #include <petscvec.h> #include <petscdmda.h> #include <math.h> #include <assert.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <iostream> // 1-D MMS Test Globals #define MIN_GRID_POINT 0 #define MAX_GRID_POINT 3 #define STARTING_GRID_SPACING 1//201 #define NUM_GRID_SPACE_CALCULATIONS 0 // 14 FIXME what's the limit here? #define NUM_2ND_GRID_SPACE_CALCULATIONS 0 // 2-D MMS Test Globals #define NUM_2D_GRID_SPACE_CALCULATIONS 0 //12 // FIXME is there a limit here? SLOWS DOWN A LOT ON 20k+ values in each direction? #define NUM_2D_2ND_GRID_SPACE_CALCULATIONS 0 #define COEFFICIENT_SOLVE 1 // IMPORTANT: 0 for NO coefficient solve (w mu), 1 (or any other numeric value) to solve WITH coefficient #define NUM_X_PTS 5 //201 #define NUM_Y_PTS 6 //201 #define X_MIN 0 #define Y_MIN 0 #define X_MAX 5 #define Y_MAX 10 //-------------------------------------------------------------------------------------------------------------------------------- //Globals for the Linear Solve Program #define PTS_IN_X 6 #define PTS_IN_Y 5 #define X_MINIMUM 0.0 #define Y_MINIMUM 0.0 #define X_MAXIMUM 5.0 #define Y_MAXIMUM 10.0 typedef struct { /* problem parameters */ PetscInt order; PetscInt n_x, n_y; Vec Bottom, Top, Left, Right; /* boundary values */ PetscScalar alphaDx, alphaDy, alphaT, beta; Vec mu; PetscScalar dx_spacing, dy_spacing; /* Working space */ Vec localX, localV; /* ghosted local vector */ DM da; /* distributed array data structure */ DM cda; Mat H; } AppCtx; PetscScalar MMS_uA(PetscScalar x, PetscScalar y) { return cos(x) * sin(y) + 2; } PetscScalar MMS_uA_dx(PetscScalar x, PetscScalar y) { return -sin(x) * sin(y); } PetscScalar MMS_uA_dxx(PetscScalar x, PetscScalar y) { return -cos(x) * sin(y); } PetscScalar MMS_uA_dy(PetscScalar x, PetscScalar y) { return cos(x) * cos(y); } PetscScalar MMS_uA_dyy(PetscScalar x, PetscScalar y) { return -cos(x) * sin(y); } PetscScalar MMS_mu(PetscScalar x, PetscScalar y) { return sin(x) * sin(y) + 2; } PetscScalar MMS_mu_dx(PetscScalar x, PetscScalar y) { return cos(x) * sin(y); } PetscScalar MMS_mu_dy(PetscScalar x, PetscScalar y) { return sin(x) * cos(y); } PetscScalar MMS_uA_dmuxx(PetscScalar x, PetscScalar y) { return MMS_mu(x,y) * MMS_uA_dxx(x,y) + MMS_mu_dx(x,y) * MMS_uA_dx(x,y); } PetscScalar MMS_uA_dmuyy(PetscScalar x, PetscScalar y) { return MMS_mu(x,y) * MMS_uA_dyy(x,y) + MMS_mu_dy(x,y) * MMS_uA_dx(x,y); } PetscScalar MMS_uS(PetscScalar x, PetscScalar y) { return MMS_mu(x,y) * (MMS_uA_dxx(x,y) + MMS_uA_dyy(x,y)) + MMS_mu_dx(x,y) * MMS_uA_dx(x,y) + MMS_mu_dy(x,y) * MMS_uA_dy(x,y); } /* Function: writeVec * ------------------ * This function allows users to pass in a vector and * a file location (including name) for a PETSc vector. * If the current directory is the desired location, * a string containing the name of the file * will suffice. The vector can then be imported to * MATLAB for error checking or other usage. */ PetscErrorCode writeVec(Vec vec,const char * loc) { PetscErrorCode ierr = 0; PetscViewer viewer; PetscViewerBinaryOpen(PETSC_COMM_WORLD,loc,FILE_MODE_WRITE,&viewer); ierr = VecView(vec,viewer);CHKERRQ(ierr); ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr); return ierr; } /* Function: calculate_two_norm * ---------------------------- * This function calculates the two-norm * of the difference of two vectors, multiplies * the calculated norm by 1/sqrt(length of vector) * and outputs this error value as well as the log (base 2) * of the error value. The Vec that will contain the difference is * the first argument (diff). The second and third arguments * are the two Vecs that we are taking the difference of. The last * argument is the length of the vectors, the number of entries * in the given Vecs. */ PetscErrorCode calculate_two_norm(Vec &diff, const Vec &x, const Vec &y, int size) { PetscErrorCode ierr = 0; PetscScalar a = -1; // set the multiple in the WAXPY operation to negative so it just subtracts VecWAXPY(diff,a,x,y); // diff = x - y PetscReal norm = 0; // zeroes out the norm value VecNorm(diff,NORM_2,&norm); // norm = NORM_2(diff) PetscReal answer = norm * (1/(sqrt(size))); // error equals norm times 1 over the sqrt of the Vec length PetscPrintf(PETSC_COMM_WORLD, "Error: % .5e ", answer); answer = log2(answer); // take the log (base 2) for easier readability PetscPrintf(PETSC_COMM_WORLD, "Log of Error: % .5e\n", answer); // I USED TO HAVE %.15e return ierr; } /* Function: Dx_1d * ------------------------------------ * This function takes in a derivative matrix (in the form of a vector) * that it will fill. It also takes in a grid spacing interval (PetscScalar) * and the values at each interval (which is a matrix placed in the form * of a vector). The vectors are passed in by reference. One * also needs to pass in the DMDA associated with the given Vecs. * * Vecs: * - u is the vector that one passes in to hold the calculated derivative. * - z is the vector that holds the sampled values of the function */ PetscErrorCode Dx_1d(Vec &u, Vec &z, PetscScalar spacing, DM &da) { PetscErrorCode ierr = 0; // Creating local Vecs y (function values) and calc_diff (derivative) Vec y, calc_diff; // Values that hold specific indices for iteration PetscInt yistart, yiend, fistart, fiend, yi_extra; // Creates local vectors using the DMDA to ensure correct partitioning DMCreateLocalVector(da,&y); DMCreateLocalVector(da,&calc_diff); // Make it such that the DMDA splits the global Vecs into local Vecs ierr = DMGlobalToLocalBegin(da,z,INSERT_VALUES,y);CHKERRQ(ierr); ierr = DMGlobalToLocalEnd(da,z,INSERT_VALUES,y);CHKERRQ(ierr); ierr = DMGlobalToLocalBegin(da,u,INSERT_VALUES,calc_diff);CHKERRQ(ierr); ierr = DMGlobalToLocalEnd(da,u,INSERT_VALUES,calc_diff);CHKERRQ(ierr); // Obtains the ownership range of both the function-value Vec and the derivative Vec ierr = VecGetOwnershipRange(y,&yistart,&yiend);CHKERRQ(ierr); ierr = VecGetOwnershipRange(calc_diff,&fistart,&fiend);CHKERRQ(ierr); // Here we set the current to the beginning and the previous to the beginning // We set the next to the one directly after the start. PetscInt yi_current = yistart; PetscInt yi_prev = yistart; PetscInt yi_next = yistart + 1; PetscScalar slope = 0; // This will contain the derivative on each calculation PetscScalar y_1, y_2, y_3; // These are used to keep the derivative values we pull from the function Vec PetscInt fi = fistart; // We start the current iteration on the first value in the function Vec while(yi_current < yiend) { yi_next = yi_current + 1; // If the current index is between the start and the end of the Vec // simply calculate the derivative using the central difference method if (yi_current > yistart && yi_current < yiend - 1) { yi_prev = yi_current - 1; ierr = VecGetValues(y,1,&yi_prev,&y_1);CHKERRQ(ierr); ierr = VecGetValues(y,1,&yi_next,&y_2);CHKERRQ(ierr); slope = ((y_2 - y_1) / (2 * spacing)); // This is where I calculate the derivative at the beginning // of the Vec. I use coefficients and 3 points to obtain // second-order accuracy. } else if (yi_current == yistart) { ierr = VecGetValues(y,1,&yi_current,&y_1);CHKERRQ(ierr); ierr = VecGetValues(y,1,&yi_next,&y_2);CHKERRQ(ierr); yi_extra = yi_next + 1; ierr = VecGetValues(y,1,&yi_extra,&y_3);CHKERRQ(ierr); slope = (((-y_3) + (4 * y_2) + (-3 * y_1)) / (2 * spacing)); // This is where I calculate the derivative at the end of the // Vec. I use coefficients and 3 points at the end of the Vec // to obtain second-order accuracy. } else if (yi_current == yiend - 1) { yi_prev = yi_current - 1; ierr = VecGetValues(y,1,&yi_prev,&y_1);CHKERRQ(ierr); ierr = VecGetValues(y,1,&yi_current,&y_2);CHKERRQ(ierr); yi_extra = yi_prev - 1; ierr = VecGetValues(y,1,&yi_extra,&y_3);CHKERRQ(ierr); slope = (((y_3) + (-4 * y_1) + (3 * y_2)) / (2 * spacing)); } // This sets the Vec value to the calculated derivative ierr = VecSetValues(calc_diff,1,&fi,&slope,INSERT_VALUES);CHKERRQ(ierr); // Increment here fi++; yi_current++; } // Assemble the Vec - do we need this here? Not sure. ierr = VecAssemblyBegin(calc_diff);CHKERRQ(ierr); ierr = VecAssemblyEnd(calc_diff);CHKERRQ(ierr); // Take the Vec values from the local Vecs and put them back in their respective global Vecs. ierr = DMLocalToGlobalBegin(da,y,INSERT_VALUES,z);CHKERRQ(ierr); ierr = DMLocalToGlobalEnd(da,y,INSERT_VALUES,z);CHKERRQ(ierr); ierr = DMLocalToGlobalBegin(da,calc_diff,INSERT_VALUES,u);CHKERRQ(ierr); ierr = DMLocalToGlobalEnd(da,calc_diff,INSERT_VALUES,u);CHKERRQ(ierr); // Dispose of the local Vecs VecDestroy(&y); VecDestroy(&calc_diff); return ierr; } /* Function: Dxx_1d * ------------------------------------ * This function takes in a derivative matrix (in the form of a vector) * that it will fill. It also takes in a grid spacing interval (PetscScalar) * and the values at each interval (which is a matrix placed in the form * of a vector). The vectors are passed in by reference. One * also needs to pass in the DMDA associated with the given Vecs. * * Vecs: * - u is the vector that one passes in to hold the calculated derivative. * - z is the vector that holds the sampled values of the function */ PetscErrorCode Dxx_1d(Vec &u, Vec &z, PetscScalar spacing, DM &da) { PetscErrorCode ierr = 0; // Creating local Vecs y (function values) and calc_diff (derivative) Vec y, calc_diff; // Values that hold specific indices for iteration PetscInt yistart, yiend, fistart, fiend, yi_extra; // Creates local vectors using the DMDA to ensure correct partitioning DMCreateLocalVector(da,&y); DMCreateLocalVector(da,&calc_diff); // Make it such that the DMDA splits the global Vecs into local Vecs ierr = DMGlobalToLocalBegin(da,z,INSERT_VALUES,y);CHKERRQ(ierr); ierr = DMGlobalToLocalEnd(da,z,INSERT_VALUES,y);CHKERRQ(ierr); ierr = DMGlobalToLocalBegin(da,u,INSERT_VALUES,calc_diff);CHKERRQ(ierr); ierr = DMGlobalToLocalEnd(da,u,INSERT_VALUES,calc_diff);CHKERRQ(ierr); // Obtains the ownership range of both the function-value Vec and the derivative Vec ierr = VecGetOwnershipRange(y,&yistart,&yiend);CHKERRQ(ierr); ierr = VecGetOwnershipRange(calc_diff,&fistart,&fiend);CHKERRQ(ierr); // Here we set the current to the beginning and the previous to the beginning // We set the next to the one directly after the start. PetscInt yi_current = yistart; PetscInt yi_prev = yistart; PetscInt yi_next = yistart + 1; PetscScalar slope = 0; // This will contain the derivative on each calculation PetscScalar y_1, y_2, y_3; // These are used to keep the derivative values we pull from the function Vec PetscInt fi = fistart; // We start the current iteration on the first value in the function Vec while(yi_current < yiend) { yi_next = yi_current + 1; // If the current index is between the start and the end of the Vec // simply calculate the derivative using the central difference method if (yi_current > yistart && yi_current < yiend - 1) { yi_prev = yi_current - 1; ierr = VecGetValues(y,1,&yi_prev,&y_1);CHKERRQ(ierr); ierr = VecGetValues(y,1,&yi_current,&y_2);CHKERRQ(ierr); ierr = VecGetValues(y,1,&yi_next,&y_3);CHKERRQ(ierr); slope = ((y_1 - (2 * y_2) + y_3) / (spacing * spacing)); // This is where I calculate the derivative at the beginning // of the Vec. I use coefficients and 3 points to obtain // second-order accuracy. } else if (yi_current == yistart) { ierr = VecGetValues(y,1,&yi_current,&y_1);CHKERRQ(ierr); ierr = VecGetValues(y,1,&yi_next,&y_2);CHKERRQ(ierr); yi_extra = yi_next + 1; ierr = VecGetValues(y,1,&yi_extra,&y_3);CHKERRQ(ierr); slope = (y_1 - (2 * y_2) + y_3) / (spacing * spacing); // This is where I calculate the derivative at the end of the // Vec. I use coefficients and 3 points at the end of the Vec // to obtain second-order accuracy. } else if (yi_current == yiend - 1) { yi_prev = yi_current - 1; ierr = VecGetValues(y,1,&yi_prev,&y_1);CHKERRQ(ierr); ierr = VecGetValues(y,1,&yi_current,&y_2);CHKERRQ(ierr); yi_extra = yi_prev - 1; ierr = VecGetValues(y,1,&yi_extra,&y_3);CHKERRQ(ierr); slope = (y_2 - (2 * (y_1)) + y_3) / (spacing * spacing); } // This sets the Vec value to the calculated derivative ierr = VecSetValues(calc_diff,1,&fi,&slope,INSERT_VALUES);CHKERRQ(ierr); // Increment here fi++; yi_current++; } // Assemble the Vec - do we need this here? Not sure. ierr = VecAssemblyBegin(calc_diff);CHKERRQ(ierr); ierr = VecAssemblyEnd(calc_diff);CHKERRQ(ierr); // Take the Vec values from the local Vecs and put them back in their respective global Vecs. ierr = DMLocalToGlobalBegin(da,y,INSERT_VALUES,z);CHKERRQ(ierr); ierr = DMLocalToGlobalEnd(da,y,INSERT_VALUES,z);CHKERRQ(ierr); ierr = DMLocalToGlobalBegin(da,calc_diff,INSERT_VALUES,u);CHKERRQ(ierr); ierr = DMLocalToGlobalEnd(da,calc_diff,INSERT_VALUES,u);CHKERRQ(ierr); // Dispose of the local Vecs VecDestroy(&y); VecDestroy(&calc_diff); return ierr; } /* Function: calculate_Dx_1d * ----------------------------- * This function calculates the first * derivative of a Vec using only * the number of entries (n), the minimum value (x_min), * and the maximum value (x_max). It calculates * all other need values. */ PetscErrorCode calculate_Dx_1d(PetscInt n, PetscInt x_min, PetscInt x_max) { PetscErrorCode ierr = 0; PetscInt i = 0, xistart, xiend, yistart, yiend, diff_start, diff_end; /* iteration values */ PetscScalar v = 0, mult = 0; /* v is my temp value I use to fill Vecs, mult is the spacing between each value of the Vec (h, dx) */ Vec w = NULL, x = NULL, y = NULL, calc_diff = NULL, diff = NULL; /* vectors */ mult = ((PetscReal)(x_max - x_min))/(n - 1); // evenly partitioning the Vec to have equally sized spacing between values // MUST CREATE DMDA - STENCIL WIDTH 1 FOR BOUNDARIES // IMPORTANT: SINCE STENCIL WIDTH IS 1, BE SURE THAT THERE ARE AT LEAST 3 END VALUES ON THE END OF A PARTITIONED VEC DM da; DMDACreate1d(PETSC_COMM_WORLD,DMDA_BOUNDARY_NONE,n,1,1,NULL,&da); // Create first Vec, this one holds the values at specific points (at every spacing) ierr = DMCreateGlobalVector(da,&x); // Holds spacing values // Same Vec format, duplicated. ierr = VecDuplicate(x,&w);CHKERRQ(ierr); // Will eventually be used to hold the difference between the actual derivative and the calculated one. ierr = VecDuplicate(x,&y);CHKERRQ(ierr); // Holds function values ierr = VecDuplicate(x,&calc_diff);CHKERRQ(ierr); // Holds calculated derivative ierr = VecDuplicate(x,&diff);CHKERRQ(ierr); // Holds actual derivative ierr = PetscObjectSetName((PetscObject) x, "x (spacing values)");CHKERRQ(ierr); ierr = PetscObjectSetName((PetscObject) w, "w");CHKERRQ(ierr); ierr = PetscObjectSetName((PetscObject) y, "y (func. values)");CHKERRQ(ierr); ierr = PetscObjectSetName((PetscObject) calc_diff, "calculated derivative");CHKERRQ(ierr); ierr = PetscObjectSetName((PetscObject) diff, "actual derivative");CHKERRQ(ierr); /* This is where I fill in the x vector. * I put in multiples defined by the grid * spacing from the minimum value to the maximum. */ VecGetOwnershipRange(x,&xistart,&xiend); for(i = xistart; i < xiend; i++) { v = (i*mult); VecSetValues(x,1,&i,&v,INSERT_VALUES); } ierr = VecAssemblyBegin(x);CHKERRQ(ierr); ierr = VecAssemblyEnd(x);CHKERRQ(ierr); /* This is where I fill in the y vector. * Its values can be defined by a hard-coded * function below. Comment out a single * function to dictate what will be in the y Vec. */ ierr = VecGetOwnershipRange(y,&yistart,&yiend);CHKERRQ(ierr); for(i = yistart; i < yiend; i++) { ierr = VecGetValues(x,1,&i,&v);CHKERRQ(ierr); // v *= v; // x^2 // v = (v*v*v); // x^3 v = sin(v); // sine function // v = cos(v); // cosine function ierr = VecSetValues(y,1,&i,&v,INSERT_VALUES);CHKERRQ(ierr); } ierr = VecAssemblyBegin(y);CHKERRQ(ierr); ierr = VecAssemblyEnd(y);CHKERRQ(ierr); /* This is where I fill in the true * analytical derivative. It's hard-coded * as well. */ ierr = VecGetOwnershipRange(diff,&diff_start,&diff_end);CHKERRQ(ierr); for(i = diff_start; i < diff_end; i++) { ierr = VecGetValues(x,1,&i,&v);CHKERRQ(ierr); // v = 2*v; // 2x // v = (3)*(v*v); //3x^2 v = cos(v); // cosine function // v = -sin(v); // -sine function ierr = VecSetValues(diff,1,&i,&v,INSERT_VALUES);CHKERRQ(ierr); } ierr = VecAssemblyBegin(diff);CHKERRQ(ierr); ierr = VecAssemblyEnd(diff);CHKERRQ(ierr); /* Here we pass in the calculated derivative Vec (to be filled), * our spacing, our Vec with function values (y), and the DMDA. * It will fill the calc_diff Vec with our calculated derivative. */ ierr = Dx_1d(calc_diff, y, mult, da);CHKERRQ(ierr); /* This is where we calculate norm using the difference between * the analytical (true) derivative and the calculated derivative and print * out the error. Below here, we print out information (number of entries, * the current spacing). */ PetscPrintf(PETSC_COMM_WORLD, "Nx: %15i Spacing: % .15e ", n, mult); ierr = calculate_two_norm(w, calc_diff, diff, n);CHKERRQ(ierr); /* To print out any of the Vecs, uncomment one of the lines below */ // ierr = VecView(x,PETSC_VIEWER_STDOUT_WORLD);CHKERRQ(ierr); // ierr = VecView(y,PETSC_VIEWER_STDOUT_WORLD);CHKERRQ(ierr); // ierr = VecView(calc_diff,PETSC_VIEWER_STDOUT_WORLD);CHKERRQ(ierr); // ierr = VecView(diff,PETSC_VIEWER_STDOUT_WORLD);CHKERRQ(ierr); // BE SURE TO DISPOSE OF ALL VECS AND DMDAS! ierr = VecDestroy(&w);CHKERRQ(ierr); ierr = VecDestroy(&x);CHKERRQ(ierr); ierr = VecDestroy(&y);CHKERRQ(ierr); ierr = VecDestroy(&calc_diff);CHKERRQ(ierr); ierr = VecDestroy(&diff);CHKERRQ(ierr); ierr = DMDestroy(&da);CHKERRQ(ierr); return ierr; } /* Function: calculate_Dxx_1d * ----------------------------- * This function calculates the second * derivative of a Vec using only * the number of entries (n), the minimum value (x_min), * and the maximum value (x_max). It calculates * all other need values. */ PetscErrorCode calculate_Dxx_1d(PetscInt n, PetscInt x_min, PetscInt x_max) { PetscErrorCode ierr = 0; PetscInt i = 0, xistart, xiend, yistart, yiend, diff_start, diff_end; /* iteration values */ PetscScalar v = 0, mult = 0; /* v is my temp value I use to fill Vecs, mult is the spacing between each value of the Vec (h, dx) */ Vec w = NULL, x = NULL, y = NULL, calc_diff = NULL, diff = NULL; /* vectors */ mult = ((PetscReal)(x_max - x_min))/(n - 1); // evenly partitioning the Vec to have equally sized spacing between values // MUST CREATE DMDA - STENCIL WIDTH 1 FOR BOUNDARIES // IMPORTANT: SINCE STENCIL WIDTH IS 1, BE SURE THAT THERE ARE AT LEAST 3 END VALUES ON THE END OF A PARTITIONED VEC DM da; DMDACreate1d(PETSC_COMM_WORLD,DMDA_BOUNDARY_NONE,n,1,1,NULL,&da); // Create first Vec, this one holds the values at specific points (at every spacing) ierr = DMCreateGlobalVector(da,&x); // Holds spacing values // Same Vec format, duplicated. ierr = VecDuplicate(x,&w);CHKERRQ(ierr); // Will eventually be used to hold the difference between the actual derivative and the calculated one. ierr = VecDuplicate(x,&y);CHKERRQ(ierr); // Holds function values ierr = VecDuplicate(x,&calc_diff);CHKERRQ(ierr); // Holds calculated derivative ierr = VecDuplicate(x,&diff);CHKERRQ(ierr); // Holds actual derivative ierr = PetscObjectSetName((PetscObject) x, "x (spacing values)");CHKERRQ(ierr); ierr = PetscObjectSetName((PetscObject) w, "w");CHKERRQ(ierr); ierr = PetscObjectSetName((PetscObject) y, "y (func. values)");CHKERRQ(ierr); ierr = PetscObjectSetName((PetscObject) calc_diff, "calculated derivative");CHKERRQ(ierr); ierr = PetscObjectSetName((PetscObject) diff, "actual derivative");CHKERRQ(ierr); /* This is where I fill in the x vector. * I put in multiples defined by the grid * spacing from the minimum value to the maximum. */ VecGetOwnershipRange(x,&xistart,&xiend); for(i = xistart; i < xiend; i++) { v = (i*mult); VecSetValues(x,1,&i,&v,INSERT_VALUES); } ierr = VecAssemblyBegin(x);CHKERRQ(ierr); ierr = VecAssemblyEnd(x);CHKERRQ(ierr); /* This is where I fill in the y vector. * Its values can be defined by a hard-coded * function below. Comment out a single * function to dictate what will be in the y Vec. */ ierr = VecGetOwnershipRange(y,&yistart,&yiend);CHKERRQ(ierr); for(i = yistart; i < yiend; i++) { ierr = VecGetValues(x,1,&i,&v);CHKERRQ(ierr); // v *= v; // x^2 // v = (v*v*v); // x^3 v = sin(v); // sine function // v = cos(v); // cosine function ierr = VecSetValues(y,1,&i,&v,INSERT_VALUES);CHKERRQ(ierr); } ierr = VecAssemblyBegin(y);CHKERRQ(ierr); ierr = VecAssemblyEnd(y);CHKERRQ(ierr); /* This is where I fill in the true * analytical derivative. It's hard-coded * as well. */ ierr = VecGetOwnershipRange(diff,&diff_start,&diff_end);CHKERRQ(ierr); for(i = diff_start; i < diff_end; i++) { ierr = VecGetValues(x,1,&i,&v);CHKERRQ(ierr); // v = 2*v; // 2x // v = (3)*(v*v); //3x^2 // v = cos(v); // cosine function v = -sin(v); // -sine function ierr = VecSetValues(diff,1,&i,&v,INSERT_VALUES);CHKERRQ(ierr); } ierr = VecAssemblyBegin(diff);CHKERRQ(ierr); ierr = VecAssemblyEnd(diff);CHKERRQ(ierr); /* Here we pass in the calculated derivative Vec (to be filled), * our spacing, our Vec with function values (y), and the DMDA. * It will fill the calc_diff Vec with our calculated derivative. */ ierr = Dxx_1d(calc_diff, y, mult, da);CHKERRQ(ierr); /* This is where we calculate norm using the difference between * the analytical (true) derivative and the calculated derivative and print * out the error. Below here, we print out information (number of entries, * the current spacing). */ PetscPrintf(PETSC_COMM_WORLD, "Nx: %15i Spacing: % .15e ", n, mult); ierr = calculate_two_norm(w, calc_diff, diff, n);CHKERRQ(ierr); /* To print out any of the Vecs, uncomment one of the lines below */ // ierr = VecView(x,PETSC_VIEWER_STDOUT_WORLD);CHKERRQ(ierr); // ierr = VecView(y,PETSC_VIEWER_STDOUT_WORLD);CHKERRQ(ierr); // ierr = VecView(calc_diff,PETSC_VIEWER_STDOUT_WORLD);CHKERRQ(ierr); // ierr = VecView(diff,PETSC_VIEWER_STDOUT_WORLD);CHKERRQ(ierr); // BE SURE TO DISPOSE OF ALL VECS AND DMDAS! ierr = VecDestroy(&w);CHKERRQ(ierr); ierr = VecDestroy(&x);CHKERRQ(ierr); ierr = VecDestroy(&y);CHKERRQ(ierr); ierr = VecDestroy(&calc_diff);CHKERRQ(ierr); ierr = VecDestroy(&diff);CHKERRQ(ierr); ierr = DMDestroy(&da);CHKERRQ(ierr); return ierr; } /* Function: truncation_error * -------------------------- * This function serves as a test function to see where the convergence fails. */ PetscErrorCode truncation_error(Vec &diff_x, PetscScalar &mult_x, DM &da) { PetscErrorCode ierr = 0; PetscInt m, n, mStart, nStart, j, i, M; DMDAGetInfo(da,NULL,&M,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL); Vec local_diff_x; PetscScalar** local_diff_x_arr; ierr = DMCreateLocalVector(da, &local_diff_x);CHKERRQ(ierr); ierr = DMGlobalToLocalBegin(da, diff_x, INSERT_VALUES, local_diff_x);CHKERRQ(ierr); ierr = DMGlobalToLocalEnd(da, diff_x, INSERT_VALUES, local_diff_x);CHKERRQ(ierr); ierr = DMDAVecGetArray(da, local_diff_x, &local_diff_x_arr);CHKERRQ(ierr); PetscInt x_index = (((int)M/5)); PetscPrintf(PETSC_COMM_WORLD, "Spacing: % .15e At index ([j][i]) [%i][%5i]F'(0.0001) = % .15e\n", mult_x, 2, x_index, local_diff_x_arr[2][x_index]); return ierr; } /* Function: Dy_2d * ---------------------------------- * 1st derivative solve in the y-direction for 2-D. * * diff_y - the output Vec (it will hold the calculated derivative) * grid - the input Vec (it holds the function values to draw from) * dy - the spacing between each point in the y-direction * da - DMDA object */ PetscErrorCode Dy_2d(Vec &diff_y, Vec &grid, PetscScalar dy, DM &da) { PetscErrorCode ierr = 0; PetscInt m, n, mStart, nStart, j, i, N; DMDAGetInfo(da,NULL,NULL,&N,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL); Vec local_diff_y, local_grid; PetscScalar** local_diff_y_arr; PetscScalar** local_grid_arr; ierr = DMCreateLocalVector(da, &local_diff_y);CHKERRQ(ierr); ierr = DMCreateLocalVector(da, &local_grid);CHKERRQ(ierr); ierr = DMDAVecGetArray(da, local_diff_y, &local_diff_y_arr);CHKERRQ(ierr); ierr = DMGlobalToLocalBegin(da, grid, INSERT_VALUES, local_grid);CHKERRQ(ierr); ierr = DMGlobalToLocalEnd(da, grid, INSERT_VALUES, local_grid);CHKERRQ(ierr); ierr = DMDAVecGetArray(da, local_grid, &local_grid_arr);CHKERRQ(ierr); ierr = DMDAGetCorners(da, &mStart, &nStart, 0, &m, &n, 0);CHKERRQ(ierr); for (j = nStart; j < nStart + n; j++) { for (i = mStart; i < mStart + m; i++) { if (j > 0 && j < N - 1) { local_diff_y_arr[j][i] = (local_grid_arr[j+1][i] - local_grid_arr[j-1][i])/(2.0 * dy); } else if (j == 0) { local_diff_y_arr[j][i] = (-1.5 * local_grid_arr[0][i] + 2.0 * local_grid_arr[1][i] - 0.5 * local_grid_arr[2][i])/ dy; } else if (j == N - 1) { local_diff_y_arr[j][i] = (0.5 * local_grid_arr[N-3][i] - 2.0 * local_grid_arr[N-2][i] + 1.5 * local_grid_arr[N-1][i]) / dy; } } } ierr = DMDAVecRestoreArray(da, local_diff_y, &local_diff_y_arr);CHKERRQ(ierr); ierr = DMDAVecRestoreArray(da, local_grid, &local_grid_arr);CHKERRQ(ierr); ierr = DMLocalToGlobalBegin(da, local_diff_y, INSERT_VALUES, diff_y);CHKERRQ(ierr); ierr = DMLocalToGlobalEnd(da, local_diff_y, INSERT_VALUES, diff_y);CHKERRQ(ierr); VecDestroy(&local_diff_y); VecDestroy(&local_grid); return ierr; } /* Function: Dx_2d * ---------------------------------- * * diff_x - the output Vec (it will hold the calculated derivative) * grid - the input Vec (it holds the function values to draw from) * dx - the spacing between each point in the x-direction * da - DMDA object */ //~PetscErrorCode Dx_2d(Vec &diff_x, Vec &grid, PetscScalar dx, DM &da) { PetscErrorCode ierr = 0; PetscInt m, n, mStart, nStart, j, i, M; DMDAGetInfo(da,NULL,&M,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL); Vec local_diff_x, local_grid; PetscScalar** local_diff_x_arr; PetscScalar** local_grid_arr; ierr = DMCreateLocalVector(da, &local_diff_x);CHKERRQ(ierr); ierr = DMCreateLocalVector(da, &local_grid);CHKERRQ(ierr); ierr = DMDAVecGetArray(da, local_diff_x, &local_diff_x_arr);CHKERRQ(ierr); ierr = DMGlobalToLocalBegin(da, grid, INSERT_VALUES, local_grid);CHKERRQ(ierr); ierr = DMGlobalToLocalEnd(da, grid, INSERT_VALUES, local_grid);CHKERRQ(ierr); ierr = DMDAVecGetArray(da, local_grid, &local_grid_arr); CHKERRQ(ierr); ierr = DMDAGetCorners(da, &mStart, &nStart, 0, &m, &n, 0);CHKERRQ(ierr); for (j = nStart; j < nStart + n; j++) { for (i = mStart; i < mStart + m; i++) { if (i > 0 && i < M - 1) {local_diff_x_arr[j][i] = (local_grid_arr[j][i+1] - local_grid_arr[j][i-1])/(2.0 * dx); } else if (i == 0) { local_diff_x_arr[j][i] = (-1.5 * local_grid_arr[j][0] + 2.0 * local_grid_arr[j][1] - 0.5 * local_grid_arr[j][2])/ dx; } else if (i == M - 1) { local_diff_x_arr[j][i] = (0.5 * local_grid_arr[j][M-3] - 2.0 * local_grid_arr[j][M-2] + 1.5 * local_grid_arr[j][M-1]) / dx; } } } ierr = DMDAVecRestoreArray(da, local_diff_x, &local_diff_x_arr);CHKERRQ(ierr); ierr = DMDAVecRestoreArray(da, local_grid, &local_grid_arr);CHKERRQ(ierr); ierr = DMLocalToGlobalBegin(da, local_diff_x, INSERT_VALUES, diff_x);CHKERRQ(ierr); ierr = DMLocalToGlobalEnd(da, local_diff_x, INSERT_VALUES, diff_x);CHKERRQ(ierr); VecDestroy(&local_diff_x); VecDestroy(&local_grid); return ierr; } /* Function: Dyy_2d * ---------------------------------- * diff_y - the output Vec (it will hold the calculated derivative) * grid - the input Vec (it holds the function values to draw from) * dy - the spacing between each point in the y-direction * da - DMDA object */ PetscErrorCode Dyy_2d(Vec &diff_y, const Vec &grid, const PetscScalar dy, const DM &da) { PetscErrorCode ierr = 0; PetscInt m, n, mStart, nStart, j, i, N; DMDAGetInfo(da,NULL,NULL,&N,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL); Vec local_diff_y, local_grid; PetscScalar** local_diff_y_arr; PetscScalar** local_grid_arr; ierr = DMCreateLocalVector(da, &local_diff_y);CHKERRQ(ierr); ierr = DMCreateLocalVector(da, &local_grid);CHKERRQ(ierr); ierr = DMDAVecGetArray(da, local_diff_y, &local_diff_y_arr); CHKERRQ(ierr); ierr = DMGlobalToLocalBegin(da, grid, INSERT_VALUES, local_grid);CHKERRQ(ierr); ierr = DMGlobalToLocalEnd(da, grid, INSERT_VALUES, local_grid);CHKERRQ(ierr); ierr = DMDAVecGetArray(da, local_grid, &local_grid_arr); CHKERRQ(ierr); ierr = DMDAGetCorners(da, &mStart, &nStart, 0, &m, &n, 0); CHKERRQ(ierr); for (j = nStart; j < nStart + n; j++) { for (i = mStart; i < mStart + m; i++) { if (j > 0 && j < N - 1) { local_diff_y_arr[j][i] = (local_grid_arr[j+1][i] - (2*local_grid_arr[j][i]) + local_grid_arr[j-1][i])/(dy * dy); } else if (j == 0) { local_diff_y_arr[j][i] = (local_grid_arr[0][i] - (2 * local_grid_arr[1][i]) + local_grid_arr[2][i])/(dy * dy); } else if (j == N - 1) { local_diff_y_arr[j][i] = (local_grid_arr[N-1][i] - (2 * local_grid_arr[N-2][i]) + local_grid_arr[N-3][i])/(dy * dy); } } } ierr = DMDAVecRestoreArray(da, local_diff_y, &local_diff_y_arr);CHKERRQ(ierr); ierr = DMDAVecRestoreArray(da, local_grid, &local_grid_arr);CHKERRQ(ierr); ierr = DMLocalToGlobalBegin(da, local_diff_y, INSERT_VALUES, diff_y);CHKERRQ(ierr); ierr = DMLocalToGlobalEnd(da, local_diff_y, INSERT_VALUES, diff_y);CHKERRQ(ierr); VecDestroy(&local_diff_y); VecDestroy(&local_grid); return ierr; } /* Function: Dxx_2d * -------------------------------------- * diff_x - the output Vec (it will hold the calculated derivative) * grid - the input Vec (it holds the function values to draw from) * dx - the spacing between each point in the x-direction * da - DMDA object */ PetscErrorCode Dxx_2d(Vec &diff_x, const Vec &grid, const PetscScalar dx, const DM &da) { PetscErrorCode ierr = 0; PetscInt m, n, mStart, nStart, j, i, M; DMDAGetInfo(da,NULL,&M,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL); VecSet(diff_x,0.0); Vec local_diff_x, local_grid; PetscScalar** local_diff_x_arr; PetscScalar** local_grid_arr; ierr = DMCreateLocalVector(da, &local_diff_x);CHKERRQ(ierr); ierr = DMCreateLocalVector(da, &local_grid);CHKERRQ(ierr); ierr = DMDAVecGetArray(da, local_diff_x, &local_diff_x_arr);CHKERRQ(ierr); ierr = DMGlobalToLocalBegin(da, grid, INSERT_VALUES, local_grid);CHKERRQ(ierr); ierr = DMGlobalToLocalEnd(da, grid, INSERT_VALUES, local_grid);CHKERRQ(ierr); ierr = DMDAVecGetArray(da, local_grid, &local_grid_arr);CHKERRQ(ierr); DMDAGetCorners(da, &mStart, &nStart, 0, &m, &n, 0); for (j = nStart; j < nStart + n; j++) { for (i = mStart; i < mStart + m; i++) { if (i > 0 && i < M - 1) {local_diff_x_arr[j][i] = (local_grid_arr[j][i+1] - (2 * local_grid_arr[j][i]) + local_grid_arr[j][i-1])/(dx * dx); } else if (i == 0) { local_diff_x_arr[j][i] = (local_grid_arr[j][0] - (2 * local_grid_arr[j][1]) + local_grid_arr[j][2])/(dx * dx); } else if (i == M - 1) { local_diff_x_arr[j][i] = (local_grid_arr[j][M-1] - (2 * local_grid_arr[j][M-2]) + local_grid_arr[j][M-3])/(dx * dx); } //PetscPrintf(PETSC_COMM_SELF, "[%i][%i] = %g\n", j, i, local_diff_x_arr[j][i]); } } ierr = DMDAVecRestoreArray(da, local_diff_x, &local_diff_x_arr);CHKERRQ(ierr); ierr = DMDAVecRestoreArray(da, local_grid, &local_grid_arr);CHKERRQ(ierr); ierr = DMLocalToGlobalBegin(da, local_diff_x, INSERT_VALUES, diff_x);CHKERRQ(ierr); ierr = DMLocalToGlobalEnd(da, local_diff_x, INSERT_VALUES, diff_x);CHKERRQ(ierr); VecDestroy(&local_diff_x); VecDestroy(&local_grid); return ierr; } /* Function: Dmuyy_2d * ------------------ * diff_y - the output Vec (it will hold the calculated derivative) * grid - the input Vec (it holds the function values to draw from) * mu - the Vec that holds the values of mu * dy - the spacing between each point in the y-direction * da - DMDA object */ PetscErrorCode Dmuyy_2d(Vec &diff_y, const Vec &grid, const Vec &mu, const PetscScalar dy, const DM &da) { PetscErrorCode ierr = 0; PetscInt m, n, mStart, nStart, j, i, N; DMDAGetInfo(da,NULL,NULL,&N,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL); Vec local_diff_y = NULL, local_grid = NULL, local_mu = NULL; PetscScalar** local_diff_y_arr; PetscScalar** local_grid_arr; PetscScalar** local_mu_arr; ierr = DMCreateLocalVector(da, &local_diff_y);CHKERRQ(ierr); ierr = DMCreateLocalVector(da, &local_grid);CHKERRQ(ierr); ierr = DMCreateLocalVector(da, &local_mu);CHKERRQ(ierr); ierr = DMDAVecGetArray(da, local_diff_y, &local_diff_y_arr);CHKERRQ(ierr); ierr = DMGlobalToLocalBegin(da, grid, INSERT_VALUES, local_grid);CHKERRQ(ierr); ierr = DMGlobalToLocalEnd(da, grid, INSERT_VALUES, local_grid);CHKERRQ(ierr); ierr = DMDAVecGetArray(da, local_grid, &local_grid_arr);CHKERRQ(ierr); ierr = DMGlobalToLocalBegin(da, mu, INSERT_VALUES, local_mu);CHKERRQ(ierr); ierr = DMGlobalToLocalEnd(da, mu, INSERT_VALUES, local_mu);CHKERRQ(ierr); ierr = DMDAVecGetArray(da, local_mu, &local_mu_arr); CHKERRQ(ierr); ierr = DMDAGetCorners(da, &mStart, &nStart, 0, &m, &n, 0);CHKERRQ(ierr); for (j = nStart; j < nStart + n; j++) { for (i = mStart; i < mStart + m; i++) { if (j > 0 && j < N - 1) { local_diff_y_arr[j][i] = (0.5 * (((local_mu_arr[j][i] + local_mu_arr[j-1][i]) * local_grid_arr[j-1][i]) - ((local_mu_arr[j+1][i] + 2 * local_mu_arr[j][i] + local_mu_arr[j-1][i]) * local_grid_arr[j][i]) + ((local_mu_arr[j][i] + local_mu_arr[j+1][i]) * local_grid_arr[j+1][i]) ))/(dy * dy); } else if (j == 0) { local_diff_y_arr[j][i] = (0.5 * (((local_mu_arr[1][i] + local_mu_arr[0][i]) * local_grid_arr[0][i]) - ((local_mu_arr[2][i] + 2 * local_mu_arr[1][i] + local_mu_arr[0][i]) * local_grid_arr[1][i]) + ((local_mu_arr[1][i] + local_mu_arr[2][i]) * local_grid_arr[2][i]) ))/(dy * dy); } else if (j == N - 1) { local_diff_y_arr[j][i] = (0.5 * (((local_mu_arr[N-2][i] + local_mu_arr[N-1][i]) * local_grid_arr[N-1][i]) - ((local_mu_arr[N-3][i] + 2 * local_mu_arr[N-2][i] + local_mu_arr[N-1][i]) * local_grid_arr[N-2][i]) + ((local_mu_arr[N-2][i] + local_mu_arr[N-3][i]) * local_grid_arr[N-3][i]) ))/(dy * dy); } } } ierr = DMDAVecRestoreArray(da, local_diff_y, &local_diff_y_arr);CHKERRQ(ierr); ierr = DMDAVecRestoreArray(da, local_grid, &local_grid_arr);CHKERRQ(ierr); ierr = DMDAVecRestoreArray(da, local_mu, &local_mu_arr);CHKERRQ(ierr); ierr = DMLocalToGlobalBegin(da, local_diff_y, INSERT_VALUES, diff_y);CHKERRQ(ierr); ierr = DMLocalToGlobalEnd(da, local_diff_y, INSERT_VALUES, diff_y);CHKERRQ(ierr); VecDestroy(&local_diff_y); VecDestroy(&local_grid); VecDestroy(&local_mu); return ierr; } /* Function: Dmuxx_2d * -------------------------------------- * diff_x - the output Vec (it will hold the calculated derivative) * grid - the input Vec (it holds the function values to draw from) * mu - the Vec that holds the values of mu * dx - the spacing between each point in the x-direction * da - DMDA object */ PetscErrorCode Dmuxx_2d(Vec &diff_x, const Vec &grid, const Vec &mu, const PetscScalar dx, const DM &da) { PetscErrorCode ierr = 0; PetscInt m, n, mStart, nStart, j, i, M; DMDAGetInfo(da,NULL,&M,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL); Vec local_diff_x = NULL, local_grid = NULL, local_mu = NULL; PetscScalar** local_diff_x_arr; PetscScalar** local_grid_arr; PetscScalar** local_mu_arr; ierr = DMCreateLocalVector(da, &local_diff_x);CHKERRQ(ierr); ierr = DMCreateLocalVector(da, &local_grid);CHKERRQ(ierr); ierr = DMCreateLocalVector(da, &local_mu);CHKERRQ(ierr); ierr = DMDAVecGetArray(da, local_diff_x, &local_diff_x_arr); CHKERRQ(ierr); ierr = DMGlobalToLocalBegin(da, grid, INSERT_VALUES, local_grid);CHKERRQ(ierr); ierr = DMGlobalToLocalEnd(da, grid, INSERT_VALUES, local_grid);CHKERRQ(ierr); ierr = DMDAVecGetArray(da, local_grid, &local_grid_arr); CHKERRQ(ierr); ierr = DMGlobalToLocalBegin(da, mu, INSERT_VALUES, local_mu);CHKERRQ(ierr); ierr = DMGlobalToLocalEnd(da, mu, INSERT_VALUES, local_mu);CHKERRQ(ierr); ierr = DMDAVecGetArray(da, local_mu, &local_mu_arr); CHKERRQ(ierr); ierr = DMDAGetCorners(da, &mStart, &nStart, 0, &m, &n, 0); CHKERRQ(ierr); for (j = nStart; j < nStart + n; j++) { for (i = mStart; i < mStart + m; i++) { if (i > 0 && i < M - 1) {local_diff_x_arr[j][i] = (0.5 * (((local_mu_arr[j][i] + local_mu_arr[j][i-1]) * local_grid_arr[j][i-1]) - ((local_mu_arr[j][i+1] + 2 * local_mu_arr[j][i] + local_mu_arr[j][i-1]) * local_grid_arr[j][i]) + ((local_mu_arr[j][i] + local_mu_arr[j][i+1]) * local_grid_arr[j][i+1]) ))/(dx * dx); } else if (i == 0) { local_diff_x_arr[j][i] = (0.5 * (((local_mu_arr[j][1] + local_mu_arr[j][0]) * local_grid_arr[j][0]) - ((local_mu_arr[j][2] + 2 * local_mu_arr[j][1] + local_mu_arr[j][0]) * local_grid_arr[j][1]) + ((local_mu_arr[j][1] + local_mu_arr[j][2]) * local_grid_arr[j][2]) ))/(dx * dx); } else if (i == M - 1) { local_diff_x_arr[j][i] = (0.5 * (((local_mu_arr[j][M-2] + local_mu_arr[j][M-1]) * local_grid_arr[j][M-1]) - ((local_mu_arr[j][M-3] + 2 * local_mu_arr[j][M-2] + local_mu_arr[j][M-1]) * local_grid_arr[j][M-2]) + ((local_mu_arr[j][M-2] + local_mu_arr[j][M-3]) * local_grid_arr[j][M-3]) ))/(dx * dx); } //PetscPrintf(PETSC_COMM_SELF, "[%i][%i] = %g\n", j, i, local_diff_x_arr[j][i]); } } ierr = DMDAVecRestoreArray(da, local_diff_x, &local_diff_x_arr);CHKERRQ(ierr); ierr = DMDAVecRestoreArray(da, local_grid, &local_grid_arr);CHKERRQ(ierr); ierr = DMDAVecRestoreArray(da, local_mu, &local_mu_arr);CHKERRQ(ierr); ierr = DMLocalToGlobalBegin(da, local_diff_x, INSERT_VALUES, diff_x);CHKERRQ(ierr); ierr = DMLocalToGlobalEnd(da, local_diff_x, INSERT_VALUES, diff_x);CHKERRQ(ierr); VecDestroy(&local_diff_x); VecDestroy(&local_grid); VecDestroy(&local_mu); return ierr; } /* Function: calculate_Dx_Dy_2D * --------------------------------------- * Calculates both the first derivative in x and y for a 2-D grid. * x_len - number of points in the x direction * y_len - number of points in the y direction * x_max - maximum value in the x direction * x_min - minimum value in the x_direction * y_max - maximum value in the y direction * y_min - minimum value in the y direction */ PetscErrorCode calculate_Dx_Dy_2D(PetscInt x_len, PetscInt y_len, PetscScalar x_max, PetscScalar x_min, PetscScalar y_max, PetscScalar y_min) { PetscErrorCode ierr = 0; double t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0; t1 = MPI_Wtime(); PetscInt i = 0, j = 0, mStart = 0, m = 0, nStart = 0, n = 0, grid_istart, grid_iend, diff_x_start, diff_x_end, diff_y_start, diff_y_end; PetscScalar v = 0, mult_x = 0, mult_y = 0; Vec grid = NULL, diff_x = NULL, diff_y = NULL, act_diff_x = NULL, act_diff_y = NULL, grid_error_diff = NULL, /* vectors */ local_coords = NULL, local_grid = NULL, local_act_diff_x = NULL, local_act_diff_y = NULL; // first row, global vectors, second row, local vectors PetscInt num_grid_entries = (x_len) * (y_len); // total number of entries on the grid mult_x = ((PetscReal)(x_max - x_min))/(x_len - 1); // spacing in the x direction mult_y = ((PetscReal)(y_max - y_min))/(y_len - 1); // spacing in the y direction DM da; DM cda; DMDACoor2d **coords; // 2D array containing x and y data members // FIXME should I use DMDA_STENCIL_STAR && do we need a stencil width of 2? ierr = DMDACreate2d(PETSC_COMM_WORLD,DMDA_BOUNDARY_NONE, DMDA_BOUNDARY_NONE, DMDA_STENCIL_BOX, x_len, y_len, PETSC_DECIDE, PETSC_DECIDE, 1, 2, NULL, NULL, &da); CHKERRQ(ierr); DMDASetUniformCoordinates(da, x_min, x_max, y_min, y_max, 0.0, 0.0); DMGetCoordinateDM(da, &cda); DMGetCoordinatesLocal(da, &local_coords); DMDAVecGetArray(cda, local_coords, &coords); DMDAGetCorners(cda, &mStart, &nStart, 0, &m, &n, 0); ierr = DMCreateGlobalVector(da,&grid); ierr = VecDuplicate(grid, &diff_x);CHKERRQ(ierr); ierr = VecDuplicate(grid, &diff_y);CHKERRQ(ierr); ierr = VecDuplicate(grid, &act_diff_x);CHKERRQ(ierr); ierr = VecDuplicate(grid, &act_diff_y);CHKERRQ(ierr); ierr = VecDuplicate(grid, &grid_error_diff);CHKERRQ(ierr); ierr = PetscObjectSetName((PetscObject) grid, "global grid");CHKERRQ(ierr); ierr = PetscObjectSetName((PetscObject) diff_x, "diff_x");CHKERRQ(ierr); ierr = PetscObjectSetName((PetscObject) diff_y, "diff_y");CHKERRQ(ierr); ierr = PetscObjectSetName((PetscObject) act_diff_x, "act_diff_x");CHKERRQ(ierr); ierr = PetscObjectSetName((PetscObject) act_diff_y, "act_diff_y");CHKERRQ(ierr); ierr = PetscObjectSetName((PetscObject) grid_error_diff, "grid_error_diff");CHKERRQ(ierr); // Set up GRID ierr = DMCreateLocalVector(da, &local_grid);CHKERRQ(ierr); ierr = DMGlobalToLocalBegin(da, grid, INSERT_VALUES, local_grid);CHKERRQ(ierr); ierr = DMGlobalToLocalEnd(da, grid, INSERT_VALUES, local_grid);CHKERRQ(ierr); //FIXME PetscMPIInt rank; MPI_Comm_rank(PETSC_COMM_WORLD, &rank); //FIXME PetscInt x_index = x_len/5; bool printed = false; PetscScalar **local_grid_arr; DMDAVecGetArray(da, local_grid, &local_grid_arr); for (j = nStart; j < nStart + n; j++) { for (i = mStart; i < mStart + m; i++) { // PetscPrintf(PETSC_COMM_SELF, "%i: (coords[%i][%i].x, coords[%i][%i].y) = (%g, %g)\n)", rank, j, i, j, i, coords[j][i].x, coords[j][i].y); // local_grid_arr[j][i] = coords[j][i].y; // FIXME //if(i == x_index && printed == false) { // PetscPrintf(PETSC_COMM_WORLD, "\nx_index: %i SHOULD BE 0.1 = % .5e\n", x_index, coords[j][x_index].x); // printed = true; //} //local_grid_arr[j][i] = (.01*(coords[j][i].x * coords[j][i].x * coords[j][i].x) + (coords[j][i].y * coords[j][i].y * coords[j][i].y)); local_grid_arr[j][i] = cos(coords[j][i].x) * sin(coords[j][i].y);//sin(coords[j][i].x) + cos(coords[j][i].y); } } DMDAVecRestoreArray(da, local_grid, &local_grid_arr); ierr = DMLocalToGlobalBegin(da, local_grid, INSERT_VALUES, grid);CHKERRQ(ierr); ierr = DMLocalToGlobalEnd(da, local_grid, INSERT_VALUES, grid);CHKERRQ(ierr); // SET UP ACT_DIFF_X ierr = DMCreateLocalVector(da, &local_act_diff_x);CHKERRQ(ierr); ierr = DMGlobalToLocalBegin(da, act_diff_x, INSERT_VALUES, local_act_diff_x);CHKERRQ(ierr); ierr = DMGlobalToLocalEnd(da, act_diff_x, INSERT_VALUES, local_act_diff_x);CHKERRQ(ierr); PetscScalar **local_act_diff_x_arr; DMDAVecGetArray(da, local_act_diff_x, &local_act_diff_x_arr); for (j = nStart; j < nStart + n; j++) { for (i = mStart; i < mStart + m; i++) { // PetscPrintf(PETSC_COMM_SELF, "%i: (coords[%i][%i].x, coords[%i][%i].y) = (%g, %g)\n)", rank, j, i, j, i, coords[j][i].x, coords[j][i].y); // local_act_diff_x_arr[j][i] = coords[j][i].x; local_act_diff_x_arr[j][i] = -sin(coords[j][i].x) * sin(coords[j][i].y);//cos(coords[j][i].x); //local_act_diff_x_arr[j][i] = .01*(3 * coords[j][i].x * coords[j][i].x); } } DMDAVecRestoreArray(da, local_act_diff_x, &local_act_diff_x_arr); ierr = DMLocalToGlobalBegin(da, local_act_diff_x, INSERT_VALUES, act_diff_x);CHKERRQ(ierr); ierr = DMLocalToGlobalEnd(da, local_act_diff_x, INSERT_VALUES, act_diff_x);CHKERRQ(ierr); // SET UP ACT_DIFF_Y ierr = DMCreateLocalVector(da, &local_act_diff_y);CHKERRQ(ierr); ierr = DMGlobalToLocalBegin(da, act_diff_y, INSERT_VALUES, local_act_diff_y);CHKERRQ(ierr); ierr = DMGlobalToLocalEnd(da, act_diff_y, INSERT_VALUES, local_act_diff_y);CHKERRQ(ierr); PetscScalar **local_act_diff_y_arr; DMDAVecGetArray(da, local_act_diff_y, &local_act_diff_y_arr); for (j = nStart; j < nStart + n; j++) { for (i = mStart; i < mStart + m; i++) { // PetscPrintf(PETSC_COMM_SELF, "%i: (coords[%i][%i].x, coords[%i][%i].y) = (%g, %g)\n)", rank, j, i, j, i, coords[j][i].x, coords[j][i].y); //local_act_diff_y_arr[j][i] = .01*(3 * coords[j][i].y * coords[j][i].y); local_act_diff_y_arr[j][i] = cos(coords[j][i].y) * cos(coords[j][i].x); } } DMDAVecRestoreArray(da, local_act_diff_y, &local_act_diff_y_arr); ierr = DMLocalToGlobalBegin(da, local_act_diff_y, INSERT_VALUES, act_diff_y);CHKERRQ(ierr); ierr = DMLocalToGlobalEnd(da, local_act_diff_y, INSERT_VALUES, act_diff_y);CHKERRQ(ierr); t2 = MPI_Wtime(); ierr = Dy_2d(diff_y, grid, mult_y, da);CHKERRQ(ierr); t3 = MPI_Wtime(); ierr = Dx_2d(diff_x, grid, mult_x, da);CHKERRQ(ierr); t4 = MPI_Wtime(); PetscPrintf(PETSC_COMM_WORLD, "Ny: %5i Spacing: % .5e Log of Spacing: % .5e ", y_len, mult_y, log2(mult_y)); // I used to have %15! calculate_two_norm(grid_error_diff, diff_y, act_diff_y, num_grid_entries); PetscPrintf(PETSC_COMM_WORLD, " Nx: %5i Spacing: % .5e Log of Spacing: % .5e ", x_len, mult_x, log2(mult_x)); calculate_two_norm(grid_error_diff, diff_x, act_diff_x, num_grid_entries); t5 = MPI_Wtime(); // writeVec(grid, "grid_file"); // writeVec(diff_x, "calc_diff_x_file"); // writeVec(diff_y, "calc_diff_y_file"); // writeVec(act_diff_x, "actual_diff_x_file"); // writeVec(act_diff_y, "actual_diff_y_file"); // Truncation Error Test!!! //ierr = truncation_error(diff_x, mult_x, da);CHKERRQ(ierr); // FIXME make sure all Vecs and DMs are being destroyed - go to other functions as well! ierr = VecDestroy(&grid);CHKERRQ(ierr); ierr = VecDestroy(&diff_y);CHKERRQ(ierr); ierr = VecDestroy(&diff_x);CHKERRQ(ierr); ierr = VecDestroy(&act_diff_y);CHKERRQ(ierr); ierr = VecDestroy(&act_diff_x);CHKERRQ(ierr); ierr = VecDestroy(&grid_error_diff);CHKERRQ(ierr); ierr = VecDestroy(&local_grid);CHKERRQ(ierr); ierr = VecDestroy(&local_act_diff_y);CHKERRQ(ierr); ierr = VecDestroy(&local_act_diff_x);CHKERRQ(ierr); //ierr = VecDestroy(&local_coords);CHKERRQ(ierr); //ierr = DMDestroy(&cda);CHKERRQ(ierr); ierr = DMDestroy(&da);CHKERRQ(ierr); t6 = MPI_Wtime(); PetscPrintf(PETSC_COMM_WORLD, "\nTime spent setting up and filling grid/actual derivative Vecs: % 8g\n", t2 - t1); PetscPrintf(PETSC_COMM_WORLD, "Time spent calculating 2Dy derivative: % 8g\n", t3 - t2); PetscPrintf(PETSC_COMM_WORLD, "Time spent calculating 2Dx derivative: % 8g\n", t4 - t3); PetscPrintf(PETSC_COMM_WORLD, "Time spent calculating norms: % 8g\n", t5 - t4); PetscPrintf(PETSC_COMM_WORLD, "Total time for this iteration: % 8g\n\n", t6 - t1); return ierr; } /* Function: calculate_Dxx_Dyy_2D * ------------------------------------------- * Calculates both second derivatives in x and y for a 2-D grid. * IMPORTANT: Depending on the global set at the top of this program, * the function will either solve the second derivative WITH coefficient or WITHOUT. * * x_len - number of points in the x direction * y_len - number of points in the y direction * x_max - maximum value in the x direction * x_min - minimum value in the x_direction * y_max - maximum value in the y direction * y_min - minimum value in the y direction */ PetscErrorCode calculate_Dxx_Dyy_2D(PetscInt x_len, PetscInt y_len, PetscScalar x_max, PetscScalar x_min, PetscScalar y_max, PetscScalar y_min) { PetscErrorCode ierr = 0; double t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0; t1 = MPI_Wtime(); PetscInt i = 0, j = 0, mStart = 0, m = 0, nStart = 0, n = 0, grid_istart, grid_iend, diff_x_start, diff_x_end, diff_y_start, diff_y_end; PetscScalar v = 0, mult_x = 0, mult_y = 0; Vec grid = NULL, diff_x = NULL, diff_y = NULL, act_diff_x = NULL, act_diff_y = NULL, grid_error_diff = NULL, /* vectors */ local_coords = NULL, local_grid = NULL, local_act_diff_x = NULL, local_act_diff_y = NULL, mu = NULL, local_mu = NULL, dxxmu = NULL, local_dxxmu = NULL, dyymu = NULL, local_dyymu = NULL; // first row, global vectors | second row, local vectors | third row, mu PetscInt num_grid_entries = (x_len) * (y_len); // total number of entries on the grid mult_x = ((PetscReal)(x_max - x_min))/(x_len - 1); // spacing in the x direction mult_y = ((PetscReal)(y_max - y_min))/(y_len - 1); // spacing in the y direction DM da; DM cda; DMDACoor2d **coords; // 2D array containing x and y data members // FIXME should I use DMDA_STENCIL_STAR?? DMDA Set Up ierr = DMDACreate2d(PETSC_COMM_WORLD,DMDA_BOUNDARY_NONE, DMDA_BOUNDARY_NONE, DMDA_STENCIL_BOX, x_len, y_len, PETSC_DECIDE, PETSC_DECIDE, 1, 2, NULL, NULL, &da); CHKERRQ(ierr); DMDASetUniformCoordinates(da, x_min, x_max, y_min, y_max, 0.0, 0.0); DMGetCoordinateDM(da, &cda); DMGetCoordinatesLocal(da, &local_coords); DMDAVecGetArray(cda, local_coords, &coords); DMDAGetCorners(cda, &mStart, &nStart, 0, &m, &n, 0); ierr = DMCreateGlobalVector(da,&grid); ierr = VecDuplicate(grid, &diff_x);CHKERRQ(ierr); ierr = VecDuplicate(grid, &diff_y);CHKERRQ(ierr); ierr = VecDuplicate(grid, &act_diff_x);CHKERRQ(ierr); ierr = VecDuplicate(grid, &act_diff_y);CHKERRQ(ierr); ierr = VecDuplicate(grid, &grid_error_diff);CHKERRQ(ierr); ierr = VecDuplicate(grid, &mu);CHKERRQ(ierr); ierr = VecDuplicate(grid, &dxxmu);CHKERRQ(ierr); ierr = VecDuplicate(grid, &dyymu);CHKERRQ(ierr); ierr = PetscObjectSetName((PetscObject) grid, "global grid");CHKERRQ(ierr); ierr = PetscObjectSetName((PetscObject) diff_x, "diff_x");CHKERRQ(ierr); ierr = PetscObjectSetName((PetscObject) diff_y, "diff_y");CHKERRQ(ierr); ierr = PetscObjectSetName((PetscObject) act_diff_x, "act_diff_x");CHKERRQ(ierr); ierr = PetscObjectSetName((PetscObject) act_diff_y, "act_diff_y");CHKERRQ(ierr); ierr = PetscObjectSetName((PetscObject) grid_error_diff, "grid_error_diff");CHKERRQ(ierr); //FIXME PetscMPIInt rank; MPI_Comm_rank(PETSC_COMM_WORLD, &rank); // Set up GRID ierr = DMCreateLocalVector(da, &local_grid);CHKERRQ(ierr); ierr = DMGlobalToLocalBegin(da, grid, INSERT_VALUES, local_grid);CHKERRQ(ierr); ierr = DMGlobalToLocalEnd(da, grid, INSERT_VALUES, local_grid);CHKERRQ(ierr); PetscScalar **local_grid_arr; DMDAVecGetArray(da, local_grid, &local_grid_arr); for (j = nStart; j < nStart + n; j++) { for (i = mStart; i < mStart + m; i++) { // PetscPrintf(PETSC_COMM_SELF, "%i: (coords[%i][%i].x, coords[%i][%i].y) = (%g, %g)\n)", rank, j, i, j, i, coords[j][i].x, coords[j][i].y); // local_grid_arr[j][i] = coords[j][i].y; // local_grid_arr[j][i] = (coords[j][i].x * coords[j][i].x * coords[j][i].x) + (coords[j][i].y * coords[j][i].y * coords[j][i].y); local_grid_arr[j][i] = cos(coords[j][i].x) + sin(coords[j][i].y); // PetscPrintf(PETSC_COMM_SELF, "%i: [%i][%i] = %g\n", rank, j, i, local_grid_arr[j][i]); } } DMDAVecRestoreArray(da, local_grid, &local_grid_arr); ierr = DMLocalToGlobalBegin(da, local_grid, INSERT_VALUES, grid);CHKERRQ(ierr); ierr = DMLocalToGlobalEnd(da, local_grid, INSERT_VALUES, grid);CHKERRQ(ierr); // SET UP ACT_DIFF_X ierr = DMCreateLocalVector(da, &local_act_diff_x);CHKERRQ(ierr); ierr = DMGlobalToLocalBegin(da, act_diff_x, INSERT_VALUES, local_act_diff_x);CHKERRQ(ierr); ierr = DMGlobalToLocalEnd(da, act_diff_x, INSERT_VALUES, local_act_diff_x);CHKERRQ(ierr); PetscScalar **local_act_diff_x_arr; DMDAVecGetArray(da, local_act_diff_x, &local_act_diff_x_arr); for (j = nStart; j < nStart + n; j++) { for (i = mStart; i < mStart + m; i++) { // PetscPrintf(PETSC_COMM_SELF, "%i: (coords[%i][%i].x, coords[%i][%i].y) = (%g, %g)\n)", rank, j, i, j, i, coords[j][i].x, coords[j][i].y); // local_act_diff_x_arr[j][i] = coords[j][i].x; local_act_diff_x_arr[j][i] = -cos(coords[j][i].x); // PetscPrintf(PETSC_COMM_SELF, "%i: [%i][%i] = %g\n", rank, j, i, local_act_diff_x_arr[j][i]); // local_act_diff_x_arr[j][i] = (6 * coords[j][i].x); } } DMDAVecRestoreArray(da, local_act_diff_x, &local_act_diff_x_arr); ierr = DMLocalToGlobalBegin(da, local_act_diff_x, INSERT_VALUES, act_diff_x);CHKERRQ(ierr); ierr = DMLocalToGlobalEnd(da, local_act_diff_x, INSERT_VALUES, act_diff_x);CHKERRQ(ierr); // SET UP ACT_DIFF_Y ierr = DMCreateLocalVector(da, &local_act_diff_y);CHKERRQ(ierr); ierr = DMGlobalToLocalBegin(da, act_diff_y, INSERT_VALUES, local_act_diff_y);CHKERRQ(ierr); ierr = DMGlobalToLocalEnd(da, act_diff_y, INSERT_VALUES, local_act_diff_y);CHKERRQ(ierr); PetscScalar **local_act_diff_y_arr; DMDAVecGetArray(da, local_act_diff_y, &local_act_diff_y_arr); for (j = nStart; j < nStart + n; j++) { for (i = mStart; i < mStart + m; i++) { // PetscPrintf(PETSC_COMM_SELF, "%i: (coords[%i][%i].x, coords[%i][%i].y) = (%g, %g)\n)", rank, j, i, j, i, coords[j][i].x, coords[j][i].y); // local_act_diff_y_arr[j][i] = (6 * coords[j][i].y); local_act_diff_y_arr[j][i] = -sin(coords[j][i].y); } } DMDAVecRestoreArray(da, local_act_diff_y, &local_act_diff_y_arr); ierr = DMLocalToGlobalBegin(da, local_act_diff_y, INSERT_VALUES, act_diff_y);CHKERRQ(ierr); ierr = DMLocalToGlobalEnd(da, local_act_diff_y, INSERT_VALUES, act_diff_y);CHKERRQ(ierr); // SET UP MU ierr = DMCreateLocalVector(da, &local_mu);CHKERRQ(ierr); ierr = DMGlobalToLocalBegin(da, mu, INSERT_VALUES, local_mu);CHKERRQ(ierr); ierr = DMGlobalToLocalEnd(da, mu, INSERT_VALUES, local_mu);CHKERRQ(ierr); PetscScalar **local_mu_arr; DMDAVecGetArray(da, local_mu, &local_mu_arr); for (j = nStart; j < nStart + n; j++) { for (i = mStart; i < mStart + m; i++) { local_mu_arr[j][i] = sin(coords[j][i].x)*(sin(coords[j][i].y)) + 2; //cos(coords[j][i].x + coords[j][i].y) + 4; // local_mu_arr[j][i] = 1; } } DMDAVecRestoreArray(da, local_mu, &local_mu_arr); ierr = DMLocalToGlobalBegin(da, local_mu, INSERT_VALUES, mu);CHKERRQ(ierr); ierr = DMLocalToGlobalEnd(da, local_mu, INSERT_VALUES, mu);CHKERRQ(ierr); // SET UP DxxMU ierr = DMCreateLocalVector(da, &local_dxxmu);CHKERRQ(ierr); ierr = DMGlobalToLocalBegin(da, dxxmu, INSERT_VALUES, local_dxxmu);CHKERRQ(ierr); ierr = DMGlobalToLocalEnd(da, dxxmu, INSERT_VALUES, local_dxxmu);CHKERRQ(ierr); PetscScalar **local_dxxmu_arr; DMDAVecGetArray(da, local_dxxmu, &local_dxxmu_arr); for (j = nStart; j < nStart + n; j++) { for (i = mStart; i < mStart + m; i++) { local_dxxmu_arr[j][i] = 0; //(-sin(coords[j][i].x + coords[j][i].y) * cos(coords[j][i].x)) + //((cos(coords[j][i].x + coords[j][i].y) + 4) * (-sin(coords[j][i].x))); // local_dxxmu_arr[j][i] = -sin(coords[j][i].x); } } DMDAVecRestoreArray(da, local_dxxmu, &local_dxxmu_arr); ierr = DMLocalToGlobalBegin(da, local_dxxmu, INSERT_VALUES, dxxmu);CHKERRQ(ierr); ierr = DMLocalToGlobalEnd(da, local_dxxmu, INSERT_VALUES, dxxmu);CHKERRQ(ierr); // SET UP DyyMU ierr = DMCreateLocalVector(da, &local_dyymu);CHKERRQ(ierr); ierr = DMGlobalToLocalBegin(da, dyymu, INSERT_VALUES, local_dyymu);CHKERRQ(ierr); ierr = DMGlobalToLocalEnd(da, dyymu, INSERT_VALUES, local_dyymu);CHKERRQ(ierr); PetscScalar **local_dyymu_arr; DMDAVecGetArray(da, local_dyymu, &local_dyymu_arr); for (j = nStart; j < nStart + n; j++) { for (i = mStart; i < mStart + m; i++) { local_dyymu_arr[j][i] = 0; //(-sin(coords[j][i].x + coords[j][i].y) * (-sin(coords[j][i].y))) + //((cos(coords[j][i].x + coords[j][i].y) + 4) * (-cos(coords[j][i].y))); // local_dyymu_arr[j][i] = -cos(coords[j][i].y); } } DMDAVecRestoreArray(da, local_dyymu, &local_dyymu_arr); ierr = DMLocalToGlobalBegin(da, local_dyymu, INSERT_VALUES, dyymu);CHKERRQ(ierr); ierr = DMLocalToGlobalEnd(da, local_dyymu, INSERT_VALUES, dyymu);CHKERRQ(ierr); // derivative calculations & error calculations if(COEFFICIENT_SOLVE) { t2 = MPI_Wtime(); ierr = Dmuyy_2d(diff_y, grid, mu, mult_y, da);CHKERRQ(ierr); t3 = MPI_Wtime(); ierr = Dmuxx_2d(diff_x, grid, mu, mult_x, da);CHKERRQ(ierr); t4 = MPI_Wtime(); PetscPrintf(PETSC_COMM_WORLD, "Ny: %5i Spacing: % .5e Log of Spacing: % .5e ", y_len, mult_y, log2(mult_y)); // I used to have %15! calculate_two_norm(grid_error_diff, diff_y, dyymu, num_grid_entries); // PetscPrintf(PETSC_COMM_WORLD, "Nx: %5i Spacing: % .5e Log of Spacing: % .5e ", x_len, mult_x, log2(mult_x)); PetscPrintf(PETSC_COMM_WORLD, " Nx: %5i Spacing: % .5e Log of Spacing: % .5e ", x_len, mult_x, log2(mult_x)); calculate_two_norm(grid_error_diff, diff_x, dxxmu, num_grid_entries); } else { t2 = MPI_Wtime(); ierr = Dyy_2d(diff_y, grid, mult_y, da);CHKERRQ(ierr); t3 = MPI_Wtime(); ierr = Dxx_2d(diff_x, grid, mult_x, da);CHKERRQ(ierr); t4 = MPI_Wtime(); PetscPrintf(PETSC_COMM_WORLD, "Ny: %5i Spacing: % .5e Log of Spacing: % .5e ", y_len, mult_y, log2(mult_y)); // I used to have %15! calculate_two_norm(grid_error_diff, diff_y, act_diff_y, num_grid_entries); //PetscPrintf(PETSC_COMM_WORLD, "Nx: %5i Spacing: % .5e Log of Spacing: % .5e ", x_len, mult_x, log2(mult_x)); PetscPrintf(PETSC_COMM_WORLD, " Nx: %5i Spacing: % .5e Log of Spacing: % .5e ", x_len, mult_x, log2(mult_x)); calculate_two_norm(grid_error_diff, diff_x, act_diff_x, num_grid_entries); } t5 = MPI_Wtime(); // writeVec(grid, "grid_file"); // writeVec(diff_x, "calc_diff_x_file"); // writeVec(diff_y, "calc_diff_y_file"); // writeVec(act_diff_x, "actual_diff_x_file"); // writeVec(act_diff_y, "actual_diff_y_file"); // FIXME make sure all Vecs and DMs are being destroyed - go to other functions as well! ierr = VecDestroy(&grid);CHKERRQ(ierr); ierr = VecDestroy(&diff_y);CHKERRQ(ierr); ierr = VecDestroy(&diff_x);CHKERRQ(ierr); ierr = VecDestroy(&act_diff_y);CHKERRQ(ierr); ierr = VecDestroy(&act_diff_x);CHKERRQ(ierr); ierr = VecDestroy(&grid_error_diff);CHKERRQ(ierr); ierr = VecDestroy(&local_grid);CHKERRQ(ierr); ierr = VecDestroy(&local_act_diff_y);CHKERRQ(ierr); ierr = VecDestroy(&local_act_diff_x);CHKERRQ(ierr); ierr = VecDestroy(&mu);CHKERRQ(ierr); ierr = VecDestroy(&dxxmu);CHKERRQ(ierr); ierr = VecDestroy(&dyymu);CHKERRQ(ierr); ierr = VecDestroy(&local_mu);CHKERRQ(ierr); ierr = VecDestroy(&local_dxxmu);CHKERRQ(ierr); ierr = VecDestroy(&local_dyymu);CHKERRQ(ierr); //ierr = DMDestroy(&cda);CHKERRQ(ierr); ierr = DMDestroy(&da);CHKERRQ(ierr); t6 = MPI_Wtime(); PetscPrintf(PETSC_COMM_WORLD, "\nTime spent setting up and filling grid/actual derivative Vecs: % 8g\n", t2 - t1); PetscPrintf(PETSC_COMM_WORLD, "Time spent calculating 2Dy derivative: % 8g\n", t3 - t2); PetscPrintf(PETSC_COMM_WORLD, "Time spent calculating 2Dx derivative: % 8g\n", t4 - t3); PetscPrintf(PETSC_COMM_WORLD, "Time spent calculating norms: % 8g\n", t5 - t4); PetscPrintf(PETSC_COMM_WORLD, "Total time for this iteration: % 8g\n\n", t6 - t1); return ierr; } /* Function: MMSTest() * ------------------- * */ PetscErrorCode MMSTest() { PetscErrorCode ierr = 0; PetscInt n = STARTING_GRID_SPACING, min = MIN_GRID_POINT, max = MAX_GRID_POINT, x_len = NUM_X_PTS, y_len = NUM_Y_PTS; PetscScalar x_min = X_MIN, x_max = X_MAX, y_max = Y_MAX, y_min = Y_MIN; assert(n > 2); PetscPrintf(PETSC_COMM_WORLD, "1-D 1ST DERIVATIVES\n"); for(int i = 0; i < NUM_GRID_SPACE_CALCULATIONS; i++) { PetscPrintf(PETSC_COMM_WORLD, "Iteration: %15i ", i+1); ierr = calculate_Dx_1d(n, min, max);CHKERRQ(ierr); n = ((n - 1) * 2) + 1; } PetscPrintf(PETSC_COMM_WORLD, "1-D 2ND DERIVATIVES\n"); for(int i = 0; i < NUM_2ND_GRID_SPACE_CALCULATIONS; i++) { PetscPrintf(PETSC_COMM_WORLD, "Iteration: %15i ", i+1); ierr = calculate_Dxx_1d(n, min, max);CHKERRQ(ierr); n = ((n - 1) * 2) + 1; } PetscPrintf(PETSC_COMM_WORLD, "2-D 1ST DERIVATIVES\n"); assert(x_len > 3); assert(y_len > 3); for(int i = 0; i < NUM_2D_GRID_SPACE_CALCULATIONS; i++) { PetscPrintf(PETSC_COMM_WORLD, "Iteration: %15i ", i+1); calculate_Dx_Dy_2D(x_len, y_len, x_max, x_min, y_max, y_min); x_len = ((x_len - 1) * 2) + 1; y_len = ((y_len - 1) * 2) + 1; } PetscPrintf(PETSC_COMM_WORLD, "2-D 2ND DERIVATIVES\n"); x_len = NUM_X_PTS; y_len = NUM_Y_PTS; x_min = X_MIN; x_max = X_MAX; y_max = Y_MAX; y_min = Y_MIN; assert(x_len > 3); assert(y_len > 3); for(int i = 0; i < NUM_2D_2ND_GRID_SPACE_CALCULATIONS; i++) { PetscPrintf(PETSC_COMM_WORLD, "Iteration: %15i ", i+1); calculate_Dxx_Dyy_2D(x_len, y_len, x_max, x_min, y_max, y_min); x_len = ((x_len - 1) * 2) + 1; y_len = ((y_len - 1) * 2) + 1; } PetscPrintf(PETSC_COMM_WORLD, "\n"); return ierr; } /* Function: setRHS_R * ------------------ * */ PetscErrorCode setRHS_R(Vec &RHS, const Vec &r, const PetscScalar &h_11, const PetscScalar alpha_R, const DM &da) { PetscMPIInt rank; MPI_Comm_rank(PETSC_COMM_WORLD, &rank); PetscErrorCode ierr = 0; PetscInt m, n, mStart, nStart, j, i, M = NULL, N = NULL, ristart, riend; PetscScalar v; DMDAGetInfo(da, NULL, &M, &N,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL); DMDAGetCorners(da, &mStart, &nStart, 0, &m, &n, 0); ierr = VecGetOwnershipRange(r,&ristart,&riend);CHKERRQ(ierr); for(i = ristart; i < riend; i++) { ierr = VecGetValues(r,1,&i,&v);CHKERRQ(ierr); v = v * h_11 * alpha_R; ierr = VecSetValues(r,1,&i,&v,INSERT_VALUES);CHKERRQ(ierr); } ierr = VecAssemblyBegin(r);CHKERRQ(ierr); ierr = VecAssemblyEnd(r);CHKERRQ(ierr); //ierr = VecView(r,PETSC_VIEWER_STDOUT_WORLD);CHKERRQ(ierr); // VecScatter routine! IMPORTANT! VecScatter scatter; // scatter context IS from,to; // index sets that define the scatter int idx_from[M], idx_to[M]; for(i = 0; i < M; i++) { idx_from[i] = i; } for(i = 0; i < M; i++) { idx_to[i] = i + ((N-1) * M); } AO ao; DMDAGetAO(da,&ao); AOApplicationToPetsc(ao,M,idx_to); ISCreateGeneral(PETSC_COMM_SELF,M,idx_from,PETSC_COPY_VALUES,&from); ISCreateGeneral(PETSC_COMM_SELF,M,idx_to,PETSC_COPY_VALUES,&to); VecScatterCreate(r,from,RHS,to,&scatter); // gx = source vector, gy = destination vector VecScatterBegin(scatter,r,RHS,INSERT_VALUES,SCATTER_FORWARD); VecScatterEnd(scatter,r,RHS,INSERT_VALUES,SCATTER_FORWARD); //VecView(RHS,PETSC_VIEWER_STDOUT_WORLD); ISDestroy(&from); ISDestroy(&to); VecScatterDestroy(&scatter); // PRINT OUT RHS /* Vec local_RHS; ierr = DMCreateLocalVector(da, &local_RHS);CHKERRQ(ierr); ierr = DMGlobalToLocalBegin(da, RHS, INSERT_VALUES, local_RHS);CHKERRQ(ierr); ierr = DMGlobalToLocalEnd(da, RHS, INSERT_VALUES, local_RHS);CHKERRQ(ierr); PetscScalar **local_RHS_arr; DMDAVecGetArray(da, local_RHS, &local_RHS_arr); for (j = nStart; j < nStart + n; j++) { for (i = mStart; i < mStart + m; i++) { PetscPrintf(PETSC_COMM_SELF, "%i: [%i][%i] = %g\n", rank, j, i, local_RHS_arr[j][i]); } } DMDAVecRestoreArray(da, local_RHS, &local_RHS_arr); ierr = DMLocalToGlobalBegin(da, local_RHS, INSERT_VALUES, RHS);CHKERRQ(ierr); ierr = DMLocalToGlobalEnd(da, local_RHS, INSERT_VALUES, RHS);CHKERRQ(ierr); VecDestroy(&local_RHS); */ return ierr; } /* Function: setRHS_B * ------------------ * */ PetscErrorCode setRHS_B(Vec &RHS, const Vec &b, const PetscScalar &h_11, const PetscScalar alpha_B, const DM &da) { PetscMPIInt rank; MPI_Comm_rank(PETSC_COMM_WORLD, &rank); PetscErrorCode ierr = 0; PetscInt m, n, mStart, nStart, j, i, M = NULL, N = NULL, bistart, biend; PetscScalar v; DMDAGetInfo(da, NULL, &M, &N,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL); DMDAGetCorners(da, &mStart, &nStart, 0, &m, &n, 0); ierr = VecGetOwnershipRange(b,&bistart,&biend);CHKERRQ(ierr); for(i = bistart; i < biend; i++) { ierr = VecGetValues(b,1,&i,&v);CHKERRQ(ierr); v = v * h_11 * alpha_B; ierr = VecSetValues(b,1,&i,&v,INSERT_VALUES);CHKERRQ(ierr); } ierr = VecAssemblyBegin(b);CHKERRQ(ierr); ierr = VecAssemblyEnd(b);CHKERRQ(ierr); //ierr = VecView(b,PETSC_VIEWER_STDOUT_WORLD);CHKERRQ(ierr); // VecScatter routine! IMPORTANT! VecScatter scatter; // scatter context IS from,to; // index sets that define the scatter int idx_from[N], idx_to[N]; for(i = 0; i < N; i++) { idx_from[i] = i; } for(i = 0; i < N; i++) { idx_to[i] = i * M + (M-1); } AO ao; DMDAGetAO(da,&ao); AOApplicationToPetsc(ao,N,idx_to); ISCreateGeneral(PETSC_COMM_SELF,N,idx_from,PETSC_COPY_VALUES,&from); ISCreateGeneral(PETSC_COMM_SELF,N,idx_to,PETSC_COPY_VALUES,&to); VecScatterCreate(b,from,RHS,to,&scatter); // gx = source vector, gy = destination vector VecScatterBegin(scatter,b,RHS,INSERT_VALUES,SCATTER_FORWARD); VecScatterEnd(scatter,b,RHS,INSERT_VALUES,SCATTER_FORWARD); //VecView(RHS,PETSC_VIEWER_STDOUT_WORLD); ISDestroy(&from); ISDestroy(&to); VecScatterDestroy(&scatter); // PRINT OUT RHS /* Vec local_RHS; ierr = DMCreateLocalVector(da, &local_RHS);CHKERRQ(ierr); ierr = DMGlobalToLocalBegin(da, RHS, INSERT_VALUES, local_RHS);CHKERRQ(ierr); ierr = DMGlobalToLocalEnd(da, RHS, INSERT_VALUES, local_RHS);CHKERRQ(ierr); PetscScalar **local_RHS_arr; DMDAVecGetArray(da, local_RHS, &local_RHS_arr); for (j = nStart; j < nStart + n; j++) { for (i = mStart; i < mStart + m; i++) { PetscPrintf(PETSC_COMM_SELF, "%i: [%i][%i] = %g\n", rank, j, i, local_RHS_arr[j][i]); } } DMDAVecRestoreArray(da, local_RHS, &local_RHS_arr); ierr = DMLocalToGlobalBegin(da, local_RHS, INSERT_VALUES, RHS);CHKERRQ(ierr); ierr = DMLocalToGlobalEnd(da, local_RHS, INSERT_VALUES, RHS);CHKERRQ(ierr); VecDestroy(&local_RHS); */ return ierr; } /* Function: setRHS_T * -------------- * */ PetscErrorCode setRHS_T(Vec &RHS, const Vec &g, const PetscScalar &h_11, const PetscScalar alpha_T, const DM &da) { PetscMPIInt rank; MPI_Comm_rank(PETSC_COMM_WORLD, &rank); PetscErrorCode ierr = 0; PetscInt m, n, mStart, nStart, j, i, M = NULL, N = NULL, gistart, giend; PetscScalar v; DMDAGetInfo(da, NULL, &M, &N,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL); DMDAGetCorners(da, &mStart, &nStart, 0, &m, &n, 0); ierr = VecGetOwnershipRange(g,&gistart,&giend);CHKERRQ(ierr); for(i = gistart; i < giend; i++) { ierr = VecGetValues(g,1,&i,&v);CHKERRQ(ierr); v = (v + i) * (1/h_11) * alpha_T; //v = (double) i; ierr = VecSetValues(g,1,&i,&v,INSERT_VALUES);CHKERRQ(ierr); } ierr = VecAssemblyBegin(g);CHKERRQ(ierr); ierr = VecAssemblyEnd(g);CHKERRQ(ierr); //ierr = VecView(g,PETSC_VIEWER_STDOUT_WORLD);CHKERRQ(ierr); // VecScatter routine! IMPORTANT! VecScatter scatter; // scatter context IS from,to; // index sets that define the scatter //int idx_from[] = {0,1,2,3,4}, idx_to[] = {0,11,22,33,44}; int idx_from[N], idx_to[N]; for(i = 0; i < N; i++) { idx_from[i] = i; } for(i = 0; i < N; i++) { idx_to[i] = i * M; } AO ao; DMDAGetAO(da,&ao); AOApplicationToPetsc(ao,N,idx_to); ISCreateGeneral(PETSC_COMM_SELF,N,idx_from,PETSC_COPY_VALUES,&from); ISCreateGeneral(PETSC_COMM_SELF,N,idx_to,PETSC_COPY_VALUES,&to); VecScatterCreate(g,from,RHS,to,&scatter); // gx = source vector, gy = destination vector VecScatterBegin(scatter,g,RHS,INSERT_VALUES,SCATTER_FORWARD); VecScatterEnd(scatter,g,RHS,INSERT_VALUES,SCATTER_FORWARD); //VecView(RHS,PETSC_VIEWER_STDOUT_WORLD); ISDestroy(&from); ISDestroy(&to); VecScatterDestroy(&scatter); // PRINT OUT RHS /* Vec local_RHS; ierr = DMCreateLocalVector(da, &local_RHS);CHKERRQ(ierr); ierr = DMGlobalToLocalBegin(da, RHS, INSERT_VALUES, local_RHS);CHKERRQ(ierr); ierr = DMGlobalToLocalEnd(da, RHS, INSERT_VALUES, local_RHS);CHKERRQ(ierr); PetscScalar **local_RHS_arr; DMDAVecGetArray(da, local_RHS, &local_RHS_arr); for (j = nStart; j < nStart + n; j++) { for (i = mStart; i < mStart + m; i++) { PetscPrintf(PETSC_COMM_SELF, "%i: [%i][%i] = %g\n", rank, j, i, local_RHS_arr[j][i]); } } DMDAVecRestoreArray(da, local_RHS, &local_RHS_arr); ierr = DMLocalToGlobalBegin(da, local_RHS, INSERT_VALUES, RHS);CHKERRQ(ierr); ierr = DMLocalToGlobalEnd(da, local_RHS, INSERT_VALUES, RHS);CHKERRQ(ierr); VecDestroy(&local_RHS); */ return ierr; } /* Function: Dy_2d_Boundary * ---------------------------------- * 1st derivative solve in the y-direction for 2-D. * * diff_y - the output Vec (it will hold the calculated derivative on the boundary in y-direction) * grid - the input Vec (it holds the function values to draw from) * dy - the spacing between each point in the y-direction * da - DMDA object */ PetscErrorCode Dy_2d_Boundary(Vec &diff_y, Vec &grid, PetscScalar dy, DM &da) { PetscErrorCode ierr = 0; PetscInt m, n, mStart, nStart, j, i, M, N; DMDAGetInfo(da,NULL,&M,&N,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL); Vec local_diff_y, local_grid; PetscScalar** local_diff_y_arr; PetscScalar** local_grid_arr; ierr = DMCreateLocalVector(da, &local_diff_y);CHKERRQ(ierr); ierr = DMCreateLocalVector(da, &local_grid);CHKERRQ(ierr); ierr = DMDAVecGetArray(da, local_diff_y, &local_diff_y_arr);CHKERRQ(ierr); ierr = DMGlobalToLocalBegin(da, grid, INSERT_VALUES, local_grid);CHKERRQ(ierr); ierr = DMGlobalToLocalEnd(da, grid, INSERT_VALUES, local_grid);CHKERRQ(ierr); ierr = DMDAVecGetArray(da, local_grid, &local_grid_arr);CHKERRQ(ierr); ierr = DMDAGetCorners(da, &mStart, &nStart, 0, &m, &n, 0);CHKERRQ(ierr); for (j = nStart; j < nStart + n; j++) { for (i = mStart; i < mStart + m; i++) { if (j > 0 && j < N - 1 && i > 0 && i < M - 1) { local_diff_y_arr[j][i] = 0; } else if (j == 0) { local_diff_y_arr[j][i] = -(-1.5 * local_grid_arr[0][i] + 2.0 * local_grid_arr[1][i] - 0.5 * local_grid_arr[2][i])/ dy; } else if (j == N - 1) { local_diff_y_arr[j][i] = (0.5 * local_grid_arr[N-3][i] - 2.0 * local_grid_arr[N-2][i] + 1.5 * local_grid_arr[N-1][i]) / dy; } } } ierr = DMDAVecRestoreArray(da, local_diff_y, &local_diff_y_arr);CHKERRQ(ierr); ierr = DMDAVecRestoreArray(da, local_grid, &local_grid_arr);CHKERRQ(ierr); ierr = DMLocalToGlobalBegin(da, local_diff_y, INSERT_VALUES, diff_y);CHKERRQ(ierr); ierr = DMLocalToGlobalEnd(da, local_diff_y, INSERT_VALUES, diff_y);CHKERRQ(ierr); VecDestroy(&local_diff_y); VecDestroy(&local_grid); return ierr; } /* Function: Dx_2d_Boundary * ---------------------------------- * * diff_x - the output Vec (it will hold the calculated derivative on the boundary in x-direction) * grid - the input Vec (it holds the function values to draw from) * dx - the spacing between each point in the x-direction * da - DMDA object */ PetscErrorCode Dx_2d_Boundary(Vec &diff_x, Vec &grid, PetscScalar dx, DM &da) { PetscErrorCode ierr = 0; PetscInt m, n, mStart, nStart, j, i, M, N; DMDAGetInfo(da,NULL,&M,&N,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL); Vec local_diff_x, local_grid; PetscScalar** local_diff_x_arr; PetscScalar** local_grid_arr; ierr = DMCreateLocalVector(da, &local_diff_x);CHKERRQ(ierr); ierr = DMCreateLocalVector(da, &local_grid);CHKERRQ(ierr); ierr = DMDAVecGetArray(da, local_diff_x, &local_diff_x_arr);CHKERRQ(ierr); ierr = DMGlobalToLocalBegin(da, grid, INSERT_VALUES, local_grid);CHKERRQ(ierr); ierr = DMGlobalToLocalEnd(da, grid, INSERT_VALUES, local_grid);CHKERRQ(ierr); ierr = DMDAVecGetArray(da, local_grid, &local_grid_arr); CHKERRQ(ierr); ierr = DMDAGetCorners(da, &mStart, &nStart, 0, &m, &n, 0);CHKERRQ(ierr); for (j = nStart; j < nStart + n; j++) { for (i = mStart; i < mStart + m; i++) { if (i > 0 && i < M - 1 && j > 0 && j < N - 1) {local_diff_x_arr[j][i] = 0; } else if (i == 0) { local_diff_x_arr[j][i] = -(-1.5 * local_grid_arr[j][0] + 2.0 * local_grid_arr[j][1] - 0.5 * local_grid_arr[j][2])/ dx; } else if (i == M - 1) { local_diff_x_arr[j][i] = (0.5 * local_grid_arr[j][M-3] - 2.0 * local_grid_arr[j][M-2] + 1.5 * local_grid_arr[j][M-1]) / dx; } } } ierr = DMDAVecRestoreArray(da, local_diff_x, &local_diff_x_arr);CHKERRQ(ierr); ierr = DMDAVecRestoreArray(da, local_grid, &local_grid_arr);CHKERRQ(ierr); ierr = DMLocalToGlobalBegin(da, local_diff_x, INSERT_VALUES, diff_x);CHKERRQ(ierr); ierr = DMLocalToGlobalEnd(da, local_diff_x, INSERT_VALUES, diff_x);CHKERRQ(ierr); VecDestroy(&local_diff_x); VecDestroy(&local_grid); return ierr; } PetscErrorCode multiplyByHinvx(Vec &out, Vec &in, PetscScalar h, PetscInt order, AppCtx* ctx) { PetscErrorCode ierr = 0; ierr = VecSet(out, 0);CHKERRQ(ierr); if(order == 2) { PetscInt m, n, mStart, nStart, j, i, M, N; DMDAGetInfo(ctx->da,NULL,&M,&N,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL); Vec local_out, local_in; PetscScalar** local_out_arr; PetscScalar** local_in_arr; ierr = DMCreateLocalVector(ctx->da, &local_out);CHKERRQ(ierr); ierr = DMCreateLocalVector(ctx->da, &local_in);CHKERRQ(ierr); ierr = DMDAVecGetArray(ctx->da, local_out, &local_out_arr);CHKERRQ(ierr); ierr = DMGlobalToLocalBegin(ctx->da, in, INSERT_VALUES, local_in);CHKERRQ(ierr); ierr = DMGlobalToLocalEnd(ctx->da, in, INSERT_VALUES, local_in);CHKERRQ(ierr); ierr = DMDAVecGetArray(ctx->da, local_in, &local_in_arr); CHKERRQ(ierr); ierr = DMDAGetCorners(ctx->da, &mStart, &nStart, 0, &m, &n, 0);CHKERRQ(ierr); for (j = nStart; j < nStart + n; j++) { for (i = mStart; i < mStart + m; i++) { if (j > 0 && j < N - 1) local_out_arr[j][i] = 1/h * local_in_arr[j][i]; else local_out_arr[j][i] = 2/h * local_in_arr[j][i]; /* else if (i == 0) { //local_out_arr[j][i] = -(-1.5 * local_in_arr[j][0] + //2.0 * local_in_arr[j][1] - 0.5 * local_in_arr[j][2])/ h; } else if (i == M - 1) { local_out_arr[j][i] = (0.5 * local_in_arr[j][M-3] - 2.0 * local_in_arr[j][M-2] + 1.5 * local_in_arr[j][M-1]) / h; }*/ } } ierr = DMDAVecRestoreArray(ctx->da, local_out, &local_out_arr);CHKERRQ(ierr); ierr = DMDAVecRestoreArray(ctx->da, local_in, &local_in_arr);CHKERRQ(ierr); ierr = DMLocalToGlobalBegin(ctx->da, local_out, INSERT_VALUES, out);CHKERRQ(ierr); ierr = DMLocalToGlobalEnd(ctx->da, local_out, INSERT_VALUES, out);CHKERRQ(ierr); VecDestroy(&local_out); VecDestroy(&local_in); return ierr; } else if (order == 4) { } return -1; } PetscErrorCode multiplyBy_BSx_IyT_s(Vec &ADisp2, Vec& mu, Vec &fx, PetscScalar h) { //, string& Stype, string& Btype) { PetscErrorCode ierr = 0; return ierr; } PetscErrorCode SetLeftToMult(Vec& ADisp1, Vec& mu, Vec& temp, AppCtx* ctx) { PetscErrorCode ierr = 0; PetscInt m, n, mStart, nStart, j, i, M, N; DMDAGetInfo(ctx->da, NULL, &M, &N,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL); Vec local_ADisp1, local_mu, local_temp; PetscScalar **local_ADisp1_arr; PetscScalar** local_mu_arr; PetscScalar** local_temp_arr; ierr = DMCreateLocalVector(ctx->da, &local_ADisp1);CHKERRQ(ierr); ierr = DMCreateLocalVector(ctx->da, &local_mu);CHKERRQ(ierr); ierr = DMCreateLocalVector(ctx->da, &local_temp);CHKERRQ(ierr); DMDAGetCorners(ctx->da, &mStart, &nStart, 0, &m, &n, 0); //rank PetscMPIInt rank; MPI_Comm_rank(PETSC_COMM_WORLD, &rank); ierr = DMGlobalToLocalBegin(ctx->da, ADisp1, INSERT_VALUES, local_ADisp1);CHKERRQ(ierr); ierr = DMGlobalToLocalEnd(ctx->da, ADisp1, INSERT_VALUES, local_ADisp1);CHKERRQ(ierr); ierr = DMDAVecGetArray(ctx->da, local_ADisp1, &local_ADisp1_arr);CHKERRQ(ierr); ierr = DMGlobalToLocalBegin(ctx->da, temp, INSERT_VALUES, local_temp);CHKERRQ(ierr); ierr = DMGlobalToLocalEnd(ctx->da, temp, INSERT_VALUES, local_temp);CHKERRQ(ierr); ierr = DMDAVecGetArray(ctx->da, local_temp, &local_temp_arr); CHKERRQ(ierr); ierr = DMGlobalToLocalBegin(ctx->da, mu, INSERT_VALUES, local_mu);CHKERRQ(ierr); ierr = DMGlobalToLocalEnd(ctx->da, mu, INSERT_VALUES, local_mu);CHKERRQ(ierr); ierr = DMDAVecGetArray(ctx->da, local_mu, &local_mu_arr); CHKERRQ(ierr); j = nStart + n - 1; for (i = mStart; i < mStart + m; i++) { local_ADisp1_arr[j][i] = local_mu_arr[j][i] * local_temp_arr[j][i]; } DMDAVecRestoreArray(ctx->da, local_ADisp1, &local_ADisp1_arr); ierr = DMLocalToGlobalBegin(ctx->da, local_ADisp1, INSERT_VALUES, ADisp1);CHKERRQ(ierr); ierr = DMLocalToGlobalEnd(ctx->da, local_ADisp1, INSERT_VALUES, ADisp1);CHKERRQ(ierr); VecDestroy(&local_ADisp1); VecDestroy(&local_mu); VecDestroy(&local_temp); return ierr; } PetscErrorCode setRHS_L(Vec &RHS, const Vec &fx, const PetscScalar &h_11, const PetscScalar alpha_L, const DM &da) { PetscErrorCode ierr = 0; /* PetscMPIInt rank; MPI_Comm_rank(PETSC_COMM_WORLD, &rank); Vec temp; Vec rhs_disp1; ierr = VecDuplicate(fx, &rhs_disp1);CHKERRQ(ierr); ierr = VecDuplicate(fx, &temp);CHKERRQ(ierr); ierr = VecSet(rhs_disp1, 0);CHKERRQ(ierr); ierr = multiplyByHinvx(temp, fx, da, 2, ctx);CHKERRQ(ierr); Vec rhs_disp2; ierr = VecDuplicate(fx, &rhs_disp2);CHKERRQ(ierr); ierr = VecSet(rhs_disp2, 0);CHKERRQ(ierr); */ return ierr; } /* Function: MyMatMult * ------------------- * * */ PetscErrorCode MyMatMult(Mat A, Vec fx, Vec ans) { PetscErrorCode ierr = 0; void *ptr; AppCtx *ctx; MatShellGetContext(A,&ptr); ctx = (AppCtx*)ptr; // Below is what the multiplication operation should do! Vec sum = NULL, dmuxx = NULL, dmuyy = NULL; ierr = VecDuplicate(fx, &sum); ierr = VecDuplicate(fx, &dmuxx); ierr = VecDuplicate(fx, &dmuyy); ierr = Dmuxx_2d(dmuxx, fx, ctx->mu, ctx->dx_spacing, ctx->da);CHKERRQ(ierr); //writeVec(dmuxx, "Uxx"); ierr = Dmuyy_2d(dmuyy, fx, ctx->mu, ctx->dy_spacing, ctx->da);CHKERRQ(ierr); //writeVec(dmuyy, "Uxx"); PetscScalar one = 1.0; ierr = VecAXPY(dmuyy, one, dmuxx);CHKERRQ(ierr); ierr = VecCopy(dmuyy, ans);CHKERRQ(ierr); Vec Dx, Dy, DxDyBoundary; ierr = VecDuplicate(fx, &Dx); ierr = VecDuplicate(fx, &Dy); ierr = VecDuplicate(fx, &DxDyBoundary); ierr = Dx_2d_Boundary(Dx, fx, ctx->dx_spacing, ctx->da);CHKERRQ(ierr); ierr = Dy_2d_Boundary(Dy, fx, ctx->dx_spacing, ctx->da);CHKERRQ(ierr); ierr = VecAXPY(Dy, one, Dx);CHKERRQ(ierr); ierr = VecCopy(Dy, DxDyBoundary);CHKERRQ(ierr); ierr = VecAXPY(dmuyy, one, DxDyBoundary);CHKERRQ(ierr); ierr = VecCopy(dmuyy, ans);CHKERRQ(ierr); // BOUNDARY CONDITIONS Vec out; ierr = VecDuplicate(fx, &out);CHKERRQ(ierr); ierr = VecSet(out, 0);CHKERRQ(ierr); Vec temp; ierr = VecDuplicate(fx, &temp);CHKERRQ(ierr); ierr = VecSet(temp, 0);CHKERRQ(ierr); // DISPLACEMENT // LEFT BOUNDARY Vec ADisp1; ierr = VecDuplicate(fx, &ADisp1);CHKERRQ(ierr); ierr = VecSet(ADisp1, 0);CHKERRQ(ierr); ierr = multiplyByHinvx(temp, fx, ctx->dx_spacing, ctx->order, ctx);CHKERRQ(ierr); ierr = SetLeftToMult(ADisp1, ctx->mu, temp, ctx);CHKERRQ(ierr); Vec ADisp2; ierr = VecDuplicate(fx, &ADisp1);CHKERRQ(ierr); ierr = VecSet(ADisp1, 0);CHKERRQ(ierr); //string Stype = ""; // = ctx.Stype //string Btype = ""; ierr = multiplyBy_BSx_IyT_s(ADisp2, ctx->mu, fx, ctx->dx_spacing);//, Stype, Btype); // RIGHT BOUNDARY // TRACTION // TOP BOUNDARY // BOTTOM BOUNDARY //print /* PetscInt m, n, mStart, nStart, j, i, M = NULL, N = NULL; DMDAGetInfo(ctx->da, NULL, &M, &N,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL); DMDAGetCorners(ctx->da, &mStart, &nStart, 0, &m, &n, 0); PetscMPIInt rank; MPI_Comm_rank(PETSC_COMM_WORLD, &rank); Vec DxDyBoundary_print; ierr = DMCreateLocalVector(ctx->da, &DxDyBoundary_print);CHKERRQ(ierr); ierr = DMGlobalToLocalBegin(ctx->da, DxDyBoundary, INSERT_VALUES, DxDyBoundary_print);CHKERRQ(ierr); ierr = DMGlobalToLocalEnd(ctx->da, DxDyBoundary, INSERT_VALUES, DxDyBoundary_print);CHKERRQ(ierr); PetscScalar **DxDyBoundary_print_arr; DMDAVecGetArray(ctx->da, DxDyBoundary_print, &DxDyBoundary_print_arr); for (j = nStart; j < nStart + n; j++) { for (i = mStart; i < mStart + m; i++) { PetscPrintf(PETSC_COMM_SELF, "%i: [%i][%i] = %g\n", rank, j, i, DxDyBoundary_print_arr[j][i]); } } DMDAVecRestoreArray(ctx->da, DxDyBoundary_print, &DxDyBoundary_print_arr); ierr = DMLocalToGlobalBegin(ctx->da, DxDyBoundary_print, INSERT_VALUES, DxDyBoundary);CHKERRQ(ierr); ierr = DMLocalToGlobalEnd(ctx->da, DxDyBoundary_print, INSERT_VALUES, DxDyBoundary);CHKERRQ(ierr); VecDestroy(&DxDyBoundary_print); */ //writeVec(DxDyBoundary, "DxDyBoundary"); //endprint //FIXME!!!! DO WE ADD THE BOUNDARY TO EXISTING VALUES FROM THE DERIVATIVE, OR DO WE ZERO // THEM OUT BEFORE ADDING??? //calculate RHS with 1st derivative on borders //Vec RHS = NULL; //ierr = VecDuplicate(fx, &RHS); //PetscScalar h_11 = 1; //PetscScalar alpha_R = 2; //setRHS_R(RHS, ans, h_11, // alpha_R, ctx->da); //setRHS_L(RHS, ans, h_11, // alpha_R, ctx->da); //setRHS_T(RHS, ans, h_11, // alpha_R, ctx->da); //setRHS_B(RHS, ans, h_11, // alpha_R, ctx->da); ierr = VecDestroy(&Dx);CHKERRQ(ierr); ierr = VecDestroy(&Dy);CHKERRQ(ierr); ierr = VecDestroy(&DxDyBoundary);CHKERRQ(ierr); ierr = VecDestroy(&sum);CHKERRQ(ierr); ierr = VecDestroy(&dmuxx);CHKERRQ(ierr); ierr = VecDestroy(&dmuyy);CHKERRQ(ierr); return ierr; } PetscErrorCode testMyMatMult() { PetscErrorCode ierr = 0; AppCtx ctx; PetscScalar x_len = NUM_X_PTS, y_len = NUM_Y_PTS; PetscScalar x_min = X_MIN, x_max = X_MAX, y_max = Y_MAX, y_min = Y_MIN; for(int i = 0; i < NUM_2D_2ND_GRID_SPACE_CALCULATIONS; i++) { x_len = ((x_len - 1) * 2) + 1; y_len = ((y_len - 1) * 2) + 1; } PetscPrintf(PETSC_COMM_WORLD, "Test for MyMatMult\n"); PetscInt i = 0, j = 0, mStart = 0, m = 0, nStart = 0, n = 0, fx_istart, fx_iend, dx_start, dx_end, dy_start, dy_end; PetscScalar v = 0; Vec fx = NULL, dx = NULL, dy = NULL, a_dx = NULL, a_dy = NULL, fx_err = NULL, /* vectors */ local_coords = NULL, local_fx = NULL, local_a_dx = NULL, local_a_dy = NULL, /* mu = NULL, */ local_mu = NULL, dxxmu = NULL, local_dxxmu = NULL, dyymu = NULL, local_dyymu = NULL, ans = NULL, a_ans = NULL; // first row, global vecs, second row, local vecs, third row, mu and 2nd derivatives // last row, answer vector PetscInt num_entries = (x_len) * (y_len); //total number of entries on the grid ctx.dx_spacing = ((PetscReal)(x_max - x_min))/(x_len - 1); // spacing in the x direction ctx.dy_spacing = ((PetscReal)(y_max - y_min))/(y_len - 1); // spacing in the y direction ctx.n_x = x_len; ctx.n_y = y_len; ctx.alphaDx = -4/ctx.dx_spacing; ctx.alphaDy = -4/ctx.dy_spacing; ctx.alphaT = -1; ctx.beta = 1; ctx.order = 2; DMDACoor2d **coords; DMDACreate2d(PETSC_COMM_WORLD, DMDA_BOUNDARY_NONE, DMDA_BOUNDARY_NONE, DMDA_STENCIL_BOX, ctx.n_x, ctx.n_y, PETSC_DECIDE, PETSC_DECIDE, 1, 2, NULL, NULL, &ctx.da); DMDASetUniformCoordinates(ctx.da, x_min, x_max, y_min, y_max, 0.0, 0.0); DMGetCoordinateDM(ctx.da, &ctx.cda); DMGetCoordinatesLocal(ctx.da, &local_coords); DMDAVecGetArray(ctx.cda, local_coords, &coords); DMDAGetCorners(ctx.cda, &mStart, &nStart, 0, &m, &n, 0); // allows us to have information about the DMDA DMDALocalInfo info; ierr = DMDAGetLocalInfo(ctx.da, &info); ierr = DMCreateGlobalVector(ctx.da, &fx); ierr = VecDuplicate(fx, &dx);CHKERRQ(ierr); ierr = VecDuplicate(fx, &dy);CHKERRQ(ierr); ierr = VecDuplicate(fx, &a_dx);CHKERRQ(ierr); ierr = VecDuplicate(fx, &a_dy);CHKERRQ(ierr); ierr = VecDuplicate(fx, &fx_err);CHKERRQ(ierr); ierr = VecDuplicate(fx, &ctx.mu);CHKERRQ(ierr); ierr = VecDuplicate(fx, &dxxmu);CHKERRQ(ierr); ierr = VecDuplicate(fx, &dyymu);CHKERRQ(ierr); ierr = VecDuplicate(fx, &ans);CHKERRQ(ierr); ierr = VecDuplicate(fx, &a_ans);CHKERRQ(ierr); PetscMPIInt rank; MPI_Comm_rank(PETSC_COMM_WORLD, &rank); // Set up fx to pull values from ierr = DMCreateLocalVector(ctx.da, &local_fx);CHKERRQ(ierr); ierr = DMGlobalToLocalBegin(ctx.da, fx, INSERT_VALUES, local_fx);CHKERRQ(ierr); ierr = DMGlobalToLocalEnd(ctx.da, fx, INSERT_VALUES, local_fx);CHKERRQ(ierr); PetscScalar **local_fx_arr; DMDAVecGetArray(ctx.da, local_fx, &local_fx_arr); for (j = nStart; j < nStart + n; j++) { for (i = mStart; i < mStart + m; i++) { //PetscPrintf(PETSC_COMM_SELF, "%i: (coords[%i][%i].x, coords[%i][%i].y) = (%g, %g)\n)", rank, j, i, j, i, coords[j][i].x, coords[j][i].y); // local_fx_arr[j][i] = coords[j][i].y; // local_fx_arr[j][i] = (coords[j][i].x * coords[j][i].x * coords[j][i].x) + (coords[j][i].y * coords[j][i].y * coords[j][i].y); // local_fx_arr[j][i] = coords[j][i].x; local_fx_arr[j][i] = MMS_uA(coords[j][i].x, coords[j][i].y); // local_fx_arr[j][i] = cos(coords[j][i].x) * sin(coords[j][i].y); // PetscPrintf(PETSC_COMM_SELF, "%i: [%i][%i] = %g\n", rank, j, i, local_grid_arr[j][i]); } } DMDAVecRestoreArray(ctx.da, local_fx, &local_fx_arr); ierr = DMLocalToGlobalBegin(ctx.da, local_fx, INSERT_VALUES, fx);CHKERRQ(ierr); ierr = DMLocalToGlobalEnd(ctx.da, local_fx, INSERT_VALUES, fx);CHKERRQ(ierr); //set up a_dx ierr = DMCreateLocalVector(ctx.da, &local_a_dx);CHKERRQ(ierr); ierr = DMGlobalToLocalBegin(ctx.da, a_dx, INSERT_VALUES, local_a_dx);CHKERRQ(ierr); ierr = DMGlobalToLocalEnd(ctx.da, a_dx, INSERT_VALUES, local_a_dx);CHKERRQ(ierr); PetscScalar **local_a_dx_arr; DMDAVecGetArray(ctx.da, local_a_dx, &local_a_dx_arr); for (j = nStart; j < nStart + n; j++) { for (i = mStart; i < mStart + m; i++) { // PetscPrintf(PETSC_COMM_SELF, "%i: (coords[%i][%i].x, coords[%i][%i].y) = (%g, %g)\n)", rank, j, i, j, i, coords[j][i].x, coords[j][i].y); // local_act_diff_x_arr[j][i] = coords[j][i].x; local_a_dx_arr[j][i] = MMS_uA_dx(coords[j][i].x, coords[j][i].y); //local_a_dx_arr[j][i] = -sin(coords[j][i].x); // PetscPrintf(PETSC_COMM_SELF, "%i: [%i][%i] = %g\n", rank, j, i, local_act_diff_x_arr[j][i]); // local_act_diff_x_arr[j][i] = (6 * coords[j][i].x); } } DMDAVecRestoreArray(ctx.da, local_a_dx, &local_a_dx_arr); ierr = DMLocalToGlobalBegin(ctx.da, local_a_dx, INSERT_VALUES, a_dx);CHKERRQ(ierr); ierr = DMLocalToGlobalEnd(ctx.da, local_a_dx, INSERT_VALUES, a_dx);CHKERRQ(ierr); // SET UP ACT_DIFF_Y ierr = DMCreateLocalVector(ctx.da, &local_a_dy);CHKERRQ(ierr); ierr = DMGlobalToLocalBegin(ctx.da, a_dy, INSERT_VALUES, local_a_dy);CHKERRQ(ierr); ierr = DMGlobalToLocalEnd(ctx.da, a_dy, INSERT_VALUES, local_a_dy);CHKERRQ(ierr); PetscScalar **local_a_dy_arr; DMDAVecGetArray(ctx.da, local_a_dy, &local_a_dy_arr); for (j = nStart; j < nStart + n; j++) { for (i = mStart; i < mStart + m; i++) { // PetscPrintf(PETSC_COMM_SELF, "%i: (coords[%i][%i].x, coords[%i][%i].y) = (%g, %g)\n)", rank, j, i, j, i, coords[j][i].x, coords[j][i].y); // local_act_diff_y_arr[j][i] = (6 * coords[j][i].y); //local_a_dy_arr[j][i] = -cos(coords[j][i].y); local_a_dy_arr[j][i] = MMS_uA_dy(coords[j][i].x, coords[j][i].y); } } DMDAVecRestoreArray(ctx.da, local_a_dy, &local_a_dy_arr); ierr = DMLocalToGlobalBegin(ctx.da, local_a_dy, INSERT_VALUES, a_dy);CHKERRQ(ierr); ierr = DMLocalToGlobalEnd(ctx.da, local_a_dy, INSERT_VALUES, a_dy);CHKERRQ(ierr); // SET UP MU ierr = DMCreateLocalVector(ctx.da, &local_mu);CHKERRQ(ierr); ierr = DMGlobalToLocalBegin(ctx.da, ctx.mu, INSERT_VALUES, local_mu);CHKERRQ(ierr); ierr = DMGlobalToLocalEnd(ctx.da, ctx.mu, INSERT_VALUES, local_mu);CHKERRQ(ierr); PetscScalar **local_mu_arr; DMDAVecGetArray(ctx.da, local_mu, &local_mu_arr); for (j = nStart; j < nStart + n; j++) { for (i = mStart; i < mStart + m; i++) { local_mu_arr[j][i] = MMS_mu(coords[j][i].x, coords[j][i].y); //local_mu_arr[j][i] = sin(coords[j][i].x) * sin(coords[j][i].y) + 2; // local_mu_arr[j][i] = 1; } } DMDAVecRestoreArray(ctx.da, local_mu, &local_mu_arr); ierr = DMLocalToGlobalBegin(ctx.da, local_mu, INSERT_VALUES, ctx.mu);CHKERRQ(ierr); ierr = DMLocalToGlobalEnd(ctx.da, local_mu, INSERT_VALUES, ctx.mu);CHKERRQ(ierr); // SET UP DxxMU ierr = DMCreateLocalVector(ctx.da, &local_dxxmu);CHKERRQ(ierr); ierr = DMGlobalToLocalBegin(ctx.da, dxxmu, INSERT_VALUES, local_dxxmu);CHKERRQ(ierr); ierr = DMGlobalToLocalEnd(ctx.da, dxxmu, INSERT_VALUES, local_dxxmu);CHKERRQ(ierr); PetscScalar **local_dxxmu_arr; DMDAVecGetArray(ctx.da, local_dxxmu, &local_dxxmu_arr); for (j = nStart; j < nStart + n; j++) { for (i = mStart; i < mStart + m; i++) { local_dxxmu_arr[j][i] = MMS_uA_dmuxx(coords[j][i].x, coords[j][i].y); //local_dxxmu_arr[j][i] = (-sin(coords[j][i].x + coords[j][i].y) * cos(coords[j][i].x)) + // ((cos(coords[j][i].x + coords[j][i].y) + 4) * (-sin(coords[j][i].x))); // local_dxxmu_arr[j][i] = -sin(coords[j][i].x); } } DMDAVecRestoreArray(ctx.da, local_dxxmu, &local_dxxmu_arr); ierr = DMLocalToGlobalBegin(ctx.da, local_dxxmu, INSERT_VALUES, dxxmu);CHKERRQ(ierr); ierr = DMLocalToGlobalEnd(ctx.da, local_dxxmu, INSERT_VALUES, dxxmu);CHKERRQ(ierr); // SET UP DyyMU ierr = DMCreateLocalVector(ctx.da, &local_dyymu);CHKERRQ(ierr); ierr = DMGlobalToLocalBegin(ctx.da, dyymu, INSERT_VALUES, local_dyymu);CHKERRQ(ierr); ierr = DMGlobalToLocalEnd(ctx.da, dyymu, INSERT_VALUES, local_dyymu);CHKERRQ(ierr); PetscScalar **local_dyymu_arr; DMDAVecGetArray(ctx.da, local_dyymu, &local_dyymu_arr); for (j = nStart; j < nStart + n; j++) { for (i = mStart; i < mStart + m; i++) { local_dyymu_arr[j][i] = MMS_uA_dmuyy(coords[j][i].x, coords[j][i].y); //local_dyymu_arr[j][i] = (-sin(coords[j][i].x + coords[j][i].y) * (-sin(coords[j][i].y))) + // ((cos(coords[j][i].x + coords[j][i].y) + 4) * (-cos(coords[j][i].y))); // local_dyymu_arr[j][i] = -cos(coords[j][i].y); } } DMDAVecRestoreArray(ctx.da, local_dyymu, &local_dyymu_arr); ierr = DMLocalToGlobalBegin(ctx.da, local_dyymu, INSERT_VALUES, dyymu);CHKERRQ(ierr); ierr = DMLocalToGlobalEnd(ctx.da, local_dyymu, INSERT_VALUES, dyymu);CHKERRQ(ierr); //writeVec(fx,"fx"); //Vec dfx; //ierr = VecDuplicate(fx, &dfx); //ierr = Dx_2d(dfx, fx, ctx.dx_spacing, ctx.da); //writeVec(dfx, "dfx"); PetscInt vec_size = NULL; VecGetLocalSize(fx, &vec_size); // set up linear solve context (matrices, etc.) Mat H_Shell; //MatCreateAIJ(MPI_COMM_WORLD,info.xm,info.ym,info.mx,info.my,7,NULL,3,NULL,&(user.H)); MatCreateShell(PETSC_COMM_WORLD, vec_size, vec_size, num_entries, num_entries,(void*)&ctx,&H_Shell); MatShellSetOperation(H_Shell,MATOP_MULT, (void(*)(void))MyMatMult); MatMult(H_Shell, fx, ans); //writeVec(ans, "ans"); // calculate analytical answer ierr = VecCopy(a_dy, a_ans);CHKERRQ(ierr); PetscScalar one = 1.0; ierr = VecAXPY(a_ans, one, a_dx); calculate_two_norm(fx_err, ans, a_ans, num_entries); MatDestroy(&H_Shell); VecDestroy(&fx); VecDestroy(&dx); VecDestroy(&dy); VecDestroy(&a_dx); VecDestroy(&a_dy); VecDestroy(&fx_err); //VecDestroy(&local_coords); VecDestroy(&local_fx); VecDestroy(&local_a_dx); VecDestroy(&local_a_dy); VecDestroy(&local_mu); VecDestroy(&dxxmu); VecDestroy(&local_dxxmu); VecDestroy(&dyymu); VecDestroy(&local_dyymu); VecDestroy(&ans); VecDestroy(&a_ans); VecDestroy(&ctx.mu); DMDestroy(&ctx.da); PetscPrintf(PETSC_COMM_WORLD, "\n"); return ierr; } /* Function: Solve_Linear_Equation * ------------------------------- * */ PetscErrorCode Solve_Linear_Equation() { PetscErrorCode ierr = 0; PetscInt num_x_pts = NUM_X_PTS, num_y_pts = NUM_Y_PTS; PetscScalar x_min = X_MINIMUM, x_max = X_MAXIMUM, y_max = Y_MAXIMUM, y_min = Y_MINIMUM; PetscInt i = 0, j = 0, mStart = 0, m = 0, nStart = 0, n = 0; PetscScalar v = 0, mult_x = 0, mult_y = 0, alpha_T = -1, alpha_B = -2, alpha_L = -3, alpha_R = -4, h_11 = 2; Vec grid = NULL, RHS = NULL, g = NULL, b = NULL, l = NULL, r = NULL, local_grid = NULL, local_RHS = NULL, local_coords = NULL; PetscInt num_grid_entries = (num_x_pts) * (num_y_pts); // total number of entries on the grid mult_x = ((PetscReal)(x_max - x_min))/(num_x_pts - 1); // spacing in the x direction mult_y = ((PetscReal)(y_max - y_min))/(num_y_pts - 1); // spacing in the y direction DM da; DM cda; DMDACoor2d **coords; // 2D array containing x and y data members ierr = DMDACreate2d(PETSC_COMM_WORLD,DMDA_BOUNDARY_NONE, DMDA_BOUNDARY_NONE, DMDA_STENCIL_BOX, num_x_pts, num_y_pts, PETSC_DECIDE, PETSC_DECIDE, 1, 2, NULL, NULL, &da); CHKERRQ(ierr); DMDASetUniformCoordinates(da, x_min, x_max, y_min, y_max, 0.0, 0.0); DMGetCoordinateDM(da, &cda); DMGetCoordinatesLocal(da, &local_coords); DMDAVecGetArray(cda, local_coords, &coords); DMDAGetCorners(cda, &mStart, &nStart, 0, &m, &n, 0); ierr = DMCreateGlobalVector(da,&grid); ierr = VecDuplicate(grid, &RHS);CHKERRQ(ierr); //FIXME PetscMPIInt rank; MPI_Comm_rank(PETSC_COMM_WORLD, &rank); // FILL GRID ierr = DMCreateLocalVector(da, &local_grid);CHKERRQ(ierr); ierr = DMGlobalToLocalBegin(da, grid, INSERT_VALUES, local_grid);CHKERRQ(ierr); ierr = DMGlobalToLocalEnd(da, grid, INSERT_VALUES, local_grid);CHKERRQ(ierr); PetscScalar **local_grid_arr; DMDAVecGetArray(da, local_grid, &local_grid_arr); for (j = nStart; j < nStart + n; j++) { for (i = mStart; i < mStart + m; i++) { local_grid_arr[j][i] = (coords[j][i].x); } } DMDAVecRestoreArray(da, local_grid, &local_grid_arr); ierr = DMLocalToGlobalBegin(da, local_grid, INSERT_VALUES, grid);CHKERRQ(ierr); ierr = DMLocalToGlobalEnd(da, local_grid, INSERT_VALUES, grid);CHKERRQ(ierr); //FILL RHS ierr = DMCreateLocalVector(da, &local_RHS);CHKERRQ(ierr); ierr = DMGlobalToLocalBegin(da, RHS, INSERT_VALUES, local_RHS);CHKERRQ(ierr); ierr = DMGlobalToLocalEnd(da, RHS, INSERT_VALUES, local_RHS);CHKERRQ(ierr); PetscScalar **local_RHS_arr; DMDAVecGetArray(da, local_RHS, &local_RHS_arr); for (j = nStart; j < nStart + n; j++) { for (i = mStart; i < mStart + m; i++) { local_RHS_arr[j][i] = 0; // PetscPrintf(PETSC_COMM_SELF, "%i: [%i][%i] = %g\n", rank, j, i, local_RHS_arr[j][i]); } } DMDAVecRestoreArray(da, local_RHS, &local_RHS_arr); ierr = DMLocalToGlobalBegin(da, local_RHS, INSERT_VALUES, RHS);CHKERRQ(ierr); ierr = DMLocalToGlobalEnd(da, local_RHS, INSERT_VALUES, RHS);CHKERRQ(ierr); // FILL g VecCreate(PETSC_COMM_WORLD,&g); VecSetSizes(g,PETSC_DECIDE,num_y_pts); VecSetFromOptions(g); PetscObjectSetName((PetscObject) g, "g"); VecSet(g,1.0); // FILL b VecCreate(PETSC_COMM_WORLD,&b); VecSetSizes(b,PETSC_DECIDE,num_y_pts); VecSetFromOptions(b); PetscObjectSetName((PetscObject) b, "b"); VecSet(b,1.0); // FILL l VecCreate(PETSC_COMM_WORLD,&l); VecSetSizes(l,PETSC_DECIDE,num_x_pts); VecSetFromOptions(l); PetscObjectSetName((PetscObject) l, "l"); VecSet(l,1.0); // FILL r VecCreate(PETSC_COMM_WORLD,&r); VecSetSizes(r,PETSC_DECIDE,num_x_pts); VecSetFromOptions(r); PetscObjectSetName((PetscObject) r, "r"); VecSet(r,1.0); ierr = setRHS_T(RHS, g, h_11, alpha_T, da);CHKERRQ(ierr); ierr = setRHS_B(RHS, b, h_11, alpha_B, da);CHKERRQ(ierr); ierr = setRHS_L(RHS, l, h_11, alpha_L, da);CHKERRQ(ierr); ierr = setRHS_R(RHS, r, h_11, alpha_R, da);CHKERRQ(ierr); // PRINT RHS /* Vec local_RHS_print; ierr = DMCreateLocalVector(da, &local_RHS_print);CHKERRQ(ierr); ierr = DMGlobalToLocalBegin(da, RHS, INSERT_VALUES, local_RHS_print);CHKERRQ(ierr); ierr = DMGlobalToLocalEnd(da, RHS, INSERT_VALUES, local_RHS_print);CHKERRQ(ierr); PetscScalar **local_RHS_print_arr; DMDAVecGetArray(da, local_RHS_print, &local_RHS_print_arr); for (j = nStart; j < nStart + n; j++) { for (i = mStart; i < mStart + m; i++) { PetscPrintf(PETSC_COMM_SELF, "%i: [%i][%i] = %g\n", rank, j, i, local_RHS_print_arr[j][i]); } } DMDAVecRestoreArray(da, local_RHS_print, &local_RHS_print_arr); ierr = DMLocalToGlobalBegin(da, local_RHS_print, INSERT_VALUES, RHS);CHKERRQ(ierr); ierr = DMLocalToGlobalEnd(da, local_RHS_print, INSERT_VALUES, RHS);CHKERRQ(ierr); VecDestroy(&local_RHS_print); // writeVec(RHS, "RHS"); */ VecDestroy(&grid); VecDestroy(&RHS); VecDestroy(&g); VecDestroy(&b); VecDestroy(&l); VecDestroy(&r); VecDestroy(&local_grid); VecDestroy(&local_RHS); DMDestroy(&da); DMDestroy(&cda); return ierr; } PetscErrorCode testMultiplyByHinvx() { PetscErrorCode ierr = 0; AppCtx ctx; PetscScalar x_len = NUM_X_PTS, y_len = NUM_Y_PTS; PetscScalar x_min = X_MIN, x_max = X_MAX, y_max = Y_MAX, y_min = Y_MIN; Vec fx = NULL, dx = NULL, /* vectors */ temp, local_coords = NULL, local_fx = NULL; for(int i = 0; i < NUM_2D_2ND_GRID_SPACE_CALCULATIONS; i++) { x_len = ((x_len - 1) * 2) + 1; y_len = ((y_len - 1) * 2) + 1; } PetscInt num_entries = (x_len) * (y_len); //total number of entries on the grid ctx.dx_spacing = ((PetscReal)(x_max - x_min))/(x_len - 1); // spacing in the x direction ctx.dy_spacing = ((PetscReal)(y_max - y_min))/(y_len - 1); // spacing in the y direction ctx.n_x = x_len; ctx.n_y = y_len; ctx.alphaDx = -4/ctx.dx_spacing; ctx.alphaDy = -4/ctx.dy_spacing; ctx.alphaT = -1; ctx.beta = 1; ctx.order = 2; DMDACoor2d **coords; DMDACreate2d(PETSC_COMM_WORLD, DMDA_BOUNDARY_NONE, DMDA_BOUNDARY_NONE, DMDA_STENCIL_BOX, ctx.n_x, ctx.n_y, PETSC_DECIDE, PETSC_DECIDE, 1, 2, NULL, NULL, &ctx.da); PetscInt i = 0, j = 0, mStart = 0, m = 0, nStart = 0, n = 0, fx_istart, fx_iend, dx_start, dx_end, dy_start, dy_end; PetscScalar v = 0; ierr = DMCreateGlobalVector(ctx.da, &fx);CHKERRQ(ierr); ierr = VecDuplicate(fx, &temp);CHKERRQ(ierr); DMDASetUniformCoordinates(ctx.da, x_min, x_max, y_min, y_max, 0.0, 0.0); DMGetCoordinateDM(ctx.da, &ctx.cda); DMGetCoordinatesLocal(ctx.da, &local_coords); DMDAVecGetArray(ctx.cda, local_coords, &coords); DMDAGetCorners(ctx.cda, &mStart, &nStart, 0, &m, &n, 0); // allows us to have information about the DMDA DMDALocalInfo info; ierr = DMDAGetLocalInfo(ctx.da, &info); PetscMPIInt rank; MPI_Comm_rank(PETSC_COMM_WORLD, &rank); // Set up fx to pull values from ierr = DMCreateLocalVector(ctx.da, &local_fx);CHKERRQ(ierr); ierr = DMGlobalToLocalBegin(ctx.da, fx, INSERT_VALUES, local_fx);CHKERRQ(ierr); ierr = DMGlobalToLocalEnd(ctx.da, fx, INSERT_VALUES, local_fx);CHKERRQ(ierr); PetscScalar **local_fx_arr; DMDAVecGetArray(ctx.da, local_fx, &local_fx_arr); for (j = nStart; j < nStart + n; j++) { for (i = mStart; i < mStart + m; i++) { local_fx_arr[j][i] = MMS_uA(coords[j][i].x, coords[j][i].y); } } DMDAVecRestoreArray(ctx.da, local_fx, &local_fx_arr); ierr = DMLocalToGlobalBegin(ctx.da, local_fx, INSERT_VALUES, fx);CHKERRQ(ierr); ierr = DMLocalToGlobalEnd(ctx.da, local_fx, INSERT_VALUES, fx);CHKERRQ(ierr); ierr = multiplyByHinvx(temp, fx, ctx.dx_spacing, ctx.order, &ctx);CHKERRQ(ierr); writeVec(temp, "Hinvx_C"); return ierr; } /* Function: main * -------------- * */ int main(int argc,char **argv) { PetscErrorCode ierr = 0; PetscInitialize(&argc,&argv,(char*)0,NULL); //ierr = MMSTest();CHKERRQ(ierr); //ierr = Solve_Linear_Equation();CHKERRQ(ierr); //testMyMatMult(); testMultiplyByHinvx(); PetscFinalize(); return ierr; }
42.986425
154
0.65533
28e4dd08d57b29ea49ce0da075a25972d028a369
599
cpp
C++
ares/msx/cartridge/slot.cpp
moon-chilled/Ares
909fb098c292f8336d0502dc677050312d8b5c81
[ "0BSD" ]
7
2020-07-25T11:44:39.000Z
2021-01-29T13:21:31.000Z
ares/msx/cartridge/slot.cpp
jchw-forks/ares
d78298a1e95fd0ce65feabfd4f13b60e31210a7a
[ "0BSD" ]
null
null
null
ares/msx/cartridge/slot.cpp
jchw-forks/ares
d78298a1e95fd0ce65feabfd4f13b60e31210a7a
[ "0BSD" ]
1
2021-03-22T16:15:30.000Z
2021-03-22T16:15:30.000Z
CartridgeSlot cartridgeSlot{"Cartridge Slot"}; CartridgeSlot expansionSlot{"Expansion Slot"}; CartridgeSlot::CartridgeSlot(string name) : name(name) { } auto CartridgeSlot::load(Node::Object parent) -> void { port = parent->append<Node::Port>(name); port->setFamily(interface->name()); port->setType("Cartridge"); port->setAllocate([&](auto name) { return cartridge.allocate(port); }); port->setConnect([&] { return cartridge.connect(); }); port->setDisconnect([&] { return cartridge.disconnect(); }); } auto CartridgeSlot::unload() -> void { cartridge.disconnect(); port = {}; }
29.95
73
0.692821
28e68ae27d59696ba3a543ed75abea88f0146efa
7,627
cpp
C++
src/FirebaseCommunication.cpp
floryt/floryt-credential-provider
c6fba1aa791e192927a6f7a53a7db1b6cd398e14
[ "Apache-2.0" ]
5
2017-05-10T15:06:43.000Z
2017-11-25T09:49:27.000Z
src/FirebaseCommunication.cpp
floryt/floryt-credential-provider
c6fba1aa791e192927a6f7a53a7db1b6cd398e14
[ "Apache-2.0" ]
14
2017-05-02T21:43:37.000Z
2017-06-17T11:44:36.000Z
src/FirebaseCommunication.cpp
floryt/floryt-credential-provider
c6fba1aa791e192927a6f7a53a7db1b6cd398e14
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <fstream> #include <stdlib.h> #include <windows.h> #include <thread> #include "FirebaseCommunication.h" #include <atlbase.h> #include <atlconv.h> #include <vector> FirebaseCommunication::FirebaseCommunication() { http = new HTTPclient(); cv = false; } EXIT_TYPE FirebaseCommunication::TryToConnect(LPCWSTR username) { //post - "ping" to check if server is a avalible EXIT_TYPE to_return; dbugLog::log_write("TryToConnect", "attempting to connect"); //------------------------------ping------------------------------ //setting the data std::string answer = "_"; //so if the request failed we will se "_" in the log //***********getting text from config********* std::string firebase_function = config::get_val("GETcheckConnectionFooName"); //******************************************** char* data = _strdup(http->createJson(username)); //"{\"username\":\"Steven\",\"computerUID\":\"123456789\"}"; //from const char* to char* std::string tempd(data); dbugLog::log_write("AuthenticationPost", "created json: " + tempd + "length: " + std::to_string(tempd.length())); if (tempd.length() > 0) //to prevent exception { if (data[0] == ' ') //fixing bug { data[0] = '{'; dbugLog::log_write("AuthenticationPost", "[FIXED] fixed json: " + std::string(data)); } } else { dbugLog::log_write("AuthenticationPost", "[ERROR] json is empty"); } bool isError = false; //initial CV cv = false; //starting thread std::thread tempt(&FirebaseCommunication::ThreadWait, this, firebase_function, data, std::ref(answer), std::ref(isError)); tempt.detach(); //waiting for response while (cv == false) { dbugLog::log_write("TryToConnect", "no response yet"); Sleep(1000); } //---after reciving response std::string ans(answer); dbugLog::log_write("TryToConnect", "recived: " + ans); if (isError) { dbugLog::log_write("TryToConnect", "could'nt connect"); to_return = cant_connect_to_server; } else { //processig the data if (strcmp(answer.c_str(), "OK") == 0) { dbugLog::log_write("TryToConnect", "connection succeeded"); to_return = connection_to_server_succeeded; } else { dbugLog::log_write("TryToConnect", "connection failed"); to_return = cant_connect_to_server; } } return to_return; } EXIT_TYPE FirebaseCommunication::AuthenticationPostMock(LPCWSTR username, LPCWSTR* recived_message, POST_STEP step) { *recived_message = L"my message"; return authentication_succeeded; } EXIT_TYPE FirebaseCommunication::TryToConnectMock() { return connection_to_server_succeeded; } //works for all types of requests we need here EXIT_TYPE FirebaseCommunication::AuthenticationPost(LPCWSTR username, LPCWSTR* recived_message, POST_STEP step) //recived_message: a pointer to enter the message from admin { //post with json EXIT_TYPE to_return; (*recived_message) = L"_"; //no need of config - log purpose only. std::string mes = "no step"; if (step == obtain_user_identity) { mes = "obtainIdentityVerification"; } else if (step == obtain_admin_permission) { mes = "obtainAdminPermission"; } dbugLog::log_write("AuthenticationPost", "attempting to Authenticate: step " + mes); //------------------------------post------------------------------ //setting the data std::string answer = "__"; cv = false; std::string firebase_function = ""; if (step == obtain_user_identity) { //***********getting text from config********* firebase_function = config::get_val("POSTobtainUserIdentityFooName"); //******************************************** } else if (step == obtain_admin_permission) { //***********getting text from config********* firebase_function = config::get_val("POSTobtainAdminPermissionFooName"); //******************************************** } bool isError = false; char* data = _strdup(http->createJson(username)); //"{\"username\":\"Steven\",\"computerUID\":\"123456789\"}"; //from const char* to char* std::string tempd(data); dbugLog::log_write("AuthenticationPost", "created json: " + tempd + "length: "+ std::to_string(tempd.length())); if (tempd.length() > 0) //to prevent exception { if (data[0] == ' ') //fixing bug { data[0] = '{'; dbugLog::log_write("AuthenticationPost", "[FIXED] fixed json: " + std::string(data)); } } else { dbugLog::log_write("AuthenticationPost", "[ERROR] json is empty"); } //initial CV cv = false; //starting thread std::thread tempt(&FirebaseCommunication::ThreadWait, this, firebase_function, strdup(data), std::ref(answer), std::ref(isError)); tempt.detach(); //waiting for response while (cv == false) { dbugLog::log_write("AuthenticationPost", "no response yet"); Sleep(1000); } //---after reciving response std::string ans(answer); dbugLog::log_write("AuthenticationPost", "got response: " + ans); if (isError) //it could be a timeout for example { if (strcmp((answer.substr(0, 11)).c_str(), "12002") == 0) { to_return = time_out; dbugLog::log_write("AuthenticationPost", "detedcet timeout"); } else { to_return = bad_request; //it's not a bad request but it will be handled the same way dbugLog::log_write("AuthenticationPost", "detedcet some error in request"); } } else { //processig the data if (strcmp((answer.substr(0, 11)).c_str(), "Bad Request") == 0) { dbugLog::log_write("AuthenticationPost", "connection failed: Bad request"); to_return = bad_request; } else //we got an actual data { std::string* message = new std::string(); (*message) = ""; bool isAccess = http->parseJSON((char*)ans.c_str(), message); //--parsing the message /*std::wstring stemp = s2ws(*message); LPCWSTR result = stemp.c_str();*/ if (message->size() == 2) //bug fix - message is "" { (*message) = ":)"; //recived no messgae. TODO- update field in struct dbugLog::log_write("AuthenticationPost", "detected message bug - recived empty message"); } std::wstring stemp = std::wstring(message->begin(), message->end()); //CASTING: string to lpcwstr LPCWSTR result = stemp.c_str(); (*recived_message) = result; dbugLog::log_write("AuthenticationPost", "message from admin: " + (*message)); if (isAccess) //access = true { dbugLog::log_write("AuthenticationPost", "step succeeded"); to_return = authentication_succeeded; } else { dbugLog::log_write("AuthenticationPost", "access denied"); to_return = access_denied; } } } return to_return; } std::wstring FirebaseCommunication::s2ws(const std::string& s) //TODO: move to helpers { int len; int slength = (int)s.length() + 1; len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0); wchar_t* buf = new wchar_t[len]; MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len); std::wstring r(buf); delete[] buf; return r; } FirebaseCommunication::~FirebaseCommunication() { dbugLog::log_write("~FirebaseCommunication", "distractor"); //delete _log; delete http; } void FirebaseCommunication::ThreadWait(std::string req_type, char* data, std::string &packet_buffer, bool& is_Error) { char* ans; bool isError = false; //if (req_type == "/connectivity_check") //TODO: send struct and return struct //{ // ans = http->GET(isError, _strdup(req_type.c_str())); //CASTING: string to char* // std::string str(ans); // packet_buffer = ans; //} std::vector<char> cstr(req_type.c_str(), req_type.c_str() + req_type.size() + 1); ans = http->POST(data, isError, _strdup(req_type.c_str())); std::string str(ans); packet_buffer = ans; is_Error = isError; cv = true; }
25.680135
172
0.65373
28e8e12c7fd4e9a32413e89bc05840b200afbfb8
2,939
hpp
C++
include/conjunctive.hpp
taboege/libpropcalc
b64dbf66a6d58fb8ec8e646530b482bbd96b0ba6
[ "Artistic-2.0" ]
1
2021-06-01T01:08:56.000Z
2021-06-01T01:08:56.000Z
include/conjunctive.hpp
taboege/libpropcalc
b64dbf66a6d58fb8ec8e646530b482bbd96b0ba6
[ "Artistic-2.0" ]
null
null
null
include/conjunctive.hpp
taboege/libpropcalc
b64dbf66a6d58fb8ec8e646530b482bbd96b0ba6
[ "Artistic-2.0" ]
null
null
null
/* * conjunctive.hpp - Clause and Conjunctive * * Copyright (C) 2019-2020 Tobias Boege * * This program is free software; you can redistribute it and/or * modify it under the terms of the Artistic License 2.0 * * 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 * Artistic License 2.0 for more details. */ #ifndef PROPCALC_CONJUNCTIVE_HPP #define PROPCALC_CONJUNCTIVE_HPP #include <propcalc/varmap.hpp> #include <propcalc/stream.hpp> #include <propcalc/assignment.hpp> namespace Propcalc { /** * A clause represents a collection of literals, that is a mapping of * variables to signs. A variable mapping to true is a positive literal, * one mapping to false a negative literal. * * Put another way, the value a variable maps to is the assignment to * that variable which would satisfy the clause. */ class Clause : public VarMap { public: /** Create a dummy clause on no variables. */ Clause(void) : VarMap() { } /** Create the any-false clause on the given variables. */ Clause(std::vector<VarRef> vars) : VarMap(vars) { } /** Initialize the mapping with the given data. */ Clause(std::initializer_list<std::pair<VarRef, bool>> il) : VarMap(il) { } /** Initialize the clause from a VarMap object. */ Clause(VarMap&& vm) : VarMap(vm) { } /** Flip all signs in the clause. */ Clause operator~(void) const { Clause neg(order); for (auto& v : order) neg[v] = !vmap.at(v); return neg; } /** * Evaluate the Clause on an Assignment. This uses the natural partial * assignment semantics, that is when a variable in the assignment is * not mentioned in the clause, this fact is ignored. Such a variable * cannot make the clause true. * * In particular an empty clause always yields false (the identity * element with respect to disjunction). */ bool eval(const Assignment& assign) const { for (auto v : assign.vars()) { if (exists(v) && (*this)[v] == assign[v]) return true; } return false; } }; namespace { [[maybe_unused]] std::ostream& operator<<(std::ostream& os, const Clause& cl) { os << "{ "; for (auto& v : cl.vars()) os << (cl[v] ? "" : "-") << v->name << " "; return os << "}"; } } class Conjunctive : public Stream<Clause> { public: /** * Evaluate the conjunction of clauses enumerated. If there is no * clause, returns true (the identity element with respect to * conjunction), as all clauses are satisfied. * * If you want to evaluate the Conjunctive multiple times, it must * be put into caching mode before the first clause is iterated.. */ bool eval(const Assignment& assign) { for (auto cl : *this) { if (!cl.eval(assign)) return false; } return true; } }; } #endif /* PROPCALC_CONJUNCTIVE_HPP */
29.686869
76
0.668935
28e99cb39fc64a5c13027faddbb0fd4894dcf6f0
2,865
cpp
C++
main.cpp
NexFarming/farm-a1-temp-control
d656aa3df838f14594eccf7c0a7e6b745b08af27
[ "MIT" ]
null
null
null
main.cpp
NexFarming/farm-a1-temp-control
d656aa3df838f14594eccf7c0a7e6b745b08af27
[ "MIT" ]
null
null
null
main.cpp
NexFarming/farm-a1-temp-control
d656aa3df838f14594eccf7c0a7e6b745b08af27
[ "MIT" ]
null
null
null
/* Copyright (c) 2021 NexFarming * All rights reserved * * Author: Tasnim Zotder * Git: git@github.com:NexFarming/farm-a1-temp-control.git */ #include <stdio.h> #include "hardware/adc.h" #include "hardware/gpio.h" #include "pico/binary_info.h" #include "pico/stdlib.h" const uint LED_PIN = 25; const uint DELAY_TIME = 1000; const float IDEAL_TEMP_MIN = 27.0f; const float IDEAL_TEMP_MAX = 30.0f; // relay pins for bulb const uint RELAY_PIN_0 = 10; // fan 0 const uint RELAY_PIN_1 = 11; // fan 1 const uint RELAY_PIN_2 = 12; // fan 2 const uint RELAY_PIN_3 = 13; // cooler 0 float get_room_temp() { adc_init(); adc_set_temp_sensor_enabled(true); adc_select_input(4); float temperature; float temp_sum = 0; const int loop_count = 10; for (size_t idx = 0; idx < loop_count; idx++) { uint16_t raw = adc_read(); const float conversion_factor = 3.3f / (1 << 12); float voltage = raw * conversion_factor; temperature = 27 - (voltage - 0.706) / 0.001721; temp_sum += temperature; sleep_ms(10); } temperature = temp_sum / loop_count; return temperature; } int control_relay(int relay_0, int relay_1, int relay_2, int relay_3) { // heaters gpio_put(RELAY_PIN_0, relay_0); gpio_put(RELAY_PIN_1, relay_1); gpio_put(RELAY_PIN_2, relay_2); // cooler(s) gpio_put(RELAY_PIN_3, relay_3); return 0; } int control_bulb(float temp) { printf("Temp: %f\n", get_room_temp()); if (temp >= IDEAL_TEMP_MIN && temp <= IDEAL_TEMP_MAX) { printf("status: in the range!\n"); control_relay(0, 0, 0, 0); gpio_put(LED_PIN, 1); } else if (temp < IDEAL_TEMP_MIN && (IDEAL_TEMP_MIN - temp) >= 2) { printf("status: below the range (X)\n"); control_relay(1, 1, 1, 0); for (size_t i = 0; i < DELAY_TIME / 120 + 1; i++) { gpio_put(LED_PIN, 0); sleep_ms(120 / 2); gpio_put(LED_PIN, 1); sleep_ms(120 / 2); } } else if (temp < IDEAL_TEMP_MIN && (IDEAL_TEMP_MIN - temp) < 2) { printf("status: below the range\n"); control_relay(1, 1, 0, 0); for (size_t i = 0; i < DELAY_TIME / 250 + 1; i++) { gpio_put(LED_PIN, 0); sleep_ms(250 / 2); gpio_put(LED_PIN, 1); sleep_ms(250 / 2); } } else if (temp > IDEAL_TEMP_MAX) { printf("status: above the range\n"); control_relay(0, 0, 0, 1); } return 0; } int main() { stdio_init_all(); printf("Farm Temperature Control\n"); gpio_init(LED_PIN); gpio_set_dir(LED_PIN, GPIO_OUT); // initialize relay pins gpio_init(RELAY_PIN_0); gpio_init(RELAY_PIN_1); gpio_init(RELAY_PIN_2); gpio_init(RELAY_PIN_3); gpio_set_dir(RELAY_PIN_0, GPIO_OUT); gpio_set_dir(RELAY_PIN_1, GPIO_OUT); gpio_set_dir(RELAY_PIN_2, GPIO_OUT); gpio_set_dir(RELAY_PIN_3, GPIO_OUT); while (1) { control_bulb(get_room_temp()); sleep_ms(DELAY_TIME); } }
22.92
71
0.649913
28ea17e10746395d1ce39607211a0cdb94805391
4,221
cpp
C++
core/3d/CCFrustum.cpp
DelinWorks/adxe
0f1ba3a086d744bb52e157e649fa986ae3c7ab05
[ "MIT" ]
76
2021-05-20T12:27:10.000Z
2022-03-23T15:27:42.000Z
core/3d/CCFrustum.cpp
DelinWorks/adxe
0f1ba3a086d744bb52e157e649fa986ae3c7ab05
[ "MIT" ]
171
2021-05-18T11:07:25.000Z
2022-03-29T20:53:27.000Z
core/3d/CCFrustum.cpp
DelinWorks/adxe
0f1ba3a086d744bb52e157e649fa986ae3c7ab05
[ "MIT" ]
42
2021-05-18T10:05:06.000Z
2022-03-22T05:40:56.000Z
/**************************************************************************** Copyright (c) 2014-2016 Chukong Technologies Inc. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. https://adxeproject.github.io/ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "3d/CCFrustum.h" #include "2d/CCCamera.h" NS_CC_BEGIN bool Frustum::initFrustum(const Camera* camera) { _initialized = true; createPlane(camera); return true; } bool Frustum::isOutOfFrustum(const AABB& aabb) const { if (_initialized) { Vec3 point; int plane = _clipZ ? 6 : 4; for (int i = 0; i < plane; i++) { const Vec3& normal = _plane[i].getNormal(); point.x = normal.x < 0 ? aabb._max.x : aabb._min.x; point.y = normal.y < 0 ? aabb._max.y : aabb._min.y; point.z = normal.z < 0 ? aabb._max.z : aabb._min.z; if (_plane[i].getSide(point) == PointSide::FRONT_PLANE) return true; } } return false; } bool Frustum::isOutOfFrustum(const OBB& obb) const { if (_initialized) { Vec3 point; int plane = _clipZ ? 6 : 4; Vec3 obbExtentX = obb._xAxis * obb._extents.x; Vec3 obbExtentY = obb._yAxis * obb._extents.y; Vec3 obbExtentZ = obb._zAxis * obb._extents.z; for (int i = 0; i < plane; i++) { const Vec3& normal = _plane[i].getNormal(); point = obb._center; point = normal.dot(obb._xAxis) > 0 ? point - obbExtentX : point + obbExtentX; point = normal.dot(obb._yAxis) > 0 ? point - obbExtentY : point + obbExtentY; point = normal.dot(obb._zAxis) > 0 ? point - obbExtentZ : point + obbExtentZ; if (_plane[i].getSide(point) == PointSide::FRONT_PLANE) return true; } } return false; } void Frustum::createPlane(const Camera* camera) { const Mat4& mat = camera->getViewProjectionMatrix(); // ref http://www.lighthouse3d.com/tutorials/view-frustum-culling/clip-space-approach-extracting-the-planes/ // extract frustum plane _plane[0].initPlane(-Vec3(mat.m[3] + mat.m[0], mat.m[7] + mat.m[4], mat.m[11] + mat.m[8]), (mat.m[15] + mat.m[12])); // left _plane[1].initPlane(-Vec3(mat.m[3] - mat.m[0], mat.m[7] - mat.m[4], mat.m[11] - mat.m[8]), (mat.m[15] - mat.m[12])); // right _plane[2].initPlane(-Vec3(mat.m[3] + mat.m[1], mat.m[7] + mat.m[5], mat.m[11] + mat.m[9]), (mat.m[15] + mat.m[13])); // bottom _plane[3].initPlane(-Vec3(mat.m[3] - mat.m[1], mat.m[7] - mat.m[5], mat.m[11] - mat.m[9]), (mat.m[15] - mat.m[13])); // top _plane[4].initPlane(-Vec3(mat.m[3] + mat.m[2], mat.m[7] + mat.m[6], mat.m[11] + mat.m[10]), (mat.m[15] + mat.m[14])); // near _plane[5].initPlane(-Vec3(mat.m[3] - mat.m[2], mat.m[7] - mat.m[6], mat.m[11] - mat.m[10]), (mat.m[15] - mat.m[14])); // far } NS_CC_END
40.980583
112
0.57285
28ec2f8060965f1042a092c1eee0b20d6470cf2d
5,576
hpp
C++
openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/boost/1.69.0-r0/boost_1_69_0/boost/python/to_python_value.hpp
sotaoverride/backup
ca53a10b72295387ef4948a9289cb78ab70bc449
[ "Apache-2.0" ]
null
null
null
openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/boost/1.69.0-r0/boost_1_69_0/boost/python/to_python_value.hpp
sotaoverride/backup
ca53a10b72295387ef4948a9289cb78ab70bc449
[ "Apache-2.0" ]
null
null
null
openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/boost/1.69.0-r0/boost_1_69_0/boost/python/to_python_value.hpp
sotaoverride/backup
ca53a10b72295387ef4948a9289cb78ab70bc449
[ "Apache-2.0" ]
null
null
null
// Copyright David Abrahams 2002. // Copyright Stefan Seefeld 2016. // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef boost_python_to_python_value_hpp_ #define boost_python_to_python_value_hpp_ #include <boost/mpl/if.hpp> #include <boost/mpl/or.hpp> #include <boost/python/converter/builtin_converters.hpp> #include <boost/python/converter/object_manager.hpp> #include <boost/python/converter/registered.hpp> #include <boost/python/converter/registry.hpp> #include <boost/python/converter/shared_ptr_to_python.hpp> #include <boost/python/detail/prefix.hpp> #include <boost/python/detail/type_traits.hpp> #include <boost/python/detail/value_arg.hpp> #include <boost/python/detail/value_is_shared_ptr.hpp> #include <boost/python/handle.hpp> #include <boost/python/refcount.hpp> #include <boost/python/tag.hpp> namespace boost { namespace python { namespace detail { #ifndef BOOST_PYTHON_NO_PY_SIGNATURES template <bool is_const_ref> struct object_manager_get_pytype { template <class U> static PyTypeObject const* get(U& (*)() = 0) { return converter::object_manager_traits<U>::get_pytype(); } }; template <> struct object_manager_get_pytype<true> { template <class U> static PyTypeObject const* get(U const& (*)() = 0) { return converter::object_manager_traits<U>::get_pytype(); } }; #endif template <class T> struct object_manager_to_python_value { typedef typename value_arg<T>::type argument_type; PyObject* operator()(argument_type) const; #ifndef BOOST_PYTHON_NO_PY_SIGNATURES typedef boost::mpl::bool_<is_handle<T>::value> is_t_handle; typedef boost::detail::indirect_traits::is_reference_to_const<T> is_t_const; PyTypeObject const* get_pytype() const { return get_pytype_aux((is_t_handle*)0); } inline static PyTypeObject const* get_pytype_aux(mpl::true_*) { return converter::object_manager_traits<T>::get_pytype(); } inline static PyTypeObject const* get_pytype_aux(mpl::false_*) { return object_manager_get_pytype<is_t_const::value>::get((T(*)())0); } #endif // This information helps make_getter() decide whether to try to // return an internal reference or not. I don't like it much, // but it will have to serve for now. BOOST_STATIC_CONSTANT(bool, uses_registry = false); }; template <class T> struct registry_to_python_value { typedef typename value_arg<T>::type argument_type; PyObject* operator()(argument_type) const; #ifndef BOOST_PYTHON_NO_PY_SIGNATURES PyTypeObject const* get_pytype() const { return converter::registered<T>::converters.to_python_target_type(); } #endif // This information helps make_getter() decide whether to try to // return an internal reference or not. I don't like it much, // but it will have to serve for now. BOOST_STATIC_CONSTANT(bool, uses_registry = true); }; template <class T> struct shared_ptr_to_python_value { typedef typename value_arg<T>::type argument_type; PyObject* operator()(argument_type) const; #ifndef BOOST_PYTHON_NO_PY_SIGNATURES PyTypeObject const* get_pytype() const { return get_pytype((boost::type<argument_type>*)0); } #endif // This information helps make_getter() decide whether to try to // return an internal reference or not. I don't like it much, // but it will have to serve for now. BOOST_STATIC_CONSTANT(bool, uses_registry = false); private: #ifndef BOOST_PYTHON_NO_PY_SIGNATURES template <class U> PyTypeObject const* get_pytype(boost::type<shared_ptr<U>&>*) const { return converter::registered<U>::converters.to_python_target_type(); } template <class U> PyTypeObject const* get_pytype(boost::type<const shared_ptr<U>&>*) const { return converter::registered<U>::converters.to_python_target_type(); } #if !defined(BOOST_NO_CXX11_SMART_PTR) template <class U> PyTypeObject const* get_pytype(boost::type<std::shared_ptr<U>&>*) const { return converter::registered<U>::converters.to_python_target_type(); } template <class U> PyTypeObject const* get_pytype(boost::type<const std::shared_ptr<U>&>*) const { return converter::registered<U>::converters.to_python_target_type(); } #endif #endif }; } // namespace detail template <class T> struct to_python_value : mpl::if_<detail::value_is_shared_ptr<T>, detail::shared_ptr_to_python_value<T>, typename mpl::if_< mpl::or_<converter::is_object_manager<T>, converter::is_reference_to_object_manager<T>>, detail::object_manager_to_python_value<T>, detail::registry_to_python_value<T>>::type>::type { }; // // implementation // namespace detail { template <class T> inline PyObject* registry_to_python_value<T>::operator()(argument_type x) const { return converter::registered<argument_type>::converters.to_python(&x); } template <class T> inline PyObject* object_manager_to_python_value<T>:: operator()(argument_type x) const { return python::upcast<PyObject>( python::xincref(get_managed_object(x, tag))); } template <class T> inline PyObject* shared_ptr_to_python_value<T>:: operator()(argument_type x) const { return converter::shared_ptr_to_python(x); } } // namespace detail } // namespace python } // namespace boost #endif
28.44898
80
0.713056
28ee2971e314ad6b1d93446ca500b09d146aa587
6,151
cpp
C++
taichi/ir/type_factory.cpp
gaoxinge/taichi
86d403f071b8505858763d4712b37cd71b89db91
[ "MIT" ]
1
2020-11-10T07:17:01.000Z
2020-11-10T07:17:01.000Z
taichi/ir/type_factory.cpp
gaoxinge/taichi
86d403f071b8505858763d4712b37cd71b89db91
[ "MIT" ]
1
2020-08-24T05:18:43.000Z
2020-08-24T05:18:43.000Z
taichi/ir/type_factory.cpp
gaoxinge/taichi
86d403f071b8505858763d4712b37cd71b89db91
[ "MIT" ]
null
null
null
#include "taichi/ir/type_factory.h" #include "taichi/ir/type_utils.h" TLANG_NAMESPACE_BEGIN TypeFactory &TypeFactory::get_instance() { static TypeFactory *type_factory = new TypeFactory; return *type_factory; } TypeFactory::TypeFactory() { } Type *TypeFactory::get_primitive_type(PrimitiveTypeID id) { std::lock_guard<std::mutex> _(mut_); if (primitive_types_.find(id) == primitive_types_.end()) { primitive_types_[id] = std::make_unique<PrimitiveType>(id); } return primitive_types_[id].get(); } Type *TypeFactory::get_tensor_type(std::vector<int> shape, Type *element) { auto encode = [](const std::vector<int> &shape) -> std::string { std::string s; for (int i = 0; i < (int)shape.size(); ++i) s += fmt::format(i == 0 ? "{}" : "_{}", std::to_string(shape[i])); return s; }; auto key = std::make_pair(encode(shape), element); if (tensor_types_.find(key) == tensor_types_.end()) { tensor_types_[key] = std::make_unique<TensorType>(shape, element); } return tensor_types_[key].get(); } Type *TypeFactory::get_pointer_type(Type *element, bool is_bit_pointer) { auto key = std::make_pair(element, is_bit_pointer); if (pointer_types_.find(key) == pointer_types_.end()) { pointer_types_[key] = std::make_unique<PointerType>(element, is_bit_pointer); } return pointer_types_[key].get(); } Type *TypeFactory::get_custom_int_type(int num_bits, bool is_signed, Type *compute_type) { auto key = std::make_tuple(num_bits, is_signed, compute_type); if (custom_int_types_.find(key) == custom_int_types_.end()) { custom_int_types_[key] = std::make_unique<CustomIntType>(num_bits, is_signed, compute_type); } return custom_int_types_[key].get(); } Type *TypeFactory::get_custom_float_type(Type *digits_type, Type *exponent_type, Type *compute_type, float64 scale) { auto key = std::make_tuple(digits_type, exponent_type, compute_type, scale); if (custom_float_types_.find(key) == custom_float_types_.end()) { custom_float_types_[key] = std::make_unique<CustomFloatType>( digits_type, exponent_type, compute_type, scale); } return custom_float_types_[key].get(); } Type *TypeFactory::get_bit_struct_type(PrimitiveType *physical_type, std::vector<Type *> member_types, std::vector<int> member_bit_offsets) { bit_struct_types_.push_back(std::make_unique<BitStructType>( physical_type, member_types, member_bit_offsets)); return bit_struct_types_.back().get(); } Type *TypeFactory::get_bit_array_type(PrimitiveType *physical_type, Type *element_type, int num_elements) { bit_array_types_.push_back(std::make_unique<BitArrayType>( physical_type, element_type, num_elements)); return bit_array_types_.back().get(); } PrimitiveType *TypeFactory::get_primitive_int_type(int bits, bool is_signed) { Type *int_type; if (bits == 8) { int_type = get_primitive_type(PrimitiveTypeID::i8); } else if (bits == 16) { int_type = get_primitive_type(PrimitiveTypeID::i16); } else if (bits == 32) { int_type = get_primitive_type(PrimitiveTypeID::i32); } else if (bits == 64) { int_type = get_primitive_type(PrimitiveTypeID::i64); } else { TI_ERROR("No primitive int type has {} bits", bits); } if (!is_signed) { int_type = to_unsigned(DataType(int_type)); } return int_type->cast<PrimitiveType>(); } PrimitiveType *TypeFactory::get_primitive_real_type(int bits) { Type *real_type; if (bits == 16) { real_type = get_primitive_type(PrimitiveTypeID::f16); } else if (bits == 32) { real_type = get_primitive_type(PrimitiveTypeID::f32); } else if (bits == 64) { real_type = get_primitive_type(PrimitiveTypeID::f64); } else { TI_ERROR("No primitive real type has {} bits", bits); } return real_type->cast<PrimitiveType>(); } DataType TypeFactory::create_vector_or_scalar_type(int width, DataType element, bool element_is_pointer) { TI_ASSERT(width == 1); if (element_is_pointer) { return TypeFactory::get_instance().get_pointer_type(element); } else { return element; } } DataType TypeFactory::create_tensor_type(std::vector<int> shape, DataType element) { return TypeFactory::get_instance().get_tensor_type(shape, element); } namespace { static bool compare_types(DataType x, DataType y) { // Is the first type "bigger" than the second type? if (is_real(x) != is_real(y)) { // One is real, the other is integral. // real > integral return is_real(x); } else { if (is_real(x) && is_real(y)) { // Both are real return data_type_bits(x) > data_type_bits(y); } else { // Both are integral auto x_bits = data_type_bits(x); auto y_bits = data_type_bits(y); if (x_bits != y_bits) { return x_bits > y_bits; } else { // Same number of bits. Unsigned > signed auto x_unsigned = !is_signed(x); auto y_unsigned = !is_signed(y); return x_unsigned > y_unsigned; } } } } static DataType to_primitive_type(DataType d) { if (d->is<PointerType>()) { d = d->as<PointerType>()->get_pointee_type(); TI_WARN("promoted_type got a pointer input."); } if (d->is<TensorType>()) { d = d->as<TensorType>()->get_element_type(); TI_WARN("promoted_type got a tensor input."); } auto primitive = d->cast<PrimitiveType>(); TI_ASSERT_INFO(primitive, "Failed to get primitive type from {}", d->to_string()); return primitive; }; } // namespace DataType promoted_type(DataType x, DataType y) { if (compare_types(to_primitive_type(x), to_primitive_type(y))) return x; else return y; } TLANG_NAMESPACE_END
32.544974
78
0.635994
28f640562ad99b13585c57fbf97d8b1e249ecc96
12,024
cpp
C++
src/ledger/LedgerTxnClaimableBalanceSQL.cpp
V5DF8/stellar-core
3fb2dc6bea41ed9160313f856e57451897f68cd9
[ "Apache-2.0", "BSD-2-Clause", "MIT", "ECL-2.0", "BSL-1.0", "BSD-3-Clause" ]
10
2017-09-23T08:25:40.000Z
2022-01-04T10:28:02.000Z
src/ledger/LedgerTxnClaimableBalanceSQL.cpp
V5DF8/stellar-core
3fb2dc6bea41ed9160313f856e57451897f68cd9
[ "Apache-2.0", "BSD-2-Clause", "MIT", "ECL-2.0", "BSL-1.0", "BSD-3-Clause" ]
1
2021-11-10T00:25:10.000Z
2021-11-10T02:50:40.000Z
src/ledger/LedgerTxnClaimableBalanceSQL.cpp
V5DF8/stellar-core
3fb2dc6bea41ed9160313f856e57451897f68cd9
[ "Apache-2.0", "BSD-2-Clause", "MIT", "ECL-2.0", "BSL-1.0", "BSD-3-Clause" ]
2
2021-10-21T20:34:04.000Z
2021-11-21T14:13:54.000Z
// Copyright 2020 Stellar Development Foundation and contributors. Licensed // under the Apache License, Version 2.0. See the COPYING file at the root // of this distribution or at http://www.apache.org/licenses/LICENSE-2.0 #include "ledger/LedgerTxnImpl.h" #include "util/GlobalChecks.h" #include "util/types.h" namespace stellar { std::shared_ptr<LedgerEntry const> LedgerTxnRoot::Impl::loadClaimableBalance(LedgerKey const& key) const { auto balanceID = toOpaqueBase64(key.claimableBalance().balanceID); std::string claimableBalanceEntryStr; LedgerEntry le; std::string sql = "SELECT ledgerentry " "FROM claimablebalance " "WHERE balanceid= :balanceid"; auto prep = mDatabase.getPreparedStatement(sql); auto& st = prep.statement(); st.exchange(soci::into(claimableBalanceEntryStr)); st.exchange(soci::use(balanceID)); st.define_and_bind(); st.execute(true); if (!st.got_data()) { return nullptr; } fromOpaqueBase64(le, claimableBalanceEntryStr); releaseAssert(le.data.type() == CLAIMABLE_BALANCE); return std::make_shared<LedgerEntry const>(std::move(le)); } class BulkLoadClaimableBalanceOperation : public DatabaseTypeSpecificOperation<std::vector<LedgerEntry>> { Database& mDb; std::vector<std::string> mBalanceIDs; std::vector<LedgerEntry> executeAndFetch(soci::statement& st) { std::string balanceIdStr, claimableBalanceEntryStr; st.exchange(soci::into(balanceIdStr)); st.exchange(soci::into(claimableBalanceEntryStr)); st.define_and_bind(); { auto timer = mDb.getSelectTimer("claimablebalance"); st.execute(true); } std::vector<LedgerEntry> res; while (st.got_data()) { res.emplace_back(); auto& le = res.back(); fromOpaqueBase64(le, claimableBalanceEntryStr); releaseAssert(le.data.type() == CLAIMABLE_BALANCE); st.fetch(); } return res; } public: BulkLoadClaimableBalanceOperation(Database& db, UnorderedSet<LedgerKey> const& keys) : mDb(db) { mBalanceIDs.reserve(keys.size()); for (auto const& k : keys) { releaseAssert(k.type() == CLAIMABLE_BALANCE); mBalanceIDs.emplace_back( toOpaqueBase64(k.claimableBalance().balanceID)); } } std::vector<LedgerEntry> doSqliteSpecificOperation(soci::sqlite3_session_backend* sq) override { std::vector<char const*> cstrBalanceIDs; cstrBalanceIDs.reserve(mBalanceIDs.size()); for (size_t i = 0; i < mBalanceIDs.size(); ++i) { cstrBalanceIDs.emplace_back(mBalanceIDs[i].c_str()); } std::string sql = "WITH r AS (SELECT value FROM carray(?, ?, 'char*')) " "SELECT balanceid, ledgerentry " "FROM claimablebalance " "WHERE balanceid IN r"; auto prep = mDb.getPreparedStatement(sql); auto be = prep.statement().get_backend(); if (be == nullptr) { throw std::runtime_error("no sql backend"); } auto sqliteStatement = dynamic_cast<soci::sqlite3_statement_backend*>(be); auto st = sqliteStatement->stmt_; sqlite3_reset(st); sqlite3_bind_pointer(st, 1, cstrBalanceIDs.data(), "carray", 0); sqlite3_bind_int(st, 2, static_cast<int>(cstrBalanceIDs.size())); return executeAndFetch(prep.statement()); } #ifdef USE_POSTGRES std::vector<LedgerEntry> doPostgresSpecificOperation(soci::postgresql_session_backend* pg) override { std::string strBalanceIDs; marshalToPGArray(pg->conn_, strBalanceIDs, mBalanceIDs); std::string sql = "WITH r AS (SELECT unnest(:v1::TEXT[])) " "SELECT balanceid, ledgerentry " "FROM claimablebalance " "WHERE balanceid IN (SELECT * from r)"; auto prep = mDb.getPreparedStatement(sql); auto& st = prep.statement(); st.exchange(soci::use(strBalanceIDs)); return executeAndFetch(st); } #endif }; UnorderedMap<LedgerKey, std::shared_ptr<LedgerEntry const>> LedgerTxnRoot::Impl::bulkLoadClaimableBalance( UnorderedSet<LedgerKey> const& keys) const { if (!keys.empty()) { BulkLoadClaimableBalanceOperation op(mDatabase, keys); return populateLoadedEntries( keys, mDatabase.doDatabaseTypeSpecificOperation(op)); } else { return {}; } } class BulkDeleteClaimableBalanceOperation : public DatabaseTypeSpecificOperation<void> { Database& mDb; LedgerTxnConsistency mCons; std::vector<std::string> mBalanceIDs; public: BulkDeleteClaimableBalanceOperation( Database& db, LedgerTxnConsistency cons, std::vector<EntryIterator> const& entries) : mDb(db), mCons(cons) { mBalanceIDs.reserve(entries.size()); for (auto const& e : entries) { releaseAssert(!e.entryExists()); releaseAssert(e.key().ledgerKey().type() == CLAIMABLE_BALANCE); mBalanceIDs.emplace_back(toOpaqueBase64( e.key().ledgerKey().claimableBalance().balanceID)); } } void doSociGenericOperation() { std::string sql = "DELETE FROM claimablebalance WHERE balanceid = :id"; auto prep = mDb.getPreparedStatement(sql); auto& st = prep.statement(); st.exchange(soci::use(mBalanceIDs)); st.define_and_bind(); { auto timer = mDb.getDeleteTimer("claimablebalance"); st.execute(true); } if (static_cast<size_t>(st.get_affected_rows()) != mBalanceIDs.size() && mCons == LedgerTxnConsistency::EXACT) { throw std::runtime_error("Could not update data in SQL"); } } void doSqliteSpecificOperation(soci::sqlite3_session_backend* sq) override { doSociGenericOperation(); } #ifdef USE_POSTGRES void doPostgresSpecificOperation(soci::postgresql_session_backend* pg) override { std::string strBalanceIDs; marshalToPGArray(pg->conn_, strBalanceIDs, mBalanceIDs); std::string sql = "WITH r AS (SELECT unnest(:v1::TEXT[])) " "DELETE FROM claimablebalance " "WHERE balanceid IN (SELECT * FROM r)"; auto prep = mDb.getPreparedStatement(sql); auto& st = prep.statement(); st.exchange(soci::use(strBalanceIDs)); st.define_and_bind(); { auto timer = mDb.getDeleteTimer("claimablebalance"); st.execute(true); } if (static_cast<size_t>(st.get_affected_rows()) != mBalanceIDs.size() && mCons == LedgerTxnConsistency::EXACT) { throw std::runtime_error("Could not update data in SQL"); } } #endif }; void LedgerTxnRoot::Impl::bulkDeleteClaimableBalance( std::vector<EntryIterator> const& entries, LedgerTxnConsistency cons) { BulkDeleteClaimableBalanceOperation op(mDatabase, cons, entries); mDatabase.doDatabaseTypeSpecificOperation(op); } class BulkUpsertClaimableBalanceOperation : public DatabaseTypeSpecificOperation<void> { Database& mDb; std::vector<std::string> mBalanceIDs; std::vector<std::string> mClaimableBalanceEntrys; std::vector<int32_t> mLastModifieds; void accumulateEntry(LedgerEntry const& entry) { releaseAssert(entry.data.type() == CLAIMABLE_BALANCE); mBalanceIDs.emplace_back( toOpaqueBase64(entry.data.claimableBalance().balanceID)); mClaimableBalanceEntrys.emplace_back(toOpaqueBase64(entry)); mLastModifieds.emplace_back( unsignedToSigned(entry.lastModifiedLedgerSeq)); } public: BulkUpsertClaimableBalanceOperation( Database& Db, std::vector<EntryIterator> const& entryIter) : mDb(Db) { for (auto const& e : entryIter) { releaseAssert(e.entryExists()); accumulateEntry(e.entry().ledgerEntry()); } } void doSociGenericOperation() { std::string sql = "INSERT INTO claimablebalance " "(balanceid, ledgerentry, lastmodified) " "VALUES " "( :id, :v1, :v2 ) " "ON CONFLICT (balanceid) DO UPDATE SET " "balanceid = excluded.balanceid, ledgerentry = " "excluded.ledgerentry, lastmodified = " "excluded.lastmodified"; auto prep = mDb.getPreparedStatement(sql); soci::statement& st = prep.statement(); st.exchange(soci::use(mBalanceIDs)); st.exchange(soci::use(mClaimableBalanceEntrys)); st.exchange(soci::use(mLastModifieds)); st.define_and_bind(); { auto timer = mDb.getUpsertTimer("claimablebalance"); st.execute(true); } if (static_cast<size_t>(st.get_affected_rows()) != mBalanceIDs.size()) { throw std::runtime_error("Could not update data in SQL"); } } void doSqliteSpecificOperation(soci::sqlite3_session_backend* sq) override { doSociGenericOperation(); } #ifdef USE_POSTGRES void doPostgresSpecificOperation(soci::postgresql_session_backend* pg) override { std::string strBalanceIDs, strClaimableBalanceEntry, strLastModifieds; PGconn* conn = pg->conn_; marshalToPGArray(conn, strBalanceIDs, mBalanceIDs); marshalToPGArray(conn, strClaimableBalanceEntry, mClaimableBalanceEntrys); marshalToPGArray(conn, strLastModifieds, mLastModifieds); std::string sql = "WITH r AS " "(SELECT unnest(:ids::TEXT[]), unnest(:v1::TEXT[]), " "unnest(:v2::INT[]))" "INSERT INTO claimablebalance " "(balanceid, ledgerentry, lastmodified) " "SELECT * FROM r " "ON CONFLICT (balanceid) DO UPDATE SET " "balanceid = excluded.balanceid, ledgerentry = " "excluded.ledgerentry, " "lastmodified = excluded.lastmodified"; auto prep = mDb.getPreparedStatement(sql); soci::statement& st = prep.statement(); st.exchange(soci::use(strBalanceIDs)); st.exchange(soci::use(strClaimableBalanceEntry)); st.exchange(soci::use(strLastModifieds)); st.define_and_bind(); { auto timer = mDb.getUpsertTimer("claimablebalance"); st.execute(true); } if (static_cast<size_t>(st.get_affected_rows()) != mBalanceIDs.size()) { throw std::runtime_error("Could not update data in SQL"); } } #endif }; void LedgerTxnRoot::Impl::bulkUpsertClaimableBalance( std::vector<EntryIterator> const& entries) { BulkUpsertClaimableBalanceOperation op(mDatabase, entries); mDatabase.doDatabaseTypeSpecificOperation(op); } void LedgerTxnRoot::Impl::dropClaimableBalances() { throwIfChild(); mEntryCache.clear(); mBestOffers.clear(); std::string coll = mDatabase.getSimpleCollationClause(); mDatabase.getSession() << "DROP TABLE IF EXISTS claimablebalance;"; mDatabase.getSession() << "CREATE TABLE claimablebalance (" << "balanceid VARCHAR(48) " << coll << " PRIMARY KEY, " << "ledgerentry TEXT NOT NULL, " << "lastmodified INT NOT NULL);"; } }
32.585366
80
0.603127
28f7b2a9efaeb2b9a22cf5b02803470c9cdc2706
4,072
cpp
C++
OpenGL/GLFWContextGL.cpp
IKholopov/TierGine
1a3c7cd2bed460af672d7cd5c33d7e7863043989
[ "Apache-2.0" ]
null
null
null
OpenGL/GLFWContextGL.cpp
IKholopov/TierGine
1a3c7cd2bed460af672d7cd5c33d7e7863043989
[ "Apache-2.0" ]
null
null
null
OpenGL/GLFWContextGL.cpp
IKholopov/TierGine
1a3c7cd2bed460af672d7cd5c33d7e7863043989
[ "Apache-2.0" ]
null
null
null
/* Copyright 2018 Igor Kholopov, 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 <GLFWContextGL.h> #include <GLMaterial.h> #include <GLShader.h> namespace TierGine { IShader* GLFWContextGL::CreateShader(IShader::Type shaderType) { GLShader* shader = new GLShader(shaderType, *this); shaders.insert({shader, nullptr}).first->second.reset(shader); return shader; } void GLFWContextGL::BindShader(const IShader* shader, IPipeline* pipeline) { auto foundShader = shaders.find(shader); assert(foundShader != shaders.end()); auto foundPipeline = pipelines.find(pipeline); assert(foundPipeline != pipelines.end()); foundPipeline->second->BindShader(*foundShader->second); } TG_Status GLFWContextGL::Activate() { glfwMakeContextCurrent(window.GetWindow()); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); return TG_Ok; } IPipeline* GLFWContextGL::CreatePipeline() { GLProgram* program = new GLProgram(*this); pipelines.insert({program, nullptr}).first->second.reset(program); return program; } void GLFWContextGL::DeletePipeline(IPipeline* pipeline) { auto storedPipeline = pipelines.find(pipeline); assert(storedPipeline != pipelines.end()); pipelines.erase(storedPipeline); } void GLFWContextGL::DeleteShader(IShader* shader) { auto storedShader = shaders.find(shader); assert(storedShader != shaders.end()); shaders.erase(storedShader); } IMesh* GLFWContextGL::CreateMesh() { GLMesh* mesh = new GLMesh(*this); meshes.insert({mesh, nullptr}).first->second.reset(mesh); return mesh; } void GLFWContextGL::DeleteMesh(const IMesh* mesh) { auto storedMesh = meshes.find(mesh); assert(storedMesh != meshes.end()); meshes.erase(storedMesh); } ITexture* GLFWContextGL::CreateTexture() { GLTexture* texture = new GLTexture(*this); textures.insert({texture, nullptr}).first->second.reset(texture); return texture; } void GLFWContextGL::DeleteTexture(const ITexture* texture) { auto storedTexture = textures.find(texture); assert(storedTexture != textures.end()); textures.erase(storedTexture); } ITextureSampler* GLFWContextGL::CreateTextureSampler(const std::string& name) { GLTextureSampler* sampler = new GLTextureSampler(*this, name); textureSamplers.insert({sampler, nullptr}).first->second.reset(sampler); return sampler; } void GLFWContextGL::DeleteTextureSampler(const ITextureSampler* sampler) { auto storedSampler = textureSamplers.find(sampler); assert(storedSampler != textureSamplers.end()); textureSamplers.erase(storedSampler); } IFramebuffer* GLFWContextGL::CreateFramebuffer(int width, int height) { GLFramebuffer* buffer = new GLFramebuffer(*this, width, height); framebuffers.insert({buffer, nullptr}).first->second.reset(buffer); return buffer; } void GLFWContextGL::DeleteFramebuffer(const IFramebuffer* buffer) { auto storedBuffer = framebuffers.find(buffer); assert(storedBuffer != framebuffers.end()); framebuffers.erase(storedBuffer); } float GLFWContextGL::GetScreenDepthAt(int x, int y) const { float value = -1.0f; glReadPixels(x, y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &value); return value; } std::unique_ptr<IMaterial> GLFWContextGL::CreateMaterial(ITextureSampler* sampler) { return std::unique_ptr<IMaterial>(new GLMaterial(sampler)); } }
29.085714
82
0.718566
28fa9a0f35c465b171eff066be2899cb0884efe2
8,494
cpp
C++
mbed-os/drivers/QSPI.cpp
h7ga40/PeachCam
06d023a908dc38228e77b47f80bc8496a4d35806
[ "Apache-2.0" ]
1
2019-12-13T05:51:34.000Z
2019-12-13T05:51:34.000Z
mbed-os/drivers/QSPI.cpp
h7ga40/PeachCam
06d023a908dc38228e77b47f80bc8496a4d35806
[ "Apache-2.0" ]
null
null
null
mbed-os/drivers/QSPI.cpp
h7ga40/PeachCam
06d023a908dc38228e77b47f80bc8496a4d35806
[ "Apache-2.0" ]
1
2021-09-17T15:41:36.000Z
2021-09-17T15:41:36.000Z
/* mbed Microcontroller Library * Copyright (c) 2006-2018 ARM Limited * * 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 "drivers/QSPI.h" #include "platform/mbed_critical.h" #include <string.h> #if DEVICE_QSPI namespace mbed { QSPI *QSPI::_owner = NULL; SingletonPtr<PlatformMutex> QSPI::_mutex; QSPI::QSPI(PinName io0, PinName io1, PinName io2, PinName io3, PinName sclk, PinName ssel, int mode) : _qspi() { _qspi_io0 = io0; _qspi_io1 = io1; _qspi_io2 = io2; _qspi_io3 = io3; _qspi_clk = sclk; _qspi_cs = ssel; _inst_width = QSPI_CFG_BUS_SINGLE; _address_width = QSPI_CFG_BUS_SINGLE; _address_size = QSPI_CFG_ADDR_SIZE_24; _alt_width = QSPI_CFG_BUS_SINGLE; _alt_size = QSPI_CFG_ALT_SIZE_8; _data_width = QSPI_CFG_BUS_SINGLE; _num_dummy_cycles = 0; _mode = mode; _hz = ONE_MHZ; _initialized = false; //Go ahead init the device here with the default config bool success = _initialize(); MBED_ASSERT(success); } qspi_status_t QSPI::configure_format(qspi_bus_width_t inst_width, qspi_bus_width_t address_width, qspi_address_size_t address_size, qspi_bus_width_t alt_width, qspi_alt_size_t alt_size, qspi_bus_width_t data_width, int dummy_cycles) { qspi_status_t ret_status = QSPI_STATUS_OK; lock(); _inst_width = inst_width; _address_width = address_width; _address_size = address_size; _alt_width = alt_width; _alt_size = alt_size; _data_width = data_width; _num_dummy_cycles = dummy_cycles; unlock(); return ret_status; } qspi_status_t QSPI::set_frequency(int hz) { qspi_status_t ret_status = QSPI_STATUS_OK; if (_initialized) { lock(); _hz = hz; //If the same owner, just change freq. //Otherwise we may have to change mode as well, so call _acquire if (_owner == this) { if (QSPI_STATUS_OK != qspi_frequency(&_qspi, _hz)) { ret_status = QSPI_STATUS_ERROR; } } else { _acquire(); } unlock(); } else { ret_status = QSPI_STATUS_ERROR; } return ret_status; } qspi_status_t QSPI::read(int address, char *rx_buffer, size_t *rx_length) { qspi_status_t ret_status = QSPI_STATUS_ERROR; if (_initialized) { if ((rx_length != NULL) && (rx_buffer != NULL)) { if (*rx_length != 0) { lock(); if (true == _acquire()) { _build_qspi_command(-1, address, -1); if (QSPI_STATUS_OK == qspi_read(&_qspi, &_qspi_command, rx_buffer, rx_length)) { ret_status = QSPI_STATUS_OK; } } unlock(); } } else { ret_status = QSPI_STATUS_INVALID_PARAMETER; } } return ret_status; } qspi_status_t QSPI::write(int address, const char *tx_buffer, size_t *tx_length) { qspi_status_t ret_status = QSPI_STATUS_ERROR; if (_initialized) { if ((tx_length != NULL) && (tx_buffer != NULL)) { if (*tx_length != 0) { lock(); if (true == _acquire()) { _build_qspi_command(-1, address, -1); if (QSPI_STATUS_OK == qspi_write(&_qspi, &_qspi_command, tx_buffer, tx_length)) { ret_status = QSPI_STATUS_OK; } } unlock(); } } else { ret_status = QSPI_STATUS_INVALID_PARAMETER; } } return ret_status; } qspi_status_t QSPI::read(int instruction, int alt, int address, char *rx_buffer, size_t *rx_length) { qspi_status_t ret_status = QSPI_STATUS_ERROR; if (_initialized) { if ((rx_length != NULL) && (rx_buffer != NULL)) { if (*rx_length != 0) { lock(); if (true == _acquire()) { _build_qspi_command(instruction, address, alt); if (QSPI_STATUS_OK == qspi_read(&_qspi, &_qspi_command, rx_buffer, rx_length)) { ret_status = QSPI_STATUS_OK; } } unlock(); } } else { ret_status = QSPI_STATUS_INVALID_PARAMETER; } } return ret_status; } qspi_status_t QSPI::write(int instruction, int alt, int address, const char *tx_buffer, size_t *tx_length) { qspi_status_t ret_status = QSPI_STATUS_ERROR; if (_initialized) { if ((tx_length != NULL) && (tx_buffer != NULL)) { if (*tx_length != 0) { lock(); if (true == _acquire()) { _build_qspi_command(instruction, address, alt); if (QSPI_STATUS_OK == qspi_write(&_qspi, &_qspi_command, tx_buffer, tx_length)) { ret_status = QSPI_STATUS_OK; } } unlock(); } } else { ret_status = QSPI_STATUS_INVALID_PARAMETER; } } return ret_status; } qspi_status_t QSPI::command_transfer(int instruction, int address, const char *tx_buffer, size_t tx_length, const char *rx_buffer, size_t rx_length) { qspi_status_t ret_status = QSPI_STATUS_ERROR; if (_initialized) { lock(); if (true == _acquire()) { _build_qspi_command(instruction, address, -1); //We just need the command if (QSPI_STATUS_OK == qspi_command_transfer(&_qspi, &_qspi_command, (const void *)tx_buffer, tx_length, (void *)rx_buffer, rx_length)) { ret_status = QSPI_STATUS_OK; } } unlock(); } return ret_status; } void QSPI::lock() { _mutex->lock(); } void QSPI::unlock() { _mutex->unlock(); } // Note: Private helper function to initialize qspi HAL bool QSPI::_initialize() { if (_mode != 0 && _mode != 1) { _initialized = false; return _initialized; } qspi_status_t ret = qspi_init(&_qspi, _qspi_io0, _qspi_io1, _qspi_io2, _qspi_io3, _qspi_clk, _qspi_cs, _hz, _mode); if (QSPI_STATUS_OK == ret) { _initialized = true; } else { _initialized = false; } return _initialized; } // Note: Private function with no locking bool QSPI::_acquire() { if (_owner != this) { //This will set freq as well _initialize(); _owner = this; } return _initialized; } void QSPI::_build_qspi_command(int instruction, int address, int alt) { memset(&_qspi_command, 0, sizeof(qspi_command_t)); //Set up instruction phase parameters _qspi_command.instruction.bus_width = _inst_width; if (instruction != -1) { _qspi_command.instruction.value = instruction; _qspi_command.instruction.disabled = false; } else { _qspi_command.instruction.disabled = true; } //Set up address phase parameters _qspi_command.address.bus_width = _address_width; _qspi_command.address.size = _address_size; if (address != -1) { _qspi_command.address.value = address; _qspi_command.address.disabled = false; } else { _qspi_command.address.disabled = true; } //Set up alt phase parameters _qspi_command.alt.bus_width = _alt_width; _qspi_command.alt.size = _alt_size; if (alt != -1) { _qspi_command.alt.value = alt; _qspi_command.alt.disabled = false; } else { _qspi_command.alt.disabled = true; } _qspi_command.dummy_count = _num_dummy_cycles; //Set up bus width for data phase _qspi_command.data.bus_width = _data_width; } } // namespace mbed #endif
29.391003
233
0.585708
28facf720609c04d87a5b43e7e093224eeff0866
4,630
cpp
C++
modules/imgproc/test/test_watershed.cpp
snosov1/opencv
ce05d6cb89450a5778f4c0169b5da5589798192a
[ "BSD-3-Clause" ]
144
2015-01-15T03:38:44.000Z
2022-02-17T09:07:52.000Z
modules/imgproc/test/test_watershed.cpp
snosov1/opencv
ce05d6cb89450a5778f4c0169b5da5589798192a
[ "BSD-3-Clause" ]
28
2016-10-16T19:42:37.000Z
2018-09-14T21:29:48.000Z
modules/imgproc/test/test_watershed.cpp
snosov1/opencv
ce05d6cb89450a5778f4c0169b5da5589798192a
[ "BSD-3-Clause" ]
58
2015-01-14T23:43:49.000Z
2021-11-15T05:19:08.000Z
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of the copyright holders may not 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 Intel Corporation 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. // //M*/ #include "test_precomp.hpp" #include <string> using namespace cv; using namespace std; class CV_WatershedTest : public cvtest::BaseTest { public: CV_WatershedTest(); ~CV_WatershedTest(); protected: void run(int); }; CV_WatershedTest::CV_WatershedTest() {} CV_WatershedTest::~CV_WatershedTest() {} void CV_WatershedTest::run( int /* start_from */) { string exp_path = string(ts->get_data_path()) + "watershed/wshed_exp.png"; Mat exp = imread(exp_path, 0); Mat orig = imread(string(ts->get_data_path()) + "inpaint/orig.png"); FileStorage fs(string(ts->get_data_path()) + "watershed/comp.xml", FileStorage::READ); if (orig.empty() || !fs.isOpened()) { ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA ); return; } CvSeq* cnts = (CvSeq*)fs["contours"].readObj(); Mat markers(orig.size(), CV_32SC1); markers = Scalar(0); IplImage iplmrks = markers; vector<unsigned char> colors(1); for(int i = 0; cnts != 0; cnts = cnts->h_next, ++i ) { cvDrawContours( &iplmrks, cnts, Scalar::all(i + 1), Scalar::all(i + 1), -1, CV_FILLED); Point* p = (Point*)cvGetSeqElem(cnts, 0); //expected image was added with 1 in order to save to png //so now we substract 1 to get real color if(!exp.empty()) colors.push_back(exp.ptr(p->y)[p->x] - 1); } fs.release(); const int compNum = (int)(colors.size() - 1); watershed(orig, markers); for(int j = 0; j < markers.rows; ++j) { int* line = markers.ptr<int>(j); for(int i = 0; i < markers.cols; ++i) { int& pixel = line[i]; if (pixel == -1) // border continue; if (pixel <= 0 || pixel > compNum) continue; // bad result, doing nothing and going to get error latter; // repaint in saved color to compare with expected; if(!exp.empty()) pixel = colors[pixel]; } } Mat markers8U; markers.convertTo(markers8U, CV_8U, 1, 1); if( exp.empty() || orig.size() != exp.size() ) { imwrite(exp_path, markers8U); exp = markers8U; } if (0 != norm(markers8U, exp, NORM_INF)) { ts->set_failed_test_info( cvtest::TS::FAIL_MISMATCH ); return; } ts->set_failed_test_info(cvtest::TS::OK); } TEST(Imgproc_Watershed, regression) { CV_WatershedTest test; test.safe_run(); }
34.81203
95
0.643413
28fb6f6d11fe5dd49b984fa8107b29b7eb1c4a35
1,103
cpp
C++
source/lab4/dfp.cpp
Jovvik/methopt-lab-1
2c3acaf653c7214a925ed1292b9d1d30a33d2737
[ "Unlicense" ]
null
null
null
source/lab4/dfp.cpp
Jovvik/methopt-lab-1
2c3acaf653c7214a925ed1292b9d1d30a33d2737
[ "Unlicense" ]
null
null
null
source/lab4/dfp.cpp
Jovvik/methopt-lab-1
2c3acaf653c7214a925ed1292b9d1d30a33d2737
[ "Unlicense" ]
null
null
null
#include "lab4/dfp.h" #include "iostream" #include "lab1/brent.h" #include "lab3/solver.h" using namespace lab4; DFP::DFP() : s(lab2::Vector({1})), d(lab2::Vector({1})), G(lab2::Matrix({{1}}, std::nullopt)) {} lab2::Vector DFP::iteration(lab2::NFunction &f, double) { lab2::Vector x_k_1 = get_points().back(), g_x = f.grad(x_k_1); if (iteration_count == 0) { G = lab2::Matrix::I(x_k_1.size()); d = g_x * (-1); return x_k_1; } const auto r = lab1::Brent( [&f, x = x_k_1, d_ = d](double a) { return f(x + d_ * a); }, ONE_DIM_EPS, ONE_DIM_START, ONE_DIM_END) .optimize(); s = d * r; auto x = x_k_1 + s, g_y = g_x; g_x = f.grad(x); auto p = g_x - g_y, v = G * p; G = G + lab2::Matrix::vector_mul(s, s) / (s * p) - lab2::Matrix::vector_mul(v, v) / (v * p); d = (G * g_x) * (-1); return x; } bool DFP::is_done(lab2::NFunction &, double epsilon) const { return s.norm() < epsilon; }
28.282051
66
0.483228
28fc02a851e81e019b0eca73e0ce310b05bacffc
1,765
cpp
C++
week2/6_sinExample_circlePlusPath/src/ofApp.cpp
evejweinberg/algo2012
7e13c20bab94e1769f6751c4e124964ae05b7087
[ "MIT" ]
94
2015-01-12T16:07:57.000Z
2021-12-24T06:48:04.000Z
week2/6_sinExample_circlePlusPath/src/ofApp.cpp
theomission/algo2012
7e13c20bab94e1769f6751c4e124964ae05b7087
[ "MIT" ]
null
null
null
week2/6_sinExample_circlePlusPath/src/ofApp.cpp
theomission/algo2012
7e13c20bab94e1769f6751c4e124964ae05b7087
[ "MIT" ]
18
2015-03-12T23:11:08.000Z
2022-02-05T05:43:51.000Z
#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup(){ ofSetVerticalSync(true); ofBackground(0,0,0); ofSetCircleResolution(100); radius = 50; } //-------------------------------------------------------------- void ofApp::update(){ radius = radius + 0.1; } //-------------------------------------------------------------- void ofApp::draw(){ float xorig = 500; float yorig = 300; float angle = ofGetElapsedTimef()*3.5; float x = xorig + radius * cos(angle); float y = yorig + radius * -sin(angle); ofPoint temp; temp.x = x; temp.y = y; points.push_back(temp); if (points.size() > 1000){ points.erase(points.begin()); } ofSetRectMode(OF_RECTMODE_CENTER); ofSetColor(255,0,127); ofFill(); ofCircle(x,y,10); ofSetColor(255,255,255); ofNoFill(); ofBeginShape(); for (int i = 0; i < points.size(); i++){ ofVertex(points[i].x, points[i].y); } ofEndShape(); } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ }
17.65
64
0.398867
28fc99035e0c7318fc6617c3c8d037dd9c7adecb
2,602
cpp
C++
unit_tests/stencil_composition/test_make_loop_intervals.cpp
mbianco/gridtools
1abef09881a31495a3d02a15d3fe21620c6dde98
[ "BSD-3-Clause" ]
null
null
null
unit_tests/stencil_composition/test_make_loop_intervals.cpp
mbianco/gridtools
1abef09881a31495a3d02a15d3fe21620c6dde98
[ "BSD-3-Clause" ]
null
null
null
unit_tests/stencil_composition/test_make_loop_intervals.cpp
mbianco/gridtools
1abef09881a31495a3d02a15d3fe21620c6dde98
[ "BSD-3-Clause" ]
1
2019-06-14T10:35:50.000Z
2019-06-14T10:35:50.000Z
/* * GridTools * * Copyright (c) 2014-2019, ETH Zurich * All rights reserved. * * Please, refer to the LICENSE file in the root directory. * SPDX-License-Identifier: BSD-3-Clause */ #include <gridtools/stencil_composition/make_loop_intervals.hpp> #include <gtest/gtest.h> #include <gridtools/common/defs.hpp> #include <gridtools/meta.hpp> #include <gridtools/stencil_composition/interval.hpp> #include <gridtools/stencil_composition/level.hpp> namespace gridtools { namespace { using meta::list; template <uint_t Splitter, int_t Offset> using lev = level<Splitter, Offset, 3>; using from_t = lev<0, 1>; using to_t = lev<3, -1>; using axis_interval_t = interval<from_t, to_t>; struct stage1 {}; struct stage2 {}; template <template <class...> class StagesMaker> GT_META_DEFINE_ALIAS(testee, make_loop_intervals, (StagesMaker, axis_interval_t)); namespace no_stages { using testee_t = GT_META_CALL(testee, meta::always<list<>>::apply); static_assert(std::is_same<testee_t, list<>>{}, ""); } // namespace no_stages namespace simple { using testee_t = GT_META_CALL(testee, meta::always<list<stage1>>::apply); static_assert(std::is_same<testee_t, list<loop_interval<from_t, to_t, list<stage1>>>>{}, ""); } // namespace simple namespace overlap { template <uint_t Splitter, int_t Offset> constexpr int_t idx() { return level_to_index<lev<Splitter, Offset>>::value; } constexpr bool has_stage1(int_t i) { return i >= idx<0, 2>() && i < idx<2, 1>(); } constexpr bool has_stage2(int_t i) { return i >= idx<1, 1>() && i < idx<3, -1>(); } template <class Index> GT_META_DEFINE_ALIAS(stages_maker, meta::filter, (meta::not_<std::is_void>::apply, meta::list<conditional_t<has_stage1(Index::value), stage1, void>, conditional_t<has_stage2(Index::value), stage2, void>>)); using testee_t = GT_META_CALL(testee, stages_maker); using expected_t = list<loop_interval<lev<0, 2>, lev<1, -1>, list<stage1>>, loop_interval<lev<1, 1>, lev<2, -1>, list<stage1, stage2>>, loop_interval<lev<2, 1>, lev<3, -2>, list<stage2>>>; static_assert(std::is_same<testee_t, expected_t>{}, ""); } // namespace overlap TEST(dummy, dummy) {} } // namespace } // namespace gridtools
35.162162
105
0.60146
28fc9f8b5966ad5fa16cf33a230b6e621d29ef4f
1,035
cpp
C++
src/swimport/tests/14_arrays/src.cpp
talos-gis/swimport
e8f0fcf02b0c9751b199f750f1f8bc57c8ff54b3
[ "MIT" ]
1
2019-03-07T20:43:42.000Z
2019-03-07T20:43:42.000Z
src/swimport/tests/14_arrays/src.cpp
talos-gis/swimport
e8f0fcf02b0c9751b199f750f1f8bc57c8ff54b3
[ "MIT" ]
null
null
null
src/swimport/tests/14_arrays/src.cpp
talos-gis/swimport
e8f0fcf02b0c9751b199f750f1f8bc57c8ff54b3
[ "MIT" ]
null
null
null
#include "src.h" #include <string.h> #include <stdlib.h> int sum(int const * A_members, size_t n){ auto ret = 0; for (int i = 0; i < n; i++){ ret += *A_members; A_members++; } return ret; } void digits(int n, int** A_output, size_t* size, int base){ auto ret = (int*)malloc(0); size_t i = 0; while (n != 0){ ret = (int*)realloc(ret, sizeof(int)*(++i)); ret[i-1] = n%base; n /= base; } *size = i; *A_output = ret; } void inc(double * AIO_x, size_t n, double offset){ for (size_t i = 0; i < n; i++){ AIO_x[i] += offset; } } const int VERY_BIG_NUMBER = 1'000'000; void very_big_array(int** A_out, size_t* size){ *A_out = new int[VERY_BIG_NUMBER]; *size = VERY_BIG_NUMBER; } void very_big_array_malloc(int** A_out, size_t* size){ *A_out = (int*)calloc(VERY_BIG_NUMBER, sizeof(int)); *size = VERY_BIG_NUMBER; } int vbav[1000] = {}; void very_big_array_view(int*& A_out, size_t& size){ A_out = vbav; size = 1000; }
21.5625
59
0.571981
28fcc247a08f4de74270d83536ad306853dc7395
6,726
cpp
C++
aws-cpp-sdk-apigatewayv2/source/model/Stage.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-apigatewayv2/source/model/Stage.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-apigatewayv2/source/model/Stage.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T12:02:58.000Z
2021-11-09T12:02:58.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/apigatewayv2/model/Stage.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace ApiGatewayV2 { namespace Model { Stage::Stage() : m_accessLogSettingsHasBeenSet(false), m_apiGatewayManaged(false), m_apiGatewayManagedHasBeenSet(false), m_autoDeploy(false), m_autoDeployHasBeenSet(false), m_clientCertificateIdHasBeenSet(false), m_createdDateHasBeenSet(false), m_defaultRouteSettingsHasBeenSet(false), m_deploymentIdHasBeenSet(false), m_descriptionHasBeenSet(false), m_lastDeploymentStatusMessageHasBeenSet(false), m_lastUpdatedDateHasBeenSet(false), m_routeSettingsHasBeenSet(false), m_stageNameHasBeenSet(false), m_stageVariablesHasBeenSet(false), m_tagsHasBeenSet(false) { } Stage::Stage(JsonView jsonValue) : m_accessLogSettingsHasBeenSet(false), m_apiGatewayManaged(false), m_apiGatewayManagedHasBeenSet(false), m_autoDeploy(false), m_autoDeployHasBeenSet(false), m_clientCertificateIdHasBeenSet(false), m_createdDateHasBeenSet(false), m_defaultRouteSettingsHasBeenSet(false), m_deploymentIdHasBeenSet(false), m_descriptionHasBeenSet(false), m_lastDeploymentStatusMessageHasBeenSet(false), m_lastUpdatedDateHasBeenSet(false), m_routeSettingsHasBeenSet(false), m_stageNameHasBeenSet(false), m_stageVariablesHasBeenSet(false), m_tagsHasBeenSet(false) { *this = jsonValue; } Stage& Stage::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("accessLogSettings")) { m_accessLogSettings = jsonValue.GetObject("accessLogSettings"); m_accessLogSettingsHasBeenSet = true; } if(jsonValue.ValueExists("apiGatewayManaged")) { m_apiGatewayManaged = jsonValue.GetBool("apiGatewayManaged"); m_apiGatewayManagedHasBeenSet = true; } if(jsonValue.ValueExists("autoDeploy")) { m_autoDeploy = jsonValue.GetBool("autoDeploy"); m_autoDeployHasBeenSet = true; } if(jsonValue.ValueExists("clientCertificateId")) { m_clientCertificateId = jsonValue.GetString("clientCertificateId"); m_clientCertificateIdHasBeenSet = true; } if(jsonValue.ValueExists("createdDate")) { m_createdDate = jsonValue.GetString("createdDate"); m_createdDateHasBeenSet = true; } if(jsonValue.ValueExists("defaultRouteSettings")) { m_defaultRouteSettings = jsonValue.GetObject("defaultRouteSettings"); m_defaultRouteSettingsHasBeenSet = true; } if(jsonValue.ValueExists("deploymentId")) { m_deploymentId = jsonValue.GetString("deploymentId"); m_deploymentIdHasBeenSet = true; } if(jsonValue.ValueExists("description")) { m_description = jsonValue.GetString("description"); m_descriptionHasBeenSet = true; } if(jsonValue.ValueExists("lastDeploymentStatusMessage")) { m_lastDeploymentStatusMessage = jsonValue.GetString("lastDeploymentStatusMessage"); m_lastDeploymentStatusMessageHasBeenSet = true; } if(jsonValue.ValueExists("lastUpdatedDate")) { m_lastUpdatedDate = jsonValue.GetString("lastUpdatedDate"); m_lastUpdatedDateHasBeenSet = true; } if(jsonValue.ValueExists("routeSettings")) { Aws::Map<Aws::String, JsonView> routeSettingsJsonMap = jsonValue.GetObject("routeSettings").GetAllObjects(); for(auto& routeSettingsItem : routeSettingsJsonMap) { m_routeSettings[routeSettingsItem.first] = routeSettingsItem.second.AsObject(); } m_routeSettingsHasBeenSet = true; } if(jsonValue.ValueExists("stageName")) { m_stageName = jsonValue.GetString("stageName"); m_stageNameHasBeenSet = true; } if(jsonValue.ValueExists("stageVariables")) { Aws::Map<Aws::String, JsonView> stageVariablesJsonMap = jsonValue.GetObject("stageVariables").GetAllObjects(); for(auto& stageVariablesItem : stageVariablesJsonMap) { m_stageVariables[stageVariablesItem.first] = stageVariablesItem.second.AsString(); } m_stageVariablesHasBeenSet = true; } if(jsonValue.ValueExists("tags")) { Aws::Map<Aws::String, JsonView> tagsJsonMap = jsonValue.GetObject("tags").GetAllObjects(); for(auto& tagsItem : tagsJsonMap) { m_tags[tagsItem.first] = tagsItem.second.AsString(); } m_tagsHasBeenSet = true; } return *this; } JsonValue Stage::Jsonize() const { JsonValue payload; if(m_accessLogSettingsHasBeenSet) { payload.WithObject("accessLogSettings", m_accessLogSettings.Jsonize()); } if(m_apiGatewayManagedHasBeenSet) { payload.WithBool("apiGatewayManaged", m_apiGatewayManaged); } if(m_autoDeployHasBeenSet) { payload.WithBool("autoDeploy", m_autoDeploy); } if(m_clientCertificateIdHasBeenSet) { payload.WithString("clientCertificateId", m_clientCertificateId); } if(m_createdDateHasBeenSet) { payload.WithString("createdDate", m_createdDate.ToGmtString(DateFormat::ISO_8601)); } if(m_defaultRouteSettingsHasBeenSet) { payload.WithObject("defaultRouteSettings", m_defaultRouteSettings.Jsonize()); } if(m_deploymentIdHasBeenSet) { payload.WithString("deploymentId", m_deploymentId); } if(m_descriptionHasBeenSet) { payload.WithString("description", m_description); } if(m_lastDeploymentStatusMessageHasBeenSet) { payload.WithString("lastDeploymentStatusMessage", m_lastDeploymentStatusMessage); } if(m_lastUpdatedDateHasBeenSet) { payload.WithString("lastUpdatedDate", m_lastUpdatedDate.ToGmtString(DateFormat::ISO_8601)); } if(m_routeSettingsHasBeenSet) { JsonValue routeSettingsJsonMap; for(auto& routeSettingsItem : m_routeSettings) { routeSettingsJsonMap.WithObject(routeSettingsItem.first, routeSettingsItem.second.Jsonize()); } payload.WithObject("routeSettings", std::move(routeSettingsJsonMap)); } if(m_stageNameHasBeenSet) { payload.WithString("stageName", m_stageName); } if(m_stageVariablesHasBeenSet) { JsonValue stageVariablesJsonMap; for(auto& stageVariablesItem : m_stageVariables) { stageVariablesJsonMap.WithString(stageVariablesItem.first, stageVariablesItem.second); } payload.WithObject("stageVariables", std::move(stageVariablesJsonMap)); } if(m_tagsHasBeenSet) { JsonValue tagsJsonMap; for(auto& tagsItem : m_tags) { tagsJsonMap.WithString(tagsItem.first, tagsItem.second); } payload.WithObject("tags", std::move(tagsJsonMap)); } return payload; } } // namespace Model } // namespace ApiGatewayV2 } // namespace Aws
23.935943
114
0.741748
28fd242a80f8682bd11333cca0515fa98191be66
16,513
cpp
C++
earth_enterprise/src/fusion/fusionui/AssetChooser.cpp
tornado12345/earthenterprise
0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9
[ "Apache-2.0" ]
2,661
2017-03-20T22:12:50.000Z
2022-03-30T09:43:19.000Z
earth_enterprise/src/fusion/fusionui/AssetChooser.cpp
tornado12345/earthenterprise
0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9
[ "Apache-2.0" ]
1,531
2017-03-24T17:20:32.000Z
2022-03-16T18:11:14.000Z
earth_enterprise/src/fusion/fusionui/AssetChooser.cpp
tornado12345/earthenterprise
0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9
[ "Apache-2.0" ]
990
2017-03-24T11:54:28.000Z
2022-03-22T11:51:47.000Z
// Copyright 2017 Google Inc. // // 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 "fusion/fusionui/AssetChooser.h" #include <Qt/qstring.h> #include <Qt/qlineedit.h> #include <Qt/qpushbutton.h> #include <Qt/qcombobox.h> #include <Qt/qmessagebox.h> #include <Qt/q3iconview.h> #include <Qt/qinputdialog.h> #include <Qt/qapplication.h> #include <Qt/qcoreevent.h> #include "fusion/gst/gstAssetManager.h" #include "fusion/fusionui/Preferences.h" #include "fusion/fusionui/AssetManager.h" namespace { int ChangeDirEventId = int(QEvent::registerEventType()); class ChangeDirEvent : public QCustomEvent { public: explicit ChangeDirEvent(const gstAssetFolder &folder) : QCustomEvent(ChangeDirEventId), folder_(folder) { } gstAssetFolder folder_; }; // ----------------------------------------------------------------------------- using QIconView = Q3IconView; class FolderItem : public QIconViewItem { public: FolderItem(QIconView* parent, const gstAssetFolder& f); const gstAssetFolder getFolder() { return folder; } private: gstAssetFolder folder; }; // ----------------------------------------------------------------------------- FolderItem::FolderItem(QIconView* parent, const gstAssetFolder& f) : QIconViewItem(parent), folder(f) { std::string san = shortAssetName(f.name()); setText(san.c_str()); AssetDisplayHelper a(AssetDefs::Invalid, std::string()); setPixmap(a.GetPixmap()); setKey(QString("0" + text())); } // ----------------------------------------------------------------------------- class AssetItem : public QIconViewItem { public: AssetItem(QIconView* parent, gstAssetHandle handle); gstAssetHandle getAssetHandle() { return assetHandle; } private: gstAssetHandle assetHandle; }; // ----------------------------------------------------------------------------- AssetItem::AssetItem(QIconView* parent, gstAssetHandle handle) : QIconViewItem(parent), assetHandle(handle) { auto saname = shortAssetName(handle->getName()); setText(saname.c_str()); Asset asset = handle->getAsset(); AssetDisplayHelper a(asset->type, asset->subtype); setPixmap(a.GetPixmap()); setKey(QString("%1").arg(a.GetSortKey()) + text()); } } // namespace // ----------------------------------------------------------------------------- /////////////////////////////// OPEN RESOURCE AssetChooser::AssetChooser(QWidget* parent, AssetChooser::Mode m, AssetDefs::Type t, const std::string& st) : AssetChooserBase(parent, 0, false, 0), mode_(m), type_(t), subtype_(st), current_folder_(theAssetManager->getAssetRoot()) { const QString SaveBtnText = QObject::tr("Save"); const QString OpenBtnText = QObject::tr("Open"); iconView->setSorting(true); if (mode_ == Save || mode_ == SaveAs) { ok_btn->setText(SaveBtnText); setCaption(SaveBtnText); } else { ok_btn->setText(OpenBtnText); setCaption(OpenBtnText); } AssetDisplayHelper adh(type_, subtype_); compatible_asset_types_.push_back(adh); filterCombo->insertItem(adh.GetPixmap(), adh.PrettyName()); filterCombo->insertItem("All"); // This will draw the iconview contents. chooseFilter(adh.PrettyName()); ok_btn->setEnabled(false); // Accept key presses. setFocusPolicy(Qt::StrongFocus); // Restore previous directory for this type/subtype. RestorePreviousDir(adh); } AssetChooser::AssetChooser( QWidget* parent, AssetChooser::Mode m, const std::vector<AssetCategoryDef>& compatible_asset_defs, const std::string &all_compatible_assets_filter_text, const std::string &all_compatible_assets_icon_name) : AssetChooserBase(parent, 0, false, 0), mode_(m), all_compatible_assets_filter_text_(all_compatible_assets_filter_text), current_folder_(theAssetManager->getAssetRoot()) { assert(mode_ == Open); assert(!compatible_asset_defs.empty()); { // Note: it is not required for Open Dialog, but just to have them // initialized. const AssetCategoryDef& asset_category_def = compatible_asset_defs[0]; type_ = asset_category_def.type; subtype_ = asset_category_def.subtype; } const QString OpenBtnText = QObject::tr("Open"); ok_btn->setText(OpenBtnText); setCaption(OpenBtnText); iconView->setSorting(true); // Insert 'all compatible assets' item in view filter combobox of OpenDialog. if (!all_compatible_assets_filter_text_.empty()) { if (!(all_compatible_assets_filter_text_.empty() || all_compatible_assets_icon_name.empty())) { filterCombo->insertItem( AssetDisplayHelper::LoadPixmap( QObject::tr(all_compatible_assets_icon_name.c_str())), QObject::tr(all_compatible_assets_filter_text_.c_str())); } else { assert(!all_compatible_assets_filter_text_.empty()); assert(all_compatible_assets_icon_name.empty()); filterCombo->insertItem( QObject::tr(all_compatible_assets_filter_text_.c_str())); } } // Insert compatible asset items in view filter combobox of OpenDialog. for (const auto& i : compatible_asset_defs) { AssetDisplayHelper adh(i.type, i.subtype); compatible_asset_types_.push_back(adh); filterCombo->insertItem(adh.GetPixmap(), adh.PrettyName()); } filterCombo->insertItem("All"); assert(compatible_asset_types_.size() != 0); // This will draw the iconview contents. if (!all_compatible_assets_filter_text_.empty()) { chooseFilter(QObject::tr(all_compatible_assets_filter_text_.c_str())); } else { const AssetDisplayHelper& adh = compatible_asset_types_[0]; chooseFilter(adh.PrettyName()); } ok_btn->setEnabled(false); // Accept key presses. setFocusPolicy(Qt::StrongFocus); // Restore previous directory for this type/subtype. const AssetDisplayHelper& adh = compatible_asset_types_[0]; RestorePreviousDir(adh); } void AssetChooser::RestorePreviousDir(const AssetDisplayHelper& adh) { if (khExists(Preferences::filepath("assetchooser.xml").latin1())) { if (chooser_history_.Load( Preferences::filepath("assetchooser.xml").latin1())) { QString dir = chooser_history_.FindDir(adh.GetSortKey()); if (!dir.isEmpty()) { QString path = AssetDefs::AssetRoot().c_str(); path += "/"; path += dir; if (khDirExists(path.latin1())) { updateView(gstAssetFolder(path)); } else { notify(NFY_WARN, "Invalid path in history: %s", path.latin1()); } } } } } void AssetChooser::chooseFilter(const QString& str) { if (str == "All") { match_string_.clear(); } else { match_string_ = str.latin1(); } updateView(current_folder_); } bool AssetChooser::matchFilter(const gstAssetHandle handle) const { Asset asset = handle->getAsset(); if (asset->meta.GetAs("hidden", false)) { return false; } if (match_string_.empty()) return true; AssetDisplayHelper a(asset->type, asset->subtype); if (match_string_ == all_compatible_assets_filter_text_) { assert(!all_compatible_assets_filter_text_.empty()); for (const auto& i : compatible_asset_types_) { if (a.PrettyName() == i.PrettyName()) return true; } return false; } return (a.PrettyName() == match_string_.c_str()); } void AssetChooser::keyPressEvent(QKeyEvent* e) { if (e->key() == Qt::Key_Backspace) { cdtoparent(); e->accept(); } else if (e->key() == Qt::Key_Escape) { reject(); e->accept(); } else { e->ignore(); } } void AssetChooser::customEvent(QEvent *e) { // Make sure this is really an event that we sent. if (int(e->type()) == ChangeDirEventId) { ChangeDirEvent* cdEvent = dynamic_cast<ChangeDirEvent*>(e); iconView->clearSelection(); updateView(cdEvent->folder_); } } void AssetChooser::accept() { if (mode_ == Open) { // Check whether item has been selected; // Note: there is no textEdited-signal in Qt3, so we compare // name of selected/current item with nameEdit's text to make a decision // whether it has been edited. QIconViewItem* item = iconView->currentItem(); if (item != NULL) { AssetItem* assetItem = dynamic_cast<AssetItem*>(item); if (assetItem != NULL) { // If name doesn't match with current item name, then reset item // pointer to initiate searching of item by name below. auto gname = getName(); std::string san1 { shortAssetName(assetItem->getAssetHandle() ->getName().toUtf8().constData()) }; std::string san2 { shortAssetName(assetItem->getAssetHandle() ->getName().toStdString().c_str()) }; if (san1 == san2) { gname.clear(); gname = QString(san2.c_str()); } if (gname != san2.c_str()) { item = NULL; } } } if (item == NULL) { // Note: means that name have been edited and we try to find item by name. item = iconView->findItem(getName(), QKeySequence::ExactMatch); } // here AssetItem* assetItem = dynamic_cast<AssetItem*>(item); if (assetItem != NULL) { auto saname = shortAssetName(assetItem->getAssetHandle()->getName()); nameEdit->setText(saname.c_str()); gstAssetHandle asset_handle = assetItem->getAssetHandle(); Asset asset = asset_handle->getAsset(); type_ = asset->type; subtype_ = asset->subtype; } else { QMessageBox::critical( this, "Error", tr("The specified asset \"") + getName() + tr("\" does not exist."), tr("OK"), QString::null, QString::null, 0); return; } } QString fullpath; if (!getFullPath(fullpath)) { QMessageBox::critical(this, tr("Error"), fullpath, tr("OK"), QString::null, QString::null, 0); return; } if (mode_ == Save || mode_ == SaveAs) { // validate this asset name is unique and prompt if not! std::string ref { fullpath.toUtf8().constData() }; if (Asset(ref)) { if (QMessageBox::warning(this, "Warning", fullpath + tr(" already exists.\nDo you want to replace it?"), tr("OK"), tr("Cancel"), 0, 1) == 1) return; } } else { // Validate whether this asset exists and has compatible asset type. std::string ref { fullpath.toUtf8().constData() }; if (!Asset(ref)) { QMessageBox::critical( this, "Error", tr("The specified asset \"") + getName() + tr("\" does not exist."), tr("OK"), QString::null, QString::null, 0); return; } if (!IsCompatibleAsset()) { QMessageBox::critical(this, "Error", tr("The selected asset \"") + getName() + tr("\" has an incompatible asset type."), tr("OK"), QString::null, QString::null, 0); return; } } // save directory for this type/subtype AssetDisplayHelper adh(type_, subtype_); chooser_history_.SetDir(adh.GetSortKey(), current_folder_.relativePath()); chooser_history_.Save(Preferences::filepath("assetchooser.xml").latin1()); AssetChooserBase::accept(); } bool AssetChooser::getFullPath(QString& fullpath) const { QString path; if (current_folder_.relativePath().isEmpty()) { path = getName(); } else { path = current_folder_.relativePath() + "/" + getName(); } QString errormsg; std::string fullassetname; try { fullassetname = AssetDefs::NormalizeAssetName(path.latin1(), type_, subtype_); } catch(const std::exception& e) { errormsg = QString::fromUtf8(e.what()); } catch(...) { errormsg = "Unknown error"; } if (!errormsg.isEmpty()) { fullpath = errormsg; return false; } fullpath = fullassetname.c_str(); return true; } bool AssetChooser::IsCompatibleAsset() const { assert(mode_ == Open); const AssetDisplayHelper adh(type_, subtype_); std::vector<AssetDisplayHelper>::const_iterator it = std::find( compatible_asset_types_.begin(), compatible_asset_types_.end(), adh); return it != compatible_asset_types_.end(); } QString AssetChooser::getName() const { return nameEdit->text(); } const gstAssetFolder& AssetChooser::getFolder() const { return current_folder_; } void AssetChooser::selectItem(QIconViewItem* item) { AssetItem* assetItem = dynamic_cast<AssetItem*>(item); if (assetItem != NULL) { std::string aname { assetItem->getAssetHandle()->getName().toStdString() }, sname { shortAssetName(aname.c_str()) }; nameEdit->setText(sname.c_str()); } } void AssetChooser::nameChanged(const QString& str) { if (str.isEmpty()) { ok_btn->setEnabled(false); } else { QIconViewItem* item = iconView->currentItem(); if (item != NULL) { // If name doesn't match with current item, then clear selection. AssetItem* assetItem = dynamic_cast<AssetItem*>(item); if (assetItem != NULL) { std::string san = shortAssetName(assetItem->getAssetHandle()->getName()); if (getName().toStdString() != san) { iconView->clearSelection(); } } } ok_btn->setEnabled(true); ok_btn->setDefault(true); } } void AssetChooser::chooseItem(QIconViewItem* item) { FolderItem* folder = dynamic_cast<FolderItem*>(item); if (folder != NULL) { // we can't call updateView directly since it will replace the contents // of the list. And the Qt routine that called us will access it again // after we return. Post an event back to myself with the folder // and we'll call updateView when we get it QApplication::postEvent(this, new ChangeDirEvent(folder->getFolder())); return; } AssetItem* asset = dynamic_cast<AssetItem*>(item); if (asset != NULL) accept(); } void AssetChooser::cdtoparent() { if (current_folder_.name() == theAssetManager->getAssetRoot().name()) return; updateView(current_folder_.getParentFolder()); } void AssetChooser::NewDirectory() { bool ok; QString text = QInputDialog::getText("Make New Folder", tr("Enter new folder name:"), QLineEdit::Normal, QString::null, &ok, this); if (ok && !text.isEmpty()) { QString newdir(current_folder_.fullPath() + "/" + text); QString error; if (!theAssetManager->makeDir (AssetDefs::FilenameToAssetPath(newdir.latin1()), error)) { QMessageBox::critical(this, tr("Error"), error, tr("OK"), QString::null, QString::null, 0); } else { updateView(current_folder_); } } } void AssetChooser::updateView(const gstAssetFolder& folder) { current_folder_ = folder; if (folder.name() == theAssetManager->getAssetRoot().name()) { cdtoparentBtn->setEnabled(false); } else { cdtoparentBtn->setEnabled(true); } iconView->clear(); // // first add all folders // std::vector<gstAssetFolder> folders = folder.getAssetFolders(); for (const auto& it : folders) { (void)new FolderItem(iconView, it); } // // now add all assets // std::vector<gstAssetHandle> items = folder.getAssetHandles(); for (auto& it : items) { if (matchFilter(it)) (void)new AssetItem(iconView, it); } // // populate ancestry combobox // ancestryCombo->clear(); gstAssetFolder f = folder; while (f.isValid() && f.name() != theAssetManager->getAssetRoot().name()) { ancestryCombo->insertItem(AssetManager::AssetRoot() + "/" + f.relativePath(), 0); f = f.getParentFolder(); } ancestryCombo->insertItem(AssetManager::AssetRoot() + "/", 0); ancestryCombo->setCurrentItem(ancestryCombo->count() - 1); } void AssetChooser::chooseAncestor(const QString& ancestor) { gstAssetFolder f = current_folder_; while (f.isValid()) { if (ancestor == QString(AssetManager::AssetRoot() + "/") + f.relativePath()) { updateView(f); return; } f = f.getParentFolder(); } }
30.410681
83
0.639072
28fd96fc5361c29e837e17697d3fb454a7f06f87
3,052
cpp
C++
main.cpp
olpotkin/storyboard
8fa3012f84e6eac023cbf7f3a77d5c05306ee282
[ "MIT" ]
null
null
null
main.cpp
olpotkin/storyboard
8fa3012f84e6eac023cbf7f3a77d5c05306ee282
[ "MIT" ]
null
null
null
main.cpp
olpotkin/storyboard
8fa3012f84e6eac023cbf7f3a77d5c05306ee282
[ "MIT" ]
null
null
null
/* In this exercise we want to design a Storyboard. Our version of the Storyboard * contains arbitrary many notes (imagine it like putting sticky notes on a board). * Every note has a title, a text and a set of tags. E.g. * - title: "Test Traceplayer" * - text: "Implement a unit test for the class Traceplayer of the spark core framework." * - tags: {"unit test", "traceplayer", "testing", "spark core"} * * Our Storyboard should enable us to search for notes by title, text and tags. * E.g.: * searchByTitle("Test Traceplayer") * searchByTag({"testing", "unit test"}) * searchByText("Implement a unit test for the class Traceplayer of the spark core framework.") * For the sake of simplicity we don't want to do any similiarity or prefix matching when * searching for a title, tag or text. Only an exact match should give results. * * The skeleton code below can be used as a starting point but doesn't have to. * The comments "fill in" are placeholders where you definitely have to put in some code when * you use this skeleton code. But this doesn't mean that you shouldn't or can't put code anywhere else. * * Also write some simple unit tests to show how you would test the functionality of the Storyboard. * Don't use any testing framework. Simple if-statements are sufficient for this exercise. * * Hint: Think about performance versus memory tradeoffs in your design, so you can give good * reasons for your decision. */ /// /// @brief /// @author Oleg Potkin <olpotkin@gmail.com> /// #include "core/storyboard.h" int main() { Note note_1{1, "Note 1", "Some text #", {"tag1", "tag2"} }; Note note_2{2, "Note 2", "Some text #", {"tag2", "tag3"} }; Note note_3{3, "Note 3", "Some text #", {"tag1", "tag5"} }; Note note_4{4, "Note 4", "Some text #", {"tag1", "tag5"} }; Storyboard sb{}; sb.addNote(note_1); sb.addNote(note_2); sb.addNote(note_3); sb.addNote(note_4); std::cout << "Initial size of storyboard = " << sb.getSize() << std::endl; sb.deleteNote(4); std::cout << "Size of storyboard after deletion of 1 note = " << sb.getSize() << std::endl; std::cout << std::endl; auto search_1 = sb.searchByTitle("Note 1"); for (const auto& s : search_1) { auto n = sb.getNoteById(s); std::cout << "search by title:" << " ID=" << n.getId() << " Title=" << n.getTitle() << std::endl; } std::cout << std::endl; auto search_2 = sb.searchByText("Some text #"); for (const auto& s : search_2) { auto n = sb.getNoteById(s); std::cout << "search by text:" << " ID=" << n.getId() << " Title=" << n.getTitle() << std::endl; } std::cout << std::endl; auto search_3 = sb.searchByTag("tag5"); for (const auto& s : search_3) { auto n = sb.getNoteById(s); std::cout << "search by tag " << "'#tag5': " << " ID=" << n.getId() << " Title=" << n.getTitle() << std::endl; } std::cout << std::endl; return 0; }
35.905882
104
0.617628
28fda0af045e54a3671e62bbcc2d434c1e57a272
73,497
cpp
C++
src/tests/ClassPath/src/bstrwrap.cpp
TakuKitamura/verimqtt-c
30109f66df126e5860f2329ce2ad3cfb7f12d9da
[ "MIT" ]
42
2020-03-15T22:07:04.000Z
2022-03-18T18:49:35.000Z
src/tests/ClassPath/src/bstrwrap.cpp
TakuKitamura/verimqtt-c
30109f66df126e5860f2329ce2ad3cfb7f12d9da
[ "MIT" ]
6
2020-06-04T17:07:29.000Z
2021-02-17T14:49:05.000Z
src/tests/ClassPath/src/bstrwrap.cpp
TakuKitamura/verimqtt-c
30109f66df126e5860f2329ce2ad3cfb7f12d9da
[ "MIT" ]
9
2020-08-07T11:49:08.000Z
2022-02-20T14:15:35.000Z
/* * This source file is part of the bstring string library. This code was * written by Paul Hsieh in 2002 - 2006, and is covered by the BSD open source * license. Refer to the accompanying documentation for details on usage and * license. */ /* * bstrwrap.c * * This file is the C++ wrapper for the bstring functions. */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdarg.h> #include <limits.h> #include <ctype.h> #include "../include/Strings/bstring.hpp" #include "../include/Strings/VerySimpleReadOnlyString.hpp" #if defined(BSTRLIB_MEMORY_DEBUG) #include "memdbg.h" #endif // Forward declare the uint64 serializer namespace Strings { char* ulltoa(uint64 value, char* result, int base); } namespace Bstrlib { // Constructors. String::String() { slen = 0; mlen = 8; data = (unsigned char*)malloc(mlen); if (!data) { mlen = 0; bstringThrow("Failure in default constructor"); } else data[0] = '\0'; } String::String(const void * blk, int len) { slen = mlen = 0; data = 0; if (len >= 0) { mlen = len + 1; slen = len; data = (uint8 * ) malloc(mlen); } if (!data) { mlen = slen = 0; bstringThrow("Failure in block constructor"); } else { if (slen > 0 && blk) memcpy(data, blk, slen); data[slen] = '\0'; } } String::String(const void * ownedBlock, const int len, const int allocLen) { slen = len; mlen = allocLen; data = (unsigned char*)ownedBlock; } String::String(char c, int len) { slen = mlen = 0; data = 0; if (len >= 0) { mlen = len + 1; slen = len; data = (uint8 * ) malloc(mlen); } if (!data) { mlen = slen = 0; bstringThrow("Failure in repeat(char) constructor"); } else { if (slen > 0) memset(data, c, slen); data[slen] = '\0'; } } String::String(char c) { slen = mlen = 0; data = 0; data = (unsigned char*)malloc(2); if (data) { data[0] = (unsigned char)c; data[1] = '\0'; mlen = 2; slen = 1; } else bstringThrow("Failure in (char) constructor"); } String::String(unsigned char c) { slen = mlen = 0; data = 0; data = (unsigned char*)malloc(2); if (data) { data[0] = c; data[1] = '\0'; mlen = 2; slen = 1; } else bstringThrow("Failure in (char) constructor"); } String::String(const char *s) { slen = mlen = 0; data = 0; if (s) { slen = (int)strlen(s); mlen = slen + 1; data = (unsigned char*)malloc(mlen); if (!data) { mlen = slen = 0; bstringThrow("Failure in (char *) constructor"); } else memcpy(data, s, mlen); } } String::String(int len, const char *s) { slen = mlen = 0; data = 0; if (s) { slen = (int)strlen(s); mlen = slen + 1; if (mlen < len) mlen = len; data = (uint8 * ) malloc(mlen); if (!data) { mlen = slen = 0; bstringThrow("Failure in (int len, char *) constructor"); } memcpy(data, s, slen + 1); } } String::String(const String& b) { slen = b.slen; mlen = slen + 1; data = 0; if (mlen > 0) data = (uint8 * ) malloc(mlen); if (!data) { bstringThrow("Failure in (String) constructor"); } else { memcpy(data, b.data, slen); data[slen] = '\0'; } } String::String(const tagbstring& x) { slen = x.slen; mlen = slen + 1; data = 0; if (slen >= 0 && x.data != NULL) data = (uint8 * ) malloc(mlen); if (!data) { bstringThrow("Failure in (tagbstring) constructor"); } else { memcpy(data, x.data, slen); data[slen] = '\0'; } } String::String(const Strings::VerySimpleReadOnlyString & b) { slen = mlen = 0; data = 0; if (b.getLength() >= 0) { mlen = b.getLength() + 1; slen = b.getLength(); data = (uint8 * ) malloc(mlen); } if (!data) { mlen = slen = 0; bstringThrow("Failure in block constructor"); } else { if (slen > 0 && b.getData()) memcpy(data, b.getData(), slen); data[slen] = '\0'; } } // Destructor. String::~String() { if (data != NULL) { free(data); data = NULL; } mlen = 0; slen = -__LINE__; } // = operator. const String& String::operator=(char c) { if (mlen <= 0) bstringThrow("Write protection error"); if (2 >= mlen) Alloc(2); if (!data) { mlen = slen = 0; bstringThrow("Failure in =(char) operator"); } else { slen = 1; data[0] = (unsigned char) c; data[1] = '\0'; } return *this; } const String& String::operator=(unsigned char c) { if (mlen <= 0) bstringThrow("Write protection error"); if (2 >= mlen) Alloc(2); if (!data) { mlen = slen = 0; bstringThrow("Failure in =(char) operator"); } else { slen = 1; data[0] = c; data[1] = '\0'; } return *this; } const String& String::operator=(const char *s) { int tmpSlen; if (mlen <= 0) bstringThrow("Write protection error"); if (NULL == s) s = ""; if ((tmpSlen = (int)strlen(s)) >= mlen) Alloc(tmpSlen); if (data) { slen = tmpSlen; memcpy(data, s, tmpSlen + 1); } else { mlen = slen = 0; bstringThrow("Failure in =(const char *) operator"); } return *this; } const String& String::operator=(const String& b) { if (&b == this) return *this; if (mlen <= 0) bstringThrow("Write protection error"); if (b.slen >= mlen) Alloc(b.slen); slen = b.slen; if (!data) { mlen = slen = 0; bstringThrow("Failure in =(String) operator"); } else { memcpy(data, b.data, slen); data[slen] = '\0'; } return *this; } const String& String::operator=(const tagbstring& x) { if (mlen <= 0) bstringThrow("Write protection error"); if (x.slen < 0) bstringThrow("Failure in =(tagbstring) operator, badly formed tagbstring"); if (x.slen >= mlen) Alloc(x.slen); slen = x.slen; if (!data) { mlen = slen = 0; bstringThrow("Failure in =(tagbstring) operator"); } else { memcpy(data, x.data, slen); data[slen] = '\0'; } return *this; } const String& String::operator +=(const String& b) { if (BSTR_ERR == bconcat(this, (bstring)&b)) bstringThrow("Failure in concatenate"); return *this; } const String& String::operator +=(const char *s) { struct tagbstring x; char * d; int i, l; if (mlen <= 0) bstringThrow("Write protection error"); /* Optimistically concatenate directly */ l = mlen - slen; d = (char *) &data[slen]; for (i = 0; i < l; i++) { if ((*d++ = *s++) == '\0') { slen += i; return *this; } } slen += i; cstr2tbstr(x, s); if (BSTR_ERR == bconcat(this, &x)) bstringThrow("Failure in concatenate"); return *this; } const String& String::operator +=(char c) { if (BSTR_ERR == bconchar(this, c)) bstringThrow("Failure in concatenate"); return *this; } const String& String::operator +=(unsigned char c) { if (BSTR_ERR == bconchar(this, (char) c)) bstringThrow("Failure in concatenate"); return *this; } const String& String::operator +=(const tagbstring& x) { if (mlen <= 0) bstringThrow("Write protection error"); if (x.slen < 0) bstringThrow("Failure in +=(tagbstring) operator, badly formed tagbstring"); Alloc(x.slen + slen + 1); if (!data) { mlen = slen = 0; bstringThrow("Failure in +=(tagbstring) operator"); } else { memcpy(data + slen, x.data, x.slen); slen += x.slen; data[slen] = '\0'; } return *this; } const String String::operator+(char c) const { String retval(*this); retval += c; return retval; } const String String::operator+(unsigned char c) const { String retval(*this); retval += c; return retval; } const String String::operator+(const String& b) const { String retval(*this); retval += b; return retval; } const String String::operator+(const char *s) const { String retval(*this); if (s == NULL) return retval; retval += s; return retval; } const String String::operator+(const uint8 * s) const { String retval(*this); if (s == NULL) return retval; retval +=(char *) s; return retval; } const String String::operator+(const int c) const { String retval(*this); retval += c; return retval; } const String String::operator+(const unsigned int c) const { String retval(*this); retval += c; return retval; } const String String::operator+(const float c) const { String retval(*this); retval += c; return retval; } const String String::operator+(const double c) const { String retval(*this); retval += c; return retval; } const String String::operator+(const int64 c) const { String retval(*this); retval += c; return retval; } const String String::operator+(const uint64 c) const { String retval(*this); retval += c; return retval; } const String& String::operator +=(const int c) { #ifndef HasFloatParsing char buffer[12] = { c < 0 ? '-': '\0' }; utoa((unsigned long)(c < 0 ? -c : c), &buffer[c < 0 ? 1 : 0], 10); return *this += buffer; #else return *this += String::Print("%d", c); #endif } const String& String::operator +=(const unsigned int c) { #ifndef HasFloatParsing char buffer[11] = { 0 }; utoa((unsigned long)c, buffer, 10); return *this += buffer; #else return *this += String::Print("%u", c); #endif } const String& String::operator +=(const int64 c) { #ifndef HasFloatParsing char buffer[22] = { c < 0 ? '-': '\0' }; Strings::ulltoa((uint64)(c < 0 ? -c : c), &buffer[c < 0 ? 1 : 0], 10); return *this += buffer; #else return *this += String::Print(PF_LLD, c); #endif } const String& String::operator +=(const uint64 c) { #ifndef HasFloatParsing char buffer[21] = { 0 }; Strings::ulltoa(c, buffer, 10); return *this += buffer; #else return *this += String::Print(PF_LLU, c); #endif } String String::getHexOf(const uint64 c) { char buffer[23] = { '0', 'x' }; Strings::ulltoa(c, buffer+2, 16); return String(buffer); } int64 String::parseInt(int base, int * endPos) const { const char * text = (const char*)data; if (!slen) { if (endPos) *endPos = 0; return 0; } bool negative = text[0] == '-'; text += (int)negative; const char baseText[] = "0123456789abcdef", BASEText[] = "0123456789ABCDEF"; // Check the current base, if auto detection is activated if (!base) { if (text[0] != '0') base = 10; else switch(text[1]) { case 'X': case 'x': base = 16; text += 2; break; case 'B': case 'b': base = 2; text += 2; break; default: base = 8; text += 1; break; } } // Let's start conversion int64 ret = 0; while (text) { const char * charPos = strchr(baseText, *text); int digit = (int)(charPos - baseText); if (charPos == NULL && base > 10) { charPos = strchr(BASEText, *text); digit = (int)(charPos - BASEText); } if (charPos == NULL) break; if (digit >= base) break; ret = ret * base + digit; text++; } if (endPos) *endPos = (int)(text - (const char*)data); return negative ? -ret : ret; } const String& String::operator +=(const float c) { #ifndef HasFloatParsing char buffer[15] = { 0 }; ftoa(c, buffer, 6); return *this += buffer; #else return *this += String::Print("%lg", c); #endif } const String& String::operator +=(const double c) { #ifndef HasFloatParsing char buffer[15] = { 0 }; ftoa((float)c, buffer, 6); return *this += buffer; #else return *this += String::Print("%lg", c); #endif } const String String::operator+(const tagbstring& x) const { if (x.slen < 0) bstringThrow("Failure in + (tagbstring) operator, badly formed tagbstring"); String retval(*this); retval += x; return retval; } bool String::operator ==(const String& b) const { int retval; if (BSTR_ERR ==(retval = biseq((bstring)this, (bstring)&b))) bstringThrow("Failure in compare (==)"); return retval != 0; } bool String::operator ==(const char * s) const { int retval; if (NULL == s) return slen == 0; if (BSTR_ERR ==(retval = biseqcstr((bstring) this, s))) bstringThrow("Failure in compare (==)"); return retval != 0; } bool String::operator ==(const uint8 * s) const { int retval; if (NULL == s) return slen == 0; if (BSTR_ERR ==(retval = biseqcstr((bstring) this, (char *) s))) bstringThrow("Failure in compare (==)"); return retval != 0; } bool String::operator !=(const String& b) const { return !((*this) == b); } bool String::operator !=(const char * s) const { return !((*this) == s); } bool String::operator !=(const uint8 * s) const { return !((*this) == s); } bool String::operator <(const String& b) const { int retval; if (SHRT_MIN ==(retval = bstrcmp((bstring) this, (bstring)&b))) bstringThrow("Failure in compare (<)"); return retval < 0; } bool String::operator <(const char * s) const { if (NULL == s) return false; return strcmp((const char *)this->data, s) < 0; } bool String::operator <(const uint8 * s) const { if (NULL == s) return false; return strcmp((const char *)this->data, (const char *)s) < 0; } bool String::operator <=(const String& b) const { int retval; if (SHRT_MIN ==(retval = bstrcmp((bstring) this, (bstring)&b))) bstringThrow("Failure in compare (<=)"); return retval <= 0; } bool String::operator <=(const char * s) const { if (NULL == s) return slen == 0; return strcmp((const char *)this->data, s) <= 0; } bool String::operator <=(const uint8 * s) const { if (NULL == s) return slen == 0; return strcmp((const char *)this->data, (const char *)s) <= 0; } bool String::operator >(const String& b) const { return !((*this) <= b); } bool String::operator >(const char * s) const { return !((*this) <= s); } bool String::operator >(const uint8 * s) const { return !((*this) <= s); } bool String::operator >=(const String& b) const { return !((*this) < b); } bool String::operator >=(const char * s) const { return !((*this) < s); } bool String::operator >=(const uint8 * s) const { return !((*this) < s); } #ifdef HasFloatParsing String::operator double() const { return parseDouble(); } String::operator float() const { return (float)parseDouble(); } double String::parseDouble(int * consumed) const { char * ep = NULL; double ret = data ? strtod((const char*)data, &ep) : 0; if (consumed) *consumed = (int)(ep - (const char*)data); return ret; } #endif String::operator signed int() const { return (signed int)parseInt(10); } String::operator unsigned int() const { return (unsigned int)parseInt(10); } String::operator int64() const { return (int64)parseInt(10); } int String::Scan(const char * fmt, void * data) const { return sscanf((const char *)this->data, fmt, data); } #ifdef __TURBOC__ # ifndef BSTRLIB_NOVSNP # define BSTRLIB_NOVSNP # endif #endif /* Give WATCOM C/C++, MSVC some latitude for their non - support of vsnprintf */ #if defined(__WATCOMC__) || defined(_MSC_VER) #define exvsnprintf(r,b,n,f,a) {r = _vsnprintf (b,n,f,a);} #else #ifdef BSTRLIB_NOVSNP /* This is just a hack. If you are using a system without a vsnprintf, it is not recommended that bformat be used at all. */ #define exvsnprintf(r,b,n,f,a) {vsprintf (b,f,a); r = -1;} #define START_VSNBUFF (256) #else #if defined(__GNUC__) && !defined(__PPC__) /* Something is making gcc complain about this prototype not being here, so I've just gone ahead and put it in. */ extern "C" { extern int vsnprintf(char *buf, size_t count, const char *format, va_list arg); } #endif #define exvsnprintf(r,b,n,f,a) {r = vsnprintf (b,n,f,a);} #endif #endif #ifndef START_VSNBUFF #define START_VSNBUFF (16) #endif /* * Yeah I'd like to just call a vformat function or something, but because of * the ANSI specified brokeness of the va_* macros, it is actually not * possible to do this correctly. */ String & String::Format(const char * fmt, ...) { bstring b; va_list arglist; int r, n; if (mlen <= 0) bstringThrow("Write protection error"); if (fmt == NULL) *this = "<NULL>"; else { if ((b = bfromcstr("")) == NULL) { *this = "<NULL>"; } else { if ((n = 2*(int)strlen(fmt)) < START_VSNBUFF) n = START_VSNBUFF; for (;;) { if (BSTR_OK != balloc(b, n + 2)) { b = bformat("<OUTM>"); break; } va_start(arglist, fmt); exvsnprintf(r, (char *) b->data, n + 1, fmt, arglist); va_end(arglist); b->data[n] = '\0'; b->slen = (int)strlen((char *) b->data); if (b->slen < n) break; if (r > n) n = r; else n += n; } *this = *b; bdestroy(b); } } return *this; } /* * Yeah I'd like to just call a vformat function or something, but because of * the ANSI specified brokeness of the va_* macros, it is actually not * possible to do this correctly. */ String String::Print(const char * fmt, ...) { bstring b; va_list arglist; int r, n; String ret; if (fmt == NULL) return ret; else { if ((b = bfromcstr("")) == NULL) { ret = "<NULL>"; } else { if ((n = 2*(int)strlen(fmt)) < START_VSNBUFF) n = START_VSNBUFF; for (;;) { if (BSTR_OK != balloc(b, n + 2)) { b = bformat("<OUTM>"); break; } va_start(arglist, fmt); exvsnprintf(r, (char *) b->data, n + 1, fmt, arglist); va_end(arglist); b->data[n] = '\0'; b->slen = (int)strlen((char *) b->data); if (b->slen < n) break; if (r > n) n = r; else n += n; } ret = *b; bdestroy(b); } } return ret; } void String::Formata(const char * fmt, ...) { bstring b; va_list arglist; int r, n; if (mlen <= 0) bstringThrow("Write protection error"); if (fmt == NULL) { *this += "<NULL>"; } else { if ((b = bfromcstr("")) == NULL) { *this += "<NULL>"; } else { if ((n = 2*(int)strlen(fmt)) < START_VSNBUFF) n = START_VSNBUFF; for (;;) { if (BSTR_OK != balloc(b, n + 2)) { b = bformat("<OUTM>"); break; } va_start(arglist, fmt); exvsnprintf(r, (char *) b->data, n + 1, fmt, arglist); va_end(arglist); b->data[n] = '\0'; b->slen = (int)strlen((char *) b->data); if (b->slen < n) break; if (r > n) n = r; else n += n; } *this += *b; bdestroy(b); } } } bool String::caselessEqual(const String& b) const { int ret; if (BSTR_ERR ==(ret = biseqcaseless((bstring) this, (bstring) &b))) bstringThrow("String::caselessEqual Unable to compare"); return ret == 1; } int String::caselessCmp(const String& b) const { int ret; if (SHRT_MIN ==(ret = bstricmp((bstring) this, (bstring) &b))) bstringThrow("String::caselessCmp Unable to compare"); return ret; } int String::Count(const String & b) const { int i = 0, j = 0; int count = 0; for (; i + j < slen; ) { if ((unsigned char) b[j] == data[i + j]) { j++; if (j == b.slen) { i+= j; j = 0; count ++; continue; } continue; } i++; j = 0; } return count; } int String::Find(const String& b, int pos) const { return binstr((bstring) this, pos, (bstring) &b); } int String::Find(const char * b, int pos) const { int i, j; if (NULL == b) return BSTR_ERR; if ((unsigned int) pos > (unsigned int) slen) return BSTR_ERR; if ('\0' == b[0]) return pos; if (pos == slen) return BSTR_ERR; i = pos; j = 0; for (; i + j < slen; ) { if ((unsigned char) b[j] == data[i + j]) { j++; if ('\0' == b[j]) return i; continue; } i++; j = 0; } return BSTR_ERR; } int String::caselessFind(const String& b, int pos) const { return binstrcaseless((bstring) this, pos, (bstring) &b); } int String::caselessFind(const char * b, int pos) const { struct tagbstring t; if (NULL == b) return BSTR_ERR; if ((unsigned int) pos > (unsigned int) slen) return BSTR_ERR; if ('\0' == b[0]) return pos; if (pos == slen) return BSTR_ERR; btfromcstr(t, b); return binstrcaseless((bstring) this, pos, (bstring) &t); } int String::Find(char c, int pos) const { if (pos < 0) return BSTR_ERR; for (; pos < slen; pos++) { if (data[pos] ==(unsigned char) c) return pos; } return BSTR_ERR; } int String::reverseFind(const String& b, int pos) const { return binstrr((bstring) this, pos, (bstring) &b); } int String::reverseFind(const char * b, int pos) const { struct tagbstring t; if (NULL == b) return BSTR_ERR; cstr2tbstr(t, b); return binstrr((bstring) this, pos, &t); } int String::caselessReverseFind(const String& b, int pos) const { return binstrrcaseless((bstring) this, pos, (bstring) &b); } int String::caselessReverseFind(const char * b, int pos) const { struct tagbstring t; if (NULL == b) return BSTR_ERR; if ((unsigned int) pos > (unsigned int) slen) return BSTR_ERR; if ('\0' == b[0]) return pos; if (pos == slen) return BSTR_ERR; btfromcstr(t, b); return binstrrcaseless((bstring) this, pos, (bstring) &t); } int String::reverseFind(char c, int pos) const { if (pos < 0) pos = slen-1; if (pos > slen) return BSTR_ERR; if (pos == slen) pos--; for (; pos >= 0; pos--) { if (data[pos] ==(unsigned char) c) return pos; } return BSTR_ERR; } int String::findAnyChar(const String& b, int pos) const { return binchr((bstring) this, pos, (bstring) &b); } int String::findAnyChar(const char * s, int pos) const { struct tagbstring t; if (NULL == s) return BSTR_ERR; cstr2tbstr(t, s); return binchr((bstring) this, pos, (bstring) &t); } int String::invFindAnyChar(const String& b, int pos) const { return bninchr((bstring) this, pos, (bstring) &b); } int String::invFindAnyChar(const char * s, int pos) const { struct tagbstring t; if (NULL == s) return BSTR_ERR; cstr2tbstr(t, s); return bninchr((bstring) this, pos, &t); } int String::reverseFindAnyChar(const String& b, int pos) const { return binchrr((bstring) this, pos, (bstring) &b); } int String::reverseFindAnyChar(const char * s, int pos) const { struct tagbstring t; if (NULL == s) return BSTR_ERR; cstr2tbstr(t, s); return binchrr((bstring) this, pos, &t); } int String::invReverseFindAnyChar(const String& b, int pos) const { return bninchrr((bstring) this, pos, (bstring) &b); } int String::invReverseFindAnyChar(const char * s, int pos) const { struct tagbstring t; if (NULL == s) return BSTR_ERR; cstr2tbstr(t, s); return bninchrr((bstring) this, pos, &t); } String String::extractToken(char c, int & pos) const { String ret; if (pos >= slen) return ret; int findNextPos = Find(c, pos); if (findNextPos == -1) findNextPos = slen; ret = midString(pos, findNextPos - pos); pos = findNextPos + 1; return ret; } const String String::midString(int left, int len) const { struct tagbstring t; if (len < 0) { // Want data from the right of the string, without specifying the start point // For example String("abcdefgh").midString(0, -3) => "abcde" if (-len >= slen) left = 0; else { // Check for String("abcdef").midString(-3, -1) => "de" if (left < 0) { left = max(0, slen + left); len = slen + len - left; } else len += slen; } } if (left < 0) { // Want data from the right of the string len = len > -left ? -left : len; left = slen + left; } if (len > slen - left) len = slen - left; if (len <= 0 || left < 0) return String(""); blk2tbstr(t, data + left, len); return String(t); } char * String::Alloc(int length) { if (BSTR_ERR == balloc((bstring)this, length)) bstringThrow("Failure in Alloc"); return (char*)data; } void String::Fill(int length, unsigned char fill) { slen = 0; if (BSTR_ERR == bsetstr(this, length, NULL, fill)) bstringThrow("Failure in fill"); } void String::setSubstring(int pos, const String& b, unsigned char fill) { if (BSTR_ERR == bsetstr(this, pos, (bstring) &b, fill)) bstringThrow("Failure in setstr"); } void String::setSubstring(int pos, const char * s, unsigned char fill) { struct tagbstring t; if (NULL == s) return; cstr2tbstr(t, s); if (BSTR_ERR == bsetstr(this, pos, &t, fill)) { bstringThrow("Failure in setstr"); } } void String::Insert(int pos, const String& b, unsigned char fill) { if (BSTR_ERR == binsert(this, pos, (bstring) &b, fill)) bstringThrow("Failure in insert"); } void String::Insert(int pos, const char * s, unsigned char fill) { struct tagbstring t; if (NULL == s) return; cstr2tbstr(t, s); if (BSTR_ERR == binsert(this, pos, &t, fill)) bstringThrow("Failure in insert"); } void String::insertChars(int pos, int len, unsigned char fill) { if (BSTR_ERR == binsertch(this, pos, len, fill)) bstringThrow("Failure in insertchrs"); } void String::Replace(int pos, int len, const String& b, unsigned char fill) { if (BSTR_ERR == breplace(this, pos, len, (bstring) &b, fill)) bstringThrow("Failure in Replace"); } void String::Replace(int pos, int len, const char * s, unsigned char fill) { struct tagbstring t; int q; if (mlen <= 0) bstringThrow("Write protection error"); if (NULL == s || (pos | len) < 0) return; if (pos + len >= slen) { cstr2tbstr(t, s); if (BSTR_ERR == bsetstr(this, pos, &t, fill)) bstringThrow("Failure in Replace"); else if (pos + t.slen < slen) { slen = pos + t.slen; data[slen] = '\0'; } } else { /* Aliasing case */ if ((unsigned int)(data - (uint8 * ) s) < (unsigned int) slen) { Replace(pos, len, String(s), fill); return; } if ((q = (int)strlen(s)) > len) { Alloc(slen + q - len); if (NULL == data) return; } if (q != len) memmove(data + pos + q, data + pos + len, slen - (pos + len)); memcpy(data + pos, s, q); slen += q - len; data[slen] = '\0'; } } String & String::findAndReplace(const String& find, const String& repl, int pos) { if (BSTR_ERR == bfindreplace(this, (bstring) &find, (bstring) &repl, pos)) bstringThrow("Failure in findreplace"); return *this; } String & String::findAndReplace(const String& find, const char * repl, int pos) { struct tagbstring t; if (NULL == repl) return *this; cstr2tbstr(t, repl); if (BSTR_ERR == bfindreplace(this, (bstring) &find, (bstring) &t, pos)) bstringThrow("Failure in findreplace"); return *this; } String & String::findAndReplace(const char * find, const String& repl, int pos) { struct tagbstring t; if (NULL == find) return *this; cstr2tbstr(t, find); if (BSTR_ERR == bfindreplace(this, (bstring) &t, (bstring) &repl, pos)) bstringThrow("Failure in findreplace"); return *this; } String & String::findAndReplace(const char * find, const char * repl, int pos) { struct tagbstring t, u; if (NULL == repl || NULL == find) return *this; cstr2tbstr(t, find); cstr2tbstr(u, repl); if (BSTR_ERR == bfindreplace(this, (bstring) &t, (bstring) &u, pos)) bstringThrow("Failure in findreplace"); return *this; } String & String::findAndReplaceCaseless(const String& find, const String& repl, int pos) { if (BSTR_ERR == bfindreplacecaseless(this, (bstring) &find, (bstring) &repl, pos)) bstringThrow("Failure in findreplacecaseless"); return *this; } String & String::findAndReplaceCaseless(const String& find, const char * repl, int pos) { struct tagbstring t; if (NULL == repl) return *this; cstr2tbstr(t, repl); if (BSTR_ERR == bfindreplacecaseless(this, (bstring) &find, (bstring) &t, pos)) bstringThrow("Failure in findreplacecaseless"); return *this; } String & String::findAndReplaceCaseless(const char * find, const String& repl, int pos) { struct tagbstring t; if (NULL == find) return *this; cstr2tbstr(t, find); if (BSTR_ERR == bfindreplacecaseless(this, (bstring) &t, (bstring) &repl, pos)) bstringThrow("Failure in findreplacecaseless"); return *this; } String & String::findAndReplaceCaseless(const char * find, const char * repl, int pos) { struct tagbstring t, u; if (NULL == repl || NULL == find) return *this; cstr2tbstr(t, find); cstr2tbstr(u, repl); if (BSTR_ERR == bfindreplacecaseless(this, (bstring) &t, (bstring) &u, pos)) bstringThrow("Failure in findreplacecaseless"); return *this; } void String::Remove(int pos, int len) { if (BSTR_ERR == bdelete(this, pos, len)) bstringThrow("Failure in remove"); } void String::Truncate(int len) { if (len < 0) return; if (len < slen) { slen = len; data[len] = '\0'; } } void String::leftTrim(const String& b) { if (!b.slen) return; int l = invFindAnyChar(b, 0); if (l == BSTR_ERR) l = slen; Remove(0, l); } void String::rightTrim(const String& b) { if (!b.slen) return; int l = invReverseFindAnyChar(b, slen - 1); if (l == BSTR_ERR) l = slen - 1; slen = l + 1; if (mlen > slen) data[slen] = '\0'; } void String::toUppercase() { if (BSTR_ERR == btoupper((bstring) this)) bstringThrow("Failure in toupper"); } void String::toLowercase() { if (BSTR_ERR == btolower((bstring) this)) bstringThrow("Failure in tolower"); } void String::Repeat(int count) { count *= slen; if (count <= 0) { Truncate(0); return; } if (BSTR_ERR == bpattern(this, count)) bstringThrow("Failure in repeat"); } /* int String::gets(bNgetc getcPtr, void * parm, char terminator) { if (mlen <= 0) bstringThrow("Write protection error"); bstring b = bgets(getcPtr, parm, terminator); if (b == NULL) { slen = 0; return -1; } *this = *b; bdestroy(b); return 0; } int String::read(bNread readPtr, void * parm) { if (mlen <= 0) bstringThrow("Write protection error"); bstring b = bread(readPtr, parm); if (b == NULL) { slen = 0; return -1; } *this = *b; bdestroy(b); return 0; } */ const String operator+(const char *a, const String& b) { return String(a) + b; } const String operator+(const uint8 * a, const String& b) { return String((const char *)a) + b; } const String operator+(char c, const String& b) { return String(c) + b; } const String operator+(unsigned char c, const String& b) { return String(c) + b; } const String operator+(const tagbstring& x, const String& b) { return String(x) + b; } String String::normalizedPath(char sep, const bool includeLastSep) const { int rightLimit = slen - 1; while (rightLimit >= 0 && data[rightLimit] == sep) rightLimit--; return includeLastSep || rightLimit < 0 ? midString(0, rightLimit+1) + sep : midString(0, rightLimit+1); } String & String::replaceAllTokens(char from, char to) { if (!from || !to) return *this; for (int i = 0; i < slen; i++) if (data[i] == from) data[i] = to; return *this; } String String::replacedAll(const String & find, const String & by) const { int count = Count(find); int replacedLength = (slen + count * (by.slen - find.slen)) + 1; char * rep = (char*)malloc(replacedLength); if (rep == NULL) return String(); int pos = 0, repos = 0, newPos = 0; while ((newPos = Find(find, pos)) != -1) { memcpy(&rep[repos], &data[pos], (newPos - pos)); repos += (newPos - pos); memcpy(&rep[repos], by.data, by.slen); repos += by.slen; newPos += find.slen; pos = newPos; } // Copy the remaining part if (pos < slen) { memcpy(&rep[repos], &data[pos], slen - pos); repos += slen - pos; } rep[repos] = '\0'; return String(rep, replacedLength - 1, replacedLength); } // Get the string up to the first occurrence of the given string const String String::upToFirst(const String & find, const bool includeFind) const { int pos = Find(find, 0); if (pos == -1) return includeFind ? "" : *this; return midString(0, includeFind ? pos + find.getLength() : pos); } // Get the string up to the last occurrence of the given string const String String::upToLast(const String & find, const bool includeFind) const { int pos = reverseFind(find, slen - 1); if (pos == -1) return includeFind ? "" : *this; return midString(0, includeFind ? pos + find.getLength() : pos); } // Get the string from the first occurrence of the given string const String String::fromFirst(const String & find, const bool includeFind) const { int pos = Find(find, 0); if (pos == -1) return includeFind ? *this : String(); return midString(includeFind ? pos : pos + find.getLength(), slen); } // Get the string from the first occurrence of the given string const String String::dropUpTo(const String & find, const bool includeFind) const { const unsigned int pos = Find(find); if (pos == (unsigned int)-1) return *this; return midString(includeFind ? pos : pos + find.getLength(), slen); } // Get the string from the last occurrence of the given string const String String::fromLast(const String & find, const bool includeFind) const { int pos = reverseFind(find, slen - 1); if (pos == -1) return includeFind ? *this : String(); return midString(includeFind ? pos : pos + find.getLength(), slen); } // Split a string when the needle is found first, returning the part before the needle, and // updating the string to start on or after the needle. const String String::splitFrom(const String & find, const bool includeFind) { int pos = Find(find, 0); if (pos == -1) { if (includeFind) { String ret(*this); *this = ""; return ret; } return String(); } int size = pos + find.getLength(); String ret = midString(0, includeFind ? size : pos); if (BSTR_ERR == bdelete(this, 0, size)) bstringThrow("Failure in remove"); return ret; } // Split a string when the needle is found first, returning the part before the needle, and // updating the string to start on or after the needle. const String String::fromTo(const String & from, const String & to, const bool includeFind) const { const int fromPos = Find(from); if (fromPos == -1) return ""; const int toPos = Find(to, fromPos + from.slen); return midString(includeFind ? fromPos : fromPos + from.slen, toPos != -1 ? (includeFind ? toPos + to.slen - fromPos : toPos - fromPos - from.slen) // If the "to" needle was not found, either we return the whole string (includeFind) or an empty string : (includeFind ? slen - fromPos : 0)); } // Get the substring up to the given needle if found, or the whole string if not, and split from here. const String String::splitUpTo(const String & find, const bool includeFind) { int pos = Find(find, 0); if (pos == -1) { String ret(*this); *this = ""; return ret; } int size = pos + find.getLength(); String ret = midString(0, includeFind ? size : pos); if (BSTR_ERR == bdelete(this, 0, size)) bstringThrow("Failure in remove"); return ret; } // Split the string at the given position. const String String::splitAt(const int pos) { String ret = midString(0, pos); if (BSTR_ERR == bdelete(this, 0, pos)) bstringThrow("Failure in remove"); return ret; } // Split the string when no more in the given set const String String::splitWhenNoMore(const String & set) { int pos = invFindAnyChar(set); String ret = midString(0, pos == -1 ? slen : pos); if (BSTR_ERR == bdelete(this, 0, ret.slen)) bstringThrow("Failure in remove"); return ret; } // Align the string so it fits in the given length. String String::alignedTo(const int length, int side, char fill) const { if (slen > length) return *this; int diffInSize = (length - slen), leftCount = side == 1 ? diffInSize : (side == 0 ? diffInSize / 2 : 0), rightCount = side == -1 ? diffInSize : (side == 0 ? (diffInSize + 1) / 2 : 0); return String().Filled(leftCount, fill) + *this + Filled(rightCount, fill); } void String::writeProtect() { if (mlen >= 0) mlen = -1; } void String::writeAllow() { if (mlen == -1) mlen = slen + (slen == 0); else if (mlen < 0) bstringThrow("Cannot unprotect a constant"); } uint32 getUnicode(const unsigned char * & array) { // Get the current char const uint8 c = *array; if ((c & 0x80)) { // The data is in the 7 low bits uint32 dataMask = 0x7f; // The count bit mask uint32 bitCountMask = 0x40; // The consumption count int charCount = 0; while ((c & bitCountMask) != 0 && bitCountMask) { ++charCount; dataMask >>= 1; bitCountMask >>= 1; } // Get the few bits remaining here uint32 n = (c & dataMask); // Then extract the remaining bits ++array; while (--charCount >= 0 && *array) { const uint8 extra = *array; // Make sure it's a valid UTF8 encoding if ((extra & 0xc0) != 0x80) break; // Store the new bits too n <<= 6; n |= (extra & 0x3f); ++array; } return n; } if (c) ++array; return c; } int getUnicodeCharCount(const unsigned char * array) { const uint8 c = *array; if ((c & 0x80)) { // The count bit mask uint32 bitCountMask = 0x40; // The consumption count int charCount = 0; while ((c & bitCountMask) != 0 && bitCountMask) { ++charCount; bitCountMask >>= 1; } return charCount; } return c == 0 ? 0 : 1; } // Get the i-th unicode char. uint32 String::getUnicodeChar(int pos) const { // 1. Iterate to the given position const unsigned char * array = data; while (pos && *array) { (void)getUnicode(array); pos--; } return getUnicode(array); } // This counts the number of Unicode characters in the string. size_t String::getUnicodeLength() const { size_t size = 0; unsigned char * array = data, * end = data + slen; int cnt = getUnicodeCharCount(&array[size]); while (cnt && array < end) { size ++; array += cnt; cnt = getUnicodeCharCount(array); } return size; } #if (WantRegularExpressions == 1) // Forward declare the functions we'll be using namespace RegExp { #define TestReturn(cond, error) if (cond) return (error) struct Branch { /** Index of the bracket pair */ int bracketIndex; /** Position of branching in the regular expression */ const char * branchPos; }; struct BracketPair { /** Index of the branch for this pair */ int branchIndex; /** The number of branches in this pair */ int branchesCount; /** First char after '(' in expression */ const char * ptr; /** Text length in char between parenthesis */ int len; }; /** A Capture */ struct Cap { const char * ptr; int len; }; /** Default construct the information with stack based allocation, and only expand if required to heap based allocation */ struct RegexpInfo { enum RegExError { NotFound = -1, SyntaxError = -2, UnexpectedQuantifier = -3, UnbalancedBrackets = -4, BadSetOfCharacter = -5, BadMetaCharacter = -6, CapturesArrayTooSmall = -7, NotEnoughMemory = -8, }; /** Store all branches in the regular expression. */ Branch * branches; int branchesCount; /** Store all brackets pair in the expression. The first entry contains the whole expression */ BracketPair * brackets; int bracketsCount; /* Array of captures provided by the user */ Cap * caps; int capsCount; /** You can use (?i) to start the Regular Expression, or use caseInsensitive search while matching */ bool caseSensitive; /** First position for the match */ int firstMatchPos; /** The stack based allocation for the branches */ Branch stackBranch[10]; /** The stack based allocation for the pairs */ BracketPair stackPair[10]; /** Construction */ RegexpInfo(Cap * capts, int capsCount, bool caseSensitive = true) : branches(stackBranch), branchesCount(0), brackets(stackPair), bracketsCount(0), caps(capts), capsCount(capsCount), caseSensitive(caseSensitive), firstMatchPos(-1) {} ~RegexpInfo() { if (branches != stackBranch) { free(branches); branches = 0; } if (brackets != stackPair) { free(brackets); brackets = 0; } } /** This is used for marking allowed metacharacters and quantifiers */ static uint8 charMap[256]; bool addBrackets(const char * ptr, int len) { if ((size_t)(bracketsCount + 1) >= ArrSz(stackPair)) { // Need to re-allocate the brackets pair BracketPair * newPair = (BracketPair *)malloc((bracketsCount + 1) * sizeof(BracketPair)); if (!newPair) return false; memcpy(newPair, brackets, bracketsCount * sizeof(BracketPair)); if (brackets != stackPair) free(brackets); brackets = newPair; } brackets[bracketsCount].ptr = ptr; brackets[bracketsCount].len = len; bracketsCount++; return true; } bool addBranch(int index, const char * pos) { if ((size_t)(branchesCount + 1) >= ArrSz(stackBranch)) { // Need to re-allocate the brackets pair Branch * newBranch = (Branch *)malloc((branchesCount + 1) * sizeof(Branch)); if (!newBranch) return false; memcpy(newBranch, branches, branchesCount * sizeof(Branch)); if (branches != stackBranch) free(branches); branches = newBranch; } branches[branchesCount].bracketIndex = index; branches[branchesCount].branchPos = pos; branchesCount++; return true; } /** Helper functions */ static inline int operatorLen(const char *re) { return re[0] == '\\' && re[1] == 'x' ? 4 : re[0] == '\\' ? 2 : 1; } static inline int getOperatorLen(const char *re, int regExpLen) { if (re[0] != '[') return operatorLen(re); int len = 1; while (len < regExpLen && re[len] != ']') len += operatorLen(re + len); return regExpLen > len ? len + 1 : 0; } static inline int hexToInteger(const uint8 * s) { return (charMap[s[0]] & 0xF0) | (charMap[s[1]] >> 4); } int matchOperand(const uint8 * re, const uint8 * s) { switch (*re) { // If we reach those, the expression is malformed case '|': return SyntaxError; case '$': return NotFound; // Any char would do, let's accept it case '.': break; case '\\': // Metacharacters switch (re[1]) { case 'S': TestReturn((charMap[*s] & 4), NotFound); break; case 's': TestReturn(!(charMap[*s] & 4), NotFound); break; case 'd': TestReturn(!(charMap[*s] & 8), NotFound); break; case 'x': // Match byte, \xHH where HH is hexadecimal byte representaion TestReturn(hexToInteger(re + 2) != *s, NotFound); break; default: // Valid metacharacter check is done in internalProcess() TestReturn(re[1] != s[0], NotFound); break; } break; // Any normal character default: if (!caseSensitive) { TestReturn(tolower(*re) != tolower(*s), NotFound); } else { TestReturn(*re != *s, NotFound); } break; } return 1; } // This is used to match a "[]" based set int matchSet(const char *re, int regExpLen, const char *s) { int len = 0, result = -1, invert = re[0] == '^'; // If the set is inverted, eat the first char if (invert) re++,regExpLen--; // Inverted logic, result should stay 0 for matching while (len <= regExpLen && re[len] != ']' && result <= 0) { // Check range if ( (re[len] != '-' && re[len + 1] == '-' && re[len + 2] != ']') && (re[len + 2] != '\0')) { result = !caseSensitive ? (*s >= re[len] && *s <= re[len + 2]) : (tolower(*s) >= tolower(re[len]) && tolower(*s) <= tolower(re[len + 2])); len += 3; } else { result = matchOperand((uint8 * )re + len, (uint8 *)s); len += operatorLen(re + len); } } return (invert && result <= 0) || (!invert && result > 0) ? 1 : -1; } int internalProcess(const char *re, int regExpLen, const char *s, int s_len, int bracketIndex) { int reIndex = 0, strIndex = 0, n, step; for (reIndex = strIndex = 0; reIndex < regExpLen && strIndex <= s_len; reIndex += step) { // Handle quantifiers. Get the length of the chunk. step = re[reIndex] == '(' ? brackets[bracketIndex + 1].len + 2 : getOperatorLen(re + reIndex, regExpLen - reIndex); TestReturn(charMap[(uint8)re[reIndex]] & 2, UnexpectedQuantifier); TestReturn(step <= 0, BadSetOfCharacter); // Is it a quantifier ? if (reIndex + step < regExpLen && (charMap[(uint8)re[reIndex + step]] & 2)) { if (re[reIndex + step] == '?') { // Zero or once int result = internalProcess(re + reIndex, step, s + strIndex, s_len - strIndex, bracketIndex); strIndex += result > 0 ? result : 0; // Silent failure reIndex++; } else if (re[reIndex + step] == '+' || re[reIndex + step] == '*') { // Zero|One or more bool greedy = true; int strMatchEndIndex = strIndex, strEndIndex = strIndex, strFirstMatchIndex, strSecondMatchIndex = -1, reEndIndex; // Check for greedyness mode reEndIndex = reIndex + step + 1; if (reEndIndex < regExpLen && re[reEndIndex] == '?') { greedy = false; reEndIndex++; } do { // Match the quantified expression only once if ((strFirstMatchIndex = internalProcess(re + reIndex, step, s + strMatchEndIndex, s_len - strMatchEndIndex, bracketIndex)) > 0) strMatchEndIndex += strFirstMatchIndex; // Is only one match required (and this one failed) ? if (re[reIndex + step] == '+' && strFirstMatchIndex < 0) break; // Check if we have something after quantifier if (reEndIndex >= regExpLen) // Nothing left in expression after quantifier, let's try to eat as much as possible strEndIndex = strMatchEndIndex; // Try to match the rest of the expression after the quantifier else if ((strSecondMatchIndex = internalProcess(re + reEndIndex, regExpLen - reEndIndex, s + strMatchEndIndex, s_len - strMatchEndIndex, bracketIndex)) >= 0) // Matched after quantifier strEndIndex = strMatchEndIndex + strSecondMatchIndex; // Continue if greedy and something else to eat if (strEndIndex > strIndex && !greedy) break; } while (strFirstMatchIndex > 0); // Try zero match too (try to match the rest of the expression after quantifier) if (strFirstMatchIndex < 0 && re[reIndex + step] == '*' && strSecondMatchIndex < 0 && (strSecondMatchIndex = internalProcess(re + reEndIndex, regExpLen - reEndIndex, s + strIndex, s_len - strIndex, bracketIndex)) > 0) strEndIndex = strIndex + strSecondMatchIndex; TestReturn(re[reIndex + step] == '+' && strEndIndex == strIndex, NotFound); // Check the rest of the regex in case of zero match (ie: on *) TestReturn(strEndIndex == strIndex && reEndIndex < regExpLen && strSecondMatchIndex < 0, NotFound); // Expression matched completely return strEndIndex; } continue; } n = 0; switch(re[reIndex]) { // Is a set ? case '[': n = matchSet(re + reIndex + 1, regExpLen - (reIndex + 2), s + strIndex); TestReturn(n <= 0, NotFound); break; // Is a bracket ? case '(': n = NotFound; bracketIndex++; TestReturn(bracketIndex >= bracketsCount, SyntaxError); if (regExpLen - (reIndex + step) <= 0) { // Nothing after the bracket n = processBranch(s + strIndex, s_len - strIndex, bracketIndex); } else { // Need to process the branch, and then the remaining expression int j2; for (j2 = 0; j2 <= s_len - strIndex; j2++) { if ( (n = processBranch(s + strIndex, s_len - (strIndex + j2), bracketIndex)) >= 0 && internalProcess(re + reIndex + step, regExpLen - (reIndex + step), s + strIndex + n, s_len - (strIndex + n), bracketIndex) >= 0) break; } } TestReturn(n < 0, n); if (caps != NULL && n > 0) { caps[bracketIndex - 1].ptr = s + strIndex; caps[bracketIndex - 1].len = n; } break; // Begin of section case '^': TestReturn(strIndex != 0, NotFound); break; // End of section case '$': TestReturn(strIndex != s_len, NotFound); break; default: TestReturn(strIndex >= s_len, NotFound); n = matchOperand((uint8 * ) (re + reIndex), (uint8 * ) (s + strIndex)); TestReturn(n <= 0, n); break; } strIndex += n; } return strIndex; } // Process branch points int processBranch(const char *s, int s_len, int branchIndex) { const BracketPair * b = &brackets[branchIndex]; int i = 0, len, result; const char *p; do { p = i == 0 ? b->ptr : branches[b->branchIndex + i - 1].branchPos + 1; len = b->branchesCount == 0 ? b->len : (i == b->branchesCount ? b->ptr + b->len - p : branches[b->branchIndex + i].branchPos - p); result = internalProcess(p, len, s, s_len, branchIndex); } while (result <= 0 && i++ < b->branchesCount); // At least 1 iteration return result; } int process(const char *s, int s_len) { int result = -1; bool isAnchored = brackets[0].ptr[0] == '^'; for (int i = 0; i <= s_len; i++) { result = processBranch(s + i, s_len - i, 0); if (result >= 0) { // Completed search firstMatchPos = i; result += i; break; } if (isAnchored) break; } return result; } void setupBranchPoints() { int i, j; Branch tmp; // Sort branches first based on bracketIndex for (i = 0; i < branchesCount; i++) { for (j = i + 1; j < branchesCount; j++) { if (branches[i].bracketIndex > branches[j].bracketIndex) { tmp = branches[i]; branches[i] = branches[j]; branches[j] = tmp; } } } // Sort brackets too to know beforehand where (and how many branches) the branches points for (i = j = 0; i < bracketsCount; i++) { brackets[i].branchesCount = 0; brackets[i].branchIndex = j; while (j < branchesCount && branches[j].bracketIndex == i) { brackets[i].branchesCount++; j++; } } } int analyze(const char *re, int regExpLen, const char *s, int s_len, int & capsRequired) { int step = 0, depth = 0; // Capture the complete expression in the first bracket TestReturn(!addBrackets(re, regExpLen), NotEnoughMemory); // Compute the number of brackets and branches required, and test basic validity for the expression for (int i = 0; i < regExpLen; i += step) { step = getOperatorLen(re + i, regExpLen - i); if (re[i] == '|') { TestReturn(!addBranch(brackets[bracketsCount - 1].len == -1 ? bracketsCount - 1 : depth, re+i), NotEnoughMemory); } else if (re[i] == '\\') { TestReturn(i >= regExpLen - 1, BadMetaCharacter); if (re[i + 1] == 'x') { // Hex digit specification must follow hexadecimal numbers TestReturn(re[i + 1] == 'x' && i >= regExpLen - 3, BadMetaCharacter); TestReturn(re[i + 1] == 'x' && !((charMap[(uint8)re[i + 2]] & 0xF8) && (charMap[(uint8)re[i + 3]] & 0xF8)), BadMetaCharacter); } else { TestReturn((RegexpInfo::charMap[(uint8)re[i + 1]] & 1) == 0, BadMetaCharacter); } } else if (re[i] == '(') { // Need to increment the depth to set the correct index on matching parenthesis depth++; TestReturn(!addBrackets(re+i+1, -1), NotEnoughMemory); capsRequired++; TestReturn(s && capsCount > 0 && bracketsCount - 1 > capsCount, CapturesArrayTooSmall); } else if (re[i] == ')') { // Fix index int ind = brackets[bracketsCount - 1].len == -1 ? bracketsCount - 1 : depth; brackets[ind].len = &re[i] - brackets[ind].ptr; depth--; TestReturn(depth < 0, UnbalancedBrackets); // Shortcut bad expression failure TestReturn(i > 0 && re[i - 1] == '(', NotFound); } } TestReturn(depth != 0, UnbalancedBrackets); setupBranchPoints(); return 0; } }; // Stores : bit 0 = metacharacter // bit 1 = quantifier // bit 2 = space // bit 3 = digit // bit 4-7 = hex/decimal value uint8 RegexpInfo::charMap[] = { 0 /* 0 */, 0 /* 1 */, 0 /* 2 */, 0 /* 3 */, 0 /* 4 */, 0 /* 5 */, 0 /* 6 */, 0 /* 7 */, 0 /* 8 */, 4 /* 9 */, 4 /* 10 */, 4 /* 11 */, 4 /* 12 */, 4 /* 13 */, 0 /* 14 */, 0 /* 15 */, 0 /* 16 */, 0 /* 17 */, 0 /* 18 */, 0 /* 19 */, 0 /* 20 */, 0 /* 21 */, 0 /* 22 */, 0 /* 23 */, 0 /* 24 */, 0 /* 25 */, 0 /* 26 */, 0 /* 27 */, 0 /* 28 */, 0 /* 29 */, 0 /* 30 */, 0 /* 31 */, 4 /* ' ' */, 0 /* '!' */, 0 /* '"' */, 0 /* '#' */, 1 /* '$' */, 0 /* '%' */, 0 /* '&' */, 0 /* ''' */, 1 /* '(' */, 1 /* ')' */, 3 /* '*' */, 3 /* '+' */, 0 /* ',' */, 0 /* '-' */, 1 /* '.' */, 0 /* '/' */, 8 /* '0' */, 0x18 /* '1' */, 0x28 /* '2' */, 0x38 /* '3' */, 0x48 /* '4' */, 0x58 /* '5' */, 0x68 /* '6' */, 0x78 /* '7' */, 0x88 /* '8' */, 0x98 /* '9' */, 0 /* ':' */, 0 /* ';' */, 0 /* '<' */, 0 /* '=' */, 0 /* '>' */, 3 /* '?' */, 0 /* '@' */, 0xA0 /* 'A' */, 0xB0 /* 'B' */, 0xC0 /* 'C' */, 0xD0 /* 'D' */, 0xE0 /* 'E' */, 0xF0 /* 'F' */, 0 /* 'G' */, 0 /* 'H' */, 0 /* 'I' */, 0 /* 'J' */, 0 /* 'K' */, 0 /* 'L' */, 0 /* 'M' */, 0 /* 'N' */, 0 /* 'O' */, 0 /* 'P' */, 0 /* 'Q' */, 0 /* 'R' */, 1 /* 'S' */, 0 /* 'T' */, 0 /* 'U' */, 0 /* 'V' */, 0 /* 'W' */, 0 /* 'X' */, 0 /* 'Y' */, 0 /* 'Z' */, 1 /* '[' */, 1 /* '\' */, 1 /* ']' */, 1 /* '^' */, 0 /* '_' */, 0 /* '`' */, 0xA0 /* 'a' */, 0xB0 /* 'b' */, 0xC0 /* 'c' */, 0xD1 /* 'd' */, 0xE0 /* 'e' */, 0xF0 /* 'f' */, 0 /* 'g' */, 0 /* 'h' */, 0 /* 'i' */, 0 /* 'j' */, 0 /* 'k' */, 0 /* 'l' */, 0 /* 'm' */, 0 /* 'n' */, 0 /* 'o' */, 0 /* 'p' */, 0 /* 'q' */, 0 /* 'r' */, 1 /* 's' */, 0 /* 't' */, 0 /* 'u' */, 0 /* 'v' */, 0 /* 'w' */, 0 /* 'x' */, 0 /* 'y' */, 0 /* 'z' */, 0 /* '{' */, 1 /* '|' */, 0 /* '}' */, 0 /* '~' */, 0 /* '' */, }; static int RegExpMatch(const char *regexp, const char *s, int s_len, Cap * caps, int capsCount, int & capsRequired, bool caseSensitive, int * matchPos = 0) { if (memcmp(regexp, "(?i)", 4) == 0) { caseSensitive = false; regexp += 4; } RegexpInfo info(caps, capsCount, caseSensitive); capsRequired = 0; int res = info.analyze(regexp, strlen(regexp), s, s_len, capsRequired); if (res != 0) return res; if (!s) return 0; res = info.process(s, s_len); if (matchPos) *matchPos = info.firstMatchPos; return res; } } // Match the expression against the compiled regular expression int String::regExMatch(const String & regEx, String * captures, int & capCount, const bool caseSensitive, int * matchPos) const { // If no captures, run a trial run to get the amount of captures required if (!captures) return RegExp::RegExpMatch(regEx, (const char*)0, 0, 0, 0, capCount, caseSensitive); RegExp::Cap * caps = new RegExp::Cap[capCount]; if (!caps) return NotEnoughMemory; memset(caps, 0, capCount * sizeof(*caps)); int res = RegExp::RegExpMatch(regEx, (const char*)data, slen, caps, capCount, capCount, caseSensitive, matchPos); for (int i = 0; i < capCount; i++) captures[i] = String(caps[i].ptr, caps[i].len); delete[] caps; return res; } // Fit the regular expression for this string bool String::regExFit(const String & regEx, const bool caseSensitive, void ** captOpt, int * captCount) const { int localCap = 0; void * localOpt = 0; int & capturesCount = captCount ? *captCount : localCap; void * & capturesOpt = captOpt ? *captOpt : localOpt; if (!capturesCount || !capturesOpt) { if (RegExp::RegExpMatch(regEx, (const char*)0, 0, 0, 0, capturesCount, caseSensitive) < 0) return false; // Allocate the buffer now capturesOpt = malloc(capturesCount * sizeof(RegExp::Cap)); } // Cast the buffer to something we can support RegExp::Cap * caps = (RegExp::Cap *)capturesOpt; if (!caps) return false; memset(caps, 0, capturesCount * sizeof(*caps)); int req = 0; int res = RegExp::RegExpMatch(regEx, (const char*)data, slen, caps, capturesCount, req, caseSensitive); if (&capturesOpt == &localOpt) free(localOpt); return res >= 0; } // Return a string with value replaced as regular expression String String::regExReplace(const String & regEx, const String & _with, const bool caseSensitive, int iterations) const { int capCount = 0; int res = RegExp::RegExpMatch(regEx, (const char*)0, 0, 0, 0, capCount, caseSensitive); if (res) return ""; RegExp::Cap * caps = new RegExp::Cap[capCount + 1]; if (!caps) return ""; int processedData = 0; String ret; while(iterations--) { memset(caps, 0, capCount * sizeof(*caps)); String with = _with; int matchPos = 0; res = RegExp::RegExpMatch(regEx, (const char*)data + processedData, slen - processedData, caps+1, capCount, capCount, caseSensitive, &matchPos); if (res <= 0) break; caps[0].ptr = (const char*)data + processedData + matchPos; caps[0].len = res - processedData - matchPos; ret += midString(processedData, matchPos) + with.splitUpTo("\\"); while (with.slen) { int noMoreDigitPos = with.invFindAnyChar("0123456789"); if (noMoreDigitPos == 0) { ret += '\\'; } else if (noMoreDigitPos == -1) { noMoreDigitPos = with.getLength(); } if (noMoreDigitPos > 0) { int pos = with.midString(0, noMoreDigitPos).parseInt(10); if (pos <= capCount) { ret += String(caps[pos].ptr, caps[pos].len); with.splitAt(noMoreDigitPos); } else { // Output the slashed text ret += '\\'; ret += with.data[0]; with.splitAt(1); } } // Output the rest ret += with.splitUpTo("\\"); } processedData += res; } // Copy the remaining part ret += midString(processedData, slen); delete[] caps; return ret; } #endif } // namespace Bstrlib
32.738085
234
0.466876
e9005849663072c857de6b3ce39173f8d237bd98
6,361
cpp
C++
src/appleseed/renderer/modeling/bsdf/bsdfsample.cpp
joelbarmettlerUZH/appleseed
6da8ff684aa33648a247a4d4005bb4595862e0b3
[ "MIT" ]
1,907
2015-01-04T00:13:22.000Z
2022-03-30T15:14:00.000Z
src/appleseed/renderer/modeling/bsdf/bsdfsample.cpp
joelbarmettlerUZH/appleseed
6da8ff684aa33648a247a4d4005bb4595862e0b3
[ "MIT" ]
1,196
2015-01-04T10:50:01.000Z
2022-03-04T09:18:22.000Z
src/appleseed/renderer/modeling/bsdf/bsdfsample.cpp
joelbarmettlerUZH/appleseed
6da8ff684aa33648a247a4d4005bb4595862e0b3
[ "MIT" ]
373
2015-01-06T10:08:53.000Z
2022-03-12T10:25:57.000Z
// // This source file is part of appleseed. // Visit https://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2015-2018 Esteban Tovagliari, The appleseedhq Organization // // 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. // // Interface header. #include "bsdfsample.h" // appleseed.foundation headers. #include "foundation/math/basis.h" // Standard headers. #include <cmath> using namespace foundation; namespace renderer { namespace { void compute_normal_derivatives( const BSDF::LocalGeometry& local_geometry, const Vector3f& o, const Vector3f& dodx, const Vector3f& dody, foundation::Vector3f& dndx, foundation::Vector3f& dndy, float& ddndx, float& ddndy) { // // Reference: // // Physically Based Rendering, first edition, page 513. // const Vector3f dndu(local_geometry.m_shading_point->get_dndu(0)); const Vector3f dndv(local_geometry.m_shading_point->get_dndv(0)); const Vector2f duvdx(local_geometry.m_shading_point->get_duvdx(0)); const Vector2f duvdy(local_geometry.m_shading_point->get_duvdy(0)); dndx = dndu * duvdx[0] + dndv * duvdx[1]; dndy = dndu * duvdy[0] + dndv * duvdy[1]; const Vector3f& n = local_geometry.m_shading_basis.get_normal(); ddndx = dot(dodx, n) + dot(o, dndx); ddndy = dot(dody, n) + dot(o, dndy); } } // // BSDFSample class implementation. // void BSDFSample::compute_specular_reflected_differentials( const BSDF::LocalGeometry& local_geometry, const Dual3f& outgoing) { if (outgoing.has_derivatives()) { // // Reference: // // Physically Based Rendering, first edition, page 513. // const Vector3f dodx = -(outgoing.get_dx() - outgoing.get_value()); const Vector3f dody = -(outgoing.get_dy() - outgoing.get_value()); Vector3f dndx, dndy; float ddndx, ddndy; compute_normal_derivatives( local_geometry, outgoing.get_value(), dodx, dody, dndx, dndy, ddndx, ddndy); const Vector3f& n = local_geometry.m_shading_basis.get_normal(); const float dot_on = dot(outgoing.get_value(), n); const Vector3f& i = m_incoming.get_value(); m_incoming.set_derivatives( i - dodx + 2.0f * Vector3f(dot_on * dndx + ddndx * n), i - dody + 2.0f * Vector3f(dot_on * dndy + ddndy * n)); } } void BSDFSample::compute_specular_transmitted_differentials( const BSDF::LocalGeometry& local_geometry, const float eta, const bool is_entering, const Dual3f& outgoing) { if (outgoing.has_derivatives()) { const Vector3f dodx = -(outgoing.get_dx() - outgoing.get_value()); const Vector3f dody = -(outgoing.get_dy() - outgoing.get_value()); Vector3f dndx, dndy; float ddndx, ddndy; compute_normal_derivatives( local_geometry, outgoing.get_value(), dodx, dody, dndx, dndy, ddndx, ddndy); const Vector3f& n = local_geometry.m_shading_basis.get_normal(); const float dot_on = dot(-outgoing.get_value(), n); const float dot_in = std::abs(dot(m_incoming.get_value(), n)); const float mu = eta * dot_on - dot_in; const float a = eta - (square(eta) * dot_on) / dot_in; const float dmudx = a * ddndx; const float dmudy = a * ddndy; const Vector3f& i = m_incoming.get_value(); m_incoming.set_derivatives( i - eta * dodx - Vector3f(mu * dndx + dmudx * n), i - eta * dody - Vector3f(mu * dndy + dmudy * n)); } } void BSDFSample::compute_glossy_reflected_differentials( const BSDF::LocalGeometry& local_geometry, const float roughness, const Dual3f& outgoing) { // TODO: scale differentials based on roughness. compute_specular_reflected_differentials(local_geometry, outgoing); } void BSDFSample::compute_glossy_transmitted_differentials( const BSDF::LocalGeometry& local_geometry, const float eta, const float roughness, const bool is_entering, const Dual3f& outgoing) { // TODO: scale differentials based on roughness. compute_specular_transmitted_differentials( local_geometry, eta, is_entering, outgoing); } void BSDFSample::compute_diffuse_differentials(const Dual3f& outgoing) { if (outgoing.has_derivatives()) { // 1/25 of the hemisphere. // Reference: https://www.pbrt.org/texcache.pdf const auto& i = m_incoming.get_value(); const Basis3f basis(m_incoming.get_value()); m_incoming.set_derivatives( normalize(i + 0.2f * basis.get_tangent_u()), normalize(i + 0.2f * basis.get_tangent_v())); } } } // namespace renderer
32.454082
80
0.622386
e90096d4600be5ce516dff8cb5d49840032d3696
4,037
cpp
C++
src/rschol/geometry/FiniteDifference.cpp
jeffc71/rank_structured_cholesky
1b5df69bd6b9187435897786e7461cdd341e8db0
[ "Unlicense" ]
3
2017-09-07T16:14:33.000Z
2021-09-18T04:47:06.000Z
src/rschol/geometry/FiniteDifference.cpp
jeffchadwick/rank_structured_cholesky
1b5df69bd6b9187435897786e7461cdd341e8db0
[ "Unlicense" ]
null
null
null
src/rschol/geometry/FiniteDifference.cpp
jeffchadwick/rank_structured_cholesky
1b5df69bd6b9187435897786e7461cdd341e8db0
[ "Unlicense" ]
null
null
null
////////////////////////////////////////////////////////////////////// // Copyright (c) 2015, Jeff Chadwick and David Bindel // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder 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. ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // FiniteDifference.cpp: Implementation // ////////////////////////////////////////////////////////////////////// #include "FiniteDifference.h" ////////////////////////////////////////////////////////////////////// // Stencils for finite difference laplacian operator ////////////////////////////////////////////////////////////////////// const Real FiniteDifference::LAPLACIAN_STENCIL[] = { -1.0, 2.0, -1.0 }; const int FiniteDifference::LAPLACIAN_STENCIL_INDEX[] = { -1, 0, 1 }; const int FiniteDifference::LAPLACIAN_STENCIL_SZ = 3; ////////////////////////////////////////////////////////////////////// // Generates a finite difference Laplacian matrix with Dirichlet // boundary conditions, assuming a constant grid cell spacing of h ////////////////////////////////////////////////////////////////////// void FiniteDifference::generateLaplacian( SPARSE_MATRIX &L, Tuple3i gridDivisions, Real h ) { int sz = GRID_SIZE( gridDivisions ); Real inv_h2 = 1.0 / ( h * h ); L.resize( sz, sz ); L.clear(); FOR_ALL_3D_POINTS( gridDivisions, idx ) { // Apply the Laplacian along each dimension for ( int d = 0; d < 3; d++ ) { for ( int lap_idx = 0; lap_idx < LAPLACIAN_STENCIL_SZ; lap_idx++ ) { Tuple3i entry_idx = idx; int row_idx = INDEX_3D_GRID( gridDivisions, idx ); int offset = LAPLACIAN_STENCIL_INDEX[ lap_idx ]; entry_idx[d] += offset; if ( !checkFDIndex( gridDivisions, entry_idx ) ) continue; int col_idx = INDEX_3D_GRID( gridDivisions, entry_idx ); L( row_idx, col_idx ) += LAPLACIAN_STENCIL[ lap_idx ] * inv_h2; } } } } // Evaluates a function at all points of a finite difference grid void FiniteDifference::evaluateGridEntries( const Tuple3i &gridDivisions, Real h, const ScalarEvaluator &f, VECTOR &x ) { int sz = GRID_SIZE( gridDivisions ); VEC3F p; int x_idx = 0; x.resizeAndWipe( sz ); FOR_ALL_3D_POINTS( gridDivisions, idx ) { p = assignPoint( idx, h ); x( x_idx ) = f( p ); x_idx++; } }
36.369369
81
0.583354
e902b84a9cfaa34c2c09dffbd1740b49dbc860ff
2,122
hpp
C++
file_access.hpp
piccolo255/mhd2d-solver
be635bb6f5f8d3d06a9fa02a15801eedd1f50306
[ "Unlicense" ]
null
null
null
file_access.hpp
piccolo255/mhd2d-solver
be635bb6f5f8d3d06a9fa02a15801eedd1f50306
[ "Unlicense" ]
null
null
null
file_access.hpp
piccolo255/mhd2d-solver
be635bb6f5f8d3d06a9fa02a15801eedd1f50306
[ "Unlicense" ]
null
null
null
#ifndef FILE_ACCESS_HPP_INCLUDED #define FILE_ACCESS_HPP_INCLUDED // Read value of a key, show warning and default value if the key is missing template <class T> T readEntry ( boost::property_tree::ptree pt , std::string section , std::string name , T defaultValue ); // Read settings from property tree: Div B corrector void readParamsDivBCorrector ( boost::property_tree::ptree &pt , t_params &params ); // Read settings from property tree: Shock tube problem void readProblemShockTube ( boost::property_tree::ptree &pt , t_params &params , t_data &data ); // Read settings from property tree: Explosion problem void readProblemExplosion ( boost::property_tree::ptree &pt , t_params &params , t_data &data ); // Read settings from property tree: Orszag-Tang vortex problem void readProblemOTVortex ( boost::property_tree::ptree &pt , t_params &params , t_data &data ); // Read settings from property tree: Plasma sheet problem void readProblemPlasmaSheet ( boost::property_tree::ptree &pt , t_params &params , t_data &data ); // Read settings from property tree: Wave test problem void readProblemWaveTest ( boost::property_tree::ptree &pt , t_params &params , t_data &data ); // Print info about the binary file structure (with hints for plotting with GNUplot) void outputBinaryHintFile ( const std::string filename , const t_params &params , const t_output &output_grid ); // Output grid data file in binary format void outputGridDataBinary ( const t_output &output , const t_params &params , const t_data &data , int step , int index , int divb_nxfirst , int divb_nxlast , int divb_nyfirst , int divb_nylast , double uumax ); // Output grid data file in textual format void outputGridDataText ( const t_output &output , const t_params &params , const t_data &data , int step , int index , int divb_nxfirst , int divb_nxlast , int divb_nyfirst , int divb_nylast , double uumax ); #endif // FILE_ACCESS_HPP_INCLUDED
26.525
84
0.696984
e902e7570e55f2b4279d1fec67f70f1d90a0049a
2,629
cpp
C++
Supermicro/benchmarks/maskrcnn/implementations/pytorch_SYS-420GP-TNAR/maskrcnn_benchmark/csrc/cuda/nhwc/transforms.cpp
gglin001/training_results_v1.1
58fd4103f0f465bda6eb56a06a74b7bbccbbcf24
[ "Apache-2.0" ]
48
2020-07-29T18:09:23.000Z
2021-10-09T01:53:33.000Z
Supermicro/benchmarks/maskrcnn/implementations/pytorch_SYS-420GP-TNAR/maskrcnn_benchmark/csrc/cuda/nhwc/transforms.cpp
gglin001/training_results_v1.1
58fd4103f0f465bda6eb56a06a74b7bbccbbcf24
[ "Apache-2.0" ]
21
2021-08-31T08:34:50.000Z
2022-03-17T11:42:10.000Z
NVIDIA/benchmarks/maskrcnn/implementations/pytorch/maskrcnn_benchmark/csrc/cuda/nhwc/transforms.cpp
lablup/training_results_v0.7
f5bb59aa0f8b18b602763abe47d1d24d0d54b197
[ "Apache-2.0" ]
42
2020-08-01T06:41:24.000Z
2022-01-20T10:33:08.000Z
/****************************************************************************** * * Copyright (c) 2018-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 <ATen/ATen.h> #include <ATen/NativeFunctions.h> #include <ATen/Config.h> #include <ATen/cuda/CUDAConfig.h> #include <ATen/cuda/Exceptions.h> #include <cudnn.h> #include "THC/THC.h" #include "torch/torch.h" #include <ATen/cudnn/cudnn-wrapper.h> #include "Descriptors.h" //#include <ATen/cudnn/Types.h> #include "Types.h" #include <ATen/cudnn/Utils.h> #include "ParamsHash.h" #include <ATen/TensorUtils.h> #include <functional> #include <iterator> #include <sstream> #include <algorithm> #include <memory> #include <mutex> #include <stdint.h> #include <unordered_map> namespace at { namespace native { namespace nhwc { at::Tensor cudnnNhwcToNchw(const at::Tensor& input) { int N = input.size(0); int C = input.size(3); int H = input.size(1); int W = input.size(2); at::Tensor output = at::empty({N,C,H,W}, input.options()); auto handle = getCudnnHandle(); auto dataType = getCudnnDataType(input); at::native::nhwc::TensorDescriptor in_desc; at::native::nchw::TensorDescriptor out_desc; in_desc.set(input); out_desc.set(output); float alpha=1.0f; float beta=0.0f; cudnnTransformTensor(handle, &alpha, in_desc.desc(), input.data_ptr(), &beta, out_desc.desc(), output.data_ptr()); return output; } at::Tensor cudnnNchwToNhwc(const at::Tensor& input) { int N = input.size(0); int C = input.size(1); int H = input.size(2); int W = input.size(3); at::Tensor output = at::empty({N,H,W,C}, input.options()); auto handle = getCudnnHandle(); auto dataType = getCudnnDataType(input); at::native::nchw::TensorDescriptor in_desc; at::native::nhwc::TensorDescriptor out_desc; in_desc.set(input); out_desc.set(output); float alpha=1.0f; float beta=0.0f; cudnnTransformTensor(handle, &alpha, in_desc.desc(), input.data_ptr(), &beta, out_desc.desc(), output.data_ptr()); return output; } }}}
30.929412
116
0.670978
e90363efe24449aee213324e34ea26d2fc0605bd
644
cpp
C++
NotSoFAT32/Fat32Directory.cpp
Rohansi/NotSoFAT32
fd6b6a5528b5af00518a83b3d1c2061a87b007e3
[ "MIT" ]
1
2020-11-03T16:11:59.000Z
2020-11-03T16:11:59.000Z
NotSoFAT32/Fat32Directory.cpp
Rohansi/NotSoFAT32
fd6b6a5528b5af00518a83b3d1c2061a87b007e3
[ "MIT" ]
1
2020-11-04T11:34:44.000Z
2020-11-04T11:34:44.000Z
NotSoFAT32/Fat32Directory.cpp
Rohansi/NotSoFAT32
fd6b6a5528b5af00518a83b3d1c2061a87b007e3
[ "MIT" ]
null
null
null
#include "Interface/IFat32Directory.hpp" #include "Fat32Directory.hpp" #include "Fat32Root.hpp" #include "Fat32File.hpp" #include <algorithm> #include <string> Fat32Directory::Fat32Directory(std::weak_ptr<Fat32Disk> fat32, std::shared_ptr<DirectoryEntry> entry) : IFat32Directory(fat32) { m_fat32 = fat32; m_entry = entry; } Fat32Directory::Fat32Directory(Fat32Directory &&other) : IFat32Directory(std::move(other)) { m_fat32 = std::move(other.m_fat32); m_entry = std::move(other.m_entry); } void Fat32Directory::initialize() { IFat32Directory::m_entry = std::move(m_entry); IFat32Directory::initialize(); }
23
101
0.728261
e9072b9c77026ef3859d16d1fb06f7b3292b71ea
4,641
cc
C++
compiler/optimizing/dex_cache_array_fixups_arm.cc
lifansama/xposed_art_n
ec3fbe417d74d4664cec053d91dd4e3881176374
[ "MIT" ]
234
2017-07-18T05:30:27.000Z
2022-01-07T02:21:31.000Z
compiler/optimizing/dex_cache_array_fixups_arm.cc
lifansama/xposed_art_n
ec3fbe417d74d4664cec053d91dd4e3881176374
[ "MIT" ]
21
2017-07-18T04:56:09.000Z
2018-08-10T17:32:16.000Z
compiler/optimizing/dex_cache_array_fixups_arm.cc
lifansama/xposed_art_n
ec3fbe417d74d4664cec053d91dd4e3881176374
[ "MIT" ]
56
2017-07-18T10:37:10.000Z
2022-01-07T02:19:22.000Z
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "dex_cache_array_fixups_arm.h" #include "base/arena_containers.h" #include "utils/dex_cache_arrays_layout-inl.h" namespace art { namespace arm { /** * Finds instructions that need the dex cache arrays base as an input. */ class DexCacheArrayFixupsVisitor : public HGraphVisitor { public: explicit DexCacheArrayFixupsVisitor(HGraph* graph) : HGraphVisitor(graph), dex_cache_array_bases_(std::less<const DexFile*>(), // Attribute memory use to code generator. graph->GetArena()->Adapter(kArenaAllocCodeGenerator)) {} void MoveBasesIfNeeded() { for (const auto& entry : dex_cache_array_bases_) { // Bring the base closer to the first use (previously, it was in the // entry block) and relieve some pressure on the register allocator // while avoiding recalculation of the base in a loop. HArmDexCacheArraysBase* base = entry.second; base->MoveBeforeFirstUserAndOutOfLoops(); } } private: void VisitLoadString(HLoadString* load_string) OVERRIDE { // If this is a load with PC-relative access to the dex cache methods array, // we need to add the dex cache arrays base as the special input. if (load_string->GetLoadKind() == HLoadString::LoadKind::kDexCachePcRelative) { // Initialize base for target dex file if needed. const DexFile& dex_file = load_string->GetDexFile(); HArmDexCacheArraysBase* base = GetOrCreateDexCacheArrayBase(dex_file); // Update the element offset in base. DexCacheArraysLayout layout(kArmPointerSize, &dex_file); base->UpdateElementOffset(layout.StringOffset(load_string->GetStringIndex())); // Add the special argument base to the load. load_string->AddSpecialInput(base); } } void VisitInvokeStaticOrDirect(HInvokeStaticOrDirect* invoke) OVERRIDE { // If this is an invoke with PC-relative access to the dex cache methods array, // we need to add the dex cache arrays base as the special input. if (invoke->HasPcRelativeDexCache()) { // Initialize base for target method dex file if needed. MethodReference target_method = invoke->GetTargetMethod(); HArmDexCacheArraysBase* base = GetOrCreateDexCacheArrayBase(*target_method.dex_file); // Update the element offset in base. DexCacheArraysLayout layout(kArmPointerSize, target_method.dex_file); base->UpdateElementOffset(layout.MethodOffset(target_method.dex_method_index)); // Add the special argument base to the method. DCHECK(!invoke->HasCurrentMethodInput()); invoke->AddSpecialInput(base); } } HArmDexCacheArraysBase* GetOrCreateDexCacheArrayBase(const DexFile& dex_file) { // Ensure we only initialize the pointer once for each dex file. auto lb = dex_cache_array_bases_.lower_bound(&dex_file); if (lb != dex_cache_array_bases_.end() && !dex_cache_array_bases_.key_comp()(&dex_file, lb->first)) { return lb->second; } // Insert the base at the start of the entry block, move it to a better // position later in MoveBaseIfNeeded(). HArmDexCacheArraysBase* base = new (GetGraph()->GetArena()) HArmDexCacheArraysBase(dex_file); HBasicBlock* entry_block = GetGraph()->GetEntryBlock(); entry_block->InsertInstructionBefore(base, entry_block->GetFirstInstruction()); dex_cache_array_bases_.PutBefore(lb, &dex_file, base); return base; } using DexCacheArraysBaseMap = ArenaSafeMap<const DexFile*, HArmDexCacheArraysBase*, std::less<const DexFile*>>; DexCacheArraysBaseMap dex_cache_array_bases_; }; void DexCacheArrayFixups::Run() { if (graph_->HasIrreducibleLoops()) { // Do not run this optimization, as irreducible loops do not work with an instruction // that can be live-in at the irreducible loop header. return; } DexCacheArrayFixupsVisitor visitor(graph_); visitor.VisitInsertionOrder(); visitor.MoveBasesIfNeeded(); } } // namespace arm } // namespace art
41.070796
97
0.721181
e9086e1fbdc59a6691aded7cb2e54cb31b51dba5
15,212
cpp
C++
nfc/src/DOOM/doomclassic/timidity/resample.cpp
1337programming/leviathan
ca9a31b45c25fd23f361d67136ae5ac6b98d2628
[ "Apache-2.0" ]
null
null
null
nfc/src/DOOM/doomclassic/timidity/resample.cpp
1337programming/leviathan
ca9a31b45c25fd23f361d67136ae5ac6b98d2628
[ "Apache-2.0" ]
null
null
null
nfc/src/DOOM/doomclassic/timidity/resample.cpp
1337programming/leviathan
ca9a31b45c25fd23f361d67136ae5ac6b98d2628
[ "Apache-2.0" ]
null
null
null
/* TiMidity -- Experimental MIDI to WAVE converter Copyright (C) 1995 Tuukka Toivonen <toivonen@clinet.fi> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. resample.c */ #include <math.h> #include <stdio.h> #include <stdlib.h> #include "config.h" #include "common.h" #include "instrum.h" #include "playmidi.h" #include "output.h" #include "controls.h" #include "tables.h" #include "resample.h" #ifdef LINEAR_INTERPOLATION # if defined(LOOKUP_HACK) && defined(LOOKUP_INTERPOLATION) # define RESAMPLATION \ v1=src[ofs>>FRACTION_BITS];\ v2=src[(ofs>>FRACTION_BITS)+1];\ *dest++ = v1 + (iplookup[(((v2-v1)<<5) & 0x03FE0) | \ ((ofs & FRACTION_MASK) >> (FRACTION_BITS-5))]); # else # define RESAMPLATION \ v1=src[ofs>>FRACTION_BITS];\ v2=src[(ofs>>FRACTION_BITS)+1];\ *dest++ = v1 + (((v2-v1) * (ofs & FRACTION_MASK)) >> FRACTION_BITS); # endif # define INTERPVARS sample_t v1, v2 #else /* Earplugs recommended for maximum listening enjoyment */ # define RESAMPLATION *dest++=src[ofs>>FRACTION_BITS]; # define INTERPVARS #endif #define FINALINTERP if (ofs == le) *dest++=src[ofs>>FRACTION_BITS]; /* So it isn't interpolation. At least it's final. */ extern sample_t *resample_buffer; void Real_Tim_Free( void *pt ); /*************** resampling with fixed increment *****************/ static sample_t *rs_plain(int v, int32_t *countptr) { /* Play sample until end, then free the voice. */ INTERPVARS; Voice *vp=&voice[v]; sample_t *dest=resample_buffer, *src=vp->sample->data; int32_t ofs=vp->sample_offset, incr=vp->sample_increment, le=vp->sample->data_length, count=*countptr; #ifdef PRECALC_LOOPS int32_t i; if (incr<0) incr = -incr; /* In case we're coming out of a bidir loop */ /* Precalc how many times we should go through the loop. NOTE: Assumes that incr > 0 and that ofs <= le */ i = (le - ofs) / incr + 1; if (i > count) { i = count; count = 0; } else count -= i; while (i--) { RESAMPLATION; ofs += incr; } if (ofs >= le) { FINALINTERP; vp->status=VOICE_FREE; ctl->note(v); *countptr-=count+1; } #else /* PRECALC_LOOPS */ while (count--) { RESAMPLATION; ofs += incr; if (ofs >= le) { FINALINTERP; vp->status=VOICE_FREE; ctl->note(v); *countptr-=count+1; break; } } #endif /* PRECALC_LOOPS */ vp->sample_offset=ofs; /* Update offset */ return resample_buffer; } static sample_t *rs_loop(Voice *vp, int32_t count) { /* Play sample until end-of-loop, skip back and continue. */ INTERPVARS; int32_t ofs=vp->sample_offset, incr=vp->sample_increment, le=vp->sample->loop_end, ll=le - vp->sample->loop_start; sample_t *dest=resample_buffer, *src=vp->sample->data; #ifdef PRECALC_LOOPS int32_t i; while (count) { if (ofs >= le) /* NOTE: Assumes that ll > incr and that incr > 0. */ ofs -= ll; /* Precalc how many times we should go through the loop */ i = (le - ofs) / incr + 1; if (i > count) { i = count; count = 0; } else count -= i; while (i--) { RESAMPLATION; ofs += incr; } } #else while (count--) { RESAMPLATION; ofs += incr; if (ofs>=le) ofs -= ll; /* Hopefully the loop is longer than an increment. */ } #endif vp->sample_offset=ofs; /* Update offset */ return resample_buffer; } static sample_t *rs_bidir(Voice *vp, int32_t count) { INTERPVARS; int32_t ofs=vp->sample_offset, incr=vp->sample_increment, le=vp->sample->loop_end, ls=vp->sample->loop_start; sample_t *dest=resample_buffer, *src=vp->sample->data; #ifdef PRECALC_LOOPS int32_t le2 = le<<1, ls2 = ls<<1, i; /* Play normally until inside the loop region */ if (ofs <= ls) { /* NOTE: Assumes that incr > 0, which is NOT always the case when doing bidirectional looping. I have yet to see a case where both ofs <= ls AND incr < 0, however. */ i = (ls - ofs) / incr + 1; if (i > count) { i = count; count = 0; } else count -= i; while (i--) { RESAMPLATION; ofs += incr; } } /* Then do the bidirectional looping */ while(count) { /* Precalc how many times we should go through the loop */ i = ((incr > 0 ? le : ls) - ofs) / incr + 1; if (i > count) { i = count; count = 0; } else count -= i; while (i--) { RESAMPLATION; ofs += incr; } if (ofs>=le) { /* fold the overshoot back in */ ofs = le2 - ofs; incr *= -1; } else if (ofs <= ls) { ofs = ls2 - ofs; incr *= -1; } } #else /* PRECALC_LOOPS */ /* Play normally until inside the loop region */ if (ofs < ls) { while (count--) { RESAMPLATION; ofs += incr; if (ofs>=ls) break; } } /* Then do the bidirectional looping */ if (count>0) while (count--) { RESAMPLATION; ofs += incr; if (ofs>=le) { /* fold the overshoot back in */ ofs = le - (ofs - le); incr = -incr; } else if (ofs <= ls) { ofs = ls + (ls - ofs); incr = -incr; } } #endif /* PRECALC_LOOPS */ vp->sample_increment=incr; vp->sample_offset=ofs; /* Update offset */ return resample_buffer; } /*********************** vibrato versions ***************************/ /* We only need to compute one half of the vibrato sine cycle */ static int vib_phase_to_inc_ptr(int phase) { if (phase < VIBRATO_SAMPLE_INCREMENTS/2) return VIBRATO_SAMPLE_INCREMENTS/2-1-phase; else if (phase >= 3*VIBRATO_SAMPLE_INCREMENTS/2) return 5*VIBRATO_SAMPLE_INCREMENTS/2-1-phase; else return phase-VIBRATO_SAMPLE_INCREMENTS/2; } static int32_t update_vibrato(Voice *vp, int sign) { int32_t depth; int phase, pb; double a; if (vp->vibrato_phase++ >= 2*VIBRATO_SAMPLE_INCREMENTS-1) vp->vibrato_phase=0; phase=vib_phase_to_inc_ptr(vp->vibrato_phase); if (vp->vibrato_sample_increment[phase]) { if (sign) return -vp->vibrato_sample_increment[phase]; else return vp->vibrato_sample_increment[phase]; } /* Need to compute this sample increment. */ depth=vp->sample->vibrato_depth<<7; if (vp->vibrato_sweep) { /* Need to update sweep */ vp->vibrato_sweep_position += vp->vibrato_sweep; if (vp->vibrato_sweep_position >= (1<<SWEEP_SHIFT)) vp->vibrato_sweep=0; else { /* Adjust depth */ depth *= vp->vibrato_sweep_position; depth >>= SWEEP_SHIFT; } } a = FSCALE(((double)(vp->sample->sample_rate) * (double)(vp->frequency)) / ((double)(vp->sample->root_freq) * (double)(play_mode->rate)), FRACTION_BITS); pb=(int)((sine(vp->vibrato_phase * (SINE_CYCLE_LENGTH/(2*VIBRATO_SAMPLE_INCREMENTS))) * (double)(depth) * VIBRATO_AMPLITUDE_TUNING)); if (pb<0) { pb=-pb; a /= bend_fine[(pb>>5) & 0xFF] * bend_coarse[pb>>13]; } else a *= bend_fine[(pb>>5) & 0xFF] * bend_coarse[pb>>13]; /* If the sweep's over, we can store the newly computed sample_increment */ if (!vp->vibrato_sweep) vp->vibrato_sample_increment[phase]=(int32_t) a; if (sign) a = -a; /* need to preserve the loop direction */ return (int32_t) a; } static sample_t *rs_vib_plain(int v, int32_t *countptr) { /* Play sample until end, then free the voice. */ INTERPVARS; Voice *vp=&voice[v]; sample_t *dest=resample_buffer, *src=vp->sample->data; int32_t le=vp->sample->data_length, ofs=vp->sample_offset, incr=vp->sample_increment, count=*countptr; int cc=vp->vibrato_control_counter; /* This has never been tested */ if (incr<0) incr = -incr; /* In case we're coming out of a bidir loop */ while (count--) { if (!cc--) { cc=vp->vibrato_control_ratio; incr=update_vibrato(vp, 0); } RESAMPLATION; ofs += incr; if (ofs >= le) { FINALINTERP; vp->status=VOICE_FREE; ctl->note(v); *countptr-=count+1; break; } } vp->vibrato_control_counter=cc; vp->sample_increment=incr; vp->sample_offset=ofs; /* Update offset */ return resample_buffer; } static sample_t *rs_vib_loop(Voice *vp, int32_t count) { /* Play sample until end-of-loop, skip back and continue. */ INTERPVARS; int32_t ofs=vp->sample_offset, incr=vp->sample_increment, le=vp->sample->loop_end, ll=le - vp->sample->loop_start; sample_t *dest=resample_buffer, *src=vp->sample->data; int cc=vp->vibrato_control_counter; #ifdef PRECALC_LOOPS int32_t i; int vibflag=0; while (count) { /* Hopefully the loop is longer than an increment */ if(ofs >= le) ofs -= ll; /* Precalc how many times to go through the loop, taking the vibrato control ratio into account this time. */ i = (le - ofs) / incr + 1; if(i > count) i = count; if(i > cc) { i = cc; vibflag = 1; } else cc -= i; count -= i; while(i--) { RESAMPLATION; ofs += incr; } if(vibflag) { cc = vp->vibrato_control_ratio; incr = update_vibrato(vp, 0); vibflag = 0; } } #else /* PRECALC_LOOPS */ while (count--) { if (!cc--) { cc=vp->vibrato_control_ratio; incr=update_vibrato(vp, 0); } RESAMPLATION; ofs += incr; if (ofs>=le) ofs -= ll; /* Hopefully the loop is longer than an increment. */ } #endif /* PRECALC_LOOPS */ vp->vibrato_control_counter=cc; vp->sample_increment=incr; vp->sample_offset=ofs; /* Update offset */ return resample_buffer; } static sample_t *rs_vib_bidir(Voice *vp, int32_t count) { INTERPVARS; int32_t ofs=vp->sample_offset, incr=vp->sample_increment, le=vp->sample->loop_end, ls=vp->sample->loop_start; sample_t *dest=resample_buffer, *src=vp->sample->data; int cc=vp->vibrato_control_counter; #ifdef PRECALC_LOOPS int32_t le2=le<<1, ls2=ls<<1, i; int vibflag = 0; /* Play normally until inside the loop region */ while (count && (ofs <= ls)) { i = (ls - ofs) / incr + 1; if (i > count) i = count; if (i > cc) { i = cc; vibflag = 1; } else cc -= i; count -= i; while (i--) { RESAMPLATION; ofs += incr; } if (vibflag) { cc = vp->vibrato_control_ratio; incr = update_vibrato(vp, 0); vibflag = 0; } } /* Then do the bidirectional looping */ while (count) { /* Precalc how many times we should go through the loop */ i = ((incr > 0 ? le : ls) - ofs) / incr + 1; if(i > count) i = count; if(i > cc) { i = cc; vibflag = 1; } else cc -= i; count -= i; while (i--) { RESAMPLATION; ofs += incr; } if (vibflag) { cc = vp->vibrato_control_ratio; incr = update_vibrato(vp, (incr < 0)); vibflag = 0; } if (ofs >= le) { /* fold the overshoot back in */ ofs = le2 - ofs; incr *= -1; } else if (ofs <= ls) { ofs = ls2 - ofs; incr *= -1; } } #else /* PRECALC_LOOPS */ /* Play normally until inside the loop region */ if (ofs < ls) { while (count--) { if (!cc--) { cc=vp->vibrato_control_ratio; incr=update_vibrato(vp, 0); } RESAMPLATION; ofs += incr; if (ofs>=ls) break; } } /* Then do the bidirectional looping */ if (count>0) while (count--) { if (!cc--) { cc=vp->vibrato_control_ratio; incr=update_vibrato(vp, (incr < 0)); } RESAMPLATION; ofs += incr; if (ofs>=le) { /* fold the overshoot back in */ ofs = le - (ofs - le); incr = -incr; } else if (ofs <= ls) { ofs = ls + (ls - ofs); incr = -incr; } } #endif /* PRECALC_LOOPS */ vp->vibrato_control_counter=cc; vp->sample_increment=incr; vp->sample_offset=ofs; /* Update offset */ return resample_buffer; } sample_t *resample_voice(int v, int32_t *countptr) { int32_t ofs; uint8_t modes; Voice *vp=&voice[v]; if (!(vp->sample->sample_rate)) { /* Pre-resampled data -- just update the offset and check if we're out of data. */ ofs=vp->sample_offset >> FRACTION_BITS; /* Kind of silly to use FRACTION_BITS here... */ if (*countptr >= (vp->sample->data_length>>FRACTION_BITS) - ofs) { /* Note finished. Free the voice. */ vp->status = VOICE_FREE; ctl->note(v); /* Let the caller know how much data we had left */ *countptr = (vp->sample->data_length>>FRACTION_BITS) - ofs; } else vp->sample_offset += *countptr << FRACTION_BITS; return vp->sample->data+ofs; } /* Need to resample. Use the proper function. */ modes=vp->sample->modes; if (vp->vibrato_control_ratio) { if ((modes & MODES_LOOPING) && ((modes & MODES_ENVELOPE) || (vp->status==VOICE_ON || vp->status==VOICE_SUSTAINED))) { if (modes & MODES_PINGPONG) return rs_vib_bidir(vp, *countptr); else return rs_vib_loop(vp, *countptr); } else return rs_vib_plain(v, countptr); } else { if ((modes & MODES_LOOPING) && ((modes & MODES_ENVELOPE) || (vp->status==VOICE_ON || vp->status==VOICE_SUSTAINED))) { if (modes & MODES_PINGPONG) return rs_bidir(vp, *countptr); else return rs_loop(vp, *countptr); } else return rs_plain(v, countptr); } } void pre_resample(Sample * sp) { double a, xdiff; int32_t incr, ofs, newlen, count; int16_t *newdata, *dest, *src = (int16_t *) sp->data; int16_t v1, v2, v3, v4, *vptr; static const char note_name[12][3] = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" }; ctl->cmsg(CMSG_INFO, VERB_NOISY, " * pre-resampling for note %d (%s%d)", sp->note_to_use, note_name[sp->note_to_use % 12], (sp->note_to_use & 0x7F) / 12); a = ((double) (sp->sample_rate) * freq_table[(int) (sp->note_to_use)]) / ((double) (sp->root_freq) * play_mode->rate); newlen = (int32_t)(sp->data_length / a); dest = newdata = (int16_t*)safe_malloc(newlen >> (FRACTION_BITS - 1)); count = (newlen >> FRACTION_BITS) - 1; ofs = incr = (sp->data_length - (1 << FRACTION_BITS)) / count; if (--count) *dest++ = src[0]; /* Since we're pre-processing and this doesn't have to be done in real-time, we go ahead and do the full sliding cubic interpolation. */ while (--count) { vptr = src + (ofs >> FRACTION_BITS); v1 = *(vptr - 1); v2 = *vptr; v3 = *(vptr + 1); v4 = *(vptr + 2); xdiff = FSCALENEG(ofs & FRACTION_MASK, FRACTION_BITS); *dest++ = (int16_t)(v2 + (xdiff / 6.0) * (-2 * v1 - 3 * v2 + 6 * v3 - v4 + xdiff * (3 * (v1 - 2 * v2 + v3) + xdiff * (-v1 + 3 * (v2 - v3) + v4)))); ofs += incr; } if (ofs & FRACTION_MASK) { v1 = src[ofs >> FRACTION_BITS]; v2 = src[(ofs >> FRACTION_BITS) + 1]; *dest++ = v1 + (((v2 - v1) * (ofs & FRACTION_MASK)) >> FRACTION_BITS); } else *dest++ = src[ofs >> FRACTION_BITS]; sp->data_length = newlen; sp->loop_start = (int32_t)(sp->loop_start / a); sp->loop_end = (int32_t)(sp->loop_end / a); Real_Tim_Free(sp->data); sp->data = (sample_t *) newdata; sp->sample_rate = 0; }
20.584574
76
0.619445
e9095f5c3976ebb5e723a494ff5ea410ceeea824
1,831
cc
C++
pw_result/result_test.cc
LuDuda/pigweed
dcd7230895a234156bc7b6e5061e6936627c5fbb
[ "Apache-2.0" ]
null
null
null
pw_result/result_test.cc
LuDuda/pigweed
dcd7230895a234156bc7b6e5061e6936627c5fbb
[ "Apache-2.0" ]
null
null
null
pw_result/result_test.cc
LuDuda/pigweed
dcd7230895a234156bc7b6e5061e6936627c5fbb
[ "Apache-2.0" ]
null
null
null
// Copyright 2020 The Pigweed Authors // // 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 // // https://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 "pw_result/result.h" #include "gtest/gtest.h" namespace pw { namespace { TEST(Result, CreateOk) { Result<const char*> res("hello"); EXPECT_TRUE(res.ok()); EXPECT_EQ(res.status(), OkStatus()); EXPECT_EQ(res.value(), "hello"); } TEST(Result, CreateNotOk) { Result<int> res(Status::DataLoss()); EXPECT_FALSE(res.ok()); EXPECT_EQ(res.status(), Status::DataLoss()); } TEST(Result, ValueOr) { Result<int> good(3); Result<int> bad(Status::DataLoss()); EXPECT_EQ(good.value_or(42), 3); EXPECT_EQ(bad.value_or(42), 42); } TEST(Result, ConstructType) { struct Point { Point(int a, int b) : x(a), y(b) {} int x; int y; }; Result<Point> origin{std::in_place, 0, 0}; ASSERT_TRUE(origin.ok()); ASSERT_EQ(origin.value().x, 0); ASSERT_EQ(origin.value().y, 0); } Result<float> Divide(float a, float b) { if (b == 0) { return Status::InvalidArgument(); } return a / b; } TEST(Divide, ReturnOk) { Result<float> res = Divide(10, 5); ASSERT_TRUE(res.ok()); EXPECT_EQ(res.value(), 2.0f); } TEST(Divide, ReturnNotOk) { Result<float> res = Divide(10, 0); EXPECT_FALSE(res.ok()); EXPECT_EQ(res.status(), Status::InvalidArgument()); } } // namespace } // namespace pw
23.779221
80
0.67231
e90ae0565c37d5f0e74b9139ce7411ccba6f1ba1
604
cpp
C++
C-C++/activitySelection(Greedy).cpp
psinha30/dataStructure-Algorithms
a5b097f9136cf458d8b95350a05ac19a99f3cbf3
[ "MIT" ]
1
2019-12-30T18:07:07.000Z
2019-12-30T18:07:07.000Z
C-C++/activitySelection(Greedy).cpp
psinha30/dataStructure-Algorithms
a5b097f9136cf458d8b95350a05ac19a99f3cbf3
[ "MIT" ]
null
null
null
C-C++/activitySelection(Greedy).cpp
psinha30/dataStructure-Algorithms
a5b097f9136cf458d8b95350a05ac19a99f3cbf3
[ "MIT" ]
1
2018-12-20T04:58:26.000Z
2018-12-20T04:58:26.000Z
#include <bits/stdc++.h> using namespace std; int i, n; struct activity { int s,f; }; bool compare(activity a1, activity a2) { return (a1.f < a2.f); } void activity_greedy(activity a[], int m) { if(m >= n) return; if(a[m].s >= a[i].f) { if(i == 0) cout << "{" << a[i].s << "," << a[i].f << "} "; cout << "{" << a[m].s << "," << a[m].f << "} "; i = m; activity_greedy(a, m + 1); } else activity_greedy(a, m + 1); } int main() { cin >> n; activity a[n]; for(int i = 0; i < n; i++) cin >> a[i].s >> a[i].f; sort(a, a+n, compare); activity_greedy(a, 0); return 0; }
13.422222
50
0.488411
e90b8019e09a093019fe759575d1090ce194170b
8,206
cpp
C++
src/mongo/s/catalog/type_config_version.cpp
LightBitsLabs/mongo
9480ef00a8df2464457ab0f31c7a336f882e8ec1
[ "Apache-2.0" ]
25
2016-12-07T09:39:51.000Z
2021-12-16T11:17:37.000Z
src/mongo/s/catalog/type_config_version.cpp
Man1029/CMONGO
c40380caa14e05509f46993aa8b8da966b09b0b5
[ "ECL-2.0", "Apache-2.0" ]
1
2015-05-29T16:12:10.000Z
2015-05-29T16:12:10.000Z
src/mongo/s/catalog/type_config_version.cpp
Man1029/CMONGO
c40380caa14e05509f46993aa8b8da966b09b0b5
[ "ECL-2.0", "Apache-2.0" ]
23
2017-01-22T03:35:26.000Z
2021-12-16T11:17:39.000Z
/** * Copyright (C) 2012 10gen Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * As a special exception, the copyright holders give permission to link the * code of portions of this program with the OpenSSL library under certain * conditions as described in each individual source file and distribute * linked combinations including the program with the OpenSSL library. You * must comply with the GNU Affero General Public License in all respects * for all of the code used other than as permitted herein. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you do not * wish to do so, delete this exception statement from your version. If you * delete this exception statement from all source files in the program, * then also delete it in the license file. */ #include "mongo/s/catalog/type_config_version.h" #include "mongo/base/status_with.h" #include "mongo/bson/bsonobj.h" #include "mongo/bson/bsonobjbuilder.h" #include "mongo/bson/util/bson_extract.h" #include "mongo/s/catalog/config_server_version.h" #include "mongo/s/catalog/legacy/config_upgrade.h" #include "mongo/util/assert_util.h" #include "mongo/util/mongoutils/str.h" namespace mongo { const std::string VersionType::ConfigNS = "config.version"; const BSONField<int> VersionType::minCompatibleVersion("minCompatibleVersion"); const BSONField<int> VersionType::currentVersion("currentVersion"); const BSONField<BSONArray> VersionType::excludingMongoVersions("excluding"); const BSONField<OID> VersionType::clusterId("clusterId"); const BSONField<OID> VersionType::upgradeId("upgradeId"); const BSONField<BSONObj> VersionType::upgradeState("upgradeState"); void VersionType::clear() { _minCompatibleVersion.reset(); _currentVersion.reset(); _excludingMongoVersions.reset(); _clusterId.reset(); _upgradeId.reset(); _upgradeState.reset(); } void VersionType::cloneTo(VersionType* other) const { other->clear(); other->_minCompatibleVersion = _minCompatibleVersion; other->_currentVersion = _currentVersion; other->_excludingMongoVersions = _excludingMongoVersions; other->_clusterId = _clusterId; other->_upgradeId = _upgradeId; other->_upgradeState = _upgradeState; } Status VersionType::validate() const { if (!_minCompatibleVersion.is_initialized()) { return {ErrorCodes::NoSuchKey, str::stream() << "missing " << minCompatibleVersion.name() << " field"}; } if (!_currentVersion.is_initialized()) { return {ErrorCodes::NoSuchKey, str::stream() << "missing " << currentVersion.name() << " field"}; } // UpgradeHistory::UpgradeHistory_NoEpochVersion is the last version without a cluster id if (getCurrentVersion() > UpgradeHistory::UpgradeHistory_NoEpochVersion && !_clusterId.is_initialized()) { return {ErrorCodes::NoSuchKey, str::stream() << "missing " << clusterId.name() << " field"}; } return Status::OK(); } BSONObj VersionType::toBSON() const { BSONObjBuilder builder; builder.append("_id", 1); if (_minCompatibleVersion) builder.append(minCompatibleVersion.name(), getMinCompatibleVersion()); if (_currentVersion) builder.append(currentVersion.name(), getCurrentVersion()); if (_excludingMongoVersions) { builder.append(excludingMongoVersions.name(), MongoVersionRange::toBSONArray(getExcludingMongoVersions())); } if (_clusterId) builder.append(clusterId.name(), getClusterId()); if (_upgradeId) { builder.append(upgradeId.name(), getUpgradeId()); builder.append(upgradeState.name(), getUpgradeState()); } return builder.obj(); } StatusWith<VersionType> VersionType::fromBSON(const BSONObj& source) { VersionType version; { long long vMinCompatibleVersion; Status status = bsonExtractIntegerField(source, minCompatibleVersion.name(), &vMinCompatibleVersion); if (!status.isOK()) return status; version._minCompatibleVersion = vMinCompatibleVersion; } { long long vCurrentVersion; Status status = bsonExtractIntegerField(source, currentVersion.name(), &vCurrentVersion); if (status.isOK()) { version._currentVersion = vCurrentVersion; } else if (status == ErrorCodes::NoSuchKey) { version._currentVersion = version._minCompatibleVersion; } else { return status; } } { BSONElement vClusterIdElem; Status status = bsonExtractTypedField(source, clusterId.name(), BSONType::jstOID, &vClusterIdElem); if (status.isOK()) { version._clusterId = vClusterIdElem.OID(); } else if (status == ErrorCodes::NoSuchKey && version.getCurrentVersion() <= UpgradeHistory::UpgradeHistory_NoEpochVersion) { // UpgradeHistory::UpgradeHistory_NoEpochVersion is the last version // without a cluster id } else { return status; } } { BSONElement vExclMongoVersionsElem; Status status = bsonExtractTypedField( source, excludingMongoVersions.name(), BSONType::Array, &vExclMongoVersionsElem); if (status.isOK()) { version._excludingMongoVersions = std::vector<MongoVersionRange>(); BSONObjIterator it(vExclMongoVersionsElem.Obj()); while (it.more()) { MongoVersionRange range; std::string errMsg; if (!range.parseBSONElement(it.next(), &errMsg)) { return {ErrorCodes::FailedToParse, errMsg}; } version._excludingMongoVersions->push_back(range); } } else if (status == ErrorCodes::NoSuchKey) { // 'excludingMongoVersions' field is optional } else { return status; } } { BSONElement vUpgradeIdElem; Status status = bsonExtractTypedField(source, upgradeId.name(), BSONType::jstOID, &vUpgradeIdElem); if (status.isOK()) { version._upgradeId = vUpgradeIdElem.OID(); } else if (status == ErrorCodes::NoSuchKey) { // 'upgradeId' field is optional } else { return status; } } if (source.hasField(upgradeState.name())) { BSONElement vUpgradeStateElem; Status status = bsonExtractTypedField( source, upgradeState.name(), BSONType::Object, &vUpgradeStateElem); if (status.isOK()) { version._upgradeState = vUpgradeStateElem.Obj().getOwned(); } else if (status == ErrorCodes::NoSuchKey) { // 'upgradeState' field is optional } else { return status; } } return version; } void VersionType::setMinCompatibleVersion(const int minCompatibleVersion) { _minCompatibleVersion = minCompatibleVersion; } void VersionType::setCurrentVersion(const int currentVersion) { _currentVersion = currentVersion; } void VersionType::setClusterId(const OID& clusterId) { invariant(clusterId.isSet()); _clusterId = clusterId; } void VersionType::setExcludingMongoVersions( const std::vector<MongoVersionRange>& excludingMongoVersions) { _excludingMongoVersions = excludingMongoVersions; } std::string VersionType::toString() const { return toBSON().toString(); } } // namespace mongo
35.991228
100
0.668535
e90c56f98148e6359b1636cd2dd13aff6c42f4cd
6,985
cpp
C++
Cursor.cpp
JermSmith/TDGame
198599ef229eb6c852dabc7ea72f5537dd10ab5c
[ "MIT" ]
null
null
null
Cursor.cpp
JermSmith/TDGame
198599ef229eb6c852dabc7ea72f5537dd10ab5c
[ "MIT" ]
null
null
null
Cursor.cpp
JermSmith/TDGame
198599ef229eb6c852dabc7ea72f5537dd10ab5c
[ "MIT" ]
null
null
null
#include "Cursor.h" #include "Util\Math.h" Cursor::Cursor(const sf::RenderWindow& window) : Tower(window) {} void Cursor::update(const sf::RenderWindow& window, const Path& path, const std::vector<std::unique_ptr<Tower>>& towers, bool bTowerBeingPlaced) { if (bTowerBeingPlaced) { // place dummy tower at the current mouse position to check what color the cursor circle should be m_position = sf::Vector2f(window.mapPixelToCoords(sf::Mouse::getPosition(window))); if (!bInterferesWithScene(towers, path)) { updatePositive(); //possible to place tower here } else { updateNegative(); //not possible to place tower here } } else { hide(); //do not show a cursor, since no tower is being placed } } void Cursor::render(sf::RenderTarget& renderer) { InteractableShape::render(renderer); renderer.draw(m_rangeCircle); } bool Cursor::bInterferesWithScene(const std::vector<std::unique_ptr<Tower>>& towers, const Path& path) { // depends on tower properties m_position and m_size float t_ = path.getWidth() / 2; // t_ is half width std::vector<sf::Vector2f> corners = {}; // vector containing all points to check for potential collision // the following assignment assumes m_position takes centre of circle (and that circle is aligned with axes, although doesn't matter for circles) corners.push_back(m_position); // centre int numOfPointsOnCircle = 16; // number of points on circle to check for possible collisions; power of 2 allows top and bottom of circle to be included for (int angle = (-numOfPointsOnCircle / 2 + 1); angle <= numOfPointsOnCircle; angle++) { corners.push_back(sf::Vector2f( m_position.x + cos(angle * PI * 2 / numOfPointsOnCircle) * getPrimaryDim(), m_position.y + sin(angle * PI * 2 / numOfPointsOnCircle) * getPrimaryDim())); // e.g. for increments of PI/4, # of divisions is 8 } /* could specify different "corners" for a square, diamond, etc. */ for (unsigned int i = 1; i < path.getVertices().size(); i++) { sf::Vector2f vo = path.getVertices().at(i - 1); sf::Vector2f vi = path.getVertices().at(i); float theta = atan2f(vi.y - vo.y, vi.x - vo.x); // angle of path segment in radians (CW is +ve from +ve x-axis) // ol is back left corner of the rectangle, ir is front right corner of the rectangle sf::Vector2f ol = sf::Vector2f(vo.x - t_*cos(theta) + t_*sin(theta), vo.y - t_*cos(theta) - t_*sin(theta)); sf::Vector2f or = sf::Vector2f(vo.x - t_*cos(theta) - t_*sin(theta), vo.y + t_*cos(theta) - t_*sin(theta)); sf::Vector2f il = sf::Vector2f(vi.x + t_*cos(theta) + t_*sin(theta), vi.y - t_*cos(theta) + t_*sin(theta)); sf::Vector2f ir = sf::Vector2f(vi.x + t_*cos(theta) - t_*sin(theta), vi.y + t_*cos(theta) + t_*sin(theta)); float m_; // slope of path segment ("down-right" is positive, "up-right" is negative) for (sf::Vector2f& corner : corners) { // check vertex interference if (i != path.getVertices().size() - 1) // NOT last vertex { if (distanceBetweenPoints(corner, vo) <= path.getVertexWidth() / sqrtf(2)) { return true; // a "corner" interferes with a vertex } } else // { if (distanceBetweenPoints(corner, vo) <= path.getVertexWidth() / sqrtf(2)) { return true; // a "corner" interferes with second-last vertex } if (distanceBetweenPoints(corner, vi) <= path.getVertexWidth() / sqrtf(2)) { return true; // a "corner" interferes with last vertex } } // check straight section interference if (theta == 0 || theta == PI || theta == -PI) { if (cos(theta) * corner.y >= cos(theta) * ol.y && cos(theta) * corner.y <= cos(theta) * ir.y && cos(theta) * corner.x >= cos(theta) * ol.x && cos(theta) * corner.x <= cos(theta) * ir.x) { return true; // a "corner" is inside the path space } } else if (theta == PI / 2 || theta == -PI / 2) { if (sin(theta) * corner.y >= sin(theta) * ol.y && sin(theta) * corner.y <= sin(theta) * ir.y && sin(theta) * corner.x <= sin(theta) * ol.x && sin(theta) * corner.x >= sin(theta) * ir.x) { return true; // a "corner" is inside the path space } } else // theta != 0, pi/2, pi, -pi/2, -pi { m_ = (vi.y - vo.y) / (vi.x - vo.x); // slope of path segment if (cos(theta) * (corner.y - m_*corner.x) > cos(theta) * (ol.y - m_*ol.x) && cos(theta) * (corner.y - m_*corner.x) < cos(theta) * (ir.y - m_*ir.x) && sin(theta) * (corner.y + (1 / m_)*corner.x) > sin(theta) * (ol.y + (1 / m_)*ol.x) && sin(theta) * (corner.y + (1 / m_)*corner.x) < sin(theta) * (ir.y + (1 / m_)*ir.x)) { return true; // a "corner" is inside the path space } } } } // above here is checking for interference between newObj and path // below here is checking for interference between newObj and other objects, assuming all objects are circles (size.x = size.y for circles) for (unsigned int i = 0; i < towers.size(); i++) { if (distanceBetweenPoints(m_position, towers.at(i)->getPosition()) < (getPrimaryDim() + towers.at(i)->getRadius())) { return true; } } // below here is checking for interference with menu if (m_position.x > sizes::WORLD_SIZE_X - (sizes::PLAYINGMENU_X + getPrimaryDim()) || // menu width + 1/2 tower radius (m_position.x < getPrimaryDim()) || m_position.y < getPrimaryDim() || m_position.y > sizes::WORLD_SIZE_Y - getPrimaryDim()) { return true; } return false; } // private methods below this line void Cursor::hide() { InteractableShape::setFillColour(sf::Color::Transparent); InteractableShape::setOutlineThickness(0); m_rangeCircle.setRadius(0); } void Cursor::updatePositive() { InteractableShape::setOutlineThickness(-2); InteractableShape::setOutlineColour(sf::Color::Cyan); InteractableShape::setPosition(m_position); m_rangeCircle.setRadius(m_range); m_rangeCircle.setFillColor(sf::Color(255, 255, 255, 63)); m_rangeCircle.setOutlineThickness(-2); m_rangeCircle.setOutlineColor(sf::Color::Green); m_rangeCircle.setPosition(m_position); } void Cursor::updateNegative() { InteractableShape::setFillColour(sf::Color::Transparent); InteractableShape::setOutlineThickness(-2); InteractableShape::setOutlineColour(sf::Color::Red); InteractableShape::setPosition(m_position); m_rangeCircle.setOutlineColor(sf::Color::Transparent); m_rangeCircle.setFillColor(sf::Color::Transparent); } void Cursor::generateWidgets(const sf::RenderWindow& window) { bnrCursorNote.setText("Click to place tower"); } void Cursor::populateHoverMenu() { m_hoverMenu.addWidget(bnrCursorNote); m_hoverMenu.showOutline(); } void Cursor::populateUpgradeMenu() { } void Cursor::hideHoverMenu() { m_hoverMenu.clearWidgets(); m_hoverMenu.hideOutline(); }
32.041284
153
0.644094
e90d5ab2a2d550f066f51c6659c4d2a1b8d878a5
8,823
cpp
C++
Source/WebKit/mg/control/license/loadSplash.cpp
VincentWei/mdolphin-core
48ffdcf587a48a7bb4345ae469a45c5b64ffad0e
[ "Apache-2.0" ]
6
2017-05-31T01:46:45.000Z
2018-06-12T10:53:30.000Z
Source/WebKit/mg/control/license/loadSplash.cpp
FMSoftCN/mdolphin-core
48ffdcf587a48a7bb4345ae469a45c5b64ffad0e
[ "Apache-2.0" ]
null
null
null
Source/WebKit/mg/control/license/loadSplash.cpp
FMSoftCN/mdolphin-core
48ffdcf587a48a7bb4345ae469a45c5b64ffad0e
[ "Apache-2.0" ]
2
2017-07-17T06:02:42.000Z
2018-09-19T10:08:38.000Z
/* ** $Id$ ** ** loadSplash.cpp: ** ** Copyright (C) 2003 ~ 2010 Beijing Feynman Software Technology Co., Ltd. ** ** All rights reserved by Feynman Software. ** ** Current maintainer: lvlei ** ** Create date: 2010-08-25 */ #include "mdconfig.h" #ifdef _MD_ENABLE_WATERMARK #include "licenseHidden.h" #include "c_files/watermark/watermark4.dat.c" #endif #ifdef _MD_ENABLE_LOADSPLASH #include "loadSplash.h" #include "sharedTimerLoadSplash.h" #include "c_files/loadsplash/_loadsplash_inner_res.c" #include "c_files/loadsplash/loadsplash01.dat.c" #include "c_files/loadsplash/loadsplash02.dat.c" #include "c_files/loadsplash/loadsplash03.dat.c" #include "c_files/loadsplash/loadsplash04.dat.c" #include "c_files/loadsplash/loadsplash05.dat.c" #include "c_files/loadsplash/loadsplash06.dat.c" #include "c_files/loadsplash/loadsplash07.dat.c" #include "c_files/loadsplash/loadsplash08.dat.c" #include "c_files/loadsplash/loadsplash09.dat.c" #include "c_files/loadsplash/loadsplash10.dat.c" #include "c_files/loadsplash/loadsplash11.dat.c" #include "c_files/loadsplash/loadsplash12.dat.c" #include "c_files/loadsplash/loadsplash13.dat.c" unsigned int loadSplash::intervalInMS = 100; HDC loadSplash::pictureDC = HDC_INVALID; int loadSplash::frameCount = 0; int loadSplash::splashWidth = 0; int loadSplash::splashHeight = 0; loadSplash::loadSplash(HWND hWnd, HDC hdc) :m_hwnd(hWnd) { m_isRunning = false; init(hdc); m_index = 0; resetTimer(); } loadSplash::~loadSplash() { finish(); DeleteMemDC(m_bgndDC); #if 0 DeleteMemDC(loadSplash::pictureDC); #endif } void loadSplash::initMemDCIfNeed(HDC hdc) { static bool hadInit = false; if (hadInit) { m_bgndDC = CreateCompatibleDC(loadSplash::pictureDC); int oldColor = SetBrushColor(m_bgndDC, PIXEL_lightwhite); FillBox(m_bgndDC, 0, 0, loadSplash::splashWidth, loadSplash::splashHeight); SetBrushColor(m_bgndDC, oldColor); return; } unsigned char *data; int len; BITMAP bitmap; data = __md_loadsplash_loadsplash_inner_res[0].data; len = __md_loadsplash_loadsplash_inner_res[0].data_len; LoadBitmapFromMem(hdc, &bitmap, data, len, "png"); loadSplash::splashWidth = bitmap.bmWidth; loadSplash::splashHeight = bitmap.bmHeight; loadSplash::pictureDC = CreateCompatibleDCEx(hdc, bitmap.bmWidth, bitmap.bmHeight); //loadSplash::pictureDC = CreateMemDCFromBitmap(hdc, &bitmap); m_bgndDC = CreateCompatibleDC(loadSplash::pictureDC); loadSplash::frameCount = TABLESIZE(__md_loadsplash_loadsplash_inner_res); // 13; int oldColor = SetBrushColor(m_bgndDC, PIXEL_lightwhite); FillBox(m_bgndDC, 0, 0, loadSplash::splashWidth, loadSplash::splashHeight); SetBrushColor(m_bgndDC, oldColor); UnloadBitmap(&bitmap); hadInit = true; } bool loadSplash::init(HDC hdc) { //FixMe: It is uncomfortable using hdc , but using Shared MemDC to save memory loadSplash::initMemDCIfNeed(hdc); return true; #if 0 RECT rc; SetRect(&rc, 0, 0, loadSplash::splashWidth, loadSplash::splashHeight); int w, h; int pitch; Uint8 *bits = LockDC(loadSplash::pictureDC, &rc, &w, &h, &pitch); memcpy (bits, bitmap.bmBits, pitch* h); UnlockDC(loadSplash::pictureDC); #endif //FillBoxWithBitmap(loadSplash::pictureDC, 0, 0, loadSplash::splashWidth, loadSplash::splashHeight, &bitmap); //UnloadBitmap(&bitmap); } void loadSplash::calcOffsetPos() { RECT rect; GetClientRect(m_hwnd, &rect); #ifdef LOADSPLASH_CENTER m_offsetX = (RECTW(rect) - loadSplash::splashWidth)/2.0; if (m_offsetX < 0) m_offsetX = 0; m_offsetY = (RECTH(rect) - loadSplash::splashHeight)/2.0; if (m_offsetY < 0) m_offsetY = 0; #else // right-top m_offsetX = RECTW(rect) - loadSplash::splashWidth; m_offsetX -= 20; //scrollWidth if (m_offsetX < 0) m_offsetX = 0; m_offsetY = 0; #endif } void loadSplash::updateBackgroundDC(HDC backGroundDC) { BitBlt(backGroundDC, m_offsetX, m_offsetY, loadSplash::splashWidth, loadSplash::splashHeight, m_bgndDC, 0, 0, -1); } void loadSplash::updateDC() { unsigned char *data; int len; BITMAP bitmap; data = __md_loadsplash_loadsplash_inner_res[m_index].data; len = __md_loadsplash_loadsplash_inner_res[m_index].data_len; LoadBitmapFromMem(loadSplash::pictureDC, &bitmap, data, len, "png"); m_index = (m_index + 1) % loadSplash::frameCount; #if 0 FillBoxWithBitmap(loadSplash::pictureDC, 0, 0, loadSplash::splashWidth, loadSplash::splashHeight, &bitmap); #else RECT rc; SetRect(&rc, 0, 0, loadSplash::splashWidth, loadSplash::splashHeight); int w, h; int pitch; gal_pixel colorKey; Uint8 *bits = LockDC(loadSplash::pictureDC, &rc, &w, &h, &pitch); memcpy (bits, bitmap.bmBits, pitch* h); colorKey = *(gal_pixel *)bits; UnlockDC(loadSplash::pictureDC); #endif SetMemDCAlpha(loadSplash::pictureDC, MEMDC_FLAG_SRCALPHA, 160); //SetMemDCColorKey(loadSplash::pictureDC, MEMDC_FLAG_SRCCOLORKEY, RGBA2Pixel(loadSplash::pictureDC, 0xFF, 0xFF, 0xFF, 0x00)); SetMemDCColorKey(loadSplash::pictureDC, MEMDC_FLAG_SRCCOLORKEY, colorKey); UnloadBitmap(&bitmap); } void loadSplash::updateToWindow() { updateDC(); HDC hdc = GetClientDC(m_hwnd); PCLIPRGN pClipRgn = CreateClipRgn(); RECT rect; GetClipRegion(hdc, pClipRgn); SetRect(&rect, m_offsetX, m_offsetY, m_offsetX + loadSplash::splashWidth, m_offsetY + loadSplash::splashHeight); IncludeClipRect(hdc, &rect); #ifdef PERFORMANCE_FIRST BitBlt(m_bgndDC, 0, 0, loadSplash::splashWidth, loadSplash::splashHeight, hdc, m_offsetX, m_offsetY, -1); BitBlt(loadSplash::pictureDC, 0, 0, loadSplash::splashWidth, loadSplash::splashHeight, hdc, m_offsetX, m_offsetY, -1); #else HDC copyDC = CreateCompatibleDC(m_bgndDC); BitBlt(m_bgndDC, 0, 0, 0, 0, copyDC, 0, 0, -1); BitBlt(loadSplash::pictureDC, 0, 0, 0, 0, copyDC, 0, 0, -1); BitBlt(copyDC, 0, 0, loadSplash::splashWidth, loadSplash::splashHeight, hdc, m_offsetX, m_offsetY, -1); DeleteMemDC(copyDC); #endif SelectClipRegion(hdc, pClipRgn); DestroyClipRgn(pClipRgn); ReleaseDC(hdc); } #if 0 void loadSplash::drawContentAndBackground(HDC backGroundDC, int offsetX, int offsetY, int maxWidth, int maxHeight) { unsigned char *data; int len; BITMAP bitmap; data = __md_loadsplash_loadsplash_inner_res[m_index].data; len = __md_loadsplash_loadsplash_inner_res[m_index].data_len; LoadBitmapFromMem(HDC_SCREEN, &bitmap, data, len, "png"); m_index = (m_index + 1) % loadSplash::frameCount; HDC imageDC = CreateMemDCFromBitmap(HDC_SCREEN,&bitmap); BitBlt(backGroundDC, offsetX, offsetY, loadSplash::splashWidth, loadSplash::splashHeight, loadSplash::pictureDC, 0, 0, -1); SetMemDCAlpha(imageDC,MEMDC_FLAG_SRCALPHA, 0x80); BitBlt(imageDC, 0, 0, loadSplash::splashWidth, loadSplash::splashHeight, loadSplash::pictureDC, 0, 0, -1); DeleteMemDC(imageDC); UnloadBitmap(&bitmap); } void loadSplash::updateToDC(HDC hdc, int offsetX, int offsetY, int maxWidth, int maxHeight) { PCLIPRGN pClipRgn = CreateClipRgn(); RECT rect; GetClipRegion(hdc, pClipRgn); SetRect(&rect, 0, 0, loadSplash::splashWidth, loadSplash::splashHeight); IncludeClipRect(hdc, &rect): BitBlt(loadSplash::pictureDC, 0, 0, loadSplash::splashWidth, loadSplash::splashHeight, hdc, offsetX, offsetY, -1); SelectClipRegion(hdc, pClipRgn); DestroyClipRgn(pClipRgn); } #endif BOOL loadSplash::timerFired() { //printf("loadSplash:timerFired\n"); if (!IsWindowVisible(m_hwnd)) { return TRUE; } updateToWindow(); return TRUE; } bool loadSplash::isRuning() { return m_isRunning; } bool loadSplash::start() { #if 0 static unsigned int t_id = 1; while (IsTimerInstalled(m_hwnd, t_id)) t_id++; // using shared timer ? if (!SetTimerEx(m_hwnd, t_id, (loadSplash::intervalInMS)/10.0, loadSplash::timerFired)) { fprintf(stderr, "loadSplash: SetTimerEx failed !\n"); m_timerID = 0; reture false; } m_timerID = t_id; #endif if (!m_isRunning) { sharedTimerLoadSplash* sharedTimer = sharedTimerLoadSplash::sharedTimerLoadSplashInstance(); sharedTimer->registerObject(this); m_isRunning = true; } return true; } bool loadSplash::finish() { #if 0 if (m_timerID){ KillTimer(m_hwnd, m_timerID); m_timerID = 0; } #endif if (m_isRunning) { sharedTimerLoadSplash* sharedTimer = sharedTimerLoadSplash::sharedTimerLoadSplashInstance(); sharedTimer->unRegisterObject(this); m_isRunning = false; } return true; } #endif //end _MD_ENABLE_LOADSPLASH
29.41
129
0.702142
e90ddfc73a37d14850a6693e7f8f62f8cecc169b
9,227
cpp
C++
lib/ofsocket.cpp
timmyw/ofsystem
6f955d53dc3025148763333bea0a11d0bce28c06
[ "MIT" ]
null
null
null
lib/ofsocket.cpp
timmyw/ofsystem
6f955d53dc3025148763333bea0a11d0bce28c06
[ "MIT" ]
null
null
null
lib/ofsocket.cpp
timmyw/ofsystem
6f955d53dc3025148763333bea0a11d0bce28c06
[ "MIT" ]
null
null
null
/* Copyright (C) 1997-2011 by Suntail.com AS, Tim Whelan Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <ofsys.h> #include <ofsocket.h> #include <ofutility.h> #include <oflogservice.h> #include <ofplatform.h> #if defined(OFOPSYS_WIN32) typedef LINGER OFLINGER; #else typedef struct linger OFLINGER; #if defined(OFOPSYS_LINUX) #include <netinet/tcp.h> #endif #endif OFSocket::OFSocket( ) : m_addr( 0 ), m_open( false ) { m_socket = socket( AF_INET, SOCK_STREAM, 0 ); set_options_(); } OFSocket::OFSocket( const OFAddress &remote ) : m_addr( remote ), m_open( false ) { m_socket = socket( AF_INET, SOCK_STREAM, 0 ); set_options_(); } OFSocket::OFSocket( OFOS::of_socket_t socketHandle ) : m_addr( 0 ), m_open( true ) { m_socket = socketHandle; set_options_(); } OFSocket::~OFSocket( ) { closeSocket( ); } ofint32 OFSocket::connect( const OFAddress &remote ) { m_addr = remote; if ( m_socket == -1 ) return ERR_INVAL_SOCKET; sockaddr *addr = (sockaddr*)m_addr.address(); ofint32 retv = ::connect( m_socket, addr, sizeof(sockaddr) ); if ( retv == -1 ) return OFUtility::translateLastSystemError( ); m_open = true; #if defined(OFOPSYS_WIN32) oflong param = 1; if (ioctlsocket(m_socket, FIONBIO, &param) == SOCKET_ERROR) #else ofuint32 param = fcntl(m_socket, F_GETFL); if (fcntl(m_socket, F_SETFL, param | O_NONBLOCK)) #endif OFLogService::debugLine("Error setting NBIO: %s", retrieveMsg(OFUtility::translateLastSystemError())); return ERR_SUCCESS; } ofint32 OFSocket::listen( ) { ofint32 ret = 0; ofint32 temp = 1; ret = setsockopt( m_socket, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<const char *>(&temp), sizeof(temp) ); if ( ret == -1 ) return ret; ret = bind( m_socket, (struct sockaddr *)m_addr.address(), sizeof(*m_addr.address()) ); if ( !ret ) ret = ::listen( m_socket, 5 ); return ret; } void OFSocket::closeSocket( ) { // cout << "OFSocket::closeSocket" << endl; if ( m_open ) { m_open = false; shutdown( m_socket, 2 ); #if defined(OFOPSYS_WIN32) closesocket( m_socket ); #else close( m_socket ); #endif } else { #if defined(OFOPSYS_WIN32) if ( m_socket != OFOS::OF_INVALID_SOCKET ) { shutdown( m_socket, 2 ); closesocket( m_socket ); } #else if (m_socket != OFOS::OF_INVALID_SOCKET) { shutdown( m_socket, 2 ); close( m_socket ); } #endif } m_socket = OFOS::OF_INVALID_SOCKET; } ofint32 OFSocket::send( void *buffer, ofuint32 bufferLength, bool *terminate /* = NULL */, ofuint32 chunkSize /* = 2048 */, ofuint32 timeOut /* = 30 */ ) { ofint32 leftToSend = bufferLength; char *tempBuf = static_cast<char*>(buffer); ofint32 cursent = 0; time_t timenow; time_t timestart; time( &timestart ); struct timeval tv; fd_set fdwrite; for(;;) { ofint32 rc = 0; FD_ZERO( &fdwrite ); FD_SET( m_socket, &fdwrite ); tv.tv_sec = 1; tv.tv_usec = 0; rc = select( m_socket+1, 0, &fdwrite, 0, &tv ); if ( terminate != 0 && *terminate ) return 1; if ( rc > 0 && FD_ISSET( m_socket, &fdwrite ) ) { time( &timestart ); ofint32 chunkToSend = (leftToSend < (ofint32)chunkSize) ?leftToSend:chunkSize; cursent = ::send( m_socket, tempBuf, chunkToSend, 0 ); if ( terminate != 0 && *terminate ) return 1; if ( cursent < 0 ) return -1; leftToSend -= cursent; tempBuf += cursent; if ( leftToSend <= 0 ) return 0; } time( &timenow ); if ( (ofuint32)timenow > timestart + timeOut ) break; } return 1; } ofint32 OFSocket::recv( void *buffer, ofuint32 bufferLength, ofuint32 &bytesReceived, bool *terminate /* = NULL */, ofuint32 chunkSize /* = 2048 */, ofuint32 timeOut /* = 30 */ ) { bytesReceived = 0; time_t timenow; time_t timestart; time( &timestart ); struct timeval tv; fd_set fdread; for(;;) { ofint32 rc = 0; FD_ZERO( &fdread ); FD_SET( m_socket, &fdread ); tv.tv_sec = 1; tv.tv_usec = 0; rc = select( m_socket+1, &fdread, 0, 0, &tv ); if ( terminate != 0 && *terminate ) return 1; if ( rc > 0 && FD_ISSET( m_socket, &fdread ) ) break; time( &timenow ); if ( (ofuint32)timenow > timestart + timeOut ) return 1; } ofint32 chunkToRead = (bufferLength < (ofuint32)chunkSize) ?bufferLength:chunkSize; ofint32 curRecv = ::recv( m_socket, static_cast<char *>(buffer), chunkToRead, 0 ); #if defined(VERBOSE_NETWORK) cout << "Socket:" << m_socket << " received " << curRecv << " bytes" << endl; #endif if ( terminate != 0 && *terminate ) return 1; if (curRecv < 0) { #if defined(VERBOSE_NETWORK) cout << "Socket:" << m_socket << " received -1" << endl; return -1; #endif } if ( curRecv > 0 ) { bytesReceived = curRecv; return 0; } return -1; } void OFSocket::startup( ) { #if defined(OFOPSYS_WIN32) WSADATA data; WSAStartup( MAKEWORD(2,0), &data ); #endif } void OFSocket::closedown() { #if defined(OFOPSYS_WIN32) WSACleanup(); #endif } ofuint32 OFSocket::getnamefromaddr(char* peerName, ofuint32 peerNameLen, struct in_addr* addr, ofuint32 addrLen, char useDNS /*=0*/) { const char* pn = "unknown"; if (!useDNS) { pn = inet_ntoa(*addr); } else { #if defined(OFOPSYS_WIN32) struct hostent* he = gethostbyaddr((char*)addr, addrLen, AF_INET); #else struct hostent* he = gethostbyaddr(addr, addrLen, AF_INET); #endif if (he && he->h_name) pn = he->h_name; } OFOS::strncpy2(peerName, pn, peerNameLen); return 0; } ofuint32 OFSocket::getpeername(char* peerName, ofuint32 peerNameLen, char useDNS /*= 0*/) { struct sockaddr_in pa; OFOS::of_socklen_t sl = sizeof(pa); int r = ::getpeername(m_socket, (sockaddr*)&pa, &sl); if (r != -1) { OFSocket::getnamefromaddr(peerName, peerNameLen, &pa.sin_addr, sizeof(pa.sin_addr), useDNS); } return r==0?ERR_SUCCESS:OFUtility::translateSystemError(r); } /* static */ void OFSocket::getHostName( char *host, ofuint32 length ) { RESETSTRING( host ); char x[1024]; gethostname( x, 1024 ); struct hostent *he = gethostbyname( x ); if ( he ) { OFOS::strncpy2( host, he->h_name, length ); } } /* static */ ofuint32 OFSocket::getLocalIP( ) { char name[1025]; gethostname( name, 1024 ); return OFPlatform::getHostIP(name); } void OFSocket::set_options_() { #if defined(OFOPSYS_LINUX) || defined(OFOPSYS_WIN32) ofuint32 f = 1; setsockopt(m_socket, IPPROTO_TCP, TCP_NODELAY, (char *)&f, sizeof(f)); setsockopt(m_socket, SOL_SOCKET, SO_KEEPALIVE, (char*)&f, sizeof(f)); f = OF_SOCK_SEND_BUFSIZE; setsockopt(m_socket, SOL_SOCKET, SO_SNDBUF, (char*)&f, sizeof(f)); f = OF_SOCK_RECV_BUFSIZE; setsockopt(m_socket, SOL_SOCKET, SO_RCVBUF, (char*)&f, sizeof(f)); struct timeval tv; memset(&tv, 0, sizeof(tv)); tv.tv_sec = 180; setsockopt(m_socket, SOL_SOCKET, SO_RCVTIMEO, (char*)&tv, sizeof(tv)); setsockopt(m_socket, SOL_SOCKET, SO_SNDTIMEO, (char*)&tv, sizeof(tv)); #endif } #if defined(UNIT_TEST) #include "UnitTest.h" int main( ofint32 argc, char *argv[] ) { UT_BATCH_START( "OFSocket class unit test" ); UT_TEST_START( 1, "OFSocket::getLocalIP" ); ofuint32 la = OFSocket::getLocalIP(); printf("local address: %08lx", la); UT_BATCH_END; return 0; } #endif // #if defined(UNIT_TEST)
24.671123
112
0.60117
e90e0e1b80506adc742ea818d1bbdf997615580f
9,408
cpp
C++
third_party/WebKit/Source/modules/encryptedmedia/NavigatorRequestMediaKeySystemAccess.cpp
wenfeifei/miniblink49
2ed562ff70130485148d94b0e5f4c343da0c2ba4
[ "Apache-2.0" ]
5,964
2016-09-27T03:46:29.000Z
2022-03-31T16:25:27.000Z
third_party/WebKit/Source/modules/encryptedmedia/NavigatorRequestMediaKeySystemAccess.cpp
w4454962/miniblink49
b294b6eacb3333659bf7b94d670d96edeeba14c0
[ "Apache-2.0" ]
459
2016-09-29T00:51:38.000Z
2022-03-07T14:37:46.000Z
third_party/WebKit/Source/modules/encryptedmedia/NavigatorRequestMediaKeySystemAccess.cpp
w4454962/miniblink49
b294b6eacb3333659bf7b94d670d96edeeba14c0
[ "Apache-2.0" ]
1,006
2016-09-27T05:17:27.000Z
2022-03-30T02:46:51.000Z
// 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 "config.h" #include "modules/encryptedmedia/NavigatorRequestMediaKeySystemAccess.h" #include "bindings/core/v8/ScriptPromiseResolver.h" #include "bindings/core/v8/ScriptState.h" #include "core/dom/DOMException.h" #include "core/dom/Document.h" #include "core/dom/ExceptionCode.h" #include "core/frame/UseCounter.h" #include "modules/encryptedmedia/EncryptedMediaUtils.h" #include "modules/encryptedmedia/MediaKeySession.h" #include "modules/encryptedmedia/MediaKeySystemAccess.h" #include "modules/encryptedmedia/MediaKeysController.h" #include "platform/EncryptedMediaRequest.h" #include "platform/Logging.h" #include "platform/network/ParsedContentType.h" #include "public/platform/WebEncryptedMediaClient.h" #include "public/platform/WebEncryptedMediaRequest.h" #include "public/platform/WebMediaKeySystemConfiguration.h" #include "public/platform/WebMediaKeySystemMediaCapability.h" #include "public/platform/WebVector.h" #include "wtf/Vector.h" #include "wtf/text/WTFString.h" namespace blink { namespace { static WebVector<WebEncryptedMediaInitDataType> convertInitDataTypes(const Vector<String>& initDataTypes) { WebVector<WebEncryptedMediaInitDataType> result(initDataTypes.size()); for (size_t i = 0; i < initDataTypes.size(); ++i) result[i] = EncryptedMediaUtils::convertToInitDataType(initDataTypes[i]); return result; } static WebVector<WebMediaKeySystemMediaCapability> convertCapabilities(const HeapVector<MediaKeySystemMediaCapability>& capabilities) { WebVector<WebMediaKeySystemMediaCapability> result(capabilities.size()); for (size_t i = 0; i < capabilities.size(); ++i) { const WebString& contentType = capabilities[i].contentType(); result[i].contentType = contentType; if (isValidContentType(contentType)) { // FIXME: Fail if there are unrecognized parameters. ParsedContentType type(capabilities[i].contentType()); result[i].mimeType = type.mimeType(); result[i].codecs = type.parameterValueForName("codecs"); } result[i].robustness = capabilities[i].robustness(); } return result; } static WebMediaKeySystemConfiguration::Requirement convertMediaKeysRequirement(const String& requirement) { if (requirement == "required") return WebMediaKeySystemConfiguration::Requirement::Required; if (requirement == "optional") return WebMediaKeySystemConfiguration::Requirement::Optional; if (requirement == "not-allowed") return WebMediaKeySystemConfiguration::Requirement::NotAllowed; // Everything else gets the default value. ASSERT_NOT_REACHED(); return WebMediaKeySystemConfiguration::Requirement::Optional; } static WebVector<WebEncryptedMediaSessionType> convertSessionTypes(const Vector<String>& sessionTypes) { WebVector<WebEncryptedMediaSessionType> result(sessionTypes.size()); for (size_t i = 0; i < sessionTypes.size(); ++i) result[i] = EncryptedMediaUtils::convertToSessionType(sessionTypes[i]); return result; } // This class allows capabilities to be checked and a MediaKeySystemAccess // object to be created asynchronously. class MediaKeySystemAccessInitializer final : public EncryptedMediaRequest { WTF_MAKE_NONCOPYABLE(MediaKeySystemAccessInitializer); public: MediaKeySystemAccessInitializer(ScriptState*, const String& keySystem, const HeapVector<MediaKeySystemConfiguration>& supportedConfigurations); ~MediaKeySystemAccessInitializer() override { } // EncryptedMediaRequest implementation. WebString keySystem() const override { return m_keySystem; } const WebVector<WebMediaKeySystemConfiguration>& supportedConfigurations() const override { return m_supportedConfigurations; } SecurityOrigin* securityOrigin() const override { return m_resolver->executionContext()->securityOrigin(); } void requestSucceeded(WebContentDecryptionModuleAccess*) override; void requestNotSupported(const WebString& errorMessage) override; ScriptPromise promise() { return m_resolver->promise(); } private: RefPtr<ScriptPromiseResolver> m_resolver; const String m_keySystem; WebVector<WebMediaKeySystemConfiguration> m_supportedConfigurations; }; MediaKeySystemAccessInitializer::MediaKeySystemAccessInitializer(ScriptState* scriptState, const String& keySystem, const HeapVector<MediaKeySystemConfiguration>& supportedConfigurations) : m_resolver(ScriptPromiseResolver::create(scriptState)) , m_keySystem(keySystem) , m_supportedConfigurations(supportedConfigurations.size()) { for (size_t i = 0; i < supportedConfigurations.size(); ++i) { const MediaKeySystemConfiguration& config = supportedConfigurations[i]; WebMediaKeySystemConfiguration webConfig; if (config.hasInitDataTypes()) { webConfig.hasInitDataTypes = true; webConfig.initDataTypes = convertInitDataTypes(config.initDataTypes()); } if (config.hasAudioCapabilities()) { webConfig.hasAudioCapabilities = true; webConfig.audioCapabilities = convertCapabilities(config.audioCapabilities()); } if (config.hasVideoCapabilities()) { webConfig.hasVideoCapabilities = true; webConfig.videoCapabilities = convertCapabilities(config.videoCapabilities()); } ASSERT(config.hasDistinctiveIdentifier()); webConfig.distinctiveIdentifier = convertMediaKeysRequirement(config.distinctiveIdentifier()); ASSERT(config.hasPersistentState()); webConfig.persistentState = convertMediaKeysRequirement(config.persistentState()); if (config.hasSessionTypes()) { webConfig.hasSessionTypes = true; webConfig.sessionTypes = convertSessionTypes(config.sessionTypes()); } // If |label| is not present, it will be a null string. webConfig.label = config.label(); m_supportedConfigurations[i] = webConfig; } } void MediaKeySystemAccessInitializer::requestSucceeded(WebContentDecryptionModuleAccess* access) { m_resolver->resolve(new MediaKeySystemAccess(m_keySystem, adoptPtr(access))); m_resolver.clear(); } void MediaKeySystemAccessInitializer::requestNotSupported(const WebString& errorMessage) { m_resolver->reject(DOMException::create(NotSupportedError, errorMessage)); m_resolver.clear(); } } // namespace ScriptPromise NavigatorRequestMediaKeySystemAccess::requestMediaKeySystemAccess( ScriptState* scriptState, Navigator& navigator, const String& keySystem, const HeapVector<MediaKeySystemConfiguration>& supportedConfigurations) { WTF_LOG(Media, "NavigatorRequestMediaKeySystemAccess::requestMediaKeySystemAccess()"); // From https://w3c.github.io/encrypted-media/#requestMediaKeySystemAccess // When this method is invoked, the user agent must run the following steps: // 1. If keySystem is an empty string, return a promise rejected with a // new DOMException whose name is InvalidAccessError. if (keySystem.isEmpty()) { return ScriptPromise::rejectWithDOMException( scriptState, DOMException::create(InvalidAccessError, "The keySystem parameter is empty.")); } // 2. If supportedConfigurations was provided and is empty, return a // promise rejected with a new DOMException whose name is // InvalidAccessError. if (!supportedConfigurations.size()) { return ScriptPromise::rejectWithDOMException( scriptState, DOMException::create(InvalidAccessError, "The supportedConfigurations parameter is empty.")); } // 3-4. 'May Document use powerful features?' check. ExecutionContext* executionContext = scriptState->executionContext(); String errorMessage; if (executionContext->isPrivilegedContext(errorMessage)) { UseCounter::count(executionContext, UseCounter::EncryptedMediaSecureOrigin); } else { UseCounter::countDeprecation(executionContext, UseCounter::EncryptedMediaInsecureOrigin); // TODO(ddorwin): Implement the following: // Reject promise with a new DOMException whose name is NotSupportedError. } // 5. Let origin be the origin of document. // (Passed with the execution context in step 7.) // 6. Let promise be a new promise. Document* document = toDocument(executionContext); if (!document->page()) { return ScriptPromise::rejectWithDOMException( scriptState, DOMException::create(InvalidStateError, "The context provided is not associated with a page.")); } MediaKeySystemAccessInitializer* initializer = new MediaKeySystemAccessInitializer(scriptState, keySystem, supportedConfigurations); ScriptPromise promise = initializer->promise(); // 7. Asynchronously determine support, and if allowed, create and // initialize the MediaKeySystemAccess object. MediaKeysController* controller = MediaKeysController::from(document->page()); WebEncryptedMediaClient* mediaClient = controller->encryptedMediaClient(executionContext); mediaClient->requestMediaKeySystemAccess(WebEncryptedMediaRequest(initializer)); // 8. Return promise. return promise; } } // namespace blink
44.169014
187
0.75
e90f4bead4b3127c61e8ccd7159d46826fd68eb8
1,591
cpp
C++
tests/msat/msat-array-models.cpp
andrewvaughanj/smt-switch
9c1ba328f8d69fb3b832820b765df71b0cd9bc65
[ "BSD-3-Clause" ]
49
2018-02-20T12:47:28.000Z
2021-08-14T17:06:19.000Z
tests/msat/msat-array-models.cpp
andrewvaughanj/smt-switch
9c1ba328f8d69fb3b832820b765df71b0cd9bc65
[ "BSD-3-Clause" ]
117
2017-06-30T18:26:02.000Z
2021-08-17T19:50:18.000Z
tests/msat/msat-array-models.cpp
andrewvaughanj/smt-switch
9c1ba328f8d69fb3b832820b765df71b0cd9bc65
[ "BSD-3-Clause" ]
21
2019-10-10T22:22:03.000Z
2021-07-22T14:15:10.000Z
/********************* */ /*! \file msat-array-models.cpp ** \verbatim ** Top contributors (to current version): ** Makai Mann ** This file is part of the smt-switch project. ** Copyright (c) 2020 by the authors listed in the file AUTHORS ** in the top-level source directory) and their institutional affiliations. ** All rights reserved. See the file LICENSE in the top-level source ** directory for licensing information.\endverbatim ** ** \brief ** ** **/ #include <iostream> #include <memory> #include <vector> #include "assert.h" #include "msat_factory.h" #include "smt.h" // after a full installation // #include "smt-switch/msat_factory.h" // #include "smt-switch/smt.h" using namespace smt; using namespace std; int main() { SmtSolver s = MsatSolverFactory::create(false); s->set_opt("produce-models", "true"); Sort bvsort32 = s->make_sort(BV, 32); Sort array32_32 = s->make_sort(ARRAY, bvsort32, bvsort32); Term x0 = s->make_symbol("x0", bvsort32); Term x1 = s->make_symbol("x1", bvsort32); Term y = s->make_symbol("y", bvsort32); Term arr = s->make_symbol("arr", array32_32); Term constraint = s->make_term(Equal, s->make_term(Select, arr, x0), x1); constraint = s->make_term( And, constraint, s->make_term(Equal, s->make_term(Select, arr, x1), y)); constraint = s->make_term(And, constraint, s->make_term(Distinct, x1, y)); s->assert_formula(constraint); Result r = s->check_sat(); assert(r.is_sat()); Term arr_val = s->get_value(arr); cout << arr_val << endl; return 0; }
27.912281
80
0.65242
e90fd826c539b8636606798846eaecad36402fdb
529
cpp
C++
Synthesizer/MainScreen.cpp
161563/Sylph-Synthesizer
548e62f1353f254af874d2d06fd6216b808edfd6
[ "MIT" ]
null
null
null
Synthesizer/MainScreen.cpp
161563/Sylph-Synthesizer
548e62f1353f254af874d2d06fd6216b808edfd6
[ "MIT" ]
null
null
null
Synthesizer/MainScreen.cpp
161563/Sylph-Synthesizer
548e62f1353f254af874d2d06fd6216b808edfd6
[ "MIT" ]
null
null
null
#include "MainScreen.h" #include "Song.h" #include "Music.h" #include <string> using namespace System; using namespace System::Windows::Forms; [STAThread] void main(array<String^>^ args) { Application::EnableVisualStyles(); Application::SetCompatibleTextRenderingDefault(false); for (int i = 0; i < args->Length; i++) { //MessageBox::Show(args[i]); } Synthesizer::MainScreen screen; if (args->Length == 1) { screen.setSong(new Song(args[0])); } else { screen.setSong(new Song()); } Application::Run(%screen); }
21.16
55
0.691871
e910c788acd61fff99e72aaa8cc69885e5ee4470
352
cc
C++
CondFormats/ESObjects/src/ESADCToGeVConstant.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-24T19:10:26.000Z
2019-02-19T11:45:32.000Z
CondFormats/ESObjects/src/ESADCToGeVConstant.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-23T13:40:24.000Z
2019-12-05T21:16:03.000Z
CondFormats/ESObjects/src/ESADCToGeVConstant.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
5
2018-08-21T16:37:52.000Z
2020-01-09T13:33:17.000Z
#include "CondFormats/ESObjects/interface/ESADCToGeVConstant.h" ESADCToGeVConstant::ESADCToGeVConstant() { ESvaluelow_=0.; ESvaluehigh_=0.; } ESADCToGeVConstant::ESADCToGeVConstant(const float & ESvaluelow, const float & ESvaluehigh) { ESvaluelow_ = ESvaluelow; ESvaluehigh_ = ESvaluehigh; } ESADCToGeVConstant::~ESADCToGeVConstant() { }
19.555556
93
0.775568
e91292a9cc731cdd25b3f6c27e9e922d6044775f
6,155
cc
C++
test/frame_error_test.cc
moutonislandais/SVT-AV1
a41f1601b01eec701c76600e472d2fc7d1f3a22f
[ "BSD-2-Clause-Patent" ]
1
2019-07-14T13:20:21.000Z
2019-07-14T13:20:21.000Z
test/frame_error_test.cc
moutonislandais/SVT-AV1
a41f1601b01eec701c76600e472d2fc7d1f3a22f
[ "BSD-2-Clause-Patent" ]
10
2019-03-13T06:57:17.000Z
2019-04-08T02:46:17.000Z
test/frame_error_test.cc
moutonislandais/SVT-AV1
a41f1601b01eec701c76600e472d2fc7d1f3a22f
[ "BSD-2-Clause-Patent" ]
1
2019-03-07T08:56:38.000Z
2019-03-07T08:56:38.000Z
/* * Copyright (c) 2019, Alliance for Open Media. All rights reserved * * This source code is subject to the terms of the BSD 2 Clause License and * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License * was not distributed with this source code in the LICENSE file, you can * obtain it at www.aomedia.org/license/software. If the Alliance for Open * Media Patent License 1.0 was not distributed with this source code in the * PATENTS file, you can obtain it at www.aomedia.org/license/patent. */ #include <math.h> #include <stdio.h> #include <stdlib.h> #include "gtest/gtest.h" #include "aom_dsp_rtcd.h" #include "EbUnitTestUtility.h" #include "EbUtility.h" #include "random.h" #include "util.h" namespace { typedef int64_t (*frame_error_func)(const uint8_t *const ref, int stride, const uint8_t *const dst, int p_width, int p_height, int p_stride); const int kBlockWidth[] = { 832, 834, 640, 1280, 1920, }; const int kBlockHeight[] = { 480, 482, 360, 720, 1080, }; typedef std::tuple<frame_error_func, int, int> FrameErrorParam; class AV1FrameErrorTest : public ::testing::TestWithParam<FrameErrorParam> { public: virtual ~AV1FrameErrorTest() { } virtual void SetUp() { rnd_ = new svt_av1_test_tool::SVTRandom(0, (1 << 8) - 1); } virtual void TearDown() { delete rnd_; aom_clear_system_state(); } protected: void RandomValues(frame_error_func test_impl, int width, int height); void ExtremeValues(frame_error_func test_impl, int width, int height); void RunSpeedTest(frame_error_func test_impl, int width, int height); svt_av1_test_tool::SVTRandom *rnd_; }; void AV1FrameErrorTest::RandomValues(frame_error_func test_impl, int width, int height) { const int stride = (((width * 3) / 2) + 15) & ~15; const int max_blk_size = stride * height; uint8_t *const dst = static_cast<uint8_t *>(aom_memalign(16, max_blk_size * sizeof(*dst))); uint8_t *const ref = static_cast<uint8_t *>(aom_memalign(16, max_blk_size * sizeof(*ref))); ASSERT_TRUE(dst != NULL); ASSERT_TRUE(ref != NULL); for (int i = 0; i < max_blk_size; ++i) { dst[i] = rnd_->Rand8(); ref[i] = rnd_->Rand8(); } const int64_t ref_error = av1_calc_frame_error_c(ref, stride, dst, width, height, stride); const int64_t test_error = test_impl(ref, stride, dst, width, height, stride); ASSERT_EQ(test_error, ref_error) << width << "x" << height; aom_free(dst); aom_free(ref); } void AV1FrameErrorTest::ExtremeValues(frame_error_func test_impl, int width, int height) { const int stride = (((width * 3) / 2) + 15) & ~15; const int max_blk_size = stride * height; uint8_t *const dst = static_cast<uint8_t *>(aom_memalign(16, max_blk_size * sizeof(*dst))); uint8_t *const ref = static_cast<uint8_t *>(aom_memalign(16, max_blk_size * sizeof(*ref))); ASSERT_TRUE(dst != NULL); ASSERT_TRUE(ref != NULL); for (int r = 0; r < 2; r++) { if (r == 0) { memset(dst, 0, max_blk_size); memset(ref, 255, max_blk_size); } else if (r == 1) { memset(dst, 255, max_blk_size); memset(ref, 0, max_blk_size); } const int64_t ref_error = av1_calc_frame_error_c(ref, stride, dst, width, height, stride); const int64_t test_error = test_impl(ref, stride, dst, width, height, stride); ASSERT_EQ(test_error, ref_error) << width << "x" << height; } aom_free(dst); aom_free(ref); } void AV1FrameErrorTest::RunSpeedTest(frame_error_func test_impl, int width, int height) { const int stride = (((width * 3) / 2) + 15) & ~15; const int max_blk_size = stride * height; uint8_t *const dst = static_cast<uint8_t *>(aom_memalign(16, max_blk_size * sizeof(*dst))); uint8_t *const ref = static_cast<uint8_t *>(aom_memalign(16, max_blk_size * sizeof(*ref))); ASSERT_TRUE(dst != NULL); ASSERT_TRUE(ref != NULL); for (int i = 0; i < max_blk_size; ++i) { dst[i] = ref[i] = rnd_->Rand8(); } const int num_loops = 10000000 / (width + height); frame_error_func funcs[2] = {av1_calc_frame_error_c, test_impl}; double elapsed_time[2] = {0}; for (int i = 0; i < 2; ++i) { double time; uint64_t start_time_seconds, start_time_useconds; uint64_t finish_time_seconds, finish_time_useconds; EbStartTime(&start_time_seconds, &start_time_useconds); frame_error_func func = funcs[i]; for (int j = 0; j < num_loops; ++j) { func(ref, stride, dst, width, height, stride); } EbStartTime(&finish_time_seconds, &finish_time_useconds); EbComputeOverallElapsedTimeMs(start_time_seconds, start_time_useconds, finish_time_seconds, finish_time_useconds, &time); elapsed_time[i] = 1000.0 * time / num_loops; } aom_free(dst); aom_free(ref); printf("av1_calc_frame_error %3dx%-3d: %7.2f/%7.2fns", width, height, elapsed_time[0], elapsed_time[1]); printf("(%3.2f)\n", elapsed_time[0] / elapsed_time[1]); } TEST_P(AV1FrameErrorTest, CheckOutput) { RandomValues(TEST_GET_PARAM(0), TEST_GET_PARAM(1), TEST_GET_PARAM(2)); ExtremeValues(TEST_GET_PARAM(0), TEST_GET_PARAM(1), TEST_GET_PARAM(2)); } TEST_P(AV1FrameErrorTest, DISABLED_Speed) { RunSpeedTest(TEST_GET_PARAM(0), TEST_GET_PARAM(1), TEST_GET_PARAM(2)); } INSTANTIATE_TEST_CASE_P( AVX2, AV1FrameErrorTest, ::testing::Combine(::testing::Values(&av1_calc_frame_error_avx2), ::testing::ValuesIn(kBlockWidth), ::testing::ValuesIn(kBlockHeight))); } // namespace
35.578035
78
0.612998
e916529e0689dec760e84712b9d2d9244d169ea4
1,661
cpp
C++
src/nn/axpby.cpp
tahsinkose/graphnn
cf38e2a4e459a2d0138c3153d1aa9d69137b04b2
[ "MIT" ]
277
2016-01-26T10:47:03.000Z
2022-03-28T11:47:03.000Z
src/nn/axpby.cpp
tahsinkose/graphnn
cf38e2a4e459a2d0138c3153d1aa9d69137b04b2
[ "MIT" ]
35
2017-04-05T16:02:16.000Z
2022-02-17T15:24:25.000Z
src/nn/axpby.cpp
tahsinkose/graphnn
cf38e2a4e459a2d0138c3153d1aa9d69137b04b2
[ "MIT" ]
90
2016-01-26T10:40:39.000Z
2022-02-28T10:55:32.000Z
#include "nn/axpby.h" namespace gnn { template<typename mode, typename Dtype> Axpby<mode, Dtype>::Axpby(std::string _name, Dtype _a, Dtype _b, PropErr _properr) : Factor(_name, _properr), a(_a), b(_b) { } template<typename mode, typename Dtype> void Axpby<mode, Dtype>::Forward(std::vector< std::shared_ptr<Variable> >& operands, std::vector< std::shared_ptr<Variable> >& outputs, Phase phase) { ASSERT(operands.size() == 2, "unexpected input size for " << StrType()); ASSERT(outputs.size() == 1, "unexpected output size for " << StrType()); auto& output = dynamic_cast<DTensorVar<mode, Dtype>*>(outputs[0].get())->value; auto& x = dynamic_cast<DTensorVar<mode, Dtype>*>(operands[0].get())->value; auto& y = dynamic_cast<DTensorVar<mode, Dtype>*>(operands[1].get())->value; output.CopyFrom(y); output.Axpby(a, x, b); } template<typename mode, typename Dtype> void Axpby<mode, Dtype>::Backward(std::vector< std::shared_ptr<Variable> >& operands, std::vector< bool >& isConst, std::vector< std::shared_ptr<Variable> >& outputs) { ASSERT(operands.size() == 2, "unexpected input size for " << StrType()); ASSERT(outputs.size() == 1, "unexpected output size for " << StrType()); auto cur_grad = dynamic_cast<DTensorVar<mode, Dtype>*>(outputs[0].get())->grad.Full(); for (size_t i = 0; i < operands.size(); ++i) { if (isConst[i]) continue; auto& grad_i = dynamic_cast<DTensorVar<mode, Dtype>*>(operands[i].get())->grad; ASSERT(grad_i.shape == cur_grad.shape, "no broadcasting is supported right now"); grad_i.Full().Axpy( i == 0 ? a : b, cur_grad); } } INSTANTIATE_CLASS(Axpby) }
31.942308
87
0.662854
e9176cffaec1e7d5f5a498abdb09a3fe2ae6dc3c
1,072
cpp
C++
WirelessThermometer/TimerSwitchWithServo/ServoMotion.cpp
anders-liu/arduino-gallery
8c65701a33358891b7105b50f831d7f5797288ad
[ "MIT" ]
1
2019-11-07T22:44:27.000Z
2019-11-07T22:44:27.000Z
WirelessThermometer/TimerSwitchWithServo/ServoMotion.cpp
anders-liu/arduino-gallery
8c65701a33358891b7105b50f831d7f5797288ad
[ "MIT" ]
null
null
null
WirelessThermometer/TimerSwitchWithServo/ServoMotion.cpp
anders-liu/arduino-gallery
8c65701a33358891b7105b50f831d7f5797288ad
[ "MIT" ]
null
null
null
#include "ServoMotion.h" #include "DataStore.h" #define START_DELAY 200 #define RUNNING_HOLD_PERIOD 1000 enum ServoMotionState_t { SS_OFF, SS_JUST_ON, SS_RUNNING, }; static void s_powerOff(uint8_t powerPin) { digitalWrite(powerPin, LOW); } static void s_powerOn(uint8_t powerPin) { digitalWrite(powerPin, HIGH); } void ServoMotion::setup() { pinMode(this->powerPin, OUTPUT); s_powerOff(this->powerPin); this->servo.attach(this->controlPin); } void ServoMotion::loop() { switch (this->state) { case SS_OFF: if (ds.getCurrentServoValueReadyToSend()) { this->servo.write(ds.getCurrentServoValue()); ds.clearCurrentServoValueReadyToSend(); this->state = SS_JUST_ON; this->lastMillis = millis(); } break; case SS_JUST_ON: if (millis() - this->lastMillis > START_DELAY) { s_powerOn(this->powerPin); this->state = SS_RUNNING; this->lastMillis = millis(); } break; case SS_RUNNING: if (millis() - this->lastMillis > RUNNING_HOLD_PERIOD) { s_powerOff(this->powerPin); this->state = SS_OFF; } break; } }
19.490909
58
0.697761
e917c8d3fb72073d52dbfa4de3fb13a5bec68f82
1,171
cpp
C++
deps/src/boost_1_65_1/libs/python/test/destroy_test.cpp
shreyasvj25/turicreate
32e84ca16aef8d04aff3d49ae9984bd49326bffd
[ "BSD-3-Clause" ]
11,356
2017-12-08T19:42:32.000Z
2022-03-31T16:55:25.000Z
deps/src/boost_1_65_1/libs/python/test/destroy_test.cpp
shreyasvj25/turicreate
32e84ca16aef8d04aff3d49ae9984bd49326bffd
[ "BSD-3-Clause" ]
2,402
2017-12-08T22:31:01.000Z
2022-03-28T19:25:52.000Z
deps/src/boost_1_65_1/libs/python/test/destroy_test.cpp
shreyasvj25/turicreate
32e84ca16aef8d04aff3d49ae9984bd49326bffd
[ "BSD-3-Clause" ]
1,343
2017-12-08T19:47:19.000Z
2022-03-26T11:31:36.000Z
// Copyright David Abrahams 2004. 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 <boost/python/detail/destroy.hpp> #include <boost/detail/lightweight_test.hpp> int count; int marks[] = { -1 , -1, -1 , -1, -1, -1, -1 , -1 }; int* kills = marks; struct foo { foo() : n(count++) {} ~foo() { *kills++ = n; } int n; // This used to cause compiler errors with MSVC 9.0. foo& operator~(); foo& T(); }; void assert_destructions(int n) { for (int i = 0; i < n; ++i) BOOST_TEST(marks[i] == i); BOOST_TEST(marks[n] == -1); } int main() { assert_destructions(0); foo* f1 = new foo; boost::python::detail::destroy_referent<foo const volatile&>(f1); assert_destructions(1); foo* f2 = new foo[2]; typedef foo x[2]; boost::python::detail::destroy_referent<x const&>(f2); assert_destructions(3); typedef foo y[2][2]; x* f3 = new y; boost::python::detail::destroy_referent<y&>(f3); assert_destructions(7); return boost::report_errors(); }
19.847458
72
0.600342
e917d0a96f269a8a0fb6cc14e7c1320b3cf3a3f7
700
hpp
C++
android-29/android/media/MediaRecorder_AudioEncoder.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-31/android/media/MediaRecorder_AudioEncoder.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-30/android/media/MediaRecorder_AudioEncoder.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#pragma once #include "../../JObject.hpp" namespace android::media { class MediaRecorder; } namespace android::media { class MediaRecorder_AudioEncoder : public JObject { public: // Fields static jint AAC(); static jint AAC_ELD(); static jint AMR_NB(); static jint AMR_WB(); static jint DEFAULT(); static jint HE_AAC(); static jint OPUS(); static jint VORBIS(); // QJniObject forward template<typename ...Ts> explicit MediaRecorder_AudioEncoder(const char *className, const char *sig, Ts...agv) : JObject(className, sig, std::forward<Ts>(agv)...) {} MediaRecorder_AudioEncoder(QJniObject obj); // Constructors // Methods }; } // namespace android::media
20
167
0.692857
e91a18927dc83eb1469e3ebc933d4917f5b0214b
944
cc
C++
jax/training/21-09/29/b_precessing_queries.cc
JaxVanYang/acm
ee41f1cbf692b7b1463a9467401bb6e7d38aecce
[ "MIT" ]
2
2022-01-01T16:55:02.000Z
2022-03-16T14:47:29.000Z
jax/training/21-09/29/b_precessing_queries.cc
JaxVanYang/acm
ee41f1cbf692b7b1463a9467401bb6e7d38aecce
[ "MIT" ]
null
null
null
jax/training/21-09/29/b_precessing_queries.cc
JaxVanYang/acm
ee41f1cbf692b7b1463a9467401bb6e7d38aecce
[ "MIT" ]
null
null
null
#include <iostream> #include <queue> using namespace std; using ll = long long; const int N = 2e5 + 10; ll ans[N]; struct Node { int t, d, id; }; int main() { int n, b; scanf("%d%d", &n, &b); ll ed = 0; queue<Node> q; for (int i = 0; i < n; ++i) { int t, d; scanf("%d%d", &t, &d); if (q.size() == b + 1) { ll lmt = max(ed, (ll)q.front().t) + q.front().d; if (lmt > t) { ans[i] = -1; } else { ans[q.front().id] = lmt; q.pop(); ed = lmt; q.push({t, d, i}); } } else { q.push({t, d, i}); } } while (q.size()) { ed = max(ed, (ll)q.front().t) + q.front().d; ans[q.front().id] = ed; q.pop(); } for (int i = 0; i < n; ++i) { printf("%lld ", ans[i]); } puts(""); }
17.811321
60
0.347458
e91ac1f5e22f7be38a8ace97a06691abd2c9b452
27,860
cpp
C++
libqd/qd.cpp
philippeb8/fcalc
b62a78e02b56dc4319e06d8eb36bb3d6fdafd256
[ "MIT" ]
2
2020-10-24T01:15:51.000Z
2020-10-25T04:07:30.000Z
libqd/qd.cpp
philippeb8/fcalc
b62a78e02b56dc4319e06d8eb36bb3d6fdafd256
[ "MIT" ]
null
null
null
libqd/qd.cpp
philippeb8/fcalc
b62a78e02b56dc4319e06d8eb36bb3d6fdafd256
[ "MIT" ]
null
null
null
/* * src/qd.cc * * This work was supported by the Director, Office of Science, Division * of Mathematical, Information, and Computational Sciences of the * U.S. Department of Energy under contract number DE-AC03-76SF00098. * * Copyright (c) 2000-2001 * * Contains implementation of non-inlined functions of quad-double * package. Inlined functions are found in qd_inline.h (in include directory). */ #include <cstdlib> #include <cstdio> #include <cmath> #include <iostream> //#include "config.h" //#include "bits.h" #include "qd.h" #ifndef QD_INLINE #include "qd_inline.h" #endif #ifdef _MSC_VER #define STD_RAND ::rand #else #define STD_RAND std::rand #endif using std::cout; using std::cerr; using std::endl; using std::istream; using std::ostream; using std::ios_base; using namespace qd; static const char *digits = "0123456789*"; void qd_real::abort() { exit(-1); } /********** Multiplications **********/ qd_real nint(const qd_real &a) { real x0, x1, x2, x3; x0 = nint(a[0]); x1 = x2 = x3 = real(0.0); if (x0 == a[0]) { /* First real is already an integer. */ x1 = nint(a[1]); if (x1 == a[1]) { /* Second real is already an integer. */ x2 = nint(a[2]); if (x2 == a[2]) { /* Third real is already an integer. */ x3 = nint(a[3]); } else { if (fabsl(x2 - a[2]) == real(0.5) && a[3] < real(0.0)) { x2 -= real(1.0); } } } else { if (fabsl(x1 - a[1]) == real(0.5) && a[2] < real(0.0)) { x1 -= real(1.0); } } } else { /* First real is not an integer. */ if (fabsl(x0 - a[0]) == real(0.5) && a[1] < real(0.0)) { x0 -= real(1.0); } } renorm(x0, x1, x2, x3); return qd_real(x0, x1, x2, x3); } qd_real floor(const qd_real &a) { real x0, x1, x2, x3; x1 = x2 = x3 = real(0.0); x0 = floorl(a[0]); if (x0 == a[0]) { x1 = floorl(a[1]); if (x1 == a[1]) { x2 = floorl(a[2]); if (x2 == a[2]) { x3 = floorl(a[3]); } } renorm(x0, x1, x2, x3); return qd_real(x0, x1, x2, x3); } return qd_real(x0, x1, x2, x3); } qd_real ceil(const qd_real &a) { real x0, x1, x2, x3; x1 = x2 = x3 = real(0.0); x0 = ceill(a[0]); if (x0 == a[0]) { x1 = ceill(a[1]); if (x1 == a[1]) { x2 = ceill(a[2]); if (x2 == a[2]) { x3 = ceill(a[3]); } } renorm(x0, x1, x2, x3); return qd_real(x0, x1, x2, x3); } return qd_real(x0, x1, x2, x3); } /********** Divisions **********/ /* quad-real / real */ qd_real operator/(const qd_real &a, real b) { /* Strategy: compute approximate quotient using high order reals, and then correct it 3 times using the remainder. (Analogous to long division.) */ real t0, t1; real q0, q1, q2, q3; qd_real r; q0 = a[0] / b; /* approximate quotient */ /* Compute the remainder a - q0 * b */ t0 = two_prod(q0, b, t1); r = a - dd_real(t0, t1); /* Compute the first correction */ q1 = r[0] / b; t0 = two_prod(q1, b, t1); r -= dd_real(t0, t1); /* Second correction to the quotient. */ q2 = r[0] / b; t0 = two_prod(q2, b, t1); r -= dd_real(t0, t1); /* Final correction to the quotient. */ q3 = r[0] / b; renorm(q0, q1, q2, q3); return qd_real(q0, q1, q2, q3); } /* qd_real::qd_real(const char *s) { int r = qd_real::read(s, *this); if (r != 0) { qd_real::abort(); cerr << "ERROR (qd_real::qd_real): INPUT ERROR." << endl; } } */ istream &operator>>(istream &s, qd_real &qd) { char str[255]; s >> str; qd.read(str, qd); return s; } ostream &operator<<(ostream &s, const qd_real &qd) { char str[255]; qd.write(str, s.precision(), s.flags()); return s << str; } /* Read a quad-real from s. */ int qd_real::read(const char *s, qd_real &qd) { const char *p = s; char ch; int sign = 0; int point = -1; /* location of decimal point */ int nd = 0; /* number of digits read */ int e = 0; /* exponent. */ bool done = false; qd_real r = real(0.0); /* number being read */ /* Skip any leading spaces */ while (*p == ' ') p++; while (!done && (ch = *p) != '\0') { if (ch >= '0' && ch <= '9') { /* It's a digit */ int d = ch - '0'; r *= real(10.0); r += (real) d; nd++; } else { /* Non-digit */ switch (ch) { case '.': if (point >= 0) return -1; /* we've already encountered a decimal point. */ point = nd; break; case '-': case '+': if (sign != 0 || nd > 0) return -1; /* we've already encountered a sign, or if its not at first position. */ sign = (ch == '-') ? -1 : 1; break; case 'E': case 'e': int nread; nread = sscanf(p+1, "%d", &e); done = true; if (nread != 1) return -1; /* read of exponent failed. */ break; case ' ': done = true; break; default: return -1; } } p++; } /* Adjust exponent to account for decimal point */ if (point >= 0) { e -= (nd - point); } /* Multiply the the exponent */ if (e != 0) { r *= (qd_real(10.0) ^ e); } qd = (sign < 0) ? -r : r; return 0; } /* Converts a quad-real to a string. d is the number of (decimal) significant digits. The string s must be able to hold d+8 characters. */ void qd_real::write(char *s, int d, ios_base::fmtflags l) const { qd_real r = fabs(*this); qd_real p; int e; /* exponent */ int i = 0, j = 0; /* First determine the (approximate) exponent. */ e = (int) floorl(log10l(fabsl(x[0]))); /* Find dimensions. */ bool m = (l & qd_real::showmagnitude), n = (l & std::ios_base::showpoint), is = (l & qd_real::imperialsystem); int D = (n ? d : e + (d < 1 ? d : 1)) + 1; if (x[0] == real(0.0)) { /* this == real(0.0) */ s[i ++] = digits[0]; if (n) { s[i ++] = '.'; } s[i ++] = '\0'; return; } /* Test for infinity and nan. */ if (isinf()) { sprintf(s, "NAN"); return; } if (isnan()) { sprintf(s, "NAN"); return; } /* Digits */ int *a = new int[D]; if (e < -4000) { r *= qd_real(10.0) ^ 4000; p = qd_real(10.0) ^ (e + 4000); r /= p; } else { p = qd_real(10.0) ^ e; r /= p; } /* Fix exponent if we are off by one */ if ((real const &)(r) >= real(10.0)) { r /= real(10.0); e++; } else if ((real const &)(r) < real(1.0)) { r *= real(10.0); e--; } if ((real const &)(r) >= real(10.0) || (real const &)(r) < real(1.0)) { //cerr << "ERROR (qd_real::to_str): can't compute exponent." << endl; delete [] a; //qd_real::abort(); return; } /* Extract the digits */ for (i = 0; i < D; i++) { a[i] = (int) r[0]; r -= (real) a[i]; r *= real(10.0); } /* Fix negative digits. */ for (i = D-1; i > 0; i--) { if (a[i] < 0) { a[i-1]--; a[i] += 10; } } if (a[0] <= 0) { //cerr << "ERROR (qd_real::to_str): non-positive leading digit." << endl; delete [] a; //qd_real::abort(); return; } /* Round, handle carry */ if (a[D - 1] >= 5) { a[D - 2] ++; int i = D - 2; while (i > 0 && a[i] >= 10) { a[i] -= 10; a[-- i] ++; } if (a[0] == 10) { ++ e; a[0] = 1; } } /* Start fill in the string. */ if (x[0] < real(0.0)) { s[i ++] = '-'; } bool scientific = (l & std::ios_base::scientific) || ! (e > -4 && e < D - 1); long f = scientific ? 0 : e, t = (f > 0 ? f : 0); if (! m) { // C/C++ notation for (; j < D - 1; -- f, ++ j) { if (a[j] != 0) { // Feed in leading zeros (0.0001...; 1.000...01) for (; t != f; -- t) { s[i ++] = digits[0]; if (t % 3 == 0) if (t == 0 && (scientific || n)) s[i ++] = '.'; } s[i ++] = digits[a[j]]; if (t % 3 == 0) if (t == 0 && (scientific || n)) s[i ++] = '.'; -- t; } } // Dangling zeros (10000...) for (; t >= 0; -- t) { s[i ++] = digits[0]; if (t % 3 == 0) if (t == 0 && (scientific || n)) s[i ++] = '.'; } } else if (! is) { // Metric notation for (bool first = true; j < D - 1; first = false, -- f, ++ j) { if (a[j] != 0) { // Feed in leading zeros (0.0001...; 1.000...01) for (; t != f; -- t) { if ((t + 1) % 3 == 0) if (t == -1 && (scientific || n)) s[i ++] = ','; else if (! first) s[i ++] = ' '; s[i ++] = digits[0]; } if ((t + 1) % 3 == 0) if (t == -1 && (scientific || n)) s[i ++] = ','; else if (! first) s[i ++] = ' '; s[i ++] = digits[a[j]]; -- t; } } // Dangling zeros (10000...) for (bool first = true; t >= 0; first = false, -- t) { if ((t + 1) % 3 == 0) if (t == -1 && (scientific || n)) s[i ++] = ','; else if (! first) s[i ++] = ' '; s[i ++] = digits[0]; } } else { // Imperial notation for (; j < D - 1; -- f, ++ j) { if (a[j] != 0) { // Feed in leading zeros (0.0001...; 1.000...01) for (; t != f; -- t) { s[i ++] = digits[0]; if (t % 3 == 0) if (t == 0 && (scientific || n)) s[i ++] = '.'; else if (t > 0) s[i ++] = ','; } s[i ++] = digits[a[j]]; if (t % 3 == 0) if (t == 0 && (scientific || n)) s[i ++] = '.'; else if (t > 0) s[i ++] = ','; -- t; } } // Dangling zeros (10000...) for (; t >= 0; -- t) { s[i ++] = digits[0]; if (t % 3 == 0) if (t == 0 && (scientific || n)) s[i ++] = '.'; else if (t > 0) s[i ++] = ','; } } if (! scientific) { s[i ++] = '\0'; } else { s[i ++] = 'e'; sprintf(&s[i], "%d", e); } delete [] a; } /* Computes qd^n, where n is an integer. */ qd_real npwr(const qd_real &a, int n) { if (n == 0) return real(1.0); qd_real r = a; /* odd-case multiplier */ qd_real s = real(1.0); /* current answer */ int N = abs(n); if (N > 1) { /* Use binary exponentiation. */ while (N > 0) { if (N % 2 == 1) { /* If odd, multiply by r. Note eventually N = 1, so this eventually executes. */ s *= r; } N /= 2; if (N > 0) r = sqr(r); } } else { s = r; } if (n < 0) return (real(1.0) / s); return s; } /* Computes real-real ^ real-real. */ qd_real pow(const qd_real &a, const qd_real &n) { if (n == floor(n)) { return npwr(a, n); } return exp(n * log(a)); } #ifdef QD_DEBUG /* Debugging routines */ void qd_real::dump_bits() const { cout << "[ "; print_real_info(x[0]); cout << endl << " "; print_real_info(x[1]); cout << endl << " "; print_real_info(x[2]); cout << endl << " "; print_real_info(x[3]); cout << " ]" << endl; } void qd_real::dump_components() const { printf("[ %.18e %.18e %.18e %.18e ]\n", x[0], x[1], x[2], x[3]); } void qd_real::dump() const { cout << "[ "; printf(" %25.19e ", x[0]); print_real_info(x[0]); cout << endl << " "; printf(" %25.19e ", x[1]); print_real_info(x[1]); cout << endl << " "; printf(" %25.19e ", x[2]); print_real_info(x[2]); cout << endl << " "; printf(" %25.19e ", x[3]); print_real_info(x[3]); cout << " ]" << endl; } #endif /* Divisions */ /* quad-real / real-real */ qd_real operator/ (const qd_real &a, const dd_real &b) { real q0, q1, q2, q3; qd_real r; q0 = a[0] / b._hi(); r = a - q0 * b; q1 = r[0] / b._hi(); r -= (q1 * b); q2 = r[0] / b._hi(); r -= (q2 * b); q3 = r[0] / b._hi(); #ifdef QD_SLOPPY_DIV renorm(q0, q1, q2, q3); #else r -= (q3 * b); real q4 = r[0] / b._hi(); renorm(q0, q1, q2, q3, q4); #endif return qd_real(q0, q1, q2, q3); } /* quad-real / quad-real */ qd_real operator/(const qd_real &a, const qd_real &b) { real q0, q1, q2, q3; qd_real r; q0 = a[0] / b[0]; r = a - (b * q0); q1 = r[0] / b[0]; r -= (b * q1); q2 = r[0] / b[0]; r -= (b * q2); q3 = r[0] / b[0]; #ifdef QD_SLOPPY_DIV renorm(q0, q1, q2, q3); #else r -= (b * q3); real q4 = r[0] / b[0]; renorm(q0, q1, q2, q3, q4); #endif return qd_real(q0, q1, q2, q3); } qd_real sqrt(const qd_real &a) { /* Strategy: Perform the following Newton iteration: x' = x + (1 - a * x^2) * x / 2; which converges to 1/sqrt(a), starting with the real precision approximation to 1/sqrt(a). Since Newton's iteration more or less reals the number of correct digits, we only need to perform it twice. */ if (a == real(0.0)) { return qd_real(0.0); } qd_real r = (real(1.0) / sqrtl(a[0])); qd_real h = a * real(0.5); r += ((real(0.5) - h * sqr(r)) * r); r += ((real(0.5) - h * sqr(r)) * r); r += ((real(0.5) - h * sqr(r)) * r); r *= a; return r; } /* Computes the n-th root of a */ qd_real nroot(const qd_real &a, int n) { /* Strategy: Use Newton's iteration to solve 1/(x^n) - a = 0 Newton iteration becomes x' = x + x * (1 - a * x^n) / n Since Newton's iteration converges quadratically, we only need to perform it twice. */ if (a == real(0.0)) { return qd_real(0.0); } qd_real r = powl(a[0], -real(1.0)/n); r += r * (real(1.0) - a * (r ^ n)) / (real) n; r += r * (real(1.0) - a * (r ^ n)) / (real) n; r += r * (real(1.0) - a * (r ^ n)) / (real) n; return real(1.0) / r; } qd_real exp(const qd_real &a) { /* Strategy: We first reduce the size of x by noting that exp(kr + m) = exp(m) * exp(r)^k Thus by choosing m to be a multiple of log(2) closest to x, we can make |kr| <= log(2) / 2 = 0.3466. Now we can set k = 256, so that |r| <= 0.00136. Then exp(x) = exp(kr + s log 2) = (2^s) * [exp(r)]^256 Then exp(r) is evaluated using the familiar Taylor series. Reducing the argument substantially speeds up the convergence. */ const int k = 256; if (a[0] <= real(-11335.0)) return real(0.0); if (a[0] >= real(11335.0)) { //cerr << "ERROR (qd_real::exp): Argument too large." << endl; //qd_real::abort(); return qd_real::_inf; } if (a.is_zero()) { return real(1.0); } if (a.is_one()) { return qd_real::_e; } const int z = (int) nint(a / qd_real::_log2)[0]; qd_real r = (a - qd_real::_log2 * (real) z) / (real) k; qd_real s, p; real m; real thresh = qd_real::_eps; p = sqr(r) / real(2.0); s = real(1.0) + r + p; m = real(2.0); do { m += real(1.0); p *= r; p /= m; s += p; } while (fabsl((real) p) > thresh); r = npwr(s, k); r = mul_pwr2(r, ldexpl(real(1.0), z)); return r; } /* Logarithm. Computes log(x) in quad-real precision. This is a natural logarithm (i.e., base e). */ qd_real log(const qd_real &a) { /* Strategy. The Taylor series for log converges much more slowly than that of exp, due to the lack of the factorial term in the denominator. Hence this routine instead tries to determine the root of the function f(x) = exp(x) - a using Newton iteration. The iteration is given by x' = x - f(x)/f'(x) = x - (1 - a * exp(-x)) = x + a * exp(-x) - 1. Two iteration is needed, since Newton's iteration approximately reals the number of digits per iteration. */ if (a.is_one()) { return real(0.0); } if (a[0] <= real(0.0)) { //cerr << "ERROR (qd_real::log): Non-positive argument." << endl; //qd_real::abort(); return qd_real::_nan; } qd_real x = logl(a[0]); /* Initial approximation */ x = x + a * exp(-x) - real(1.0); x = x + a * exp(-x) - real(1.0); x = x + a * exp(-x) - real(1.0); return x; } qd_real log10(const qd_real &a) { return log(a) / qd_real::_log10; } /* Computes sin(a) and cos(a) using Taylor series. Assumes |a| <= pi/2048. */ static void sincos_taylor(const qd_real &a, qd_real &sin_a, qd_real &cos_a) { const real thresh = qd_real::_eps * fabsl((real) a); qd_real p; /* Current power of a. */ qd_real s; /* Current partial sum. */ qd_real x; /* = -sqr(a) */ real m; if (a.is_zero()) { sin_a = real(0.0); cos_a = real(1.0); return; } x = -sqr(a); s = a; p = a; m = real(1.0); do { p *= x; m += real(2.0); p /= (m*(m-1)); s += p; } while (fabsl((real) p) > thresh); sin_a = s; cos_a = sqrt(real(1.0) - sqr(s)); } qd_real sin(const qd_real &a) { /* Strategy. To compute sin(x), we choose integers a, b so that x = s + a * (pi/2) + b * (pi/1024) and |s| <= pi/2048. Using a precomputed table of sin(k pi / 1024) and cos(k pi / 1024), we can compute sin(x) from sin(s) and cos(s). This greatly increases the convergence of the sine Taylor series. */ if (a.is_zero()) { return real(0.0); } /* First reduce modulo 2*pi so that |r| <= pi. */ qd_real r = drem(a, qd_real::_2pi); /* Now reduce by modulo pi/2 and then by pi/1024 so that we obtain numbers a, b, and t. */ qd_real t; qd_real sin_t, cos_t; qd_real s, c; int j = (int) divrem(r, qd_real::_pi2, t); int abs_j = abs(j); int k = (int) divrem(t, qd_real::_pi1024, t); int abs_k = abs(k); if (abs_j > 2) { //cerr << "ERROR (qd_real::sin): Cannot reduce modulo pi/2." << endl; //qd_real::abort(); return qd_real::_nan; } if (abs_k > 256) { //cerr << "ERROR (qd_real::sin): Cannot reduce modulo pi/1024." << endl; //qd_real::abort(); return qd_real::_nan; } sincos_taylor(t, sin_t, cos_t); if (abs_k == 0) { s = sin_t; c = cos_t; } else { qd_real u = qd_real::cos_table[abs_k-1]; qd_real v = qd_real::sin_table[abs_k-1]; if (k > 0) { s = u * sin_t + v * cos_t; c = u * cos_t - v * sin_t; } else { s = u * sin_t - v * cos_t; c = u * cos_t + v * sin_t; } } if (abs_j == 0) { r = s; } else if (j == 1) { r = c; } else if (j == -1) { r = -c; } else { r = -s; } return r; } qd_real cos(const qd_real &a) { if (a.is_zero()) { return real(1.0); } /* First reduce modulo 2*pi so that |r| <= pi. */ qd_real r = drem(a, qd_real::_2pi); /* Now reduce by modulo pi/2 and then by pi/1024 so that we obtain numbers a, b, and t. */ qd_real t; qd_real sin_t, cos_t; qd_real s, c; int j = (int) divrem(r, qd_real::_pi2, t); int abs_j = abs(j); int k = (int) divrem(t, qd_real::_pi1024, t); int abs_k = abs(k); if (abs_j > 2) { //cerr << "ERROR (qd_real::cos): Cannot reduce modulo pi/2." << endl; //qd_real::abort(); return qd_real::_nan; } if (abs_k > 256) { //cerr << "ERROR (qd_real::cos): Cannot reduce modulo pi/1024." << endl; //qd_real::abort(); return qd_real::_nan; } sincos_taylor(t, sin_t, cos_t); if (abs_k == 0) { s = sin_t; c = cos_t; } else { qd_real u = qd_real::cos_table[abs_k-1]; qd_real v = qd_real::sin_table[abs_k-1]; if (k > 0) { s = u * sin_t + v * cos_t; c = u * cos_t - v * sin_t; } else { s = u * sin_t - v * cos_t; c = u * cos_t + v * sin_t; } } if (abs_j == 0) { r = c; } else if (j == 1) { r = -s; } else if (j == -1) { r = s; } else { r = -c; } return r; } void sincos(const qd_real &a, qd_real &sin_a, qd_real &cos_a) { if (a.is_zero()) { sin_a = real(0.0); cos_a = real(1.0); return; } /* First reduce modulo 2*pi so that |r| <= pi. */ qd_real r = drem(a, qd_real::_2pi); /* Now reduce by modulo pi/2 and then by pi/1024 so that we obtain numbers a, b, and t. */ qd_real t; qd_real sin_t, cos_t; qd_real s, c; int j = (int) divrem(r, qd_real::_pi2, t); int abs_j = abs(j); int k = (int) divrem(t, qd_real::_pi1024, t); int abs_k = abs(k); if (abs_j > 2) { //cerr << "ERROR (qd_real::sincos): Cannot reduce modulo pi/2." << endl; //qd_real::abort(); return; } if (abs_k > 256) { //cerr << "ERROR (qd_real::sincos): Cannot reduce modulo pi/1024." << endl; //qd_real::abort(); return; } sincos_taylor(t, sin_t, cos_t); if (abs_k == 0) { s = sin_t; c = cos_t; } else { qd_real u = qd_real::cos_table[abs_k-1]; qd_real v = qd_real::sin_table[abs_k-1]; if (k > 0) { s = u * sin_t + v * cos_t; c = u * cos_t - v * sin_t; } else { s = u * sin_t - v * cos_t; c = u * cos_t + v * sin_t; } } if (abs_j == 0) { sin_a = s; cos_a = c; } else if (j == 1) { sin_a = c; cos_a = -s; } else if (j == -1) { sin_a = -c; cos_a = s; } else { sin_a = -s; cos_a = -c; } } qd_real atan(const qd_real &a) { return atan2(a, qd_real(1.0)); } qd_real atan2(const qd_real &y, const qd_real &x) { /* Strategy: Instead of using Taylor series to compute arctan, we instead use Newton's iteration to solve the equation sin(z) = y/r or cos(z) = x/r where r = sqrt(x^2 + y^2). The iteration is given by z' = z + (y - sin(z)) / cos(z) (for equation 1) z' = z - (x - cos(z)) / sin(z) (for equation 2) Here, x and y are normalized so that x^2 + y^2 = 1. If |x| > |y|, then first iteration is used since the denominator is larger. Otherwise, the second is used. */ if (x.is_zero()) { if (y.is_zero()) { /* Both x and y is zero. */ //cerr << "ERROR (qd_real::atan2): Both arguments zero." << endl; //qd_real::abort(); return qd_real::_nan; } return (y.is_positive()) ? qd_real::_pi2 : -qd_real::_pi2; } else if (y.is_zero()) { return (x.is_positive()) ? qd_real(0.0) : qd_real::_pi; } if (x == y) { return (y.is_positive()) ? qd_real::_pi4 : -qd_real::_3pi4; } if (x == -y) { return (y.is_positive()) ? qd_real::_3pi4 : -qd_real::_pi4; } qd_real r = sqrt(sqr(x) + sqr(y)); qd_real xx = x / r; qd_real yy = y / r; /* Compute real precision approximation to atan. */ qd_real z = atan2((real) y, (real) x); qd_real sin_z, cos_z; if (xx > yy) { /* Use Newton iteration 1. z' = z + (y - sin(z)) / cos(z) */ sincos(z, sin_z, cos_z); z += (yy - sin_z) / cos_z; sincos(z, sin_z, cos_z); z += (yy - sin_z) / cos_z; sincos(z, sin_z, cos_z); z += (yy - sin_z) / cos_z; } else { /* Use Newton iteration 2. z' = z - (x - cos(z)) / sin(z) */ sincos(z, sin_z, cos_z); z -= (xx - cos_z) / sin_z; sincos(z, sin_z, cos_z); z -= (xx - cos_z) / sin_z; sincos(z, sin_z, cos_z); z -= (xx - cos_z) / sin_z; } return z; } qd_real drem(const qd_real &a, const qd_real &b) { qd_real n = nint(a/b); return (a - n * b); } qd_real divrem(const qd_real &a, const qd_real &b, qd_real &r) { qd_real n = nint(a/b); r = a - n * b; return n; } qd_real tan(const qd_real &a) { qd_real s, c; sincos(a, s, c); return s/c; } qd_real asin(const qd_real &a) { qd_real abs_a = fabs(a); if (abs_a > real(1.0)) { //cerr << "ERROR (qd_real::asin): Argument out of domain." << endl; //qd_real::abort(); return qd_real::_nan; } if (abs_a.is_one()) { return (a.is_positive()) ? qd_real::_pi2 : -qd_real::_pi2; } return atan2(a, sqrt(real(1.0) - sqr(a))); } qd_real acos(const qd_real &a) { qd_real abs_a = fabs(a); if (abs_a > real(1.0)) { //cerr << "ERROR (qd_real::acos): Argument out of domain." << endl; //qd_real::abort(); return qd_real::_nan; } if (abs_a.is_one()) { return (a.is_positive()) ? qd_real(0.0) : qd_real::_pi; } return atan2(sqrt(real(1.0) - sqr(a)), a); } qd_real sinh(const qd_real &a) { if (a.is_zero()) { return real(0.0); } if (fabs(a) > real(0.05)) { qd_real ea = exp(a); return mul_pwr2(ea - inv(ea), real(0.5)); } /* Since a is small, using the above formula gives a lot of cancellation. So use Taylor series. */ qd_real s = a; qd_real t = a; qd_real r = sqr(t); real m = real(1.0); real thresh = fabsl(((real) a) * qd_real::_eps); do { m += real(2.0); t *= r; t /= (m-1) * m; s += t; } while (fabs(t) > thresh); return s; } qd_real cosh(const qd_real &a) { if (a.is_zero()) { return real(1.0); } qd_real ea = exp(a); return mul_pwr2(ea + inv(ea), real(0.5)); } qd_real tanh(const qd_real &a) { if (a.is_zero()) { return real(0.0); } if (fabsl((real) a) > real(0.05)) { qd_real ea = exp(a); qd_real inv_ea = inv(ea); return (ea - inv_ea) / (ea + inv_ea); } else { qd_real s, c; s = sinh(a); c = sqrt(real(1.0) + sqr(s)); return s / c; } } void sincosh(const qd_real &a, qd_real &s, qd_real &c) { if (fabs((real) a) <= real(0.05)) { s = sinh(a); c = sqrt(real(1.0) + sqr(s)); } else { qd_real ea = exp(a); qd_real inv_ea = inv(ea); s = mul_pwr2(ea - inv_ea, real(0.5)); c = mul_pwr2(ea + inv_ea, real(0.5)); } } qd_real asinh(const qd_real &a) { return log(a + sqrt(sqr(a) + real(1.0))); } qd_real acosh(const qd_real &a) { if (a < real(1.0)) { //cerr << "ERROR (qd_real::acosh): Argument out of domain." << endl; //qd_real::abort(); return qd_real::_nan; } return log(a + sqrt(sqr(a) - real(1.0))); } qd_real atanh(const qd_real &a) { if (fabs(a) >= real(1.0)) { //cerr << "ERROR (qd_real::atanh): Argument out of domain." << endl; //qd_real::abort(); return qd_real::_nan; } return mul_pwr2(log((real(1.0) + a) / (real(1.0) - a)), real(0.5)); } qd_real qdrand() { static const real m_const = 4.6566128730773926e-10; /* = 2^{-31} */ real m = m_const; qd_real r = real(0.0); real d; /* Strategy: Generate 31 bits at a time, using lrand48 random number generator. Shift the bits, and repeat 7 times. */ for (int i = 0; i < 7; i++, m *= m_const) { d = STD_RAND() * m; r += d; } return r; } /* polyeval(c, n, x) Evaluates the given n-th degree polynomial at x. The polynomial is given by the array of (n+1) coefficients. */ qd_real polyeval(const qd_real *c, int n, const qd_real &x) { /* Just use Horner's method of polynomial evaluation. */ qd_real r = c[n]; for (int i = n-1; i >= 0; i--) { r *= x; r += c[i]; } return r; } /* polyroot(c, n, x0) Given an n-th degree polynomial, finds a root close to the given guess x0. Note that this uses simple Newton iteration scheme, and does not work for multiple roots. */ qd_real polyroot(const qd_real *c, int n, const qd_real &x0, real thresh) { qd_real x = x0; qd_real f; qd_real *d = new qd_real[n]; bool conv = false; int i; /* Compute the coefficients of the derivatives. */ for (i = 0; i < n; i++) { d[i] = c[i+1] * (real) (i+1); } /* Newton iteration. */ for (i = 0; i < 20; i++) { f = polyeval(c, n, x); if (abs(f) < thresh) { conv = true; break; } x -= (f / polyeval(d, n-1, x)); } delete [] d; if (!conv) { //cerr << "ERROR (qd_real::polyroot): Failed to converge." << endl; //qd_real::abort(); return qd_real::_nan; } return x; } #ifdef QD_DEBUG qd_real qd_real::debug_rand() { if (STD_RAND() % 2 == 0) return qdrand(); int expn = 0; qd_real a = real(0.0); real d; for (int i = 0; i < 4; i++) { d = ldexpl(STD_RAND() / (real) RAND_MAX, -expn); a += d; expn = expn + 54 + STD_RAND() % 200; } return a; } #endif void qd_real::renorm() { ::renorm(x[0], x[1], x[2], x[3]); } void qd_real::renorm(real &e) { ::renorm(x[0], x[1], x[2], x[3], e); }
20.380395
112
0.5
e91ad983f822d9ff5302359d933c695141d3b9fc
40,106
cc
C++
third_party/blink/renderer/core/editing/layout_selection.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
third_party/blink/renderer/core/editing/layout_selection.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
third_party/blink/renderer/core/editing/layout_selection.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
/* * Copyright (C) 1999 Lars Knoll (knoll@kde.org) * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights * reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "third_party/blink/renderer/core/editing/layout_selection.h" #include "third_party/blink/renderer/core/dom/document.h" #include "third_party/blink/renderer/core/dom/node_computed_style.h" #include "third_party/blink/renderer/core/editing/editing_utilities.h" #include "third_party/blink/renderer/core/editing/ephemeral_range.h" #include "third_party/blink/renderer/core/editing/frame_selection.h" #include "third_party/blink/renderer/core/editing/selection_template.h" #include "third_party/blink/renderer/core/editing/visible_position.h" #include "third_party/blink/renderer/core/editing/visible_units.h" #include "third_party/blink/renderer/core/html/forms/text_control_element.h" #include "third_party/blink/renderer/core/layout/api/line_layout_api_shim.h" #include "third_party/blink/renderer/core/layout/layout_text.h" #include "third_party/blink/renderer/core/layout/layout_text_fragment.h" #include "third_party/blink/renderer/core/layout/layout_view.h" #include "third_party/blink/renderer/core/layout/line/inline_text_box.h" #include "third_party/blink/renderer/core/layout/ng/inline/ng_fragment_item.h" #include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_cursor.h" #include "third_party/blink/renderer/core/layout/ng/inline/ng_offset_mapping.h" #include "third_party/blink/renderer/core/layout/ng/inline/ng_physical_line_box_fragment.h" #include "third_party/blink/renderer/core/layout/ng/ng_block_node.h" #include "third_party/blink/renderer/core/paint/paint_layer.h" #include "third_party/blink/renderer/platform/fonts/shaping/shape_result_view.h" namespace blink { namespace { // TODO(yoichio): Share condition between NGOffsetMapping::AcceptsPosition. bool ShouldUseLayoutNGTextContent(const Node& node) { LayoutObject* layout_object = node.GetLayoutObject(); DCHECK(layout_object); if (layout_object->IsInline()) return layout_object->ContainingNGBlockFlow(); if (auto* block_flow = DynamicTo<LayoutBlockFlow>(layout_object)) return NGBlockNode::CanUseNewLayout(*block_flow); return false; } } // namespace // The current selection to be painted is represented as 2 pairs of // (Node, offset). // Each offset represents text offsets on selection edge if it is text. // For example, suppose we select "f^oo<br><img>|", // |start_offset_| is 1 and |end_offset_| is nullopt. // If on NG, offset is on text content offset rather than each text node. class SelectionPaintRange : public GarbageCollected<SelectionPaintRange> { public: SelectionPaintRange() = default; SelectionPaintRange(const Node& passed_start_node, absl::optional<unsigned> passed_start_offset, const Node& passed_end_node, absl::optional<unsigned> passed_end_offset) : start_node(passed_start_node), start_offset(passed_start_offset), end_node(passed_end_node), end_offset(passed_end_offset) {} void Trace(Visitor* visitor) const { visitor->Trace(start_node); visitor->Trace(end_node); } bool IsNull() const { return !start_node; } void AssertSanity() const { #if DCHECK_IS_ON() if (start_node) { DCHECK(end_node); DCHECK(start_node->GetLayoutObject()->GetSelectionState() == SelectionState::kStart || start_node->GetLayoutObject()->GetSelectionState() == SelectionState::kStartAndEnd); DCHECK(end_node->GetLayoutObject()->GetSelectionState() == SelectionState::kEnd || end_node->GetLayoutObject()->GetSelectionState() == SelectionState::kStartAndEnd); return; } DCHECK(!end_node); DCHECK(!start_offset.has_value()); DCHECK(!end_offset.has_value()); #endif } Member<const Node> start_node; absl::optional<unsigned> start_offset; Member<const Node> end_node; absl::optional<unsigned> end_offset; }; LayoutSelection::LayoutSelection(FrameSelection& frame_selection) : frame_selection_(&frame_selection), has_pending_selection_(false), paint_range_(MakeGarbageCollected<SelectionPaintRange>()) {} enum class SelectionMode { kNone, kRange, }; void LayoutSelection::AssertIsValid() const { const Document& document = frame_selection_->GetDocument(); DCHECK_GE(document.Lifecycle().GetState(), DocumentLifecycle::kLayoutClean); DCHECK(!document.IsSlotAssignmentOrLegacyDistributionDirty()); DCHECK(!has_pending_selection_); } static SelectionMode ComputeSelectionMode( const FrameSelection& frame_selection) { const SelectionInDOMTree& selection_in_dom = frame_selection.GetSelectionInDOMTree(); if (selection_in_dom.IsRange()) return SelectionMode::kRange; DCHECK(selection_in_dom.IsCaret()); return SelectionMode::kNone; } static EphemeralRangeInFlatTree CalcSelectionInFlatTree( const FrameSelection& frame_selection) { const SelectionInDOMTree& selection_in_dom = frame_selection.GetSelectionInDOMTree(); switch (ComputeSelectionMode(frame_selection)) { case SelectionMode::kNone: return {}; case SelectionMode::kRange: { const PositionInFlatTree& base = ToPositionInFlatTree(selection_in_dom.Base()); const PositionInFlatTree& extent = ToPositionInFlatTree(selection_in_dom.Extent()); if (base.IsNull() || extent.IsNull() || base == extent || !base.IsValidFor(frame_selection.GetDocument()) || !extent.IsValidFor(frame_selection.GetDocument())) return {}; return base <= extent ? EphemeralRangeInFlatTree(base, extent) : EphemeralRangeInFlatTree(extent, base); } } NOTREACHED(); return {}; } // OldSelectedNodes is current selected Nodes with // current SelectionState which is kStart, kEnd, kStartAndEnd or kInside. struct OldSelectedNodes { STACK_ALLOCATED(); public: OldSelectedNodes() : paint_range(MakeGarbageCollected<SelectionPaintRange>()) {} OldSelectedNodes(OldSelectedNodes&& other) { paint_range = other.paint_range; selected_map = std::move(other.selected_map); } OldSelectedNodes(const OldSelectedNodes&) = delete; OldSelectedNodes& operator=(const OldSelectedNodes&) = delete; SelectionPaintRange* paint_range; HeapHashMap<Member<const Node>, SelectionState> selected_map; }; std::ostream& operator<<(std::ostream&, const OldSelectedNodes&); // This struct represents a selection range in layout tree and each // Node is SelectionState-marked. struct NewPaintRangeAndSelectedNodes { STACK_ALLOCATED(); public: NewPaintRangeAndSelectedNodes() : paint_range(MakeGarbageCollected<SelectionPaintRange>()) {} NewPaintRangeAndSelectedNodes( SelectionPaintRange* passed_paint_range, HeapHashSet<Member<const Node>>&& passed_selected_objects) : paint_range(passed_paint_range), selected_objects(std::move(passed_selected_objects)) {} NewPaintRangeAndSelectedNodes(NewPaintRangeAndSelectedNodes&& other) { paint_range = other.paint_range; selected_objects = std::move(other.selected_objects); } NewPaintRangeAndSelectedNodes(const NewPaintRangeAndSelectedNodes&) = delete; NewPaintRangeAndSelectedNodes& operator=( const NewPaintRangeAndSelectedNodes&) = delete; void AssertSanity() const { #if DCHECK_IS_ON() paint_range->AssertSanity(); if (paint_range->start_node) { DCHECK(selected_objects.Contains(paint_range->start_node)) << this; DCHECK(selected_objects.Contains(paint_range->end_node)) << this; return; } DCHECK(selected_objects.IsEmpty()) << this; #endif } SelectionPaintRange* paint_range; HeapHashSet<Member<const Node>> selected_objects; }; std::ostream& operator<<(std::ostream&, const NewPaintRangeAndSelectedNodes&); static void SetShouldInvalidateIfNeeded(LayoutObject* layout_object) { if (layout_object->ShouldInvalidateSelection()) return; layout_object->SetShouldInvalidateSelection(); // We should invalidate if ancestor of |layout_object| is LayoutSVGText // because SVGRootInlineBoxPainter::Paint() paints selection for // |layout_object| in/ LayoutSVGText and it is invoked when parent // LayoutSVGText is invalidated. // That is different from InlineTextBoxPainter::Paint() which paints // LayoutText selection when LayoutText is invalidated. if (!layout_object->IsSVG()) return; for (LayoutObject* parent = layout_object->Parent(); parent; parent = parent->Parent()) { if (parent->IsSVGRoot()) return; if (parent->IsSVGText() || parent->IsNGSVGText()) { if (!parent->ShouldInvalidateSelection()) parent->SetShouldInvalidateSelection(); return; } } } static LayoutTextFragment* FirstLetterPartFor( const LayoutObject* layout_object) { // TODO(yoichio): LayoutText::GetFirstLetterPart() should be typed // LayoutTextFragment. if (const auto* layout_text = DynamicTo<LayoutText>(layout_object)) return To<LayoutTextFragment>(layout_text->GetFirstLetterPart()); return nullptr; } static void SetShouldInvalidateIfNeeded(const Node& node) { LayoutObject* layout_object = node.GetLayoutObject(); if (!layout_object) return; if (LayoutTextFragment* first_letter = FirstLetterPartFor(layout_object)) SetShouldInvalidateIfNeeded(first_letter); SetShouldInvalidateIfNeeded(layout_object); } static void SetSelectionStateIfNeeded(const Node& node, SelectionState state) { DCHECK_NE(state, SelectionState::kContain) << node; DCHECK_NE(state, SelectionState::kNone) << node; LayoutObject* layout_object = node.GetLayoutObject(); if (layout_object->GetSelectionState() == state) return; layout_object->SetSelectionState(state); // Set ancestors SelectionState kContain for CSS ::selection style. // See LayoutObject::InvalidateSelectedChildrenOnStyleChange(). for (Node& ancestor : FlatTreeTraversal::AncestorsOf(node)) { LayoutObject* ancestor_layout = ancestor.GetLayoutObject(); if (!ancestor_layout) continue; if (ancestor_layout->GetSelectionState() == SelectionState::kContain) return; ancestor_layout->LayoutObject::SetSelectionState(SelectionState::kContain); } } // Set ShouldInvalidateSelection flag of LayoutObjects // comparing them in |new_range| and |old_range|. static void SetShouldInvalidateSelection( const NewPaintRangeAndSelectedNodes& new_range, const OldSelectedNodes& old_selected_objects) { // We invalidate each LayoutObject in // MakeGarbageCollected<SelectionPaintRange> which has SelectionState of // kStart, kEnd, kStartAndEnd, or kInside and is not in old // SelectionPaintRange. for (const Node* node : new_range.selected_objects) { if (old_selected_objects.selected_map.Contains(node)) continue; const SelectionState new_state = node->GetLayoutObject()->GetSelectionState(); DCHECK_NE(new_state, SelectionState::kContain) << node; DCHECK_NE(new_state, SelectionState::kNone) << node; SetShouldInvalidateIfNeeded(*node); } // For LayoutObject in old SelectionPaintRange, we invalidate LayoutObjects // each of: // 1. LayoutObject was painted and would not be painted. // 2. LayoutObject was not painted and would be painted. for (const auto& key_value : old_selected_objects.selected_map) { const Node* const node = key_value.key; const SelectionState old_state = key_value.value; const SelectionState new_state = node->GetLayoutObject()->GetSelectionState(); if (new_state == old_state) continue; DCHECK(new_state != SelectionState::kNone || old_state != SelectionState::kNone) << node; DCHECK_NE(new_state, SelectionState::kContain) << node; DCHECK_NE(old_state, SelectionState::kContain) << node; SetShouldInvalidateIfNeeded(*node); } // Invalidate Selection start/end is moving on a same node. const SelectionPaintRange& new_paint_range = *new_range.paint_range; const SelectionPaintRange& old_paint_range = *old_selected_objects.paint_range; if (new_paint_range.IsNull()) return; if (new_paint_range.start_node->IsTextNode() && new_paint_range.start_node == old_paint_range.start_node && new_paint_range.start_offset != old_paint_range.start_offset) SetShouldInvalidateIfNeeded(*new_paint_range.start_node); if (new_paint_range.end_node->IsTextNode() && new_paint_range.end_node == old_paint_range.end_node && new_paint_range.end_offset != old_paint_range.end_offset) SetShouldInvalidateIfNeeded(*new_paint_range.end_node); } static bool IsDisplayContentElement(const Node& node) { if (!node.IsElementNode()) return false; const ComputedStyle* const style = node.GetComputedStyle(); return style && style->Display() == EDisplay::kContents; } template <typename Visitor> static void VisitSelectedInclusiveDescendantsOfInternal(const Node& node, Visitor* visitor) { // Display:content element appears in a flat tree even it doesn't have // a LayoutObject but we need to visit its children. if (!IsDisplayContentElement(node)) { LayoutObject* layout_object = node.GetLayoutObject(); if (!layout_object) return; if (layout_object->GetSelectionState() == SelectionState::kNone) return; visitor->Visit(node); } for (Node& child : FlatTreeTraversal::ChildrenOf(node)) VisitSelectedInclusiveDescendantsOfInternal(child, visitor); } static inline bool IsFlatTreeClean(const Node& node) { return !node.GetDocument().IsSlotAssignmentOrLegacyDistributionDirty(); } template <typename Visitor> static void VisitSelectedInclusiveDescendantsOf(const Node& node, Visitor* visitor) { DCHECK(IsFlatTreeClean(node)); return VisitSelectedInclusiveDescendantsOfInternal(node, visitor); } static OldSelectedNodes ResetOldSelectedNodes( const Node& root, absl::optional<unsigned> old_start_offset, absl::optional<unsigned> old_end_offset) { class OldSelectedVisitor { STACK_ALLOCATED(); public: OldSelectedVisitor(absl::optional<unsigned> passed_old_start_offset, absl::optional<unsigned> passed_old_end_offset) : old_start_offset(passed_old_start_offset), old_end_offset(passed_old_end_offset) {} void Visit(const Node& node) { LayoutObject* layout_object = node.GetLayoutObject(); const SelectionState old_state = layout_object->GetSelectionState(); DCHECK_NE(old_state, SelectionState::kNone) << node; layout_object->SetSelectionState(SelectionState::kNone); if (old_state == SelectionState::kContain) return; old_selected_objects.selected_map.insert(&node, old_state); if (old_state == SelectionState::kInside) return; switch (old_state) { case SelectionState::kStart: { DCHECK(!old_selected_objects.paint_range->start_node); old_selected_objects.paint_range->start_node = node; old_selected_objects.paint_range->start_offset = old_start_offset; break; } case SelectionState::kEnd: { DCHECK(!old_selected_objects.paint_range->end_node); old_selected_objects.paint_range->end_node = node; old_selected_objects.paint_range->end_offset = old_end_offset; break; } case SelectionState::kStartAndEnd: { DCHECK(!old_selected_objects.paint_range->start_node); DCHECK(!old_selected_objects.paint_range->end_node); old_selected_objects.paint_range->start_node = node; old_selected_objects.paint_range->start_offset = old_start_offset; old_selected_objects.paint_range->end_node = node; old_selected_objects.paint_range->end_offset = old_end_offset; break; } default: { NOTREACHED(); break; } } } OldSelectedNodes old_selected_objects; const absl::optional<unsigned> old_start_offset; const absl::optional<unsigned> old_end_offset; } visitor(old_start_offset, old_end_offset); VisitSelectedInclusiveDescendantsOf(root, &visitor); return std::move(visitor.old_selected_objects); } static absl::optional<unsigned> ComputeStartOffset( const Node& node, const PositionInFlatTree& selection_start) { if (!node.IsTextNode()) return absl::nullopt; if (&node == selection_start.AnchorNode()) return selection_start.OffsetInContainerNode(); return 0; } static absl::optional<unsigned> ComputeEndOffset( const Node& node, const PositionInFlatTree& selection_end) { auto* text_node = DynamicTo<Text>(node); if (!text_node) return absl::nullopt; if (&node == selection_end.AnchorNode()) return selection_end.OffsetInContainerNode(); return text_node->length(); } #if DCHECK_IS_ON() // Position should be offset on text or before/after a break element. static bool IsPositionValidText(const Position& position) { if (position.AnchorNode()->IsTextNode() && position.IsOffsetInAnchor()) return true; if ((IsA<HTMLBRElement>(position.AnchorNode()) || IsA<HTMLWBRElement>(position.AnchorNode())) && (position.IsBeforeAnchor() || position.IsAfterAnchor())) return true; return false; } #endif static absl::optional<unsigned> GetTextContentOffset(const Position& position) { if (position.IsNull()) return absl::nullopt; #if DCHECK_IS_ON() DCHECK(IsPositionValidText(position)); #endif DCHECK(ShouldUseLayoutNGTextContent(*position.AnchorNode())); const NGOffsetMapping* const offset_mapping = NGOffsetMapping::GetFor(position); DCHECK(offset_mapping); const absl::optional<unsigned>& ng_offset = offset_mapping->GetTextContentOffset(position); return ng_offset; } // Computes text content offset of selection start if |layout_object| is // LayoutText. static absl::optional<unsigned> GetTextContentOffsetStart( const Node& node, absl::optional<unsigned> node_offset) { if (!node.GetLayoutObject()->IsText()) return absl::nullopt; if (node.IsTextNode()) { DCHECK(node_offset.has_value()) << node; return GetTextContentOffset(Position(node, node_offset.value())); } DCHECK(IsA<HTMLWBRElement>(node) || IsA<HTMLBRElement>(node)) << node; DCHECK(!node_offset.has_value()) << node; return GetTextContentOffset(Position::BeforeNode(node)); } // Computes text content offset of selection end if |layout_object| is // LayoutText. static absl::optional<unsigned> GetTextContentOffsetEnd( const Node& node, absl::optional<unsigned> node_offset) { if (!node.GetLayoutObject()->IsText()) return {}; if (node.IsTextNode()) { DCHECK(node_offset.has_value()) << node; return GetTextContentOffset(Position(node, node_offset.value())); } DCHECK(IsA<HTMLWBRElement>(node) || IsA<HTMLBRElement>(node)) << node; DCHECK(!node_offset.has_value()) << node; return GetTextContentOffset(Position::AfterNode(node)); } static SelectionPaintRange* ComputeNewPaintRange( const SelectionPaintRange& paint_range) { DCHECK(!paint_range.IsNull()); const Node& start_node = *paint_range.start_node; // If LayoutObject is not in NG, use legacy offset. const absl::optional<unsigned> start_offset = ShouldUseLayoutNGTextContent(start_node) ? GetTextContentOffsetStart(start_node, paint_range.start_offset) : paint_range.start_offset; const Node& end_node = *paint_range.end_node; const absl::optional<unsigned> end_offset = ShouldUseLayoutNGTextContent(end_node) ? GetTextContentOffsetEnd(end_node, paint_range.end_offset) : paint_range.end_offset; return MakeGarbageCollected<SelectionPaintRange>( *paint_range.start_node, start_offset, *paint_range.end_node, end_offset); } static unsigned ClampOffset(unsigned offset, unsigned start_offset, unsigned end_offset) { DCHECK_LE(start_offset, end_offset); return std::min(std::max(offset, start_offset), end_offset); } static Text* AssociatedTextNode(const LayoutText& text) { if (const auto* fragment = DynamicTo<LayoutTextFragment>(text)) return fragment->AssociatedTextNode(); if (Node* node = text.GetNode()) return DynamicTo<Text>(node); return nullptr; } static SelectionState GetSelectionStateFor(const LayoutText& layout_text) { if (const auto* text_fragment = DynamicTo<LayoutTextFragment>(layout_text)) { Node* node = text_fragment->AssociatedTextNode(); if (!node) return SelectionState::kNone; return node->GetLayoutObject()->GetSelectionState(); } return layout_text.GetSelectionState(); } static SelectionState GetSelectionStateFor( const NGInlineCursorPosition& position) { DCHECK(position.GetLayoutObject()); return GetSelectionStateFor(To<LayoutText>(*position.GetLayoutObject())); } bool LayoutSelection::IsSelected(const LayoutObject& layout_object) { if (const auto* layout_text = DynamicTo<LayoutText>(layout_object)) return GetSelectionStateFor(*layout_text) != SelectionState::kNone; return layout_object.GetSelectionState() != SelectionState::kNone; } static inline unsigned ClampOffset(unsigned node_offset, const LayoutTextFragment& fragment) { if (fragment.Start() > node_offset) return 0; return std::min(node_offset - fragment.Start(), fragment.FragmentLength()); } static LayoutTextSelectionStatus ComputeSelectionStatusForNode( const Text& text, SelectionState selection_state, absl::optional<unsigned> start_offset, absl::optional<unsigned> end_offset) { switch (selection_state) { case SelectionState::kInside: return {0, text.length(), SelectionIncludeEnd::kInclude}; case SelectionState::kStart: return {start_offset.value(), text.length(), SelectionIncludeEnd::kInclude}; case SelectionState::kEnd: return {0, end_offset.value(), SelectionIncludeEnd::kNotInclude}; case SelectionState::kStartAndEnd: return {start_offset.value(), end_offset.value(), SelectionIncludeEnd::kNotInclude}; default: NOTREACHED(); return {0, 0, SelectionIncludeEnd::kNotInclude}; } } LayoutTextSelectionStatus LayoutSelection::ComputeSelectionStatus( const LayoutText& layout_text) const { AssertIsValid(); const SelectionState selection_state = GetSelectionStateFor(layout_text); if (selection_state == SelectionState::kNone) return {0, 0, SelectionIncludeEnd::kNotInclude}; if (Text* text = AssociatedTextNode(layout_text)) { const LayoutTextSelectionStatus text_status = ComputeSelectionStatusForNode( *text, selection_state, paint_range_->start_offset, paint_range_->end_offset); if (const auto* text_fragment = DynamicTo<LayoutTextFragment>(layout_text)) { return {ClampOffset(text_status.start, *text_fragment), ClampOffset(text_status.end, *text_fragment), text_status.include_end}; } return text_status; } // TODO(yoichio): This is really weird legacy behavior. Remove this. if (layout_text.IsBR() && selection_state == SelectionState::kEnd) return {0, 0, SelectionIncludeEnd::kNotInclude}; return {0, layout_text.TextLength(), SelectionIncludeEnd::kInclude}; } LayoutTextSelectionStatus FrameSelection::ComputeLayoutSelectionStatus( const LayoutText& text) const { return layout_selection_->ComputeSelectionStatus(text); } // FrameSelection holds selection offsets in layout block flow at // LayoutSelection::Commit() if selection starts/ends within Text that // each LayoutObject::SelectionState indicates. // These offset can be out of fragment because SelectionState is of each // LayoutText and not of each fragment for it. LayoutSelectionStatus LayoutSelection::ComputeSelectionStatus( const NGInlineCursor& cursor) const { const NGInlineCursorPosition& current = cursor.Current(); if (!current.IsLayoutGeneratedText()) return ComputeSelectionStatus(cursor, current.TextOffset()); // We don't paint selection on ellipsis. if (current.IsEllipsis()) return {0, 0, SelectSoftLineBreak::kNotSelected}; // Layout-generated text does not have corresponding text in the DOM. Find if // the previous character is selected. This is a soft-hyphen character if the // hyphen is generated from it, or the character before the hyphen if // automatic hyphenation. const unsigned offset = current->StartOffsetInContainer(cursor); DCHECK_GT(offset, 0u); LayoutSelectionStatus status = ComputeSelectionStatus(cursor, {offset - 1, offset}); if (!status.HasValidRange()) return status; // Make |LayoutSelectionStatus| to select the whole text of the hyphen. status.start = 0; status.end = current->TextLength(); return status; } LayoutSelectionStatus LayoutSelection::ComputeSelectionStatus( const NGInlineCursor& cursor, const NGTextOffset& offset) const { const unsigned start_offset = offset.start; const unsigned end_offset = offset.end; switch (GetSelectionStateFor(cursor.Current())) { case SelectionState::kStart: { const unsigned start_in_block = paint_range_->start_offset.value(); const bool is_continuous = start_in_block <= end_offset; return {ClampOffset(start_in_block, start_offset, end_offset), end_offset, (is_continuous && cursor.IsBeforeSoftLineBreak()) ? SelectSoftLineBreak::kSelected : SelectSoftLineBreak::kNotSelected}; } case SelectionState::kEnd: { const unsigned end_in_block = paint_range_->end_offset.value(); const unsigned end_in_fragment = ClampOffset(end_in_block, start_offset, end_offset); const bool is_continuous = end_offset < end_in_block; return {start_offset, end_in_fragment, (is_continuous && cursor.IsBeforeSoftLineBreak()) ? SelectSoftLineBreak::kSelected : SelectSoftLineBreak::kNotSelected}; } case SelectionState::kStartAndEnd: { const unsigned start_in_block = paint_range_->start_offset.value(); const unsigned end_in_block = paint_range_->end_offset.value(); const unsigned end_in_fragment = ClampOffset(end_in_block, start_offset, end_offset); const bool is_continuous = start_in_block <= end_offset && end_offset < end_in_block; return {ClampOffset(start_in_block, start_offset, end_offset), end_in_fragment, (is_continuous && cursor.IsBeforeSoftLineBreak()) ? SelectSoftLineBreak::kSelected : SelectSoftLineBreak::kNotSelected}; } case SelectionState::kInside: { return {start_offset, end_offset, cursor.IsBeforeSoftLineBreak() ? SelectSoftLineBreak::kSelected : SelectSoftLineBreak::kNotSelected}; } default: // This block is not included in selection. return {0, 0, SelectSoftLineBreak::kNotSelected}; } } // Given |state| that describes the provided offsets relationship to the // |paint_range_| (and thus which comparisons are valid), returns a // SelectionState that reflects where the endpoints of the selection fall, // relative to the range expressed by the offsets. SelectionState LayoutSelection::ComputeSelectionStateFromOffsets( SelectionState state, unsigned start_offset, unsigned end_offset) const { switch (state) { case SelectionState::kStart: { const unsigned start_in_block = paint_range_->start_offset.value_or(start_offset); return start_offset <= start_in_block && start_in_block <= end_offset ? SelectionState::kStart : SelectionState::kNone; } case SelectionState::kEnd: { const unsigned end_in_block = paint_range_->end_offset.value_or(end_offset); return start_offset <= end_in_block && end_in_block <= end_offset ? SelectionState::kEnd : SelectionState::kNone; } case SelectionState::kStartAndEnd: { const unsigned start_in_block = paint_range_->start_offset.value_or(start_offset); const unsigned end_in_block = paint_range_->end_offset.value_or(end_offset); const bool is_start_in_current_cursor = start_offset <= start_in_block && start_in_block <= end_offset; const bool is_end_in_current_cursor = start_offset <= end_in_block && end_in_block <= end_offset; if (is_start_in_current_cursor && is_end_in_current_cursor) return SelectionState::kStartAndEnd; else if (is_start_in_current_cursor) return SelectionState::kStart; else if (is_end_in_current_cursor) return SelectionState::kEnd; else return SelectionState::kInside; } case SelectionState::kInside: { return SelectionState::kInside; } default: return SelectionState::kNone; } } SelectionState LayoutSelection::ComputeSelectionStateForCursor( const NGInlineCursorPosition& position) const { if (!position) return SelectionState::kNone; DCHECK(position.IsText()); // Selection on ellipsis is not supported. if (position.IsEllipsis()) return SelectionState::kNone; const NGTextOffset offset = position.TextOffset(); const unsigned start_offset = offset.start; const unsigned end_offset = offset.end; // Determine the state of the overall selection, relative to the LayoutObject // associated with the current cursor position. This state will allow us know // which offset comparisons are valid, and determine if the selection // endpoints fall within the current cursor position. SelectionState state = GetSelectionStateFor(position); return ComputeSelectionStateFromOffsets(state, start_offset, end_offset); } SelectionState LayoutSelection::ComputeSelectionStateForInlineTextBox( const InlineTextBox& text_box) const { AssertIsValid(); unsigned start_offset = static_cast<unsigned>(text_box.CaretMinOffset()); unsigned end_offset = static_cast<unsigned>(text_box.CaretMaxOffset()); // Determine the state of the overall selection, relative to the // InlineTextBox. This state will allow us know which offset comparisons are // valid, and determine if the selection endpoints fall within InlineTextBox. const LayoutText* text = To<LayoutText>( LineLayoutAPIShim::ConstLayoutObjectFrom(text_box.GetLineLayoutItem())); SelectionState state = GetSelectionStateFor(*text); return ComputeSelectionStateFromOffsets(state, start_offset, end_offset); } static NewPaintRangeAndSelectedNodes CalcSelectionRangeAndSetSelectionState( const FrameSelection& frame_selection) { const SelectionInDOMTree& selection_in_dom = frame_selection.GetSelectionInDOMTree(); if (selection_in_dom.IsNone()) return {}; const EphemeralRangeInFlatTree& selection = CalcSelectionInFlatTree(frame_selection); if (selection.IsCollapsed() || frame_selection.IsHidden()) return {}; // Find first/last Node which has a visible LayoutObject while // marking SelectionState and collecting invalidation candidate LayoutObjects. const Node* start_node = nullptr; const Node* end_node = nullptr; HeapHashSet<Member<const Node>> selected_objects; for (Node& node : selection.Nodes()) { LayoutObject* const layout_object = node.GetLayoutObject(); if (!layout_object || !layout_object->CanBeSelectionLeaf()) continue; if (!start_node) { DCHECK(!end_node); start_node = end_node = &node; continue; } // In this loop, |end_node| is pointing current last candidate // LayoutObject and if it is not start and we find next, we mark the // current one as kInside. if (end_node != start_node) { SetSelectionStateIfNeeded(*end_node, SelectionState::kInside); selected_objects.insert(end_node); } end_node = &node; } // No valid LayOutObject found. if (!start_node) { DCHECK(!end_node); return {}; } // Compute offset. It has value iff start/end is text. const absl::optional<unsigned> start_offset = ComputeStartOffset( *start_node, selection.StartPosition().ToOffsetInAnchor()); const absl::optional<unsigned> end_offset = ComputeEndOffset(*end_node, selection.EndPosition().ToOffsetInAnchor()); if (start_node == end_node) { SetSelectionStateIfNeeded(*start_node, SelectionState::kStartAndEnd); selected_objects.insert(start_node); } else { SetSelectionStateIfNeeded(*start_node, SelectionState::kStart); selected_objects.insert(start_node); SetSelectionStateIfNeeded(*end_node, SelectionState::kEnd); selected_objects.insert(end_node); } SelectionPaintRange* new_range = MakeGarbageCollected<SelectionPaintRange>( *start_node, start_offset, *end_node, end_offset); if (!RuntimeEnabledFeatures::LayoutNGEnabled()) return {new_range, std::move(selected_objects)}; return {ComputeNewPaintRange(*new_range), std::move(selected_objects)}; } void LayoutSelection::SetHasPendingSelection() { has_pending_selection_ = true; } void LayoutSelection::Commit() { if (!has_pending_selection_) return; has_pending_selection_ = false; DCHECK(!frame_selection_->GetDocument().NeedsLayoutTreeUpdate()); DCHECK_GE(frame_selection_->GetDocument().Lifecycle().GetState(), DocumentLifecycle::kLayoutClean); DocumentLifecycle::DisallowTransitionScope disallow_transition( frame_selection_->GetDocument().Lifecycle()); const OldSelectedNodes& old_selected_objects = ResetOldSelectedNodes( frame_selection_->GetDocument(), paint_range_->start_offset, paint_range_->end_offset); const NewPaintRangeAndSelectedNodes& new_range = CalcSelectionRangeAndSetSelectionState(*frame_selection_); new_range.AssertSanity(); DCHECK(frame_selection_->GetDocument().GetLayoutView()->GetFrameView()); SetShouldInvalidateSelection(new_range, old_selected_objects); paint_range_ = new_range.paint_range; } void LayoutSelection::ContextDestroyed() { has_pending_selection_ = false; paint_range_->start_node = nullptr; paint_range_->start_offset = absl::nullopt; paint_range_->end_node = nullptr; paint_range_->end_offset = absl::nullopt; } static PhysicalRect SelectionRectForLayoutObject(const LayoutObject* object) { if (!object->IsRooted()) return PhysicalRect(); if (!object->CanUpdateSelectionOnRootLineBoxes()) return PhysicalRect(); return object->AbsoluteSelectionRect(); } template <typename Visitor> static void VisitLayoutObjectsOf(const Node& node, Visitor* visitor) { LayoutObject* layout_object = node.GetLayoutObject(); if (!layout_object) return; if (layout_object->GetSelectionState() == SelectionState::kContain) return; if (LayoutTextFragment* first_letter = FirstLetterPartFor(layout_object)) visitor->Visit(first_letter); visitor->Visit(layout_object); } gfx::Rect LayoutSelection::AbsoluteSelectionBounds() { Commit(); if (paint_range_->IsNull()) return gfx::Rect(); // Create a single bounding box rect that encloses the whole selection. class SelectionBoundsVisitor { STACK_ALLOCATED(); public: void Visit(const Node& node) { VisitLayoutObjectsOf(node, this); } void Visit(LayoutObject* layout_object) { selected_rect.Unite(SelectionRectForLayoutObject(layout_object)); } PhysicalRect selected_rect; } visitor; VisitSelectedInclusiveDescendantsOf(frame_selection_->GetDocument(), &visitor); return ToPixelSnappedRect(visitor.selected_rect); } void LayoutSelection::InvalidatePaintForSelection() { if (paint_range_->IsNull()) return; class InvalidatingVisitor { STACK_ALLOCATED(); public: void Visit(const Node& node) { VisitLayoutObjectsOf(node, this); } void Visit(LayoutObject* layout_object) { layout_object->SetShouldInvalidateSelection(); } } visitor; VisitSelectedInclusiveDescendantsOf(frame_selection_->GetDocument(), &visitor); } void LayoutSelection::Trace(Visitor* visitor) const { visitor->Trace(frame_selection_); visitor->Trace(paint_range_); } void PrintSelectionStatus(std::ostream& ostream, const Node& node) { ostream << (void*)&node; if (node.IsTextNode()) ostream << "#text"; else if (const auto* element = DynamicTo<Element>(node)) ostream << element->tagName().Utf8(); LayoutObject* layout_object = node.GetLayoutObject(); if (!layout_object) { ostream << " <null LayoutObject>"; return; } ostream << ' ' << layout_object->GetSelectionState(); } #if DCHECK_IS_ON() std::ostream& operator<<(std::ostream& ostream, const absl::optional<unsigned>& offset) { if (offset.has_value()) ostream << offset.value(); else ostream << "<nullopt>"; return ostream; } std::ostream& operator<<(std::ostream& ostream, const SelectionPaintRange& range) { ostream << range.start_node << ": " << range.start_offset << ", " << range.end_node << ": " << range.end_offset; return ostream; } std::ostream& operator<<( std::ostream& ostream, const HeapHashMap<Member<const Node>, SelectionState>& map) { ostream << "["; const char* comma = ""; for (const auto& key_value : map) { const Node* const node = key_value.key; const SelectionState old_state = key_value.value; ostream << comma << node << "." << old_state; comma = ", "; } ostream << "]"; return ostream; } std::ostream& operator<<(std::ostream& ostream, const OldSelectedNodes& old_node) { ostream << old_node.paint_range << ". " << old_node.selected_map; return ostream; } void PrintOldSelectedNodes(const OldSelectedNodes& old_node) { std::stringstream stream; stream << std::endl << old_node; LOG(INFO) << stream.str(); } std::ostream& operator<<( std::ostream& ostream, const HeapHashSet<Member<const Node>>& selected_objects) { ostream << "["; const char* comma = ""; for (const Node* node : selected_objects) { ostream << comma; PrintSelectionStatus(ostream, *node); comma = ", "; } ostream << "]"; return ostream; } std::ostream& operator<<(std::ostream& ostream, const NewPaintRangeAndSelectedNodes& new_range) { ostream << new_range.paint_range << ". " << new_range.selected_objects; return ostream; } void PrintSelectedNodes(const NewPaintRangeAndSelectedNodes& new_range) { std::stringstream stream; stream << std::endl << new_range; LOG(INFO) << stream.str(); } void PrintSelectionStateInDocument(const FrameSelection& selection) { class PrintVisitor { STACK_ALLOCATED(); public: void Visit(const Node& node) { PrintSelectionStatus(stream, node); } std::stringstream stream; } visitor; VisitSelectedInclusiveDescendantsOf(selection.GetDocument(), &visitor); LOG(INFO) << std::endl << visitor.stream.str(); } #endif } // namespace blink
37.587629
91
0.724181
e91ae89244ea57fb12b75ad7443543f1ad1c40a1
17,668
cpp
C++
src/CommandSet.cpp
jacobussystems/IoTJackAC1
c1ad8c13d984362c1bbf1232cbfc34e64fc039ac
[ "MIT" ]
null
null
null
src/CommandSet.cpp
jacobussystems/IoTJackAC1
c1ad8c13d984362c1bbf1232cbfc34e64fc039ac
[ "MIT" ]
null
null
null
src/CommandSet.cpp
jacobussystems/IoTJackAC1
c1ad8c13d984362c1bbf1232cbfc34e64fc039ac
[ "MIT" ]
null
null
null
/* CommandSet.cpp By Jim Davies Jacobus Systems, Brighton & Hove, UK http://www.jacobus.co.uk Provided under the MIT license: https://github.com/jacobussystems/ArdJack/blob/master/LICENSE Copyright (c) 2019 James Davies, Jacobus Systems, Brighton & Hove, UK Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "pch.h" #ifdef ARDUINO #else #include "stdafx.h" #endif #include "Beacon.h" #include "BeaconManager.h" #include "Bridge.h" #include "BridgeManager.h" #include "CmdInterpreter.h" #include "DeviceCodec1.h" #include "CommandSet.h" #include "Connection.h" #include "ConnectionManager.h" #include "Device.h" #include "DeviceManager.h" #include "Displayer.h" #include "Globals.h" #include "IoTMessage.h" #include "Log.h" #include "Part.h" #include "Utils.h" #ifdef ARDJACK_INCLUDE_PERSISTENCE #include "PersistentFile.h" #include "PersistentFileManager.h" #endif #ifdef ARDJACK_NETWORK_AVAILABLE #include "NetworkInterface.h" #include "NetworkManager.h" #endif #ifdef ARDJACK_INCLUDE_TESTS #include "Tests.h" #endif CommandSet::CommandSet() { if (Globals::Verbosity > 7) Log::LogInfo(PRM("CommandSet ctor")); _CommandCount = 0; #ifdef ARDJACK_INCLUDE_PERSISTENCE _CurrentPersistentFile = NULL; #endif for (int i = 0; i < ARDJACK_MAX_COMMANDS; i++) _Commands[i] = NULL; AddCommand(PRM("ACTIVATE"), &CommandSet::command_activate); AddCommand(PRM("ADD"), &CommandSet::command_add); AddCommand(PRM("BEEP"), &CommandSet::command_beep); AddCommand(PRM("CONFIGURE"), &CommandSet::command_configure); AddCommand(PRM("CONNECTION"), &CommandSet::command_connection); AddCommand(PRM("DEACTIVATE"), &CommandSet::command_deactivate); AddCommand(PRM("DEFINE"), &CommandSet::command_define); AddCommand(PRM("DELAY"), &CommandSet::command_delay); AddCommand(PRM("DELETE"), &CommandSet::command_delete); AddCommand(PRM("DEVICE"), &CommandSet::command_device); AddCommand(PRM("DISPLAY"), &CommandSet::command_display); AddCommand(PRM("EXIT"), &CommandSet::command_exit); #ifdef ARDJACK_INCLUDE_PERSISTENCE AddCommand(PRM("FILE"), &CommandSet::command_file); #endif AddCommand(PRM("HELP"), &CommandSet::command_help); AddCommand(PRM("MEM"), &CommandSet::command_mem); #ifdef ARDJACK_NETWORK_AVAILABLE AddCommand(PRM("NET"), &CommandSet::command_net); #endif //AddCommand(PRM("PING"), &CommandSet::command_nyi); //&command_ping); AddCommand(PRM("REACTIVATE"), &CommandSet::command_reactivate); AddCommand(PRM("REPEAT"), &CommandSet::command_repeat); AddCommand(PRM("RESET"), &CommandSet::command_reset); #ifdef ARDJACK_INCLUDE_PERSISTENCE AddCommand(PRM("RESTORE"), &CommandSet::command_restore); AddCommand(PRM("SAVE"), &CommandSet::command_save); #endif AddCommand(PRM("SEND"), &CommandSet::command_send); AddCommand(PRM("SET"), &CommandSet::command_set); AddCommand(PRM("TEST"), &CommandSet::command_test); #ifdef ARDJACK_INCLUDE_TESTS AddCommand(PRM("TESTS"), &CommandSet::command_tests); #endif } CommandSet::~CommandSet() { for (int i = 0; i < ARDJACK_MAX_COMMANDS; i++) { if (NULL != _Commands[i]) { delete _Commands[i]; _Commands[i] = NULL; } } } CommandInfo* CommandSet::AddCommand(const char* name, CommandSetCallback callback) { if (_CommandCount >= ARDJACK_MAX_COMMANDS) { return NULL; } CommandInfo *result = _Commands[_CommandCount]; if (NULL == result) { result = new CommandInfo(); _Commands[_CommandCount] = result; } _CommandCount++; strcpy(result->Name, name); result->Callback = callback; return result; } bool CommandSet::Handle(const char* line, const char* verb, const char* remainder) { if (_CommandCount == 0) { Log::LogWarning(PRM("Command Set has no commands: '"), line, "'"); return false; } // Is this command in '_Commands'? if (strlen(verb) >= ARDJACK_MAX_VERB_LENGTH) return false; char ucVerb[ARDJACK_MAX_VERB_LENGTH]; strcpy(ucVerb, verb); _strupr(ucVerb); bool (CommandSet::*pCallback)(const char* args); for (int i = 0; i < _CommandCount; i++) { CommandInfo* info = _Commands[i]; if (strcmp(ucVerb, info->Name) == 0) { pCallback = info->Callback; if (pCallback == &CommandSet::command_nyi) Log::LogWarning("NOT YET IMPLEMENTED:", ucVerb); else (*this.*pCallback)(remainder); return true; } } return false; } bool CommandSet::command_activate(const char* args) { // Activate zero or more 'IoTObjects'. if (Utils::StringIsNullOrEmpty(args)) { Log::LogWarning(PRM("ACTIVATE command: No arguments")); return true; } return Globals::ActivateObjects(args, true); } bool CommandSet::command_add(const char* args) { // Add an 'IoTObject'. if (Utils::StringIsNullOrEmpty(args)) { Log::LogWarning(PRM("ADD command: No arguments")); return true; } IoTObject* obj = Globals::AddObject(args); if (NULL == obj) return false; return true; } bool CommandSet::command_beep(const char* args) { // beep 1800 200 3 int freqHz = 1000; int durMs = 200; int beepCount = 1; char fields[3][ARDJACK_MAX_VALUE_LENGTH]; int count = Utils::SplitText2Array(args, ' ', fields, 3, ARDJACK_MAX_VALUE_LENGTH); if (count >= 1) freqHz = Utils::String2Int(fields[0], freqHz); if (count >= 2) durMs = Utils::String2Int(fields[1], durMs); if (count >= 3) beepCount = Utils::String2Int(fields[2], beepCount); for (int i = 0; i < beepCount; i++) Utils::DoBeep(freqHz, durMs); return true; } bool CommandSet::command_configure(const char* args) { // Configure an Object (Bridge, Connection, DataLogger or Device), -or- a Device's Part(s). // Syntax: // configure object item1=value1 item2=value2 // configure device.part item1=value1 item2=value2 // E.g. // 'configure ard shield=thinker' // 'configure ard.button0 name=value' // 'configure udp0 inputport=2390' if (Utils::StringIsNullOrEmpty(args)) { Log::LogWarning(PRM("CONFIGURE command: No arguments")); return true; } StringList fields; int count = Utils::SplitText(args, ' ', &fields, ARDJACK_MAX_VALUES, ARDJACK_MAX_VALUE_LENGTH); // TEMPORARY: why? if (count < 2) { Log::LogError(PRM("Configure: Less than 2 fields: "), args); return false; } // Parse the first field - is it in 'obj.partExpr' format? char fields2[2][ARDJACK_MAX_VALUE_LENGTH]; int count2 = Utils::SplitText2Array(fields.Get(0), '.', fields2, 2, ARDJACK_MAX_VALUE_LENGTH); bool dotSyntax = (count2 > 1); char objName[ARDJACK_MAX_NAME_LENGTH]; char partExpr[ARDJACK_MAX_NAME_LENGTH]; if (dotSyntax) { strcpy(objName, fields2[0]); strcpy(partExpr, fields2[1]); } else { strcpy(objName, fields2[0]); partExpr[0] = NULL; } // Check the Object name. IoTObject* obj = Globals::ObjectRegister->LookupName(objName); if (NULL == obj) { Log::LogError(PRM("Configure: Unknown object: '"), objName, "'"); return false; } if (Globals::Verbosity > 6) { char temp[102]; Log::LogInfoF(PRM("Configure: '%s', partExpr '%s'"), obj->ToString(temp), partExpr); } return obj->Configure(partExpr, &fields, 1, count - 1); } bool CommandSet::command_connection(const char* args) { if (Utils::StringIsNullOrEmpty(args)) { Log::LogWarning(PRM("CONNECTION command: No arguments")); return true; } return Globals::ConnectionMgr->Interact(args); } bool CommandSet::command_deactivate(const char* args) { // Deactivate zero or more 'IoTObjects'. if (Utils::StringIsNullOrEmpty(args)) { Log::LogWarning(PRM("DEACTIVATE command: No arguments")); return true; } return Globals::ActivateObjects(args, false); } bool CommandSet::command_define(const char* args) { // Define a Macro. if (Utils::StringIsNullOrEmpty(args)) { Log::LogWarning(PRM("DEFINE command: No arguments")); return true; } char name[ARDJACK_MAX_NAME_LENGTH]; const char* content = NULL; Utils::GetArgs(args, name, &content); if (Utils::StringIsNullOrEmpty(content)) Globals::Interpreter->RemoveMacro(name); else Globals::Interpreter->AddMacro(name, content); return true; } bool CommandSet::command_delay(const char* args) { // Delay for a number of milliseconds. int delay_ms; char fields[2][ARDJACK_MAX_VALUE_LENGTH]; int count = Utils::SplitText2Array(args, ' ', fields, 2, ARDJACK_MAX_VALUE_LENGTH); if (count == 0) return false; delay_ms = Utils::String2Int(fields[0], 1000); Utils::DelayMs(delay_ms); return true; } bool CommandSet::command_delete(const char* args) { // Delete zero or more 'IoTObjects'. if (Utils::StringIsNullOrEmpty(args)) { Log::LogWarning(PRM("DELETE command: No arguments")); return true; } return Globals::DeleteObjects(args); } bool CommandSet::command_device(const char* args) { if (Utils::StringIsNullOrEmpty(args)) { Log::LogWarning(PRM("DEVICE command: No arguments")); return true; } return Globals::DeviceMgr->Interact(args); } bool CommandSet::command_display(const char* args) { return Displayer::DisplayItem(args); } bool CommandSet::command_exit(const char* args) { Globals::UserExit = true; return true; } #ifdef ARDJACK_INCLUDE_PERSISTENCE bool CommandSet::command_file(const char* args) { // file open settings open file 'settings' for writing // file write name1=value1 // file write "name2=value 2" // file close // file open startup open file 'startup' for writing // file write "command1 yy zz" // file write "command2 yy zz" // file close // file clear clears all files // file list list the current files // file scan scan the flash storage (Arduino) / disk folder (Windows) if (Utils::StringIsNullOrEmpty(args)) { Log::LogWarning(PRM("FILE command: No arguments")); return true; } StringList fields; int count = Utils::SplitText(args, ' ', &fields, ARDJACK_MAX_VALUES, ARDJACK_MAX_VALUE_LENGTH); if (count == 0) { Log::LogError(PRM("FILE command: No arguments")); return false; } char action[20]; strcpy(action, fields.Get(0)); _strupr(action); if (Utils::StringEquals(action, "CLEAR", true)) { return Globals::PersistentFileMgr->Clear(); } if (Utils::StringEquals(action, "CLOSE", true)) { if (NULL == _CurrentPersistentFile) { Log::LogError(PRM("FILE CLOSE command: No file open")); return false; } return _CurrentPersistentFile->Close(); } if (Utils::StringEquals(action, "LIST", true)) { return Globals::PersistentFileMgr->List(); } if (Utils::StringEquals(action, "LOADINI", true)) { // Load the specified INI file. if (count < 2) { Log::LogError(PRM("FILE LOAD command: Insufficient arguments in '"), args, "'"); return false; } return Globals::PersistentFileMgr->LoadIniFile(fields.Get(1)); } if (Utils::StringEquals(action, "OPEN", true)) { if (count < 2) { Log::LogError(PRM("FILE OPEN command: Insufficient arguments in '"), args, "'"); return false; } if (NULL != _CurrentPersistentFile) { _CurrentPersistentFile->Close(); _CurrentPersistentFile = NULL; } char name[ARDJACK_MAX_NAME_LENGTH]; strcpy(name, fields.Get(1)); _CurrentPersistentFile = Globals::PersistentFileMgr->Lookup(name, true); if (NULL == _CurrentPersistentFile) { Log::LogError(PRM("FILE OPEN command: No such file: "), name); return false; } return _CurrentPersistentFile->Open("w"); } if (Utils::StringEquals(action, "SCAN", true)) { #ifdef ARDUINO return Globals::PersistentFileMgr->Scan(); #else return Globals::PersistentFileMgr->Scan(Globals::AppDocsFolder); #endif } if (Utils::StringEquals(action, "WRITE", true)) { if (NULL == _CurrentPersistentFile) { Log::LogError(PRM("FILE WRITE command: No file open")); return false; } if (!_CurrentPersistentFile->IsOpen()) { Log::LogError(PRM("FILE WRITE command: File not open: "), _CurrentPersistentFile->Name); return false; } if (count < 2) return _CurrentPersistentFile->Puts(""); else return _CurrentPersistentFile->Puts(fields.Get(1)); } Log::LogError(PRM("FILE command: Invalid option: "), action); return false; } #endif bool CommandSet::command_help(const char* args) { Log::LogInfo(PRM("Available commands:")); for (int i = 0; i < _CommandCount; i++) { CommandInfo* info = _Commands[i]; Log::LogInfo(" ", info->Name); } return true; } bool CommandSet::command_mem(const char* args) { return Displayer::DisplayMemory(); } #ifdef ARDJACK_NETWORK_AVAILABLE bool CommandSet::command_net(const char* args) { if (Utils::StringIsNullOrEmpty(args)) { Log::LogWarning(PRM("NET command: No arguments")); return true; } return Globals::NetworkMgr->Interact(args); } #endif bool CommandSet::command_nyi(const char* args) { // NOT YET IMPLEMENTED. return false; } bool CommandSet::command_reactivate(const char* args) { // Rectivate zero or more 'IoTObjects' (reactivate = deactivate + activate). if (Utils::StringIsNullOrEmpty(args)) { Log::LogWarning(PRM("REACTIVATE command: No arguments")); return true; } return Globals::ReactivateObjects(args); } bool CommandSet::command_repeat(const char* args) { if (Utils::StringIsNullOrEmpty(args)) { Log::LogWarning(PRM("REPEAT command: No arguments")); return true; } char firstPart[ARDJACK_MAX_VERB_LENGTH]; const char* remainder = NULL; Utils::GetArgs(args, firstPart, &remainder); int count = atoi(firstPart); char temp[20]; for (int i = 1; i <= count; i++) { if (Globals::Verbosity > 3) { sprintf(temp, PRM("%d of %d"), i, count); Log::LogInfo(PRM("command_repeat: Cycle "), temp); } Globals::Interpreter->Execute(remainder); } return true; } bool CommandSet::command_reset(const char* args) { Log::LogInfo(PRM("command_reset")); void(*resetFunc) (void) = 0; // declare reset function at address 0 resetFunc(); return true; } #ifdef ARDJACK_INCLUDE_PERSISTENCE bool CommandSet::command_restore(const char* args) { // Reload the configuration file (if any). return Globals::LoadIniFile("configuration"); } bool CommandSet::command_save(const char* args) { // Save some basic items of the current configuration to file "configuration". return Globals::SaveIniFile("configuration"); } #endif bool CommandSet::command_send(const char* args) { // Send text via the specified Connection. // Syntax: // send conn "text" if (Utils::StringIsNullOrEmpty(args)) { Log::LogWarning(PRM("SEND command: No arguments")); return true; } char fields[2][ARDJACK_MAX_VALUE_LENGTH]; int count = Utils::SplitText2Array(args, ' ', fields, 2, ARDJACK_MAX_VALUE_LENGTH); if (count < 2) { Log::LogError(PRM("Insufficient fields for SEND command: '"), args, "'"); return false; } Connection* conn = Globals::ConnectionMgr->LookupConnection(fields[0]); if (NULL == conn) { Log::LogError(PRM("No such Connection: '"), fields[0], "'"); return false; } return conn->SendText(fields[1]); } bool CommandSet::command_set(const char* args) { if (Utils::StringIsNullOrEmpty(args)) { Log::LogWarning(PRM("SET command: No arguments")); return true; } char fields[2][ARDJACK_MAX_VALUE_LENGTH]; bool handled; int count = Utils::SplitText2Array(args, ' ', fields, 2, ARDJACK_MAX_VALUE_LENGTH); return Globals::Set(fields[0], fields[1], &handled); } #ifdef ARDJACK_INCLUDE_TESTS bool CommandSet::command_test(const char* args) { if (Utils::StringIsNullOrEmpty(args)) { Log::LogWarning(PRM("TEST command: No arguments")); return true; } // "test number arg1 arg2 verbosity" char fields[4][ARDJACK_MAX_VALUE_LENGTH]; int count = Utils::SplitText2Array(args, ' ', fields, 4, ARDJACK_MAX_VALUE_LENGTH); int number = 1; int arg1 = 0; int arg2 = 0; int verbosity = 10; if (count >= 1) { number = atoi(fields[0]); if (count >= 2) { arg1 = atoi(fields[1]); if (count >= 3) { arg2 = atoi(fields[2]); if (count >= 4) verbosity = atoi(fields[3]); } } } RunTest(number, arg1, arg2, verbosity); return true; } bool CommandSet::command_tests(const char* args) { // TEMPORARY: RunTests(10); return true; } #else bool CommandSet::command_test(const char* args) { Log::LogInfoF(PRM("Entry")); int save = Globals::Verbosity; Globals::Verbosity = 10; Log::LogInfoF(PRM("--- STRING LISTS ---")); StringList* sl1 = new StringList(); for (int i = 0; i < 3; i++) { StringList* sl2 = new StringList(); delete sl2; StringList* sl3 = new StringList(); delete sl3; } delete sl1; Log::LogInfoF(PRM("--- MESSAGES ---")); IoTMessage* msg = new IoTMessage(); delete msg; Log::LogInfoF(PRM("--- BEACONS ---")); Beacon* beacon = new Beacon("beacon"); delete beacon; Globals::Verbosity = save; Log::LogInfoF(PRM("Exit")); return true; } #endif
21.467801
114
0.698325
e91b95a988d5806fc6591bb8e7c17a03fe79ecec
2,716
cpp
C++
src/Interpreters/InterpreterExternalDDLQuery.cpp
athom/ClickHouse
4f4cc9d7404fd489a7229633b22b5ea1889bd8c0
[ "Apache-2.0" ]
15,577
2019-09-23T11:57:53.000Z
2022-03-31T18:21:48.000Z
src/Interpreters/InterpreterExternalDDLQuery.cpp
athom/ClickHouse
4f4cc9d7404fd489a7229633b22b5ea1889bd8c0
[ "Apache-2.0" ]
16,476
2019-09-23T11:47:00.000Z
2022-03-31T23:06:01.000Z
src/Interpreters/InterpreterExternalDDLQuery.cpp
athom/ClickHouse
4f4cc9d7404fd489a7229633b22b5ea1889bd8c0
[ "Apache-2.0" ]
3,633
2019-09-23T12:18:28.000Z
2022-03-31T15:55:48.000Z
#if !defined(ARCADIA_BUILD) # include "config_core.h" #endif #include <Interpreters/InterpreterExternalDDLQuery.h> #include <Interpreters/Context.h> #include <Parsers/IAST.h> #include <Parsers/ASTDropQuery.h> #include <Parsers/ASTRenameQuery.h> #include <Parsers/ASTIdentifier.h> #include <Parsers/ASTExternalDDLQuery.h> #ifdef USE_MYSQL # include <Interpreters/MySQL/InterpretersMySQLDDLQuery.h> # include <Parsers/MySQL/ASTAlterQuery.h> # include <Parsers/MySQL/ASTCreateQuery.h> #endif namespace DB { namespace ErrorCodes { extern const int SYNTAX_ERROR; extern const int BAD_ARGUMENTS; } InterpreterExternalDDLQuery::InterpreterExternalDDLQuery(const ASTPtr & query_, ContextMutablePtr context_) : WithMutableContext(context_), query(query_) { } BlockIO InterpreterExternalDDLQuery::execute() { const ASTExternalDDLQuery & external_ddl_query = query->as<ASTExternalDDLQuery &>(); if (getContext()->getClientInfo().query_kind != ClientInfo::QueryKind::SECONDARY_QUERY) throw Exception("Cannot parse and execute EXTERNAL DDL FROM.", ErrorCodes::SYNTAX_ERROR); if (external_ddl_query.from->name == "MySQL") { #ifdef USE_MYSQL const ASTs & arguments = external_ddl_query.from->arguments->children; if (arguments.size() != 2 || !arguments[0]->as<ASTIdentifier>() || !arguments[1]->as<ASTIdentifier>()) throw Exception("MySQL External require two identifier arguments.", ErrorCodes::BAD_ARGUMENTS); if (external_ddl_query.external_ddl->as<ASTDropQuery>()) return MySQLInterpreter::InterpreterMySQLDropQuery( external_ddl_query.external_ddl, getContext(), getIdentifierName(arguments[0]), getIdentifierName(arguments[1])).execute(); else if (external_ddl_query.external_ddl->as<ASTRenameQuery>()) return MySQLInterpreter::InterpreterMySQLRenameQuery( external_ddl_query.external_ddl, getContext(), getIdentifierName(arguments[0]), getIdentifierName(arguments[1])).execute(); else if (external_ddl_query.external_ddl->as<MySQLParser::ASTAlterQuery>()) return MySQLInterpreter::InterpreterMySQLAlterQuery( external_ddl_query.external_ddl, getContext(), getIdentifierName(arguments[0]), getIdentifierName(arguments[1])).execute(); else if (external_ddl_query.external_ddl->as<MySQLParser::ASTCreateQuery>()) return MySQLInterpreter::InterpreterMySQLCreateQuery( external_ddl_query.external_ddl, getContext(), getIdentifierName(arguments[0]), getIdentifierName(arguments[1])).execute(); #endif } return BlockIO(); } }
37.722222
110
0.716495
e91bb7ad2417fd19f53f460456ea1f1c77480762
15,625
cc
C++
test/cctest/compiler/test-run-jsops.cc
guillermomolina/v8-sparc
40f43c91a59835819cdd544b25d0ea415a753bbb
[ "BSD-3-Clause" ]
null
null
null
test/cctest/compiler/test-run-jsops.cc
guillermomolina/v8-sparc
40f43c91a59835819cdd544b25d0ea415a753bbb
[ "BSD-3-Clause" ]
null
null
null
test/cctest/compiler/test-run-jsops.cc
guillermomolina/v8-sparc
40f43c91a59835819cdd544b25d0ea415a753bbb
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2014 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // TODO(jochen): Remove this after the setting is turned on globally. #define V8_IMMINENT_DEPRECATION_WARNINGS #include "test/cctest/compiler/function-tester.h" using namespace v8::internal; using namespace v8::internal::compiler; TEST(BinopAdd) { FunctionTester T("(function(a,b) { return a + b; })"); T.CheckCall(3, 1, 2); T.CheckCall(-11, -2, -9); T.CheckCall(-11, -1.5, -9.5); T.CheckCall(T.Val("AB"), T.Val("A"), T.Val("B")); T.CheckCall(T.Val("A11"), T.Val("A"), T.Val(11)); T.CheckCall(T.Val("12B"), T.Val(12), T.Val("B")); T.CheckCall(T.Val("38"), T.Val("3"), T.Val("8")); T.CheckCall(T.Val("31"), T.Val("3"), T.NewObject("([1])")); T.CheckCall(T.Val("3[object Object]"), T.Val("3"), T.NewObject("({})")); } TEST(BinopSubtract) { FunctionTester T("(function(a,b) { return a - b; })"); T.CheckCall(3, 4, 1); T.CheckCall(3.0, 4.5, 1.5); T.CheckCall(T.Val(-9), T.Val("0"), T.Val(9)); T.CheckCall(T.Val(-9), T.Val(0.0), T.Val("9")); T.CheckCall(T.Val(1), T.Val("3"), T.Val("2")); T.CheckCall(T.nan(), T.Val("3"), T.Val("B")); T.CheckCall(T.Val(2), T.Val("3"), T.NewObject("([1])")); T.CheckCall(T.nan(), T.Val("3"), T.NewObject("({})")); } TEST(BinopMultiply) { FunctionTester T("(function(a,b) { return a * b; })"); T.CheckCall(6, 3, 2); T.CheckCall(4.5, 2.0, 2.25); T.CheckCall(T.Val(6), T.Val("3"), T.Val(2)); T.CheckCall(T.Val(4.5), T.Val(2.0), T.Val("2.25")); T.CheckCall(T.Val(6), T.Val("3"), T.Val("2")); T.CheckCall(T.nan(), T.Val("3"), T.Val("B")); T.CheckCall(T.Val(3), T.Val("3"), T.NewObject("([1])")); T.CheckCall(T.nan(), T.Val("3"), T.NewObject("({})")); } TEST(BinopDivide) { FunctionTester T("(function(a,b) { return a / b; })"); T.CheckCall(2, 8, 4); T.CheckCall(2.1, 8.4, 4); T.CheckCall(V8_INFINITY, 8, 0); T.CheckCall(-V8_INFINITY, -8, 0); T.CheckCall(T.infinity(), T.Val(8), T.Val("0")); T.CheckCall(T.minus_infinity(), T.Val("-8"), T.Val(0.0)); T.CheckCall(T.Val(1.5), T.Val("3"), T.Val("2")); T.CheckCall(T.nan(), T.Val("3"), T.Val("B")); T.CheckCall(T.Val(1.5), T.Val("3"), T.NewObject("([2])")); T.CheckCall(T.nan(), T.Val("3"), T.NewObject("({})")); } TEST(BinopModulus) { FunctionTester T("(function(a,b) { return a % b; })"); T.CheckCall(3, 8, 5); T.CheckCall(T.Val(3), T.Val("8"), T.Val(5)); T.CheckCall(T.Val(3), T.Val(8), T.Val("5")); T.CheckCall(T.Val(1), T.Val("3"), T.Val("2")); T.CheckCall(T.nan(), T.Val("3"), T.Val("B")); T.CheckCall(T.Val(1), T.Val("3"), T.NewObject("([2])")); T.CheckCall(T.nan(), T.Val("3"), T.NewObject("({})")); } TEST(BinopShiftLeft) { FunctionTester T("(function(a,b) { return a << b; })"); T.CheckCall(4, 2, 1); T.CheckCall(T.Val(4), T.Val("2"), T.Val(1)); T.CheckCall(T.Val(4), T.Val(2), T.Val("1")); } TEST(BinopShiftRight) { FunctionTester T("(function(a,b) { return a >> b; })"); T.CheckCall(4, 8, 1); T.CheckCall(-4, -8, 1); T.CheckCall(T.Val(4), T.Val("8"), T.Val(1)); T.CheckCall(T.Val(4), T.Val(8), T.Val("1")); } TEST(BinopShiftRightLogical) { FunctionTester T("(function(a,b) { return a >>> b; })"); T.CheckCall(4, 8, 1); T.CheckCall(0x7ffffffc, -8, 1); T.CheckCall(T.Val(4), T.Val("8"), T.Val(1)); T.CheckCall(T.Val(4), T.Val(8), T.Val("1")); } TEST(BinopAnd) { FunctionTester T("(function(a,b) { return a & b; })"); T.CheckCall(7, 7, 15); T.CheckCall(7, 15, 7); T.CheckCall(T.Val(7), T.Val("15"), T.Val(7)); T.CheckCall(T.Val(7), T.Val(15), T.Val("7")); } TEST(BinopOr) { FunctionTester T("(function(a,b) { return a | b; })"); T.CheckCall(6, 4, 2); T.CheckCall(6, 2, 4); T.CheckCall(T.Val(6), T.Val("2"), T.Val(4)); T.CheckCall(T.Val(6), T.Val(2), T.Val("4")); } TEST(BinopXor) { FunctionTester T("(function(a,b) { return a ^ b; })"); T.CheckCall(7, 15, 8); T.CheckCall(7, 8, 15); T.CheckCall(T.Val(7), T.Val("8"), T.Val(15)); T.CheckCall(T.Val(7), T.Val(8), T.Val("15")); } TEST(BinopStrictEqual) { FunctionTester T("(function(a,b) { return a === b; })"); T.CheckTrue(7, 7); T.CheckFalse(7, 8); T.CheckTrue(7.1, 7.1); T.CheckFalse(7.1, 8.1); T.CheckTrue(T.Val("7.1"), T.Val("7.1")); T.CheckFalse(T.Val(7.1), T.Val("7.1")); T.CheckFalse(T.Val(7), T.undefined()); T.CheckFalse(T.undefined(), T.Val(7)); CompileRun("var o = { desc : 'I am a singleton' }"); T.CheckFalse(T.NewObject("([1])"), T.NewObject("([1])")); T.CheckFalse(T.NewObject("({})"), T.NewObject("({})")); T.CheckTrue(T.NewObject("(o)"), T.NewObject("(o)")); } TEST(BinopEqual) { FunctionTester T("(function(a,b) { return a == b; })"); T.CheckTrue(7, 7); T.CheckFalse(7, 8); T.CheckTrue(7.1, 7.1); T.CheckFalse(7.1, 8.1); T.CheckTrue(T.Val("7.1"), T.Val("7.1")); T.CheckTrue(T.Val(7.1), T.Val("7.1")); CompileRun("var o = { desc : 'I am a singleton' }"); T.CheckFalse(T.NewObject("([1])"), T.NewObject("([1])")); T.CheckFalse(T.NewObject("({})"), T.NewObject("({})")); T.CheckTrue(T.NewObject("(o)"), T.NewObject("(o)")); } TEST(BinopNotEqual) { FunctionTester T("(function(a,b) { return a != b; })"); T.CheckFalse(7, 7); T.CheckTrue(7, 8); T.CheckFalse(7.1, 7.1); T.CheckTrue(7.1, 8.1); T.CheckFalse(T.Val("7.1"), T.Val("7.1")); T.CheckFalse(T.Val(7.1), T.Val("7.1")); CompileRun("var o = { desc : 'I am a singleton' }"); T.CheckTrue(T.NewObject("([1])"), T.NewObject("([1])")); T.CheckTrue(T.NewObject("({})"), T.NewObject("({})")); T.CheckFalse(T.NewObject("(o)"), T.NewObject("(o)")); } TEST(BinopLessThan) { FunctionTester T("(function(a,b) { return a < b; })"); T.CheckTrue(7, 8); T.CheckFalse(8, 7); T.CheckTrue(-8.1, -8); T.CheckFalse(-8, -8.1); T.CheckFalse(0.111, 0.111); T.CheckFalse(T.Val("7.1"), T.Val("7.1")); T.CheckFalse(T.Val(7.1), T.Val("6.1")); T.CheckFalse(T.Val(7.1), T.Val("7.1")); T.CheckTrue(T.Val(7.1), T.Val("8.1")); } TEST(BinopLessThanOrEqual) { FunctionTester T("(function(a,b) { return a <= b; })"); T.CheckTrue(7, 8); T.CheckFalse(8, 7); T.CheckTrue(-8.1, -8); T.CheckFalse(-8, -8.1); T.CheckTrue(0.111, 0.111); T.CheckTrue(T.Val("7.1"), T.Val("7.1")); T.CheckFalse(T.Val(7.1), T.Val("6.1")); T.CheckTrue(T.Val(7.1), T.Val("7.1")); T.CheckTrue(T.Val(7.1), T.Val("8.1")); } TEST(BinopGreaterThan) { FunctionTester T("(function(a,b) { return a > b; })"); T.CheckFalse(7, 8); T.CheckTrue(8, 7); T.CheckFalse(-8.1, -8); T.CheckTrue(-8, -8.1); T.CheckFalse(0.111, 0.111); T.CheckFalse(T.Val("7.1"), T.Val("7.1")); T.CheckTrue(T.Val(7.1), T.Val("6.1")); T.CheckFalse(T.Val(7.1), T.Val("7.1")); T.CheckFalse(T.Val(7.1), T.Val("8.1")); } TEST(BinopGreaterThanOrEqual) { FunctionTester T("(function(a,b) { return a >= b; })"); T.CheckFalse(7, 8); T.CheckTrue(8, 7); T.CheckFalse(-8.1, -8); T.CheckTrue(-8, -8.1); T.CheckTrue(0.111, 0.111); T.CheckTrue(T.Val("7.1"), T.Val("7.1")); T.CheckTrue(T.Val(7.1), T.Val("6.1")); T.CheckTrue(T.Val(7.1), T.Val("7.1")); T.CheckFalse(T.Val(7.1), T.Val("8.1")); } TEST(BinopIn) { FunctionTester T("(function(a,b) { return a in b; })"); T.CheckTrue(T.Val("x"), T.NewObject("({x:23})")); T.CheckFalse(T.Val("y"), T.NewObject("({x:42})")); T.CheckFalse(T.Val(123), T.NewObject("({x:65})")); T.CheckTrue(T.Val(1), T.NewObject("([1,2,3])")); } TEST(BinopInstanceOf) { FunctionTester T("(function(a,b) { return a instanceof b; })"); T.CheckTrue(T.NewObject("(new Number(23))"), T.NewObject("Number")); T.CheckFalse(T.NewObject("(new Number(23))"), T.NewObject("String")); T.CheckFalse(T.NewObject("(new String('a'))"), T.NewObject("Number")); T.CheckTrue(T.NewObject("(new String('b'))"), T.NewObject("String")); T.CheckFalse(T.Val(1), T.NewObject("Number")); T.CheckFalse(T.Val("abc"), T.NewObject("String")); CompileRun("var bound = (function() {}).bind(undefined)"); T.CheckTrue(T.NewObject("(new bound())"), T.NewObject("bound")); T.CheckTrue(T.NewObject("(new bound())"), T.NewObject("Object")); T.CheckFalse(T.NewObject("(new bound())"), T.NewObject("Number")); } TEST(UnopNot) { FunctionTester T("(function(a) { return !a; })"); T.CheckCall(T.true_value(), T.false_value(), T.undefined()); T.CheckCall(T.false_value(), T.true_value(), T.undefined()); T.CheckCall(T.true_value(), T.Val(0.0), T.undefined()); T.CheckCall(T.false_value(), T.Val(123), T.undefined()); T.CheckCall(T.false_value(), T.Val("x"), T.undefined()); T.CheckCall(T.true_value(), T.undefined(), T.undefined()); T.CheckCall(T.true_value(), T.nan(), T.undefined()); } TEST(UnopCountPost) { FunctionTester T("(function(a) { return a++; })"); T.CheckCall(T.Val(0.0), T.Val(0.0), T.undefined()); T.CheckCall(T.Val(2.3), T.Val(2.3), T.undefined()); T.CheckCall(T.Val(123), T.Val(123), T.undefined()); T.CheckCall(T.Val(7), T.Val("7"), T.undefined()); T.CheckCall(T.nan(), T.Val("x"), T.undefined()); T.CheckCall(T.nan(), T.undefined(), T.undefined()); T.CheckCall(T.Val(1.0), T.true_value(), T.undefined()); T.CheckCall(T.Val(0.0), T.false_value(), T.undefined()); T.CheckCall(T.nan(), T.nan(), T.undefined()); } TEST(UnopCountPre) { FunctionTester T("(function(a) { return ++a; })"); T.CheckCall(T.Val(1.0), T.Val(0.0), T.undefined()); T.CheckCall(T.Val(3.3), T.Val(2.3), T.undefined()); T.CheckCall(T.Val(124), T.Val(123), T.undefined()); T.CheckCall(T.Val(8), T.Val("7"), T.undefined()); T.CheckCall(T.nan(), T.Val("x"), T.undefined()); T.CheckCall(T.nan(), T.undefined(), T.undefined()); T.CheckCall(T.Val(2.0), T.true_value(), T.undefined()); T.CheckCall(T.Val(1.0), T.false_value(), T.undefined()); T.CheckCall(T.nan(), T.nan(), T.undefined()); } TEST(PropertyNamedLoad) { FunctionTester T("(function(a,b) { return a.x; })"); T.CheckCall(T.Val(23), T.NewObject("({x:23})"), T.undefined()); T.CheckCall(T.undefined(), T.NewObject("({y:23})"), T.undefined()); } TEST(PropertyKeyedLoad) { FunctionTester T("(function(a,b) { return a[b]; })"); T.CheckCall(T.Val(23), T.NewObject("({x:23})"), T.Val("x")); T.CheckCall(T.Val(42), T.NewObject("([23,42,65])"), T.Val(1)); T.CheckCall(T.undefined(), T.NewObject("({x:23})"), T.Val("y")); T.CheckCall(T.undefined(), T.NewObject("([23,42,65])"), T.Val(4)); } TEST(PropertyNamedStore) { FunctionTester T("(function(a) { a.x = 7; return a.x; })"); T.CheckCall(T.Val(7), T.NewObject("({})"), T.undefined()); T.CheckCall(T.Val(7), T.NewObject("({x:23})"), T.undefined()); } TEST(PropertyKeyedStore) { FunctionTester T("(function(a,b) { a[b] = 7; return a.x; })"); T.CheckCall(T.Val(7), T.NewObject("({})"), T.Val("x")); T.CheckCall(T.Val(7), T.NewObject("({x:23})"), T.Val("x")); T.CheckCall(T.Val(9), T.NewObject("({x:9})"), T.Val("y")); } TEST(PropertyNamedDelete) { FunctionTester T("(function(a) { return delete a.x; })"); CompileRun("var o = Object.create({}, { x: { value:23 } });"); T.CheckTrue(T.NewObject("({x:42})"), T.undefined()); T.CheckTrue(T.NewObject("({})"), T.undefined()); T.CheckFalse(T.NewObject("(o)"), T.undefined()); } TEST(PropertyKeyedDelete) { FunctionTester T("(function(a, b) { return delete a[b]; })"); CompileRun("function getX() { return 'x'; }"); CompileRun("var o = Object.create({}, { x: { value:23 } });"); T.CheckTrue(T.NewObject("({x:42})"), T.Val("x")); T.CheckFalse(T.NewObject("(o)"), T.Val("x")); T.CheckFalse(T.NewObject("(o)"), T.NewObject("({toString:getX})")); } TEST(GlobalLoad) { FunctionTester T("(function() { return g; })"); T.CheckThrows(T.undefined(), T.undefined()); CompileRun("var g = 23;"); T.CheckCall(T.Val(23)); } TEST(GlobalStoreSloppy) { FunctionTester T("(function(a,b) { g = a + b; return g; })"); T.CheckCall(T.Val(33), T.Val(22), T.Val(11)); CompileRun("delete g"); CompileRun("const g = 23"); T.CheckCall(T.Val(23), T.Val(55), T.Val(44)); } TEST(GlobalStoreStrict) { FunctionTester T("(function(a,b) { 'use strict'; g = a + b; return g; })"); T.CheckThrows(T.Val(22), T.Val(11)); CompileRun("var g = 'a global variable';"); T.CheckCall(T.Val(33), T.Val(22), T.Val(11)); } TEST(ContextLoad) { FunctionTester T("(function(a,b) { (function(){a}); return a + b; })"); T.CheckCall(T.Val(65), T.Val(23), T.Val(42)); T.CheckCall(T.Val("ab"), T.Val("a"), T.Val("b")); } TEST(ContextStore) { FunctionTester T("(function(a,b) { (function(){x}); var x = a; return x; })"); T.CheckCall(T.Val(23), T.Val(23), T.undefined()); T.CheckCall(T.Val("a"), T.Val("a"), T.undefined()); } TEST(LookupLoad) { FunctionTester T("(function(a,b) { with(a) { return x + b; } })"); T.CheckCall(T.Val(24), T.NewObject("({x:23})"), T.Val(1)); T.CheckCall(T.Val(32), T.NewObject("({x:23, b:9})"), T.Val(2)); T.CheckCall(T.Val(45), T.NewObject("({__proto__:{x:42}})"), T.Val(3)); T.CheckCall(T.Val(69), T.NewObject("({get x() { return 65; }})"), T.Val(4)); } TEST(LookupStore) { FunctionTester T("(function(a,b) { var x; with(a) { x = b; } return x; })"); T.CheckCall(T.undefined(), T.NewObject("({x:23})"), T.Val(1)); T.CheckCall(T.Val(2), T.NewObject("({y:23})"), T.Val(2)); T.CheckCall(T.Val(23), T.NewObject("({b:23})"), T.Val(3)); T.CheckCall(T.undefined(), T.NewObject("({__proto__:{x:42}})"), T.Val(4)); } TEST(BlockLoadStore) { FunctionTester T("(function(a) { 'use strict'; { let x = a+a; return x; }})"); T.CheckCall(T.Val(46), T.Val(23)); T.CheckCall(T.Val("aa"), T.Val("a")); } TEST(BlockLoadStoreNested) { const char* src = "(function(a,b) {" "'use strict';" "{ let x = a, y = a;" " { let y = b;" " return x + y;" " }" "}})"; FunctionTester T(src); T.CheckCall(T.Val(65), T.Val(23), T.Val(42)); T.CheckCall(T.Val("ab"), T.Val("a"), T.Val("b")); } TEST(ObjectLiteralComputed) { FunctionTester T("(function(a,b) { o = { x:a+b }; return o.x; })"); T.CheckCall(T.Val(65), T.Val(23), T.Val(42)); T.CheckCall(T.Val("ab"), T.Val("a"), T.Val("b")); } TEST(ObjectLiteralNonString) { FunctionTester T("(function(a,b) { o = { 7:a+b }; return o[7]; })"); T.CheckCall(T.Val(65), T.Val(23), T.Val(42)); T.CheckCall(T.Val("ab"), T.Val("a"), T.Val("b")); } TEST(ObjectLiteralPrototype) { FunctionTester T("(function(a) { o = { __proto__:a }; return o.x; })"); T.CheckCall(T.Val(23), T.NewObject("({x:23})"), T.undefined()); T.CheckCall(T.undefined(), T.NewObject("({y:42})"), T.undefined()); } TEST(ObjectLiteralGetter) { FunctionTester T("(function(a) { o = { get x() {return a} }; return o.x; })"); T.CheckCall(T.Val(23), T.Val(23), T.undefined()); T.CheckCall(T.Val("x"), T.Val("x"), T.undefined()); } TEST(ArrayLiteral) { FunctionTester T("(function(a,b) { o = [1, a + b, 3]; return o[1]; })"); T.CheckCall(T.Val(65), T.Val(23), T.Val(42)); T.CheckCall(T.Val("ab"), T.Val("a"), T.Val("b")); } TEST(RegExpLiteral) { FunctionTester T("(function(a) { o = /b/; return o.test(a); })"); T.CheckTrue(T.Val("abc")); T.CheckFalse(T.Val("xyz")); } TEST(ClassLiteral) { FLAG_harmony_sloppy = true; const char* src = "(function(a,b) {" " class C {" " x() { return a; }" " static y() { return b; }" " get z() { return 0; }" " constructor() {}" " }" " return new C().x() + C.y();" "})"; FunctionTester T(src); T.CheckCall(T.Val(65), T.Val(23), T.Val(42)); T.CheckCall(T.Val("ab"), T.Val("a"), T.Val("b")); }
28.775322
80
0.574848
e91e00225954bf4ddeab940c29899f540699a0db
7,822
cpp
C++
lib/DxilDia/DxcPixLiveVariables.cpp
seanbaxter/DirectXShaderCompiler
6d02c8d43ff3fdeb9963acaf3af00c62aaa01f44
[ "NCSA" ]
null
null
null
lib/DxilDia/DxcPixLiveVariables.cpp
seanbaxter/DirectXShaderCompiler
6d02c8d43ff3fdeb9963acaf3af00c62aaa01f44
[ "NCSA" ]
null
null
null
lib/DxilDia/DxcPixLiveVariables.cpp
seanbaxter/DirectXShaderCompiler
6d02c8d43ff3fdeb9963acaf3af00c62aaa01f44
[ "NCSA" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// // // // DxcPixLiveVariables.cpp // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // Defines the mapping between instructions and the set of live variables // // for it. // // // /////////////////////////////////////////////////////////////////////////////// #include "dxc/Support/WinIncludes.h" #include "DxcPixDxilDebugInfo.h" #include "DxcPixLiveVariables.h" #include "DxcPixLiveVariables_FragmentIterator.h" #include "DxilDiaSession.h" #include "dxc/Support/Global.h" #include "llvm37/ADT/SmallVector.h" #include "llvm37/IR/DebugInfo.h" #include "llvm37/IR/DebugInfoMetadata.h" #include "llvm37/IR/Dominators.h" #include "llvm37/IR/Instructions.h" #include "llvm37/IR/Intrinsics.h" #include "llvm37/IR/IntrinsicInst.h" #include "llvm37/IR/Module.h" #include <unordered_map> // ValidateDbgDeclare ensures that all of the bits in // [FragmentSizeInBits, FragmentOffsetInBits) are currently // not assigned to a dxil alloca register -- i.e., it // tries to find overlapping alloca registers -- which should // never happen -- to report the issue. void ValidateDbgDeclare( dxil_debug_info::VariableInfo *VarInfo, unsigned FragmentSizeInBits, unsigned FragmentOffsetInBits ) { #ifndef NDEBUG for (unsigned i = 0; i < FragmentSizeInBits; ++i) { const unsigned BitNum = FragmentOffsetInBits + i; VarInfo->m_DbgDeclareValidation.resize( std::max<unsigned>(VarInfo->m_DbgDeclareValidation.size(), BitNum + 1)); assert(!VarInfo->m_DbgDeclareValidation[BitNum]); VarInfo->m_DbgDeclareValidation[BitNum] = true; } #endif // !NDEBUG } struct dxil_debug_info::LiveVariables::Impl { using VariableInfoMap = std::unordered_map< llvm37::DIVariable *, std::unique_ptr<VariableInfo>>; using LiveVarsMap = std::unordered_map<llvm37::DIScope*, VariableInfoMap>; IMalloc *m_pMalloc; DxcPixDxilDebugInfo *m_pDxilDebugInfo; llvm37::Module *m_pModule; LiveVarsMap m_LiveVarsDbgDeclare; void Init( IMalloc *pMalloc, DxcPixDxilDebugInfo *pDxilDebugInfo, llvm37::Module *pModule); void Init_DbgDeclare(llvm37::DbgDeclareInst *DbgDeclare); VariableInfo *AssignValueToOffset( VariableInfoMap *VarInfoMap, llvm37::DIVariable *Var, llvm37::Value *Address, unsigned FragmentIndex, unsigned FragmentOffsetInBits); }; void dxil_debug_info::LiveVariables::Impl::Init( IMalloc *pMalloc, DxcPixDxilDebugInfo *pDxilDebugInfo, llvm37::Module *pModule) { m_pMalloc = pMalloc; m_pDxilDebugInfo = pDxilDebugInfo; m_pModule = pModule; llvm37::Function* DbgDeclareFn = llvm37::Intrinsic::getDeclaration( m_pModule, llvm37::Intrinsic::dbg_declare); for (llvm37::User* U : DbgDeclareFn->users()) { if (auto* DbgDeclare = llvm37::dyn_cast<llvm37::DbgDeclareInst>(U)) { Init_DbgDeclare(DbgDeclare); } } } void dxil_debug_info::LiveVariables::Impl::Init_DbgDeclare( llvm37::DbgDeclareInst *DbgDeclare ) { llvm37::Value *Address = DbgDeclare->getAddress(); auto *Variable = DbgDeclare->getVariable(); auto *Expression = DbgDeclare->getExpression(); if (Address == nullptr || Variable == nullptr || Expression == nullptr) { return; } auto* AddressAsAlloca = llvm37::dyn_cast<llvm37::AllocaInst>(Address); if (AddressAsAlloca == nullptr) { return; } auto *S = Variable->getScope(); if (S == nullptr) { return; } auto Iter = CreateMemberIterator( DbgDeclare, m_pModule->getDataLayout(), AddressAsAlloca, Expression); if (!Iter) { // MemberIterator creation failure, this skip this var. return; } unsigned FragmentIndex; while (Iter->Next(&FragmentIndex)) { const unsigned FragmentSizeInBits = Iter->SizeInBits(FragmentIndex); const unsigned FragmentOffsetInBits = Iter->OffsetInBits(FragmentIndex); VariableInfo* VarInfo = AssignValueToOffset( &m_LiveVarsDbgDeclare[S], Variable, Address, FragmentIndex, FragmentOffsetInBits); // SROA can split structs so that multiple allocas back the same variable. // In this case the expression will be empty if (Expression->getNumElements() != 0) { ValidateDbgDeclare( VarInfo, FragmentSizeInBits, FragmentOffsetInBits); } } } dxil_debug_info::VariableInfo* dxil_debug_info::LiveVariables::Impl::AssignValueToOffset( VariableInfoMap *VarInfoMap, llvm37::DIVariable *Variable, llvm37::Value *Address, unsigned FragmentIndex, unsigned FragmentOffsetInBits ) { // FragmentIndex is the index within the alloca'd value // FragmentOffsetInBits is the offset within the HLSL variable // that maps to Address[FragmentIndex] auto it = VarInfoMap->find(Variable); if (it == VarInfoMap->end()) { auto InsertIt = VarInfoMap->emplace( Variable, std::make_unique<VariableInfo>(Variable)); assert(InsertIt.second); it = InsertIt.first; } auto *VarInfo = it->second.get(); auto &FragmentLocation = VarInfo->m_ValueLocationMap[FragmentOffsetInBits]; FragmentLocation.m_V = Address; FragmentLocation.m_FragmentIndex = FragmentIndex; return VarInfo; } dxil_debug_info::LiveVariables::LiveVariables() = default; dxil_debug_info::LiveVariables::~LiveVariables() = default; HRESULT dxil_debug_info::LiveVariables::Init(DxcPixDxilDebugInfo *pDxilDebugInfo) { Clear(); m_pImpl->Init(pDxilDebugInfo->GetMallocNoRef(), pDxilDebugInfo, pDxilDebugInfo->GetModuleRef()); return S_OK; } void dxil_debug_info::LiveVariables::Clear() { m_pImpl.reset(new dxil_debug_info::LiveVariables::Impl()); } HRESULT dxil_debug_info::LiveVariables::GetLiveVariablesAtInstruction( llvm37::Instruction *IP, IDxcPixDxilLiveVariables **ppResult) const { DXASSERT(IP != nullptr, "else IP should not be nullptr"); DXASSERT(ppResult != nullptr, "else Result should not be nullptr"); std::vector<const VariableInfo *> LiveVars; std::set<std::string> LiveVarsName; const llvm37::DebugLoc &DL = IP->getDebugLoc(); if (!DL) { return E_FAIL; } llvm37::DIScope *S = DL->getScope(); if (S == nullptr) { return E_FAIL; } const llvm37::DITypeIdentifierMap EmptyMap; while (S != nullptr) { auto it = m_pImpl->m_LiveVarsDbgDeclare.find(S); if (it != m_pImpl->m_LiveVarsDbgDeclare.end()) { for (const auto &VarAndInfo : it->second) { auto *Var = VarAndInfo.first; llvm37::StringRef VarName = Var->getName(); if (Var->getLine() > DL.getLine()) { // Defined later in the HLSL source. continue; } if (VarName.empty()) { // No name?... continue; } if (!LiveVarsName.insert(VarName).second) { // There's a variable with the same name; use the // previous one instead. continue; } LiveVars.emplace_back(VarAndInfo.second.get()); } } S = S->getScope().resolve(EmptyMap); } return CreateDxilLiveVariables( m_pImpl->m_pDxilDebugInfo, std::move(LiveVars), ppResult); }
28.34058
98
0.634748
e91eca6dca5931a7a428435ee48946a8912f5bc1
8,039
cpp
C++
src/IECore/ClientDisplayDriver.cpp
gcodebackups/cortex-vfx
72fa6c6eb3327fce4faf01361c8fcc2e1e892672
[ "BSD-3-Clause" ]
5
2016-07-26T06:09:28.000Z
2022-03-07T03:58:51.000Z
src/IECore/ClientDisplayDriver.cpp
turbosun/cortex
4bdc01a692652cd562f3bfa85f3dae99d07c0b15
[ "BSD-3-Clause" ]
null
null
null
src/IECore/ClientDisplayDriver.cpp
turbosun/cortex
4bdc01a692652cd562f3bfa85f3dae99d07c0b15
[ "BSD-3-Clause" ]
3
2015-03-25T18:45:24.000Z
2020-02-15T15:37:18.000Z
////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2007-2013, Image Engine Design Inc. All rights reserved. // Copyright (c) 2012, John Haddon. 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 Image Engine Design nor the names of any // other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "boost/asio.hpp" #include "boost/bind.hpp" #include "IECore/ClientDisplayDriver.h" #include "IECore/private/DisplayDriverServerHeader.h" #include "IECore/SimpleTypedData.h" #include "IECore/MemoryIndexedIO.h" using namespace boost; using namespace std; using namespace Imath; using namespace IECore; using boost::asio::ip::tcp; struct ClientDisplayDriver::PrivateData : public RefCounted { public : PrivateData() : m_service(), m_host(""), m_port(""), m_scanLineOrderOnly(false), m_acceptsRepeatedData(false), m_socket( m_service ) { } ~PrivateData() { m_socket.close(); } boost::asio::io_service m_service; std::string m_host; std::string m_port; bool m_scanLineOrderOnly; bool m_acceptsRepeatedData; boost::asio::ip::tcp::socket m_socket; }; IE_CORE_DEFINERUNTIMETYPED( ClientDisplayDriver ); const DisplayDriver::DisplayDriverDescription<ClientDisplayDriver> ClientDisplayDriver::g_description; ClientDisplayDriver::ClientDisplayDriver( const Imath::Box2i &displayWindow, const Imath::Box2i &dataWindow, const std::vector<std::string> &channelNames, IECore::ConstCompoundDataPtr parameters ) : DisplayDriver( displayWindow, dataWindow, channelNames, parameters ), m_data( new PrivateData() ) { // expects three custom StringData parameters : displayHost, displayPort and displayType const StringData *displayHostData = parameters->member<StringData>( "displayHost", true /* throw if missing */ ); const StringData *displayPortData = parameters->member<StringData>( "displayPort", true /* throw if missing */ ); m_data->m_host = displayHostData->readable(); m_data->m_port = displayPortData->readable(); tcp::resolver resolver(m_data->m_service); tcp::resolver::query query(m_data->m_host, m_data->m_port); boost::system::error_code error; tcp::resolver::iterator iterator = resolver.resolve( query, error ); if( !error ) { error = boost::asio::error::host_not_found; while( error && iterator != tcp::resolver::iterator() ) { m_data->m_socket.close(); m_data->m_socket.connect( *iterator++, error ); } } if( error ) { throw Exception( std::string( "Could not connect to remote display driver server : " ) + error.message() ); } MemoryIndexedIOPtr io; ConstCharVectorDataPtr buf; Box2iDataPtr displayWindowData = new Box2iData( displayWindow ); Box2iDataPtr dataWindowData = new Box2iData( dataWindow ); StringVectorDataPtr channelNamesData = new StringVectorData( channelNames ); IECore::CompoundDataPtr tmpParameters = parameters->copy(); tmpParameters->writable()[ "clientPID" ] = new IntData( getpid() ); // build the data block io = new MemoryIndexedIO( ConstCharVectorDataPtr(), IndexedIO::rootPath, IndexedIO::Exclusive | IndexedIO::Write ); displayWindowData->Object::save( io, "displayWindow" ); dataWindowData->Object::save( io, "dataWindow" ); channelNamesData->Object::save( io, "channelNames" ); tmpParameters->Object::save( io, "parameters" ); buf = io->buffer(); size_t dataSize = buf->readable().size(); sendHeader( DisplayDriverServerHeader::imageOpen, dataSize ); m_data->m_socket.send( boost::asio::buffer( &(buf->readable()[0]), dataSize ) ); if ( receiveHeader( DisplayDriverServerHeader::imageOpen ) != sizeof(m_data->m_scanLineOrderOnly) ) { throw Exception( "Invalid returned scanLineOrder from display driver server!" ); } m_data->m_socket.receive( boost::asio::buffer( &m_data->m_scanLineOrderOnly, sizeof(m_data->m_scanLineOrderOnly) ) ); if ( receiveHeader( DisplayDriverServerHeader::imageOpen ) != sizeof(m_data->m_acceptsRepeatedData) ) { throw Exception( "Invalid returned acceptsRepeatedData from display driver server!" ); } m_data->m_socket.receive( boost::asio::buffer( &m_data->m_acceptsRepeatedData, sizeof(m_data->m_acceptsRepeatedData) ) ); } ClientDisplayDriver::~ClientDisplayDriver() { } std::string ClientDisplayDriver::host() const { return m_data->m_host; } std::string ClientDisplayDriver::port() const { return m_data->m_port; } bool ClientDisplayDriver::scanLineOrderOnly() const { return m_data->m_scanLineOrderOnly; } bool ClientDisplayDriver::acceptsRepeatedData() const { return m_data->m_acceptsRepeatedData; } void ClientDisplayDriver::sendHeader( int msg, size_t dataSize ) { DisplayDriverServerHeader header( (DisplayDriverServerHeader::MessageType)msg, dataSize ); m_data->m_socket.send( boost::asio::buffer( header.buffer(), header.headerLength ) ); } size_t ClientDisplayDriver::receiveHeader( int msg ) { DisplayDriverServerHeader header; m_data->m_socket.receive( boost::asio::buffer( header.buffer(), header.headerLength ) ); if ( !header.valid() ) { throw Exception( "Invalid display driver header block on socket package." ); } size_t bytesAhead = header.getDataSize(); if ( header.messageType() == DisplayDriverServerHeader::exception ) { vector<char> txt; txt.resize( bytesAhead ); m_data->m_socket.receive( boost::asio::buffer( &(txt[0]), bytesAhead ) ); throw Exception( std::string("Error on remote display driver: ") + &(txt[0]) ); } if ( header.messageType() != msg ) { throw Exception( "Unexpected message type on display driver socket package." ); } return bytesAhead; } void ClientDisplayDriver::imageData( const Box2i &box, const float *data, size_t dataSize ) { MemoryIndexedIOPtr io; ConstCharVectorDataPtr buf; // build the data block Box2iDataPtr boxData = new Box2iData( box ); FloatVectorDataPtr dataData = new FloatVectorData( std::vector<float>( data, data+dataSize ) ); io = new MemoryIndexedIO( ConstCharVectorDataPtr(), IndexedIO::rootPath, IndexedIO::Exclusive | IndexedIO::Write ); staticPointerCast<Object>(boxData)->save( io, "box" ); staticPointerCast<Object>(dataData)->save( io, "data" ); buf = io->buffer(); size_t blockSize = buf->readable().size(); sendHeader( DisplayDriverServerHeader::imageData, blockSize ); m_data->m_socket.send( boost::asio::buffer( &(buf->readable()[0]), blockSize) ); } void ClientDisplayDriver::imageClose() { sendHeader( DisplayDriverServerHeader::imageClose, 0 ); receiveHeader( DisplayDriverServerHeader::imageClose ); m_data->m_socket.close(); }
36.211712
198
0.729942
11e6c30dcde0cc94e1bced45e45c43acbf92c259
2,471
cpp
C++
proxygen/lib/http/codec/compress/HPACKCodec.cpp
zhuzy-xys/fb_proxygen
1727d7bb6d9c161a4c2f01d80da6e70e29c7c29b
[ "BSD-3-Clause" ]
null
null
null
proxygen/lib/http/codec/compress/HPACKCodec.cpp
zhuzy-xys/fb_proxygen
1727d7bb6d9c161a4c2f01d80da6e70e29c7c29b
[ "BSD-3-Clause" ]
null
null
null
proxygen/lib/http/codec/compress/HPACKCodec.cpp
zhuzy-xys/fb_proxygen
1727d7bb6d9c161a4c2f01d80da6e70e29c7c29b
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include <proxygen/lib/http/codec/compress/HPACKCodec.h> #include <algorithm> #include <folly/String.h> #include <folly/io/Cursor.h> #include <proxygen/lib/http/codec/compress/HPACKHeader.h> #include <iosfwd> using folly::IOBuf; using folly::io::Cursor; using proxygen::compress::Header; using proxygen::compress::HeaderPiece; using proxygen::compress::HeaderPieceList; using std::unique_ptr; using std::vector; namespace proxygen { namespace compress { std::pair<vector<HPACKHeader>, uint32_t> prepareHeaders( vector<Header>& headers) { // convert to HPACK API format std::pair<vector<HPACKHeader>, uint32_t> converted; converted.first.reserve(headers.size()); uint32_t uncompressed = 0; for (const auto& h : headers) { // HPACKHeader automatically lowercases converted.first.emplace_back(*h.name, *h.value); auto& header = converted.first.back(); converted.second += header.name.size() + header.value.size() + 2; } return converted; } } HPACKCodec::HPACKCodec(TransportDirection /*direction*/) : encoder_(true, HPACK::kTableSize), decoder_(HPACK::kTableSize, maxUncompressed_) {} unique_ptr<IOBuf> HPACKCodec::encode(vector<Header>& headers) noexcept { auto prepared = compress::prepareHeaders(headers); encodedSize_.uncompressed = prepared.second; auto buf = encoder_.encode(prepared.first, encodeHeadroom_); recordCompressedSize(buf.get()); return buf; } void HPACKCodec::recordCompressedSize( const IOBuf* stream) { encodedSize_.compressed = 0; if (stream) { encodedSize_.compressed += stream->computeChainDataLength(); } if (stats_) { stats_->recordEncode(Type::HPACK, encodedSize_); } } void HPACKCodec::decodeStreaming( Cursor& cursor, uint32_t length, HPACK::StreamingCallback* streamingCb) noexcept { streamingCb->stats = stats_; decoder_.decodeStreaming(cursor, length, streamingCb); } void HPACKCodec::describe(std::ostream& stream) const { stream << "DecoderTable:\n" << decoder_; stream << "EncoderTable:\n" << encoder_; } std::ostream& operator<<(std::ostream& os, const HPACKCodec& codec) { codec.describe(os); return os; } }
28.402299
79
0.723998
11e8215b2b9ab33162d6c0be79765fb86481e4c3
5,260
cpp
C++
examples/freverb.cpp
vlazzarini/aurora
4990d81a6873beace4a39d6584cc77afbda82cf4
[ "BSD-3-Clause" ]
11
2021-11-26T16:23:40.000Z
2022-01-19T21:36:35.000Z
examples/freverb.cpp
vlazzarini/aurora
4990d81a6873beace4a39d6584cc77afbda82cf4
[ "BSD-3-Clause" ]
null
null
null
examples/freverb.cpp
vlazzarini/aurora
4990d81a6873beace4a39d6584cc77afbda82cf4
[ "BSD-3-Clause" ]
null
null
null
// freverb.cpp: // reverb processing example // depends on libsndfile // // (c) V Lazzarini, 2021 // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // 3. Neither the name of the copyright holder 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 #include "Del.h" #include <array> #include <cmath> #include <cstdlib> #include <iostream> #include <sndfile.h> #include <vector> using namespace Aurora; template <typename S> inline S scl(S a, S b) { return a * b; } template <typename S> struct Reverb { static constexpr S dt[4] = {0.037, 0.031, 0.029, 0.023}; static constexpr S adt[2] = {0.01, 0.0017}; std::array<Del<S, lp_delay>, 4> combs; std::array<Del<S>, 2> apfs; Mix<S> mix; BinOp<S, scl> gain; std::array<std::vector<S>, 4> mem; std::array<S, 4> g; S rvt; void reverb_time(S rvt) { std::size_t n = 0; for (auto &gs : g) gs = std::pow(.001, dt[n++] / rvt); } void lp_freq(S lpf, S fs) { for (auto &m : mem) { m[0] = 0; double c = 2. - std::cos(2 * M_PI * lpf / fs); m[1] = sqrt(c * c - 1.f) - c; } } void reset(S rvt, S lpf, S fs) { std::size_t n = 0; for (auto &obj : combs) obj.reset(dt[n++], fs); apfs[0].reset(adt[0], fs); apfs[1].reset(adt[1], fs); reverb_time(rvt); lp_freq(lpf, fs); } Reverb(S rvt, S lpf, S fs = def_sr, std::size_t vsize = def_vsize) : combs({Del<S, lp_delay>(dt[0], fs, vsize), Del<S, lp_delay>(dt[1], fs, vsize), Del<S, lp_delay>(dt[2], fs, vsize), Del<S, lp_delay>(dt[3], fs, vsize)}), apfs({Del<S>(adt[0], fs, vsize), Del<S>(adt[1], fs, vsize)}), mix(vsize), gain(vsize), mem({std::vector<S>(2), std::vector<S>(2), std::vector<S>(2), std::vector<S>(2)}), g({0, 0, 0, 0}) { reverb_time(rvt); lp_freq(lpf, fs); }; const std::vector<S> &operator()(const std::vector<S> &in, S rmx) { S ga0 = 0.7; S ga1 = 0.7; auto &s = gain(0.25, mix(combs[0](in, 0, g[0], 0, &mem[0]), combs[1](in, 0, g[1], 0, &mem[1]), combs[2](in, 0, g[2], 0, &mem[2]), combs[3](in, 0, g[3], 0, &mem[3]))); return mix(in, gain(rmx, apfs[1](apfs[0](s, 0, ga0, -ga0), 0, ga1, -ga1))); } }; int main(int argc, const char **argv) { SF_INFO sfinfo; SNDFILE *fpin, *fpout; int n; if (argc > 5) { if ((fpin = sf_open(argv[1], SFM_READ, &sfinfo)) != NULL) { if (sfinfo.channels < 2) { fpout = sf_open(argv[2], SFM_WRITE, &sfinfo); float rvt = atof(argv[3]); float rmx = atof(argv[4]); float cf = atof(argv[5]); std::vector<float> buffer(def_vsize); Reverb<float> reverb(rvt, cf, sfinfo.samplerate); do { std::fill(buffer.begin(), buffer.end(), 0); n = sf_read_float(fpin, buffer.data(), def_vsize); if (n) { buffer.resize(n); auto &out = reverb(buffer, rmx); sf_write_float(fpout, out.data(), n); } else break; } while (1); std::cout << buffer.size() << std::endl; buffer.resize(def_vsize); std::cout << buffer.size() << std::endl; n = sfinfo.samplerate * rvt; std::fill(buffer.begin(), buffer.end(), 0); do { auto &out = reverb(buffer, rmx); sf_write_float(fpout, out.data(), def_vsize); n -= def_vsize; } while (n > 0); sf_close(fpin); sf_close(fpout); return 0; } else std::cout << "only mono soundfiles permitted\n"; sf_close(fpin); return 1; } else std::cout << "could not open " << argv[1] << std::endl; return 1; } std::cout << "usage: " << argv[0] << " infile outfile reverb_time reverb_amount lpf \n" << std::endl; return -1; }
35.066667
80
0.585551
11e891310680f0eb1585c118d56651afab914aaa
11,927
cc
C++
modules/perception/obstacle/fusion/probabilistic_fusion/pbf_kalman_motion_fusion.cc
berthu/apollo
5da49a293e3ad60856448fd61bf6548714cde854
[ "Apache-2.0" ]
22
2018-10-10T14:46:32.000Z
2022-02-28T12:43:43.000Z
modules/perception/obstacle/fusion/probabilistic_fusion/pbf_kalman_motion_fusion.cc
berthu/apollo
5da49a293e3ad60856448fd61bf6548714cde854
[ "Apache-2.0" ]
1
2021-03-09T16:46:45.000Z
2021-03-09T16:46:45.000Z
modules/perception/obstacle/fusion/probabilistic_fusion/pbf_kalman_motion_fusion.cc
berthu/apollo
5da49a293e3ad60856448fd61bf6548714cde854
[ "Apache-2.0" ]
12
2018-12-24T02:17:19.000Z
2021-12-06T01:54:09.000Z
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/perception/obstacle/fusion/probabilistic_fusion/pbf_kalman_motion_fusion.h" #include "modules/common/log.h" #include "modules/perception/common/geometry_util.h" #include "modules/perception/common/perception_gflags.h" #include "modules/perception/obstacle/base/types.h" namespace apollo { namespace perception { PbfKalmanMotionFusion::PbfKalmanMotionFusion() { initialized_ = false; name_ = "PbfKalmanMotionFusion"; } PbfKalmanMotionFusion::~PbfKalmanMotionFusion() {} void PbfKalmanMotionFusion::Initialize(const Eigen::Vector3d &anchor_point, const Eigen::Vector3d &velocity) { belief_anchor_point_ = anchor_point; belief_velocity_ = velocity; belief_acceleration_ = Eigen::Vector3d(0, 0, 0); } void PbfKalmanMotionFusion::Initialize( const std::shared_ptr<PbfSensorObject> new_object) { ACHECK(new_object != nullptr && new_object->object != nullptr) << "Initialize PbfKalmanMotionFusion with null sensor object"; if (is_lidar(new_object->sensor_type)) { belief_anchor_point_ = new_object->object->anchor_point; belief_velocity_ = new_object->object->velocity; belief_acceleration_ = Eigen::Vector3d(0, 0, 0); initialized_ = true; } else if (is_radar(new_object->sensor_type)) { belief_anchor_point_ = new_object->object->anchor_point; belief_velocity_ = new_object->object->velocity; belief_acceleration_ = Eigen::Vector3d(0, 0, 0); initialized_ = true; } else if (is_camera(new_object->sensor_type)) { belief_anchor_point_ = new_object->object->anchor_point; belief_velocity_ = new_object->object->velocity; belief_acceleration_ = Eigen::Vector3d(0, 0, 0); initialized_ = true; } a_matrix_.setIdentity(); a_matrix_(0, 2) = FLAGS_a_matrix_covariance_coeffcient_1; a_matrix_(1, 3) = FLAGS_a_matrix_covariance_coeffcient_2; // initialize states to the states of the detected obstacle posteriori_state_(0) = belief_anchor_point_(0); posteriori_state_(1) = belief_anchor_point_(1); posteriori_state_(2) = belief_velocity_(0); posteriori_state_(3) = belief_velocity_(1); priori_state_ = posteriori_state_; q_matrix_.setIdentity(); q_matrix_ *= FLAGS_q_matrix_coefficient_amplifier; r_matrix_.setIdentity(); r_matrix_.topLeftCorner(2, 2) = FLAGS_r_matrix_amplifier * new_object->object->position_uncertainty.topLeftCorner(2, 2); r_matrix_.block<2, 2>(2, 2) = FLAGS_r_matrix_amplifier * new_object->object->velocity_uncertainty.topLeftCorner(2, 2); p_matrix_.setIdentity(); p_matrix_.topLeftCorner(2, 2) = FLAGS_p_matrix_amplifier * new_object->object->position_uncertainty.topLeftCorner(2, 2); p_matrix_.block<2, 2>(2, 2) = FLAGS_p_matrix_amplifier * new_object->object->velocity_uncertainty.topLeftCorner(2, 2); c_matrix_.setIdentity(); } void PbfKalmanMotionFusion::Predict(Eigen::Vector3d *anchor_point, Eigen::Vector3d *velocity, const double time_diff) { *anchor_point = belief_anchor_point_ + belief_velocity_ * time_diff; *velocity = belief_velocity_; } void PbfKalmanMotionFusion::UpdateWithObject( const std::shared_ptr<PbfSensorObject> new_object, const double time_diff) { ACHECK(new_object != nullptr && new_object->object != nullptr) << "update PbfKalmanMotionFusion with null sensor object"; // predict and then correct a_matrix_.setIdentity(); a_matrix_(0, 2) = time_diff; a_matrix_(1, 3) = time_diff; priori_state_ = a_matrix_ * posteriori_state_; priori_state_(2) += belief_acceleration_(0) * time_diff; priori_state_(3) += belief_acceleration_(1) * time_diff; p_matrix_ = ((a_matrix_ * p_matrix_) * a_matrix_.transpose()) + q_matrix_; p_matrix_.block<2, 2>(2, 0) = Eigen::Matrix2d::Zero(); p_matrix_.block<2, 2>(0, 2) = Eigen::Matrix2d::Zero(); Eigen::Vector3d measured_acceleration = Eigen::Vector3d::Zero(); if (new_object->sensor_type == SensorType::VELODYNE_64) { belief_anchor_point_ = new_object->object->center; belief_velocity_ = new_object->object->velocity; if (GetLidarHistoryLength() >= 3) { int old_velocity_index = GetLidarHistoryIndex(3); Eigen::Vector3d old_velocity = history_velocity_[old_velocity_index]; double old_timediff = GetHistoryTimediff(old_velocity_index, new_object->timestamp); measured_acceleration = (belief_velocity_ - old_velocity) / old_timediff; } if ((GetLidarHistoryLength() >= 3 && GetRadarHistoryLength() >= 3) || history_velocity_.size() > 20) { history_velocity_.pop_front(); history_time_diff_.pop_front(); history_velocity_is_radar_.pop_front(); } history_velocity_.push_back(belief_velocity_); history_time_diff_.push_back(new_object->timestamp); history_velocity_is_radar_.push_back(false); } else if (new_object->sensor_type == SensorType::RADAR) { belief_anchor_point_(0) = new_object->object->center(0); belief_anchor_point_(1) = new_object->object->center(1); belief_velocity_(0) = new_object->object->velocity(0); belief_velocity_(1) = new_object->object->velocity(1); if (GetRadarHistoryLength() >= 3) { int old_velocity_index = GetRadarHistoryIndex(3); Eigen::Vector3d old_velocity = history_velocity_[old_velocity_index]; double old_timediff = GetHistoryTimediff(old_velocity_index, new_object->timestamp); measured_acceleration = (belief_velocity_ - old_velocity) / old_timediff; } if ((GetLidarHistoryLength() >= 3 && GetRadarHistoryLength() >= 3) || history_velocity_.size() > 20) { history_velocity_.pop_front(); history_time_diff_.pop_front(); history_velocity_is_radar_.pop_front(); } history_velocity_.push_back(belief_velocity_); history_time_diff_.push_back(new_object->timestamp); history_velocity_is_radar_.push_back(true); } else if (new_object->sensor_type == SensorType::CAMERA) { belief_anchor_point_(0) = new_object->object->center(0); belief_anchor_point_(1) = new_object->object->center(1); belief_velocity_(0) = new_object->object->velocity(0); belief_velocity_(1) = new_object->object->velocity(1); history_velocity_.push_back(belief_velocity_); history_time_diff_.push_back(new_object->timestamp); history_velocity_is_radar_.push_back(false); } else { AERROR << "unsupported sensor type for PbfKalmanMotionFusion: " << static_cast<int>(new_object->sensor_type); return; } Eigen::Vector4d measurement; measurement(0) = belief_anchor_point_(0); measurement(1) = belief_anchor_point_(1); measurement(2) = belief_velocity_(0); measurement(3) = belief_velocity_(1); // r_matrix_ = new_object.uncertainty_mat; r_matrix_.setIdentity(); r_matrix_.topLeftCorner(2, 2) = new_object->object->position_uncertainty.topLeftCorner(2, 2); r_matrix_.block<2, 2>(2, 2) = new_object->object->velocity_uncertainty.topLeftCorner(2, 2); // Use lidar when there is no radar yet if (GetRadarHistoryLength() == 0 && GetLidarHistoryLength() > 1) { r_matrix_.setIdentity(); r_matrix_ *= 0.01; } k_matrix_ = p_matrix_ * c_matrix_.transpose() * (c_matrix_ * p_matrix_ * c_matrix_.transpose() + r_matrix_).inverse(); Eigen::Vector4d predict_measurement(priori_state_(0), priori_state_(1), priori_state_(2), priori_state_(3)); posteriori_state_ = priori_state_ + k_matrix_ * (measurement - predict_measurement); p_matrix_ = (Eigen::Matrix4d::Identity() - k_matrix_ * c_matrix_) * p_matrix_ * (Eigen::Matrix4d::Identity() - k_matrix_ * c_matrix_).transpose() + k_matrix_ * r_matrix_ * k_matrix_.transpose(); belief_anchor_point_(0) = posteriori_state_(0); belief_anchor_point_(1) = posteriori_state_(1); belief_velocity_(0) = posteriori_state_(2); belief_velocity_(1) = posteriori_state_(3); UpdateAcceleration(measured_acceleration); if (belief_velocity_.head(2).norm() < 0.05) { belief_velocity_ = Eigen::Vector3d(0, 0, 0); } } void PbfKalmanMotionFusion::UpdateWithoutObject(const double time_diff) { belief_anchor_point_ = belief_anchor_point_ + belief_velocity_ * time_diff; } void PbfKalmanMotionFusion::GetState(Eigen::Vector3d *anchor_point, Eigen::Vector3d *velocity) { *anchor_point = belief_anchor_point_; *velocity = belief_velocity_; } void PbfKalmanMotionFusion::SetState(const Eigen::Vector3d &anchor_point, const Eigen::Vector3d &velocity) { belief_anchor_point_ = anchor_point; belief_velocity_ = velocity; } int PbfKalmanMotionFusion::GetRadarHistoryLength() { int history_length = 0; for (size_t i = 0; i < history_velocity_is_radar_.size(); ++i) { if (history_velocity_is_radar_[i]) { history_length++; } } return history_length; } int PbfKalmanMotionFusion::GetLidarHistoryLength() { int history_length = history_velocity_is_radar_.size(); history_length -= GetRadarHistoryLength(); return history_length; } int PbfKalmanMotionFusion::GetLidarHistoryIndex(const int &history_seq) { int history_index = 0; int history_count = 0; for (size_t i = 1; i <= history_velocity_is_radar_.size(); ++i) { history_index = history_velocity_is_radar_.size() - i; if (!history_velocity_is_radar_[history_index]) { history_count++; } if (history_count == history_seq) { break; } } return history_index; } int PbfKalmanMotionFusion::GetRadarHistoryIndex(const int &history_seq) { int history_index = 0; int history_count = 0; for (size_t i = 1; i <= history_velocity_is_radar_.size(); ++i) { history_index = history_velocity_is_radar_.size() - i; if (history_velocity_is_radar_[history_index]) { history_count++; } if (history_count == history_seq) { break; } } return history_index; } double PbfKalmanMotionFusion::GetHistoryTimediff( const int &history_index, const double &current_timestamp) { double history_timestamp = history_time_diff_[history_index]; double history_timediff = current_timestamp - history_timestamp; return history_timediff; } void PbfKalmanMotionFusion::UpdateAcceleration( const Eigen::VectorXd &measured_acceleration) { Eigen::Matrix2d mat_c = Eigen::Matrix2d::Identity(); Eigen::Matrix2d mat_q = Eigen::Matrix2d::Identity() * 0.5; Eigen::Matrix2d mat_k = p_matrix_.block<2, 2>(2, 2) * mat_c.transpose() * (mat_c * p_matrix_.block<2, 2>(2, 2) * mat_c.transpose() + mat_q) .inverse(); Eigen::Vector2d acceleration_gain = mat_k * (measured_acceleration.head(2) - mat_c * belief_acceleration_.head(2)); // breakdown float breakdown_threshold = 2; if (acceleration_gain.norm() > breakdown_threshold) { acceleration_gain.normalize(); acceleration_gain *= breakdown_threshold; } belief_acceleration_(0) += acceleration_gain(0); belief_acceleration_(1) += acceleration_gain(1); } } // namespace perception } // namespace apollo
38.598706
93
0.707722
11e89ae4be449dc35bba4162b7bcf602238a19b9
1,469
cpp
C++
Libraries/LibC/mman.cpp
ZKing1000/serenity
cc68654a44be00deb5edf3b2d2319a663012f015
[ "BSD-2-Clause" ]
3
2019-09-22T11:38:04.000Z
2020-01-21T19:09:27.000Z
Libraries/LibC/mman.cpp
ZKing1000/serenity
cc68654a44be00deb5edf3b2d2319a663012f015
[ "BSD-2-Clause" ]
8
2019-08-25T12:52:40.000Z
2019-09-08T14:46:11.000Z
Libraries/LibC/mman.cpp
ZKing1000/serenity
cc68654a44be00deb5edf3b2d2319a663012f015
[ "BSD-2-Clause" ]
1
2021-08-03T13:04:49.000Z
2021-08-03T13:04:49.000Z
#include <Kernel/Syscall.h> #include <errno.h> #include <mman.h> #include <stdio.h> extern "C" { void* mmap(void* addr, size_t size, int prot, int flags, int fd, off_t offset) { Syscall::SC_mmap_params params { (u32)addr, size, prot, flags, fd, offset, nullptr }; int rc = syscall(SC_mmap, &params); if (rc < 0 && -rc < EMAXERRNO) { errno = -rc; return (void*)-1; } return (void*)rc; } void* mmap_with_name(void* addr, size_t size, int prot, int flags, int fd, off_t offset, const char* name) { Syscall::SC_mmap_params params { (u32)addr, size, prot, flags, fd, offset, name }; int rc = syscall(SC_mmap, &params); if (rc < 0 && -rc < EMAXERRNO) { errno = -rc; return (void*)-1; } return (void*)rc; } int munmap(void* addr, size_t size) { int rc = syscall(SC_munmap, addr, size); __RETURN_WITH_ERRNO(rc, rc, -1); } int mprotect(void* addr, size_t size, int prot) { int rc = syscall(SC_mprotect, addr, size, prot); __RETURN_WITH_ERRNO(rc, rc, -1); } int set_mmap_name(void* addr, size_t size, const char* name) { int rc = syscall(SC_set_mmap_name, addr, size, name); __RETURN_WITH_ERRNO(rc, rc, -1); } int shm_open(const char* name, int flags, mode_t mode) { int rc = syscall(SC_shm_open, name, flags, mode); __RETURN_WITH_ERRNO(rc, rc, -1); } int shm_unlink(const char* name) { int rc = syscall(SC_unlink, name); __RETURN_WITH_ERRNO(rc, rc, -1); } }
24.483333
106
0.632403
11eadbad492afe970e53ec4cb9da196688a0abca
27,642
cpp
C++
OpenSim/Actuators/Schutte1993Muscle_Deprecated.cpp
MariaHammer/opensim-core_HaeufleMuscle
96257e9449d9ac430bbb54e56cd13aaebeee1242
[ "Apache-2.0" ]
532
2015-03-13T18:51:10.000Z
2022-03-27T08:08:29.000Z
OpenSim/Actuators/Schutte1993Muscle_Deprecated.cpp
MariaHammer/opensim-core_HaeufleMuscle
96257e9449d9ac430bbb54e56cd13aaebeee1242
[ "Apache-2.0" ]
2,701
2015-01-03T21:33:34.000Z
2022-03-30T07:13:41.000Z
OpenSim/Actuators/Schutte1993Muscle_Deprecated.cpp
MariaHammer/opensim-core_HaeufleMuscle
96257e9449d9ac430bbb54e56cd13aaebeee1242
[ "Apache-2.0" ]
271
2015-02-16T23:25:29.000Z
2022-03-30T20:12:17.000Z
/* -------------------------------------------------------------------------- * * OpenSim: Schutte1993Muscle_Deprecated.cpp * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Copyright (c) 2005-2017 Stanford University and the Authors * * Author(s): Peter Loan, Jeffrey A. Reinbolt * * * * 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. * * -------------------------------------------------------------------------- */ //============================================================================= // INCLUDES //============================================================================= #include "Schutte1993Muscle_Deprecated.h" #include <OpenSim/Common/SimmSpline.h> #include <OpenSim/Common/SimmMacros.h> //============================================================================= // STATICS //============================================================================= using namespace std; using namespace OpenSim; //============================================================================= // CONSTRUCTOR(S) AND DESTRUCTOR //============================================================================= //_____________________________________________________________________________ /** * Default constructor. */ Schutte1993Muscle_Deprecated::Schutte1993Muscle_Deprecated() { constructProperties(); } //_____________________________________________________________________________ /** * Constructor. */ Schutte1993Muscle_Deprecated::Schutte1993Muscle_Deprecated (const std::string& aName, double aMaxIsometricForce, double aOptimalFiberLength, double aTendonSlackLength, double aPennationAngle) { constructProperties(); setName(aName); setMaxIsometricForce(aMaxIsometricForce); setOptimalFiberLength(aOptimalFiberLength); setTendonSlackLength(aTendonSlackLength); setPennationAngleAtOptimalFiberLength(aPennationAngle); } //============================================================================= // CONSTRUCTION METHODS //============================================================================= //_____________________________________________________________________________ // Allocate and initialize properties. void Schutte1993Muscle_Deprecated::constructProperties() { constructProperty_time_scale(0.1); constructProperty_activation1(7.667); constructProperty_activation2(1.459854); constructProperty_damping(0.1); int tendonForceLengthCurvePoints = 17; double tendonForceLengthCurveX[] = {-10.00000000, -0.00200000, -0.00100000, 0.00000000, 0.00131000, 0.00281000, 0.00431000, 0.00581000, 0.00731000, 0.00881000, 0.01030000, 0.01180000, 0.01230000, 9.20000000, 9.20100000, 9.20200000, 20.00000000}; double tendonForceLengthCurveY[] = {0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.01080000, 0.02570000, 0.04350000, 0.06520000, 0.09150000, 0.12300000, 0.16100000, 0.20800000, 0.22700000, 345.00000000, 345.00000000, 345.00000000, 345.00000000}; SimmSpline tendonForceLengthCurve (tendonForceLengthCurvePoints, tendonForceLengthCurveX, tendonForceLengthCurveY); constructProperty_tendon_force_length_curve(tendonForceLengthCurve); int activeForceLengthCurvePoints = 21; double activeForceLengthCurveX[] = {-5.30769200, -4.30769200, -1.92307700, -0.88461500, -0.26923100, 0.23076900, 0.46153800, 0.52725000, 0.62875000, 0.71875000, 0.86125000, 1.04500000, 1.21750000, 1.43875000, 1.50000000, 1.61538500, 2.00000000, 2.96153800, 3.69230800, 5.46153800, 9.90190200}; double activeForceLengthCurveY[] = {0.01218800, 0.02189900, 0.03646600, 0.05249300, 0.07531200, 0.11415800, 0.15785900, 0.22666700, 0.63666700, 0.85666700, 0.95000000, 0.99333300, 0.77000000, 0.24666700, 0.19382100, 0.13325200, 0.07268300, 0.04441700, 0.03634100, 0.02189900, 0.00733200}; SimmSpline activeForceLengthCurve (activeForceLengthCurvePoints, activeForceLengthCurveX, activeForceLengthCurveY); constructProperty_active_force_length_curve(activeForceLengthCurve); int passiveForceLengthCurvePoints = 13; double passiveForceLengthCurveX[] = {-5.00000000, 0.99800000, 0.99900000, 1.00000000, 1.10000000, 1.20000000, 1.30000000, 1.40000000, 1.50000000, 1.60000000, 1.60100000, 1.60200000, 5.00000000}; double passiveForceLengthCurveY[] = {0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.03500000, 0.12000000, 0.26000000, 0.55000000, 1.17000000, 2.00000000, 2.00000000, 2.00000000, 2.00000000}; SimmSpline passiveForceLengthCurve (passiveForceLengthCurvePoints, passiveForceLengthCurveX, passiveForceLengthCurveY); constructProperty_passive_force_length_curve(passiveForceLengthCurve); } //_____________________________________________________________________________ /** * Perform some set up functions that happen after the * object has been deserialized or copied. * * @param aModel model containing this Schutte1993Muscle_Deprecated. */ void Schutte1993Muscle_Deprecated::extendConnectToModel(Model& aModel) { // Base class Super::extendConnectToModel(aModel); } //============================================================================= // GET //============================================================================= //----------------------------------------------------------------------------- // TIME SCALE //----------------------------------------------------------------------------- //_____________________________________________________________________________ /** * Set the scale factor for normalizing time. * * @param aTimeScale The scale factor for normalizing time. * @return Whether the scale factor was successfully changed. */ bool Schutte1993Muscle_Deprecated::setTimeScale(double aTimeScale) { set_time_scale(aTimeScale); return true; } //----------------------------------------------------------------------------- // ACTIVATION 1 //----------------------------------------------------------------------------- //_____________________________________________________________________________ /** * Set the time constant of ramping up of muscle force. * * @param aActivation1 The time constant of ramping up of muscle force. * @return Whether the time constant was successfully changed. */ bool Schutte1993Muscle_Deprecated::setActivation1(double aActivation1) { set_activation1(aActivation1); return true; } //----------------------------------------------------------------------------- // ACTIVATION 2 //----------------------------------------------------------------------------- //_____________________________________________________________________________ /** * Set the time constant of ramping up and ramping down of muscle force. * * @param aActivation1 The time constant of ramping up and ramping down of muscle force. * @return Whether the time constant was successfully changed. */ bool Schutte1993Muscle_Deprecated::setActivation2(double aActivation2) { set_activation2(aActivation2); return true; } //----------------------------------------------------------------------------- // DAMPING //----------------------------------------------------------------------------- //_____________________________________________________________________________ /** * Set the damping factor related to maximum contraction velocity. * * @param aDamping The damping factor related to maximum contraction velocity. * @return Whether the damping factor was successfully changed. */ bool Schutte1993Muscle_Deprecated::setDamping(double aDamping) { set_damping(aDamping); return true; } //_____________________________________________________________________________ /** * Compute the actuation for the muscle. This function assumes * that computeDerivatives has already been called. */ double Schutte1993Muscle_Deprecated::computeActuation(const SimTK::State& s) const { double tendonForce; double passiveForce; double activeForce; double activationDeriv; double fiberLengthDeriv; double norm_tendon_length, ca; double norm_muscle_tendon_length, pennation_angle; double excitation = getExcitation(s); /* Normalize the muscle states */ double activation = getActivation(s); double normFiberLength = getFiberLength(s) / _optimalFiberLength; /* Compute normalized muscle state derivatives */ if (excitation >= activation) activationDeriv = (excitation - activation) * (get_activation1() * excitation + get_activation2()); else activationDeriv = (excitation - activation) * get_activation2(); pennation_angle = calcPennation(normFiberLength, 1.0, _pennationAngleAtOptimal); ca = cos(pennation_angle); norm_muscle_tendon_length = getLength(s) / _optimalFiberLength; norm_tendon_length = norm_muscle_tendon_length - normFiberLength * ca; tendonForce = calcTendonForce(s,norm_tendon_length); passiveForce = calcNonzeroPassiveForce(s,normFiberLength, 0.0); activeForce = getActiveForceLengthCurve().calcValue(SimTK::Vector(1, normFiberLength) ); if (activeForce < 0.0) activeForce = 0.0; /* If pennation equals 90 degrees, fiber length equals muscle width and fiber * velocity goes to zero. Pennation will stay at 90 until tendon starts to * pull, then "stiff tendon" approximation is used to calculate approximate * fiber velocity. */ if (EQUAL_WITHIN_ERROR(ca, 0.0)) { if (EQUAL_WITHIN_ERROR(tendonForce, 0.0)) { fiberLengthDeriv = 0.0;; } else { double h = norm_muscle_tendon_length - _tendonSlackLength; double w = _optimalFiberLength * sin(_pennationAngleAtOptimal); double new_fiber_length = sqrt(h*h + w*w) / _optimalFiberLength; double new_pennation_angle = calcPennation(new_fiber_length, 1.0, _pennationAngleAtOptimal); double new_ca = cos(new_pennation_angle); fiberLengthDeriv = getLengtheningSpeed(s) * get_time_scale() / _optimalFiberLength * new_ca; } } else { double velocity_dependent_force = tendonForce / ca - passiveForce; if (velocity_dependent_force < 0.0) velocity_dependent_force = 0.0; fiberLengthDeriv = calcFiberVelocity(s,activation, activeForce, velocity_dependent_force); } /* Un-normalize the muscle state derivatives and forces. */ setActivationDeriv(s, activationDeriv / get_time_scale()); setFiberLengthDeriv(s, fiberLengthDeriv * _optimalFiberLength / get_time_scale()); tendonForce = tendonForce * _maxIsometricForce; setActuation(s, tendonForce); setTendonForce(s, tendonForce); setPassiveForce(s, passiveForce * _maxIsometricForce); return( tendonForce ); } //============================================================================= // GET AND SET //============================================================================= //_____________________________________________________________________________ /** * Get the active force-length curve. * * @return Pointer to the active force-length curve (Function). */ const Function& Schutte1993Muscle_Deprecated::getActiveForceLengthCurve() const { return get_active_force_length_curve(); } //_____________________________________________________________________________ /** * Set the active force-length curve. * * @param aActiveForceLengthCurve Pointer to an active force-length curve (Function). * @return Whether active force-length curve was successfully changed. */ bool Schutte1993Muscle_Deprecated:: setActiveForceLengthCurve(const Function& aActiveForceLengthCurve) { set_active_force_length_curve(aActiveForceLengthCurve); return true; } //_____________________________________________________________________________ /** * Get the passive force-length curve. * * @return Pointer to the passive force-length curve (Function). */ const Function& Schutte1993Muscle_Deprecated::getPassiveForceLengthCurve() const { return get_passive_force_length_curve(); } //_____________________________________________________________________________ /** * Get the passive force-length curve. * * @param aPassiveForceLengthCurve Pointer to a passive force-length curve (Function). * @return Whether passive force-length curve was successfully changed. */ bool Schutte1993Muscle_Deprecated:: setPassiveForceLengthCurve(const Function& aPassiveForceLengthCurve) { set_passive_force_length_curve(aPassiveForceLengthCurve); return true; } //_____________________________________________________________________________ /** * Get the tendon force-length curve. * * @return Pointer to the tendon force-length curve (Function). */ const Function& Schutte1993Muscle_Deprecated::getTendonForceLengthCurve() const { return get_tendon_force_length_curve(); } //_____________________________________________________________________________ /** * Get the tendon force-length curve. * * @param aTendonForceLengthCurve Pointer to a tendon force-length curve (Function). * @return Whether tendon force-length curve was successfully changed. */ bool Schutte1993Muscle_Deprecated:: setTendonForceLengthCurve(const Function& aTendonForceLengthCurve) { set_tendon_force_length_curve(aTendonForceLengthCurve); return true; } //_____________________________________________________________________________ /** * Calculate the force in tendon by finding tendon strain * and using it to interpolate the tendon force-length curve. * * @param aNormTendonLength Normalized length of the tendon. * @return The force in the tendon. */ double Schutte1993Muscle_Deprecated::calcTendonForce(const SimTK::State& s, double aNormTendonLength) const { double tendon_force; double norm_resting_length = _tendonSlackLength / _optimalFiberLength; double tendon_strain = (aNormTendonLength - norm_resting_length) / norm_resting_length; if (tendon_strain < 0.0) tendon_force = 0.0; else tendon_force = getTendonForceLengthCurve().calcValue(SimTK::Vector(1, tendon_strain)); return tendon_force; } //_____________________________________________________________________________ /** * calcNonzeroPassiveForce: written by Chris Raasch and Lisa Schutte. * This function calculates the passive force in the muscle fibers using * an exponential instead of cubic splines. This results in non-zero passive * force for any fiber length (and thus prevents "slack" muscle/tendon problems). * It includes the contribution of an exponential passive force-length curve * (which equals 1.0 at norm_fiber_length = 1.5) as well as the damping effects * due to contraction velocity. It should someday be replaced by a new * passive-force spline in the muscle input file, but for now it includes * constants as Chris and Lisa derived them for their specific muscle model. * * @param aNormTendonLength Normalized length of the tendon. * @return The passive force in the muscle fibers. */ double Schutte1993Muscle_Deprecated::calcNonzeroPassiveForce(const SimTK::State& s, double aNormFiberLength, double aNormFiberVelocity) const { double flcomponent = 0.0; if (getProperty_passive_force_length_curve().getValueIsDefault()) flcomponent = exp(8.0*(aNormFiberLength - 1.0)) / exp(4.0); else flcomponent = getPassiveForceLengthCurve().calcValue(SimTK::Vector(1, aNormFiberLength) ); return flcomponent + get_damping() * aNormFiberVelocity; } //_________ ____________________________________________________________________ /** * calcFiberVelocity: written by Chris Raasch and Lisa Schutte. * This function calculates the fiber velocity using an inverse * muscle force-velocity relationship with damping. It should * someday be replaced by a new force-velocity spline in the muscle input * file, but for now it includes constants as Chris and Lisa derived them * for their specific muscle model. * * @param aActivation Activation of the muscle. * @param aActiveForce Active force in the muscle fibers. * @param aVelocityDependentForce Force value that depends on fiber velocity. * @return The velocity of the muscle fibers. */ double Schutte1993Muscle_Deprecated::calcFiberVelocity(const SimTK::State& s, double aActivation, double aActiveForce, double aVelocityDependentForce) const { double b, c, fiber_velocity; double kv = 0.15, slope_k = 0.13, fmax = 1.4; if (aVelocityDependentForce < -get_damping()) { fiber_velocity = aVelocityDependentForce / get_damping(); } else if (aVelocityDependentForce < aActivation * aActiveForce) { c = kv * (aVelocityDependentForce - aActivation * aActiveForce) / get_damping(); b = -kv * (aVelocityDependentForce / kv + aActivation * aActiveForce + get_damping()) / get_damping(); fiber_velocity = (-b - sqrt(b * b - 4 * c)) / 2.0; } else { c = -(slope_k * kv / ((get_damping() * (kv + 1)))) * (aVelocityDependentForce - aActivation * aActiveForce); b = -(aVelocityDependentForce / get_damping() -fmax * aActivation * aActiveForce / get_damping() - slope_k * kv / (kv + 1)); fiber_velocity = (-b + sqrt(b * b - 4 * c)) / 2.0; } return fiber_velocity; } //_____________________________________________________________________________ /** * computeIsometricForce: this function finds the force in a muscle, assuming * static equilibrium. Using the total muscle-tendon length, it finds the * fiber and tendon lengths so that the forces in each match. This routine * takes pennation angle into account, so its definition of static equilibrium * is when tendon_force = fiber_force * cos(pennation_angle). This function * will modify the object's values for length, fiberLength, * and passiveForce. * * @param aActivation Activation of the muscle. * @return The isometric force in the muscle. */ double Schutte1993Muscle_Deprecated::computeIsometricForce(SimTK::State& s, double aActivation) const { #define MAX_ITERATIONS 100 #define ERROR_LIMIT 0.01 int i; double length,tendon_length, fiber_force, tmp_fiber_length, min_tendon_stiffness; double cos_factor, fiber_stiffness; double old_fiber_length{SimTK::NaN}, length_change, tendon_stiffness, percent; double error_force = 0.0, old_error_force, tendon_force, tendon_strain; double passiveForce, activeForce, tendonForce, fiberLength; if (_optimalFiberLength < ROUNDOFF_ERROR) { setStateVariableValue(s, STATE_FIBER_LENGTH_NAME, 0.0); setPassiveForce(s, 0.0); setActuation(s, 0.0); setTendonForce(s, 0.0); return 0.0; } length = getLength(s); // Make first guess of fiber and tendon lengths. Make fiber length equal to // optimal_fiber_length so that you start in the middle of the active+passive // force-length curve. Muscle_width is the width, or thickness, of the // muscle-tendon unit. It is the shortest allowable fiber length because if // the muscle-tendon length is very short, the pennation angle will be 90 // degrees and the fibers will be vertical (assuming the tendon is horizontal). // When this happens, the fibers are as long as the muscle is wide. // If the resting tendon length is zero, then set the fiber length equal to // the muscle tendon length / cosine_factor, and find its force directly. double muscle_width = _optimalFiberLength * sin(_pennationAngleAtOptimal); if (_tendonSlackLength < ROUNDOFF_ERROR) { tendon_length = 0.0; cos_factor = cos(atan(muscle_width / length)); fiberLength = length / cos_factor; activeForce = getActiveForceLengthCurve().calcValue(SimTK::Vector(1, fiberLength / _optimalFiberLength)) * aActivation * _maxIsometricForce; if (activeForce < 0.0) activeForce = 0.0; passiveForce = calcNonzeroPassiveForce(s, fiberLength / _optimalFiberLength, 0.0) * _maxIsometricForce; setPassiveForce(s, passiveForce ); setStateVariableValue(s, STATE_FIBER_LENGTH_NAME, fiberLength); tendonForce = (activeForce + passiveForce) * cos_factor; setActuation(s, tendonForce); setTendonForce(s, tendonForce); return tendonForce; } else if (length < _tendonSlackLength) { setStateVariableValue(s, STATE_FIBER_LENGTH_NAME, muscle_width); setPassiveForce(s, 0.0); setActuation(s, 0.0); setTendonForce(s, 0.0); return 0.0; } else { fiberLength = _optimalFiberLength; cos_factor = cos(calcPennation(fiberLength, _optimalFiberLength, _pennationAngleAtOptimal)); tendon_length = length - fiberLength * cos_factor; /* Check to make sure tendon is not shorter than its slack length. If it * is, set the length to its slack length and re-compute fiber length. */ if (tendon_length < _tendonSlackLength) { tendon_length = _tendonSlackLength; cos_factor = cos(atan(muscle_width / (length - tendon_length))); fiberLength = (length - tendon_length) / cos_factor; if (fiberLength < muscle_width) fiberLength = muscle_width; } } // Muscle-tendon force is found using an iterative method. First, you guess // the length of the muscle fibers and the length of the tendon, and // calculate their respective forces. If the forces match (are within // ERROR_LIMIT of each other), stop; else change the length guesses based // on the error and try again. for (i = 0; i < MAX_ITERATIONS; i++) { activeForce = getActiveForceLengthCurve().calcValue(SimTK::Vector(1, fiberLength / _optimalFiberLength)) * aActivation; if (activeForce < 0.0) activeForce = 0.0; passiveForce = calcNonzeroPassiveForce(s, fiberLength / _optimalFiberLength, 0.0); if (passiveForce < 0.0) passiveForce = 0.0; fiber_force = (activeForce + passiveForce ) * _maxIsometricForce * cos_factor; tendon_strain = (tendon_length / _tendonSlackLength - 1.0); if (tendon_strain < 0.0) tendon_force = 0.0; else tendon_force = getTendonForceLengthCurve().calcValue(SimTK::Vector(1, tendon_strain)) * _maxIsometricForce; setActuation(s, tendon_force); setTendonForce(s, tendon_force); old_error_force = error_force; error_force = tendon_force - fiber_force; if (DABS(error_force) <= ERROR_LIMIT) // muscle-tendon force found! break; if (i == 0) old_error_force = error_force; if (DSIGN(error_force) != DSIGN(old_error_force)) { percent = DABS(error_force) / (DABS(error_force) + DABS(old_error_force)); tmp_fiber_length = old_fiber_length; old_fiber_length = fiberLength; fiberLength += percent * (tmp_fiber_length - fiberLength); } else { // Estimate the stiffnesses of the tendon and the fibers. If tendon // stiffness is too low, then the next length guess will overshoot // the equilibrium point. So we artificially raise it using the // normalized muscle force. (_activeForce+_passiveForce) is the // normalized force for the current fiber length, and we assume that // the equilibrium length is close to this current length. So we want // to get force = (_activeForce+_passiveForce) from the tendon as well. // We hope this will happen by setting the tendon stiffness to // (_activeForce+_passiveForce) times its maximum stiffness. double tendon_elastic_modulus = 1200.0; double tendon_max_stress = 32.0; tendon_stiffness = getTendonForceLengthCurve().calcValue(SimTK::Vector(1, tendon_strain)) * _maxIsometricForce / _tendonSlackLength; min_tendon_stiffness = (activeForce + passiveForce) * tendon_elastic_modulus * _maxIsometricForce / (tendon_max_stress * _tendonSlackLength); if (tendon_stiffness < min_tendon_stiffness) tendon_stiffness = min_tendon_stiffness; fiber_stiffness = _maxIsometricForce / _optimalFiberLength * (getActiveForceLengthCurve().calcValue(SimTK::Vector(1, fiberLength / _optimalFiberLength)) + calcNonzeroPassiveForce(s, fiberLength / _optimalFiberLength, 0.0)); // determine how much the fiber and tendon lengths have to // change to make the error_force zero. But don't let the // length change exceed half the optimal fiber length because // that's too big a change to make all at once. length_change = fabs(error_force/(fiber_stiffness / cos_factor + tendon_stiffness)); if (fabs(length_change / _optimalFiberLength) > 0.5) length_change = 0.5 * _optimalFiberLength; // now change the fiber length depending on the sign of the error // and the sign of the fiber stiffness (which equals the sign of // the slope of the muscle's force-length curve). old_fiber_length = fiberLength; if (error_force > 0.0) fiberLength += length_change; else fiberLength -= length_change; } cos_factor = cos(calcPennation(fiberLength, _optimalFiberLength, _pennationAngleAtOptimal)); tendon_length = length - fiberLength * cos_factor; // Check to make sure tendon is not shorter than its slack length. If it is, // set the length to its slack length and re-compute fiber length. if (tendon_length < _tendonSlackLength) { tendon_length = _tendonSlackLength; cos_factor = cos(atan(muscle_width / (length - tendon_length))); fiberLength = (length - tendon_length) / cos_factor; } } setStateVariableValue(s, STATE_FIBER_LENGTH_NAME, fiberLength); setPassiveForce(s, passiveForce * _maxIsometricForce); return tendon_force; } // Satisfy the ActivationFiberLengthMuscle_Deprecated interface double Schutte1993Muscle_Deprecated::calcPassiveForce(const SimTK::State& s, double aNormFiberLength) const { return calcNonzeroPassiveForce(s,aNormFiberLength, 0.0); } double Schutte1993Muscle_Deprecated::calcActiveForce(const SimTK::State& s, double aNormFiberLength) const { return getActiveForceLengthCurve().calcValue(SimTK::Vector(1, aNormFiberLength) ); }
44.015924
313
0.678714
11ec6438742eeb4119f26905fc2b29bcf4313a3c
10,387
cpp
C++
src/ZeroHalfSystem.cpp
DanielKowalczyk1984/PM
0738c662f7bf95792c86f493525d868d7b7346d8
[ "MIT" ]
null
null
null
src/ZeroHalfSystem.cpp
DanielKowalczyk1984/PM
0738c662f7bf95792c86f493525d868d7b7346d8
[ "MIT" ]
null
null
null
src/ZeroHalfSystem.cpp
DanielKowalczyk1984/PM
0738c662f7bf95792c86f493525d868d7b7346d8
[ "MIT" ]
null
null
null
// MIT License // Copyright (c) 2021 Daniel Kowalczyk // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include "ZeroHalfSystem.hpp" #include <boost/container_hash/extensions.hpp> // for hash_combine #include <boost/dynamic_bitset/dynamic_bitset.hpp> // for dynamic_bitset #include <cmath> // for ceil #include <cstddef> // for size_t #include <limits> // for numeric_limits #include <range/v3/algorithm/any_of.hpp> // for any_of, any_of_fn #include <range/v3/algorithm/for_each.hpp> // for for_each, for_... #include <range/v3/algorithm/min.hpp> // for min, min_fn #include <range/v3/numeric/inner_product.hpp> // for inner_product #include <range/v3/range/conversion.hpp> // for to, operator| #include <range/v3/utility/swap.hpp> // for swap #include <range/v3/view/all.hpp> // for all_t, all_fn #include <range/v3/view/drop.hpp> // for drop_view, drop #include <range/v3/view/enumerate.hpp> // for enumerate_fn #include <range/v3/view/iota.hpp> // for iota_view, ints #include <range/v3/view/join.hpp> // for join_view, joi... #include <range/v3/view/stride.hpp> // for stride_view #include <range/v3/view/transform.hpp> // for transform_view #include <range/v3/view/view.hpp> // for operator|, vie... #include <range/v3/view/zip.hpp> // for zip_view, zip #include <range/v3/view/zip_with.hpp> // for iter_zip_with_... #include <unordered_map> // for unordered_map #include <vector> // for vector, allocator namespace vs = ranges::views; ZeroHalfSystem::ZeroHalfSystem(const MatrixDouble& A, [[maybe_unused]] const VectorDouble& _b, const VectorDouble& _x) : x_star(_x), row_index(A.size(), boost::dynamic_bitset{A.size()}) { // auto min_elem = // ranges::min(ranges::min(ranges::views::transform( // A, [](auto& row) { return ranges::min(row); })), // ranges::min(_b)); // auto add_elem = 0.0; // if (min_elem < 0.0) { // add_elem = std::ceil(-min_elem / HALF) * HALF; // } // auto func_add_value = [&add_elem](auto& it) -> int { // return static_cast<int>(add_elem + it) % 2; // }; // A_bar = vs::transform(A, // [&func_add_value](auto& row) { // return vs::transform(row, func_add_value) | // ranges::to<std::vector>(); // }) | // ranges::to<std::vector>(); // b_bar = vs::transform(_b, func_add_value) | ranges::to<std::vector>; // auto tmp = vs::transform( // A, [&_x](auto& row) { return ranges::inner_product(row, _x, 0.0); }); // slack = // vs::zip_with([](auto lhs, auto rhs) { return lhs - rhs; }, _b, tmp) | // ranges::to<std::vector>(); // for (auto&& [i, set] : row_index | vs::enumerate) { // set[i] = true; // } // reduce_system(); } void ZeroHalfSystem::remove_row(size_t _row) { ranges::swap(A_bar[_row], A_bar[nb_rows - 1]); ranges::swap(slack[_row], slack[nb_rows - 1]); ranges::swap(b_bar[_row], b_bar[nb_rows - 1]); ranges::swap(row_index[_row], row_index[nb_rows - 1]); --nb_rows; // A_bar.pop_back(); } void ZeroHalfSystem::remove_col(size_t _col) { for (auto& it : A_bar) { ranges::swap(it[_col], it[nb_columns - 1]); } ranges::swap(x_star[_col], x_star[nb_columns - 1]); --nb_columns; } void ZeroHalfSystem::reduce_system() { // auto col = 0UL; // /** Rule 1 */ // while (col < nb_columns) { // if (x_star[col] < EPS) { // remove_col(col); // } else { // ++col; // } // } // /** Rule 2 */ // auto row = 0UL; // while (row < nb_rows) { // auto any_one = // ranges::any_of(A_bar[row], [](auto& a) { return a == 1; }) || // (b_bar[row] == 1); // if (any_one) { // ++row; // } else { // remove_row(row); // } // } // /** Rule 3,4,5 */ // std::unordered_map<size_t, int> column_dict{}; // col = 0UL; // while (col < nb_columns) { // size_t key = 0UL; // int counter{}; // int last_one{-1}; // for (auto&& [r, a] : A_bar | vs::enumerate) { // if (a[col]) { // boost::hash_combine(key, r); // ++counter; // last_one = static_cast<int>(r); // } // } // if (counter == 0) { // remove_col(col); // } else if (counter == 1) { // slack[last_one] += x_star[col]; // remove_col(col); // } else if (column_dict.find(key) != column_dict.end()) { // auto aux = column_dict[key]; // x_star[aux] += x_star[col]; // remove_col(col); // } else { // column_dict[key] = col; // ++col; // } // } // /** Rule 6 */ // row = 0UL; // while (row < nb_rows) { // if (slack[row] >= 1.0) { // remove_row(row); // } else { // ++row; // } // } // /** Use hash combine to detect equivalent columns */ // /** Rule 7 Dekoster et al. */ // std::unordered_map<size_t, int> row_dict; // row = 0UL; // while (row < nb_rows) { // size_t key = 0UL; // ranges::for_each(A_bar[row], [&key](auto& it_col) { // if (it_col) { // boost::hash_combine(key, it_col); // } // }); // if (b_bar[row]) { // boost::hash_combine(key, nb_columns); // } // if (row_dict.find(key) == row_dict.end()) { // row_dict[key] = row; // ++row; // } else { // auto tmp = row_dict[key]; // if (slack[tmp] < slack[row]) { // remove_row(row); // } else { // ranges::swap(row_index[tmp], row_index[row]); // ranges::swap(slack[tmp], slack[row]); // remove_row(row); // } // } // } } void ZeroHalfSystem::reduce_gauss() { // auto row = 0UL; // while (row < nb_rows) { // if (slack[row] < EPS) { // auto high_x = std::numeric_limits<double>::min(); // auto best_col = -1; // auto counter = 0; // for (auto j = 0UL; j < nb_columns; ++j) { // if (A_bar[row][j]) { // ++counter; // if (x_star[j] > high_x) { // high_x = x_star[j]; // best_col = j; // } // } // } // if (counter == 0) { // if (b_bar[row]) { // /** construct ineq */ // } // remove_row(row); // } else { // for (auto&& [r, x] : vs::enumerate(A_bar)) { // if (r != row && x[best_col] == 1) { // add_to_row(row, r); // } // slack[row] += x_star[best_col]; // remove_col(best_col); // ++row; // } // } // } else { // ++row; // } // } } void ZeroHalfSystem::evaluate_rows(const std::vector<int>& _rows) { auto sum_slack = 0.0; ranges::for_each(_rows, [&](int idx) { sum_slack += slack[idx]; }); if (sum_slack <= 1.0 - HALF * EPS) { std::vector<int> v(nb_rows, 0); ranges::for_each(_rows, [&](int idx) { v[idx] = 1; }); auto odd = (ranges::inner_product(v, b_bar, 0) % 2) == 1; if (odd) { auto left = vs::ints(size_t{}, nb_columns) | vs::transform([&](int i) { return ranges::inner_product(v | vs::all, A_bar | vs::join | vs::drop(i) | vs::stride(nb_columns), 0) % 2; }); auto val = ranges::inner_product(left, x_star, 0.0); if (val < 1 - HALF * EPS) { auto result = row_index[0]; for (auto& it : row_index | vs::drop(0)) { result ^= it; } /** construct ineq */ } } } } void ZeroHalfSystem::add_to_row(size_t i, size_t j) { for (auto&& [lhs, rhs] : vs::zip(A_bar[i], A_bar[j])) { rhs = (lhs + rhs) % 2; } b_bar[j] = (b_bar[i] + b_bar[j]) % 2; row_index[j] = row_index[i] ^ row_index[j]; slack[j] = slack[i] + slack[j]; } ZeroHalfSystem::ZeroHalfSystem([[maybe_unused]]const DdStructure<NodeBdd>& bdd) { // auto& table = bdd.getDiagram(); }
36.318182
81
0.476654
11efde7b5950be22407b08107a2a50dd10497eb5
3,137
cc
C++
src/canvas/canvas/Persistency/Provenance/EventAuxiliary.cc
JeffersonLab/ARIEL
49054ac62a84d48e269f7171daabb98e12a0be90
[ "BSD-3-Clause" ]
null
null
null
src/canvas/canvas/Persistency/Provenance/EventAuxiliary.cc
JeffersonLab/ARIEL
49054ac62a84d48e269f7171daabb98e12a0be90
[ "BSD-3-Clause" ]
null
null
null
src/canvas/canvas/Persistency/Provenance/EventAuxiliary.cc
JeffersonLab/ARIEL
49054ac62a84d48e269f7171daabb98e12a0be90
[ "BSD-3-Clause" ]
2
2020-09-26T01:37:11.000Z
2021-05-03T13:02:24.000Z
#include "canvas/Persistency/Provenance/EventAuxiliary.h" // vim: set sw=2 expandtab : #include <ostream> #include <utility> using namespace std; namespace art { EventAuxiliary::~EventAuxiliary() {} EventAuxiliary::EventAuxiliary() : id_{}, time_{}, isRealData_{false}, experimentType_{Any} {} EventAuxiliary::EventAuxiliary(EventID const& theId, Timestamp const& theTime, bool isReal, ExperimentType eType /*= Any*/) : id_{theId}, time_{theTime}, isRealData_{isReal}, experimentType_{eType} {} EventAuxiliary::EventAuxiliary(EventAuxiliary const& rhs) : id_{rhs.id_} , time_{rhs.time_} , isRealData_{rhs.isRealData_} , experimentType_{rhs.experimentType_} {} EventAuxiliary::EventAuxiliary(EventAuxiliary&& rhs) : id_{move(rhs.id_)} , time_{move(rhs.time_)} , isRealData_{move(rhs.isRealData_)} , experimentType_{move(rhs.experimentType_)} {} EventAuxiliary& EventAuxiliary::operator=(EventAuxiliary const& rhs) { if (this != &rhs) { id_ = rhs.id_; time_ = rhs.time_; isRealData_ = rhs.isRealData_; experimentType_ = rhs.experimentType_; } return *this; } EventAuxiliary& EventAuxiliary::operator=(EventAuxiliary&& rhs) { id_ = move(rhs.id_); time_ = move(rhs.time_); isRealData_ = move(rhs.isRealData_); experimentType_ = move(rhs.experimentType_); return *this; } Timestamp const& EventAuxiliary::time() const noexcept { auto const& ret = time_; return ret; } EventID const& EventAuxiliary::id() const noexcept { auto const& ret = id_; return ret; } EventID const& EventAuxiliary::eventID() const noexcept { auto const& ret = id_; return ret; } RunID const& EventAuxiliary::runID() const noexcept { auto const& ret = id_.runID(); return ret; } SubRunID const& EventAuxiliary::subRunID() const noexcept { auto const& ret = id_.subRunID(); return ret; } RunNumber_t EventAuxiliary::run() const noexcept { auto ret = id_.run(); return ret; } SubRunNumber_t EventAuxiliary::subRun() const noexcept { auto ret = id_.subRun(); return ret; } EventNumber_t EventAuxiliary::event() const noexcept { auto ret = id_.event(); return ret; } bool EventAuxiliary::isRealData() const noexcept { auto ret = isRealData_; return ret; } EventAuxiliary::ExperimentType EventAuxiliary::experimentType() const noexcept { auto ret = experimentType_; return ret; } bool EventAuxiliary::operator==(EventAuxiliary const& other) const noexcept { auto ret = (id_ == other.id_) && (time_ == other.time_) && (isRealData_ == other.isRealData_) && (experimentType_ == other.experimentType_); return ret; } void EventAuxiliary::write(ostream& os) const { os << id_ << endl; } ostream& operator<<(ostream& os, const EventAuxiliary& p) { p.write(os); return os; } } // namespace art
20.503268
77
0.630539
11f3cbe46634b80efade80446aa4ed7b5742fe26
8,136
hpp
C++
include/dca/io/hdf5/hdf5_reader.hpp
gonidelis/DCA
b219350a335b96c85b74de9a88bd00d4f37f0ce2
[ "BSD-3-Clause" ]
null
null
null
include/dca/io/hdf5/hdf5_reader.hpp
gonidelis/DCA
b219350a335b96c85b74de9a88bd00d4f37f0ce2
[ "BSD-3-Clause" ]
11
2020-04-22T14:50:27.000Z
2021-09-10T05:43:51.000Z
include/dca/io/hdf5/hdf5_reader.hpp
weilewei/DCA
b219350a335b96c85b74de9a88bd00d4f37f0ce2
[ "BSD-3-Clause" ]
1
2019-09-22T16:33:19.000Z
2019-09-22T16:33:19.000Z
// Copyright (C) 2018 ETH Zurich // Copyright (C) 2018 UT-Battelle, LLC // All rights reserved. // // See LICENSE for terms of usage. // See CITATION.md for citation guidelines, if DCA++ is used for scientific publications. // // Author: Peter Staar (taa@zurich.ibm.com) // // HDF5 reader. #ifndef DCA_IO_HDF5_HDF5_READER_HPP #define DCA_IO_HDF5_HDF5_READER_HPP #include <complex> #include <string> #include <vector> #include "H5Cpp.h" #include "dca/io/buffer.hpp" #include "dca/function/domains.hpp" #include "dca/function/function.hpp" #include "dca/io/hdf5/hdf5_types.hpp" #include "dca/linalg/matrix.hpp" #include "dca/linalg/vector.hpp" namespace dca { namespace io { // dca::io:: class HDF5Reader { public: typedef H5::H5File file_type; // In: verbose. If true, the reader outputs a short log whenever it is executed. HDF5Reader(bool verbose = true) : verbose_(verbose) {} ~HDF5Reader(); constexpr static bool is_reader = true; constexpr static bool is_writer = false; void open_file(std::string file_name); void close_file(); void open_group(std::string name) { paths_.push_back(name); } void close_group() { paths_.pop_back(); } std::string get_path(); template <typename arbitrary_struct_t> static void from_file(arbitrary_struct_t& arbitrary_struct, std::string file_name); // `execute` returns true if the object is read correctly. template <typename Scalartype> bool execute(const std::string& name, Scalartype& value); template <typename Scalar> bool execute(const std::string& name, std::vector<Scalar>& value); template <typename Scalar> bool execute(const std::string& name, std::vector<std::vector<Scalar>>& value); template <typename Scalar, std::size_t n> bool execute(const std::string& name, std::vector<std::array<Scalar, n>>& value); bool execute(const std::string& name, std::string& value); bool execute(const std::string& name, std::vector<std::string>& value); // TODO: Remove? (only thing that depends on domains.hpp) template <typename domain_type> bool execute(std::string /*name*/, func::dmn_0<domain_type>& /*dmn*/) { return false; } template <typename Scalartype, typename domain_type> bool execute(func::function<Scalartype, domain_type>& f); template <typename Scalartype, typename domain_type> bool execute(const std::string& name, func::function<Scalartype, domain_type>& f); template <typename Scalar> bool execute(const std::string& name, dca::linalg::Vector<Scalar, dca::linalg::CPU>& A); template <typename Scalar> bool execute(const std::string& name, dca::linalg::Matrix<Scalar, dca::linalg::CPU>& A); template <typename Scalar> bool execute(dca::linalg::Matrix<Scalar, dca::linalg::CPU>& A); bool execute(const std::string& name, io::Buffer& buff) { return execute(name, static_cast<io::Buffer::Container&>(buff)); } private: bool exists(const std::string& name) const; void read(const std::string& name, H5::DataType type, void* data) const; std::vector<hsize_t> readSize(const std::string& name) const; std::unique_ptr<H5::H5File> file_; std::vector<std::string> paths_; bool verbose_; }; template <typename arbitrary_struct_t> void HDF5Reader::from_file(arbitrary_struct_t& arbitrary_struct, std::string file_name) { HDF5Reader reader_obj; reader_obj.open_file(file_name); arbitrary_struct.read_write(reader_obj); reader_obj.close_file(); } template <typename Scalar> bool HDF5Reader::execute(const std::string& name, Scalar& value) { std::string full_name = get_path() + "/" + name; if (!exists(full_name)) { return false; } read(full_name, HDF5_TYPE<Scalar>::get_PredType(), &value); return true; } template <typename Scalar> bool HDF5Reader::execute(const std::string& name, std::vector<Scalar>& value) { std::string full_name = get_path() + "/" + name; if (!exists(full_name)) { return false; } auto dims = readSize(full_name); assert(dims.size() == 1); value.resize(dims.at(0)); read(full_name, HDF5_TYPE<Scalar>::get_PredType(), value.data()); return true; } template <typename Scalar> bool HDF5Reader::execute(const std::string& name, std::vector<std::vector<Scalar>>& value) { std::string full_name = get_path() + "/" + name; if (!exists(full_name)) { return false; } auto size = readSize(full_name)[0]; const auto type = H5::VarLenType(HDF5_TYPE<Scalar>::get_PredType()); std::vector<hvl_t> data(size); H5::DataSet dataset = file_->openDataSet(name.c_str()); dataset.read(data.data(), type); value.resize(size); for (int i = 0; i < size; ++i) { value[i].resize(data[i].len); std::copy_n(static_cast<Scalar*>(data[i].p), data[i].len, value[i].data()); } dataset.vlenReclaim(data.data(), type, dataset.getSpace()); return true; } template <typename Scalar, std::size_t n> bool HDF5Reader::execute(const std::string& name, std::vector<std::array<Scalar, n>>& value) { std::string full_name = get_path() + "/" + name; if (!exists(full_name)) { return false; } auto dims = readSize(full_name); assert(dims.size() == 2); if (dims.at(1) != n) { throw(std::length_error("Wrong array size")); } value.resize(dims[0]); read(full_name, HDF5_TYPE<Scalar>::get_PredType(), value.data()); return true; } template <typename Scalartype, typename domain_type> bool HDF5Reader::execute(func::function<Scalartype, domain_type>& f) { return execute(f.get_name(), f); } template <typename Scalartype, typename domain_type> bool HDF5Reader::execute(const std::string& name, func::function<Scalartype, domain_type>& f) { std::string full_name = get_path() + "/" + name; if (!exists(full_name)) { std::cout << "\n\n\t the function (" + name + ") does not exist in path : " + get_path() + "\n\n"; return false; } std::cout << "\n\tstart reading function : " << name; H5::DataSet dataset = file_->openDataSet(full_name.c_str()); try { // Read sizes. std::vector<hsize_t> dims; auto domain_attribute = dataset.openAttribute("domain-sizes"); hsize_t n_dims; domain_attribute.getSpace().getSimpleExtentDims(&n_dims); dims.resize(n_dims); domain_attribute.read(HDF5_TYPE<hsize_t>::get_PredType(), dims.data()); // Check sizes. if (dims.size() != f.signature()) throw(std::length_error("The number of domains is different")); for (int i = 0; i < f.signature(); ++i) { if (dims[i] != f[i]) throw(std::length_error("The size of domain " + std::to_string(i) + " is different")); } } catch (H5::Exception& err) { std::cerr << "Could not perform a size check on the function " << name << std::endl; } read(full_name, HDF5_TYPE<Scalartype>::get_PredType(), f.values()); return true; } template <typename Scalar> bool HDF5Reader::execute(const std::string& name, dca::linalg::Vector<Scalar, dca::linalg::CPU>& V) { std::string full_name = get_path() + "/" + name; if (!exists(full_name)) { return false; } auto dims = readSize(full_name); assert(dims.size() == 1); V.resize(dims.at(0)); read(full_name, HDF5_TYPE<Scalar>::get_PredType(), V.ptr()); return true; } template <typename Scalar> bool HDF5Reader::execute(const std::string& name, dca::linalg::Matrix<Scalar, dca::linalg::CPU>& A) { std::string full_name = get_path() + "/" + name; if (!exists(full_name)) { return false; } auto dims = readSize(full_name); assert(dims.size() == 2); std::vector<Scalar> linearized(dims[0] * dims[1]); read(full_name, HDF5_TYPE<Scalar>::get_PredType(), linearized.data()); // HDF5 is column major, while Matrix is row major. A.resizeNoCopy(std::make_pair(dims[0], dims[1])); for (int i = 0, linindex = 0; i < A.nrRows(); ++i) { for (int j = 0; j < A.nrCols(); ++j) A(i, j) = linearized[linindex++]; } A.set_name(name); return true; } template <typename Scalar> bool HDF5Reader::execute(dca::linalg::Matrix<Scalar, dca::linalg::CPU>& A) { return execute(A.get_name(), A); } } // namespace io } // namespace dca #endif // DCA_IO_HDF5_HDF5_READER_HPP
28.055172
101
0.678343
11f561c54c4c77935addf7364cc459c6526ab83b
7,305
hpp
C++
Contrib-Intel/RSD-PSME-RMM/common/agent-framework/include/agent-framework/state_machine/enum_state_machine.hpp
opencomputeproject/Rack-Manager
e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a
[ "MIT" ]
5
2019-11-11T07:57:26.000Z
2022-03-28T08:26:53.000Z
Contrib-Intel/RSD-PSME-RMM/common/agent-framework/include/agent-framework/state_machine/enum_state_machine.hpp
opencomputeproject/Rack-Manager
e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a
[ "MIT" ]
3
2019-09-05T21:47:07.000Z
2019-09-17T18:10:45.000Z
Contrib-Intel/RSD-PSME-RMM/common/agent-framework/include/agent-framework/state_machine/enum_state_machine.hpp
opencomputeproject/Rack-Manager
e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a
[ "MIT" ]
11
2019-07-20T00:16:32.000Z
2022-01-11T14:17:48.000Z
/*! * @copyright * Copyright (c) 2016-2019 Intel Corporation * * @copyright * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * @copyright * http://www.apache.org/licenses/LICENSE-2.0 * * @copyright * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @file state_machine/enum_state_machine.hpp * @brief Declaration of the EnumStateMachine template * */ #pragma once #include <functional> #include <vector> #include "wrap.hpp" namespace agent_framework { namespace state_machine { /*! * Class representing a simple enum-based state machine. It uses enums to represent states and events, therefore * states cannot really store their own data. State machine is parametrized with two types: STATE which is a type of * machine states and EVENT representing Events type. * */ template <typename STATE, typename EVENT> class EnumStateMachine { public: struct Transition; /*! * Type definition of the functions used in state machines - used for guards and actions. They accept one * parameter that describe the transition and return bool value: for actions, true means that action was * successful, for guards, true means that the transition may be started. * */ using StateMachineFunction = std::function<bool(const Transition&)>; /*! Type declaration of the TransitionTable */ using TransitionTable = std::vector<Transition>; /*! Struct representing single transition of the state machine */ struct Transition final { public: /*! * @brief Constructor * @param[in] i_s Initial state before the transition * @param[in] e Event that triggers the transition * @param[in] e_s End state after the transition * @param[in] a Action triggered by the transition (default action = no action) * @param[in] g Guard checking if transition should be performed (default guard = always) * */ Transition(const STATE& i_s, const EVENT& e, const STATE& e_s, StateMachineFunction a = do_nothing, StateMachineFunction g = always): init_state(i_s), event(e), end_state(e_s), action(a), guard(g) {} /*! * @brief Default action during transitions - does nothing * @return Always returns true * */ static constexpr bool do_nothing(const Transition&) { return true; } /*! * @brief Default guard - always true * @return Always returns true * */ static constexpr bool always(const Transition&) { return true; } /*! Initial state required for the transition */ STATE init_state; /*! Event triggering the transition */ EVENT event; /*! End state after the transition */ STATE end_state; /*! Action triggered by the transition */ StateMachineFunction action; /*! Additional condition for transition to take place */ StateMachineFunction guard; }; /*! * @brief Constructor * @param[in] init_state Initial state of the machine * @param[in] transition_table Transition table describing transitions allowed in the * state machine (default = no transitions, empty table) * */ EnumStateMachine(const STATE& init_state, const TransitionTable& transition_table = {}): m_current_state(init_state), m_transition_table(transition_table) {} /*! Copy constructor */ EnumStateMachine(const EnumStateMachine&) = default; /*! Move constructor */ EnumStateMachine(EnumStateMachine&&) = default; /*! Copy Assignment operators */ EnumStateMachine& operator=(const EnumStateMachine&) = default; /*! Move Assignment operators */ EnumStateMachine& operator=(EnumStateMachine&&) = default; /*! * @brief Destructor * */ virtual ~EnumStateMachine() {} /*! * @brief Adds a transition to the state machine * @param[in] init_state Initial state before the transition * @param[in] event Event that triggers the transition * @param[in] end_state End state after the transition * @param[in] action Action triggered by the transition (default action = no action) * @param[in] guard Guard checking if transition should be performed (default guard = always) * @return Reference to the state machine * */ EnumStateMachine& add_transition(const STATE& init_state, const EVENT& event, const STATE& end_state, StateMachineFunction action = Transition::do_nothing, StateMachineFunction guard = Transition::always) { m_transition_table.emplace_back(Transition{init_state, event, end_state, action, guard}); return *this; } /*! * @brief Returns current machine state * @return Current machine state * */ STATE get_current_state() const { return m_current_state; } /*! * @brief Sends specific event to the machine * @param[in] event Event sent to the state machine * @return False if the event would cause state machine to change its state, but due to state machine action * failure, state was not changed and transition did not happen. * */ bool send_event(const EVENT& event) { do_on_event_action(event); for (const auto& transition : m_transition_table) { if (transition.init_state == m_current_state && transition.event == event && do_guard_check(transition)) { if (!do_transition(transition)) { return false; } m_current_state = transition.end_state; return true; } } return true; } protected: /*! * @brief Method used to check guards of the transition. * Should be overriden in derived classes if change of the behaviour is desired. * @param[in] transition Information about the transition * @return True if the guard returned true * */ virtual bool do_guard_check(const Transition& transition) { return transition.guard(transition); } /*! * @brief Method used to perform transition action. * Should be overriden in derived classes if change of the behaviour is desired. * @param[in] transition Information about the transition * @return True if action was successful * */ virtual bool do_transition(const Transition& transition) { return transition.action(transition); } /*! * @brief Method called as a first method in send_event call * Should be overriden in derived classes if change of the behaviour is desired. * */ virtual void do_on_event_action(const EVENT&) { } private: /*! Current state of the state machine */ STATE m_current_state{}; /*! Transition table of the state machine */ TransitionTable m_transition_table{}; }; } }
34.620853
118
0.665161
11f72ce0b197f74c326bdb0e5b8762a804b43bbb
27
cpp
C++
lib/STD/Ostream.cpp
hlp2/EnjoLib
6bb69d0b00e367a800b0ef2804808fd1303648f4
[ "BSD-3-Clause" ]
3
2021-06-14T15:36:46.000Z
2022-02-28T15:16:08.000Z
lib/STD/Ostream.cpp
hlp2/EnjoLib
6bb69d0b00e367a800b0ef2804808fd1303648f4
[ "BSD-3-Clause" ]
1
2021-07-17T07:52:15.000Z
2021-07-17T07:52:15.000Z
lib/STD/Ostream.cpp
hlp2/EnjoLib
6bb69d0b00e367a800b0ef2804808fd1303648f4
[ "BSD-3-Clause" ]
3
2021-07-12T14:52:38.000Z
2021-11-28T17:10:33.000Z
#include <STD/Ostream.hpp>
13.5
26
0.740741
11f87b43e5fe24fbaf37fc6f98f9b1a8f343fbb9
1,321
cpp
C++
SelfLearningFromVideo/imooc-DatastructureAndAlgorithm/AllCodeFromTeacher/08-Minimum-Span-Trees/06-Kruskal-Algorithm/main.cpp
YaKaiLi/YaKaiLi-PAT-Related
5eca2d90a6e7fc069fd8c320721d337676200ade
[ "MIT" ]
1
2018-08-22T15:12:39.000Z
2018-08-22T15:12:39.000Z
SelfLearningFromVideo/imooc-DatastructureAndAlgorithm/AllCodeFromTeacher/08-Minimum-Span-Trees/06-Kruskal-Algorithm/main.cpp
YaKaiLi/YaKaiLi-PAT-Related
5eca2d90a6e7fc069fd8c320721d337676200ade
[ "MIT" ]
1
2020-08-31T09:32:56.000Z
2020-08-31T09:32:56.000Z
C++/08-Minimum-Span-Trees/06-Kruskal-Algorithm/main.cpp
DragonYong/Happy-Algorithm
7ca585d5990f5c4587ab4e22178ecb88e5d57d91
[ "Apache-2.0" ]
2
2018-08-09T13:59:29.000Z
2018-08-23T15:02:40.000Z
#include <iostream> #include <iomanip> #include "DenseGraph.h" #include "SparseGraph.h" #include "ReadGraph.h" #include "LazyPrimMST.h" #include "PrimMST.h" #include "KruskalMST.h" using namespace std; int main() { string filename = "testG1.txt"; int V = 8; SparseGraph<double> g = SparseGraph<double>(V, false); ReadGraph<SparseGraph<double>, double> readGraph(g, filename); // Test Lazy Prim MST cout<<"Test Lazy Prim MST:"<<endl; LazyPrimMST<SparseGraph<double>, double> lazyPrimMST(g); vector<Edge<double>> mst = lazyPrimMST.mstEdges(); for( int i = 0 ; i < mst.size() ; i ++ ) cout<<mst[i]<<endl; cout<<"The MST weight is: "<<lazyPrimMST.result()<<endl; cout<<endl; // Test Prim MST cout<<"Test Prim MST:"<<endl; PrimMST<SparseGraph<double>, double> primMST(g); mst = primMST.mstEdges(); for( int i = 0 ; i < mst.size() ; i ++ ) cout<<mst[i]<<endl; cout<<"The MST weight is: "<<primMST.result()<<endl; cout<<endl; // Test Kruskal MST cout<<"Test Kruskal MST:"<<endl; KruskalMST<SparseGraph<double>, double> kruskalMST(g); mst = kruskalMST.mstEdges(); for( int i = 0 ; i < mst.size() ; i ++ ) cout<<mst[i]<<endl; cout<<"The MST weight is: "<<kruskalMST.result()<<endl; return 0; }
25.403846
66
0.612415
11f8e7f086843de435f0ba0729c37d98bf1c72de
1,726
cpp
C++
patches/exploding_villagers.cpp
HSZemi/auto-mods
695be813636f71419490df689f2d09eda1a2c496
[ "MIT" ]
10
2020-06-14T21:00:23.000Z
2021-12-08T12:33:01.000Z
patches/exploding_villagers.cpp
HSZemi/auto-mods
695be813636f71419490df689f2d09eda1a2c496
[ "MIT" ]
15
2020-09-12T21:10:41.000Z
2021-11-07T14:39:20.000Z
patches/exploding_villagers.cpp
HSZemi/auto-mods
695be813636f71419490df689f2d09eda1a2c496
[ "MIT" ]
13
2020-08-31T22:48:34.000Z
2021-11-07T14:17:22.000Z
#include "exploding_villagers.h" #include <set> #include "genie/dat/DatFile.h" #include "ids.h" void configureExplodingVillagers(genie::DatFile *df, bool nerfSaboteur) { std::set<int> villagers = { ID_FISHING_SHIP, ID_TRADE_COG, ID_TRADE_CART_EMPTY, ID_TRADE_CART_FULL, ID_VILLAGER_BASE_M, ID_VILLAGER_BASE_F, ID_VILLAGER_FARMER_M, ID_VILLAGER_FARMER_F, ID_VILLAGER_SHEPHERD_M, ID_VILLAGER_SHEPHERD_F, ID_VILLAGER_FORAGER_M, ID_VILLAGER_FORAGER_F, ID_VILLAGER_HUNTER_M, ID_VILLAGER_HUNTER_F, ID_VILLAGER_FISHER_M, ID_VILLAGER_FISHER_F, ID_VILLAGER_WOOD_M, ID_VILLAGER_WOOD_F, ID_VILLAGER_GOLD_M, ID_VILLAGER_GOLD_F, ID_VILLAGER_STONE_M, ID_VILLAGER_STONE_F, ID_VILLAGER_BUILDER_M, ID_VILLAGER_BUILDER_F, ID_VILLAGER_REPAIRER_M, ID_VILLAGER_REPAIRER_F, }; for (genie::Civ &civ : df->Civs) { for (int villager_id : villagers) { civ.Units.at(villager_id).DeadUnitID = ID_SABOTEUR; std::cout << "Patched Villager unit " << villager_id << " for civ " << civ.Name << "\n"; } genie::Unit &saboteur = civ.Units.at(ID_SABOTEUR); saboteur.HitPoints = 0; if (nerfSaboteur) { saboteur.Type50.Attacks.at(0).Amount = 50; saboteur.Type50.Attacks.at(1).Amount = 90; saboteur.Type50.Attacks.at(2).Amount = 0; } saboteur.Type50.MaxRange = 2; saboteur.Type50.BlastAttackLevel = 1; // cut trees saboteur.TrainSound = -1; saboteur.WwiseTrainSoundID = 0; // prevent melee unit train sound from playing std::cout << "Patched Saboteur unit for civ " << civ.Name << "\n"; } }
46.648649
101
0.660487
11f9887f888c3b0af2c96c08de66cd8d689cc1b4
864
cpp
C++
ultrasonic-sensor-with-leds.cpp
pferreirafabricio/arduvino
0ce2ef73cc36db420787943a8372bb6ef785124d
[ "MIT" ]
null
null
null
ultrasonic-sensor-with-leds.cpp
pferreirafabricio/arduvino
0ce2ef73cc36db420787943a8372bb6ef785124d
[ "MIT" ]
null
null
null
ultrasonic-sensor-with-leds.cpp
pferreirafabricio/arduvino
0ce2ef73cc36db420787943a8372bb6ef785124d
[ "MIT" ]
null
null
null
#define pinTrigger 9 #define pinEcho 10 const int ledsColors[] = { 7, 6, 5 }; const int red = ledsColors[0]; const int blue = ledsColors[1]; const int green = ledsColors[2]; int readDistance() { digitalWrite(pinTrigger, LOW); delayMicroseconds(2); digitalWrite(pinTrigger, HIGH); delayMicroseconds(10); digitalWrite(pinTrigger, LOW); unsigned long echoTime = pulseIn(pinEcho, HIGH); return round(echoTime * 0.01717); } void setup() { pinMode(pinTrigger, OUTPUT); pinMode(pinEcho, INPUT); for (int index = 0; index < 4; index++) pinMode(ledsColors[index], OUTPUT); } void loop() { int distance = readDistance(); digitalWrite(red, distance >= 0.1 && distance < 100 ? HIGH : LOW); digitalWrite(blue, distance >= 100 && distance < 200 ? HIGH : LOW); digitalWrite(green, distance >= 200 ? HIGH : LOW); delay(100); }
20.571429
69
0.667824
11fa0a388389d1b9f2847950551f953a106927b7
2,727
cpp
C++
src/kalman_filter.cpp
linuxairhead/SDC-C2-P1-Extended-Kalman-Filter
1f797f777cd1d9b9cedd0ab0fda14fc9a5b153f4
[ "MIT" ]
null
null
null
src/kalman_filter.cpp
linuxairhead/SDC-C2-P1-Extended-Kalman-Filter
1f797f777cd1d9b9cedd0ab0fda14fc9a5b153f4
[ "MIT" ]
null
null
null
src/kalman_filter.cpp
linuxairhead/SDC-C2-P1-Extended-Kalman-Filter
1f797f777cd1d9b9cedd0ab0fda14fc9a5b153f4
[ "MIT" ]
null
null
null
#include "kalman_filter.h" #include <string> using Eigen::MatrixXd; using Eigen::VectorXd; // Please note that the Eigen library does not initialize // VectorXd or MatrixXd objects with zeros upon creation. KalmanFilter::KalmanFilter() { /* * private variable for debug */ fn = "Constructor"; } KalmanFilter::~KalmanFilter() {} void KalmanFilter::Init(VectorXd &x_in, MatrixXd &P_in, MatrixXd &F_in, MatrixXd &H_in, MatrixXd &R_in, MatrixXd &Q_in) { fn = "Init"; KF_DEBUG(fn, "Start"); x_ = x_in; I_ = MatrixXd::Identity(x_.size(), x_.size()); P_ = I_; P_(2,2) = 1000; P_(3,3) = 1000; F_ = I_; H_ = H_in; R_ = R_in; Q_ = Q_in; KF_DEBUG(fn, "End"); } void KalmanFilter::Predict() { fn = "Predict"; KF_DEBUG(fn, "start"); /** * predict the state */ KF_DEBUG(fn, "x_"); KF_DEBUG(fn, x_ ); KF_DEBUG(fn, "F_"); KF_DEBUG(fn, F_ ); x_ = F_ * x_; // u = 0 P_ = F_ * P_ * F_.transpose() + Q_; KF_DEBUG(fn, x_ ); } void KalmanFilter::Update(const VectorXd &z) { fn = "KalmanFilterUpdate"; KF_DEBUG(fn, "Start"); /** * update the state by using Kalman Filter equations */ VectorXd y = z - H_ * x_; KF_DEBUG(fn, "End 1"); MatrixXd S = H_ * P_ * H_.transpose() + R_; KF_DEBUG(fn, "End 2"); MatrixXd K = P_ * H_.transpose() * S.inverse(); KF_DEBUG(fn, "End 3"); x_ = x_ + K * y; P_ = (I_ - K * H_) * P_; KF_DEBUG(fn, "End 4"); } void KalmanFilter::UpdateEKF(const VectorXd &z) { fn = "UpdateEFK"; KF_DEBUG(fn, "Start"); KF_DEBUG(fn, x_); /** * update the state by using Extended Kalman Filter equations */ float px = x_[0]; float py = x_[1]; float vx = x_[2]; float vy = x_[3]; // If ro == 0, skip the update step to avoid dividing by zero. if( px == 0. && py == 0. ) return; float rho = sqrt( px*px + py*py ); KF_DEBUG(fn, "rho"); KF_DEBUG(fn, rho); VectorXd z_pred(3); z_pred << rho, atan2( py, px ), ( px*vx + py*vy )/rho; KF_DEBUG(fn, "z_pred"); KF_DEBUG(fn, z_pred); // Update the state using Extended Kalman Filter equations VectorXd y = z - z_pred; if( y[1] > PI ) y[1] -= 2.f*PI; if( y[1] < -PI ) y[1] += 2.f*PI; KF_DEBUG(fn, "y"); KF_DEBUG(fn, y); MatrixXd Hj_ = tools.CalculateJacobian( x_ ); KF_DEBUG(fn, "Hj_"); KF_DEBUG(fn, Hj_); KF_DEBUG(fn, "P_"); KF_DEBUG(fn, P_); KF_DEBUG(fn, "R_"); KF_DEBUG(fn, R_); MatrixXd S = Hj_*P_* Hj_.transpose() + R_; KF_DEBUG(fn, "S"); KF_DEBUG(fn, S); MatrixXd K = P_*Hj_.transpose()*S.inverse(); KF_DEBUG(fn, "K"); KF_DEBUG(fn, K); // Compute new state x_ = x_ + ( K * y ); P_ = ( I_ - K * Hj_ ) * P_; }
19.905109
73
0.569124
11fa69c4678eecb2a577cd77411fee1a390e1c6c
9,612
cc
C++
Validation/DTRecHits/plugins/DTSegment2DSLPhiQuality.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
1
2019-08-09T08:42:11.000Z
2019-08-09T08:42:11.000Z
Validation/DTRecHits/plugins/DTSegment2DSLPhiQuality.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
null
null
null
Validation/DTRecHits/plugins/DTSegment2DSLPhiQuality.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
1
2019-03-19T13:44:54.000Z
2019-03-19T13:44:54.000Z
/* * See header file for a description of this class. * * \author S. Bolognesi and G. Cerminara - INFN Torino */ #include <iostream> #include <map> #include "DataFormats/DTRecHit/interface/DTRecHitCollection.h" #include "DataFormats/DTRecHit/interface/DTRecSegment4DCollection.h" #include "DataFormats/MuonDetId/interface/DTWireId.h" #include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/Frameworkfwd.h" #include "Geometry/DTGeometry/interface/DTChamber.h" #include "Geometry/DTGeometry/interface/DTGeometry.h" #include "Geometry/Records/interface/MuonGeometryRecord.h" #include "SimDataFormats/TrackingHit/interface/PSimHitContainer.h" #include "Validation/DTRecHits/interface/DTHitQualityUtils.h" #include "DTSegment2DSLPhiQuality.h" #include "Histograms.h" using namespace std; using namespace edm; namespace dtsegment2dsl { struct Histograms { std::unique_ptr<HRes2DHit> h2DHitSuperPhi; std::unique_ptr<HEff2DHit> h2DHitEff_SuperPhi; }; } using namespace dtsegment2dsl; // Constructor DTSegment2DSLPhiQuality::DTSegment2DSLPhiQuality(const ParameterSet& pset) { // Get the debug parameter for verbose output debug_ = pset.getUntrackedParameter<bool>("debug"); DTHitQualityUtils::debug = debug_; // the name of the simhit collection simHitLabel_ = pset.getUntrackedParameter<InputTag>("simHitLabel"); simHitToken_ = consumes<PSimHitContainer>(pset.getUntrackedParameter<InputTag>("simHitLabel")); // the name of the 2D rec hit collection segment4DLabel_ = pset.getUntrackedParameter<InputTag>("segment4DLabel"); segment4DToken_ = consumes<DTRecSegment4DCollection>(pset.getUntrackedParameter<InputTag>("segment4DLabel")); // sigma resolution on position sigmaResPos_ = pset.getParameter<double>("sigmaResPos"); // sigma resolution on angle sigmaResAngle_ = pset.getParameter<double>("sigmaResAngle"); doall_ = pset.getUntrackedParameter<bool>("doall", false); local_ = pset.getUntrackedParameter<bool>("local", false); } void DTSegment2DSLPhiQuality::bookHistograms(DQMStore::ConcurrentBooker & booker, edm::Run const& run, edm::EventSetup const& setup, Histograms & histograms) const { // Book the histos histograms.h2DHitSuperPhi = std::make_unique<HRes2DHit> ("SuperPhi", booker, doall_, local_); if (doall_) { histograms.h2DHitEff_SuperPhi = std::make_unique<HEff2DHit> ("SuperPhi", booker); } } // The real analysis void DTSegment2DSLPhiQuality::dqmAnalyze(edm::Event const& event, edm::EventSetup const& setup, Histograms const& histograms) const { // Get the DT Geometry ESHandle<DTGeometry> dtGeom; setup.get<MuonGeometryRecord>().get(dtGeom); // Get the SimHit collection from the event edm::Handle<PSimHitContainer> simHits; event.getByToken(simHitToken_, simHits); // FIXME: second string to be removed // Map simHits by chamber map<DTChamberId, PSimHitContainer > simHitsPerCh; for (const auto & simHit : *simHits) { // Create the id of the chamber (the simHits in the DT known their wireId) DTChamberId chamberId = (((DTWireId(simHit.detUnitId())).layerId()).superlayerId()).chamberId(); // Fill the map simHitsPerCh[chamberId].push_back(simHit); } // Get the 4D rechits from the event Handle<DTRecSegment4DCollection> segment4Ds; event.getByToken(segment4DToken_, segment4Ds); if (!segment4Ds.isValid()) { if (debug_) { cout << "[DTSegment2DSLPhiQuality]**Warning: no 4D Segments with label: " << segment4DLabel_ << " in this event, skipping!" << endl; } return; } // Loop over all chambers containing a segment DTRecSegment4DCollection::id_iterator chamberId; for (chamberId = segment4Ds->id_begin(); chamberId != segment4Ds->id_end(); ++chamberId) { //------------------------- simHits ---------------------------// // Get simHits of each chamber PSimHitContainer simHits = simHitsPerCh[(*chamberId)]; // Map simhits per wire map<DTWireId, PSimHitContainer > simHitsPerWire = DTHitQualityUtils::mapSimHitsPerWire(simHits); map<DTWireId, const PSimHit*> muSimHitPerWire = DTHitQualityUtils::mapMuSimHitsPerWire(simHitsPerWire); int nMuSimHit = muSimHitPerWire.size(); if (nMuSimHit == 0 || nMuSimHit == 1) { if (debug_ && nMuSimHit == 1) { cout << "[DTSegment2DSLPhiQuality] Only " << nMuSimHit << " mu SimHit in this chamber, skipping!" << endl; } continue; // If no or only one mu SimHit is found skip this chamber } if (debug_) { cout << "=== Chamber " << (*chamberId) << " has " << nMuSimHit << " SimHits" << endl; } // Find outer and inner mu SimHit to build a segment pair<const PSimHit*, const PSimHit*> inAndOutSimHit = DTHitQualityUtils::findMuSimSegment(muSimHitPerWire); // Find direction and position of the sim Segment in Chamber RF pair<LocalVector, LocalPoint> dirAndPosSimSegm = DTHitQualityUtils::findMuSimSegmentDirAndPos(inAndOutSimHit, (*chamberId),&(*dtGeom)); LocalVector simSegmLocalDir = dirAndPosSimSegm.first; LocalPoint simSegmLocalPos = dirAndPosSimSegm.second; const DTChamber* chamber = dtGeom->chamber(*chamberId); GlobalPoint simSegmGlobalPos = chamber->toGlobal(simSegmLocalPos); // Atan(x/z) angle and x position in SL RF float angleSimSeg = DTHitQualityUtils::findSegmentAlphaAndBeta(simSegmLocalDir).first; float posSimSeg = simSegmLocalPos.x(); // Position (in eta, phi coordinates) in lobal RF float etaSimSeg = simSegmGlobalPos.eta(); float phiSimSeg = simSegmGlobalPos.phi(); if (debug_) { cout << " Simulated segment: local direction " << simSegmLocalDir << endl << " local position " << simSegmLocalPos << endl << " angle " << angleSimSeg << endl; } //---------------------------- recHits --------------------------// // Get the range of rechit for the corresponding chamberId bool recHitFound = false; DTRecSegment4DCollection::range range = segment4Ds->get(*chamberId); int nsegm = distance(range.first, range.second); if (debug_) { cout << " Chamber: " << *chamberId << " has " << nsegm << " 4D segments" << endl; } if (nsegm!= 0) { // Find the best RecHit: look for the 4D RecHit with the phi angle closest // to that of segment made of SimHits. // RecHits must have delta alpha and delta position within 5 sigma of // the residual distribution (we are looking for residuals of segments // usefull to the track fit) for efficency purpose const DTRecSegment2D* bestRecHit = nullptr; bool bestRecHitFound = false; double deltaAlpha = 99999; // Loop over the recHits of this chamberId for (DTRecSegment4DCollection::const_iterator segment4D = range.first; segment4D!= range.second; ++segment4D) { // Check the dimension if ((*segment4D).dimension() != 4) { if (debug_) { cout << "[DTSegment2DSLPhiQuality]***Error: This is not 4D segment!!!" << endl; } continue; } // Get 2D superPhi segments from 4D segments const DTChamberRecSegment2D* phiSegment2D = (*segment4D).phiSegment(); if ((*phiSegment2D).dimension() != 2) { if (debug_) { cout << "[DTSegment2DQuality]***Error: This is not 2D segment!!!" << endl; } abort(); } // Segment Local Direction and position (in Chamber RF) LocalVector recSegDirection = (*phiSegment2D).localDirection(); float recSegAlpha = DTHitQualityUtils::findSegmentAlphaAndBeta(recSegDirection).first; if (debug_) { cout << " RecSegment direction: " << recSegDirection << endl << " position : " << (*phiSegment2D).localPosition() << endl << " alpha : " << recSegAlpha << endl; } if (fabs(recSegAlpha - angleSimSeg) < deltaAlpha) { deltaAlpha = fabs(recSegAlpha - angleSimSeg); bestRecHit = &(*phiSegment2D); bestRecHitFound = true; } } // End of Loop over all 4D RecHits of this chambers if (bestRecHitFound) { // Best rechit direction and position in Chamber RF LocalPoint bestRecHitLocalPos = bestRecHit->localPosition(); LocalVector bestRecHitLocalDir = bestRecHit->localDirection(); LocalError bestRecHitLocalPosErr = bestRecHit->localPositionError(); LocalError bestRecHitLocalDirErr = bestRecHit->localDirectionError(); float angleBestRHit = DTHitQualityUtils::findSegmentAlphaAndBeta(bestRecHitLocalDir).first; if (fabs(angleBestRHit - angleSimSeg) < 5*sigmaResAngle_ && fabs(bestRecHitLocalPos.x() - posSimSeg) < 5*sigmaResPos_) { recHitFound = true; } // Fill Residual histos histograms.h2DHitSuperPhi->fill(angleSimSeg, angleBestRHit, posSimSeg, bestRecHitLocalPos.x(), etaSimSeg, phiSimSeg, sqrt(bestRecHitLocalPosErr.xx()), sqrt(bestRecHitLocalDirErr.xx()) ); } } // end of if (nsegm!= 0) // Fill Efficiency plot if (doall_) { histograms.h2DHitEff_SuperPhi->fill(etaSimSeg, phiSimSeg, posSimSeg, angleSimSeg, recHitFound); } } // End of loop over chambers } // declare this as a framework plugin #include "FWCore/Framework/interface/MakerMacros.h" DEFINE_FWK_MODULE(DTSegment2DSLPhiQuality);
39.719008
165
0.675198
11fe3791e770cdf9ea0e90baba1f10810b5b35bc
23,298
cpp
C++
src/Solver/SolverNonLinear.cpp
chalmersplasmatheory/DREAM
715637ada94f5e35db16f23c2fd49bb7401f4a27
[ "MIT" ]
12
2020-09-07T11:19:10.000Z
2022-02-17T17:40:19.000Z
src/Solver/SolverNonLinear.cpp
chalmersplasmatheory/DREAM
715637ada94f5e35db16f23c2fd49bb7401f4a27
[ "MIT" ]
110
2020-09-02T15:29:24.000Z
2022-03-09T09:50:01.000Z
src/Solver/SolverNonLinear.cpp
chalmersplasmatheory/DREAM
715637ada94f5e35db16f23c2fd49bb7401f4a27
[ "MIT" ]
3
2021-05-21T13:24:31.000Z
2022-02-11T14:43:12.000Z
/** * Implementation of a custom Newton solver which only utilizes * the linear solvers of PETSc. */ #include <iostream> #include <string> #include <vector> #include "DREAM/IO.hpp" #include "DREAM/OutputGeneratorSFile.hpp" #include "DREAM/Solver/SolverNonLinear.hpp" using namespace DREAM; using namespace std; /** * Constructor. */ SolverNonLinear::SolverNonLinear( FVM::UnknownQuantityHandler *unknowns, vector<UnknownQuantityEquation*> *unknown_equations, EquationSystem *eqsys, enum OptionConstants::linear_solver ls, enum OptionConstants::linear_solver bk, const int_t maxiter, const real_t reltol, bool verbose ) : Solver(unknowns, unknown_equations, ls, bk), eqsys(eqsys), maxiter(maxiter), reltol(reltol), verbose(verbose) { this->timeKeeper = new FVM::TimeKeeper("Solver non-linear"); this->timerTot = this->timeKeeper->AddTimer("total", "Total time"); this->timerRebuild = this->timeKeeper->AddTimer("rebuildtot", "Rebuild coefficients"); this->timerResidual = this->timeKeeper->AddTimer("residual", "Construct residual"); this->timerJacobian = this->timeKeeper->AddTimer("jacobian", "Construct jacobian"); this->timerInvert = this->timeKeeper->AddTimer("invert", "Invert jacobian"); } /** * Destructor. */ SolverNonLinear::~SolverNonLinear() { Deallocate(); delete this->timeKeeper; } /** * "Accept" the current solution and prepare for taking * another Newton step. */ void SolverNonLinear::AcceptSolution() { real_t *x = this->x1; this->x1 = this->x0; this->x0 = x; this->StoreSolution(x); } /** * Allocate memory for all objects used by this solver. */ void SolverNonLinear::Allocate() { this->AllocateJacobianMatrix(); const len_t N = jacobian->GetNRows(); // Select linear solver this->SelectLinearSolver(N); VecCreateSeq(PETSC_COMM_WORLD, N, &this->petsc_F); VecCreateSeq(PETSC_COMM_WORLD, N, &this->petsc_dx); this->x0 = new real_t[N]; this->x1 = new real_t[N]; this->dx = new real_t[N]; this->xinit = new real_t[N]; this->x_2norm = new real_t[this->unknown_equations->size()]; this->dx_2norm = new real_t[this->unknown_equations->size()]; } /** * Allocates memory for and properly sets up the jacobian matrix. * If the jacobian matrix has previously been allocated, it will * first be deleted. * * WHY DO WE CALL THIS METHOD MORE THAN ONCE? * In the very first iteration, many elements of the jacobian matrix are often * identically zero. If we don't insert the zeros explicitly, PETSc will remove * the memory we allocated for them on the first call to 'Assemble()' requiring * the memory to be reallocated in the next iteration (which may take a _very_ * long time). However, if we insert the zeros explicitly, the linear solver * will not be able to tell that the elements are in fact non-zero and will * take ages to solve the system. As a compromise, we would like to use the * non-zero pattern obtained in the second Newton iteration of the simulation, * we should be very close to the non-zero pattern of the remainder of the * simulation. Hence, we call this method after the first iteration is finished * to completely reset the matrix, including the non-zero pattern. Reallocating * all the memory in one go is significantly faster than asking PETSc to * allocate memory specifically for all the elements we would like to add in the * second iteration. */ void SolverNonLinear::AllocateJacobianMatrix() { if (this->jacobian != nullptr) delete this->jacobian; this->jacobian = new FVM::BlockMatrix(); for (len_t i = 0; i < nontrivial_unknowns.size(); i++) { len_t id = nontrivial_unknowns[i]; UnknownQuantityEquation *eqn = this->unknown_equations->at(id); unknownToMatrixMapping[id] = this->jacobian->CreateSubEquation(eqn->NumberOfElements(), eqn->NumberOfNonZeros_jac(), id); } this->jacobian->ConstructSystem(); } /** * Deallocate memory used by this solver. */ void SolverNonLinear::Deallocate() { if (backupInverter != nullptr) delete backupInverter; delete mainInverter; delete jacobian; delete [] this->x_2norm; delete [] this->dx_2norm; delete [] this->x0; delete [] this->x1; delete [] this->dx; delete [] this->xinit; VecDestroy(&this->petsc_F); VecDestroy(&this->petsc_dx); } /** * Returns the name of the specified non-trivial unknown quantity. * * idx: Index into 'this->nontrivial_unknowns' of the non-trivial unknown * to return the name of. */ const string& SolverNonLinear::GetNonTrivialName(const len_t idx) { return this->unknowns->GetUnknown(this->nontrivial_unknowns[idx])->GetName(); } /** * Initialize the solver. */ void SolverNonLinear::initialize_internal( const len_t, vector<len_t>& ) { this->Allocate(); if (this->convChecker == nullptr) this->SetConvergenceChecker( new ConvergenceChecker(unknowns, this->nontrivial_unknowns, this->reltol) ); } /** * Check if the solver has converged. */ bool SolverNonLinear::IsConverged(const real_t *x, const real_t *dx) { if (this->GetIteration() >= this->MaxIter()){ throw SolverException( "Non-linear solver reached the maximum number of allowed " "iterations: " LEN_T_PRINTF_FMT ".", this->MaxIter() ); } // always print verbose for the last few iterations before reaching max const len_t numVerboseBeforeMax = 3; bool printVerbose = this->Verbose() || (this->MaxIter() - this->GetIteration())<=numVerboseBeforeMax; if (printVerbose) DREAM::IO::PrintInfo("ITERATION %d", this->GetIteration()); return convChecker->IsConverged(x, dx, printVerbose); } /** * Set the initial guess for the solver. * * guess: Vector containing values of initial guess. */ void SolverNonLinear::SetInitialGuess(const real_t *guess) { if (guess != nullptr) { for (len_t i = 0; i < this->matrix_size; i++) this->x0[i] = guess[i]; } else { for (len_t i = 0; i < this->matrix_size; i++) this->x0[i] = 0; } } /** * Revert the solution to the initial guess. */ void SolverNonLinear::ResetSolution() { this->unknowns->GetLongVectorPrevious(this->nontrivial_unknowns, this->x0); this->StoreSolution(this->x0); } /** * Solve the equation system (advance the system in time * by one step). * * t: Time at which the current solution is given. * dt: Time step to take. * * (the obtained solution will correspond to time t'=t+dt) */ void SolverNonLinear::Solve(const real_t t, const real_t dt) { // Return to main matrix inverter (in case backup inverter // was used to complete last time step) this->SwitchToMainInverter(); this->nTimeStep++; this->t = t; this->dt = dt; this->timeKeeper->StartTimer(timerTot); try { this->_InternalSolve(); } catch (FVM::FVMException &ex) { // Retry with backup-solver (if allowed and not already used) if (this->backupInverter != nullptr && this->inverter != this->backupInverter) { if (this->Verbose()) { DREAM::IO::PrintInfo( "Main inverter failed to converge. Switching to backup inverter." ); DREAM::IO::PrintError(ex.what()); } // Retry solve this->SwitchToBackupInverter(); this->_InternalSolve(); } else // Rethrow exception throw ex; } // Save basic statistics for step this->nIterations.push_back(this->iteration); this->usedBackupInverter.push_back(this->inverter == this->backupInverter); this->timeKeeper->StopTimer(timerTot); } void SolverNonLinear::_InternalSolve() { // Take Newton steps len_t iter = 0; const real_t *x, *dx; do { iter++; this->SetIteration(iter); REDO_ITER: dx = this->TakeNewtonStep(); // Solution rejected (solver likely switched) if (dx == nullptr) { if (iter < this->MaxIter()) goto REDO_ITER; else throw SolverException("Maximum number of iterations reached while dx=nullptr."); } x = UpdateSolution(dx); // TODO backtracking... AcceptSolution(); } while (!IsConverged(x, dx)); } /** * Debugging routine for saving both the "analytically" computed * Jacobian, as well as the Jacobian evaluated numerically using * finite differences, to file. When this method is called, the * 'jacobian' variable is assumed to contain the "analytical" * Jacobian matrix for the current time/iteration. This routine * will then save that matrix, compute the corresponding numerical * Jacobian, and save that. * * name: Base name to use for files. */ void SolverNonLinear::SaveNumericalJacobian(const std::string& name) { this->_EvaluateJacobianNumerically(this->jacobian); this->jacobian->View(FVM::Matrix::BINARY_MATLAB, name + "_num"); abort(); } void SolverNonLinear::SaveJacobian() { this->jacobian->View(FVM::Matrix::BINARY_MATLAB, "petsc_jacobian"); } void SolverNonLinear::SaveJacobian(const std::string& name) { this->jacobian->View(FVM::Matrix::BINARY_MATLAB, name); } /** * Store the current solution to the UnknownQuantityHandler. */ void SolverNonLinear::StoreSolution(const real_t *x) { this->unknowns->Store(this->nontrivial_unknowns, x); } /** * Calculate the next Newton step to take. */ const real_t *SolverNonLinear::TakeNewtonStep() { this->timeKeeper->StartTimer(timerRebuild); this->RebuildTerms(this->t, this->dt); this->timeKeeper->StopTimer(timerRebuild); // Evaluate function vector this->timeKeeper->StartTimer(timerResidual); real_t *fvec; VecGetArray(this->petsc_F, &fvec); this->BuildVector(this->t, this->dt, fvec, this->jacobian); VecRestoreArray(this->petsc_F, &fvec); this->timeKeeper->StopTimer(timerResidual); // Reconstruct the jacobian matrix after taking the first // iteration. // (See the comment above 'AllocateJacobianMatrix()' for // details about why we do this...) if (this->nTimeStep == 1 && this->iteration == 2) this->AllocateJacobianMatrix(); // Evaluate jacobian this->timeKeeper->StartTimer(timerJacobian); this->BuildJacobian(this->t, this->dt, this->jacobian); this->timeKeeper->StopTimer(timerJacobian); // Print/save debug info and apply preconditioner (if enabled) if (this->debugrescaled) { this->Precondition(this->jacobian, this->petsc_F); this->SaveDebugInfoBefore(this->nTimeStep, this->iteration); } else { this->SaveDebugInfoBefore(this->nTimeStep, this->iteration); this->Precondition(this->jacobian, this->petsc_F); } // Solve J*dx = F this->timeKeeper->StartTimer(timerInvert); inverter->Invert(this->jacobian, &this->petsc_F, &this->petsc_dx); if (inverter->GetReturnCode() != 0) { if (this->Verbose()) DREAM::IO::PrintInfo("Switching to backup inverter... " INT_T_PRINTF_FMT, inverter->GetReturnCode()); this->SwitchToBackupInverter(); return nullptr; } this->timeKeeper->StopTimer(timerInvert); // Undo preconditioner and save additional debug info (if requested) if (this->debugrescaled) { this->SaveDebugInfoAfter(this->nTimeStep, this->iteration); this->UnPrecondition(this->petsc_dx); } else { this->UnPrecondition(this->petsc_dx); this->SaveDebugInfoAfter(this->nTimeStep, this->iteration); } // Copy dx VecGetArray(this->petsc_dx, &fvec); for (len_t i = 0; i < this->matrix_size; i++) this->dx[i] = fvec[i]; VecRestoreArray(this->petsc_dx, &fvec); return this->dx; } /** * Helper function to damping factor calculation; given a quantity * X0 and its change dX in the iteration, returns the maximal step * length (damping) such that X>threshold*X0 after the iteration */ const real_t MaximalStepLengthAtGridPoint( real_t X0, real_t dX, real_t threshold ){ real_t maxStepAtI = 1.0; if(dX>X0*std::numeric_limits<real_t>::min()) // dX positive, with check to avoid overflow maxStepAtI = (1-threshold) * X0 / dX; return maxStepAtI; } /** * Returns a dampingFactor such that x1 = x0 - dampingFactor*dx satisfies * physically-motivated constraints, such as positivity of temperature. * If initial guess dx from Newton step satisfies all constraints, returns 1. */ const real_t MaximalPhysicalStepLength(real_t *x0, const real_t *dx, len_t iteration, std::vector<len_t> nontrivial_unknowns, FVM::UnknownQuantityHandler *unknowns, IonHandler *ionHandler, len_t &id_uqn){ real_t maxStepLength = 1.0; real_t threshold = 0.1; std::vector<len_t> ids_nonNegativeQuantities; // add those quantities which we expect to be non-negative // T_cold and n_cold will crash the simulation if negative, so they should always be added ids_nonNegativeQuantities.push_back(unknowns->GetUnknownID(OptionConstants::UQTY_T_COLD)); ids_nonNegativeQuantities.push_back(unknowns->GetUnknownID(OptionConstants::UQTY_N_TOT)); ids_nonNegativeQuantities.push_back(unknowns->GetUnknownID(OptionConstants::UQTY_N_COLD)); if(unknowns->HasUnknown(OptionConstants::UQTY_W_COLD)) ids_nonNegativeQuantities.push_back(unknowns->GetUnknownID(OptionConstants::UQTY_W_COLD)); if(unknowns->HasUnknown(OptionConstants::UQTY_WI_ENER)) ids_nonNegativeQuantities.push_back(unknowns->GetUnknownID(OptionConstants::UQTY_WI_ENER)); if(unknowns->HasUnknown(OptionConstants::UQTY_NI_DENS)) ids_nonNegativeQuantities.push_back(unknowns->GetUnknownID(OptionConstants::UQTY_NI_DENS)); bool nonNegativeZeff = true; const len_t id_ni = unknowns->GetUnknownID(OptionConstants::UQTY_ION_SPECIES); const len_t N = nontrivial_unknowns.size(); const len_t N_nn = ids_nonNegativeQuantities.size(); len_t offset = 0; // sum over non-trivial unknowns for (len_t it=0; it<N; it++) { const len_t id = nontrivial_unknowns[it]; FVM::UnknownQuantity *uq = unknowns->GetUnknown(id); len_t NCells = uq->NumberOfElements(); // check whether unknown it is a non-negative quantity bool isNonNegativeQuantity = false; for (len_t it_nn = 0; it_nn < N_nn; it_nn++) if(id==ids_nonNegativeQuantities[it_nn]) isNonNegativeQuantity = true; // Quantities which physically cannot be negative, require that they cannot // be reduced by more than some threshold in each iteration. if(isNonNegativeQuantity) for(len_t i=0; i<NCells; i++){ // require x1 > threshold*x0 real_t maxStepAtI = MaximalStepLengthAtGridPoint(x0[offset+i], dx[offset+i], threshold); // if this is a stronger constaint than current maxlength, override if(maxStepAtI < maxStepLength && maxStepAtI>0){ maxStepLength = maxStepAtI; id_uqn = id; } } if(nonNegativeZeff && id==id_ni){ len_t nZ = ionHandler->GetNZ(); const len_t *Zs = ionHandler->GetZs(); len_t nr = NCells/uq->NumberOfMultiples(); for(len_t ir=0; ir<nr; ir++){ real_t nZ0Z0=0; real_t dnZ0Z0=0; for(len_t iz=0; iz<nZ; iz++) for(len_t Z0=0; Z0<=Zs[iz]; Z0++){ len_t ind = ionHandler->GetIndex(iz,Z0); nZ0Z0 += Z0*Z0*x0[offset+ind*nr+ir]; dnZ0Z0 += Z0*Z0*dx[offset+ind*nr+ir]; } real_t maxStepAtI = MaximalStepLengthAtGridPoint(nZ0Z0, dnZ0Z0, threshold); if(maxStepAtI < maxStepLength && maxStepAtI>0){ maxStepLength = maxStepAtI; id_uqn = id; } } } offset += NCells; } // Add automatic damping for abnormally high number of iterations to force convergence bool automaticDampingWithItertion = false; // skip the below for now; the method did not seem to stabilize ill-posed cases if(automaticDampingWithItertion){ real_t minDamping = 0.1; len_t itMax = 100; len_t itThresh = 30; if(iteration>itThresh) maxStepLength *= std::max(minDamping, 1.0 - ((1.0-minDamping)*(iteration-itThresh))/(itMax-itThresh)); } return maxStepLength; } /** * Update the current solution with the Newton step 'dx'. * * dx: Newton step to take. */ const real_t *SolverNonLinear::UpdateSolution(const real_t *dx) { len_t id_uqn; real_t dampingFactor = MaximalPhysicalStepLength(x0,dx,iteration,nontrivial_unknowns,unknowns,ionHandler,id_uqn); if(dampingFactor < 1 && this->Verbose()) { DREAM::IO::PrintInfo(); DREAM::IO::PrintInfo("Newton iteration dynamically damped for unknown quantity: %s",unknowns->GetUnknown(id_uqn)->GetName().c_str()); DREAM::IO::PrintInfo("to conserve positivity, by a factor: %e", dampingFactor); DREAM::IO::PrintInfo(); } for (len_t i = 0; i < this->matrix_size; i++) this->x1[i] = this->x0[i] - dampingFactor*dx[i]; return this->x1; } /** * Print timing information after the solve. */ void SolverNonLinear::PrintTimings() { this->timeKeeper->PrintTimings(true, 0); this->Solver::PrintTimings_rebuild(); } /** * Save timing information to the given SFile object. * * sf: SFile object to save timing information to. * path: Path in file to save timing information to. */ void SolverNonLinear::SaveTimings(SFile *sf, const string& path) { this->timeKeeper->SaveTimings(sf, path); sf->CreateStruct(path+"/rebuild"); this->Solver::SaveTimings_rebuild(sf, path+"/rebuild"); } /** * Save debugging information for the current iteration, * _before_ the new solution has been calculated. * * iTimeStep: Current time step index. * iIteration: Current iteration index. */ void SolverNonLinear::SaveDebugInfoBefore( len_t iTimeStep, len_t iIteration ) { if ((this->savetimestep == iTimeStep && (this->saveiteration == iIteration || this->saveiteration == 0)) || this->savetimestep == 0) { string suffix = "_" + to_string(iTimeStep) + "_" + to_string(iIteration); if (this->savejacobian) { string jacname; if (this->savetimestep == 0 || this->saveiteration == 0) jacname = "petsc_jac" + suffix; else jacname = "petsc_jac"; SaveJacobian(jacname); } if (this->savevector) { string resname; if (this->savetimestep == 0 || this->saveiteration == 0) resname = "residual" + suffix + ".mat"; else resname = "residual.mat"; real_t *fvec; VecGetArray(this->petsc_F, &fvec); SFile *sf = SFile::Create(resname, SFILE_MODE_WRITE); sf->WriteList("F", fvec, this->jacobian->GetNRows()); sf->Close(); VecRestoreArray(this->petsc_F, &fvec); } if (this->savenumjac) { string jacname; if (this->savetimestep == 0 || this->saveiteration == 0) jacname = "petsc_jac" + suffix; else jacname = "petsc_jac"; SaveNumericalJacobian(jacname); } if (this->printjacobianinfo) this->jacobian->PrintInfo(); } } /** * Save debugging information for the current iteration, * _after_ the new solution has been calculated. * * iTimeStep: Current time step index. * iIteration: Current iteration index. */ void SolverNonLinear::SaveDebugInfoAfter( len_t iTimeStep, len_t iIteration ) { if ((this->savetimestep == iTimeStep && (this->saveiteration == iIteration || this->saveiteration == 0)) || this->savetimestep == 0) { string suffix = "_" + to_string(iTimeStep) + "_" + to_string(iIteration); if (this->savesolution) { string solname = "solution_dx"; if (this->savetimestep == 0 || this->saveiteration == 0) solname += suffix; solname += ".mat"; real_t *xvec; VecGetArray(this->petsc_dx, &xvec); SFile *sf = SFile::Create(solname, SFILE_MODE_WRITE); sf->WriteList("dx", xvec, this->jacobian->GetNRows()); sf->Close(); VecRestoreArray(this->petsc_dx, &xvec); } // Save full output? if (this->savesystem) { string outname = "debugout"; if (this->savetimestep == 0 || this->saveiteration == 0) outname += suffix; outname += ".h5"; OutputGeneratorSFile *outgen = new OutputGeneratorSFile(this->eqsys, outname); outgen->SaveCurrent(); delete outgen; } } } /** * Enable or disable debug mode. * * printjacobianinfo: If true, prints detailed debug information about the * PETSc matrix for the jacobian in every iteration. * savejacobian: If true, saves the jacobian using a PETSc viewer in * the specified time step(s). * savesolution: If true, saves the solution vector in the specified * time step(s). * savevector: If true, saves the residual vector in the specified * time step(s). * savenumjac: If true, calculates the jacobian numerically and saves * it using a PETSc viewer in the specified time step(s). * timestep: Time step index to save debug info for. If 0, saves * the information in every iteration of every time step. * iteration: Iteration of specified time step to save debug info for. * savesystem: If true, saves the full equation system, including grid information, * to a proper DREAMOutput file. However, only the most recently obtained * solution is saved. * rescaled: If true, saves the rescaled version of the jacobian/solution/residual. */ void SolverNonLinear::SetDebugMode( bool printjacobianinfo, bool savesolution, bool savejacobian, bool savevector, bool savenumjac, int_t timestep, int_t iteration, bool savesystem, bool rescaled ) { this->printjacobianinfo = printjacobianinfo; this->savejacobian = savejacobian; this->savesolution = savesolution; this->savevector = savevector; this->savenumjac = savenumjac; this->savetimestep = timestep; this->saveiteration = iteration; this->savesystem = savesystem; this->debugrescaled = rescaled; } /** * Override switch to backup inverter. */ void SolverNonLinear::SwitchToBackupInverter() { // Switch inverter to use this->Solver::SwitchToBackupInverter(); // Restore solution to initial guess for time step this->ResetSolution(); } /** * Write basic data from the solver to the output file. * This data is mainly statistics about the solution. * * sf: SFile object to use for writing. * name: Name of group within file to store data in. */ void SolverNonLinear::WriteDataSFile(SFile *sf, const std::string& name) { sf->CreateStruct(name); int32_t type = (int32_t)OptionConstants::SOLVER_TYPE_NONLINEAR; sf->WriteList(name+"/type", &type, 1); // Number of iterations per time step sf->WriteList(name+"/iterations", this->nIterations.data(), this->nIterations.size()); // Whether or not backup inverter was used for a given time step len_t nubi = this->usedBackupInverter.size(); int32_t *ubi = new int32_t[nubi]; for (len_t i = 0; i < nubi; i++) ubi[i] = this->usedBackupInverter[i] ? 1 : 0; sf->WriteList(name+"/backupinverter", ubi, nubi); delete [] ubi; }
32.72191
204
0.671646
11fe9a58a48bcc51367fa66399833a89d61dfc03
10,976
cpp
C++
bindings/c/test/mako/operations.cpp
BearerPipelineTest/foundationdb
02fc80f12eb7bbb94a12469b2ca066f33bd23aa8
[ "Apache-2.0" ]
1
2022-02-23T07:17:32.000Z
2022-02-23T07:17:32.000Z
bindings/c/test/mako/operations.cpp
BearerPipelineTest/foundationdb
02fc80f12eb7bbb94a12469b2ca066f33bd23aa8
[ "Apache-2.0" ]
null
null
null
bindings/c/test/mako/operations.cpp
BearerPipelineTest/foundationdb
02fc80f12eb7bbb94a12469b2ca066f33bd23aa8
[ "Apache-2.0" ]
1
2022-03-01T12:28:03.000Z
2022-03-01T12:28:03.000Z
/* * operations.cpp * * This source file is part of the FoundationDB open source project * * Copyright 2013-2022 Apple Inc. and the FoundationDB project authors * * 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 "blob_granules.hpp" #include "operations.hpp" #include "mako.hpp" #include "logger.hpp" #include "utils.hpp" #include <array> extern thread_local mako::Logger logr; namespace mako { using namespace fdb; const std::array<Operation, MAX_OP> opTable{ { { "GRV", { { StepKind::READ, [](Transaction& tx, Arguments const&, ByteString&, ByteString&, ByteString&) { return tx.getReadVersion().eraseType(); }, [](Future& f, Transaction&, Arguments const&, ByteString&, ByteString&, ByteString&) { if (f && !f.error()) { f.get<future_var::Int64>(); } } } }, 1, false }, { "GET", { { StepKind::READ, [](Transaction& tx, Arguments const& args, ByteString& key, ByteString&, ByteString&) { return tx.get(key, false /*snapshot*/).eraseType(); }, [](Future& f, Transaction&, Arguments const&, ByteString&, ByteString&, ByteString& val) { if (f && !f.error()) { f.get<future_var::Value>(); } } } }, 1, false }, { "GETRANGE", { { StepKind::READ, [](Transaction& tx, Arguments const& args, ByteString& begin, ByteString& end, ByteString&) { return tx .getRange(key_select::firstGreaterOrEqual(begin), key_select::lastLessOrEqual(end, 1), 0 /*limit*/, 0 /*target_bytes*/, args.streaming_mode, 0 /*iteration*/, false /*snapshot*/, args.txnspec.ops[OP_GETRANGE][OP_REVERSE]) .eraseType(); }, [](Future& f, Transaction&, Arguments const&, ByteString&, ByteString&, ByteString& val) { if (f && !f.error()) { f.get<future_var::KeyValueArray>(); } } } }, 1, false }, { "SGET", { { StepKind::READ, [](Transaction& tx, Arguments const& args, ByteString& key, ByteString&, ByteString&) { return tx.get(key, true /*snapshot*/).eraseType(); }, [](Future& f, Transaction&, Arguments const&, ByteString&, ByteString&, ByteString& val) { if (f && !f.error()) { f.get<future_var::Value>(); } } } }, 1, false }, { "SGETRANGE", { { StepKind::READ, [](Transaction& tx, Arguments const& args, ByteString& begin, ByteString& end, ByteString&) { return tx .getRange(key_select::firstGreaterOrEqual(begin), key_select::lastLessOrEqual(end, 1), 0 /*limit*/, 0 /*target_bytes*/, args.streaming_mode, 0 /*iteration*/, true /*snapshot*/, args.txnspec.ops[OP_GETRANGE][OP_REVERSE]) .eraseType(); }, [](Future& f, Transaction&, Arguments const&, ByteString&, ByteString&, ByteString& val) { if (f && !f.error()) { f.get<future_var::KeyValueArray>(); } } } }, 1, false }, { "UPDATE", { { StepKind::READ, [](Transaction& tx, Arguments const& args, ByteString& key, ByteString&, ByteString&) { return tx.get(key, false /*snapshot*/).eraseType(); }, [](Future& f, Transaction&, Arguments const&, ByteString&, ByteString&, ByteString& val) { if (f && !f.error()) { f.get<future_var::Value>(); } } }, { StepKind::IMM, [](Transaction& tx, Arguments const& args, ByteString& key, ByteString&, ByteString& value) { randomString(value.data(), args.value_length); tx.set(key, value); return Future(); } } }, 2, true }, { "INSERT", { { StepKind::IMM, [](Transaction& tx, Arguments const& args, ByteString& key, ByteString&, ByteString& value) { // key[0..args.key_length] := concat(key_prefix, random_string) randomString(key.data() + intSize(KEY_PREFIX), args.key_length - intSize(KEY_PREFIX)); randomString(value.data(), args.value_length); tx.set(key, value); return Future(); } } }, 1, true }, { "INSERTRANGE", { { StepKind::IMM, [](Transaction& tx, Arguments const& args, ByteString& key, ByteString&, ByteString& value) { randomString(value.data(), args.value_length); // key[0..args.key_length] := concat(prefix, random_string, num[0..range_digits]) const auto range = args.txnspec.ops[OP_INSERTRANGE][OP_RANGE]; assert(range > 0); const auto range_digits = digits(range); const auto random_len = args.key_length - intSize(KEY_PREFIX) - range_digits; randomString(&key[intSize(KEY_PREFIX)], random_len); for (auto i = 0; i < range; i++) { numericWithFill(&key[args.key_length - range_digits], range_digits, i); tx.set(key, value); } return Future(); } } }, 1, true }, { "OVERWRITE", { { StepKind::IMM, [](Transaction& tx, Arguments const& args, ByteString& key, ByteString&, ByteString& value) { randomString(value.data(), args.value_length); tx.set(key, value); return Future(); } } }, 1, true }, { "CLEAR", { { StepKind::IMM, [](Transaction& tx, Arguments const& args, ByteString& key, ByteString&, ByteString&) { tx.clear(key); return Future(); } } }, 1, true }, { "SETCLEAR", { { StepKind::COMMIT, [](Transaction& tx, Arguments const& args, ByteString& key, ByteString&, ByteString& value) { randomString(&key[KEY_PREFIX.size()], args.key_length - intSize(KEY_PREFIX)); randomString(value.data(), args.value_length); tx.set(key, value); return tx.commit().eraseType(); } }, { StepKind::IMM, [](Transaction& tx, Arguments const& args, ByteString& key, ByteString&, ByteString&) { tx.reset(); // assuming commit from step 0 worked. tx.clear(key); // key should forward unchanged from step 0 return Future(); } } }, 2, true }, { "CLEARRANGE", { { StepKind::IMM, [](Transaction& tx, Arguments const& args, ByteString& begin, ByteString& end, ByteString&) { tx.clearRange(begin, end); return Future(); } } }, 1, true }, { "SETCLEARRANGE", { { StepKind::COMMIT, [](Transaction& tx, Arguments const& args, ByteString& key_begin, ByteString& key, ByteString& value) { randomString(value.data(), args.value_length); // key[0..args.key_length] := concat(prefix, random_string, num[0..range_digits]) const auto range = args.txnspec.ops[OP_SETCLEARRANGE][OP_RANGE]; assert(range > 0); const auto range_digits = digits(range); const auto random_len = args.key_length - intSize(KEY_PREFIX) - range_digits; randomString(&key[KEY_PREFIX.size()], random_len); for (auto i = 0; i < range; i++) { numericWithFill(&key[args.key_length - range_digits], range_digits, i); tx.set(key, value); if (i == 0) key_begin.assign(key); } return tx.commit().eraseType(); } }, { StepKind::IMM, [](Transaction& tx, Arguments const& args, ByteString& begin, ByteString& end, ByteString&) { tx.reset(); tx.clearRange(begin, end); return Future(); } } }, 2, true }, { "COMMIT", { { StepKind::NONE, nullptr } }, 0, false }, { "TRANSACTION", { { StepKind::NONE, nullptr } }, 0, false }, { "READBLOBGRANULE", { { StepKind::ON_ERROR, [](Transaction& tx, Arguments const& args, ByteString& begin, ByteString& end, ByteString&) { auto err = Error{}; err = tx.setOptionNothrow(FDB_TR_OPTION_READ_YOUR_WRITES_DISABLE, BytesRef()); if (err) { // Issuing read/writes before disabling RYW results in error. // Possible malformed workload? // As workloads execute in sequence, retrying would likely repeat this error. fmt::print(stderr, "ERROR: TR_OPTION_READ_YOUR_WRITES_DISABLE: {}", err.what()); return Future(); } // Allocate a separate context per call to avoid multiple threads accessing auto user_context = blob_granules::local_file::UserContext(args.bg_file_path); auto api_context = blob_granules::local_file::createApiContext(user_context, args.bg_materialize_files); auto r = tx.readBlobGranules(begin, end, 0 /* beginVersion*/, -2, /* endVersion. -2 (latestVersion) is use txn read version */ api_context); user_context.clear(); auto out = Result::KeyValueArray{}; err = r.getKeyValueArrayNothrow(out); if (!err || err.is(2037 /*blob_granule_not_materialized*/)) return Future(); const auto level = (err.is(1020 /*not_committed*/) || err.is(1021 /*commit_unknown_result*/) || err.is(1213 /*tag_throttled*/)) ? VERBOSE_WARN : VERBOSE_NONE; logr.printWithLogLevel(level, "ERROR", "get_keyvalue_array() after readBlobGranules(): {}", err.what()); return tx.onError(err).eraseType(); } } }, 1, false } } }; } // namespace mako
39.768116
117
0.52961
11fef5edd78a78f36c6e940c3d169c9fa005b273
5,082
cc
C++
ecs/src/model/DescribeSnapshotGroupsRequest.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
ecs/src/model/DescribeSnapshotGroupsRequest.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
ecs/src/model/DescribeSnapshotGroupsRequest.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/ecs/model/DescribeSnapshotGroupsRequest.h> using AlibabaCloud::Ecs::Model::DescribeSnapshotGroupsRequest; DescribeSnapshotGroupsRequest::DescribeSnapshotGroupsRequest() : RpcServiceRequest("ecs", "2014-05-26", "DescribeSnapshotGroups") { setMethod(HttpRequest::Method::Post); } DescribeSnapshotGroupsRequest::~DescribeSnapshotGroupsRequest() {} long DescribeSnapshotGroupsRequest::getResourceOwnerId() const { return resourceOwnerId_; } void DescribeSnapshotGroupsRequest::setResourceOwnerId(long resourceOwnerId) { resourceOwnerId_ = resourceOwnerId; setParameter(std::string("ResourceOwnerId"), std::to_string(resourceOwnerId)); } std::string DescribeSnapshotGroupsRequest::getResourceGroupId() const { return resourceGroupId_; } void DescribeSnapshotGroupsRequest::setResourceGroupId(const std::string &resourceGroupId) { resourceGroupId_ = resourceGroupId; setParameter(std::string("ResourceGroupId"), resourceGroupId); } std::string DescribeSnapshotGroupsRequest::getRegionId() const { return regionId_; } void DescribeSnapshotGroupsRequest::setRegionId(const std::string &regionId) { regionId_ = regionId; setParameter(std::string("RegionId"), regionId); } std::string DescribeSnapshotGroupsRequest::getNextToken() const { return nextToken_; } void DescribeSnapshotGroupsRequest::setNextToken(const std::string &nextToken) { nextToken_ = nextToken; setParameter(std::string("NextToken"), nextToken); } std::vector<DescribeSnapshotGroupsRequest::Tag> DescribeSnapshotGroupsRequest::getTag() const { return tag_; } void DescribeSnapshotGroupsRequest::setTag(const std::vector<DescribeSnapshotGroupsRequest::Tag> &tag) { tag_ = tag; for(int dep1 = 0; dep1 != tag.size(); dep1++) { auto tagObj = tag.at(dep1); std::string tagObjStr = std::string("Tag") + "." + std::to_string(dep1 + 1); setParameter(tagObjStr + ".Key", tagObj.key); setParameter(tagObjStr + ".Value", tagObj.value); } } std::string DescribeSnapshotGroupsRequest::getResourceOwnerAccount() const { return resourceOwnerAccount_; } void DescribeSnapshotGroupsRequest::setResourceOwnerAccount(const std::string &resourceOwnerAccount) { resourceOwnerAccount_ = resourceOwnerAccount; setParameter(std::string("ResourceOwnerAccount"), resourceOwnerAccount); } std::string DescribeSnapshotGroupsRequest::getOwnerAccount() const { return ownerAccount_; } void DescribeSnapshotGroupsRequest::setOwnerAccount(const std::string &ownerAccount) { ownerAccount_ = ownerAccount; setParameter(std::string("OwnerAccount"), ownerAccount); } std::vector<std::string> DescribeSnapshotGroupsRequest::getSnapshotGroupId() const { return snapshotGroupId_; } void DescribeSnapshotGroupsRequest::setSnapshotGroupId(const std::vector<std::string> &snapshotGroupId) { snapshotGroupId_ = snapshotGroupId; } long DescribeSnapshotGroupsRequest::getOwnerId() const { return ownerId_; } void DescribeSnapshotGroupsRequest::setOwnerId(long ownerId) { ownerId_ = ownerId; setParameter(std::string("OwnerId"), std::to_string(ownerId)); } std::vector<std::string> DescribeSnapshotGroupsRequest::getAdditionalAttributes() const { return additionalAttributes_; } void DescribeSnapshotGroupsRequest::setAdditionalAttributes(const std::vector<std::string> &additionalAttributes) { additionalAttributes_ = additionalAttributes; } std::string DescribeSnapshotGroupsRequest::getInstanceId() const { return instanceId_; } void DescribeSnapshotGroupsRequest::setInstanceId(const std::string &instanceId) { instanceId_ = instanceId; setParameter(std::string("InstanceId"), instanceId); } std::string DescribeSnapshotGroupsRequest::getName() const { return name_; } void DescribeSnapshotGroupsRequest::setName(const std::string &name) { name_ = name; setParameter(std::string("Name"), name); } int DescribeSnapshotGroupsRequest::getMaxResults() const { return maxResults_; } void DescribeSnapshotGroupsRequest::setMaxResults(int maxResults) { maxResults_ = maxResults; setParameter(std::string("MaxResults"), std::to_string(maxResults)); } std::vector<std::string> DescribeSnapshotGroupsRequest::getStatus() const { return status_; } void DescribeSnapshotGroupsRequest::setStatus(const std::vector<std::string> &status) { status_ = status; }
32.576923
116
0.757182
f501f8e3f8c6c1e95b27c22e5aa52ac6d8439695
162
cpp
C++
test/example_divide.cpp
justasbr/cmake-example
ba059e8d24d8c92e779e9f04317fa15825869826
[ "BSD-3-Clause" ]
null
null
null
test/example_divide.cpp
justasbr/cmake-example
ba059e8d24d8c92e779e9f04317fa15825869826
[ "BSD-3-Clause" ]
null
null
null
test/example_divide.cpp
justasbr/cmake-example
ba059e8d24d8c92e779e9f04317fa15825869826
[ "BSD-3-Clause" ]
null
null
null
#include "gtest/gtest.h" #include "example.h" TEST(example, divide) { double res; res = divide_numbers(10.0, 2.0); ASSERT_NEAR(res, 5.0, 1.0e-11); }
16.2
36
0.62963
f502ee1deac07713d6f8eac80c65fe975c84cea6
1,976
cpp
C++
avx512-string/speed_strrchr.cpp
demonMOE-s/Toys
09ddd7e3f1d3956427c2f3d9e99ca05fc63c177e
[ "BSD-2-Clause" ]
2
2019-01-06T05:32:18.000Z
2019-12-12T04:54:56.000Z
avx512-string/speed_strrchr.cpp
demonMOE-s/Toys
09ddd7e3f1d3956427c2f3d9e99ca05fc63c177e
[ "BSD-2-Clause" ]
null
null
null
avx512-string/speed_strrchr.cpp
demonMOE-s/Toys
09ddd7e3f1d3956427c2f3d9e99ca05fc63c177e
[ "BSD-2-Clause" ]
null
null
null
#include <cstdlib> #include <cstdio> #include <cstdint> #include <cstring> #include <cassert> #include <immintrin.h> #include "gettime.cpp" #include "avx512f-strrchr.cpp" class TestCase { private: char* buffer; size_t size; volatile size_t count; public: TestCase(size_t s) : size(s) { buffer = new char[s + 64]; memset(buffer, '?', s + 64); buffer[s - 1] = 0; } ~TestCase() { delete[] buffer; } public: template <typename STRCHR> void run(STRCHR strrchr_function) { for (size_t i=0; i < size; i++) { buffer[i] = 'X'; count += int(strrchr_function(buffer, 'X') != NULL); buffer[i] = '?'; } } void run_std_function() { for (size_t i=0; i < size; i++) { buffer[i] = 'X'; count += int(strrchr(buffer, 'X') != NULL); buffer[i] = '?'; } } }; class Test { size_t size; size_t iterations; uint32_t ref_time; public: Test(size_t size, size_t iterations) : size(size) , iterations(iterations) , ref_time(0) {} template <typename STRCHR> void measure(const char* name, STRCHR strrchr_function) { printf("%-20s [", name); fflush(stdout); TestCase test(size); const uint32_t t1 = get_time(); for (size_t i=0; i < iterations; i++) { putchar('.'); fflush(stdout); test.run(strrchr_function); } const uint32_t t2 = get_time(); const uint32_t time = t2 - t1; printf("] %0.4f s", time/1000000.0); if (ref_time == 0) { ref_time = time; } else { printf(" (%0.2f)", ref_time/double(time)); } putchar('\n'); } }; int main() { Test test(10*1024, 5); test.measure("std::strrchr", [](const char* s, int c){return strrchr(s, c);}); test.measure("AVX512F", avx512f_strrchr); }
19.76
82
0.520243
f5034e6203be2938ccfe99db5b1475da39f48d1c
10,595
cpp
C++
QtMainWindow.cpp
nvoronin1337/Qt-Database-Management-System
07ab5796f61eb95a90fef7c6e15d3048ae4549d5
[ "MIT" ]
null
null
null
QtMainWindow.cpp
nvoronin1337/Qt-Database-Management-System
07ab5796f61eb95a90fef7c6e15d3048ae4549d5
[ "MIT" ]
null
null
null
QtMainWindow.cpp
nvoronin1337/Qt-Database-Management-System
07ab5796f61eb95a90fef7c6e15d3048ae4549d5
[ "MIT" ]
null
null
null
#include "QtMainWindow.h" QtMainWindow::QtMainWindow(const std::string username, QWidget* parent) : QMainWindow(parent) { setupUi(this); this->username = username; this->user = new GuiUser(username); std::string fileName = username + "_form_gui.txt"; std::string title = "Data Hive | User: " + username; setWindowTitle(QString::fromStdString(title)); QStringList headers; headers << tr("Title") << tr("Description") << tr("Date Modified"); QFile file(QString::fromStdString(fileName)); file.open(QIODevice::ReadOnly); tree_model = new TreeModel(headers, file.readAll()); tree_model_selection = new QItemSelectionModel(tree_model); file.close(); treeView->header()->setStyleSheet("::section{ background-color: #424242;}"); treeView->setHeaderHidden(false); treeView->setModel(tree_model); treeView->setSelectionModel(tree_model_selection); for (int column = 0; column < tree_model->columnCount(); ++column) treeView->resizeColumnToContents(column); setupSlots(); } QtMainWindow::~QtMainWindow() { saveModelData(true); } void QtMainWindow::populateSimpleTreeFromStorage() const { QStandardItem* db_item; QStandardItem* table_item; QStandardItem* action1; QList<QStandardItem*> items; QStandardItemModel *tree_model = new QStandardItemModel(); /** * Loop through the Storage. For each database add an item to the tree. */ for (size_t i = 0; i < user->getStorageManager()->getStorage()->databases.size(); i++) { db_item = new QStandardItem(QIcon("dbIcon.png"), QString::fromStdString(user->getStorageManager()->getStorage()->databases[i]->databaseName)); action1 = new QStandardItem(QIcon("deleteIcon.png"), QString::fromStdString("")); items.append(db_item); items.append(action1); tree_model->appendRow(items); items.clear(); // Loop through the database. For each table add an item to the tree. for (size_t k = 0; k < user->getStorageManager()->getStorage()->databases[i]->tables.size(); k++) { table_item = new QStandardItem(QIcon("tableIcon.png"), QString::fromStdString(user->getStorageManager()->getStorage()->databases[i]->tables[k]->tableName)); action1 = new QStandardItem(QIcon("deleteIcon.png"), QString::fromStdString("")); items.append(table_item); items.append(action1); db_item->appendRow(items); items.clear(); } } treeView->setModel(tree_model); QModelIndex child_index = tree_model->index(0,0); tree_model->item(0, 0)->removeRow(0); } void QtMainWindow::setupSlots() noexcept { connect(readMeAction, &QAction::triggered, this, &QtMainWindow::openUrl); connect(treeView->selectionModel(), &QItemSelectionModel::selectionChanged, this, &QtMainWindow::updateActions); connect(menuActions, &QMenu::aboutToShow, this, &QtMainWindow::updateActions); connect(insertRowAction, &QAction::triggered, this, &QtMainWindow::insertRow); connect(insertColumnAction, &QAction::triggered, this, &QtMainWindow::insertColumn); connect(removeRowAction, &QAction::triggered, this, &QtMainWindow::removeRow); connect(removeColumnAction, &QAction::triggered, this, &QtMainWindow::removeColumn); connect(insertChildAction, &QAction::triggered, this, &QtMainWindow::insertChild); connect(btnSave, SIGNAL(pressed()), this, SLOT(saveModelData())); connect(btnDetails, SIGNAL(pressed()), this, SLOT(btn_details_pressed())); updateActions(); } void QtMainWindow::writeItemData(QVector<QVariant> item_data, bool isChild) const noexcept { std::string filename_str = user->getUsername() + "_form_gui.txt"; QString filename = QString::fromStdString(filename_str); QFile fileout(filename); if (fileout.open(QFile::ReadWrite | QFile::Text | QFile::Append)) { QTextStream out(&fileout); for (QVector<QVariant>::iterator iter = item_data.begin(); iter < item_data.end(); iter++) { if(!isChild) out << iter->toString() << " "; else out << " " << iter->toString() << " "; } out << "\n"; fileout.close(); } } void QtMainWindow::updateUsersStorage(TreeItem* parent,TreeItem* child) const noexcept { auto parent_data = parent->getItemData(); QVector<QVariant>::iterator parent_iter = parent_data.begin(); std::string database_name = parent_iter->toString().toStdString(); // if database -> add database if (child == nullptr) { user->getStorageManager()->addDatabase(database_name); } // if table -> addTable else { auto child_data = child->getItemData(); QVector<QVariant>::iterator child_iter = child_data.begin(); std::string table_name = child_iter->toString().toStdString(); //empty columns for now (better change) std::vector<std::string> cols = { "test" }; user->getStorageManager()->addTableToDatabase(database_name, table_name, cols); } } void QtMainWindow::saveModelData(bool isQuitting) const { user->getStorageManager()->getStorage()->databases.clear(); std::string filename_str = user->getUsername() + "_form_gui.txt"; std::ofstream ofs; ofs.open(filename_str, std::ofstream::out | std::ofstream::trunc); ofs.close(); auto row_max = tree_model->rowCount(); auto column = 0; TreeItem* tree_item; QModelIndex model_index; for (int row = 0; row < row_max; row++) { model_index = tree_model->index(row, column); tree_item = tree_model->getItem(model_index); auto item_data = tree_item->getItemData(); writeItemData(item_data, false); updateUsersStorage(tree_item); if (tree_item->childCount() > 0) { for (int child_num = 0; child_num < tree_item->childCount(); child_num++) { auto childItem = tree_item->child(child_num); writeItemData(childItem->getItemData(), true); updateUsersStorage(tree_item, childItem); } } } auto helper = std::make_unique<dbms::FileIOHelper>(); helper->saveStorageText(user->getStorageManager()->getStorage(), this->user->getUsername() + ".txt"); if (!isQuitting) { QMessageBox msgbox; msgbox.setText("Data is saved!"); msgbox.setStyleSheet("QMessageBox { background-color: #424242; font: 75 italic 12pt \"Gill Sans MT\"; color: rgb(1, 223, 165);}"); msgbox.exec(); } } // DETAILS PRESSED void QtMainWindow::btn_details_pressed() const { QModelIndex index = treeView->selectionModel()->currentIndex(); auto item = tree_model->getItem(index); if (item->childCount() != 0) { QMessageBox msgbox; msgbox.setText("Please select a table!"); msgbox.setStyleSheet("QMessageBox { background-color: #424242; font: 75 italic 12pt \"Gill Sans MT\"; color: rgb(1, 223, 165);}"); msgbox.exec(); return; } auto parent_item = item->parent(); auto parent_item_data = parent_item->getItemData(); auto iter_parent = parent_item_data.begin(); std::string database = iter_parent->toString().toStdString(); auto item_data = item->getItemData(); auto iter = item_data.begin(); std::string table_name = iter->toString().toStdString(); std::unique_ptr<QtTableDetailsDialog> details_dialog = std::make_unique<QtTableDetailsDialog>(database, table_name, user); //Qt::WindowFlags flags(Qt::WindowTitleHint); //details_dialog->setWindowFlags(flags); details_dialog->exec(); } // SLOTS void QtMainWindow::insertChild() { QModelIndex index = treeView->selectionModel()->currentIndex(); QAbstractItemModel* model = treeView->model(); if (model->columnCount(index) == 0) { if (!model->insertColumn(0, index)) return; } if (!model->insertRow(0, index)) return; for (int column = 0; column < model->columnCount(index); ++column) { QModelIndex child = model->index(0, column, index); model->setData(child, QVariant("[No data]"), Qt::EditRole); if (!model->headerData(column, Qt::Horizontal).isValid()) model->setHeaderData(column, Qt::Horizontal, QVariant("[No header]"), Qt::EditRole); } treeView->selectionModel()->setCurrentIndex(model->index(0, 0, index), QItemSelectionModel::ClearAndSelect); updateActions(); } bool QtMainWindow::insertColumn() { QAbstractItemModel* model = treeView->model(); int column = treeView->selectionModel()->currentIndex().column(); // Insert a column in the parent item. bool changed = model->insertColumn(column + 1); if (changed) model->setHeaderData(column + 1, Qt::Horizontal, QVariant("[No header]"), Qt::EditRole); updateActions(); return changed; } void QtMainWindow::insertRow() { QModelIndex index = treeView->selectionModel()->currentIndex(); QAbstractItemModel* model = treeView->model(); if (!model->insertRow(index.row() + 1, index.parent())) return; updateActions(); for (int column = 0; column < model->columnCount(index.parent()); ++column) { QModelIndex child = model->index(index.row() + 1, column, index.parent()); model->setData(child, QVariant("[No data]"), Qt::EditRole); } } bool QtMainWindow::removeColumn() { QAbstractItemModel* model = treeView->model(); int column = treeView->selectionModel()->currentIndex().column(); // Insert columns in each child of the parent item. bool changed = model->removeColumn(column); if (changed) updateActions(); return changed; } void QtMainWindow::removeRow() { QModelIndex index = treeView->selectionModel()->currentIndex(); QAbstractItemModel* model = treeView->model(); if (model->removeRow(index.row(), index.parent())) updateActions(); } bool QtMainWindow::openUrl() { return QDesktopServices::openUrl(QUrl("file:///C:/Users/Nikita/source/repos/QtGuiDBMS_v4_0/QtGuiApplication1/html/annotated.html", QUrl::TolerantMode)); } void QtMainWindow::updateActions() { bool hasSelection = !treeView->selectionModel()->selection().isEmpty(); removeRowAction->setEnabled(hasSelection); removeColumnAction->setEnabled(hasSelection); bool hasCurrent = treeView->selectionModel()->currentIndex().isValid(); insertRowAction->setEnabled(hasCurrent); insertColumnAction->setEnabled(hasCurrent); if (hasCurrent) { treeView->closePersistentEditor(treeView->selectionModel()->currentIndex()); int row = treeView->selectionModel()->currentIndex().row(); int column = treeView->selectionModel()->currentIndex().column(); if (treeView->selectionModel()->currentIndex().parent().isValid()) Ui::QtGuiApplication1Class::statusBar->showMessage(tr("Position: (%1,%2)").arg(row).arg(column)); else Ui::QtGuiApplication1Class::statusBar->showMessage(tr("Position: (%1,%2) in top level").arg(row).arg(column)); } }
32.400612
160
0.695422
f50379b3edb9761db1e8ac54cdd79386bea95457
8,374
cpp
C++
android/android_9/frameworks/native/libs/gui/BufferItem.cpp
yakuizhao/intel-vaapi-driver
b2bb0383352694941826543a171b557efac2219b
[ "MIT" ]
null
null
null
android/android_9/frameworks/native/libs/gui/BufferItem.cpp
yakuizhao/intel-vaapi-driver
b2bb0383352694941826543a171b557efac2219b
[ "MIT" ]
null
null
null
android/android_9/frameworks/native/libs/gui/BufferItem.cpp
yakuizhao/intel-vaapi-driver
b2bb0383352694941826543a171b557efac2219b
[ "MIT" ]
null
null
null
/* * Copyright 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <gui/BufferItem.h> #include <ui/Fence.h> #include <ui/GraphicBuffer.h> #include <system/window.h> namespace android { template<typename T> static inline constexpr uint32_t low32(const T n) { return static_cast<uint32_t>(static_cast<uint64_t>(n)); } template<typename T> static inline constexpr uint32_t high32(const T n) { return static_cast<uint32_t>(static_cast<uint64_t>(n)>>32); } template<typename T> static inline constexpr T to64(const uint32_t lo, const uint32_t hi) { return static_cast<T>(static_cast<uint64_t>(hi)<<32 | lo); } BufferItem::BufferItem() : mGraphicBuffer(NULL), mFence(NULL), mCrop(Rect::INVALID_RECT), mTransform(0), mScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE), mTimestamp(0), mIsAutoTimestamp(false), mDataSpace(HAL_DATASPACE_UNKNOWN), mFrameNumber(0), mSlot(INVALID_BUFFER_SLOT), mIsDroppable(false), mAcquireCalled(false), mTransformToDisplayInverse(false), mSurfaceDamage(), mAutoRefresh(false), mQueuedBuffer(true), mIsStale(false), mApi(0) { } BufferItem::~BufferItem() {} template <typename T> static void addAligned(size_t& size, T /* value */) { size = FlattenableUtils::align<sizeof(T)>(size); size += sizeof(T); } size_t BufferItem::getPodSize() const { size_t size = 0; addAligned(size, mCrop); addAligned(size, mTransform); addAligned(size, mScalingMode); addAligned(size, low32(mTimestamp)); addAligned(size, high32(mTimestamp)); addAligned(size, mIsAutoTimestamp); addAligned(size, mDataSpace); addAligned(size, low32(mFrameNumber)); addAligned(size, high32(mFrameNumber)); addAligned(size, mSlot); addAligned(size, mIsDroppable); addAligned(size, mAcquireCalled); addAligned(size, mTransformToDisplayInverse); addAligned(size, mAutoRefresh); addAligned(size, mQueuedBuffer); addAligned(size, mIsStale); addAligned(size, mApi); return size; } size_t BufferItem::getFlattenedSize() const { size_t size = sizeof(uint32_t); // Flags if (mGraphicBuffer != 0) { size += mGraphicBuffer->getFlattenedSize(); size = FlattenableUtils::align<4>(size); } if (mFence != 0) { size += mFence->getFlattenedSize(); size = FlattenableUtils::align<4>(size); } size += mSurfaceDamage.getFlattenedSize(); size += mHdrMetadata.getFlattenedSize(); size = FlattenableUtils::align<8>(size); return size + getPodSize(); } size_t BufferItem::getFdCount() const { size_t count = 0; if (mGraphicBuffer != 0) { count += mGraphicBuffer->getFdCount(); } if (mFence != 0) { count += mFence->getFdCount(); } return count; } template <typename T> static void writeAligned(void*& buffer, size_t& size, T value) { size -= FlattenableUtils::align<alignof(T)>(buffer); FlattenableUtils::write(buffer, size, value); } status_t BufferItem::flatten( void*& buffer, size_t& size, int*& fds, size_t& count) const { // make sure we have enough space if (size < BufferItem::getFlattenedSize()) { return NO_MEMORY; } // content flags are stored first uint32_t& flags = *static_cast<uint32_t*>(buffer); // advance the pointer FlattenableUtils::advance(buffer, size, sizeof(uint32_t)); flags = 0; if (mGraphicBuffer != 0) { status_t err = mGraphicBuffer->flatten(buffer, size, fds, count); if (err) return err; size -= FlattenableUtils::align<4>(buffer); flags |= 1; } if (mFence != 0) { status_t err = mFence->flatten(buffer, size, fds, count); if (err) return err; size -= FlattenableUtils::align<4>(buffer); flags |= 2; } status_t err = mSurfaceDamage.flatten(buffer, size); if (err) return err; FlattenableUtils::advance(buffer, size, mSurfaceDamage.getFlattenedSize()); err = mHdrMetadata.flatten(buffer, size); if (err) return err; FlattenableUtils::advance(buffer, size, mHdrMetadata.getFlattenedSize()); // Check we still have enough space if (size < getPodSize()) { return NO_MEMORY; } writeAligned(buffer, size, mCrop); writeAligned(buffer, size, mTransform); writeAligned(buffer, size, mScalingMode); writeAligned(buffer, size, low32(mTimestamp)); writeAligned(buffer, size, high32(mTimestamp)); writeAligned(buffer, size, mIsAutoTimestamp); writeAligned(buffer, size, mDataSpace); writeAligned(buffer, size, low32(mFrameNumber)); writeAligned(buffer, size, high32(mFrameNumber)); writeAligned(buffer, size, mSlot); writeAligned(buffer, size, mIsDroppable); writeAligned(buffer, size, mAcquireCalled); writeAligned(buffer, size, mTransformToDisplayInverse); writeAligned(buffer, size, mAutoRefresh); writeAligned(buffer, size, mQueuedBuffer); writeAligned(buffer, size, mIsStale); writeAligned(buffer, size, mApi); return NO_ERROR; } template <typename T> static void readAligned(const void*& buffer, size_t& size, T& value) { size -= FlattenableUtils::align<alignof(T)>(buffer); FlattenableUtils::read(buffer, size, value); } status_t BufferItem::unflatten( void const*& buffer, size_t& size, int const*& fds, size_t& count) { if (size < sizeof(uint32_t)) { return NO_MEMORY; } uint32_t flags = 0; FlattenableUtils::read(buffer, size, flags); if (flags & 1) { mGraphicBuffer = new GraphicBuffer(); status_t err = mGraphicBuffer->unflatten(buffer, size, fds, count); if (err) return err; size -= FlattenableUtils::align<4>(buffer); } if (flags & 2) { mFence = new Fence(); status_t err = mFence->unflatten(buffer, size, fds, count); if (err) return err; size -= FlattenableUtils::align<4>(buffer); mFenceTime = std::make_shared<FenceTime>(mFence); } status_t err = mSurfaceDamage.unflatten(buffer, size); if (err) return err; FlattenableUtils::advance(buffer, size, mSurfaceDamage.getFlattenedSize()); err = mHdrMetadata.unflatten(buffer, size); if (err) return err; FlattenableUtils::advance(buffer, size, mHdrMetadata.getFlattenedSize()); // Check we still have enough space if (size < getPodSize()) { return NO_MEMORY; } uint32_t timestampLo = 0, timestampHi = 0; uint32_t frameNumberLo = 0, frameNumberHi = 0; readAligned(buffer, size, mCrop); readAligned(buffer, size, mTransform); readAligned(buffer, size, mScalingMode); readAligned(buffer, size, timestampLo); readAligned(buffer, size, timestampHi); mTimestamp = to64<int64_t>(timestampLo, timestampHi); readAligned(buffer, size, mIsAutoTimestamp); readAligned(buffer, size, mDataSpace); readAligned(buffer, size, frameNumberLo); readAligned(buffer, size, frameNumberHi); mFrameNumber = to64<uint64_t>(frameNumberLo, frameNumberHi); readAligned(buffer, size, mSlot); readAligned(buffer, size, mIsDroppable); readAligned(buffer, size, mAcquireCalled); readAligned(buffer, size, mTransformToDisplayInverse); readAligned(buffer, size, mAutoRefresh); readAligned(buffer, size, mQueuedBuffer); readAligned(buffer, size, mIsStale); readAligned(buffer, size, mApi); return NO_ERROR; } const char* BufferItem::scalingModeName(uint32_t scalingMode) { switch (scalingMode) { case NATIVE_WINDOW_SCALING_MODE_FREEZE: return "FREEZE"; case NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW: return "SCALE_TO_WINDOW"; case NATIVE_WINDOW_SCALING_MODE_SCALE_CROP: return "SCALE_CROP"; default: return "Unknown"; } } } // namespace android
31.246269
82
0.682708
f5045c748160ad1a6302eed469cc2b9f98bc8aeb
228
cpp
C++
src/matlab.cpp
git-steb/structural-deformable-models
4706a65e0dc031d16e259e526fd6a55e805855d1
[ "MIT" ]
2
2017-03-01T20:07:09.000Z
2020-07-12T11:02:21.000Z
src/matlab.cpp
git-steb/structural-deformable-models
4706a65e0dc031d16e259e526fd6a55e805855d1
[ "MIT" ]
null
null
null
src/matlab.cpp
git-steb/structural-deformable-models
4706a65e0dc031d16e259e526fd6a55e805855d1
[ "MIT" ]
null
null
null
#include <stdlib.h> #include "common.h" #include "matlab.h" static string matlabprog = "matlab -nojvw -nosplash -nodesktop -r "; int matlabCall(const std::string& cmd) { return system((matlabprog+cmd+", exit").c_str()); }
20.727273
68
0.688596
f5047324f534260cc5a9edba0d1fd55d268966b7
67,031
cpp
C++
libuvccamera/src/main/jni/UVCCamera/serenegiant_usb_UVCCamera.cpp
ChrisRF-W/UVCCamera
1c9614118df7069bd571da77a4cbc6a1cf5d8468
[ "Apache-2.0" ]
1
2021-05-15T08:22:16.000Z
2021-05-15T08:22:16.000Z
libuvccamera/src/main/jni/UVCCamera/serenegiant_usb_UVCCamera.cpp
ChrisRF-W/UVCCamera
1c9614118df7069bd571da77a4cbc6a1cf5d8468
[ "Apache-2.0" ]
null
null
null
libuvccamera/src/main/jni/UVCCamera/serenegiant_usb_UVCCamera.cpp
ChrisRF-W/UVCCamera
1c9614118df7069bd571da77a4cbc6a1cf5d8468
[ "Apache-2.0" ]
1
2021-03-11T06:24:04.000Z
2021-03-11T06:24:04.000Z
/* * UVCCamera * library and sample to access to UVC web camera on non-rooted Android device * * Copyright (c) 2014-2017 saki t_saki@serenegiant.com * * File name: serenegiant_usb_UVCCamera.cpp * * 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. * * All files in the folder are under this Apache License, Version 2.0. * Files in the jni/libjpeg, jni/libusb, jin/libuvc, jni/rapidjson folder may have a different license, see the respective files. */ #if 1 // 不输出调试信息时 #ifndef LOG_NDEBUG #define LOG_NDEBUG // LOGV/LOGD/MARK不输出 #endif #undef USE_LOGALL // 仅输出指定的LOGx #else #define USE_LOGALL #undef LOG_NDEBUG #undef NDEBUG #endif #include <jni.h> #include <android/native_window_jni.h> #include "libUVCCamera.h" #include "UVCCamera.h" #include "libuvc/libuvc_internal.h" /** * set the value into the long field * @param env: this param should not be null * @param bullet_obj: this param should not be null * @param field_name * @params val */ static jlong setField_long(JNIEnv *env, jobject java_obj, const char *field_name, jlong val) { #if LOCAL_DEBUG LOGV("setField_long:"); #endif jclass clazz = env->GetObjectClass(java_obj); jfieldID field = env->GetFieldID(clazz, field_name, "J"); if (LIKELY(field)) env->SetLongField(java_obj, field, val); else { LOGE("__setField_long:field '%s' not found", field_name); } #ifdef ANDROID_NDK env->DeleteLocalRef(clazz); #endif return val; } /** * @param env: this param should not be null * @param bullet_obj: this param should not be null */ static jlong __setField_long(JNIEnv *env, jobject java_obj, jclass clazz, const char *field_name, jlong val) { #if LOCAL_DEBUG LOGV("__setField_long:"); #endif jfieldID field = env->GetFieldID(clazz, field_name, "J"); if (LIKELY(field)) env->SetLongField(java_obj, field, val); else { LOGE("__setField_long:field '%s' not found", field_name); } return val; } /** * @param env: this param should not be null * @param bullet_obj: this param should not be null */ jint __setField_int(JNIEnv *env, jobject java_obj, jclass clazz, const char *field_name, jint val) { LOGV("__setField_int:"); jfieldID id = env->GetFieldID(clazz, field_name, "I"); if (LIKELY(id)) env->SetIntField(java_obj, id, val); else { LOGE("__setField_int:field '%s' not found", field_name); env->ExceptionClear(); // clear java.lang.NoSuchFieldError exception } return val; } /** * set the value into int field * @param env: this param should not be null * @param java_obj: this param should not be null * @param field_name * @params val */ jint setField_int(JNIEnv *env, jobject java_obj, const char *field_name, jint val) { LOGV("setField_int:"); jclass clazz = env->GetObjectClass(java_obj); __setField_int(env, java_obj, clazz, field_name, val); #ifdef ANDROID_NDK env->DeleteLocalRef(clazz); #endif return val; } static ID_TYPE nativeCreate(JNIEnv *env, jobject thiz) { ENTER(); UVCCamera *camera = new UVCCamera(); setField_long(env, thiz, "mNativePtr", reinterpret_cast<ID_TYPE>(camera)); RETURN(reinterpret_cast<ID_TYPE>(camera), ID_TYPE); } // 销毁本机相机对象 static void nativeDestroy(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { ENTER(); setField_long(env, thiz, "mNativePtr", 0); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { SAFE_DELETE(camera); } EXIT(); } //====================================================================== // 设置帧缓存大小 static void nativeFrameBufferSize(JNIEnv *env, jobject thiz, jint frameBufferSize) { frame_buffer_size = (int)frameBufferSize; } // 设置是否丢弃不完整帧 static void nativeDropIncompleteFrame(JNIEnv *env, jobject thiz, jint dropIncompleteFrame) { drop_incomplete_frame = (int)dropIncompleteFrame; } // 设置是否需要水平镜像处理 static void nativeHorizontalMirror(JNIEnv *env, jobject thiz, ID_TYPE id_camera, jint horizontalMirror) { UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { return camera->setHorizontalMirror(horizontalMirror); } } // 设置是否需要垂直镜像处理 static void nativeVerticalMirror(JNIEnv *env, jobject thiz, ID_TYPE id_camera, jint verticalMirror) { UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { return camera->setVerticalMirror(verticalMirror); } } // 设置摄像头自身角度 static void nativeCameraAngle(JNIEnv *env, jobject thiz, ID_TYPE id_camera, jint cameraAngle) { UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { return camera->setCameraAngle(cameraAngle); } } // 连接相机 static jint nativeConnect(JNIEnv *env, jobject thiz, ID_TYPE id_camera, jint vid, jint pid, jint fd, jint busNum, jint devAddr, jstring usbfs_str) { ENTER(); int result = JNI_ERR; UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); const char *c_usbfs = env->GetStringUTFChars(usbfs_str, JNI_FALSE); if (LIKELY(camera && (fd > 0))) { // libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_DEBUG); result = camera->connect(vid, pid, fd, busNum, devAddr, c_usbfs); } env->ReleaseStringUTFChars(usbfs_str, c_usbfs); RETURN(result, jint); } // 断开与相机的连接 static jint nativeRelease(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { ENTER(); int result = JNI_ERR; UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->release(); } RETURN(result, jint); } //====================================================================== static jint nativeSetStatusCallback(JNIEnv *env, jobject thiz, ID_TYPE id_camera, jobject jIStatusCallback) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { jobject status_callback_obj = env->NewGlobalRef(jIStatusCallback); result = camera->setStatusCallback(env, status_callback_obj); } RETURN(result, jint); } static jint nativeSetButtonCallback(JNIEnv *env, jobject thiz, ID_TYPE id_camera, jobject jIButtonCallback) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { jobject button_callback_obj = env->NewGlobalRef(jIButtonCallback); result = camera->setButtonCallback(env, button_callback_obj); } RETURN(result, jint); } static jobject nativeGetSupportedSize(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { ENTER(); jstring result = NULL; UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { char *c_str = camera->getSupportedSize(); if (LIKELY(c_str)) { result = env->NewStringUTF(c_str); free(c_str); } } RETURN(result, jobject); } //====================================================================== // 设定预览画面的大小 static jint nativeSetPreviewSize(JNIEnv *env, jobject thiz, ID_TYPE id_camera, jint width, jint height, jint cameraAngle, jint min_fps, jint max_fps, jint mode, jfloat bandwidth) { ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { return camera->setPreviewSize(width, height, cameraAngle, min_fps, max_fps, mode, bandwidth); } RETURN(JNI_ERR, jint); } static jint nativeStartPreview(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { return camera->startPreview(); } RETURN(JNI_ERR, jint); } // 停止预览 static jint nativeStopPreview(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->stopPreview(); } RETURN(result, jint); } static jint nativeSetPreviewDisplay(JNIEnv *env, jobject thiz, ID_TYPE id_camera, jobject jSurface) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { ANativeWindow *preview_window = jSurface ? ANativeWindow_fromSurface(env, jSurface) : NULL; result = camera->setPreviewDisplay(preview_window); } RETURN(result, jint); } static jint nativeSetFrameCallback(JNIEnv *env, jobject thiz, ID_TYPE id_camera, jobject jIFrameCallback, jint pixel_format) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { jobject frame_callback_obj = env->NewGlobalRef(jIFrameCallback); result = camera->setFrameCallback(env, frame_callback_obj, pixel_format); } RETURN(result, jint); } static jint nativeSetCaptureDisplay(JNIEnv *env, jobject thiz, ID_TYPE id_camera, jobject jSurface) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { ANativeWindow *capture_window = jSurface ? ANativeWindow_fromSurface(env, jSurface) : NULL; result = camera->setCaptureDisplay(capture_window); } RETURN(result, jint); } //====================================================================== // 获取相机控制支持的功能 static jlong nativeGetCtrlSupports(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jlong result = 0; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { uint64_t supports; int r = camera->getCtrlSupports(&supports); if (!r) result = supports; } RETURN(result, jlong); } // 获取处理单元支持的功能 static jlong nativeGetProcSupports(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jlong result = 0; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { uint64_t supports; int r = camera->getProcSupports(&supports); if (!r) result = supports; } RETURN(result, jlong); } //====================================================================== // Java mnethod correspond to this function should not be a static mathod static jint nativeUpdateScanningModeLimit(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { int min, max, def; result = camera->updateScanningModeLimit(min, max, def); if (!result) { // 写入Java端 setField_int(env, thiz, "mScanningModeMin", min); setField_int(env, thiz, "mScanningModeMax", max); setField_int(env, thiz, "mScanningModeDef", def); } } RETURN(result, jint); } static jint nativeSetScanningMode(JNIEnv *env, jobject thiz, ID_TYPE id_camera, jint scanningMode) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->setScanningMode(scanningMode); } RETURN(result, jint); } static jint nativeGetScanningMode(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->getScanningMode(); } RETURN(result, jint); } //====================================================================== // Java mnethod correspond to this function should not be a static mathod static jint nativeUpdateExposureModeLimit(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { int min, max, def; result = camera->updateExposureModeLimit(min, max, def); if (!result) { // 写入Java端 setField_int(env, thiz, "mExposureModeMin", min); setField_int(env, thiz, "mExposureModeMax", max); setField_int(env, thiz, "mExposureModeDef", def); } } RETURN(result, jint); } static jint nativeSetExposureMode(JNIEnv *env, jobject thiz, ID_TYPE id_camera, int exposureMode) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->setExposureMode(exposureMode); } RETURN(result, jint); } static jint nativeGetExposureMode(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->getExposureMode(); } RETURN(result, jint); } //====================================================================== // Java mnethod correspond to this function should not be a static mathod static jint nativeUpdateExposurePriorityLimit(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { int min, max, def; result = camera->updateExposurePriorityLimit(min, max, def); if (!result) { // 写入Java端 setField_int(env, thiz, "mExposurePriorityMin", min); setField_int(env, thiz, "mExposurePriorityMax", max); setField_int(env, thiz, "mExposurePriorityDef", def); } } RETURN(result, jint); } static jint nativeSetExposurePriority(JNIEnv *env, jobject thiz, ID_TYPE id_camera, int priority) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->setExposurePriority(priority); } RETURN(result, jint); } static jint nativeGetExposurePriority(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->getExposurePriority(); } RETURN(result, jint); } //====================================================================== // Java mnethod correspond to this function should not be a static mathod static jint nativeUpdateExposureLimit(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { int min, max, def; result = camera->updateExposureLimit(min, max, def); if (!result) { // 写入Java端 setField_int(env, thiz, "mExposureMin", min); setField_int(env, thiz, "mExposureMax", max); setField_int(env, thiz, "mExposureDef", def); } } RETURN(result, jint); } static jint nativeSetExposure(JNIEnv *env, jobject thiz, ID_TYPE id_camera, int exposure) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->setExposure(exposure); } RETURN(result, jint); } static jint nativeGetExposure(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->getExposure(); } RETURN(result, jint); } //====================================================================== // Java mnethod correspond to this function should not be a static mathod static jint nativeUpdateExposureRelLimit(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { int min, max, def; result = camera->updateExposureRelLimit(min, max, def); if (!result) { // 写入Java端 setField_int(env, thiz, "mExposureRelMin", min); setField_int(env, thiz, "mExposureRelMax", max); setField_int(env, thiz, "mExposureRelDef", def); } } RETURN(result, jint); } static jint nativeSetExposureRel(JNIEnv *env, jobject thiz, ID_TYPE id_camera, jint exposure_rel) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->setExposureRel(exposure_rel); } RETURN(result, jint); } static jint nativeGetExposureRel(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->getExposureRel(); } RETURN(result, jint); } //====================================================================== // Java mnethod correspond to this function should not be a static mathod static jint nativeUpdateAutoFocusLimit(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { int min, max, def; result = camera->updateAutoFocusLimit(min, max, def); if (!result) { // 写入Java端 setField_int(env, thiz, "mAutoFocusMin", min); setField_int(env, thiz, "mAutoFocusMax", max); setField_int(env, thiz, "mAutoFocusDef", def); } } RETURN(result, jint); } static jint nativeSetAutoFocus(JNIEnv *env, jobject thiz, ID_TYPE id_camera, jboolean autofocus) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->setAutoFocus(autofocus); } RETURN(result, jint); } static jint nativeGetAutoFocus(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->getAutoFocus(); } RETURN(result, jint); } //====================================================================== // Java mnethod correspond to this function should not be a static mathod static jint nativeUpdateAutoWhiteBlanceLimit(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { int min, max, def; result = camera->updateAutoWhiteBlanceLimit(min, max, def); if (!result) { // 写入Java端 setField_int(env, thiz, "mAutoWhiteBlanceMin", min); setField_int(env, thiz, "mAutoWhiteBlanceMax", max); setField_int(env, thiz, "mAutoWhiteBlanceDef", def); } } RETURN(result, jint); } static jint nativeSetAutoWhiteBlance(JNIEnv *env, jobject thiz, ID_TYPE id_camera, jboolean autofocus) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->setAutoWhiteBlance(autofocus); } RETURN(result, jint); } static jint nativeGetAutoWhiteBlance(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->getAutoWhiteBlance(); } RETURN(result, jint); } //====================================================================== // Java mnethod correspond to this function should not be a static mathod static jint nativeUpdateAutoWhiteBlanceCompoLimit(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { int min, max, def; result = camera->updateAutoWhiteBlanceCompoLimit(min, max, def); if (!result) { // 写入Java端 setField_int(env, thiz, "mAutoWhiteBlanceCompoMin", min); setField_int(env, thiz, "mAutoWhiteBlanceCompoMax", max); setField_int(env, thiz, "mAutoWhiteBlanceCompoDef", def); } } RETURN(result, jint); } static jint nativeSetAutoWhiteBlanceCompo(JNIEnv *env, jobject thiz, ID_TYPE id_camera, jboolean autofocus_compo) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->setAutoWhiteBlanceCompo(autofocus_compo); } RETURN(result, jint); } static jint nativeGetAutoWhiteBlanceCompo(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->getAutoWhiteBlanceCompo(); } RETURN(result, jint); } //====================================================================== // Java mnethod correspond to this function should not be a static mathod static jint nativeUpdateBrightnessLimit(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { int min, max, def; result = camera->updateBrightnessLimit(min, max, def); if (!result) { // 写入Java端 setField_int(env, thiz, "mBrightnessMin", min); setField_int(env, thiz, "mBrightnessMax", max); setField_int(env, thiz, "mBrightnessDef", def); } } RETURN(result, jint); } static jint nativeSetBrightness(JNIEnv *env, jobject thiz, ID_TYPE id_camera, jint brightness) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->setBrightness(brightness); } RETURN(result, jint); } static jint nativeGetBrightness(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = 0; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->getBrightness(); } RETURN(result, jint); } //====================================================================== // Java mnethod correspond to this function should not be a static mathod static jint nativeUpdateFocusLimit(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { int min, max, def; result = camera->updateFocusLimit(min, max, def); if (!result) { // 写入Java端 setField_int(env, thiz, "mFocusMin", min); setField_int(env, thiz, "mFocusMax", max); setField_int(env, thiz, "mFocusDef", def); } } RETURN(result, jint); } static jint nativeSetFocus(JNIEnv *env, jobject thiz, ID_TYPE id_camera, jint focus) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->setFocus(focus); } RETURN(result, jint); } static jint nativeGetFocus(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = 0; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->getFocus(); } RETURN(result, jint); } //====================================================================== // Java mnethod correspond to this function should not be a static mathod static jint nativeUpdateFocusRelLimit(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { int min, max, def; result = camera->updateFocusRelLimit(min, max, def); if (!result) { // 写入Java端 setField_int(env, thiz, "mFocusRelMin", min); setField_int(env, thiz, "mFocusRelMax", max); setField_int(env, thiz, "mFocusRelDef", def); } } RETURN(result, jint); } static jint nativeSetFocusRel(JNIEnv *env, jobject thiz, ID_TYPE id_camera, jint focus_rel) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->setFocusRel(focus_rel); } RETURN(result, jint); } static jint nativeGetFocusRel(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = 0; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->getFocusRel(); } RETURN(result, jint); } //====================================================================== // Java mnethod correspond to this function should not be a static mathod static jint nativeUpdateIrisLimit(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { int min, max, def; result = camera->updateIrisLimit(min, max, def); if (!result) { // 写入Java端 setField_int(env, thiz, "mIrisMin", min); setField_int(env, thiz, "mIrisMax", max); setField_int(env, thiz, "mIrisDef", def); } } RETURN(result, jint); } static jint nativeSetIris(JNIEnv *env, jobject thiz, ID_TYPE id_camera, jint iris) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->setIris(iris); } RETURN(result, jint); } static jint nativeGetIris(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = 0; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->getIris(); } RETURN(result, jint); } //====================================================================== // Java mnethod correspond to this function should not be a static mathod static jint nativeUpdateIrisRelLimit(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { int min, max, def; result = camera->updateIrisRelLimit(min, max, def); if (!result) { // 写入Java端 setField_int(env, thiz, "mIrisRelMin", min); setField_int(env, thiz, "mIrisRelMax", max); setField_int(env, thiz, "mIrisRelDef", def); } } RETURN(result, jint); } static jint nativeSetIrisRel(JNIEnv *env, jobject thiz, ID_TYPE id_camera, jint iris_rel) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->setIrisRel(iris_rel); } RETURN(result, jint); } static jint nativeGetIrisRel(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = 0; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->getIrisRel(); } RETURN(result, jint); } //====================================================================== // Java mnethod correspond to this function should not be a static mathod static jint nativeUpdatePanLimit(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { int min, max, def; result = camera->updatePanLimit(min, max, def); if (!result) { // 写入Java端 setField_int(env, thiz, "mPanMin", min); setField_int(env, thiz, "mPanMax", max); setField_int(env, thiz, "mPanDef", def); } } RETURN(result, jint); } static jint nativeSetPan(JNIEnv *env, jobject thiz, ID_TYPE id_camera, jint pan) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->setPan(pan); } RETURN(result, jint); } static jint nativeGetPan(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = 0; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->getPan(); } RETURN(result, jint); } //====================================================================== // Java mnethod correspond to this function should not be a static mathod static jint nativeUpdateTiltLimit(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { int min, max, def; result = camera->updateTiltLimit(min, max, def); if (!result) { // 写入Java端 setField_int(env, thiz, "mTiltMin", min); setField_int(env, thiz, "mTiltMax", max); setField_int(env, thiz, "mTiltDef", def); } } RETURN(result, jint); } static jint nativeSetTilt(JNIEnv *env, jobject thiz, ID_TYPE id_camera, jint tilt) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->setTilt(tilt); } RETURN(result, jint); } static jint nativeGetTilt(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = 0; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->getTilt(); } RETURN(result, jint); } //====================================================================== // Java mnethod correspond to this function should not be a static mathod static jint nativeUpdateRollLimit(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { int min, max, def; result = camera->updateRollLimit(min, max, def); if (!result) { // 写入Java端 setField_int(env, thiz, "mRollMin", min); setField_int(env, thiz, "mRollMax", max); setField_int(env, thiz, "mRollDef", def); } } RETURN(result, jint); } static jint nativeSetRoll(JNIEnv *env, jobject thiz, ID_TYPE id_camera, jint roll) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->setRoll(roll); } RETURN(result, jint); } static jint nativeGetRoll(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = 0; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->getRoll(); } RETURN(result, jint); } //====================================================================== // Java mnethod correspond to this function should not be a static mathod static jint nativeUpdatePanRelLimit(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { int min, max, def; result = camera->updatePanRelLimit(min, max, def); if (!result) { // 写入Java端 setField_int(env, thiz, "mPanRelMin", min); setField_int(env, thiz, "mPanRelMax", max); setField_int(env, thiz, "mPanRelDef", def); } } RETURN(result, jint); } static jint nativeSetPanRel(JNIEnv *env, jobject thiz, ID_TYPE id_camera, jint pan_rel) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->setPanRel(pan_rel); } RETURN(result, jint); } static jint nativeGetPanRel(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = 0; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->getPanRel(); } RETURN(result, jint); } //====================================================================== // Java mnethod correspond to this function should not be a static mathod static jint nativeUpdateTiltRelLimit(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { int min, max, def; result = camera->updateTiltRelLimit(min, max, def); if (!result) { // 写入Java端 setField_int(env, thiz, "mTiltRelMin", min); setField_int(env, thiz, "mTiltRelMax", max); setField_int(env, thiz, "mTiltRelDef", def); } } RETURN(result, jint); } static jint nativeSetTiltRel(JNIEnv *env, jobject thiz, ID_TYPE id_camera, jint tilt_rel) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->setTiltRel(tilt_rel); } RETURN(result, jint); } static jint nativeGetTiltRel(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = 0; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->getTiltRel(); } RETURN(result, jint); } //====================================================================== // Java mnethod correspond to this function should not be a static mathod static jint nativeUpdateRollRelLimit(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { int min, max, def; result = camera->updateRollRelLimit(min, max, def); if (!result) { // 写入Java端 setField_int(env, thiz, "mRollRelMin", min); setField_int(env, thiz, "mRollRelMax", max); setField_int(env, thiz, "mRollRelDef", def); } } RETURN(result, jint); } static jint nativeSetRollRel(JNIEnv *env, jobject thiz, ID_TYPE id_camera, jint roll_rel) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->setRollRel(roll_rel); } RETURN(result, jint); } static jint nativeGetRollRel(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = 0; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->getRollRel(); } RETURN(result, jint); } //====================================================================== // Java mnethod correspond to this function should not be a static mathod static jint nativeUpdateContrastLimit(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { int min, max, def; result = camera->updateContrastLimit(min, max, def); if (!result) { // 写入Java端 setField_int(env, thiz, "mContrastMin", min); setField_int(env, thiz, "mContrastMax", max); setField_int(env, thiz, "mContrastDef", def); } } RETURN(result, jint); } static jint nativeSetContrast(JNIEnv *env, jobject thiz, ID_TYPE id_camera, jint contrast) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->setContrast(contrast); } RETURN(result, jint); } static jint nativeGetContrast(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = 0; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->getContrast(); } RETURN(result, jint); } //====================================================================== // Java method correspond to this function should not be a static mathod static jint nativeUpdateAutoContrastLimit(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { int min, max, def; result = camera->updateAutoContrastLimit(min, max, def); if (!result) { // 写入Java端 setField_int(env, thiz, "mAutoContrastMin", min); setField_int(env, thiz, "mAutoContrastMax", max); setField_int(env, thiz, "mAutoContrastDef", def); } } RETURN(result, jint); } static jint nativeSetAutoContrast(JNIEnv *env, jobject thiz, ID_TYPE id_camera, jboolean autocontrast) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->setAutoContrast(autocontrast); } RETURN(result, jint); } static jint nativeGetAutoContrast(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->getAutoContrast(); } RETURN(result, jint); } //====================================================================== // Java mnethod correspond to this function should not be a static mathod static jint nativeUpdateSharpnessLimit(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { int min, max, def; result = camera->updateSharpnessLimit(min, max, def); if (!result) { // 写入Java端 setField_int(env, thiz, "mSharpnessMin", min); setField_int(env, thiz, "mSharpnessMax", max); setField_int(env, thiz, "mSharpnessDef", def); } } RETURN(result, jint); } static jint nativeSetSharpness(JNIEnv *env, jobject thiz, ID_TYPE id_camera, jint sharpness) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->setSharpness(sharpness); } RETURN(result, jint); } static jint nativeGetSharpness(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = 0; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->getSharpness(); } RETURN(result, jint); } //====================================================================== // Java mnethod correspond to this function should not be a static mathod static jint nativeUpdateGainLimit(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { int min, max, def; result = camera->updateGainLimit(min, max, def); if (!result) { // 写入Java端 setField_int(env, thiz, "mGainMin", min); setField_int(env, thiz, "mGainMax", max); setField_int(env, thiz, "mGainDef", def); } } RETURN(result, jint); } static jint nativeSetGain(JNIEnv *env, jobject thiz, ID_TYPE id_camera, jint gain) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->setGain(gain); } RETURN(result, jint); } static jint nativeGetGain(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = 0; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->getGain(); } RETURN(result, jint); } //====================================================================== // Java mnethod correspond to this function should not be a static mathod static jint nativeUpdateGammaLimit(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { int min, max, def; result = camera->updateGammaLimit(min, max, def); if (!result) { // 写入Java端 setField_int(env, thiz, "mGammaMin", min); setField_int(env, thiz, "mGammaMax", max); setField_int(env, thiz, "mGammaDef", def); } } RETURN(result, jint); } static jint nativeSetGamma(JNIEnv *env, jobject thiz, ID_TYPE id_camera, jint gamma) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->setGamma(gamma); } RETURN(result, jint); } static jint nativeGetGamma(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = 0; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->getGamma(); } RETURN(result, jint); } //====================================================================== // Java mnethod correspond to this function should not be a static mathod static jint nativeUpdateWhiteBlanceLimit(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { int min, max, def; result = camera->updateWhiteBlanceLimit(min, max, def); if (!result) { // 写入Java端 setField_int(env, thiz, "mWhiteBlanceMin", min); setField_int(env, thiz, "mWhiteBlanceMax", max); setField_int(env, thiz, "mWhiteBlanceDef", def); } } RETURN(result, jint); } static jint nativeSetWhiteBlance(JNIEnv *env, jobject thiz, ID_TYPE id_camera, jint whiteBlance) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->setWhiteBlance(whiteBlance); } RETURN(result, jint); } static jint nativeGetWhiteBlance(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = 0; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->getWhiteBlance(); } RETURN(result, jint); } //====================================================================== // Java mnethod correspond to this function should not be a static mathod static jint nativeUpdateWhiteBlanceCompoLimit(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { int min, max, def; result = camera->updateWhiteBlanceCompoLimit(min, max, def); if (!result) { // 写入Java端 setField_int(env, thiz, "mWhiteBlanceCompoMin", min); setField_int(env, thiz, "mWhiteBlanceCompoMax", max); setField_int(env, thiz, "mWhiteBlanceCompoDef", def); } } RETURN(result, jint); } static jint nativeSetWhiteBlanceCompo(JNIEnv *env, jobject thiz, ID_TYPE id_camera, jint whiteBlance_compo) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->setWhiteBlanceCompo(whiteBlance_compo); } RETURN(result, jint); } static jint nativeGetWhiteBlanceCompo(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = 0; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->getWhiteBlanceCompo(); } RETURN(result, jint); } //====================================================================== // Java mnethod correspond to this function should not be a static mathod static jint nativeUpdateBacklightCompLimit(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { int min, max, def; result = camera->updateBacklightCompLimit(min, max, def); if (!result) { // 写入Java端 setField_int(env, thiz, "mBacklightCompMin", min); setField_int(env, thiz, "mBacklightCompMax", max); setField_int(env, thiz, "mBacklightCompDef", def); } } RETURN(result, jint); } static jint nativeSetBacklightComp(JNIEnv *env, jobject thiz, ID_TYPE id_camera, jint backlight_comp) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->setBacklightComp(backlight_comp); } RETURN(result, jint); } static jint nativeGetBacklightComp(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = 0; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->getBacklightComp(); } RETURN(result, jint); } //====================================================================== // Java mnethod correspond to this function should not be a static mathod static jint nativeUpdateSaturationLimit(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { int min, max, def; result = camera->updateSaturationLimit(min, max, def); if (!result) { // 写入Java端 setField_int(env, thiz, "mSaturationMin", min); setField_int(env, thiz, "mSaturationMax", max); setField_int(env, thiz, "mSaturationDef", def); } } RETURN(result, jint); } static jint nativeSetSaturation(JNIEnv *env, jobject thiz, ID_TYPE id_camera, jint saturation) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->setSaturation(saturation); } RETURN(result, jint); } static jint nativeGetSaturation(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = 0; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->getSaturation(); } RETURN(result, jint); } //====================================================================== // Java mnethod correspond to this function should not be a static mathod static jint nativeUpdateHueLimit(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { int min, max, def; result = camera->updateHueLimit(min, max, def); if (!result) { // 写入Java端 setField_int(env, thiz, "mHueMin", min); setField_int(env, thiz, "mHueMax", max); setField_int(env, thiz, "mHueDef", def); } } RETURN(result, jint); } static jint nativeSetHue(JNIEnv *env, jobject thiz, ID_TYPE id_camera, jint hue) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->setHue(hue); } RETURN(result, jint); } static jint nativeGetHue(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = 0; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->getHue(); } RETURN(result, jint); } //====================================================================== // Java method correspond to this function should not be a static mathod static jint nativeUpdateAutoHueLimit(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { int min, max, def; result = camera->updateAutoHueLimit(min, max, def); if (!result) { // 写入Java端 setField_int(env, thiz, "mAutoHueMin", min); setField_int(env, thiz, "mAutoHueMax", max); setField_int(env, thiz, "mAutoHueDef", def); } } RETURN(result, jint); } static jint nativeSetAutoHue(JNIEnv *env, jobject thiz, ID_TYPE id_camera, jboolean autohue) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->setAutoHue(autohue); } RETURN(result, jint); } static jint nativeGetAutoHue(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->getAutoHue(); } RETURN(result, jint); } //====================================================================== // Java mnethod correspond to this function should not be a static mathod static jint nativeUpdatePowerlineFrequencyLimit(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { int min, max, def; result = camera->updatePowerlineFrequencyLimit(min, max, def); if (!result) { // 写入Java端 setField_int(env, thiz, "mPowerlineFrequencyMin", min); setField_int(env, thiz, "mPowerlineFrequencyMax", max); setField_int(env, thiz, "mPowerlineFrequencyDef", def); } } RETURN(result, jint); } static jint nativeSetPowerlineFrequency(JNIEnv *env, jobject thiz, ID_TYPE id_camera, jint frequency) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->setPowerlineFrequency(frequency); } RETURN(result, jint); } static jint nativeGetPowerlineFrequency(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = 0; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->getPowerlineFrequency(); } RETURN(result, jint); } //====================================================================== // Java mnethod correspond to this function should not be a static mathod static jint nativeUpdateZoomLimit(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { int min, max, def; result = camera->updateZoomLimit(min, max, def); if (!result) { // 写入Java端 setField_int(env, thiz, "mZoomMin", min); setField_int(env, thiz, "mZoomMax", max); setField_int(env, thiz, "mZoomDef", def); } } RETURN(result, jint); } static jint nativeSetZoom(JNIEnv *env, jobject thiz, ID_TYPE id_camera, jint zoom) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->setZoom(zoom); } RETURN(result, jint); } static jint nativeGetZoom(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = 0; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->getZoom(); } RETURN(result, jint); } //====================================================================== // Java mnethod correspond to this function should not be a static mathod static jint nativeUpdateZoomRelLimit(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { int min, max, def; result = camera->updateZoomRelLimit(min, max, def); if (!result) { // 写入Java端 setField_int(env, thiz, "mZoomRelMin", min); setField_int(env, thiz, "mZoomRelMax", max); setField_int(env, thiz, "mZoomRelDef", def); } } RETURN(result, jint); } static jint nativeSetZoomRel(JNIEnv *env, jobject thiz, ID_TYPE id_camera, jint zoom_rel) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->setZoomRel(zoom_rel); } RETURN(result, jint); } static jint nativeGetZoomRel(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = 0; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->getZoomRel(); } RETURN(result, jint); } //====================================================================== // Java mnethod correspond to this function should not be a static mathod static jint nativeUpdateDigitalMultiplierLimit(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { int min, max, def; result = camera->updateDigitalMultiplierLimit(min, max, def); if (!result) { // 写入Java端 setField_int(env, thiz, "mDigitalMultiplierMin", min); setField_int(env, thiz, "mDigitalMultiplierMax", max); setField_int(env, thiz, "mDigitalMultiplierDef", def); } } RETURN(result, jint); } static jint nativeSetDigitalMultiplier(JNIEnv *env, jobject thiz, ID_TYPE id_camera, jint multiplier) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->setDigitalMultiplier(multiplier); } RETURN(result, jint); } static jint nativeGetDigitalMultiplier(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = 0; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->getDigitalMultiplier(); } RETURN(result, jint); } //====================================================================== // Java mnethod correspond to this function should not be a static mathod static jint nativeUpdateDigitalMultiplierLimitLimit(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { int min, max, def; result = camera->updateDigitalMultiplierLimitLimit(min, max, def); if (!result) { // 写入Java端 setField_int(env, thiz, "mDigitalMultiplierLimitMin", min); setField_int(env, thiz, "mDigitalMultiplierLimitMax", max); setField_int(env, thiz, "mDigitalMultiplierLimitDef", def); } } RETURN(result, jint); } static jint nativeSetDigitalMultiplierLimit(JNIEnv *env, jobject thiz, ID_TYPE id_camera, jint multiplier_limit) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->setDigitalMultiplierLimit(multiplier_limit); } RETURN(result, jint); } static jint nativeGetDigitalMultiplierLimit(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = 0; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->getDigitalMultiplierLimit(); } RETURN(result, jint); } //====================================================================== // Java mnethod correspond to this function should not be a static mathod static jint nativeUpdateAnalogVideoStandardLimit(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { int min, max, def; result = camera->updateAnalogVideoStandardLimit(min, max, def); if (!result) { // 写入Java端 setField_int(env, thiz, "mAnalogVideoStandardMin", min); setField_int(env, thiz, "mAnalogVideoStandardMax", max); setField_int(env, thiz, "mAnalogVideoStandardDef", def); } } RETURN(result, jint); } static jint nativeSetAnalogVideoStandard(JNIEnv *env, jobject thiz, ID_TYPE id_camera, jint standard) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->setAnalogVideoStandard(standard); } RETURN(result, jint); } static jint nativeGetAnalogVideoStandard(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = 0; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->getAnalogVideoStandard(); } RETURN(result, jint); } //====================================================================== // Java mnethod correspond to this function should not be a static mathod static jint nativeUpdateAnalogVideoLockStateLimit(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { int min, max, def; result = camera->updateAnalogVideoLockStateLimit(min, max, def); if (!result) { // 写入Java端 setField_int(env, thiz, "mAnalogVideoLockStateMin", min); setField_int(env, thiz, "mAnalogVideoLockStateMax", max); setField_int(env, thiz, "mAnalogVideoLockStateDef", def); } } RETURN(result, jint); } static jint nativeSetAnalogVideoLockState(JNIEnv *env, jobject thiz, ID_TYPE id_camera, jint state) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->setAnalogVideoLockState(state); } RETURN(result, jint); } static jint nativeGetAnalogVideoLockState(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = 0; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->getAnalogVideoLockState(); } RETURN(result, jint); } //====================================================================== // Java method correspond to this function should not be a static mathod static jint nativeUpdatePrivacyLimit(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { int min, max, def; result = camera->updatePrivacyLimit(min, max, def); if (!result) { // 写入Java端 setField_int(env, thiz, "mPrivacyMin", min); setField_int(env, thiz, "mPrivacyMax", max); setField_int(env, thiz, "mPrivacyDef", def); } } RETURN(result, jint); } static jint nativeSetPrivacy(JNIEnv *env, jobject thiz, ID_TYPE id_camera, jboolean privacy) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->setPrivacy(privacy ? 1: 0); } RETURN(result, jint); } static jint nativeGetPrivacy(JNIEnv *env, jobject thiz, ID_TYPE id_camera) { jint result = JNI_ERR; ENTER(); UVCCamera *camera = reinterpret_cast<UVCCamera *>(id_camera); if (LIKELY(camera)) { result = camera->getPrivacy(); } RETURN(result, jint); } //********************************************************************** // //********************************************************************** jint registerNativeMethods(JNIEnv* env, const char *class_name, JNINativeMethod *methods, int num_methods) { int result = 0; jclass clazz = env->FindClass(class_name); if (LIKELY(clazz)) { int result = env->RegisterNatives(clazz, methods, num_methods); if (UNLIKELY(result < 0)) { LOGE("registerNativeMethods failed(class=%s)", class_name); } } else { LOGE("registerNativeMethods: class'%s' not found", class_name); } return result; } static JNINativeMethod methods[] = { { "nativeCreate", "()J", (void *) nativeCreate }, { "nativeDestroy", "(J)V", (void *) nativeDestroy }, // { "nativeFrameBufferSize", "(I)V", (void *) nativeFrameBufferSize }, { "nativeDropIncompleteFrame", "(I)V", (void *) nativeDropIncompleteFrame }, { "nativeHorizontalMirror", "(JI)V", (void *) nativeHorizontalMirror }, { "nativeVerticalMirror", "(JI)V", (void *) nativeVerticalMirror }, { "nativeCameraAngle", "(JI)V", (void *) nativeCameraAngle }, { "nativeConnect", "(JIIIIILjava/lang/String;)I", (void *) nativeConnect }, { "nativeRelease", "(J)I", (void *) nativeRelease }, { "nativeSetStatusCallback", "(JLcom/serenegiant/usb/IStatusCallback;)I", (void *) nativeSetStatusCallback }, { "nativeSetButtonCallback", "(JLcom/serenegiant/usb/IButtonCallback;)I", (void *) nativeSetButtonCallback }, { "nativeGetSupportedSize", "(J)Ljava/lang/String;", (void *) nativeGetSupportedSize }, { "nativeSetPreviewSize", "(JIIIIIIF)I", (void *) nativeSetPreviewSize }, { "nativeStartPreview", "(J)I", (void *) nativeStartPreview }, { "nativeStopPreview", "(J)I", (void *) nativeStopPreview }, { "nativeSetPreviewDisplay", "(JLandroid/view/Surface;)I", (void *) nativeSetPreviewDisplay }, { "nativeSetFrameCallback", "(JLcom/serenegiant/usb/IFrameCallback;I)I", (void *) nativeSetFrameCallback }, { "nativeSetCaptureDisplay", "(JLandroid/view/Surface;)I", (void *) nativeSetCaptureDisplay }, { "nativeGetCtrlSupports", "(J)J", (void *) nativeGetCtrlSupports }, { "nativeGetProcSupports", "(J)J", (void *) nativeGetProcSupports }, { "nativeUpdateScanningModeLimit", "(J)I", (void *) nativeUpdateScanningModeLimit }, { "nativeSetScanningMode", "(JI)I", (void *) nativeSetScanningMode }, { "nativeGetScanningMode", "(J)I", (void *) nativeGetScanningMode }, { "nativeUpdateExposureModeLimit", "(J)I", (void *) nativeUpdateExposureModeLimit }, { "nativeSetExposureMode", "(JI)I", (void *) nativeSetExposureMode }, { "nativeGetExposureMode", "(J)I", (void *) nativeGetExposureMode }, { "nativeUpdateExposurePriorityLimit","(J)I", (void *) nativeUpdateExposurePriorityLimit }, { "nativeSetExposurePriority", "(JI)I", (void *) nativeSetExposurePriority }, { "nativeGetExposurePriority", "(J)I", (void *) nativeGetExposurePriority }, { "nativeUpdateExposureLimit", "(J)I", (void *) nativeUpdateExposureLimit }, { "nativeSetExposure", "(JI)I", (void *) nativeSetExposure }, { "nativeGetExposure", "(J)I", (void *) nativeGetExposure }, { "nativeUpdateExposureRelLimit", "(J)I", (void *) nativeUpdateExposureRelLimit }, { "nativeSetExposureRel", "(JI)I", (void *) nativeSetExposureRel }, { "nativeGetExposureRel", "(J)I", (void *) nativeGetExposureRel }, { "nativeUpdateAutoFocusLimit", "(J)I", (void *) nativeUpdateAutoFocusLimit }, { "nativeSetAutoFocus", "(JZ)I", (void *) nativeSetAutoFocus }, { "nativeGetAutoFocus", "(J)I", (void *) nativeGetAutoFocus }, { "nativeUpdateFocusLimit", "(J)I", (void *) nativeUpdateFocusLimit }, { "nativeSetFocus", "(JI)I", (void *) nativeSetFocus }, { "nativeGetFocus", "(J)I", (void *) nativeGetFocus }, { "nativeUpdateFocusRelLimit", "(J)I", (void *) nativeUpdateFocusRelLimit }, { "nativeSetFocusRel", "(JI)I", (void *) nativeSetFocusRel }, { "nativeGetFocusRel", "(J)I", (void *) nativeGetFocusRel }, // { "nativeUpdateFocusSimpleLimit", "(J)I", (void *) nativeUpdateFocusSimpleLimit }, // { "nativeSetFocusSimple", "(JI)I", (void *) nativeSetFocusSimple }, // { "nativeGetFocusSimple", "(J)I", (void *) nativeGetFocusSimple }, { "nativeUpdateIrisLimit", "(J)I", (void *) nativeUpdateIrisLimit }, { "nativeSetIris", "(JI)I", (void *) nativeSetIris }, { "nativeGetIris", "(J)I", (void *) nativeGetIris }, { "nativeUpdateIrisRelLimit", "(J)I", (void *) nativeUpdateIrisRelLimit }, { "nativeSetIrisRel", "(JI)I", (void *) nativeSetIrisRel }, { "nativeGetIrisRel", "(J)I", (void *) nativeGetIrisRel }, { "nativeUpdatePanLimit", "(J)I", (void *) nativeUpdatePanLimit }, { "nativeSetPan", "(JI)I", (void *) nativeSetPan }, { "nativeGetPan", "(J)I", (void *) nativeGetPan }, { "nativeUpdateTiltLimit", "(J)I", (void *) nativeUpdateTiltLimit }, { "nativeSetTilt", "(JI)I", (void *) nativeSetTilt }, { "nativeGetTilt", "(J)I", (void *) nativeGetTilt }, { "nativeUpdateRollLimit", "(J)I", (void *) nativeUpdateRollLimit }, { "nativeSetRoll", "(JI)I", (void *) nativeSetRoll }, { "nativeGetRoll", "(J)I", (void *) nativeGetRoll }, { "nativeUpdatePanRelLimit", "(J)I", (void *) nativeUpdatePanRelLimit }, { "nativeSetPanRel", "(JI)I", (void *) nativeSetPanRel }, { "nativeGetPanRel", "(J)I", (void *) nativeGetPanRel }, { "nativeUpdateTiltRelLimit", "(J)I", (void *) nativeUpdateTiltRelLimit }, { "nativeSetTiltRel", "(JI)I", (void *) nativeSetTiltRel }, { "nativeGetTiltRel", "(J)I", (void *) nativeGetTiltRel }, { "nativeUpdateRollRelLimit", "(J)I", (void *) nativeUpdateRollRelLimit }, { "nativeSetRollRel", "(JI)I", (void *) nativeSetRollRel }, { "nativeGetRollRel", "(J)I", (void *) nativeGetRollRel }, { "nativeUpdateAutoWhiteBlanceLimit","(J)I", (void *) nativeUpdateAutoWhiteBlanceLimit }, { "nativeSetAutoWhiteBlance", "(JZ)I", (void *) nativeSetAutoWhiteBlance }, { "nativeGetAutoWhiteBlance", "(J)I", (void *) nativeGetAutoWhiteBlance }, { "nativeUpdateAutoWhiteBlanceCompoLimit","(J)I", (void *) nativeUpdateAutoWhiteBlanceCompoLimit }, { "nativeSetAutoWhiteBlanceCompo", "(JZ)I", (void *) nativeSetAutoWhiteBlanceCompo }, { "nativeGetAutoWhiteBlanceCompo", "(J)I", (void *) nativeGetAutoWhiteBlanceCompo }, { "nativeUpdateWhiteBlanceLimit", "(J)I", (void *) nativeUpdateWhiteBlanceLimit }, { "nativeSetWhiteBlance", "(JI)I", (void *) nativeSetWhiteBlance }, { "nativeGetWhiteBlance", "(J)I", (void *) nativeGetWhiteBlance }, { "nativeUpdateWhiteBlanceCompoLimit","(J)I", (void *) nativeUpdateWhiteBlanceCompoLimit }, { "nativeSetWhiteBlanceCompo", "(JI)I", (void *) nativeSetWhiteBlanceCompo }, { "nativeGetWhiteBlanceCompo", "(J)I", (void *) nativeGetWhiteBlanceCompo }, { "nativeUpdateBacklightCompLimit", "(J)I", (void *) nativeUpdateBacklightCompLimit }, { "nativeSetBacklightComp", "(JI)I", (void *) nativeSetBacklightComp }, { "nativeGetBacklightComp", "(J)I", (void *) nativeGetBacklightComp }, { "nativeUpdateBrightnessLimit", "(J)I", (void *) nativeUpdateBrightnessLimit }, { "nativeSetBrightness", "(JI)I", (void *) nativeSetBrightness }, { "nativeGetBrightness", "(J)I", (void *) nativeGetBrightness }, { "nativeUpdateContrastLimit", "(J)I", (void *) nativeUpdateContrastLimit }, { "nativeSetContrast", "(JI)I", (void *) nativeSetContrast }, { "nativeGetContrast", "(J)I", (void *) nativeGetContrast }, { "nativeUpdateAutoContrastLimit", "(J)I", (void *) nativeUpdateAutoContrastLimit }, { "nativeSetAutoContrast", "(JZ)I", (void *) nativeSetAutoContrast }, { "nativeGetAutoContrast", "(J)I", (void *) nativeGetAutoContrast }, { "nativeUpdateSharpnessLimit", "(J)I", (void *) nativeUpdateSharpnessLimit }, { "nativeSetSharpness", "(JI)I", (void *) nativeSetSharpness }, { "nativeGetSharpness", "(J)I", (void *) nativeGetSharpness }, { "nativeUpdateGainLimit", "(J)I", (void *) nativeUpdateGainLimit }, { "nativeSetGain", "(JI)I", (void *) nativeSetGain }, { "nativeGetGain", "(J)I", (void *) nativeGetGain }, { "nativeUpdateGammaLimit", "(J)I", (void *) nativeUpdateGammaLimit }, { "nativeSetGamma", "(JI)I", (void *) nativeSetGamma }, { "nativeGetGamma", "(J)I", (void *) nativeGetGamma }, { "nativeUpdateSaturationLimit", "(J)I", (void *) nativeUpdateSaturationLimit }, { "nativeSetSaturation", "(JI)I", (void *) nativeSetSaturation }, { "nativeGetSaturation", "(J)I", (void *) nativeGetSaturation }, { "nativeUpdateHueLimit", "(J)I", (void *) nativeUpdateHueLimit }, { "nativeSetHue", "(JI)I", (void *) nativeSetHue }, { "nativeGetHue", "(J)I", (void *) nativeGetHue }, { "nativeUpdateAutoHueLimit", "(J)I", (void *) nativeUpdateAutoHueLimit }, { "nativeSetAutoHue", "(JZ)I", (void *) nativeSetAutoHue }, { "nativeGetAutoHue", "(J)I", (void *) nativeGetAutoHue }, { "nativeUpdatePowerlineFrequencyLimit","(J)I", (void *) nativeUpdatePowerlineFrequencyLimit }, { "nativeSetPowerlineFrequency", "(JI)I", (void *) nativeSetPowerlineFrequency }, { "nativeGetPowerlineFrequency", "(J)I", (void *) nativeGetPowerlineFrequency }, { "nativeUpdateZoomLimit", "(J)I", (void *) nativeUpdateZoomLimit }, { "nativeSetZoom", "(JI)I", (void *) nativeSetZoom }, { "nativeGetZoom", "(J)I", (void *) nativeGetZoom }, { "nativeUpdateZoomRelLimit", "(J)I", (void *) nativeUpdateZoomRelLimit }, { "nativeSetZoomRel", "(JI)I", (void *) nativeSetZoomRel }, { "nativeGetZoomRel", "(J)I", (void *) nativeGetZoomRel }, { "nativeUpdateDigitalMultiplierLimit","(J)I", (void *) nativeUpdateDigitalMultiplierLimit }, { "nativeSetDigitalMultiplier","(JI)I", (void *) nativeSetDigitalMultiplier }, { "nativeGetDigitalMultiplier","(J)I", (void *) nativeGetDigitalMultiplier }, { "nativeUpdateDigitalMultiplierLimitLimit","(J)I", (void *) nativeUpdateDigitalMultiplierLimitLimit }, { "nativeSetDigitalMultiplierLimit","(JI)I", (void *) nativeSetDigitalMultiplierLimit }, { "nativeGetDigitalMultiplierLimit","(J)I", (void *) nativeGetDigitalMultiplierLimit }, { "nativeUpdateAnalogVideoStandardLimit","(J)I", (void *) nativeUpdateAnalogVideoStandardLimit }, { "nativeSetAnalogVideoStandard", "(JI)I", (void *) nativeSetAnalogVideoStandard }, { "nativeGetAnalogVideoStandard", "(J)I", (void *) nativeGetAnalogVideoStandard }, { "nativeUpdateAnalogVideoLockStateLimit","(J)I", (void *) nativeUpdateAnalogVideoLockStateLimit }, { "nativeSetAnalogVideoLoackState", "(JI)I", (void *) nativeSetAnalogVideoLockState }, { "nativeGetAnalogVideoLoackState", "(J)I", (void *) nativeGetAnalogVideoLockState }, { "nativeUpdatePrivacyLimit", "(J)I", (void *) nativeUpdatePrivacyLimit }, { "nativeSetPrivacy", "(JZ)I", (void *) nativeSetPrivacy }, { "nativeGetPrivacy", "(J)I", (void *) nativeGetPrivacy }, }; int register_uvccamera(JNIEnv *env) { LOGV("register_uvccamera:"); if (registerNativeMethods(env, "com/serenegiant/usb/UVCCamera", methods, NUM_ARRAY_ELEMENTS(methods)) < 0) { return -1; } return 0; }
29.81806
129
0.676359
f505bb79f1133b578d55b81df8ad29303067731f
3,325
cpp
C++
components/scream/src/physics/p3/tests/p3_ni_conservation_tests.cpp
mauzey1/scream
d12eb1b13039a09d9c031236af74e04262066bfc
[ "zlib-acknowledgement", "RSA-MD", "FTL" ]
null
null
null
components/scream/src/physics/p3/tests/p3_ni_conservation_tests.cpp
mauzey1/scream
d12eb1b13039a09d9c031236af74e04262066bfc
[ "zlib-acknowledgement", "RSA-MD", "FTL" ]
null
null
null
components/scream/src/physics/p3/tests/p3_ni_conservation_tests.cpp
mauzey1/scream
d12eb1b13039a09d9c031236af74e04262066bfc
[ "zlib-acknowledgement", "RSA-MD", "FTL" ]
null
null
null
#include "catch2/catch.hpp" #include "share/scream_types.hpp" #include "ekat/ekat_pack.hpp" #include "ekat/kokkos/ekat_kokkos_utils.hpp" #include "physics/p3/p3_functions.hpp" #include "physics/p3/p3_functions_f90.hpp" #include "p3_unit_tests_common.hpp" namespace scream { namespace p3 { namespace unit_test { template <typename D> struct UnitWrap::UnitTest<D>::TestNiConservation { static void run_bfb() { NiConservationData f90_data[max_pack_size]; static constexpr Int num_runs = sizeof(f90_data) / sizeof(NiConservationData); // Generate random input data // Alternatively, you can use the f90_data construtors/initializer lists to hardcode data for (auto& d : f90_data) { d.randomize(); } // Create copies of data for use by cxx and sync it to device. Needs to happen before fortran calls so that // inout data is in original state view_1d<NiConservationData> cxx_device("cxx_device", max_pack_size); const auto cxx_host = Kokkos::create_mirror_view(cxx_device); std::copy(&f90_data[0], &f90_data[0] + max_pack_size, cxx_host.data()); Kokkos::deep_copy(cxx_device, cxx_host); // Get data from fortran for (auto& d : f90_data) { ni_conservation(d); } // Get data from cxx. Run ni_conservation from a kernel and copy results back to host Kokkos::parallel_for(num_test_itrs, KOKKOS_LAMBDA(const Int& i) { const Int offset = i * Spack::n; // Init pack inputs Spack nc2ni_immers_freeze_tend, ni, ni2nr_melt_tend, ni_nucleat_tend, ni_selfcollect_tend, ni_sublim_tend, nr2ni_immers_freeze_tend; for (Int s = 0, vs = offset; s < Spack::n; ++s, ++vs) { nc2ni_immers_freeze_tend[s] = cxx_device(vs).nc2ni_immers_freeze_tend; ni[s] = cxx_device(vs).ni; ni2nr_melt_tend[s] = cxx_device(vs).ni2nr_melt_tend; ni_nucleat_tend[s] = cxx_device(vs).ni_nucleat_tend; ni_selfcollect_tend[s] = cxx_device(vs).ni_selfcollect_tend; ni_sublim_tend[s] = cxx_device(vs).ni_sublim_tend; nr2ni_immers_freeze_tend[s] = cxx_device(vs).nr2ni_immers_freeze_tend; } Functions::ni_conservation(ni, ni_nucleat_tend, nr2ni_immers_freeze_tend, nc2ni_immers_freeze_tend, cxx_device(0).dt, ni2nr_melt_tend, ni_sublim_tend, ni_selfcollect_tend); // Copy spacks back into cxx_device view for (Int s = 0, vs = offset; s < Spack::n; ++s, ++vs) { cxx_device(vs).ni2nr_melt_tend = ni2nr_melt_tend[s]; cxx_device(vs).ni_selfcollect_tend = ni_selfcollect_tend[s]; cxx_device(vs).ni_sublim_tend = ni_sublim_tend[s]; } }); Kokkos::deep_copy(cxx_host, cxx_device); // Verify BFB results for (Int i = 0; i < num_runs; ++i) { NiConservationData& d_f90 = f90_data[i]; NiConservationData& d_cxx = cxx_host[i]; REQUIRE(d_f90.ni2nr_melt_tend == d_cxx.ni2nr_melt_tend); REQUIRE(d_f90.ni_sublim_tend == d_cxx.ni_sublim_tend); REQUIRE(d_f90.ni_selfcollect_tend == d_cxx.ni_selfcollect_tend); } } // run_bfb }; } // namespace unit_test } // namespace p3 } // namespace scream namespace { TEST_CASE("ni_conservation_bfb", "[p3]") { using TestStruct = scream::p3::unit_test::UnitWrap::UnitTest<scream::DefaultDevice>::TestNiConservation; TestStruct::run_bfb(); } } // empty namespace
33.928571
178
0.704662
f5079dc0b5a15d470dcfa4ffe09aa296a1c460b2
1,563
cpp
C++
code/Brain/MarkovBrain/Gate/TritDeterministicGate.cpp
cliff-bohm/Comparitive_Hybrid_Approach_Replication
44afa3ea663bc06eeca0bc272909329d8ffe81ec
[ "MIT" ]
null
null
null
code/Brain/MarkovBrain/Gate/TritDeterministicGate.cpp
cliff-bohm/Comparitive_Hybrid_Approach_Replication
44afa3ea663bc06eeca0bc272909329d8ffe81ec
[ "MIT" ]
null
null
null
code/Brain/MarkovBrain/Gate/TritDeterministicGate.cpp
cliff-bohm/Comparitive_Hybrid_Approach_Replication
44afa3ea663bc06eeca0bc272909329d8ffe81ec
[ "MIT" ]
null
null
null
// MABE is a product of The Hintze Lab @ MSU // for general research information: // hintzelab.msu.edu // for MABE documentation: // github.com/Hintzelab/MABE/wiki // // Copyright (c) 2015 Michigan State University. All rights reserved. // to view the full license, visit: // github.com/Hintzelab/MABE/wiki/License #include "TritDeterministicGate.h" std::shared_ptr<ParameterLink<std::string>> TritDeterministicGate::IO_RangesPL = Parameters::register_parameter("BRAIN_MARKOV_GATES_TRIT-IO_Ranges", (std::string)"1-4,1-4", "range of number of inputs and outputs (min inputs-max inputs,min outputs-max outputs)"); TritDeterministicGate::TritDeterministicGate(std::pair<std::vector<int>, std::vector<int>> addresses, std::vector<std::vector<int>> _table, int _ID, std::shared_ptr<ParametersTable> _PT) : AbstractGate(_PT) { ID = _ID; inputs = addresses.first; outputs = addresses.second; table = _table; } void TritDeterministicGate::update(std::vector<double> & nodes, std::vector<double> & nextNodes) { int input = vectorToTritToInt(nodes,inputs,true); // converts the input values into an index for (size_t i = 0; i < outputs.size(); i++) { nextNodes[outputs[i]] += table[input][i]; } } std::shared_ptr<AbstractGate> TritDeterministicGate::makeCopy(std::shared_ptr<ParametersTable> _PT) { if (_PT == nullptr) { _PT = PT; } auto newGate = std::make_shared<TritDeterministicGate>(_PT); newGate->table = table; newGate->ID = ID; newGate->inputs = inputs; newGate->outputs = outputs; return newGate; }
37.214286
262
0.71785
f509caebb3efb4ecd3e9e776cdbce2ad0248a6f8
1,921
hpp
C++
gamess/libqc/rysq/src/cuda/matrix.hpp
andremirt/v_cond
6b5c364d7cd4243686488b2bd4318be3927e07ea
[ "Unlicense" ]
null
null
null
gamess/libqc/rysq/src/cuda/matrix.hpp
andremirt/v_cond
6b5c364d7cd4243686488b2bd4318be3927e07ea
[ "Unlicense" ]
null
null
null
gamess/libqc/rysq/src/cuda/matrix.hpp
andremirt/v_cond
6b5c364d7cd4243686488b2bd4318be3927e07ea
[ "Unlicense" ]
null
null
null
#ifndef _RYSQ_MATRIX_HPP_ #define _RYSQ_MATRIX_HPP_ #include <stdlib.h> #if !defined(__host__) && !defined(__device__) #define __host__ #define __device__ #endif namespace rysq { struct matrix_layout { matrix_layout() {} matrix_layout(size_t size1, size_t size2, size_t ld = 0) : size1(size1),size2(size2), ld_((ld) ? ld : size1), size(ld_*size2) {} __host__ __device__ int element_at(int i,int j) const { return i + j* ld_;} size_t size1, size2, ld_, size; }; template<typename T> class matrix_data_array { matrix_layout layout_; T *data_; size_t size_; public: matrix_data_array() {} matrix_data_array(const matrix_layout &layout, T *data, size_t size) : layout_(layout), data_(data), size_(size){} const matrix_layout& layout() const { return layout_; } T* operator[](int i) { return data_ + i*layout_.size; } const T* operator[](int i) const { return data_ + i* layout_.size; } size_t size()const { return size_; } }; template<typename T> class matrix { matrix_layout layout_; T *data_; public: matrix() {} matrix(size_t size1, size_t size2, T *data,size_t ld = 0) : layout_(size1, size2, ld), data_(data) {} size_t size1 () const { return layout_.size1; } size_t size2 () const { return layout_.size2; } T& operator()(int i,int j) { return data_[layout_.element_at(i,j)]; } const T& operator()(int i,int j) const { return data_[layout_.element_at(i,j)]; } }; namespace cuda { void reduce(const rysq::matrix_data_array<double> A, double scale, rysq::matrix<double> B); // static void reduce(const rysq::matrix_data_array<double> A, // double scale, rysq::matrix<double> B) { // reduce <double>(A, scale, B); // } // static void reduce(const rysq::matrix_data_array<double> A, // double scale, rysq::matrix<double> B) { // reduce(A, scale, B); // } } } #endif /* _RYSQ_MATRIX_HPP_ */
26.680556
82
0.664237
f50a6043320384e34588a0d5f2f10c924d01f67f
648
cpp
C++
BlackVision/LibBlackVision/Source/Engine/Graphics/Shaders/Parameters/ShaderParamMat3.cpp
black-vision-engine/bv-engine
85089d41bb22afeaa9de070646e12aa1777ecedf
[ "MIT" ]
1
2022-01-28T11:43:47.000Z
2022-01-28T11:43:47.000Z
BlackVision/LibBlackVision/Source/Engine/Graphics/Shaders/Parameters/ShaderParamMat3.cpp
black-vision-engine/bv-engine
85089d41bb22afeaa9de070646e12aa1777ecedf
[ "MIT" ]
null
null
null
BlackVision/LibBlackVision/Source/Engine/Graphics/Shaders/Parameters/ShaderParamMat3.cpp
black-vision-engine/bv-engine
85089d41bb22afeaa9de070646e12aa1777ecedf
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "ShaderParamMat3.h" #include "Memory/MemoryLeaks.h" namespace bv { // **************************** // ShaderParamMat3::ShaderParamMat3 ( const std::string & name, const glm::mat3 & value ) : GenericShaderParam( ShaderParamTypeTraits< ValueMat3::ValueType >::paramType, name ) , m_val( value ) { } // **************************** // void ShaderParamMat3::SetValue ( const glm::mat3 & value ) { m_val = value; } // **************************** // const void * ShaderParamMat3::GetValuePtr () const { return &m_val; } } //bv
17.513514
102
0.501543
f50a93c785c58ac6098a6651290a4b9002dd9b49
1,126
hpp
C++
src/oni.hpp
typingtanuki/chato
61c76bda12d4ef855e3fad06338d94a3f1735971
[ "Apache-2.0" ]
null
null
null
src/oni.hpp
typingtanuki/chato
61c76bda12d4ef855e3fad06338d94a3f1735971
[ "Apache-2.0" ]
null
null
null
src/oni.hpp
typingtanuki/chato
61c76bda12d4ef855e3fad06338d94a3f1735971
[ "Apache-2.0" ]
null
null
null
#include "constants.hpp" #include "light.hpp" #include "motor.hpp" #include "timer.hpp" #include "keypad.hpp" enum OniState { INIT, IDLE, MOVE }; class Oni { private: Light *eye = new Light(DIGITAL_PIN3, 12, 24); Motor *eyeMotor = new Motor(DIGITAL_PIN9); Motor *axeMotor = new Motor(DIGITAL_PIN13); Light *axe = new Light(DIGITAL_PIN5, 60, 60); Keypad *keypad; bool autoEyeState = false; bool autoAxeState = false; unsigned long nextEyeTime = 0; unsigned long nextAxeTime = 0; unsigned long nextEyeMoveTime = 0; unsigned long nextOniTime = 0; LightState eyeState = OFF; LightState axeState = OFF; OniState oniState = INIT; void autoEyeControl(); void autoAxeControl(); void autoEyeLightControl(); void autoAxeLightControl(); void newEyeState(); static LightState nextLightPattern(LightState current); static LightState pickEyeState(); void newAxeState(); static LightState pickAxeState(); static OniState newOniState(); public: explicit Oni(Keypad *keypad); void init(); void loop(); };
18.766667
59
0.668739
f50c0a94e46967a99ecb3936474a09e047e75c0d
826
cpp
C++
summary-ranges/solution-0.cpp
tsenmu/leetcode
6f6d11dec4e5ee0fbc0c59fd6fa97b2c556e05ee
[ "Apache-2.0" ]
null
null
null
summary-ranges/solution-0.cpp
tsenmu/leetcode
6f6d11dec4e5ee0fbc0c59fd6fa97b2c556e05ee
[ "Apache-2.0" ]
null
null
null
summary-ranges/solution-0.cpp
tsenmu/leetcode
6f6d11dec4e5ee0fbc0c59fd6fa97b2c556e05ee
[ "Apache-2.0" ]
null
null
null
class Solution { protected: string yieldRange(int begin, int end) { if (begin == end) { return to_string(begin); } return to_string(begin) + "->" + to_string(end); } public: vector<string> summaryRanges(vector<int>& nums) { const int n = nums.size(); vector<string> result; if (n == 0) { return result; } if (n == 1) { result.push_back(yieldRange(nums[0], nums[0])); return result; } int last = nums[0]; int begin = last; for (int i = 1; i < n; ++i) { if (nums[i] - last != 1) { result.push_back(yieldRange(begin, last)); begin = nums[i]; } last = nums[i]; } result.push_back(yieldRange(begin, nums[n - 1])); return result; } };
21.179487
55
0.493947
f50c6328dd3f28621e77d38577eff115188dea88
1,119
cpp
C++
Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformer.cpp
aaarsene/o3de
37e3b0226958974defd14dd6d808e8557dcd7345
[ "Apache-2.0", "MIT" ]
1
2021-09-13T00:01:12.000Z
2021-09-13T00:01:12.000Z
Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformer.cpp
aaarsene/o3de
37e3b0226958974defd14dd6d808e8557dcd7345
[ "Apache-2.0", "MIT" ]
null
null
null
Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformer.cpp
aaarsene/o3de
37e3b0226958974defd14dd6d808e8557dcd7345
[ "Apache-2.0", "MIT" ]
1
2021-07-20T11:07:25.000Z
2021-07-20T11:07:25.000Z
/* * 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 the required headers #include "MeshDeformer.h" #include <EMotionFX/Source/Allocators.h> namespace EMotionFX { AZ_CLASS_ALLOCATOR_IMPL(MeshDeformer, DeformerAllocator, 0) // constructor MeshDeformer::MeshDeformer(Mesh* mesh) : BaseObject() { mMesh = mesh; mIsEnabled = true; } // destructor MeshDeformer::~MeshDeformer() { } // check if the deformer is enabled bool MeshDeformer::GetIsEnabled() const { return mIsEnabled; } // enable or disable it void MeshDeformer::SetIsEnabled(bool enabled) { mIsEnabled = enabled; } // reinitialize the mesh deformer void MeshDeformer::Reinitialize(Actor* actor, Node* node, uint32 lodLevel) { MCORE_UNUSED(actor); MCORE_UNUSED(node); MCORE_UNUSED(lodLevel); } } // namespace EMotionFX
20.722222
158
0.649687
f50f03ccfa9b71427ab0430e3de9159602a849f4
423
cpp
C++
tests/testsmain.cpp
k9lego/huestacean
e72b43b66cc3b6b58554fa49ac207ad9f945c3fb
[ "Apache-2.0" ]
540
2018-02-16T15:15:43.000Z
2022-03-01T22:35:18.000Z
tests/testsmain.cpp
k9lego/huestacean
e72b43b66cc3b6b58554fa49ac207ad9f945c3fb
[ "Apache-2.0" ]
153
2018-02-19T13:33:14.000Z
2022-02-26T04:57:10.000Z
tests/testsmain.cpp
k9lego/huestacean
e72b43b66cc3b6b58554fa49ac207ad9f945c3fb
[ "Apache-2.0" ]
66
2018-03-17T10:54:54.000Z
2022-02-16T16:20:46.000Z
#define CATCH_CONFIG_RUNNER #include "catch/catch.hpp" #include <QCoreApplication> int main(int argc, char* argv[]) { QCoreApplication a(argc, argv); QCoreApplication::setOrganizationName("Brady Brenot"); QCoreApplication::setOrganizationDomain("bradybrenot.com"); QCoreApplication::setApplicationName("Huestacean Test"); int result = Catch::Session().run(argc, argv); return (result < 0xff ? result : 0xff); }
22.263158
60
0.751773
f50f1174e3844b028bb752ce92df7036d918a0df
4,461
cpp
C++
source/shared/cpp/ObjectModel/ActionParserRegistration.cpp
sivasakthiv/AdaptiveCards
dfa4bfef70c1111e1a5cc8eed90b2f1e8d76f75c
[ "MIT" ]
1
2020-12-07T10:57:38.000Z
2020-12-07T10:57:38.000Z
source/shared/cpp/ObjectModel/ActionParserRegistration.cpp
sivasakthiv/AdaptiveCards
dfa4bfef70c1111e1a5cc8eed90b2f1e8d76f75c
[ "MIT" ]
43
2020-09-04T23:34:16.000Z
2022-02-26T11:36:24.000Z
source/shared/cpp/ObjectModel/ActionParserRegistration.cpp
sivasakthiv/AdaptiveCards
dfa4bfef70c1111e1a5cc8eed90b2f1e8d76f75c
[ "MIT" ]
16
2021-02-10T07:46:07.000Z
2021-11-23T10:22:44.000Z
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "pch.h" #include "ActionParserRegistration.h" #include "AdaptiveCardParseException.h" #include "BaseElement.h" #include "OpenUrlAction.h" #include "ShowCardAction.h" #include "SubmitAction.h" #include "ToggleVisibilityAction.h" #include "UnknownAction.h" namespace AdaptiveSharedNamespace { ActionElementParserWrapper::ActionElementParserWrapper(std::shared_ptr<ActionElementParser> parserToWrap) : m_parser{parserToWrap} { } std::shared_ptr<BaseActionElement> ActionElementParserWrapper::Deserialize(ParseContext& context, const Json::Value& value) { const auto& idProperty = ParseUtil::GetString(value, AdaptiveCardSchemaKey::Id); const AdaptiveSharedNamespace::InternalId internalId = AdaptiveSharedNamespace::InternalId::Next(); context.PushElement(idProperty, internalId); std::shared_ptr<BaseActionElement> element = m_parser->Deserialize(context, value); context.PopElement(); return element; } std::shared_ptr<BaseActionElement> ActionElementParserWrapper::DeserializeFromString(ParseContext& context, const std::string& value) { return Deserialize(context, ParseUtil::GetJsonValueFromString(value)); } ActionParserRegistration::ActionParserRegistration() { m_knownElements.insert({ ActionTypeToString(ActionType::OpenUrl), ActionTypeToString(ActionType::ShowCard), ActionTypeToString(ActionType::Submit), ActionTypeToString(ActionType::ToggleVisibility), ActionTypeToString(ActionType::UnknownAction), }); m_cardElementParsers.insert( {{ActionTypeToString(ActionType::OpenUrl), std::make_shared<OpenUrlActionParser>()}, {ActionTypeToString(ActionType::ShowCard), std::make_shared<ShowCardActionParser>()}, {ActionTypeToString(ActionType::Submit), std::make_shared<SubmitActionParser>()}, {ActionTypeToString(ActionType::ToggleVisibility), std::make_shared<ToggleVisibilityActionParser>()}, {ActionTypeToString(ActionType::UnknownAction), std::make_shared<UnknownActionParser>()}}); } void ActionParserRegistration::AddParser(std::string const& elementType, std::shared_ptr<ActionElementParser> parser) { // make sure caller isn't attempting to overwrite a known element's parser if (m_knownElements.find(elementType) == m_knownElements.end()) { ActionParserRegistration::m_cardElementParsers[elementType] = parser; } else { throw AdaptiveCardParseException(ErrorStatusCode::UnsupportedParserOverride, "Overriding known action parsers is unsupported"); } } void ActionParserRegistration::RemoveParser(std::string const& elementType) { // make sure caller isn't attempting to remove a known element's parser if (m_knownElements.find(elementType) == m_knownElements.end()) { ActionParserRegistration::m_cardElementParsers.erase(elementType); } else { throw AdaptiveCardParseException(ErrorStatusCode::UnsupportedParserOverride, "Removing known action parsers is unsupported"); } } std::shared_ptr<ActionElementParser> ActionParserRegistration::GetParser(std::string const& elementType) const { auto parser = m_cardElementParsers.find(elementType); if (parser != ActionParserRegistration::m_cardElementParsers.end()) { // Why do we wrap the parser? As we parse elements, we need to push and pop state from the stack for ID // collision detection. We *could* do this within the implementation of parsers themselves, but that would // mean having to explain all of this to custom element parser implementors. Instead, we wrap every parser // we hand out with a helper class that performs the push/pop on behalf of the element parser. For more // details, refer to the giant comment on ID collision detection in ParseContext.cpp. std::shared_ptr<ActionElementParser> wrappedParser = std::make_shared<ActionElementParserWrapper>(parser->second); return wrappedParser; } else { return std::shared_ptr<ActionElementParser>(nullptr); } } }
44.61
139
0.702085
f5112da53a614a87c972b3056dee8ff3b0850e52
2,957
hpp
C++
include/codegen/include/UnityEngine/EventSystems/OVRPhysicsRaycaster_--c.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/UnityEngine/EventSystems/OVRPhysicsRaycaster_--c.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/UnityEngine/EventSystems/OVRPhysicsRaycaster_--c.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:06 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "utils/typedefs.h" // Including type: System.Object #include "System/Object.hpp" // Including type: UnityEngine.EventSystems.OVRPhysicsRaycaster #include "UnityEngine/EventSystems/OVRPhysicsRaycaster.hpp" // Including type: UnityEngine.RaycastHit #include "UnityEngine/RaycastHit.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System namespace System { // Forward declaring type: Comparison`1<T> template<typename T> class Comparison_1; } // Completed forward declares // Type namespace: UnityEngine.EventSystems namespace UnityEngine::EventSystems { // Autogenerated type: UnityEngine.EventSystems.OVRPhysicsRaycaster/<>c class OVRPhysicsRaycaster::$$c : public ::Il2CppObject { public: // Get static field: static public readonly UnityEngine.EventSystems.OVRPhysicsRaycaster/<>c <>9 static UnityEngine::EventSystems::OVRPhysicsRaycaster::$$c* _get_$$9(); // Set static field: static public readonly UnityEngine.EventSystems.OVRPhysicsRaycaster/<>c <>9 static void _set_$$9(UnityEngine::EventSystems::OVRPhysicsRaycaster::$$c* value); // Get static field: static public System.Comparison`1<UnityEngine.RaycastHit> <>9__15_0 static System::Comparison_1<UnityEngine::RaycastHit>* _get_$$9__15_0(); // Set static field: static public System.Comparison`1<UnityEngine.RaycastHit> <>9__15_0 static void _set_$$9__15_0(System::Comparison_1<UnityEngine::RaycastHit>* value); // Get static field: static public System.Comparison`1<UnityEngine.RaycastHit> <>9__16_0 static System::Comparison_1<UnityEngine::RaycastHit>* _get_$$9__16_0(); // Set static field: static public System.Comparison`1<UnityEngine.RaycastHit> <>9__16_0 static void _set_$$9__16_0(System::Comparison_1<UnityEngine::RaycastHit>* value); // static private System.Void .cctor() // Offset: 0x18EA91C static void _cctor(); // System.Int32 <Raycast>b__15_0(UnityEngine.RaycastHit r1, UnityEngine.RaycastHit r2) // Offset: 0x18EA98C int $Raycast$b__15_0(UnityEngine::RaycastHit r1, UnityEngine::RaycastHit r2); // System.Int32 <Spherecast>b__16_0(UnityEngine.RaycastHit r1, UnityEngine.RaycastHit r2) // Offset: 0x18EA9D0 int $Spherecast$b__16_0(UnityEngine::RaycastHit r1, UnityEngine::RaycastHit r2); // public System.Void .ctor() // Offset: 0x18EA984 // Implemented from: System.Object // Base method: System.Void Object::.ctor() static OVRPhysicsRaycaster::$$c* New_ctor(); }; // UnityEngine.EventSystems.OVRPhysicsRaycaster/<>c } DEFINE_IL2CPP_ARG_TYPE(UnityEngine::EventSystems::OVRPhysicsRaycaster::$$c*, "UnityEngine.EventSystems", "OVRPhysicsRaycaster/<>c"); #pragma pack(pop)
50.118644
132
0.735543
f511311f7559c4372d7dd7dca01bd935d8d911ca
1,069
hpp
C++
lib/inc/facter/facts/windows/dmi_resolver.hpp
whopper/cfacter
f489f62e19a161e2d909199aebd896e323dac0e8
[ "Apache-2.0" ]
null
null
null
lib/inc/facter/facts/windows/dmi_resolver.hpp
whopper/cfacter
f489f62e19a161e2d909199aebd896e323dac0e8
[ "Apache-2.0" ]
null
null
null
lib/inc/facter/facts/windows/dmi_resolver.hpp
whopper/cfacter
f489f62e19a161e2d909199aebd896e323dac0e8
[ "Apache-2.0" ]
null
null
null
/** * @file * Declares the Windows Desktop Management Information (DMI) fact resolver. */ #pragma once #include "../resolvers/dmi_resolver.hpp" #include <facter/util/windows/wmi.hpp> #include <string> #include <memory> namespace facter { namespace facts { namespace windows { /** * Responsible for resolving DMI facts. */ struct dmi_resolver : resolvers::dmi_resolver { /** * Constructs the dmi_resolver. * @param wmi_conn The WMI connection to use when resolving facts. */ dmi_resolver(std::shared_ptr<util::windows::wmi> wmi_conn = std::make_shared<util::windows::wmi>()); protected: /** * Collects the resolver data. * @param facts The fact collection that is resolving facts. * @return Returns the resolver data. */ virtual data collect_data(collection& facts) override; private: std::string read(std::string const& path); std::shared_ptr<util::windows::wmi> _wmi; }; }}} // namespace facter::facts::windows
27.410256
108
0.634238
f511d895d75af332b9ef48f66861792b00977e63
6,078
hpp
C++
communication/include/communication/CommDefs.hpp
irisk29/concord-bft
daf6a4a156fa2e9107f65de6ec6a26c39cd99796
[ "Apache-2.0" ]
null
null
null
communication/include/communication/CommDefs.hpp
irisk29/concord-bft
daf6a4a156fa2e9107f65de6ec6a26c39cd99796
[ "Apache-2.0" ]
null
null
null
communication/include/communication/CommDefs.hpp
irisk29/concord-bft
daf6a4a156fa2e9107f65de6ec6a26c39cd99796
[ "Apache-2.0" ]
null
null
null
// Concord // // Copyright (c) 2018-2020 VMware, Inc. All Rights Reserved. // // This product is licensed to you under the Apache 2.0 license (the "License"). // You may not use this product except in compliance with the Apache 2.0 License. // // This product may include a number of subcomponents with separate copyright // notices and license terms. Your use of these subcomponents is subject to the // terms and conditions of the subcomponent's license, as noted in the // LICENSE file. #pragma once #include <string> #include <cstdint> #include <memory> #include <unordered_map> #include <arpa/inet.h> #include <netdb.h> #include <sys/socket.h> #include <unistd.h> #include "communication/ICommunication.hpp" #include "communication/StatusInfo.h" #include "secret_data.h" namespace bft::communication { typedef struct sockaddr_in Addr; struct NodeInfo { std::string host; std::uint16_t port; bool isReplica; }; typedef std::unordered_map<NodeNum, NodeInfo> NodeMap; enum CommType { PlainUdp, SimpleAuthUdp, PlainTcp, SimpleAuthTcp, TlsTcp }; struct BaseCommConfig { CommType commType; std::string listenHost; uint16_t listenPort; uint32_t bufferLength; NodeMap nodes; UPDATE_CONNECTIVITY_FN statusCallback; NodeNum selfId; BaseCommConfig(CommType type, const std::string &host, uint16_t port, uint32_t bufLength, NodeMap _nodes, NodeNum _selfId, UPDATE_CONNECTIVITY_FN _statusCallback = nullptr) : commType{type}, listenHost{host}, listenPort{port}, bufferLength{bufLength}, nodes{std::move(_nodes)}, statusCallback{std::move(_statusCallback)}, selfId{_selfId} {} virtual ~BaseCommConfig() = default; }; struct PlainUdpConfig : BaseCommConfig { PlainUdpConfig(const std::string &host, uint16_t port, uint32_t bufLength, NodeMap _nodes, NodeNum _selfId, UPDATE_CONNECTIVITY_FN _statusCallback = nullptr) : BaseCommConfig( CommType::PlainUdp, host, port, bufLength, std::move(_nodes), _selfId, std::move(_statusCallback)) {} }; struct PlainTcpConfig : BaseCommConfig { int32_t maxServerId; PlainTcpConfig(const std::string &host, uint16_t port, uint32_t bufLength, NodeMap _nodes, int32_t _maxServerId, NodeNum _selfId, UPDATE_CONNECTIVITY_FN _statusCallback = nullptr) : BaseCommConfig( CommType::PlainTcp, host, port, bufLength, std::move(_nodes), _selfId, std::move(_statusCallback)), maxServerId{_maxServerId} {} }; struct TlsTcpConfig : PlainTcpConfig { std::string certificatesRootPath; // set specific suite or list of suites, as described in OpenSSL // https://www.openssl.org/docs/man1.0.2/man1/ciphers.html std::string cipherSuite; std::optional<concord::secretsmanager::SecretData> secretData; TlsTcpConfig(const std::string &host, uint16_t port, uint32_t bufLength, NodeMap _nodes, int32_t _maxServerId, NodeNum _selfId, const std::string &certRootPath, const std::string &ciphSuite, UPDATE_CONNECTIVITY_FN _statusCallback = nullptr, std::optional<concord::secretsmanager::SecretData> decryptionSecretData = std::nullopt) : PlainTcpConfig(host, port, bufLength, std::move(_nodes), _maxServerId, _selfId, std::move(_statusCallback)), certificatesRootPath{certRootPath}, cipherSuite{ciphSuite}, secretData{std::move(decryptionSecretData)} { commType = CommType::TlsTcp; } }; class PlainUDPCommunication : public ICommunication { public: static PlainUDPCommunication *create(const PlainUdpConfig &config); int getMaxMessageSize() override; int Start() override; int Stop() override; bool isRunning() const override; ConnectionStatus getCurrentConnectionStatus(NodeNum node) override; int send(NodeNum destNode, std::vector<uint8_t> &&msg) override; std::set<NodeNum> send(std::set<NodeNum> dests, std::vector<uint8_t> &&msg) override; void setReceiver(NodeNum receiverNum, IReceiver *receiver) override; ~PlainUDPCommunication() override; private: class PlainUdpImpl; // TODO(IG): convert to smart ptr PlainUdpImpl *_ptrImpl = nullptr; explicit PlainUDPCommunication(const PlainUdpConfig &config); }; class PlainTCPCommunication : public ICommunication { public: static PlainTCPCommunication *create(const PlainTcpConfig &config); int getMaxMessageSize() override; int Start() override; int Stop() override; bool isRunning() const override; ConnectionStatus getCurrentConnectionStatus(NodeNum node) override; int send(NodeNum destNode, std::vector<uint8_t> &&msg) override; std::set<NodeNum> send(std::set<NodeNum> dests, std::vector<uint8_t> &&msg) override; void setReceiver(NodeNum receiverNum, IReceiver *receiver) override; ~PlainTCPCommunication() override; private: class PlainTcpImpl; PlainTcpImpl *_ptrImpl = nullptr; explicit PlainTCPCommunication(const PlainTcpConfig &config); }; class TlsTCPCommunication : public ICommunication { public: static TlsTCPCommunication *create(const TlsTcpConfig &config); int getMaxMessageSize() override; int Start() override; int Stop() override; bool isRunning() const override; ConnectionStatus getCurrentConnectionStatus(NodeNum node) override; int send(NodeNum destNode, std::vector<uint8_t> &&msg) override; std::set<NodeNum> send(std::set<NodeNum> dests, std::vector<uint8_t> &&msg) override; void setReceiver(NodeNum receiverNum, IReceiver *receiver) override; ~TlsTCPCommunication() override; private: class TlsTcpImpl; friend class AsyncTlsConnection; std::unique_ptr<TlsTcpImpl> impl_; explicit TlsTCPCommunication(const TlsTcpConfig &config); }; } // namespace bft::communication
30.69697
116
0.699737
f512db47e285be6ddab66ee5372e8d187e73778a
1,251
hpp
C++
include/pstore/http/http_date.hpp
paulhuggett/pstore2
a0c663d10a2e2713fdf39ecdae1f9c1e96041f5c
[ "Apache-2.0" ]
11
2018-02-02T21:24:49.000Z
2020-12-11T04:06:03.000Z
include/pstore/http/http_date.hpp
SNSystems/pstore
74e9dd960245d6bfc125af03ed964d8ad660a62d
[ "Apache-2.0" ]
63
2018-02-05T17:24:59.000Z
2022-03-22T17:26:28.000Z
include/pstore/http/http_date.hpp
paulhuggett/pstore
067be94d87c87fce524c8d76c6f47c347d8f1853
[ "Apache-2.0" ]
5
2020-01-13T22:47:11.000Z
2021-05-14T09:31:15.000Z
//===- include/pstore/http/http_date.hpp ------------------*- mode: C++ -*-===// //* _ _ _ _ _ * //* | |__ | |_| |_ _ __ __| | __ _| |_ ___ * //* | '_ \| __| __| '_ \ / _` |/ _` | __/ _ \ * //* | | | | |_| |_| |_) | | (_| | (_| | || __/ * //* |_| |_|\__|\__| .__/ \__,_|\__,_|\__\___| * //* |_| * //===----------------------------------------------------------------------===// // // Part of the pstore project, under the Apache License v2.0 with LLVM Exceptions. // See https://github.com/SNSystems/pstore/blob/master/LICENSE.txt for license // information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// /// \file http_date.hpp /// \brief Functions to return a dated formatted for HTTP. #ifndef PSTORE_HTTP_HTTP_DATE_HPP #define PSTORE_HTTP_HTTP_DATE_HPP #include <chrono> #include <ctime> #include <string> namespace pstore { namespace http { std::string http_date (std::chrono::system_clock::time_point time); std::string http_date (std::time_t time); } // end namespace http } // end namespace pstore #endif // PSTORE_HTTP_HTTP_DATE_HPP
35.742857
82
0.489209
f513e3c60c7f985be18935ddb5faf2b14b497f63
2,379
cpp
C++
python/NpcompModule.cpp
raikonenfnu/mlir-npcomp
29e1b2fe89848d58c9bc07e7df7ce651850a5244
[ "Apache-2.0" ]
null
null
null
python/NpcompModule.cpp
raikonenfnu/mlir-npcomp
29e1b2fe89848d58c9bc07e7df7ce651850a5244
[ "Apache-2.0" ]
null
null
null
python/NpcompModule.cpp
raikonenfnu/mlir-npcomp
29e1b2fe89848d58c9bc07e7df7ce651850a5244
[ "Apache-2.0" ]
null
null
null
//===- NpcompModule.cpp - MLIR Python bindings ----------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include <cstddef> #include <unordered_map> #include "./NpcompModule.h" #include "./NpcompPybindUtils.h" #include "mlir-c/BuiltinAttributes.h" #include "mlir-c/BuiltinTypes.h" #include "mlir-c/Diagnostics.h" #include "npcomp-c/BasicpyTypes.h" #include "npcomp-c/InitLLVM.h" #include "npcomp-c/NumpyTypes.h" #include "npcomp-c/Registration.h" namespace { MlirType shapedToNdArrayArrayType(MlirType shaped_type) { if (!mlirTypeIsAShaped(shaped_type)) { throw py::raiseValueError("type is not a shaped type"); } return npcompNumpyNdArrayTypeGetFromShaped(shaped_type); } MlirType ndarrayToTensorType(MlirType ndarray_type) { if (!npcompTypeIsANumpyNdArray(ndarray_type)) { throw py::raiseValueError("type is not an ndarray type"); } return npcompNumpyNdArrayTypeToTensor(ndarray_type); } MlirType slotObjectType(MlirContext context, const std::string &className, const std::vector<MlirType> &slotTypes) { MlirStringRef classNameSr{className.data(), className.size()}; return ::npcompBasicPySlotObjectTypeGet(context, classNameSr, slotTypes.size(), slotTypes.data()); } // TODO: Move this upstream. void emitError(MlirLocation loc, std::string message) { ::mlirEmitError(loc, message.c_str()); } } // namespace PYBIND11_MODULE(_npcomp, m) { m.doc() = "Npcomp native python bindings"; ::npcompRegisterAllPasses(); ::npcompInitializeLLVMCodegen(); m.def("register_all_dialects", ::npcompRegisterAllDialects); m.def("shaped_to_ndarray_type", shapedToNdArrayArrayType); m.def("ndarray_to_tensor_type", ndarrayToTensorType); m.def("slot_object_type", slotObjectType); m.def("emit_error", emitError); // Optional backend modules. auto backend_m = m.def_submodule("backend", "Backend support"); (void)backend_m; #ifdef NPCOMP_ENABLE_REFJIT auto refjit_m = backend_m.def_submodule("refjit", "Reference CPU Jit Backend"); ::npcomp::python::defineBackendRefJitModule(refjit_m); #endif }
32.148649
80
0.697352
f513e4ca1c2b159ea29dd107a50d782fc2c2ca51
7,446
cpp
C++
src/qpsolver/basis.cpp
WTFHCN/HiGHS
6cec473fc821bca0d98517a11691da8b5e1b0e51
[ "MIT" ]
null
null
null
src/qpsolver/basis.cpp
WTFHCN/HiGHS
6cec473fc821bca0d98517a11691da8b5e1b0e51
[ "MIT" ]
null
null
null
src/qpsolver/basis.cpp
WTFHCN/HiGHS
6cec473fc821bca0d98517a11691da8b5e1b0e51
[ "MIT" ]
null
null
null
#include "basis.hpp" #include <cassert> #include <memory> Basis::Basis(Runtime& rt, std::vector<HighsInt> active, std::vector<BasisStatus> lower, std::vector<HighsInt> inactive) : runtime(rt), buffer_column_aq(rt.instance.num_var), buffer_row_ep(rt.instance.num_var) { for (HighsInt i = 0; i < active.size(); i++) { activeconstraintidx.push_back(active[i]); basisstatus[activeconstraintidx[i]] = lower[i]; } for (HighsInt i : inactive) { nonactiveconstraintsidx.push_back(i); } Atran = rt.instance.A.t(); build(); } void Basis::build() { updatessinceinvert = 0; baseindex = new HighsInt[activeconstraintidx.size() + nonactiveconstraintsidx.size()]; constraintindexinbasisfactor.clear(); basisfactor = HFactor(); constraintindexinbasisfactor.assign(Atran.num_row + Atran.num_col, -1); assert(nonactiveconstraintsidx.size() + activeconstraintidx.size() == Atran.num_row); HighsInt counter = 0; for (HighsInt i : nonactiveconstraintsidx) { baseindex[counter++] = i; } for (HighsInt i : activeconstraintidx) { baseindex[counter++] = i; } const bool empty_matrix = (int)Atran.index.size() == 0; if (empty_matrix) { // The index/value vectors have size zero if the matrix has no // columns. However, in the Windows build, referring to index 0 of a // vector of size zero causes a failure, so resize to 1 to prevent // this. assert(Atran.num_col == 0); Atran.index.resize(1); Atran.value.resize(1); } basisfactor.setup(Atran.num_col, Atran.num_row, (HighsInt*)&Atran.start[0], (HighsInt*)&Atran.index[0], (const double*)&Atran.value[0], baseindex); basisfactor.build(); for (size_t i = 0; i < activeconstraintidx.size() + nonactiveconstraintsidx.size(); i++) { constraintindexinbasisfactor[baseindex[i]] = i; } } void Basis::rebuild() { updatessinceinvert = 0; constraintindexinbasisfactor.clear(); constraintindexinbasisfactor.assign(Atran.num_row + Atran.num_col, -1); assert(nonactiveconstraintsidx.size() + activeconstraintidx.size() == Atran.num_row); basisfactor.build(); for (size_t i = 0; i < activeconstraintidx.size() + nonactiveconstraintsidx.size(); i++) { constraintindexinbasisfactor[baseindex[i]] = i; } } void Basis::report() { printf("basis: "); for (HighsInt a_ : activeconstraintidx) { printf("%" HIGHSINT_FORMAT " ", a_); } printf(" - "); for (HighsInt n_ : nonactiveconstraintsidx) { printf("%" HIGHSINT_FORMAT " ", n_); } printf("\n"); } // move that constraint into V section basis (will correspond to Nullspace // from now on) void Basis::deactivate(HighsInt conid) { // printf("deact %" HIGHSINT_FORMAT "\n", conid); assert(contains(activeconstraintidx, conid)); basisstatus.erase(conid); remove(activeconstraintidx, conid); nonactiveconstraintsidx.push_back(conid); } void Basis::activate(Runtime& rt, HighsInt conid, BasisStatus atlower, HighsInt nonactivetoremove, Pricing* pricing) { // printf("activ %" HIGHSINT_FORMAT "\n", conid); if (!contains(activeconstraintidx, (HighsInt)conid)) { basisstatus[conid] = atlower; activeconstraintidx.push_back(conid); } else { printf("Degeneracy? constraint %" HIGHSINT_FORMAT " already in basis\n", conid); exit(1); } // printf("drop %d\n", nonactivetoremove); // remove non-active row from basis HighsInt rowtoremove = constraintindexinbasisfactor[nonactivetoremove]; baseindex[rowtoremove] = conid; remove(nonactiveconstraintsidx, nonactivetoremove); updatebasis(rt, conid, nonactivetoremove, pricing); if (updatessinceinvert != 0) { constraintindexinbasisfactor[nonactivetoremove] = -1; constraintindexinbasisfactor[conid] = rowtoremove; } } void Basis::updatebasis(Runtime& rt, HighsInt newactivecon, HighsInt droppedcon, Pricing* pricing) { if (newactivecon == droppedcon) { return; } HighsInt droppedcon_rowindex = constraintindexinbasisfactor[droppedcon]; Atran.extractcol(newactivecon, buffer_column_aq); // column.report("col_pre_ftran"); HVector column_aq_hvec = vec2hvec(buffer_column_aq); basisfactor.ftran(column_aq_hvec, 1.0); // column.report("col_post_ftran"); Vector::unit(rt.instance.A.mat.num_col, droppedcon_rowindex, buffer_row_ep); // row_ep.report("rowep_pre_btran"); HVector row_ep_hvec = vec2hvec(buffer_row_ep); basisfactor.btran(row_ep_hvec, 1.0); // row_ep.report("rowep_post_btran"); pricing->update_weights(hvec2vec(column_aq_hvec), hvec2vec(row_ep_hvec), droppedcon, newactivecon); HighsInt hint = 99999; HighsInt row_out = droppedcon_rowindex; updatessinceinvert++; basisfactor.update(&column_aq_hvec, &row_ep_hvec, &row_out, &hint); if (updatessinceinvert >= rt.settings.reinvertfrequency || hint != 99999) { rebuild(); // printf("Hint: %d\n", hint); // printf("reinvert\n"); } } Vector& Basis::btran(const Vector& rhs, Vector& target) const { HVector rhs_hvec = vec2hvec(rhs); basisfactor.btran(rhs_hvec, 1.0); return hvec2vec(rhs_hvec, target); } Vector Basis::btran(const Vector& rhs) const { HVector rhs_hvec = vec2hvec(rhs); basisfactor.btran(rhs_hvec, 1.0); return hvec2vec(rhs_hvec); } Vector& Basis::ftran(const Vector& rhs, Vector& target) const { HVector rhs_hvec = vec2hvec(rhs); basisfactor.ftran(rhs_hvec, 1.0); return hvec2vec(rhs_hvec, target); } Vector Basis::ftran(const Vector& rhs) const { HVector rhs_hvec = vec2hvec(rhs); basisfactor.ftran(rhs_hvec, 1.0); return hvec2vec(rhs_hvec); } Vector Basis::recomputex(const Instance& inst) { assert(activeconstraintidx.size() == inst.num_var); Vector rhs(inst.num_var); for (HighsInt i = 0; i < inst.num_var; i++) { HighsInt con = activeconstraintidx[i]; if (constraintindexinbasisfactor[con] == -1) { printf("error\n"); } if (basisstatus[con] == BasisStatus::ActiveAtLower) { if (con < inst.num_con) { rhs.value[constraintindexinbasisfactor[con]] = inst.con_lo[con]; } else { rhs.value[constraintindexinbasisfactor[con]] = inst.var_lo[con - inst.num_con]; } } else { if (con < inst.num_con) { rhs.value[constraintindexinbasisfactor[con]] = inst.con_up[con]; // rhs.value[i] = inst.con_up[con]; } else { rhs.value[constraintindexinbasisfactor[con]] = inst.var_up[con - inst.num_con]; // rhs.value[i] = inst.var_up[con - inst.num_con]; } } rhs.index[i] = i; rhs.num_nz++; } HVector rhs_hvec = vec2hvec(rhs); basisfactor.btran(rhs_hvec, 1.0); return hvec2vec(rhs_hvec); } // void Basis::write(std::string filename) { // FILE* file = fopen(filename.c_str(), "w"); // fprintf(file, "%lu %lu\n", activeconstraintidx.size(), // nonactiveconstraintsidx.size()); for (HighsInt i=0; // i<activeconstraintidx.size(); i++) { // fprintf(file, "%" HIGHSINT_FORMAT " %" HIGHSINT_FORMAT "\n", // activeconstraintidx[i], (HighsInt)rowstatus[i]); // } // for (HighsInt i=0; i<nonactiveconstraintsidx.size(); i++) { // fprintf(file, "%" HIGHSINT_FORMAT " %" HIGHSINT_FORMAT "\n", // nonactiveconstraintsidx[i], (HighsInt)rowstatus[i]); // } // // TODO // fclose(file); // }
30.145749
80
0.668278
f514f43dfc4e379bd2576de01936369eed88d2a8
14,357
hpp
C++
src/3rd party/boost/boost/multi_array/view.hpp
OLR-xray/OLR-3.0
b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611
[ "Apache-2.0" ]
8
2016-01-25T20:18:51.000Z
2019-03-06T07:00:04.000Z
src/3rd party/boost/boost/multi_array/view.hpp
OLR-xray/OLR-3.0
b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611
[ "Apache-2.0" ]
null
null
null
src/3rd party/boost/boost/multi_array/view.hpp
OLR-xray/OLR-3.0
b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611
[ "Apache-2.0" ]
3
2016-02-14T01:20:43.000Z
2021-02-03T11:19:11.000Z
// Copyright (C) 2002 Ronald Garcia // // Permission to copy, use, sell and distribute this software is granted // provided this copyright notice appears in all copies. // Permission to modify the code and to distribute modified code is granted // provided this copyright notice appears in all copies, and a notice // that the code was modified is included with the copyright notice. // // This software is provided "as is" without express or implied warranty, // and with no claim as to its suitability for any purpose. // #ifndef BOOST_MULTI_ARRAY_VIEW_RG071301_HPP #define BOOST_MULTI_ARRAY_VIEW_RG071301_HPP // // view.hpp - code for creating "views" of array data. // #include "boost/multi_array/base.hpp" #include "boost/multi_array/concept_checks.hpp" #include "boost/multi_array/iterator.hpp" #include "boost/multi_array/storage_order.hpp" #include "boost/multi_array/subarray.hpp" #include "boost/multi_array/algorithm.hpp" #include "boost/array.hpp" #include "boost/limits.hpp" #include <algorithm> #include <cstddef> #include <functional> #include <numeric> namespace boost { namespace detail { namespace multi_array { // TPtr = const T* defaulted in base.hpp template <typename T, std::size_t NumDims, typename TPtr> class const_multi_array_view : public boost::detail::multi_array::multi_array_impl_base<T,NumDims> { typedef boost::detail::multi_array::multi_array_impl_base<T,NumDims> super_type; public: typedef typename super_type::value_type value_type; typedef typename super_type::const_reference const_reference; typedef typename super_type::const_iterator const_iterator; typedef typename super_type::const_iter_base const_iter_base; typedef typename super_type::const_reverse_iterator const_reverse_iterator; typedef typename super_type::element element; typedef typename super_type::size_type size_type; typedef typename super_type::difference_type difference_type; typedef typename super_type::index index; typedef typename super_type::extent_range extent_range; // template typedefs template <std::size_t NDims> struct const_array_view { typedef boost::detail::multi_array::const_multi_array_view<T,NDims> type; }; template <std::size_t NDims> struct array_view { typedef boost::detail::multi_array::multi_array_view<T,NDims> type; }; template <typename OPtr> const_multi_array_view(const const_multi_array_view<T,NumDims,OPtr>& other) : base_(other.base_), origin_offset_(other.origin_offset_), num_elements_(other.num_elements_), extent_list_(other.extent_list_), stride_list_(other.stride_list_), index_base_list_(other.index_base_list_) { } template <class BaseList> void reindex(const BaseList& values) { boost::copy_n(values.begin(),num_dimensions(),index_base_list_.begin()); origin_offset_ = this->calculate_indexing_offset(stride_list_,index_base_list_); } void reindex(index value) { index_base_list_.assign(value); origin_offset_ = this->calculate_indexing_offset(stride_list_,index_base_list_); } size_type num_dimensions() const { return NumDims; } size_type size() const { return extent_list_.front(); } size_type max_size() const { return num_elements(); } bool empty() const { return size() == 0; } const size_type* shape() const { return extent_list_.data(); } const index* strides() const { return stride_list_.data(); } const T* origin() const { return base_+origin_offset_; } size_type num_elements() const { return num_elements_; } const index* index_bases() const { return index_base_list_.data(); } template <typename IndexList> const element& operator()(IndexList indices) const { return super_type::access_element(boost::type<const element&>(), origin(), indices,strides()); } // Only allow const element access const_reference operator[](index idx) const { return super_type::access(boost::type<const_reference>(), idx,origin(), shape(),strides(), index_bases()); } // see generate_array_view in base.hpp #if !defined(BOOST_MSVC) || BOOST_MSVC > 1300 template <int NDims> #else template <int NumDims, int NDims> // else ICE #endif // BOOST_MSVC typename const_array_view<NDims>::type operator[](const boost::detail::multi_array:: index_gen<NumDims,NDims>& indices) const { typedef typename const_array_view<NDims>::type return_type; return super_type::generate_array_view(boost::type<return_type>(), indices, shape(), strides(), index_bases(), origin()); } const_iterator begin() const { return const_iterator(const_iter_base(*index_bases(),origin(), shape(),strides(),index_bases())); } const_iterator end() const { return const_iterator(const_iter_base(*index_bases()+*shape(),origin(), shape(),strides(),index_bases())); } const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); } const_reverse_iterator rend() const { return const_reverse_iterator(begin()); } template <typename OPtr> bool operator==(const const_multi_array_view<T,NumDims,OPtr>& rhs) const { if(std::equal(extent_list_.begin(), extent_list_.end(), rhs.extent_list_.begin())) return std::equal(begin(),end(),rhs.begin()); else return false; } template <typename OPtr> bool operator<(const const_multi_array_view<T,NumDims,OPtr>& rhs) const { return std::lexicographical_compare(begin(),end(),rhs.begin(),rhs.end()); } template <typename OPtr> bool operator!=(const const_multi_array_view<T,NumDims,OPtr>& rhs) const { return !(*this == rhs); } template <typename OPtr> bool operator>(const const_multi_array_view<T,NumDims,OPtr>& rhs) const { return rhs < *this; } template <typename OPtr> bool operator<=(const const_multi_array_view<T,NumDims,OPtr>& rhs) const { return !(*this > rhs); } template <typename OPtr> bool operator>=(const const_multi_array_view<T,NumDims,OPtr>& rhs) const { return !(*this < rhs); } #ifndef BOOST_NO_MEMBER_TEMPLATE_FRIENDS protected: template <typename,std::size_t> friend class multi_array_impl_base; template <typename,std::size_t,typename> friend class const_multi_array_view; #else public: // should be protected #endif // This constructor is used by multi_array_impl_base::generate_array_view // to create strides template <typename ExtentList, typename Index> explicit const_multi_array_view(TPtr base, const ExtentList& extents, const boost::array<Index,NumDims>& strides): base_(base), origin_offset_(0) { index_base_list_.assign(0); // Get the extents and strides boost::copy_n(extents.begin(),NumDims,extent_list_.begin()); boost::copy_n(strides.begin(),NumDims,stride_list_.begin()); // Calculate the array size num_elements_ = std::accumulate(extent_list_.begin(),extent_list_.end(), size_type(1),std::multiplies<size_type>()); assert(num_elements_ != 0); } typedef boost::array<size_type,NumDims> size_list; typedef boost::array<index,NumDims> index_list; TPtr base_; index origin_offset_; size_type num_elements_; size_list extent_list_; index_list stride_list_; index_list index_base_list_; private: // const_multi_array_view cannot be assigned to (no deep copies!) const_multi_array_view& operator=(const const_multi_array_view& other); }; template <typename T, std::size_t NumDims> class multi_array_view : public const_multi_array_view<T,NumDims,T*> { typedef const_multi_array_view<T,NumDims,T*> super_type; public: typedef typename super_type::value_type value_type; typedef typename super_type::reference reference; typedef typename super_type::iterator iterator; typedef typename super_type::iter_base iter_base; typedef typename super_type::reverse_iterator reverse_iterator; typedef typename super_type::const_reference const_reference; typedef typename super_type::const_iterator const_iterator; typedef typename super_type::const_iter_base const_iter_base; typedef typename super_type::const_reverse_iterator const_reverse_iterator; typedef typename super_type::element element; typedef typename super_type::size_type size_type; typedef typename super_type::difference_type difference_type; typedef typename super_type::index index; typedef typename super_type::extent_range extent_range; // template typedefs template <std::size_t NDims> struct const_array_view { typedef boost::detail::multi_array::const_multi_array_view<T,NDims> type; }; template <std::size_t NDims> struct array_view { typedef boost::detail::multi_array::multi_array_view<T,NDims> type; }; // Assignment from other ConstMultiArray types. template <typename ConstMultiArray> multi_array_view& operator=(const ConstMultiArray& other) { function_requires< boost::detail::multi_array:: ConstMultiArrayConcept<ConstMultiArray,NumDims> >(); // make sure the dimensions agree assert(other.num_dimensions() == this->num_dimensions()); assert(std::equal(other.shape(),other.shape()+this->num_dimensions(), this->shape())); // iterator-based copy std::copy(other.begin(),other.end(),begin()); return *this; } multi_array_view& operator=(const multi_array_view& other) { if (&other != this) { // make sure the dimensions agree assert(other.num_dimensions() == this->num_dimensions()); assert(std::equal(other.shape(),other.shape()+this->num_dimensions(), this->shape())); // iterator-based copy std::copy(other.begin(),other.end(),begin()); } return *this; } element* origin() { return this->base_+this->origin_offset_; } template <class IndexList> element& operator()(const IndexList& indices) { return super_type::access_element(boost::type<element&>(), origin(), indices,this->strides()); } reference operator[](index idx) { return super_type::access(boost::type<reference>(), idx,origin(), this->shape(),this->strides(), this->index_bases()); } // see generate_array_view in base.hpp #if !defined(BOOST_MSVC) || BOOST_MSVC > 1300 template <int NDims> #else template <int NumDims, int NDims> // else ICE #endif // BOOST_MSVC typename array_view<NDims>::type operator[](const boost::detail::multi_array:: index_gen<NumDims,NDims>& indices) { typedef typename array_view<NDims>::type return_type; return super_type::generate_array_view(boost::type<return_type>(), indices, this->shape(), this->strides(), this->index_bases(), origin()); } iterator begin() { return iterator(iter_base(*this->index_bases(),origin(), this->shape(),this->strides(), this->index_bases())); } iterator end() { return iterator(iter_base(*this->index_bases()+*this->shape(),origin(), this->shape(),this->strides(), this->index_bases())); } reverse_iterator rbegin() { return reverse_iterator(end()); } reverse_iterator rend() { return reverse_iterator(begin()); } // Using declarations don't seem to work for g++ // These are the proxies to work around this. const element* origin() const { return super_type::origin(); } template <class IndexList> const element& operator()(const IndexList& indices) const { return super_type::operator()(indices); } const_reference operator[](index idx) const { return super_type::operator[](idx); } // see generate_array_view in base.hpp #if !defined(BOOST_MSVC) || BOOST_MSVC > 1300 template <int NDims> #else template <int NumDims, int NDims> // else ICE #endif // BOOST_MSVC typename const_array_view<NDims>::type operator[](const boost::detail::multi_array:: index_gen<NumDims,NDims>& indices) const { return super_type::operator[](indices); } const_iterator begin() const { return super_type::begin(); } const_iterator end() const { return super_type::end(); } const_reverse_iterator rbegin() const { return super_type::rbegin(); } const_reverse_iterator rend() const { return super_type::rend(); } #ifndef BOOST_NO_MEMBER_TEMPLATE_FRIENDS private: template <typename,std::size_t> friend class multi_array_impl_base; #else public: // should be private #endif // constructor used by multi_array_impl_base::generate_array_view to // generate array views template <typename ExtentList, typename Index> explicit multi_array_view(T* base, const ExtentList& extents, const boost::array<Index,NumDims>& strides) : super_type(base,extents,strides) { } }; } // namespace multi_array } // namespace detail // // traits classes to get array_view types // template <typename Array, int N> class array_view_gen { typedef typename Array::element element; public: typedef boost::detail::multi_array::multi_array_view<element,N> type; }; template <typename Array, int N> class const_array_view_gen { typedef typename Array::element element; public: typedef boost::detail::multi_array::const_multi_array_view<element,N> type; }; } // namespace boost #endif // BOOST_MULTI_ARRAY_VIEW_RG071301_HPP
31.415755
82
0.667479