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
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
9e99f564944f9fc214e4f3acc87aa4a3cfa2b1ff
802
cpp
C++
light.cpp
HanlinHu/Ray_tracing_in_C
2848d7ffb25c357a02998441aa097ca8fbbeb12d
[ "MIT" ]
null
null
null
light.cpp
HanlinHu/Ray_tracing_in_C
2848d7ffb25c357a02998441aa097ca8fbbeb12d
[ "MIT" ]
null
null
null
light.cpp
HanlinHu/Ray_tracing_in_C
2848d7ffb25c357a02998441aa097ca8fbbeb12d
[ "MIT" ]
null
null
null
#include <stdlib.h> #include <stdio.h> #include "entities.h" #include "light.h" void append_light(const light *X, light_node *list) { light_node tmp, newNode; /* allocate the lnode */ newNode = (light_node)malloc(sizeof(struct lnode)); COPY_POINT3(newNode->element.position, X->position); COPY_COLOR(newNode->element.light_color, X->light_color); newNode->element.intensity = X->intensity; /* insert it */ newNode->next = NULL; if (*list == NULL) { /* nothing in it yet */ *list = newNode; } else { /* move to the end */ for (tmp = *list; tmp->next != NULL; tmp = tmp->next) ; tmp->next = newNode; } } void delete_light_list(light_node *list) { light_node pos, tmp; pos = *list; while (pos != NULL) { tmp = pos->next; free(pos); pos = tmp; } *list = NULL; }
17.434783
58
0.642145
HanlinHu
9e9a33555789c8254d45fb3424b9f67de3d2e5dc
6,040
cc
C++
src/common/serializable.cc
MrKOSMOS/ANESE
8ae814d615479b1496c98033a1f5bc4da5921c6f
[ "MIT" ]
349
2017-11-15T22:51:00.000Z
2022-03-21T13:43:57.000Z
src/common/serializable.cc
MrKOSMOS/ANESE
8ae814d615479b1496c98033a1f5bc4da5921c6f
[ "MIT" ]
12
2018-08-28T21:38:29.000Z
2021-12-11T16:24:36.000Z
src/common/serializable.cc
MrKOSMOS/ANESE
8ae814d615479b1496c98033a1f5bc4da5921c6f
[ "MIT" ]
28
2018-06-10T07:31:13.000Z
2022-03-21T10:54:26.000Z
#include "serializable.h" // #define fprintf(...) // disable spam /*---------- Serializable Chunk Implementation ----------*/ Serializable::Chunk::~Chunk() { delete this->data; delete this->next; } Serializable::Chunk::Chunk() { this->len = 0; this->data = nullptr; this->next = nullptr; } Serializable::Chunk::Chunk(const void* data, uint len) { this->len = len; if (this->len == 0) { // this is a nullchunk this->data = nullptr; } else { this->data = new u8 [len]; memcpy(this->data, data, len); } this->next = nullptr; } const Serializable::Chunk* Serializable::Chunk::debugprint() const { fprintf(stderr, "| %4X | ", this->len); if (this->len) fprintf(stderr, "0x%08X\n", *((uint*)this->data)); else fprintf(stderr, "(null)\n"); if (this->next) this->next->debugprint(); return this; // for chaining } void Serializable::Chunk::collate(const u8*& data, uint& len, const Chunk* co) { // calculate total length of chunk-list uint total_len = 0; { const Chunk* c = co; while (c) { total_len += (sizeof Chunk::len) + c->len; c = c->next; } } if (total_len == 0) { data = nullptr; len = 0; return; } // create a new output buffer u8* output = new u8 [total_len]; // fill the output buffer with all the chunks const Chunk* c = co; u8* p = output; while(c) { memcpy(p, &c->len, sizeof Chunk::len); p += sizeof Chunk::len; memcpy(p, c->data, c->len); p += c->len; c = c->next; } data = output; len = total_len; } const Serializable::Chunk* Serializable::Chunk::parse(const u8* data, uint len) { Chunk *head, *tail, *next; head = tail = next = nullptr; const u8* p = data; while (p < data + len) { // Construct a chunk by reading length of next chunk from datastream const u8* chunk_data = p + (sizeof Chunk::len); uint chunk_data_len = *((uint*)p); next = new Chunk(chunk_data, chunk_data_len); p += (sizeof Chunk::len) + chunk_data_len; // Append the new chunk to the list if (!head) { head = tail = next; } else { tail->next = next; tail = next; } } return head; } /*-------------------------- De/Serialize Methods --------------------------*/ static char indent_buf [256] = {0}; static uint indent_i = 0; void indent_add() { indent_buf[indent_i++] = ' '; } void indent_del() { indent_buf[--indent_i] = '\0'; } Serializable::Chunk* Serializable::serialize() const { indent_add(); const Serializable::_field_data* field_data = nullptr; uint field_data_len = 0; this->_get_serializable_state(field_data, field_data_len); Chunk *head, *tail, *next; head = tail = next = nullptr; for (uint i = 0; i < field_data_len; i++) { const _field_data& field = field_data[i]; fprintf(stderr, "[Serialization][%d] %s%-50s: len %X | ", field.type, indent_buf, field.label, (field.type >= 3) ? 0 : (field.type == 2 ? *field.len_variable : field.len_fixed) ); switch (field.type) { case _field_type::SERIAL_INVALID: assert(false); break; case _field_type::SERIAL_POD: fprintf(stderr, "0x%08X\n", *((uint*)field.thing)); next = new Chunk(field.thing, field.len_fixed); break; case _field_type::SERIAL_ARRAY_VARIABLE: fprintf(stderr, "0x%08X\n", **((uint**)field.thing)); next = new Chunk(*((void**)field.thing), *field.len_variable); break; case _field_type::SERIAL_IZABLE: fprintf(stderr, "serializable: \n"); next = ((Serializable*)field.thing)->serialize(); assert(next != nullptr); break; case _field_type::SERIAL_IZABLE_PTR: { fprintf(stderr, "serializable_ptr: "); if (!field.thing) { fprintf(stderr, "null\n"); next = new Chunk(); // nullchunk. } else { fprintf(stderr, "recursive\n"); next = ((Serializable*)field.thing)->serialize(); assert(next != nullptr); } } break; } if (!head) { head = tail = next; } else { tail->next = next; tail = next; } if (field.type == _field_type::SERIAL_IZABLE || field.type == _field_type::SERIAL_IZABLE_PTR) { while (tail->next) tail = tail->next; } } indent_del(); delete field_data; return head; } const Serializable::Chunk* Serializable::deserialize(const Chunk* c) { if (!c) return nullptr; indent_add(); const Serializable::_field_data* field_data = nullptr; uint field_data_len = 0; this->_get_serializable_state(field_data, field_data_len); for (uint i = 0; i < field_data_len; i++) { const _field_data& field = field_data[i]; fprintf(stderr, "[DeSerialization][%d] %s%-50s: len %X | ", field.type, indent_buf, field.label, (field.type >= 3) ? 0 : (field.type == 2 ? *field.len_variable : field.len_fixed) ); switch (field.type) { case _field_type::SERIAL_INVALID: assert(false); break; case _field_type::SERIAL_POD: fprintf(stderr, "0x%08X\n", *((uint*)c->data)); memcpy(field.thing, c->data, c->len); c = c->next; break; case _field_type::SERIAL_ARRAY_VARIABLE: fprintf(stderr, "0x%08X\n", *((uint*)c->data)); memcpy(*((void**)field.thing), c->data, c->len); c = c->next; break; case _field_type::SERIAL_IZABLE: fprintf(stderr, "serializable: \n"); // recursively deserialize the data c = ((Serializable*)field.thing)->deserialize(c); break; case _field_type::SERIAL_IZABLE_PTR: { fprintf(stderr, "serializable_ptr: "); if (c->len == 0 && field.thing == nullptr) { fprintf(stderr, "null\n"); // nullchunk. Ignore this and carry on. c = c->next; } else { fprintf(stderr, "recursive\n"); // recursively deserialize the data c = ((Serializable*)field.thing)->deserialize(c); } } break; } } indent_del(); delete field_data; return c; }
26.844444
81
0.588907
MrKOSMOS
9e9bb88c61534ee26bb7229d50f1c31845f82238
3,815
cpp
C++
src/FalconEngine/Graphics/Renderer/Primitive.cpp
LiuYiZhou95/FalconEngine
b798f20e9dbd01334a4e4cdbbd9a5bec74966418
[ "MIT" ]
null
null
null
src/FalconEngine/Graphics/Renderer/Primitive.cpp
LiuYiZhou95/FalconEngine
b798f20e9dbd01334a4e4cdbbd9a5bec74966418
[ "MIT" ]
null
null
null
src/FalconEngine/Graphics/Renderer/Primitive.cpp
LiuYiZhou95/FalconEngine
b798f20e9dbd01334a4e4cdbbd9a5bec74966418
[ "MIT" ]
1
2021-08-25T07:39:02.000Z
2021-08-25T07:39:02.000Z
#include <FalconEngine/Graphics/Renderer/Primitive.h> #include <FalconEngine/Graphics/Renderer/Resource/IndexBuffer.h> #include <FalconEngine/Graphics/Renderer/Resource/VertexBuffer.h> #include <FalconEngine/Graphics/Renderer/Resource/VertexGroup.h> namespace FalconEngine { /************************************************************************/ /* Constructors and Destructor */ /************************************************************************/ Primitive::Primitive(PrimitiveType type) : Primitive(type, nullptr, nullptr, nullptr) { } Primitive::Primitive(PrimitiveType type, const std::shared_ptr<VertexFormat>& vertexFormat, const std::shared_ptr<VertexGroup>& vertexGroup, const std::shared_ptr<IndexBuffer>& indexBuffer) : mType(type), mAABB(), mVertexFormat(vertexFormat), mVertexGroup(vertexGroup), mVertexOffset(0), mIndexBuffer(indexBuffer), mIndexOffset(0) { // NOTE(Wuxiang): All vertex format, vertex group and index buffer is allowed to be null // here. But they should be initialized in the derived class's constructor. } Primitive::~Primitive() { } /************************************************************************/ /* Public Members */ /************************************************************************/ PrimitiveType Primitive::GetPrimitiveType() const { return mType; } /************************************************************************/ /* Bounding Box Management */ /************************************************************************/ const AABB * Primitive::GetAABB() const { return mAABB.get(); } void Primitive::SetAABB(const AABB& aabb) { mAABB = std::make_shared<AABB>(aabb); } /************************************************************************/ /* Vertex Buffer Management */ /************************************************************************/ const VertexFormat * Primitive::GetVertexFormat() const { return mVertexFormat.get(); } std::shared_ptr<const VertexFormat> Primitive::GetVertexFormat() { return mVertexFormat; } const VertexGroup * Primitive::GetVertexGroup() const { return mVertexGroup.get(); } std::shared_ptr<const VertexGroup> Primitive::GetVertexGroup() { return mVertexGroup; } int Primitive::GetVertexNum() const { return mVertexGroup->GetVertexNum(); } int Primitive::GetVertexOffset() const { return mVertexOffset; } void Primitive::SetVertexOffset(int vertexOffset) { mVertexOffset = vertexOffset; } /************************************************************************/ /* Index Buffer Management */ /************************************************************************/ const IndexBuffer * Primitive::GetIndexBuffer() const { return mIndexBuffer.get(); } std::shared_ptr<IndexBuffer> Primitive::GetIndexBuffer() { return mIndexBuffer; } int Primitive::GetIndexOffset() const { return mIndexOffset; } void Primitive::SetIndexOffset(int indexOffset) { mIndexOffset = indexOffset; } /************************************************************************/ /* Deep and Shallow Copy */ /************************************************************************/ void Primitive::CopyTo(Primitive *lhs) { lhs->mType = mType; lhs->mAABB = mAABB; lhs->mVertexFormat = mVertexFormat; lhs->mVertexGroup = mVertexGroup; lhs->mVertexOffset = mVertexOffset; lhs->mIndexBuffer = mIndexBuffer; lhs->mIndexOffset = mIndexOffset; } }
25.264901
92
0.494364
LiuYiZhou95
9e9edb843b800c557c89644a57caae00bdcd40e2
59
cpp
C++
DeviceCode/pal/Buttons/GPIO_Buttons_fastcompile.cpp
PervasiveDigital/netmf-interpreter
03d84fe76e0b666ebec62d17d69c55c45940bc40
[ "Apache-2.0" ]
529
2015-03-10T00:17:45.000Z
2022-03-17T02:21:19.000Z
DeviceCode/pal/Buttons/GPIO_Buttons_fastcompile.cpp
PervasiveDigital/netmf-interpreter
03d84fe76e0b666ebec62d17d69c55c45940bc40
[ "Apache-2.0" ]
495
2015-03-10T22:02:46.000Z
2019-05-16T13:05:00.000Z
DeviceCode/pal/Buttons/GPIO_Buttons_fastcompile.cpp
PervasiveDigital/netmf-interpreter
03d84fe76e0b666ebec62d17d69c55c45940bc40
[ "Apache-2.0" ]
332
2015-03-10T08:04:36.000Z
2022-03-29T04:18:36.000Z
#include "GPIO_Buttons.cpp" #include "GPIO_config.cpp"
14.75
28
0.728814
PervasiveDigital
9ea153f76375eb317aa355648929cc82582d02dd
4,685
cpp
C++
runtime/src/sort.cpp
lezsakdomi/jscomp
83828441cb38ec96603a6a60be06977d4852940a
[ "Apache-2.0" ]
220
2015-07-22T03:18:03.000Z
2022-03-19T07:26:26.000Z
runtime/src/sort.cpp
lezsakdomi/jscomp
83828441cb38ec96603a6a60be06977d4852940a
[ "Apache-2.0" ]
31
2015-06-17T14:20:21.000Z
2018-10-14T12:58:41.000Z
runtime/src/sort.cpp
lezsakdomi/jscomp
83828441cb38ec96603a6a60be06977d4852940a
[ "Apache-2.0" ]
13
2015-09-16T16:07:45.000Z
2021-02-06T19:44:04.000Z
// Copyright (c) 2015 Tzvetan Mikov. // Licensed under the Apache License v2.0. See LICENSE in the project // root for complete license information. #include "jsc/sort.h" namespace js { void selectionSort (StackFrame * caller, IExchangeSortCB * cb, uint32_t begin, uint32_t end) { if (end == begin) return; for ( uint32_t i = begin, e = end - 1; i != e; ++i ) { uint32_t best = i; for ( uint32_t j = i + 1; j != end; ++j ) if (cb->less(caller, j, best)) best = j; if (best != i) cb->swap(caller, best, i); } } void insertionSort (StackFrame * caller, IExchangeSortCB * cb, uint32_t begin, uint32_t end) { if (begin == end) return; for ( uint32_t i = begin + 1; i != end; ++i ) { for ( unsigned j = i; j != begin && cb->less(caller, j, j-1); --j ) cb->swap(caller, j, j-1); } } // Must be at lest 3, for "median of three" to work #define INSERTION_THRESHOLD 6 static void doQuickSort (StackFrame * caller, IExchangeSortCB * cb, int limit, uint32_t l, uint32_t r) { tail_recursion: if (limit <= 0) { // Bail to heap sort heapSort(caller, cb, l, r+1); return; } // Median-of-three // Place the middle element at [l+1] cb->swap(caller, l+1, l + ((r - l)>>1)); // Sort, [l], [l+1], [r] if (cb->less(caller, r, l+1)) cb->swap(caller, r, l+1); if (cb->less(caller, l+1, l)) cb->swap(caller, l+1, l); if (cb->less(caller, r, l+1)) cb->swap(caller, r, l+1); // Now [l] <= [l+1] <= [r] // [l+1] is our pivot and [r] is a sentinel uint32_t pivot = l+1; uint32_t i = pivot, j = r + 1; // The pivot is at [l+1] for(;;) { while (cb->less(caller, ++i, pivot)) { } while (cb->less(caller, pivot, --j)) { } if (i >= j) break; cb->swap(caller, i, j); } // put the pivot in its final position if (j != pivot) cb->swap(caller, pivot, j); // To limit the stack size, recurse for the smaller partition and do tail-recursion for the bigger one uint32_t sl = j - l; uint32_t sr = r - j; if (sl <= sr) { if (sl > INSERTION_THRESHOLD) doQuickSort(caller, cb, limit-1, l, j-1); else insertionSort(caller, cb, l, j); if (sr > INSERTION_THRESHOLD) { l = j+1; --limit; goto tail_recursion; } else { insertionSort(caller, cb, j+1, r+1); } } else { if (sr > INSERTION_THRESHOLD) doQuickSort(caller, cb, limit-1, j+1, r); else insertionSort(caller, cb, j+1, r+1); if (sl > INSERTION_THRESHOLD) { r = j-1; --limit; goto tail_recursion; } else { insertionSort(caller, cb, l, j); } } } static inline int log2of (uint32_t v) { if (v <= 1) return 1; --v; int res = 0; if (v & 0xFFFF0000) { res += 16; v >>= 16; }; if (v & 0xFF00) { res += 8; v >>= 8; }; if (v & 0xF0) { res += 4; v >>= 4; }; if (v & 0x0C) { res += 2; v >>= 2; }; if (v & 0x02) { res += 1; v >>= 1; }; return res + 1; } void quickSort (StackFrame * caller, IExchangeSortCB * cb, uint32_t begin, uint32_t end) { if (end - begin > INSERTION_THRESHOLD) doQuickSort(caller, cb, log2of(end - begin)*2, begin, end-1); else insertionSort(caller, cb, begin, end); } /** * @param base the beginning of the logical array */ static void heapFixDown (StackFrame * caller, IExchangeSortCB * cb, uint32_t base, uint32_t begin, uint32_t end) { if (JS_UNLIKELY(end - begin <= 1)) return; uint32_t lastGood = base + (end - base - 2)/2; uint32_t i = begin; while (i <= lastGood) { uint32_t j = (i - base)*2 + 1 + base; // Find the greater of the two children if (j+1 < end && cb->less(caller, j, j+1)) ++j; // If the child is greater than us, exchange places if (!cb->less(caller, i, j)) break; cb->swap(caller, i, j); i = j; } } void heapSort (StackFrame * caller, IExchangeSortCB * cb, uint32_t begin, uint32_t end) { if (JS_UNLIKELY(end - begin <= 1)) return; // "heapify" uint32_t start = (end - begin - 2)/2 + begin; do heapFixDown(caller, cb, begin, start, end); while (start-- != begin); while (end - begin > 1) { --end; cb->swap(caller, begin, end); heapFixDown(caller, cb, begin, begin, end); } } }; // namespace js
26.468927
112
0.517609
lezsakdomi
9ea3b2da88211e4df5fb7fd1a2ea95f042944f9b
6,004
cpp
C++
tests/pool.cpp
corentinberge/dynamic-graph
89b3ab9cbac71daaa2eddb75947299270868a31b
[ "BSD-2-Clause" ]
1
2019-07-01T07:49:35.000Z
2019-07-01T07:49:35.000Z
tests/pool.cpp
corentinberge/dynamic-graph
89b3ab9cbac71daaa2eddb75947299270868a31b
[ "BSD-2-Clause" ]
null
null
null
tests/pool.cpp
corentinberge/dynamic-graph
89b3ab9cbac71daaa2eddb75947299270868a31b
[ "BSD-2-Clause" ]
null
null
null
// Copyright 2010 Thomas Moulard. // #include <sstream> #include <iostream> #include <dynamic-graph/entity.h> #include <dynamic-graph/factory.h> #include <dynamic-graph/exception-factory.h> #include <dynamic-graph/pool.h> #include <dynamic-graph/signal-ptr.h> #include <dynamic-graph/signal-time-dependent.h> #define BOOST_TEST_MODULE pool #include <boost/test/unit_test.hpp> #include <boost/test/output_test_stream.hpp> using boost::test_tools::output_test_stream; struct MyEntity : public dynamicgraph::Entity { static const std::string CLASS_NAME; dynamicgraph::SignalPtr<double, int> m_sigdSIN; dynamicgraph::SignalTimeDependent<double, int> m_sigdTimeDepSOUT; MyEntity (const std::string& name) : Entity (name) ,m_sigdSIN(NULL,"MyEntity("+name+")::input(double)::in_double") ,m_sigdTimeDepSOUT(boost::bind(&MyEntity::update,this,_1,_2), m_sigdSIN, "MyEntity("+name+")::input(double)::out_double") { signalRegistration(m_sigdSIN << m_sigdTimeDepSOUT); } virtual void display (std::ostream& os) const { os << "Hello! My name is " << getName () << " !" << std::endl; } virtual const std::string& getClassName () const { return CLASS_NAME; } double & update(double &res, const int &inTime) { const double &aDouble = m_sigdSIN(inTime); res = aDouble; return res; } }; DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN (MyEntity, "MyEntity"); namespace dg = dynamicgraph; BOOST_AUTO_TEST_CASE (pool_display) { /// Create Entity dg::Entity* entity = dg::FactoryStorage::getInstance()-> newEntity("MyEntity", "MyEntityInst"); /// Test exception catching when registering Entity bool res=false; try { dg::Entity* entity2 = dg::FactoryStorage::getInstance()-> newEntity("MyEntity", "MyEntityInst"); bool res2 = (entity2==entity); BOOST_CHECK(res2); } catch (const dg::ExceptionFactory &aef) { res =(aef.getCode()==dg::ExceptionFactory::OBJECT_CONFLICT); } BOOST_CHECK(res); /// Test exception catching when deregistering Entity res=false; try { dg::FactoryStorage::getInstance()-> deregisterEntity("MyEntityInstFailure"); } catch (const dg::ExceptionFactory &aef) { res =(aef.getCode()==dg::ExceptionFactory::OBJECT_CONFLICT); } BOOST_CHECK(res); /// Search for an entity inside the map output_test_stream output; dg::Entity& e = dg::PoolStorage::getInstance()->getEntity ("MyEntityInst"); e.display(output); BOOST_CHECK (output.is_equal ("Hello! My name is MyEntityInst !\n")); /// Search for an entity inside the map res=false; try { dg::PoolStorage::getInstance()->getEntity ("MyEntityInstFailure"); } catch (const dg::ExceptionFactory &aef) { res =(aef.getCode()==dg::ExceptionFactory::UNREFERED_OBJECT); } BOOST_CHECK (res); /// Testing entityMap const dg::PoolStorage::Entities& anEntityMap = dg::PoolStorage::getInstance()->getEntityMap(); bool testExistence = anEntityMap.find("MyEntityInst")==anEntityMap.end(); BOOST_CHECK(!testExistence); /// Testing the existence of an entity testExistence = dg::PoolStorage::getInstance()->existEntity ("MyEntityInst",entity); BOOST_CHECK(testExistence); /// Testing the completion list of pool storage dg::PoolStorage::getInstance()->writeCompletionList (output); BOOST_CHECK (output.is_equal ("MyEntityInst.in_double\nMyEntityInst.out_double\nprint\nsignals\nsignalDep\n")); /// Checking the graph generated by the pool dg::PoolStorage::getInstance()->writeGraph("output.dot"); std::fstream the_debug_file; the_debug_file.open("output.dot"); std::ostringstream oss_output_wgph; oss_output_wgph << the_debug_file.rdbuf(); the_debug_file.close(); /// Use a predefined output std::string str_to_test="/* This graph has been automatically generated.\n" " 2019 Month: 2 Day: 28 Time: 11:28 */\n" "digraph \"output\" { graph [ label=\"output\" bgcolor = white rankdir=LR ]\n" "\t node [ fontcolor = black, color = black, fillcolor = gold1, style=filled, shape=box ] ; \n" "\tsubgraph cluster_Entities { \n" "\t} \n" "\"MyEntityInst\" [ label = \"MyEntityInst\" ,\n" " fontcolor = black, color = black, fillcolor=cyan, style=filled, shape=box ]\n" "}\n"; /// Check the two substring (remove the date) - std::string s_output_wgph = oss_output_wgph.str(); std::string s_crmk="*/"; std::size_t find_s_output_wgph = s_output_wgph.find(s_crmk); std::string sub_s_output_wgph =s_output_wgph.substr(find_s_output_wgph, s_output_wgph.length()); std::size_t find_str_to_test = str_to_test.find(s_crmk); std::string sub_str_to_test =str_to_test.substr(find_str_to_test, str_to_test.length()); bool two_sub_string_identical; two_sub_string_identical=sub_str_to_test==sub_s_output_wgph; BOOST_CHECK(two_sub_string_identical); /// Test name of a valid signal. std::istringstream an_iss("MyEntityInst.in_double"); dg::SignalBase<int> &aSignal= dg::PoolStorage::getInstance()->getSignal(an_iss); std::string aSignalName=aSignal.getName(); testExistence = aSignalName=="MyEntity(MyEntityInst)::input(double)::in_double"; BOOST_CHECK(testExistence); /// Test name of an unvalid signal. an_iss.str("MyEntityInst.in2double"); try { dg::PoolStorage::getInstance()->getSignal(an_iss); } catch(const dg::ExceptionFactory &aef) { res =(aef.getCode()==dg::ExceptionFactory::UNREFERED_SIGNAL); } BOOST_CHECK(res); /// Deregister the entity. dg::PoolStorage::getInstance()->deregisterEntity (entity->getName()); /// Testing the existance of an entity testExistence = dg::PoolStorage::getInstance()->existEntity ("MyEntityInst",entity); BOOST_CHECK(!testExistence); /// Create Entity std::string name_entity("MyEntityInst2"); dg::PoolStorage::getInstance()-> clearPlugin(name_entity); dg::PoolStorage::destroy(); }
29.287805
113
0.69437
corentinberge
9eac9905161f18dc3a4e190a59c24a24634730c3
1,902
cpp
C++
Real-Time Corruptor/BizHawk_RTC/libgambatte/src/interrupter.cpp
redscientistlabs/Bizhawk50X-Vanguard
96e0f5f87671a1230784c8faf935fe70baadfe48
[ "MIT" ]
45
2017-07-24T05:31:06.000Z
2019-03-29T12:23:57.000Z
Real-Time Corruptor/BizHawk_RTC/libgambatte/src/interrupter.cpp
redscientistlabs/Bizhawk50X-Vanguard
96e0f5f87671a1230784c8faf935fe70baadfe48
[ "MIT" ]
7
2019-01-14T14:46:46.000Z
2019-01-25T20:57:05.000Z
Real-Time Corruptor/BizHawk_RTC/libgambatte/src/interrupter.cpp
redscientistlabs/Bizhawk50X-Vanguard
96e0f5f87671a1230784c8faf935fe70baadfe48
[ "MIT" ]
10
2017-07-24T02:11:43.000Z
2018-12-27T20:49:37.000Z
/*************************************************************************** * Copyright (C) 2007 by Sindre Aamås * * aamas@stud.ntnu.no * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 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 General Public License version 2 for more details. * * * * You should have received a copy of the GNU General Public License * * version 2 along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "interrupter.h" #include "memory.h" namespace gambatte { Interrupter::Interrupter(unsigned short &SP_in, unsigned short &PC_in) : SP(SP_in), PC(PC_in) {} unsigned long Interrupter::interrupt(const unsigned address, unsigned long cycleCounter, Memory &memory) { cycleCounter += 8; SP = (SP - 1) & 0xFFFF; memory.write(SP, PC >> 8, cycleCounter); cycleCounter += 4; SP = (SP - 1) & 0xFFFF; memory.write(SP, PC & 0xFF, cycleCounter); PC = address; cycleCounter += 8; return cycleCounter; } }
44.232558
106
0.476341
redscientistlabs
9eb2c54062d4af7fb20fc56ec332c1e8523b8d3c
955
cpp
C++
src/view/codeeditor/keybehavior/abstractkeybehavior.cpp
Tatsu015/markdownmindmap
93e305c04d3adb59073612a5843579d5ce11c79e
[ "MIT" ]
null
null
null
src/view/codeeditor/keybehavior/abstractkeybehavior.cpp
Tatsu015/markdownmindmap
93e305c04d3adb59073612a5843579d5ce11c79e
[ "MIT" ]
1
2022-01-18T16:10:11.000Z
2022-01-18T16:11:33.000Z
src/view/codeeditor/keybehavior/abstractkeybehavior.cpp
Tatsu015/markdownmindmap
93e305c04d3adb59073612a5843579d5ce11c79e
[ "MIT" ]
null
null
null
#include "abstractkeybehavior.h" #include <QKeyEvent> AbstractKeyBehavior::AbstractKeyBehavior() { } AbstractKeyBehavior::~AbstractKeyBehavior() { } void AbstractKeyBehavior::keyPressEvent(CodeEditor* codeEditor, QKeyEvent* event) { if (event->modifiers() == Qt::NoModifier) { noModifierKeyPressEvent(codeEditor); } else if (event->modifiers() & Qt::ControlModifier) { controlModifierKeyPressEvent(codeEditor); } else if (event->modifiers() & Qt::ShiftModifier) { shiftModifierKeyPressEvent(codeEditor); } else if (event->modifiers() & Qt::AltModifier) { altModifierKeyPressEvent(codeEditor); } else { } } void AbstractKeyBehavior::controlModifierKeyPressEvent(CodeEditor* codeEditor) { Q_UNUSED(codeEditor); } void AbstractKeyBehavior::shiftModifierKeyPressEvent(CodeEditor* codeEditor) { Q_UNUSED(codeEditor); } void AbstractKeyBehavior::altModifierKeyPressEvent(CodeEditor* codeEditor) { Q_UNUSED(codeEditor); }
28.088235
83
0.762304
Tatsu015
9eb3253e79fd27c7d9e2cf616af6e5a7751dd9ae
3,778
cpp
C++
src/PixelpartPluginCurve.cpp
soeren-m/pixelpart-plugin-unity
622dab395e04bb5c44ab170f6d399b241cd0557e
[ "MIT" ]
1
2022-03-22T09:21:22.000Z
2022-03-22T09:21:22.000Z
src/PixelpartPluginCurve.cpp
soeren-m/pixelpart-plugin-unity
622dab395e04bb5c44ab170f6d399b241cd0557e
[ "MIT" ]
null
null
null
src/PixelpartPluginCurve.cpp
soeren-m/pixelpart-plugin-unity
622dab395e04bb5c44ab170f6d399b241cd0557e
[ "MIT" ]
null
null
null
#include "PixelpartPlugin.h" extern "C" { UNITY_INTERFACE_EXPORT float UNITY_INTERFACE_API PixelpartCurveGet(pixelpart::Curve<pixelpart::floatd>* curve, float position) { if(!curve) { return 0.0f; } return static_cast<float>(curve->get(position)); } UNITY_INTERFACE_EXPORT float UNITY_INTERFACE_API PixelpartCurveGetPoint(pixelpart::Curve<pixelpart::floatd>* curve, uint32_t index) { if(!curve || index < 0 || static_cast<std::size_t>(index) >= curve->getNumPoints()) { return 0.0f; } return static_cast<float>(curve->getPoints()[static_cast<std::size_t>(index)].value); } UNITY_INTERFACE_EXPORT void UNITY_INTERFACE_API PixelpartCurveSet(pixelpart::Curve<pixelpart::floatd>* curve, float value) { if(!curve) { return; } curve->setPoints({ pixelpart::Curve<pixelpart::floatd>::Point{ 0.5, value } }); } UNITY_INTERFACE_EXPORT void UNITY_INTERFACE_API PixelpartCurveAddPoint(pixelpart::Curve<pixelpart::floatd>* curve, float position, float value) { if(!curve) { return; } curve->addPoint(position, value); } UNITY_INTERFACE_EXPORT void UNITY_INTERFACE_API PixelpartCurveSetPoint(pixelpart::Curve<pixelpart::floatd>* curve, uint32_t index, float value) { if(!curve) { return; } curve->setPoint(static_cast<std::size_t>(index), value); } UNITY_INTERFACE_EXPORT void UNITY_INTERFACE_API PixelpartCurveMovePoint(pixelpart::Curve<pixelpart::floatd>* curve, uint32_t index, float delta) { if(!curve) { return; } curve->movePoint(static_cast<std::size_t>(index), delta); } UNITY_INTERFACE_EXPORT void UNITY_INTERFACE_API PixelpartCurveShiftPoint(pixelpart::Curve<pixelpart::floatd>* curve, uint32_t index, float delta) { if(!curve) { return; } curve->shiftPoint(static_cast<std::size_t>(index), delta); } UNITY_INTERFACE_EXPORT void UNITY_INTERFACE_API PixelpartCurveRemovePoint(pixelpart::Curve<pixelpart::floatd>* curve, uint32_t index) { if(!curve) { return; } curve->removePoint(static_cast<std::size_t>(index)); } UNITY_INTERFACE_EXPORT void UNITY_INTERFACE_API PixelpartCurveClear(pixelpart::Curve<pixelpart::floatd>* curve) { if(!curve) { return; } curve->clear(); } UNITY_INTERFACE_EXPORT uint32_t UNITY_INTERFACE_API PixelpartCurveGetNumPoints(pixelpart::Curve<pixelpart::floatd>* curve) { if(!curve) { return 0U; } return curve->getNumPoints(); } UNITY_INTERFACE_EXPORT void UNITY_INTERFACE_API PixelpartCurveMove(pixelpart::Curve<pixelpart::floatd>* curve, float delta) { if(!curve) { return; } curve->move(delta); } UNITY_INTERFACE_EXPORT void UNITY_INTERFACE_API PixelpartCurveShift(pixelpart::Curve<pixelpart::floatd>* curve, float delta) { if(!curve) { return; } curve->shift(delta); } UNITY_INTERFACE_EXPORT void UNITY_INTERFACE_API PixelpartCurveSetInterpolation(pixelpart::Curve<pixelpart::floatd>* curve, int32_t method) { if(!curve) { return; } curve->setInterpolation(static_cast<pixelpart::CurveInterpolation>(method)); } UNITY_INTERFACE_EXPORT int32_t UNITY_INTERFACE_API PixelpartCurveGetInterpolation(pixelpart::Curve<pixelpart::floatd>* curve) { if(!curve) { return 0; } return static_cast<int32_t>(curve->getInterpolation()); } UNITY_INTERFACE_EXPORT void UNITY_INTERFACE_API PixelpartCurveEnableAdaptiveCache(pixelpart::Curve<pixelpart::floatd>* curve) { if(!curve) { return; } curve->enableAdaptiveCache(); } UNITY_INTERFACE_EXPORT void UNITY_INTERFACE_API PixelpartCurveEnableFixedCache(pixelpart::Curve<pixelpart::floatd>* curve, uint32_t size) { if(!curve) { return; } curve->enableFixedCache(static_cast<std::size_t>(size)); } UNITY_INTERFACE_EXPORT uint32_t UNITY_INTERFACE_API PixelpartCurveGetCacheSize(pixelpart::Curve<pixelpart::floatd>* curve) { if(!curve) { return 0; } return static_cast<uint32_t>(curve->getCacheSize()); } }
27.179856
147
0.766278
soeren-m
9eb439ffcc10306fbb31659c82087836961da1aa
70
hpp
C++
other/Renegade Ops/dxgi/FakeProcessAffinityMask/game.hpp
gibbed/Gibbed.Avalanche
549c7a7fa902c5b4d180847ad6f11867d4281398
[ "Zlib" ]
2
2020-02-08T02:50:41.000Z
2020-12-14T05:36:58.000Z
other/Renegade Ops/dxgi/FakeProcessAffinityMask/game.hpp
MerkeX/Gibbed.Avalanche
549c7a7fa902c5b4d180847ad6f11867d4281398
[ "Zlib" ]
null
null
null
other/Renegade Ops/dxgi/FakeProcessAffinityMask/game.hpp
MerkeX/Gibbed.Avalanche
549c7a7fa902c5b4d180847ad6f11867d4281398
[ "Zlib" ]
3
2018-12-05T12:15:11.000Z
2021-06-16T01:17:28.000Z
#ifndef __GAME_HPP #define __GAME_HPP bool GameHook(); #endif
10
19
0.7
gibbed
9eb6ff3c29fcea8631076bb4a163d2f1699ec8d2
2,602
cpp
C++
CppP4rhSln/13/old/plain-ptr.cpp
blacop/CppPR
a76574ee83000d898d989aab96eac4ac746244fa
[ "MIT" ]
null
null
null
CppP4rhSln/13/old/plain-ptr.cpp
blacop/CppPR
a76574ee83000d898d989aab96eac4ac746244fa
[ "MIT" ]
null
null
null
CppP4rhSln/13/old/plain-ptr.cpp
blacop/CppPR
a76574ee83000d898d989aab96eac4ac746244fa
[ "MIT" ]
null
null
null
#include <iostream> using std::ostream; using std::cout; using std::endl; #include <string> // class that has a pointer member that behaves like a plain pointer class HasPtr { public: friend ostream& operator<<(ostream&, const HasPtr&); // copy of the values we're given HasPtr(int *p, int i): ptr(p), val(i) { } // const members to return the value of the indicated data member int *get_ptr() const { return ptr; } int get_int() const { return val; } // nonconst members to change the indicated data member void set_ptr(int *p) { ptr = p; } void set_int(int i) { val = i; } // return or change the value pointed to, so ok for const objects int get_ptr_val() const { return *ptr; } void set_ptr_val(int val) const { *ptr = val; } private: int *ptr; int val; }; void f3() { int i = 42; HasPtr p1(&i, 42); HasPtr p2 = p1; cout << p2.get_ptr_val() << endl; p1.set_ptr_val(0); cout << p2.get_ptr_val() << endl; } int main() { int obj = 0; HasPtr ptr1(&obj, 42); // int* member points to obj, val is 42 HasPtr ptr2(ptr1); // int* member points to obj, val is 42 cout << "(1) ptr1: " << ptr1 << endl << "ptr2: " << ptr2 << endl; ptr1.set_ptr_val(42); // sets object to which both ptr1 and ptr2 point ptr2.get_ptr_val(); // returns 42 cout << "(2) ptr1: " << ptr1 << endl << "ptr2: " << ptr2 << endl; ptr1.set_int(0); // changes val member only in ptr1 ptr2.get_int(); // returns 42 ptr1.get_int(); // returns 0 cout << "(3) ptr1: " << ptr1 << endl << "ptr2: " << ptr2 << endl; int *ip = new int(42); // dynamically allocated int initialized to 42 HasPtr ptr(ip, 10); // HasPtr points to same object as ip does delete ip; // object pointed to by ip is freed ptr.set_ptr_val(0); // disaster: The object to which HasPtr points was freed! cout << "(4) ptr: " << ptr << endl; f3(); return 0; } void f(int *p) { // new socpe // allocates new int to hold a copy of the object to which p points HasPtr local_copy(p, 0); // . . . } // local_copy goes out of scope void f2() { int obj= 42; HasPtr local1(&obj, 0); // allocates a new int to hold a copy of obj if (obj) { // new scope HasPtr local2(local1); // local1 and local2 hold same pointer // . . . } // local2 goes out of scope, object to which it points is freed local1.set_ptr_val(0); // disaster -- the object to which local1 points was freed! } ostream& operator<<(ostream &os, const HasPtr &hp) { cout << "*ptr: " << hp.get_ptr_val() << "\tval: " << hp.get_int() << endl; return os; }
27.389474
87
0.615296
blacop
9eb84bc7df8f51591d3ef018e2bb494cb23f71e0
5,105
cpp
C++
polygon3D.cpp
degarashi/boomstick
55dc5bfcfad6119d8401f578f91df7bbd44c192b
[ "MIT" ]
1
2015-06-14T15:54:27.000Z
2015-06-14T15:54:27.000Z
polygon3D.cpp
degarashi/boomstick
55dc5bfcfad6119d8401f578f91df7bbd44c192b
[ "MIT" ]
null
null
null
polygon3D.cpp
degarashi/boomstick
55dc5bfcfad6119d8401f578f91df7bbd44c192b
[ "MIT" ]
null
null
null
#include "convex.hpp" namespace boom { namespace geo3d { Polygon::Polygon() {} Polygon::Polygon(const Vec3* vsrc) { init(vsrc); } Polygon::Polygon(const Vec3& v0, const Vec3& v1, const Vec3& v2) { init(v0, v1, v2); } void Polygon::setUserData(uint32_t dat) { _ud = dat; } uint32_t Polygon::getUserData() const { return _ud; } void Polygon::init(const Vec3& v0, const Vec3& v1, const Vec3& v2) { _vtx[0] = v0; _vtx[1] = v1; _vtx[2] = v2; spn::Bit::Set<decltype(_rflg)>(_rflg, NORMALFLAG | PLANEFLAG | CENTERFLAG); } void Polygon::init(const Vec3* vsrc) { _vtx[0] = vsrc[0]; _vtx[1] = vsrc[1]; _vtx[2] = vsrc[2]; spn::Bit::Set<decltype(_rflg)>(_rflg, NORMALFLAG | PLANEFLAG | CENTERFLAG); } const Vec3& Polygon::getNormal() const { // NORMAL更新フラグチェック if(spn::Bit::ChClear<decltype(_rflg)>(_rflg, NORMALFLAG)) { // 法線更新 _vNormal = *spn::NormalFromPoints(_vtx[0], _vtx[1], _vtx[2]); } return _vNormal; } const Vec3& Polygon::getVtx(int n) const { return _vtx[n]; } Polygon Polygon::operator * (const AMat43& m) const { Polygon ret; // 3頂点を行列変換 for(int i=0 ; i<3 ; i++) ret._vtx[i] = _vtx[i].asVec4(1) * m; spn::Bit::Set<decltype(ret._rflg)>(ret._rflg, NORMALFLAG | PLANEFLAG | CENTERFLAG); // ユーザーデータコピー ret.setUserData(getUserData()); return ret; } void Polygon::setVtx(int n, const Vec3& src) { _vtx[n] = src; spn::Bit::Set<decltype(_rflg)>(_rflg, NORMALFLAG | PLANEFLAG | CENTERFLAG); } const Plane& Polygon::getPlane() const { // PLANE更新フラグチェック if(spn::Bit::ChClear<decltype(_rflg)>(_rflg, PLANEFLAG)) { // 平面生成 _plane = Plane::FromPtDir(_vtx[0], getNormal()); } return _plane; } const Vec3& Polygon::getGCenter3D() const { if(spn::Bit::ChClear<decltype(_rflg)>(_rflg, CENTERFLAG)) { // 中心点計算 _vCenter *= 0; for(int i=0 ; i<3 ; i++) _vCenter += _vtx[i]; _vCenter /= 3; } return _vCenter; } float Polygon::calcRadius() const{ getGCenter3D(); float dist = 0; for(int i=0 ; i<3 ; i++) { float td = _vtx[i].distance(_vCenter); if(td > dist) dist = td; } return dist; } float Polygon::calcAcreage() const { Vec3 v0 = _vtx[1] - _vtx[0], v1 = _vtx[2] - _vtx[0]; if(v0.len_sq() < std::numeric_limits<float>::epsilon() || v1.len_sq() < std::numeric_limits<float>::epsilon()) return 0.0f; return (v0 % v1).length() / 2; } Segment Polygon::getEdge(int n) const { return Segment(_vtx[n], _vtx[(n+1)%3]); } Vec3 Polygon::_calcLineHit(const Vec3& pos, const Vec3& dir) const { Vec3 toV1 = _vtx[1]-_vtx[0], toV2 = _vtx[2]-_vtx[0]; float det = spn::CramerDet(toV1, toV2, dir); return spn::CramersRule(toV1, toV2, dir, pos-_vtx[0], 1.0f/det); } bool Polygon::_IsValidRange(const Vec3& res) { return spn::IsInRange(res.x, 0.0f, 1.0f) && spn::IsInRange(res.y, 0.0f, 1.0f) && spn::IsInRange(res.x+res.y, 0.0f, 1.0f); } bool Polygon::hit(const Ray& ray) const { Vec3 res = _calcLineHit(ray.pos, ray.dir); if(_IsValidRange(res)) { if(res.z < 0) return std::fabs(getPlane().dot(ray.pos)) >= 0; return true; } return false; } bool Polygon::hit(const Line& ls) const { // Rayの始点チェックを省いたバージョン Vec3 res = _calcLineHit(ls.pos, ls.dir); return _IsValidRange(res); } std::pair<Vec3,bool> Polygon::nearest(const Vec3& p) const { const auto& nml = getNormal(); Vec3 res = _calcLineHit(p, nml); Vec3 cp = _vtx[0] + (_vtx[1]-_vtx[0]) * res.x + (_vtx[2]-_vtx[0]) * res.y; if(_IsValidRange(res)) return std::make_pair(cp, true); // 各線分との距離を計算 Vec3 minNP = Segment(_vtx[0], _vtx[1]).nearest(p).first; float minD = minNP.dist_sq(p); for(int i=1 ; i<3 ; i++) { Vec3 np = Segment(_vtx[i], _vtx[(i+1)%3]).nearest(p).first; float d = np.dist_sq(p); if(d < minD) { minD = d; minNP = np; } } return std::make_pair(minNP, false); } Vec3 Polygon::support(const Vec3& dir) const { float d[3]; for(int i=0 ; i<3 ; i++) d[i] = dir.dot(_vtx[i]); if(d[0] > d[1]) { if(d[0] > d[2]) return _vtx[0]; return _vtx[2]; } else { if(d[1] > d[2]) return _vtx[1]; return _vtx[2]; } } Plane Polygon::getEdgePlane(int n) const { Vec3 tv = _vtx[(n+1)%3] - _vtx[n]; tv = getNormal() % tv; tv.normalize(); return Plane::FromPtDir(_vtx[n], tv); } bool Polygon::isOnTriangleSpace(const Vec3& p) const { // エッジを含みポリゴンと垂直な平面を3つ定義 const float epsilon = -1e-5f; for(int i=0 ; i<3 ; i++) { if(getEdgePlane(0).dot(p) <= epsilon) return false; } return true; } std::pair<int,int> Polygon::split(Polygon (&dst)[3], const Plane& plane) const { ColCv cv = ColCv::FromVtx(_vtx[0], _vtx[1], _vtx[2]), cvd[2]; cv.split(plane, cvd[0], cvd[1]); int cur = 0, pcur[2] = {}; for(int i=0 ; i<2 ; i++) { int nP = pcur[i] = cvd[i].getNPoly(); for(int j=0 ; j<nP ; j++) dst[cur++] = cvd[i].getPolygon(j); } return std::make_pair(pcur[0], pcur[1]); } } }
26.868421
86
0.588834
degarashi
9eb9ad20a51c3b259b6c9f35e09e25dea22e6ac4
4,265
cpp
C++
libwarpsharp/src/IntegerKernel.cpp
waddlesplash/WonderBrush-v2
df20b6a43115d02e4606c71f27d0712ac2aebb62
[ "MIT" ]
11
2018-11-10T11:14:11.000Z
2021-12-27T17:17:08.000Z
libwarpsharp/src/IntegerKernel.cpp
waddlesplash/WonderBrush-v2
df20b6a43115d02e4606c71f27d0712ac2aebb62
[ "MIT" ]
27
2018-11-11T00:06:25.000Z
2021-06-24T06:43:38.000Z
libwarpsharp/src/IntegerKernel.cpp
waddlesplash/WonderBrush-v2
df20b6a43115d02e4606c71f27d0712ac2aebb62
[ "MIT" ]
7
2018-11-10T20:32:49.000Z
2021-03-15T18:03:42.000Z
// IntegerKernel.cpp #include <stdio.h> #include "support.h" #include "Gray8Image.h" #include "IntegerKernel.h" using std::cerr; // constructor IntegerKernel::IntegerKernel(kernel_func function, int32 radius, bool horizontal) : fElement(NULL), fDiameter(0), fHorizontal(horizontal), fSymetry(KERNEL_SYMETRIC), fScale(0) { if (function && radius >= 0) { fDiameter = 2 * radius + 1; fElement = new int32[fDiameter]; if (fElement) { fElement[radius] = (int32)function(0); for (int32 i = 1; i < radius + 1; i++) { fElement[radius + i] = (int32)function(3 * float(i) / radius); fElement[radius - i] = (int32)function(3 * float(-i) / radius); } } else fDiameter = 0; } } // constructor IntegerKernel::IntegerKernel(int32* elements, int32 diameter, bool horizontal, uint32 symetry, int32 scale) : fElement(copy(elements, diameter)), fDiameter(diameter), fHorizontal(horizontal), fSymetry(symetry), fScale(scale) { } // copy constructor IntegerKernel::IntegerKernel(IntegerKernel& from) : fElement(copy(from.Element(), from.Diameter())), fDiameter(from.Diameter()), fHorizontal(from.IsHorizontal()), fSymetry(from.Symetry()), fScale(from.Scale()) { } // destructor IntegerKernel::~IntegerKernel() { delete[] fElement; } // IsValid bool IntegerKernel::IsValid() const { if (fElement && fDiameter > 0) return true; return false; } // = IntegerKernel& IntegerKernel::operator=(IntegerKernel& from) { if (this != &from) { delete[] fElement; fElement = copy(from.Element(), from.Diameter()); fDiameter = from.Diameter(); fHorizontal = from.IsHorizontal(); fSymetry = from.Symetry(); fScale = from.Scale(); } return *this; } // * Gray8Image* IntegerKernel::operator*(Gray8Image* from) const { Gray8Image* result = NULL; if (IsValid() && from && from->IsValid()) { uint32 width = from->Width(); uint32 height = from->Height(); result = new Gray8Image(width, height); if (result && result->IsValid()) { result->SetAllPixels(0); uint8* np = result->Pixel(); uint32 rad = fDiameter / 2; uint32 i, j, k; uint8* data = from->Pixel(); switch (fSymetry) { case KERNEL_GENERAL: if (fHorizontal) { for (j = 0; j < height; j++) for (i = rad; i < width - rad; i++) for (k = -rad; k <= rad; k++) np[i + j * width] += data[(i + k) + j * width] * fElement[k + rad]; } else { for (j = rad; j < height - rad; j++) for (i = 0; i < width; i++) for (k = -rad; k <= rad; k++) np[i + j * width] += data[i + (k + j) * width] * fElement[k + rad]; } break; case KERNEL_SYMETRIC: if (fHorizontal) { for (j = 0; j < height; j++) for (i = rad; i < width - rad; i++) { np[i + j * width] = data[i + j * width] * fElement[rad]; for (k = 1; k <= rad; k++) np[i + j * width] += (data[(i + k) + j * width] + data[(i - k) + j * width]) * fElement[k + rad]; } } else { for (j = rad; j < height - rad; j++) for (i = 0; i < width; i++) { np[i + j * width] = data[i + j * width] * fElement[rad]; for (k = 1; k <= rad; k++) np[i + j * width] += (data[i + (j + k) * width] + data[i + (j - k) * width]) * fElement[k + rad]; } } break; case KERNEL_ANTISYMETRIC: if (fHorizontal) for (j = 0; j < height; j++) for (i = rad; i < width - rad; i++) { for(k = 1; k <= rad; k++) np[i + j * width] += (data[(i + k) + j * width] - data[(i - k) + j * width]) * fElement[k + rad]; } else { for (j = rad; j < height - rad; j++) for (i = 0; i < width; i++) for (k = 1; k <= rad; k++) np[i + j * width] += (data[i + (j + k) * width] -data[i + (j - k) * width]) * fElement[k + rad]; } break; } } else { delete result; result = NULL; } } return result; } // PrintToStream void IntegerKernel::PrintToStream() { int32 r = Radius(); for (int32 i = -r; i <= r; i++) cerr << '(' << i << ", " << fElement[i + r] << ")\n"; }
23.826816
81
0.52544
waddlesplash
9ebd6392b746f97cf6ff5e91845f08d3fb0828ee
223
cpp
C++
path_tracking/stanley_controller/test/main.cpp
nvdpsingh/cpp_robotics
1ec80f16cd93abe2ff197f646a06a3ad9ef13dbd
[ "MIT" ]
57
2019-07-02T00:58:48.000Z
2022-02-20T03:13:28.000Z
path_tracking/stanley_controller/test/main.cpp
leoandersoon/cpp_robotics
b667074485117ffd68f54c3fd867a3c5f510edd9
[ "MIT" ]
null
null
null
path_tracking/stanley_controller/test/main.cpp
leoandersoon/cpp_robotics
b667074485117ffd68f54c3fd867a3c5f510edd9
[ "MIT" ]
28
2019-07-02T02:00:26.000Z
2022-02-28T16:42:35.000Z
#include <iostream> #include "stanley_controller.hpp" int main() { std::cout << "Hello, World!" << std::endl; cpp_robotics::path_tracking::stanley_controller::StanleyController sc; sc.test(); return 0; }
18.583333
74
0.668161
nvdpsingh
9ec751721ee776c12ce8506a1656d35523d28eab
3,512
cpp
C++
source/world/nodes/Node.cpp
RaygenGroup/kaleido
e4648c3f4ba88a1aae942fdd854b32142e35fb78
[ "MIT" ]
4
2021-01-28T07:39:53.000Z
2022-01-17T14:02:13.000Z
source/world/nodes/Node.cpp
RaygenEngine/Kaleido
e4648c3f4ba88a1aae942fdd854b32142e35fb78
[ "MIT" ]
null
null
null
source/world/nodes/Node.cpp
RaygenEngine/Kaleido
e4648c3f4ba88a1aae942fdd854b32142e35fb78
[ "MIT" ]
null
null
null
#include "pch/pch.h" #include "world/nodes/Node.h" #include "asset/util/ParsingAux.h" #include "asset/AssetManager.h" #include "reflection/ReflectionTools.h" #include "world/World.h" #include "core/MathAux.h" #include <glm/gtx/matrix_decompose.hpp> RootNode* Node::GetWorldRoot() const { return Engine::GetWorld()->GetRoot(); } void Node::SetNodePositionLCS(glm::vec3 lt) { m_localPosition = lt; AutoUpdateTransforms(); } void Node::SetNodeOrientationLCS(glm::quat lo) { m_localOrientation = lo; AutoUpdateTransforms(); } void Node::SetNodeEulerAnglesLCS(glm::vec3 pyr) { SetNodeOrientationLCS(glm::quat(glm::radians(pyr))); } void Node::SetNodeScaleLCS(glm::vec3 ls) { m_localScale = ls; AutoUpdateTransforms(); } void Node::SetNodeTransformLCS(const glm::mat4& lm) { m_localTransform = lm; glm::vec3 skew; glm::vec4 persp; glm::decompose(lm, m_localScale, m_localOrientation, m_localPosition, skew, persp); AutoUpdateTransforms(); } void Node::SetNodeLookAtLCS(glm::vec3 lookAt) { SetNodeOrientationLCS(math::OrientationFromLookatAndPosition(lookAt, m_localPosition)); } void Node::SetNodePositionWCS(glm::vec3 wt) { auto parentMatrix = GetParent()->GetNodeTransformWCS(); SetNodePositionLCS(glm::inverse(parentMatrix) * glm::vec4(wt, 1.f)); } void Node::SetNodeOrientationWCS(glm::quat wo) { auto worldMatrix = math::TransformMatrixFromSOT(m_scale, wo, m_position); SetNodeTransformWCS(worldMatrix); } void Node::SetNodeEulerAnglesWCS(glm::vec3 pyr) { SetNodeOrientationWCS(glm::quat(glm::radians(pyr))); } void Node::RotateNodeAroundAxisWCS(glm::vec3 worldAxis, float degrees) { const glm::quat rot = glm::angleAxis(glm::radians(degrees), glm::vec3(worldAxis)); SetNodeOrientationWCS(rot * m_orientation); } void Node::RotateNodeAroundAxisLCS(glm::vec3 localAxis, float degrees) { const glm::quat rot = glm::angleAxis(glm::radians(degrees), glm::vec3(localAxis)); SetNodeOrientationLCS(rot * m_localOrientation); } void Node::SetNodeScaleWCS(glm::vec3 ws) { auto worldMatrix = math::TransformMatrixFromSOT(ws, m_orientation, m_position); SetNodeTransformWCS(worldMatrix); } void Node::SetNodeTransformWCS(const glm::mat4& newWorldMatrix) { auto parentMatrix = GetParent()->GetNodeTransformWCS(); SetNodeTransformLCS(glm::inverse(parentMatrix) * newWorldMatrix); } void Node::SetNodeLookAtWCS(glm::vec3 lookAt) { SetNodeOrientationWCS(math::OrientationFromLookatAndPosition(lookAt, m_position)); } void Node::CalculateWorldAABB() { m_aabb = m_localBB; m_aabb.Transform(GetNodeTransformWCS()); } void Node::AutoUpdateTransforms() { UpdateTransforms(GetParent()->GetNodeTransformWCS()); } void Node::UpdateTransforms(const glm::mat4& parentMatrix) { m_dirty.set(DF::SRT); m_localTransform = math::TransformMatrixFromSOT(m_localScale, m_localOrientation, m_localPosition); m_transform = parentMatrix * m_localTransform; CalculateWorldAABB(); // PERF: glm::vec3 skew; glm::vec4 persp; glm::decompose(m_transform, m_scale, m_orientation, m_position, skew, persp); for (auto& uPtr : m_children) { uPtr->UpdateTransforms(m_transform); } } void Node::DeleteChild(Node* child) { auto it = std::find_if(m_children.begin(), m_children.end(), [&](auto& ref) { return ref.get() == child; }); m_children.erase(it); m_dirty.set(DF::Children); } void Node::AddNodePositionOffsetLCS(glm::vec3 offset) { SetNodePositionLCS(m_localPosition + offset); } void Node::AddNodePositionOffsetWCS(glm::vec3 offset) { SetNodePositionWCS(m_position + offset); }
23.891156
109
0.758257
RaygenGroup
9eca5a1f63d4545c8fdf6f44c02c7aa2852a27dc
1,794
cpp
C++
src/tests-core/tests/prototype/sample_suite.cpp
victor-smirnov/memoria
c36a957c63532176b042b411b1646c536e71a658
[ "BSL-1.0", "Apache-2.0", "OLDAP-2.8", "BSD-3-Clause" ]
2
2021-07-30T16:54:24.000Z
2021-09-08T15:48:17.000Z
src/tests-core/tests/prototype/sample_suite.cpp
victor-smirnov/memoria
c36a957c63532176b042b411b1646c536e71a658
[ "BSL-1.0", "Apache-2.0", "OLDAP-2.8", "BSD-3-Clause" ]
null
null
null
src/tests-core/tests/prototype/sample_suite.cpp
victor-smirnov/memoria
c36a957c63532176b042b411b1646c536e71a658
[ "BSL-1.0", "Apache-2.0", "OLDAP-2.8", "BSD-3-Clause" ]
2
2020-03-14T15:15:25.000Z
2020-06-15T11:26:56.000Z
// Copyright 2013 Victor Smirnov // // 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 <memoria/tests/tests.hpp> #include <memoria/tests/assertions.hpp> #include <memoria/tests/yaml.hpp> #include <memoria/reactor/reactor.hpp> #include <memoria/core/tools/time.hpp> #include <memoria/core/tools/random.hpp> #include <memoria/api/allocator/allocator_inmem_api.hpp> namespace memoria { namespace tests { using namespace reactor; class SampleSuite: public TestState { using MyType = SampleSuite; using Base = TestState; StdString text_{"ABCDE"}; InMemAllocator<> allocator_; UUID uuid_{UUID::make_random()}; public: MMA_STATE_FILEDS(text_, uuid_); MMA_INDIRECT_STATE_FILEDS(allocator_); SampleSuite() { allocator_ = InMemAllocator<>::create(); } static void init_suite(TestSuite& suite) { MMA_CLASS_TEST_WITH_REPLAY(suite, doSomething, replaySomething); } void doSomething() { text_ += ": 12345 99"; engine().coutln("Test doSomething: {}", text_); //assert_equals(1,2); } void replaySomething() { engine().coutln("Replay doSomething: {} {}", text_, uuid_); } }; namespace { auto Suite1 = register_class_suite<SampleSuite>("SampleSuite"); } }}
23.298701
75
0.69621
victor-smirnov
9ecc879c8ce38f6b9b10e646b5a908af8745e8fb
517
hpp
C++
Axis.CommonLibrary/domain/fwd/numerical_model.hpp
renato-yuzup/axis-fem
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
[ "MIT" ]
2
2021-07-23T08:49:54.000Z
2021-07-29T22:07:30.000Z
Axis.CommonLibrary/domain/fwd/numerical_model.hpp
renato-yuzup/axis-fem
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
[ "MIT" ]
null
null
null
Axis.CommonLibrary/domain/fwd/numerical_model.hpp
renato-yuzup/axis-fem
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
[ "MIT" ]
null
null
null
#pragma once /* Forward declaration generally required when manipulating the numerical model. */ namespace axis { namespace domain { namespace analyses { class NumericalModel; class ModelKinematics; class ModelDynamics; } // namespace analyses namespace elements { class Node; class DoF; class FiniteElement; } // namespace elements namespace curves { class Curve; } // namespace curves namespace boundary_conditions { class BoundaryCondition; } // namespace boundary_conditions } } // namespace axis::domain
17.233333
77
0.779497
renato-yuzup
19b2c011bb5acff263702c20ff31c30de367f8c2
6,455
cpp
C++
Demos/VerveTutorialBase/source/Verve/VActor/Humanoid/VHumanoidActor.cpp
AnteSim/Verve
22a55d182f86e3d7684fdc52f628ca57837cac8a
[ "MIT" ]
1
2021-01-02T09:17:18.000Z
2021-01-02T09:17:18.000Z
Templates/Verve/source/Verve/VActor/Humanoid/VHumanoidActor.cpp
AnteSim/Verve
22a55d182f86e3d7684fdc52f628ca57837cac8a
[ "MIT" ]
null
null
null
Templates/Verve/source/Verve/VActor/Humanoid/VHumanoidActor.cpp
AnteSim/Verve
22a55d182f86e3d7684fdc52f628ca57837cac8a
[ "MIT" ]
4
2015-05-16T17:35:07.000Z
2021-01-02T09:17:26.000Z
//----------------------------------------------------------------------------- // Verve // Copyright (C) - Violent Tulip //----------------------------------------------------------------------------- #include "VHumanoidActor.h" #include "core/stream/bitStream.h" //----------------------------------------------------------------------------- IMPLEMENT_CO_NETOBJECT_V1( VHumanoidActor ); //----------------------------------------------------------------------------- VHumanoidActor::VHumanoidActor( void ) { // Void. } VHumanoidActor::~VHumanoidActor( void ) { // Void. } //----------------------------------------------------------------------------- // // Initialisation Methods. // //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // // VHumanoidActor::onNewDataBlock( pDataBlock ); // // ... // //----------------------------------------------------------------------------- bool VHumanoidActor::onNewDataBlock( GameBaseData *pDataBlock, bool pReload ) { // Store DataBlock Reference. mDataBlock = dynamic_cast<VHumanoidActorData*>( pDataBlock ); // Valid Data? if ( !mDataBlock || !Parent::onNewDataBlock( pDataBlock, pReload ) ) { // Invalid Data. return false; } // Initialise the Controllers. if ( !initAnimationController() || !initPhysicsController() ) { // Invalid. return false; } // Initialise the Base Animation Thread. mAnimationController.initBaseAnimation( VHumanoidActorData::k_IdleAnimation, 0.f, 1.f ); // Initialise the Arm Animation Thread. mAnimationController.initArmAnimation( VHumanoidActorData::k_ArmsUpDownAnimation, 0.5f, 1.f ); /* // Initialise Head Threads. initAnimationSequence( VHumanoidActorData::k_HeadHorizontalAnimation, mHeadAnimation.HThread, 0.5f ); initAnimationSequence( VHumanoidActorData::k_HeadVerticalAnimation, mHeadAnimation.VThread, 0.5f ); */ // Valid Data. return true; } //----------------------------------------------------------------------------- // // Update Methods. // //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // // VHumanoidActor::processTick( pMove ); // // ... // //----------------------------------------------------------------------------- void VHumanoidActor::processTick( const Move *pMove ) { // Parent Call. Parent::processTick( pMove ); // Update Physics. mPhysicsController.update( TickSec, pMove ); // Update Container. updateContainer(); } //----------------------------------------------------------------------------- // // VHumanoidActor::interpolateTick( pDelta ); // // ... // //----------------------------------------------------------------------------- void VHumanoidActor::interpolateTick( F32 pDelta ) { // Parent Call. Parent::interpolateTick( pDelta ); // Update Physics. mPhysicsController.interpolateTick( pDelta ); } //----------------------------------------------------------------------------- // // VHumanoidActor::advanceTime( pDelta ); // // ... // //----------------------------------------------------------------------------- void VHumanoidActor::advanceTime( F32 pDelta ) { // Parent Call. Parent::advanceTime( pDelta ); // Valid Animation Controller? if ( getAnimationController() ) { // Update Animations. getAnimationController()->update( pDelta ); } } //----------------------------------------------------------------------------- // // VHumanoidActor::packUpdate( pConnection, pMask, pStream ); // // ... // //----------------------------------------------------------------------------- U32 VHumanoidActor::packUpdate( NetConnection *pConnection, U32 pMask, BitStream *pStream ) { // Parent Call. U32 retMask = Parent::packUpdate( pConnection, pMask, pStream ); // Physics Controller? if ( pStream->writeFlag( pMask & PhysicsMask ) ) { // Pack Physics. retMask &= mPhysicsController.packUpdate( pConnection, pMask, pStream ); } return retMask; } //----------------------------------------------------------------------------- // // VHumanoidActor::unpackUpdate( pConnection, pStream ); // // ... // //----------------------------------------------------------------------------- void VHumanoidActor::unpackUpdate( NetConnection *pConnection, BitStream *pStream ) { // Parent Call. Parent::unpackUpdate( pConnection, pStream ); // Physics Controller? if ( pStream->readFlag() ) { // Unpack Physics. mPhysicsController.unpackUpdate( pConnection, pStream ); } } //----------------------------------------------------------------------------- // // Animation Methods. // //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // // VHumanoidActor::initAnimationController(); // // ... // //----------------------------------------------------------------------------- bool VHumanoidActor::initAnimationController( void ) { // Reference Object. mAnimationController.setObject( this ); // Initialise. return mAnimationController.initAnimationTable(); } //----------------------------------------------------------------------------- // // VHumanoidActor::getAnimationController(); // // ... // //----------------------------------------------------------------------------- VActorAnimationController *VHumanoidActor::getAnimationController( void ) { return &mAnimationController; } //----------------------------------------------------------------------------- // // VHumanoidActor::initPhysicsController(); // // ... // //----------------------------------------------------------------------------- bool VHumanoidActor::initPhysicsController( void ) { // Initialise. return mPhysicsController.initPhysicsController( this ); } //----------------------------------------------------------------------------- // // VHumanoidActor::getAnimationController(); // // ... // //----------------------------------------------------------------------------- VActorPhysicsController *VHumanoidActor::getPhysicsController( void ) { return &mPhysicsController; }
26.673554
105
0.41828
AnteSim
19b4ea4abff43abd9f3ae2cea240b2b94596cc12
265,414
cpp
C++
src/base/ex_eval.cpp
dufferprog/verbexx
bfc3c30ad2ca6c246c8f88405b386475278f9ecc
[ "MIT" ]
null
null
null
src/base/ex_eval.cpp
dufferprog/verbexx
bfc3c30ad2ca6c246c8f88405b386475278f9ecc
[ "MIT" ]
1
2018-09-14T00:07:27.000Z
2018-09-14T00:07:27.000Z
src/base/ex_eval.cpp
dufferprog/verbexx
bfc3c30ad2ca6c246c8f88405b386475278f9ecc
[ "MIT" ]
1
2018-09-13T23:43:12.000Z
2018-09-13T23:43:12.000Z
// ex_eval.cpp ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //// //// //// =========== //// ex_eval.cpp -- input stream evaluation functions //// =========== //// //// //// //// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include "h__include.h" #pragma hdrstop("../pch/pch_std.pch") #define M_IN_EX_DLL #include "h__common.h" #include "h_ex_interface.h" #include "h_ex_parse.h" #include "h_ex_verb.h" #define NOEVAL_VERBLESS false // do evaluate values in verbless expressions // forward declarations for selected static functions // -------------------------------------------------- static int check_verb_parms(frame_S&, const e_expression_S&, const verbdef_S& ); static int check_verb_value(frame_S&, const e_expression_S&, const parmtype_S&, const value_S&, const std::wstring& ); static int check_verb_vlist(frame_S&, const e_expression_S&, const plist_S& , const vlist_S&, const std::wstring&, const std::wstring& = L""); // static variables // ---------------- namespace static_N { // evaluation statistics and counters uint64_t verb_count {0}; // number of verbs executed uint64_t value_count {0}; // number of values evaluated uint64_t block_count {0}; // number of blocks executed uint64_t statement_count {0}; // number of blocks executed uint64_t frame_serial {0}; // serial number of most-recently allocated (or filld-in) frame_S uint64_t frame_depth {0}; // current number of stack frames on stack uint64_t frame_max_depth {0}; // maximum number of frames on stack (high-water mark) std::shared_ptr<frame_S> newest_frame_sp { }; // owning pointer to newest stack frame on stack (keeps ref-count positive) } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ //▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ //▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ //▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ //▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ //▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ //▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ //▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ //▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////_________________________________________________________________________________________________________________________________________________________________ ////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ /////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ ////""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" //// //// //// frame statistics/utility functions //// //// ////_________________________________________________________________________________________________________________________________________________________________ ////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ /////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ ////""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" uint64_t get_eval_verb_count( void) {return static_N::verb_count ;} uint64_t get_eval_value_count( void) {return static_N::value_count ;} uint64_t get_eval_block_count( void) {return static_N::block_count ;} uint64_t get_eval_statement_count( void) {return static_N::statement_count ;} uint64_t get_eval_frame_serial( void) {return static_N::frame_serial ;} uint64_t get_eval_frame_depth( void) {return static_N::frame_depth ;} uint64_t get_eval_frame_max_depth( void) {return static_N::frame_max_depth ;} frame_S *get_newest_sf( void) {return static_N::newest_frame_sp.get() ;} ////_________________________________________________________________________________________________________________________________________________________________ ////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ /////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ ////""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" //// //// //// get_vlist_positional() -- get n-th positional value in vlist (if present) //// //// ////_________________________________________________________________________________________________________________________________________________________________ ////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ /////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ ////""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" int get_vlist_positional(const vlist_S& vlist, value_S& value, uint32_t n) try { // return unit value, and R/C = -1, if n-th positional parm is not present if (vlist.value_ct <= n) { value = unit_val(); return -1; } // n-th positional parm is present -- return parm value value = vlist.values.at(n); return 0; } M_endf ////_________________________________________________________________________________________________________________________________________________________________ ////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ /////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ ////""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" //// //// //// get_right_positional() -- get n-th positional value in right-side vlist (if present) //// //// ////_________________________________________________________________________________________________________________________________________________________________ ////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ /////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ ////""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" int get_right_positional(const e_expression_S& expression, value_S& value, uint32_t n) try { // return unit value, and R/C = -1, if n-th positional right-side parm is not present if (expression.rparms.value_ct <= n) { value = unit_val(); return -1; } // n-th positional right-side parm is present -- return parm value value = expression.rparms.values.at(n); return 0; } M_endf ////_________________________________________________________________________________________________________________________________________________________________ ////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ /////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ ////""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" //// //// //// get_left_positional() -- get n-th positional value in left-side vlist (if present) //// //// ////_________________________________________________________________________________________________________________________________________________________________ ////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ /////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ ////""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" int get_left_positional(const e_expression_S& expression, value_S& value, uint32_t n) try { // return unit value, and R/C = -1, if n-th positional left-side parm is not present if (expression.lparms.value_ct <= n) { value = unit_val(); return -1; } // n-th positional left-side parm is present -- return parm value value = expression.lparms.values.at(n); return 0; } M_endf ////_________________________________________________________________________________________________________________________________________________________________ ////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ /////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ ////""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" //// //// //// get_right_keyword() -- get n-th right-side keyword value (if present) //// //// ////_________________________________________________________________________________________________________________________________________________________________ ////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ /////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ ////""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" // version with passed-back value parm // ----------------------------------- int get_right_keyword(const e_expression_S& expression, const std::wstring& keyword_name, value_S& value, uint32_t n) try { // return unit value, and R/C = -1, if n-th right keyword is not present if (expression.rparms.eval_kws.count(keyword_name) <= n) { value = unit_val(); return -1; } // n-th keyword is present -- return keyword value value = multimap_at(expression.rparms.eval_kws, keyword_name, n); return 0; } M_endf // version with passed-back string parm // ------------------------------------ int get_right_keyword(const e_expression_S& expression, const std::wstring& keyword_name, std::wstring& ws, uint32_t n) try { // return R/C = -1, if n-th right keyword is not present -- don't modify caller's string if (expression.rparms.eval_kws.count(keyword_name) <= n) return -1; // n-th keyword is present -- find keyword value auto value = multimap_at(expression.rparms.eval_kws, keyword_name, n); if (value.ty == type_E::string) { ws = value.string; } else { count_error(); M_out_emsg1(L"get_right_keyword() -- verb= %s -- right keyword \"%S\" (%d) was not a string value, as expected") % verb_name(expression) % keyword_name % n; msgend_loc(value, expression); M_throw_v( "get_right_keyword() -- verb= %s -- right keyword \"%S\" (%d) was not a string value, as expected") % out_ws(verb_name(expression)) % out_ws(keyword_name) % n )); return -1; } return 0; } M_endf // version with passed-back int64_t parm // ------------------------------------- int get_right_keyword(const e_expression_S& expression, const std::wstring& keyword_name, int64_t& int64, uint32_t n) try { // return R/C = -1, if n-th right keyword is not present -- don't modify caller's string if (expression.rparms.eval_kws.count(keyword_name) <= n) return -1; // n-th keyword is present -- find keyword value auto value = multimap_at(expression.rparms.eval_kws, keyword_name, n); if (value.ty == type_E::int64) { int64 = value.int64; } else { count_error(); M_out_emsg1(L"get_right_keyword() -- verb= %s -- right keyword \"%S\" (%d) was not an int64 value, as expected") % verb_name(expression) % keyword_name % n; msgend_loc(value, expression); M_throw_v( "get_right_keyword() -- verb= %s -- right keyword \"%S\" (%d) was not an int64 value, as expected") % out_ws(verb_name(expression)) % out_ws(keyword_name) % n )); return -1; } return 0; } M_endf // version with passed-back float64_T parm // --------------------------------------- int get_right_keyword(const e_expression_S& expression, const std::wstring& keyword_name, float64_T& float64, uint32_t n) try { // return R/C = -1, if n-th right keyword is not present -- don't modify caller's string if (expression.rparms.eval_kws.count(keyword_name) <= n) return -1; // n-th keyword is present -- find keyword value auto value = multimap_at(expression.rparms.eval_kws, keyword_name, n); if (value.ty == type_E::float64) { float64 = value.float64; } else { count_error(); M_out_emsg1(L"get_right_keyword() -- verb= %s -- right keyword \"%S\" (%d) was not a float64 value, as expected") % verb_name(expression) % keyword_name % n; msgend_loc(value, expression); M_throw_v( "get_right_keyword() -- verb= %s -- right keyword \"%S\" (%d) was not a float64 value, as expected") % out_ws(verb_name(expression)) % out_ws(keyword_name) % n )); return -1; } return 0; } M_endf // version without passed-back value parm -- just R/C // -------------------------------------------------- int get_right_keyword(const e_expression_S& expression, const std::wstring& keyword_name, uint32_t n) try { // return R/C = -1, if n-th right keyword is not present if (expression.rparms.eval_kws.count(keyword_name) <= n) return -1; // n-th keyword is present -- return 0 return 0; } M_endf ////_________________________________________________________________________________________________________________________________________________________________ ////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ /////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ ////""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" //// //// //// get_left_keyword() -- get n-th left-side keyword value (if present) //// //// ////_________________________________________________________________________________________________________________________________________________________________ ////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ /////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ ////""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" // version with passed-back value parm // ----------------------------------- int get_left_keyword(const e_expression_S& expression, const std::wstring& keyword_name, value_S& value, uint32_t n) try { // return unit value, and R/C = -1, if n-th left keyword is not present if (expression.lparms.eval_kws.count(keyword_name) <= n) { value = unit_val(); return -1; } // n-th keyword is present -- return keyword value value = multimap_at(expression.lparms.eval_kws, keyword_name, n); return 0; } M_endf // version with passed-back string parm // ------------------------------------ int get_left_keyword(const e_expression_S& expression, const std::wstring& keyword_name, std::wstring& ws, uint32_t n) try { // return R/C = -1, if n-th left keyword is not present -- don't modify caller's string if (expression.lparms.eval_kws.count(keyword_name) <= n) return -1; // n-th keyword is present -- find keyword value auto value = multimap_at(expression.lparms.eval_kws, keyword_name, n); if (value.ty == type_E::string) { ws = value.string; } else { count_error(); M_out_emsg1(L"get_left_keyword() -- verb= %s -- left keyword \"%S\" (%d) was not a string value, as expected") % verb_name(expression) % keyword_name % n; msgend_loc(value, expression); M_throw_v( "get_left_keyword() -- verb= %s -- left keyword \"%S\" (%d) was not a string value, as expected") % out_ws(verb_name(expression)) % out_ws(keyword_name) % n )); return -1; } return 0; } M_endf // version with passed-back int64_t parm // ------------------------------------- int get_left_keyword(const e_expression_S& expression, const std::wstring& keyword_name, int64_t& int64, uint32_t n) try { // return R/C = -1, if n-th left keyword is not present -- don't modify caller's string if (expression.lparms.eval_kws.count(keyword_name) <= n) return -1; // n-th keyword is present -- find keyword value auto value = multimap_at(expression.lparms.eval_kws, keyword_name, n); if (value.ty == type_E::int64) { int64 = value.int64; } else { count_error(); M_out_emsg1(L"get_left_keyword() -- verb= %s -- left keyword \"%S\" (%d) was not an int64 value, as expected") % verb_name(expression) % keyword_name % n; msgend_loc(value, expression); M_throw_v( "get_left_keyword() -- verb= %s -- left keyword \"%S\" (%d) was not an int64 value, as expected") % out_ws(verb_name(expression)) % out_ws(keyword_name) % n )); return -1; } return 0; } M_endf // version with passed-back float64_T parm // ---------------------------------------- int get_left_keyword(const e_expression_S& expression, const std::wstring& keyword_name, float64_T& float64, uint32_t n) try { // return R/C = -1, if n-th left keyword is not present -- don't modify caller's string if (expression.lparms.eval_kws.count(keyword_name) <= n) return -1; // n-th keyword is present -- find keyword value auto value = multimap_at(expression.lparms.eval_kws, keyword_name, n); if (value.ty == type_E::float64) { float64 = value.float64; } else { count_error(); M_out_emsg1(L"get_left_keyword() -- verb= %s -- left keyword \"%S\" (%d) was not a float64 value, as expected") % verb_name(expression) % keyword_name % n; msgend_loc(value, expression); M_throw_v( "get_left_keyword() -- verb= %s -- left keyword \"%S\" (%d) was not a float64 value, as expected") % out_ws(verb_name(expression)) % out_ws(keyword_name) % n )); return -1; } return 0; } M_endf // version without passed-back value // --------------------------------- int get_left_keyword(const e_expression_S& expression, const std::wstring& keyword_name, uint32_t n) try { // return R/C = -1, if n-th right keyword is not present if (expression.lparms.eval_kws.count(keyword_name) <= n) return -1; // n-th keyword is present -- return 0 return 0; } M_endf ////_________________________________________________________________________________________________________________________________________________________________ ////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ /////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ ////""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" //// //// //// get_vlist_keyword() -- get value of n-th occurrence of passed-in keyword name, from vlist (if present) //// -- get value of n-th keyword in vlist (any keyword -- if no keyword name passed-in) //// //// ////_________________________________________________________________________________________________________________________________________________________________ ////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ /////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ ////""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" // version with passed-in keyword name -- passed-in value // ------------------------------------------------------ int get_vlist_keyword(const vlist_S& vlist, const std::wstring& keyword_name, value_S& value, uint32_t n) try { // return unit value, and R/C = -1, if n-th keyword is not present if (vlist.eval_kws.count(keyword_name) <= n) { value = unit_val(); return -1; } // n-th keyword is present -- return keyword value value = multimap_at(vlist.eval_kws, keyword_name, n); return 0; } M_endf // version with passed-in keyword name -- no passed-in value -- just R/C only // -------------------------------------------------------------------------- int get_vlist_keyword(const vlist_S& vlist, const std::wstring& keyword_name, uint32_t n) try { // return unit value, and R/C = -1, if n-th keyword is not present if (vlist.eval_kws.count(keyword_name) <= n) return -1; // n-th keyword is present -- normal R/C return 0; } M_endf // version with no passed-in keyword name // -------------------------------------- int get_vlist_keyword(const vlist_S& vlist, value_S& value, uint32_t n) try { // return unit value, and R/C = -1, if n-th keyword is not present if (vlist.eval_kws.size() <= n) { value = unit_val(); return -1; } // n-th keyword is present -- return keyword value value = multimap_deref(vlist.eval_kws, n).second; return 0; } M_endf ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ //▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ //▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ //▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ //▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ //▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ //▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ //▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ //▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //╔══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════ //║╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳ //║╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳ //║╳╳╳╳╔═════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════ //║╳╳╳╳║ //║╳╳╳╳║ //║╳╳╳╳║ //║╳╳╳╳║ CCCCCCCC HH HH EEEEEEEEEE CCCCCCCC KK KK //║╳╳╳╳║ CCCCCCCCCC HH HH EEEEEEEEEE CCCCCCCCCC KK KK //║╳╳╳╳║ CC CC HH HH EE CC CC KK KK //║╳╳╳╳║ CC HH HH EE CC KK KK //║╳╳╳╳║ CC HHHHHHHHHH EEEEEEEE CC KKKKKK //║╳╳╳╳║ CC HHHHHHHHHH EEEEEEEE CC KKKKKK //║╳╳╳╳║ CC HH HH EE CC KK KK //║╳╳╳╳║ CC CC HH HH EE CC CC KK KK //║╳╳╳╳║ CCCCCCCCCC HH HH EEEEEEEEEE CCCCCCCCCC KK KK //║╳╳╳╳║ CCCCCCCC HH HH EEEEEEEEEE CCCCCCCC KK KK //║╳╳╳╳║ //║╳╳╳╳║ //║╳╳╳╳║ //║╳╳╳╳╚═════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════ //║╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳ //║╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳ //╚══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════ ////_________________________________________________________________________________________________________________________________________________________________ ////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ /////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ ////""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" //// //// //// check_verb_value() -- complain and return error, if passed-in value doesn't match what is expected in the passed-in parmtype_S structure //// //// ////_________________________________________________________________________________________________________________________________________________________________ ////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ /////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ ////""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" // internal helper function for check_verb_parms() static int check_verb_value(frame_S& frame, const e_expression_S& expression, const parmtype_S& parmtype, const value_S& value, const std::wstring& ws) try { int rc {0}; // return OK, if no checking needed -- includes bypassing nested vlist checking if (parmtype.anything_ok) return 0; // check this value type compared to what is allowed in passed-in parmtype_S structure if ( (!parmtype.nval_ok) && (value.ty == type_E::no_value) ) // keyword with no associated value { count_error(); M_out_emsg1(L"check_verb_value() -- verb= %s %s -- unexpected keyword with no following value") % verb_name(expression) % ws; msgend_loc(value, expression); rc = -1; } if ( (!parmtype.unit_ok) && (value.ty == type_E::unit) ) { count_error(); M_out_emsg1(L"check_verb_value() -- verb= %s %s -- unexpected unit parm") % verb_name(expression) % ws; msgend_loc(value, expression); rc = -1; } if ( (!parmtype.int8_ok) && (value.ty == type_E::int8) ) { count_error(); M_out_emsg1(L"check_verb_value() -- verb= %s %s -- unexpected int8 parm = %d") % verb_name(expression) % ws % (int16_t)(value.int8); msgend_loc(value, expression); rc = -1; } if ( (!parmtype.int16_ok) && (value.ty == type_E::int16) ) { count_error(); M_out_emsg1(L"check_verb_value() -- verb= %s %s -- unexpected int16 parm = %d") % verb_name(expression) % ws % value.int16; msgend_loc(value, expression); rc = -1; } if ( (!parmtype.int32_ok) && (value.ty == type_E::int32) ) { count_error(); M_out_emsg1(L"check_verb_value() -- verb= %s %s -- unexpected int32 parm = %d") % verb_name(expression) % ws % value.int32; msgend_loc(value, expression); rc = -1; } if ( (!parmtype.int64_ok) && (value.ty == type_E::int64) ) { count_error(); M_out_emsg1(L"check_verb_value() -- verb= %s %s -- unexpected int64 parm = %d") % verb_name(expression) % ws % value.int64; msgend_loc(value, expression); rc = -1; } if ( (!parmtype.uint8_ok) && (value.ty == type_E::uint8) ) { count_error(); M_out_emsg1(L"check_verb_value() -- verb= %s %s -- unexpected uint8 parm = %d") % verb_name(expression) % ws % (uint16_t)(value.uint8); msgend_loc(value, expression); rc = -1; } if ( (!parmtype.uint16_ok) && (value.ty == type_E::uint16) ) { count_error(); M_out_emsg1(L"check_verb_value() -- verb= %s %s -- unexpected uint16 parm = %d") % verb_name(expression) % ws % value.uint16; msgend_loc(value, expression); rc = -1; } if ( (!parmtype.uint32_ok) && (value.ty == type_E::uint32) ) { count_error(); M_out_emsg1(L"check_verb_value() -- verb= %s %s -- unexpected uint32 parm = %d") % verb_name(expression) % ws % value.uint32; msgend_loc(value, expression); rc = -1; } if ( (!parmtype.uint64_ok) && (value.ty == type_E::uint64) ) { count_error(); M_out_emsg1(L"check_verb_value() -- verb= %s %s -- unexpected uint64 parm = %d") % verb_name(expression) % ws % value.uint64; msgend_loc(value, expression); rc = -1; } if ( (!parmtype.float32_ok) && (value.ty == type_E::float32) ) { count_error(); M_out_emsg1(L"check_verb_value() -- verb= %s %s -- unexpected float32 parm = %g") % verb_name(expression) % ws % value.float32; msgend_loc(value, expression); rc = -1; } if ( (!parmtype.float64_ok) && (value.ty == type_E::float64) ) { count_error(); M_out_emsg1(L"check_verb_value() -- verb= %s %s -- unexpected float64 parm = %g") % verb_name(expression) % ws % value.float64; msgend_loc(value, expression); rc = -1; } if ( (!parmtype.string_ok) && (value.ty == type_E::string) ) { count_error(); M_out_emsg1(L"check_verb_value() -- verb= %s %s -- unexpected string parm = «%s»") % verb_name(expression) % ws % shorten_str(value.string, const_N::loctext_max); msgend_loc(value, expression); rc = -1; } if ( (!parmtype.verbname_ok) && (value.ty == type_E::verbname) ) { count_error(); M_out_emsg1(L"check_verb_value() -- verb= %s %s -- unexpected verbname parm = «%s»") % verb_name(expression) % ws % shorten_str(value.string, const_N::loctext_max); msgend_loc(value, expression); rc = -1; } // check (unevaluated) identifiers -- raw(all) / variable /constant / undefined // ---------------------------------------------------------------------------- if (value.ty == type_E::identifier) { if (parmtype.raw_ident_ok) // allow any kind of (unevaluated) identifier? -- includes typdef and verbset ???? { ; // OK -- no need to check identifier type (var/const/undef) } else if ( // see if some type of identifier is OK (!parmtype.var_ident_ok ) && (!parmtype.const_ident_ok) && (!parmtype.typdef_ident_ok) && (!parmtype.verbset_ident_ok) && (!parmtype.undef_ident_ok) ) { // not expecting any type of identifier -- error count_error(); M_out_emsg1(L"check_verb_value() -- verb= %s %s -- unexpected identifier parm = %s") % verb_name(expression) % ws % shorten_str(value.string, const_N::loctext_max); msgend_loc(value, expression); rc = -1; } else // expecting some specific type(s) of identifier -- variable/const/verbset/typdefundef -- need to check further { // check local, global, or all stack frames for this identifier // note: assume local and global flags are not both set to true if (parmtype.check_local_env_only) { // check only local identifiers (not all) if ( (!parmtype.var_ident_ok) && is_local_identifier_variable(frame, value.string) ) { count_error(); M_out_emsg1(L"check_verb_value() -- verb= %s %s -- unexpected (unevaluated) already-defined local variable identifier parm = %s") % verb_name(expression) % ws % shorten_str(value.string, const_N::loctext_max) ; msgend_loc(value, expression); rc = -1; } if ( (!parmtype.const_ident_ok) && is_local_identifier_const(frame, value.string) ) { count_error(); M_out_emsg1(L"check_verb_value() -- verb= %s %s -- unexpected (unevaluated) already-defined local constant identifier parm = %s") % verb_name(expression) % ws % shorten_str(value.string, const_N::loctext_max); msgend_loc(value, expression); rc = -1; } if ( (!parmtype.typdef_ident_ok) && is_local_identifier_typdef(frame, value.string) ) { count_error(); M_out_emsg1(L"check_verb_value() -- verb= %s %s -- unexpected (unevaluated) already-defined local typdef identifier parm = %s") % verb_name(expression) % ws % shorten_str(value.string, const_N::loctext_max); msgend_loc(value, expression); rc = -1; } if ( (!parmtype.verbset_ident_ok) && is_local_identifier_verbset(frame, value.string) ) { count_error(); M_out_emsg1(L"check_verb_value() -- verb= %s %s -- unexpected (unevaluated) already-defined local verbset identifier parm = %s") % verb_name(expression) % ws % shorten_str(value.string, const_N::loctext_max); msgend_loc(value, expression); rc = -1; } if ( (!parmtype.undef_ident_ok) && (!is_local_identifier_defined(frame, value.string)) ) { count_error(); M_out_emsg1(L"check_verb_value() -- verb= %s %s -- unexpected undefined local identifier parm = %s") % verb_name(expression) % ws % shorten_str(value.string, const_N::loctext_max); msgend_loc(value, expression); rc = -1; } } else if (parmtype.check_global_env_only) { // check only global identifiers (not all) if ( (!parmtype.var_ident_ok) && is_global_identifier_variable(value.string) ) { count_error(); M_out_emsg1(L"check_verb_value() -- verb= %s %s -- unexpected (unevaluated) global already-defined variable identifier parm = %s") % verb_name(expression) % ws % shorten_str(value.string, const_N::loctext_max); msgend_loc(value, expression); rc = -1; } if ( (!parmtype.const_ident_ok) && is_global_identifier_const(value.string) ) { count_error(); M_out_emsg1(L"check_verb_value() -- verb= %s %s -- unexpected (unevaluated) global already-defined constant identifier parm = %s") % verb_name(expression) % ws % shorten_str(value.string, const_N::loctext_max); msgend_loc(value, expression); rc = -1; } if ( (!parmtype.typdef_ident_ok) && is_global_identifier_typdef(value.string) ) { count_error(); M_out_emsg1(L"check_verb_value() -- verb= %s %s -- unexpected (unevaluated) global already-defined typdef identifier parm = %s") % verb_name(expression) % ws % shorten_str(value.string, const_N::loctext_max); msgend_loc(value, expression); rc = -1; } if ( (!parmtype.verbset_ident_ok) && is_global_identifier_verbset(value.string) ) { count_error(); M_out_emsg1(L"check_verb_value() -- verb= %s %s -- unexpected (unevaluated) global already-defined verbset identifier parm = %s") % verb_name(expression) % ws % shorten_str(value.string, const_N::loctext_max); msgend_loc(value, expression); rc = -1; } if ( (!parmtype.undef_ident_ok) && (!is_global_identifier_defined(value.string)) ) { count_error(); M_out_emsg1(L"check_verb_value() -- verb= %s %s -- unexpected undefined global identifier parm = %s") % verb_name(expression) % ws % shorten_str(value.string, const_N::loctext_max); msgend_loc(value, expression); rc = -1; } } else // neither local or global flag is set -- check all stack frames for this identifier { // check all stack frames to see what identifier type is (var/const/undef) if ( (!parmtype.var_ident_ok) && is_identifier_variable(frame, value.string) ) { count_error(); M_out_emsg1(L"check_verb_value() -- verb= %s %s -- unexpected (unevaluated) already-defined variable identifier parm = %s") % verb_name(expression) % ws % shorten_str(value.string, const_N::loctext_max); msgend_loc(value, expression); rc = -1; } if ( (!parmtype.const_ident_ok) && is_identifier_const(frame, value.string) ) { count_error(); M_out_emsg1(L"check_verb_value() -- verb= %s %s -- unexpected (unevaluated) already-defined constant identifier parm = %s") % verb_name(expression) % ws % shorten_str(value.string, const_N::loctext_max); msgend_loc(value, expression); rc = -1; } if ( (!parmtype.typdef_ident_ok) && is_identifier_typdef(frame, value.string) ) { count_error(); M_out_emsg1(L"check_verb_value() -- verb= %s %s -- unexpected (unevaluated) already-defined typdef identifier parm = %s") % verb_name(expression) % ws % shorten_str(value.string, const_N::loctext_max); msgend_loc(value, expression); rc = -1; } if ( (!parmtype.verbset_ident_ok) && is_identifier_verbset(frame, value.string) ) { count_error(); M_out_emsg1(L"check_verb_value() -- verb= %s %s -- unexpected (unevaluated) already-defined verbset identifier parm = %s") % verb_name(expression) % ws % shorten_str(value.string, const_N::loctext_max); msgend_loc(value, expression); rc = -1; } if ( (!parmtype.undef_ident_ok) && (!is_identifier_defined(frame, value.string)) ) { count_error(); M_out_emsg1(L"check_verb_value() -- verb= %s %s -- unexpected undefined identifier parm = %s") % verb_name(expression) % ws % shorten_str(value.string, const_N::loctext_max); msgend_loc(value, expression); rc = -1; } } } // expecting specific identifier type(s) -- variable/const/undef } // identifier // check vlist, block, expression, verbdef, etc. // --------------------------------------------- M__(M_out(L"check_verb_value() -- value.ty = %d = %S") % (int)(value.ty) % type_str(value.ty);) if ( (!parmtype.vlist_ok) && (value.ty == type_E::vlist) ) { count_error(); M_out_emsg1(L"check_verb_value() -- verb= %s %s -- unexpected vlist parm") % verb_name(expression) % ws; msgend_loc(value, expression); rc = -1; } if ( (!parmtype.expression_ok) && (value.ty == type_E::expression) ) { count_error(); M_out_emsg1(L"check_verb_value() -- verb= %s %s -- unexpected expression parm") % verb_name(expression) % ws; msgend_loc(value, expression); rc = -1; } if ( (!parmtype.block_ok) && (value.ty == type_E::block) ) { count_error(); M_out_emsg1(L"check_verb_value() -- verb= %s %s -- unexpected block parm") % verb_name(expression) % ws; msgend_loc(value, expression); rc = -1; } if ( (!parmtype.verbset_ok) && (value.ty == type_E::verbset) ) { count_error(); M_out_emsg1(L"check_verb_value() -- verb= %s %s -- unexpected verbdef parm") % verb_name(expression) % ws; msgend_loc(value, expression); rc = -1; } if ( (!parmtype.typdef_ok) && (value.ty == type_E::typdef) ) { count_error(); M_out_emsg1(L"check_verb_value() -- verb= %s %s -- unexpected typdef parm") % verb_name(expression) % ws; msgend_loc(value, expression); rc = -1; } if ( (!parmtype.array_ok) && (value.ty == type_E::array) ) { count_error(); M_out_emsg1(L"check_verb_value() -- verb= %s %s -- unexpected array parm") % verb_name(expression) % ws; msgend_loc(value, expression); rc = -1; } if ( (!parmtype.structure_ok) && (value.ty == type_E::structure) ) { count_error(); M_out_emsg1(L"check_verb_value() -- verb= %s %s -- unexpected structure parm") % verb_name(expression) % ws; msgend_loc(value, expression); rc = -1; } if ( (!parmtype.lvalue_ref_ok) && ((value.ty == type_E::ref) && (value.ref_sp->is_lvalue)) ) { count_error(); M_out_emsg1(L"check_verb_value() -- verb= %s %s -- unexpected lvalue-ref parm") % verb_name(expression) % ws; msgend_loc(value, expression); rc = -1; } if ( (!parmtype.rvalue_ref_ok) && ((value.ty == type_E::ref) && (value.ref_sp->is_rvalue)) ) { count_error(); M_out_emsg1(L"check_verb_value() -- verb= %s %s -- unexpected rvalue-ref parm") % verb_name(expression) % ws; msgend_loc(value, expression); rc = -1; } // do int64 and float64 range checking // ----------------------------------- if ( (value.ty == type_E::int64) && parmtype.int64_ok && parmtype.int64_range ) { if ( (value.int64 < parmtype.int64_min) || (value.int64 > parmtype.int64_max) ) { count_error(); M_out_emsg1(L"check_verb_value() -- verb= %s %s -- int64 value is not in allowed range -- min=%d value=%d max=%d") % verb_name(expression) % ws % parmtype.int64_min % value.int64 % parmtype.int64_max; msgend_loc(value, expression); rc = -1; } } if ( (value.ty == type_E::float64) && parmtype.float64_ok && parmtype.float64_range ) { if ( (value.float64 < parmtype.float64_min) || (value.float64 > parmtype.float64_max) ) { count_error(); M_out_emsg1(L"check_verb_value() -- verb= %s %s -- float64 value is not in allowed range -- min=%g value=%g max=%g") % verb_name(expression) % ws % parmtype.float64_min % value.float64 % parmtype.float64_max; msgend_loc(value, expression); rc = -1; } } // validate nested vlist (if any) -- if passed-in parmtype_S points to a nested plist_S if ( parmtype.vlist_ok && (value.ty == type_E::vlist) && (parmtype.plist_sp.get() != nullptr) && (value.vlist_sp.get() != nullptr) ) { auto crc = check_verb_vlist(frame, expression, *(parmtype.plist_sp), *(value.vlist_sp), L" " + ws + L"nested vlist", L""); if (crc != 0) rc = crc; } return rc; } M_endf ////_________________________________________________________________________________________________________________________________________________________________ ////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ /////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ ////""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" //// //// //// check_verb_vlist() -- complain and return error, if values in passed-in vlist do not match what is expected in the passed-in plist_S structure //// -- note vlist should contain evaluated keywords //// ////_________________________________________________________________________________________________________________________________________________________________ ////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ /////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ ////""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" // internal helper function for check_verb_parms() static int check_verb_vlist(frame_S& frame, const e_expression_S& expression, const plist_S& plist, const vlist_S& vlist, const std::wstring& ws1, const std::wstring& ws2) try { int rc {0}; // check positional parms // ---------------------- if (!plist.no_check_positional) { // check positional parm count if (vlist.value_ct < plist.min_ct) { count_error(); M_out_emsg1(L"check_verb_vlist() -- verb= %s %s expects at least %d %s positional parm(s), but only %d were present") % verb_name(expression) % ws1 % plist.min_ct % ws2 % vlist.value_ct; msgend_loc(vlist, expression); rc = -1; } M__(M_out(L"check_verb_vlist() -- verb = %S plist.max_ct = %d vlist.value_ct = %d") % verb_name(expression) % plist.max_ct % vlist.value_ct; ) if ( (plist.max_ct >= 0) && (vlist.value_ct > plist.max_ct) ) { count_error(); M_out_emsg1(L"check_verb_vlist() -- verb= %s %s expects at most %d %s positional parm(s), but %d were present -- possible missing semicolon?") % verb_name(expression) % ws1 % plist.max_ct % ws2 % vlist.value_ct; msgend_loc(vlist, expression); rc = -1; } // set up default parmtype_S to use if vector does not have any parmtype_S elements (note this code is not executed during verb overload set pre-expansion) parmtype_S default_parmtype {}; // default parmtype default_parmtype.eval = plist.eval; // copy in eval flags (set only for verbless expression) default_parmtype.anything_ok = true; // allow anything -- default is no checking // loop to look at each positional parm and do parm type checking if (!plist.no_check_positional) { for (int i = 0; i < vlist.values.size(); i++) { std::wstring ws {ws1 + ws2 + L" positional parm " + std::to_wstring(i) + L":"}; if (plist.values.empty()) // no parmtype_S elements available? { auto crc = check_verb_value(frame, expression, default_parmtype, vlist.values.at(i), ws); // use default one just constructed -- no checking if (crc != 0) rc = crc; // remember any error } else // some parmtype_S are available in plist.values vector -- use i-th parmtype_S, or last one if not enough) { auto crc = check_verb_value(frame, expression, plist.values.at(std::min(i, (int)(plist.values.size() - 1))), vlist.values.at(i), ws); if (crc != 0) rc = crc; // remember any error } } } } // ------------------- // check keyword parms // ------------------- if (!plist.no_check_keywords) { if (plist.keywords.size() == 0) { if (vlist.eval_kws.size() > 0) { count_error(); M_out_emsg1(L"check_verb_vlist() -- verb= %s %s expects no %s keywords, but %d was/were present") % verb_name(expression) % ws1 % ws2 % vlist.kw_ct; // unevaluated keyword count msgend_loc(vlist, expression); rc = -1; } } else { std::multiset<std::wstring> kw_done { }; // keywords allowed -- check each keyword that is present in vlist to see if associated value type is allowed -- also check for duplicate kws, etc. // ------------------------------------------------------------------------------------------------------------------------------------------------ for (const auto& elem : vlist.eval_kws) // look at each keyword in vlist { std::wstring kw_find_name { }; // name used to look up keywords in plist keyword list if (plist.no_check_keyword_names) // don't check keyword names? kw_find_name = L""; // use dummy substitute name for entry in kw map else kw_find_name = elem.first; // look for this keyword name from parms vlist auto key_pct = plist.keywords.count(kw_find_name); // find "*" or this vlist keyword in list of allowed keywords for this plist if (key_pct == 0) // see if this keyword is not in the list of expected keywords for this vlist { count_error(); M_out_emsg1(L"check_verb_vlist() -- verb= %s %s -- unexpected %s keyword=%s: present") % verb_name(expression) % ws1 % ws2 % elem.first; msg_kw_loc(elem.second); msgend_loc(vlist, expression); rc = -1; } else if (key_pct == 1) // this keyword or "*"found in list of expected keywords { // check for duplicate keywords (or too many) -- (missing kw, or too few) is checked later auto kw_parmtype = plist.keywords.at(kw_find_name); // get parmtype_S for this keyword in vlist, or "*" (if not validating keyword names) auto kw_max_ct = kw_parmtype.kw_max_ct; // maximum allowed occurrences of this keyword auto kw_vct = vlist.eval_kws.count(elem.first); // get number of occurrences of this keyword in vlist (use real kw name -- assume supplied plist allows 0-nnnn occurrences, if names are not being checked) M__(M_out(L"check_verb_vlist() -- ++++++++++++++++++++++++++++++++++ find_name = %S located kw parmtype -- no_eval_ident=%S no_eval_expression=%S no_eval_vlist=%S no_eval_ref=%S verbless=%S") % kw_find_name % M_bool_cstr(kw_parmtype.eval.no_eval_ident) % M_bool_cstr(kw_parmtype.eval.no_eval_expression) % M_bool_cstr(kw_parmtype.eval.no_eval_vlist)% M_bool_cstr(kw_parmtype.eval.no_eval_ref) % M_bool_cstr(kw_parmtype.eval.verbless) ; ) if ( (kw_vct > kw_max_ct) && (kw_done.find(elem.first) == kw_done.end()) ) { if (kw_max_ct == 1) { count_error(); M_out_emsg1(L"check_verb_vlist() -- verb= %s %s -- %s keyword=%s: present %d times -- only once is allowed") % verb_name(expression) % ws1 % ws2 % elem.first % kw_vct; msg_kw_loc(elem.second); msgend_loc(vlist, expression); rc = -1; } else { count_error(); M_out_emsg1(L"check_verb_vlist() -- verb= %s %s -- %s keyword=%s: present %d times -- maximum of %d times is allowed") % verb_name(expression) % ws1 % ws2 % elem.first % kw_vct % kw_max_ct; msg_kw_loc(elem.second); msgend_loc(vlist, expression); M_out_emsgz(); rc = -1; } } kw_done.insert(elem.first); //mark this one done, so as not to complain multiple times // check located parmtype_S for this verb against actual value for keyword that is present in verb parms auto crc = check_verb_value(frame, expression, kw_parmtype, elem.second, ws1 + ws2 + L" keyword=" + elem.first + L":"); if (crc != 0) rc = crc; } else // should not occur { M_out_emsg1(L"check_verb_vlist() -- verb= %S %S -- more than one entry in %S expected keyword list -- keyword=%S verb=%S") % verb_name(expression) % ws1 % ws2 % elem.first % verb_name(expression); msgend_loc(vlist, expression); M_throw_v( "check_verb_vlist() -- verb= %s %s -- more than one entry in %s expected keyword list -- keyword=%s verb=%s") % out_ws(verb_name(expression)) % out_ws(ws1) % out_ws(ws2) % out_ws(elem.first) % out_ws(verb_name(expression)) )); return -2; // should not get here } } // Look at each keyword in plist to see if there are any required ones missing from vlist, or if there are too few occurrences (too many has already been checked) // --------------------------------------------------------------------------------------------------------------------------------------------------------------- if ( !(plist.no_check_keyword_names) ) // bypass missing required kw check if kw names are not being checked { for (const auto& elem : (plist.keywords)) // look at each exepected keyword for this plist { auto min_ct = elem.second.kw_min_ct; M__(M_out(L"check_verb_vlist() -- min_ct = %d") % min_ct;) if (min_ct > 0) // see if this keyword is required { auto kw_ct = vlist.eval_kws.count(elem.first); // actual number of occurrences for this keyword if ( (kw_ct == 0) && (min_ct >= 1) ) // see if this requried keyword is missing in passed-in vlist keyword parms { M__(M_out(L"check_verb_vlist() -- missing required kws");) count_error(); M_out_emsg1(L"check_verb_vlist() -- verb= %s %s -- missing required %s keyword=%s:") % verb_name(expression) % ws1 % ws2 % elem.first; msgend_loc(vlist, expression); M_out_emsgz(); rc = -1; } else if (kw_ct < min_ct) { M__(M_out(L"check_verb_vlist() -- not enough kws");) count_error(); M_out_emsg1(L"check_verb_vlist() -- verb= %s %s -- %s keyword=%s: is present only %d time(s) -- minimum required times is %d") % verb_name(expression) % ws1 % ws2 % elem.first % kw_ct % min_ct; msgend_loc(vlist, expression); rc = -1; } } } } // --------------------------------------------------------------------------------------------------------------------------------------------- // check for conflicting keywords (if there are any conflict sets for this plist) -- assume plist has no conflict sets, if not checking kw names // --------------------------------------------------------------------------------------------------------------------------------------------- // // - for each conflict set, either 0 or 1 of the keywords in the conflict set can be present in the vlist // if (plist.conflicts.size() > 0) { // outer loop to look at each conflict set for this plist for (const auto& conflict_set : plist.conflicts) { int conflict_ct {0}; // number of conflicting keywords found in this conflict set std::wstring conflict_str { }; // list of conflicting keywords found in this set (for error message) // inner loop to count how many keywords in vlist are in this set (should be 0 or 1) for (const auto& vl_kw_name : vlist.eval_kws) { if (conflict_set.count(vl_kw_name.first) > 0) // this keyword is in conflict set ? { conflict_ct++; conflict_str += L" " + vl_kw_name.first + L": "; } } // complain if more than one keyword in conflict list was present in this vlist if (conflict_ct > 1) { count_error(); M_out_emsg1(L"check_verb_vlist() -- verb= %s %s -- conflicting %s keywords found -- %s") % verb_name(expression) % ws1 % ws2 % conflict_str; msgend_loc(vlist, expression); rc = -1; } } // loop to ckeck each conflict set for this plist } // keyword conflict sets present for this plist // --------------------------------------------------------------------------------------------------------------------------------------------- // check for multiple choice keywords (if there are any choice sets for this plist) -- assume plist has no choice sets, if not checking kw names // --------------------------------------------------------------------------------------------------------------------------------------------- // // - for each choice set, one of the keywords in the choice set must be present in the vlist if (plist.choices.size() > 0) { // outer loop to look at each choice set for this plist for (const auto& choice_set : plist.choices) { int choice_ct {0}; // number of choice keywords found in this choice set // inner loop to count how many keywords in vlist are in this set (should be 1 or more) for (const auto& vl_kw_name : vlist.eval_kws) { if (choice_set.count(vl_kw_name.first) > 0) // this keyword is in choice set ? choice_ct++; } // complain if no keyword, or more than one keyword in the multiple choice set was found in the vlist if (choice_ct != 1) { // get string with keywords, one or more of which must be present std::wstring choice_str { }; // list of choice keywords found in this set (for error message) for (const auto cs_kw_name : choice_set) choice_str += L" " + cs_kw_name + L": "; // put out error message count_error(); if (choice_ct == 0) M_out_emsg1(L"check_verb_vlist() -- verb= %s %s -- one of the following %s keywords must be present -- %s") % verb_name(expression) % ws1 % ws2 % choice_str; else M_out_emsg1(L"check_verb_vlist() -- verb= %s %s -- only one of the following %s keywords can be present -- %s") % verb_name(expression) % ws1 % ws2 % choice_str; msgend_loc(vlist, expression); rc = -1; } } // loop to ckeck each choice set for this plist } // keyword choice sets present for this plist // -------------------------------------------------------------------------------------------------------------------------------------------- // check for required matching keywords (if there are any match sets for this plist) -- assume no match sets in plist, if not checking kw names // -------------------------------------------------------------------------------------------------------------------------------------------- // // - either none or all of the keywords in each match set must be present in the vlist // - all keywords in each match set must be occur the same number of times in the vlist // if (plist.matches.size() > 0) { // outer loop to look at each match set in list for (const auto& match_set : plist.matches) { std::wstring found_str { }; // printable list of matching keywords found in this set (for error message) std::wstring required_str { }; // printable list of keywords required in match set std::vector<uint64_t> kw_counts { }; // list of actual keyword occurrence counts in vlist std::vector<std::wstring> kw_names { }; // names of keywords found in vlist uint64_t found_ct { 0 }; // number of keywords in match set that are present in vlist uint64_t required_ct { 0 }; // total number of keywords present in match set // inner loop to check each keyword in the match set (compute required_ct = number of kws in match set, found_ct = number of these KWs in vlist) for (const auto& kw_name : match_set) { required_ct ++; // increment number of keywords present required_str += L" " + kw_name + L": "; // add this keyword to the required string auto kw_count = vlist.eval_kws.count(kw_name); // number of times this keyword is present in vlist if (kw_count > 0) // is this keyword in vlist ? { found_ct++; // increment count of keywords present found_str += L" " + kw_name + L": "; // add this keyword to the found string kw_names .push_back(kw_name); // save this kw name in vector kw_counts.push_back(kw_count); // save this kw count in vector } } // if at least one keyword in the match set was present, need to check counts, etc. (all keywords missing is OK, as far as this check goes) if (found_ct > 0) { if (found_ct != required_ct) // see if any keywords in the match set are missing { M__(M_out(L"check_verb_vlist() -- match kws -- some kws missing");) count_error(); M_out_emsg1(L"check_verb_vlist() -- verb= %s %s -- %s keyword match set=(%s) -- only some of these keywords are present: (%s)") % verb_name(expression) % ws1 % ws2 % required_str % found_str; msgend_loc(vlist, expression); rc = -1; } else // right number of keywords (all) are present { auto minmax_ct = std::minmax_element(kw_counts.cbegin(), kw_counts.cend()); M__(M_out(L"check_verb_vlist() -- *minmax_ct.first = %d, *minmax_ct.second = %d") % *(minmax_ct.first) % *(minmax_ct.second); ) if ( *(minmax_ct.first) != *(minmax_ct.second) ) // do keywords appear a different number of times in the vlist? { // build string with varying counts, for error message -- kw_counts and kw_names should be the same size == found_ct == required_count std::wstring counts_str { }; for (auto i = 0; i < found_ct; i++) counts_str += L" " + kw_names.at(i) + L":" + std::to_wstring(kw_counts.at(i)) + L"x "; M__(M_out(L"check_verb_vlist() -- match kws -- different occurrences");) count_error(); M_out_emsg1(L"check_verb_vlist() -- verb= %s %s -- %s keyword match set=(%s) -- differing number of occurrences: (%s) -- number of occurrences must all be the same") % verb_name(expression) % ws1 % ws2 % required_str % counts_str; msgend_loc(vlist, expression); rc = -1; } } } // at least one keyword in match set was present in vlist } // loop to check each match set for this plist } // keyword match sets present for this plist } // keywords allowed } // no check keywords return rc; } M_endf ////_________________________________________________________________________________________________________________________________________________________________ ////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ /////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ ////""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" //// //// //// check_verb_parms() -- complain and return error, if parms in expression don't match what is expected in the verbdef_S structure //// //// ////_________________________________________________________________________________________________________________________________________________________________ ////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ /////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ ////""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" // this function checks to see if they match those required by a specific verbdef_S static int check_verb_parms(frame_S& frame, const e_expression_S& expression, const verbdef_S& verbdef) try { int rc {0}; // check both left and right vlists vs plist requirements in passed-in expression auto crc1 = check_verb_vlist(frame, expression, verbdef.lparms, expression.lparms, L"", L"left-side" ); auto crc2 = check_verb_vlist(frame, expression, verbdef.rparms, expression.rparms, L"", L"right-side"); if (crc1 != 0) rc = crc1; if (crc2 != 0) rc = crc2; // global check for parms_some_required -- at least one positional parm on one side or the other if (verbdef.parms_some_required) { if ( (expression.lparms.value_ct == 0) && (expression.rparms.value_ct == 0) ) // both sides have no positional parms ? { count_error(); M_out_emsg1(L"check_verb_parms() -- verb= %s expects at least one positional parm on one side or the other, but none were present at all") % verb_name(expression); msgend_loc(expression); rc = -1; } } // global check for parms_same_number -- number of positional parms on both left and right sides must be the same if (verbdef.parms_some_required) { if (expression.lparms.value_ct != expression.rparms.value_ct) // both sides have same number of positional parms ? { count_error(); M_out_emsg1(L"check_verb_parms() -- verb= %s expects the same number of positional parms on each side -- left-side has %d, right-side has %d") % verb_name(expression) % expression.lparms.value_ct % expression.rparms.value_ct; msgend_loc(expression); rc = -1; } } // global check for parms_not_both_sides -- cannot have positional or *keyword* parms on both sides if (verbdef.parms_not_both_sides) { if ( ((expression.lparms.value_ct + expression.lparms.kw_ct) > 0) && ((expression.rparms.value_ct + expression.rparms.kw_ct) > 0) ) // both sides have positional or evaluated keyword parms ? { count_error(); M_out_emsg1(L"check_verb_parms() -- verb= %s does not expect positional or keyword parms on both left and right sides, but both left-side and right-side parms were present") % verb_name(expression); msgend_loc(expression); rc = -1; } } // global check for parms_left_xor_right -- positional parms must exist on exactly one side (not both sides or neither side) if (verbdef.parms_left_xor_right) { if ( (expression.lparms.value_ct == 0) && (expression.rparms.value_ct == 0) ) // both sides have no positional parms ? { count_error(); M_out_emsg1(L"check_verb_parms() -- verb= %s expects positional parms on one side or the other, but none were present on either side") % verb_name(expression); msgend_loc(expression); rc = -1; } else if ( (expression.lparms.value_ct > 0) && (expression.rparms.value_ct > 0) ) // positional parms on both sides ? { count_error(); M_out_emsg1(L"check_verb_parms() -- verb= %s expects positional parms on only one side or the other, but parms were present on both sides") % verb_name(expression); msgend_loc(expression); rc = -1; } } // global check for parms_same_type - make sure all parms in both left-side and right_side positional parm lists are the same type if (verbdef.parms_same_type) { if ( (expression.rparms.val_mixed) || (expression.lparms.val_mixed) || ( ( (expression.lparms.value_ct > 0) && (expression.rparms.value_ct > 0) ) && ( (expression.lparms.val_unit != expression.rparms.val_unit ) || (expression.lparms.val_boolean != expression.rparms.val_boolean ) || (expression.lparms.val_int8 != expression.rparms.val_int8 ) || (expression.lparms.val_int16 != expression.rparms.val_int16 ) || (expression.lparms.val_int32 != expression.rparms.val_int32 ) || (expression.lparms.val_int64 != expression.rparms.val_int64 ) || (expression.lparms.val_uint8 != expression.rparms.val_uint8 ) || (expression.lparms.val_uint16 != expression.rparms.val_uint16 ) || (expression.lparms.val_uint32 != expression.rparms.val_uint32 ) || (expression.lparms.val_uint64 != expression.rparms.val_uint64 ) || (expression.lparms.val_float32 != expression.rparms.val_float32 ) || (expression.lparms.val_float64 != expression.rparms.val_float64 ) || (expression.lparms.val_string != expression.rparms.val_string ) || (expression.lparms.val_identifier != expression.rparms.val_identifier ) || (expression.lparms.val_vlist != expression.rparms.val_vlist ) || (expression.lparms.val_expression != expression.rparms.val_expression ) || (expression.lparms.val_block != expression.rparms.val_block ) || (expression.lparms.val_verbset != expression.rparms.val_verbset ) ) ) ) { count_error(); M_out_emsg1(L"check_verb_parms() -- verb= %s expects all positional parms (both left-side and right-side) to be the same type, but more than one type was present") % verb_name(expression); msgend_loc(expression); rc = -1; } } return rc; } M_endf ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ //▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ //▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ //▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ //▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ //▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ //▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ //▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ //▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //╔══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════ //║╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳ //║╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳ //║╳╳╳╳╔═════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════ //║╳╳╳╳║ //║╳╳╳╳║ //║╳╳╳╳║ //║╳╳╳╳║ FFFFFFFFFF RRRRRRRRR AA MM MM EEEEEEEEEE //║╳╳╳╳║ FFFFFFFFFF RRRRRRRRRR AAAA MMM MMM EEEEEEEEEE //║╳╳╳╳║ FF RR RR AA AA MMMM MMMM EE //║╳╳╳╳║ FF RR RR AA AA MM MMMM MM EE //║╳╳╳╳║ FFFFFFFF RRRRRRRRRR AA AA MM MM MM EEEEEEEE //║╳╳╳╳║ FFFFFFFF RRRRRRRRR AAAAAAAAAA MM MM EEEEEEEE //║╳╳╳╳║ FF RR RR AAAAAAAAAA MM MM EE //║╳╳╳╳║ FF RR RR AA AA MM MM EE //║╳╳╳╳║ FF RR RR AA AA MM MM EEEEEEEEEE //║╳╳╳╳║ FF RR RR AA AA MM MM EEEEEEEEEE //║╳╳╳╳║ //║╳╳╳╳║ //║╳╳╳╳║ //║╳╳╳╳╚═════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════ //║╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳ //║╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳ //╚══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════ ////_________________________________________________________________________________________________________________________________________________________________ ////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ /////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ ////""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" //// //// //// frame_cmdline_parms() -- special set up of (main) stack frame with cmdline parms //// //// ////_________________________________________________________________________________________________________________________________________________________________ ////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ /////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ ////""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" void frame_cmdline_parms(frame_S& frame, int argc, wchar_t *argv[]) try { // note: passed-in stack frame has already been set up with flags, pointers, environment, global envoronment, etc. (basic setup) setup_global_environ(); // initialize global environment before using it // add command line args to passed-in stack frame right-side positional parm vector (vlist will have no location data) // also add global constants with names ARG_C ARG_0 ARG_1 ARG_2 ARG_3 ... for (auto i = 0; i < argc; i++) { value_S parm_val = string_val(argv[i]); add_positional_value( frame.rparms, parm_val ); def_global_const( std::wstring { L"ARG_" } + std::to_wstring(i), parm_val ); } def_global_const( std::wstring { L"ARG_C" }, int64_val(argc) ); return; } M_endf ////_________________________________________________________________________________________________________________________________________________________________ ////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ /////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ ////""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" //// //// //// new_frame() -- allocate new stack frame, but don't anchor it anywhere //// //// ////_________________________________________________________________________________________________________________________________________________________________ ////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ /////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ ////""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" std::shared_ptr<frame_S> new_frame() try // caller needs to assume responsibility for new frame_S being allocated { // allocate new frame_S, holding onto it with a local shared pointer std::shared_ptr<frame_S> new_frame_sp { new frame_S { } }; // allocate new stack frame and anchor it locally M__(M_out(L"new_frame() called 1 -- new_frame_sp.use_count() = %d") % new_frame_sp.use_count();) // do basic (persistent) setup -- dynamic stack chain pointers will be set up when this stack frame is activated and placed on the stack new_frame_sp->self_wp = new_frame_sp; // set weak self-ptr for use_count() debugging and later shared_ptr initialization new_frame_sp->serial = ++static_N::frame_serial; // set unique serial number in new frame_S, for debugging new_frame_sp->env.sernum = -(new_frame_sp->serial); // also save negative value in imbedded environ_S, for debugging new_frame_sp->local_sf_p = new_frame_sp.get(); // set pointer to stack frame with local environment to this stack frame -- environment has local variables for this stack frame (can be replaced later for same_scope: verbs) new_frame_sp->search_sf_p = new_frame_sp.get(); // set pointer to stack frame with local environment to this stack frame -- starting point for identifier search new_frame_sp->environ_p = &(new_frame_sp->env); // set pointer to local environment -- can be replaced by ptr to shared environment by caller M__(M_out(L"new_frame() called 3 -- new_frame_sp.use_count() = %d") % new_frame_sp.use_count();) return new_frame_sp; } M_endf ////_________________________________________________________________________________________________________________________________________________________________ ////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ /////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ ////""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" //// //// //// add_new_frame() -- alocate new stack frame and add it to to top of stack //// //// ////_________________________________________________________________________________________________________________________________________________________________ ////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ /////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ ////""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" frame_S *add_new_frame() try { // allocate new frame_S -- anchor it locally for now std::shared_ptr<frame_S> new_frame_sp = new_frame(); M__(M_out(L"add_new_frame() called 1 -- new_frame_sp.use_count() = %d") % new_frame_sp.use_count();) // add this stack frame to the top of the stack (void)add_frame(new_frame_sp); M__(M_out(L"add_new_frame() called 3 -- new_frame_sp.use_count() = %d") % new_frame_sp.use_count();) return new_frame_sp.get(); } M_endf ////_________________________________________________________________________________________________________________________________________________________________ ////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ /////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ ////""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" //// //// //// add_frame() -- add passed-in stack frame to to top of stack //// (stack pointer chain will assume ownership of this stack frame) //// //// //// sets: //// //// - parent and child SF pointers //// - main SF ptr //// //// does not set: (caller must set) //// //// - shared ptr to upward scope //// - verb main SF pointer //// - persistent SF ptr //// ////_________________________________________________________________________________________________________________________________________________________________ ////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ /////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ ////""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" frame_S *add_frame(const std::shared_ptr<frame_S>& frame_sp) try { // save away pointer to current newest stack frame (called "old frame" here) -- will go out of scope when this routine returns std::shared_ptr<frame_S> old_frame_sp { static_N::newest_frame_sp }; // hold onto current newest stack frame until back chain shared ptr is set in new stack frems // anchor new stack frame in stck frame queue head -- this will be thte owning pointer for the new stack frame static_N::newest_frame_sp = frame_sp; // (!!!!!!!!!! owning pointer !!!!!!!!!!!!!) this will hold onto new stack frame after add_frame() returns // fix up various pointers in new frame_S being added to top of stack -- no need to do anything fi adding main SF // ------------------------------------------------------------------ if (old_frame_sp.use_count() > 0) // are we adding 1st stack frame? { // stack was not empty -- adding regular/nested (not main) stack frame frame_sp->parent_sp = old_frame_sp; // set parent pointer in new stack frame (!!!!!!!!!!!!!!!!!!!! owning pointer !!!!!!!!!!!!!!!!!!!!!!) old_frame_sp->child_p = frame_sp.get(); // set new frame_S as old frame's child (non-owning pointer) } // maintain frame depth counter, etc. static_N::frame_depth++; // maintain frame depth counter static_N::frame_max_depth = std::max(static_N::frame_depth, static_N::frame_max_depth); return frame_sp.get(); // return pointer to newly-added stack frame } M_endf ////_________________________________________________________________________________________________________________________________________________________________ ////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ /////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ ////""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" //// //// //// remove_frame() -- remove newest stack frame from top of stack (this will cause stack frame be freed up, unless caller is holding onto a shared pointer to it) //// //// ////_________________________________________________________________________________________________________________________________________________________________ ////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ /////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ ////""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" void remove_frame() try { std::shared_ptr<frame_S> removed_frame_sp { static_N::newest_frame_sp } ; // shared ptr to hold onto stack frame being removed std::shared_ptr<frame_S> kept_frame_sp { removed_frame_sp->parent_sp } ; // shared ptr to hold onto stack frame being kept (2nd oldest) -- may be empty ?????? M__(M_out(L"remove_frame() -- called: removed_frame_p = %p kept_frame_p = %p") % removed_frame_sp.get() % kept_frame_sp.get();) // kept_frame_sp->verb_eval_ct += removed_frame_sp->verb_eval_ct; // add removed frame's verb count to kept's (statistical counters) // remove newest stack frame from top of stack (leave any scoping pointers alone -- these may hold onto removed stack frame in case something points to it directly or indirectly) if (kept_frame_sp.use_count() > 0) // is there a kept stack frame (i.e. removing main stack frame this time) kept_frame_sp->child_p = nullptr; // kept stack frame is now childless removed_frame_sp->parent_sp.reset(); // get rid of removed stack frame's parent pointer (kept frame will not go away, since this routine still holds a shared pointer for it) static_N::newest_frame_sp = kept_frame_sp; // update newest stack frame pointer (this will hold onto newest stack (if any are left on stack) frame after this routine returns) static_N::frame_depth--; // maintain frame depth counter return; } M_endf ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ //▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ //▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ //▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ //▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ //▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ //▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ //▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ //▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //╔══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════ //║╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳ //║╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳ //║╳╳╳╳╔═════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════ //║╳╳╳╳║ //║╳╳╳╳║ //║╳╳╳╳║ //║╳╳╳╳║ BBBBBBBBB LL OOOOOOOO CCCCCCCC KK KK //║╳╳╳╳║ BBBBBBBBBB LL OOOOOOOOOO CCCCCCCCCC KK KK //║╳╳╳╳║ BB BB LL OO OO CC CC KK KK //║╳╳╳╳║ BB BB LL OO OO CC KK KK //║╳╳╳╳║ BBBBBBBBB LL OO OO CC KKKKKK //║╳╳╳╳║ BBBBBBBBB LL OO OO CC KKKKKK //║╳╳╳╳║ BB BB LL OO OO CC KK KK //║╳╳╳╳║ BB BB LL OO OO CC CC KK KK //║╳╳╳╳║ BBBBBBBBBB LLLLLLLLLL OOOOOOOOOO CCCCCCCCCC KK KK //║╳╳╳╳║ BBBBBBBBB LLLLLLLLLL OOOOOOOO CCCCCCCC KK KK //║╳╳╳╳║ //║╳╳╳╳║ //║╳╳╳╳║ //║╳╳╳╳╚═════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════ //║╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳ //║╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳ //╚══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════ ////_________________________________________________________________________________________________________________________________________________________________ ////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ /////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ ////""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" //// //// //// eval_frame_block() -- add new frame_S to stack for this (non-verb) frameblock, and run passed-in block with that frame_S using passed-in vlists as parms //// //// ////_________________________________________________________________________________________________________________________________________________________________ ////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ /////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ ////""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" int eval_frame_block(frame_S& parent_frame, const vlist_S& left_vlist, const vlist_S& right_vlist, const block_S& block, results_S& results) try { // add new stack frame to the active frame_S queue frame_S *new_frame_p = add_new_frame(); new_frame_p->persist_sf_p = new_frame_p->parent_sp->persist_sf_p; // copy parent frame's persistent SF pointer into new SF new_frame_p->verbmain_sf_p = new_frame_p->parent_sp->verbmain_sf_p; // copy parent frame's verb main SF pointer into new SF // upward scope for a frameblock frame_S is always starts at parent stack frame -- scoping is always dynall-type (both dynamic and lexical) new_frame_p->is_frameblock = true; // indicate this stack frame was created by frameblock evaluation #ifdef M_EXPOSE_SUPPORT new_frame_p->dynall_scope = true; // frameblocks always have unrestricted dynamic (lexical, effectively) scope upwards to parent #endif new_frame_p->scope_sp = std::shared_ptr<frame_S> { parent_frame.self_wp }; // initialize shared ptr from weak self-ptr in parent frame_S new_frame_p->env.is_frameblock = true; // also flag embeded environment as belonging to a frameblock (not verb) // set up frameblock invocation parms in new stack frame new_frame_p->lparms = left_vlist; new_frame_p->rparms = right_vlist; // run frameblock's block under new stack frame -- remove frame_S when done results_S frameblock_results {}; auto erc = eval_block(*new_frame_p, block, frameblock_results); remove_frame(); // remove new stack frame from stack if (erc != 0) { results = error_results(); // results = error return erc; // return with error r/c } // handle @QUIT special results -- percolate any others that get percolated here if (frameblock_results.quit_flag) { frameblock_results.return_flag = false; // consume the @QUIT frameblock_results.special_results = false; results = frameblock_results; // pass back @QUIT results -- special results are consumed return 0; } // pass back results (including special results other than @QUIT) from block evaluation results = frameblock_results; return 0; } M_endf ////_________________________________________________________________________________________________________________________________________________________________ ////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ /////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ ////""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" //// //// //// eval_verbinit_block() -- add new frame_S to stack for this verb-block, and run passed-in block with that new stack frame, using vlists in expression as the verb-block parms //// //// ////_________________________________________________________________________________________________________________________________________________________________ ////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ /////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ ////""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" // note: proper verbdef_S from the overload set has already been picked and passed to this funcion int eval_verbinit_block(const verbdef_S& verbdef, results_S& results) try { M__(M_out(L"eval_verbinit_block() -- called");) // --------------------------------------------------------------------------------------------------------------------------- // add new SF pointing to the verbdef_S persistent environment to active frame_S queue, and setup upward scope pointers, etc. // --------------------------------------------------------------------------------------------------------------------------- frame_S *persist_frame_p = add_new_frame(); persist_frame_p->environ_p = verbdef.persist_env_sp.get(); // point new persistent SF to environ_S of verbdef_S's persistent environment persist_frame_p->is_persistent = true; // mark new SF as persistent env persist_frame_p->persist_sf_p = persist_frame_p; // persistenf SF ptr points to self persist_frame_p->local_sf_p = nullptr; // don't allow non-static variable definitions in the init: block // no verb main SF pointer in init SF -- leave search_s_p pointing to persistent_sf // set up for dynamic scope to parent SF #ifdef M_EXPOSE_SUPPORT persist_frame_p->dynall_scope = true; #elseif persist_frame_p->dynamic_scope = true; #endif persist_frame_p->scope_sp = std::shared_ptr<frame_S> { persist_frame_p->parent_sp->self_wp }; // initialize scope ptr from weak self-ptr in parent frame_S -- upward scope starts at parent on call stack, for dynamic or dynall scoping M__(M_out(L"eval_verbinit_block() -- SF setup done");) // ----------------------------------------------------------------------------------------------- // run verb's init block in the new/shared stack frame(s) -- remove new frame_S (if any) when done // ----------------------------------------------------------------------------------------------- M__(M_out(L"eval_verbinit_block() -- calling eval_block block use count = %d") % verbdef.init_block_sp.use_count() ;) results_S block_results {}; auto erc = eval_block(*persist_frame_p, *(verbdef.init_block_sp), block_results); // remove the stack frame obtained earlier // --------------------------------------- remove_frame(); // remove persistent SF from stack -- should go away, but persistent environment should stay around due to shared ptr in verbdef_S // handle any errors from verb block evaluation // -------------------------------------------- if (erc != 0) { results = error_results(); // results = error return erc; // return with error r/c } // handle any special results -- expect @END, @THROW, @XCTL, @GOTO longjmp:, and @RETURN -- do not expect uncaught @LEAVE, @GOTO, @CONTINUE, @BREAK, @QUIT, etc. if (block_results.special_results) { if (block_results.return_flag) // @RETURN is expected -- needs to be consumed here { block_results.return_flag = false; // consume the @RETURN block_results.special_results = false; results = unit_results(); // ignore @RETURN value -- use substitute UNIT value } else if (block_results.end_flag) // @END is expected { results = block_results; // percolate @END results } else if (block_results.throw_flag) // @THROW is expected { results = block_results; // percolate @THROW results } else if (block_results.skip_flag) // @SKIPTO is expected { results = block_results; // percolate @SKIPTO results } else if (block_results.lgoto_flag) // @GOTO longjmp: is expected { results = block_results; // percolate @GOTO longjmp: results } else // unexpected special results { if (block_results.goto_flag) M_out_emsg(L"User-defined verb (\"%S\") init: block evaluation ended by unconsumed @GOTO «%S»") % verbdef.info % block_results.str; // ?????? long @GOTO not allowed ????? -- need to add config flag ???? else if (block_results.xctl_flag) M_out_emsg(L"User-defined verb (\"%S\") init: block evaluation ended by unconsumed @XCTL «%S»") % verbdef.info % block_results.str; else if (block_results.leave_flag) M_out_emsg(L"User-defined verb (\"%S\") init: block evaluation ended by unconsumed @LEAVE «%S»") % verbdef.info % block_results.str; else if (block_results.break_flag) M_out_emsg(L"User-defined verb (\"%S\") init: block evaluation ended by unconsumed @BREAK") % verbdef.info; else if (block_results.continue_flag) M_out_emsg(L"User-defined verb (\"%S\") init: block evaluation ended by unconsumed @CONTINUE") % verbdef.info; else if (block_results.quit_flag) M_out_emsg(L"User-defined verb (\"%S\") init: block evaluation ended by unconsumed @QUIT") % verbdef.info; else if (block_results.error) M_out_emsg(L"User-defined verb (\"%S\") init: block evaluation ended by error") % verbdef.info; else M_out_emsg(L"User-defined verb (\"%S\") init: block evaluation ended by unexpected special results") % verbdef.info; count_error(); results = error_results(); // error results return -1; // return with error } } else // block not ended by @RETURN etc. - return value is not set { results = unit_results(); // ignore normal block results -- pass back unit value instead } return 0; // return normally -- results have already been passed-back } M_endf ////_________________________________________________________________________________________________________________________________________________________________ ////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ /////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ ////""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" //// //// //// eval_verb_block() -- add new frame_S to stack for this verb-block, and run passed-in block with that new stack frame, using vlists in expression as the verb-block parms //// //// ////_________________________________________________________________________________________________________________________________________________________________ ////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ /////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ ////""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" //////////////////////////////////////////////////////////////////////////////////////////////////////////// // local set_parm_vars() helper function //////////////////////////////////////////////////////////////////////////////////////////////////////////// static int set_parm_vars(frame_S *frame_p, e_expression_S expression, const verbdef_S& verbdef, const argvar_S& argvar, const vlist_S vlist) try { // ---------------------------------- // process list of positional argvars (right-side or left-side) // ---------------------------------- // note: unless sharing a SF with caller, *frame_p should be empty, and there should be no duplicates in the variable names list, so def_local_var() should not fail int argvar_n { 0 }; // parameter number def_parm_S def_parm { }; // local parm for def_parms_var() def_parm.unshare = true; // make sure parm values are unshared for (auto elem : argvar.pos) // elem is a std::wstring = arg variable name { int drc { 0 }; // return code from def_local_var() // see if weak alias processing or regular parm passing is required for this argvar if ( verbdef.by_alias_ok && (elem.front() == L'_') ) // by_alias: and this argvar starts with underscore char? { // get parm using weak alias -- error if this parm is not present in vlist, or is not an identifier // ------------------------------------------------------------------------------------------------ M__(M_out(L"set_parm_vars() -- get parm %S by_alias:") % elem;) // error, if not enough values in passed-in vlist to create alias for this argvar if (argvar_n >= vlist.value_ct) { count_error(); M_out_emsg1(L"set_parm_vars() -- only %d parms passsed in -- cannot make weak alias for argvar %d = \"%S\"") % vlist.value_ct % argvar_n % elem; msgend_loc(expression); return -1; } // error, if not matching parm was not passed in as an identifier that can be aliased if (vlist.values.at(argvar_n).ty != type_E::identifier) { count_error(); M_out_emsg1(L"set_parm_vars() -- passed-in parm %d is not an identifier -- cannot make weak alias for argvar = \"%S\"") % argvar_n % elem; msgend_loc(expression); return -1; } // create weak alias in parms frame using n-th argvar and passed-in identifier drc = def_parms_weak_alias(*frame_p, vlist.values.at(argvar_n).string, elem, def_parm_S { }); // return immediately with error, if def_parms_weak_alias() failed if (drc != 0) // did def_local_var() fail? -- not expected { count_error(); M_out_emsg1(L"set_parm_vars() -- when setting positional argvar %d = \"%S\" as a weak alias -- error from def_parms_weak_alias()") % argvar_n % elem; msgend_loc(expression); return -1; // r/c = error } } else { // regular parm passing -- set local variable to value passed in this parm // ----------------------------------------------------------------------- if (argvar_n >= vlist.value_ct) // this variable is past end of parms for this invocation drc = def_parms_var(*frame_p, elem, unit_val(), def_parm); // define parm variable with unit value -- make sure values are unshared else drc = def_parms_var(*frame_p, elem, vlist.values.at(argvar_n), def_parm); // define parm variable with value of passed-in n-th positional parm -- make sure values are unshared // return immediately with error, if def_parms_var() failed if (drc != 0) // did def_local_var() fail? -- not expected { count_error(); M_out_emsg1(L"set_parm_vars() -- when setting positional argvar %d = \"%S\" -- error from def_local_var()") % argvar_n % elem; msgend_loc(expression); return -1; // r/c = error } } // continue loop to process next argvar argvar_n++; // advance to next value in positional argvar list } // ------------------------------- // process list of keyword argvars (right-side or left-side) // ------------------------------- std::multiset<std::wstring> lkw_names { }; // multimap with keywords processed so far for (auto elem : argvar.key) // elem.first is a std::wstring = keyword name -- elem.second is a std::wstring = variable name { lkw_names.insert(elem.first); // add this keyword name to combined list of keywords seen so far auto kwvar_ct = lkw_names.count(elem.first); // get count of how many times this keyword name has been seen so far in argvar_S auto kwval_ct = vlist.eval_kws.count(elem.first); // get count of how many times this keyword name is seen in the invocation parms M__(M_out(L"set_parm_vars() -- left-side : kw_name = «%S» kwvar_ct=%d kwval_ct=%d") % elem.first % kwvar_ct % kwval_ct;) int drc { }; // return code from def_local_var // see if weak alias processing or regular parm passing is required for this argvar if ( verbdef.by_alias_ok && (elem.second.front() == L'_') ) // by_alias: and this argvar starts with underscore char? { // get parm using weak alias -- error if this parm is not present in vlist, or is not an identifier // ------------------------------------------------------------------------------------------------ M__(M_out(L"set_parm_vars() -- get parm %S by_alias:") % elem.second;) // error, if not enough values in passed-in vlist to create alias for this argvar if (kwvar_ct > kwval_ct) { count_error(); M_out_emsg1(L"set_parm_vars() -- only %d parms passsed in -- cannot make weak alias for argvar %d = \"%S\"") % kwval_ct % kwvar_ct % elem.second; msgend_loc(expression); return -1; } // error, if not matching parm was not passed in as an identifier that can be aliased if (multimap_at(vlist.eval_kws, elem.first, kwvar_ct-1).ty != type_E::identifier) { count_error(); M_out_emsg1(L"set_parm_vars() -- passed-in parm %d is not an identifier -- cannot make weak alias for argvar = \"%S\"") % (kwvar_ct - 1) % elem.second; msgend_loc(expression); return -1; } // create weak alias in parms frame using n-th argvar and passed-in identifier drc = def_parms_weak_alias(*frame_p, multimap_at(vlist.eval_kws, elem.first, kwvar_ct-1).string, elem.second, def_parm_S { }); // return immediately with error, if def_parms_weak_alias() failed if (drc != 0) // did def_local_var() fail? -- not expected { count_error(); M_out_emsg1(L"set_parm_vars() -- when setting positional argvar %d = \"%S\" as a weak alias -- error from def_parms_weak_alias()") % (kwvar_ct - 1) % elem.second; msgend_loc(expression); return -1; // r/c = error } } else { // regular parm passing -- set local variable to value passed in this parm // ----------------------------------------------------------------------- if (kwvar_ct > kwval_ct) // this kw/variable pair is past end of kw/value pairs in invocation args drc = def_parms_var(*frame_p, elem.second, unit_val(), def_parm); // define local parm variable with unit value -- make sure values are unshared else drc = def_parms_var(*frame_p , elem.second , multimap_at(vlist.eval_kws, elem.first, kwvar_ct-1) // find value for n-th occurrence of this keyword in invocation keyword values multimap , def_parm ); // define local non-exposed variable with value of passed-in n-th positional arg -- make sure values are unshared // return immediately with error, if def_local_var() failed if (drc != 0) // did def_local_var() fail? -- not expected { count_error(); M_out_emsg1(L"set_parm_vars() -- keyword(%S) argvar -- error from def_local_var(,%S,)") % elem.first % elem.second; msgend_loc(expression); return -1; // r/c = error } } } // if no errors found, return normally return 0; } M_endf //////////////////////////////////////////////////////////////////////////////////////////////////////////// // main eval_verb_block() function //////////////////////////////////////////////////////////////////////////////////////////////////////////// // note: proper verbdef_S from the overload set has already been picked and passed to this funcion int eval_verb_block(frame_S& parent_frame, const e_expression_S& expression, const verbdef_S& verbdef, results_S& results) try { M__(M_out(L"eval_verb_block() -- called");) frame_S *eval_frame_p { nullptr }; // ================================================================================================================================================== // obtain new SF(s) or reuse current SF, depending on same_scope: option on the verb definition // ================================================================================================================================================== // figure out upward scope for this verb // ------------------------------------- std::shared_ptr<frame_S> scope_sp { }; // temporary scope shared pointer to be copied into persistent SF (if any) or main verb SF if (verbdef.lexical_scope) { // upward scope pointer for new stack frame is the captured upward scope when verb was defined (if it is still around -- close: option should keep this SF around for life of verb definition) if (verbdef.defining_scope_wp.expired()) // enclosing SF has gone away? { if (verbdef.scope_defaulted) // lexical_scope: not coded on verb definition -- use no_scope:, since enclosing scope has gone away { scope_sp.reset(); // no upward scope for this stack frame (verb must not rely on unbound variables) } else // error -- explicit lexical_scope and enclosing scope has disappeared (close: must not have been specified) { count_error(); M_out_emsg1(L"eval_verb_block() -- the enclosing scope from the time of verb definition no longer exists -- cannot invoke the lexically-scoped verb"); msgend_loc(expression); results = error_results(); // results = error return -1; // r/c = error } } else // enclosing SF still around -- set as upward scope { scope_sp = std::shared_ptr<frame_S> { verbdef.defining_scope_wp }; // start upward scope at stack frame that defined the verb, for lexical scoping } } else if (verbdef.no_scope) // verbdef has no_scope: option { scope_sp.reset(); // no upward scope for this stack frame (verb must not rely on unbound variables) } else // must be shared_scope: , dynamic_scope: -or- dynall_scope: option on verbdef { scope_sp = std::shared_ptr<frame_S> { parent_frame.self_wp }; // initialize shared ptr from weak self-ptr in parent frame_S -- upward scope starts at parent on call stack, for dynamic or dynall scoping } // see if this verbdef has a persistent environment (note: init:{} causes persistent env -- not allowed with shared_scope: ) // ------------------------------------------------ frame_S *persist_frame_p { nullptr }; // nullptr will be replaced by address of new persistent SF (if any) if (verbdef.persist_env_sp.get() != nullptr) { M__(M_out(L"eval_verb_block() -- has persistent environment");) // --------------------------------------------------------------------------------------------------------------------------- // add new SF pointing to the verbdef_S persistent environment to active frame_S queue, and setup upward scope pointers, etc. // --------------------------------------------------------------------------------------------------------------------------- persist_frame_p = add_new_frame(); persist_frame_p->environ_p = verbdef.persist_env_sp.get(); // point new persistent SF to environ_S of verbdef_S's persistent environment persist_frame_p->is_persistent = true; // mark new SF as persistent env persist_frame_p->persist_sf_p = persist_frame_p; // persistenf SF ptr points to self // copy over scope flags from verbdef_S into persistent SF frame_S, and save away scope shared ptr as computed earlier (note: same_scope verbs should not have persistent SF) persist_frame_p->dynamic_scope = verbdef.dynamic_scope; persist_frame_p->lexical_scope = verbdef.lexical_scope; #ifdef M_EXPOSE_SUPPORT persist_frame_p->dynall_scope = verbdef.dynall_scope; #endif persist_frame_p->no_scope = verbdef.no_scope; persist_frame_p->scope_sp = scope_sp; // set up scope in persistent SF based on verbdef scope: option // replace scope_sp computed above with a shared ptr to the persistenf SF -- this will be the upward scope for the 2nd SF for this verb std::shared_ptr<frame_S> temp_sp {persist_frame_p->self_wp}; // need to set local shared_ptr from weak self ptr (will soon go out of scope) scope_sp = temp_sp; // upward scope SF for main verb SF is this persistent SF (std::shared_ptr) } M__(M_out(L"eval_verb_block() -- setting up verb main SF");) // ------------------------------------------------------------------------------------------------------------------------ // obtain and setup 2nd or only (main) SF for this verb invocation -- chain it after the persistent SF (if any) just set up // ------------------------------------------------------------------------------------------------------------------------ // add a new stack frame to the active frame_S queue after the persistent SF (if any) just added (and do basic setup) frame_S *new_frame_p = add_new_frame(); // if persistent SF was obtained always mark 2nd SF as dynall scope, pointing upward to persistent SF (note same_scoep: not allowed with persistent SF) if (persist_frame_p != nullptr) { M__(M_out(L"eval_verb_block() -- verb main SF -- have persistent SF");) #ifdef M_EXPOSE_SUPPORT new_frame_p->dynall_scope = true; #else new_frame_p->dynamic_scope = true; #endif new_frame_p->persist_sf_p = persist_frame_p; // set persistent SF pointer in dynamic SF to persistent SF for this verb persist_frame_p->verbmain_sf_p = new_frame_p; // also set verb main SF pointer in persistent SF to the new verb main SF } else // no persistent SF was set up { M__(M_out(L"eval_verb_block() -- verb main SF -- have no persistent SF");) // set verb main SF scope flags from verbdef flags, as usual new_frame_p->dynamic_scope = verbdef.dynamic_scope; new_frame_p->lexical_scope = verbdef.lexical_scope; #ifdef M_EXPOSE_SUPPORT new_frame_p->dynall_scope = verbdef.dynall_scope; #endif new_frame_p->no_scope = verbdef.no_scope; new_frame_p->same_scope = verbdef.same_scope; } M__(M_out(L"eval_verb_block() -- verb main SF -- basic setup");) // do basic setup that doesn't depend on presence/absence of persistent SF -- note that add_new_frame() has already set up the local_sf_p and search_sf_p pointers in the new SF // ----------------------------------------------------------------------- new_frame_p->scope_sp = scope_sp; // scope sp = computed scope for this verb, -or- ptr to persistent SF if (new_frame_p->same_scope) // is new non-persistent SF for same_scope: verb (parms-only SF)? { new_frame_p->is_parmsonly = true; // flag new SF as parms-only SF new_frame_p->env.is_parmsonly = true; // also flag the imbedded environment as parms-only new_frame_p->verbmain_sf_p = parent_frame.verbmain_sf_p; // set verbmain SF pointer from parent SF new_frame_p->persist_sf_p = parent_frame.persist_sf_p; // set persistent SF pointer from parent SF new_frame_p->local_sf_p = parent_frame.local_sf_p; // set local SF pointer from parent SF // search SF pointer stays pointing to the new SF } else // not setting up parms-only SF for this verb (i.e. same_scope:) { new_frame_p->is_verbmain = true; // flag this frame_S as started by verb new_frame_p->env.is_verbmain = true; // flag imbedded environment as belonging to verb new_frame_p->verbmain_sf_p = new_frame_p; // set verb main SF pointer in dynamic SF to self // persistent SF ptr was set above, local SF and search SF pointers stay the same -- set by add_new_frame() } M__(M_out(L"eval_verb_block() -- SF setup done");) // -------------------------------------------------------- // set up vlists and argvars (if any) in evaluation frame_S // -------------------------------------------------------- // set up verbname and left/right vlists in new stack frame new_frame_p->verbname = expression.verb_name; new_frame_p->lparms = expression.lparms; new_frame_p->rparms = expression.rparms; // process left-side vlist and arg-list // ------------------------------------ auto src = set_parm_vars(new_frame_p, expression, verbdef, verbdef.lvars, expression.lparms); // do left side vlist and argvar list // return immediately with error, if set_parm_vars() failed if (src != 0) // did def_local_var() fail? -- not expected { count_error(); M_out_emsg1(L"eval_verb_block() -- set_parm_vars() failed for left side vlist/argvar list -- verb will not be executed"); msgend_loc(expression); results = error_results(); // results = error return -1; // r/c = error } // process right-side vlist and arg-list // ------------------------------------- src = set_parm_vars(new_frame_p, expression, verbdef, verbdef.rvars, expression.rparms); // do right side vlist and argvar list // return immediately with error, if set_parm_vars() failed if (src != 0) // did def_local_var() fail? -- not expected { count_error(); M_out_emsg1(L"eval_verb_block() -- set_parm_vars() failed for right side vlist/argvar list -- verb will not be executed"); msgend_loc(expression); results = error_results(); // results = error return -1; // r/c = error } // ------------------------------------------------------------------------------------------ // run verb's block in the new/shared stack frame(s) -- remove new frame_S (if any) when done // ------------------------------------------------------------------------------------------ results_S block_results {}; auto erc = eval_block(*new_frame_p, *(verbdef.verb_block_sp), block_results); // if not sharing caller's stack frame(s), remove the stack frames obtained earlier // -------------------------------------------------------------------------------- remove_frame(); // remove new dynamic frame from stack -- should go away if (verbdef.persist_env_sp.get() != nullptr) // does this verb have a persistent environmnent and persistend SF? remove_frame(); // remove new persistent frame from stack -- should stay around (because of shared ptr to it in the verbdef) // handle any errors from verb block evaluation // -------------------------------------------- if (erc != 0) { results = error_results(); // results = error return erc; // return with error r/c } // handle any special results -- expect @END, @THROW, @XCTL, @GOTO longjmp:, and @RETURN -- do not expect uncaught @LEAVE, @GOTO, @CONTINUE, @BREAK, @QUIT, etc. (unless percolating everything) // ------------------------------------------------------------------------------------------------------------------------------------------------------------- if (block_results.special_results) { if (verbdef.percolate_all) // is this (same_scope:) verb percolating everything ? { results = block_results; // don't consume anything (especially @RETURN) -- just percolate } // not percolating everything -- do normal verb special results handling (especially @RETURN) else if (block_results.return_flag) // @RETURN is expected -- needs to be consumed { block_results.return_flag = false; // consume the @RETURN block_results.special_results = false; results = block_results; // pass back value from @RETURN, with no special flags } else if (block_results.xctl_flag) // @XCTL is expected -- needs to be consumed as this verb returns, but not right here { M__(M_out(L"eval_verb_block() -- saw @XCTL results -- verbdef.is_builtin = %d") % ((int)(verbdef.is_builtin));) results = block_results; // percolate @XCTL results } else if (block_results.end_flag) // @END is expected { results = block_results; // percolate @END results } else if (block_results.throw_flag) // @THROW is expected { results = block_results; // percolate @THROW results } else if (block_results.skip_flag) // @SKIPTO is expected { results = block_results; // percolate @SKIPTO results } else if (block_results.lgoto_flag) // @GOTO longjmp: is expected { results = block_results; // percolate @GOTO longjmp: results } else // unexpected special results { if (block_results.goto_flag) M_out_emsg(L"User-defined verb (\"%S\") evaluation ended by unconsumed @GOTO «%s»") % verbdef.info % block_results.str; // ?????? long @GOTO not allowed ????? -or- longjump: option else if (block_results.leave_flag) M_out_emsg(L"User-defined verb (\"%S\") evaluation ended by unconsumed @LEAVE «%s»") % verbdef.info % block_results.str; else if (block_results.quit_flag) M_out_emsg(L"User-defined verb (\"%S\") evaluation ended by unconsumed @QUIT") % verbdef.info; else if (block_results.break_flag) M_out_emsg(L"User-defined verb (\"%S\") evaluation ended by unconsumed @BREAK") % verbdef.info; else if (block_results.continue_flag) M_out_emsg(L"User-defined verb (\"%S\") evaluation ended by unconsumed @CONTINUE") % verbdef.info; else if (block_results.error) M_out_emsg(L"User-defined verb (\"%S\") evaluation ended by error") % verbdef.info; else M_out_emsg(L"User-defined verb (\"%S\") evaluation ended by unexpected special results") % verbdef.info; count_error(); results = error_results(); // error results return -1; // return with error } } else // block not ended by @RETURN etc. - return value is not set { results = block_results; // pass back normal block results } return 0; // return normally -- results have already been passed-back } M_endf ////_________________________________________________________________________________________________________________________________________________________________ ////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ /////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ ////""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" //// //// //// eval_main_block() -- using pre-built main frame_S, run passed-in block (parms already set up for main frame_S) -- no results passed back, just r/c //// //// ////_________________________________________________________________________________________________________________________________________________________________ ////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ /////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ ////""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" int eval_main_block(frame_S& frame, const block_S& block, int& wmain_rc) try { // run block prebuilt main frame_S results_S mainblock_results {}; auto erc = eval_block(frame, block, mainblock_results); if (erc != 0) { wmain_rc = -1; return erc; } // handle any percolated special results from normal block evaluation of main block if (mainblock_results.special_results) { if (mainblock_results.end_flag) // @END flag is supposed to be percolated here for action { wmain_rc = mainblock_results.int32; // return code may have been set by "@END wmain_rc" verb M__(M_out(L"eval_main_block() returning -- wmain_rc = %d") % wmain_rc;) return 0; } // mainblock expects no unmatched @GOTOs, @LEAVEs, @CONTINUEs, @BREAKs, @RETURNs, @THROWs, @XCTLs, @QUITs, etc. -- (only @END is expected here) if (mainblock_results.goto_flag) { M_out_emsg(L"main block evaluation ended by unconsumed @GOTO \"%S\" -- apparently @GOTO target label was not found") % mainblock_results.str; count_error(); wmain_rc = -1; return -1; } if (mainblock_results.lgoto_flag) { M_out_emsg(L"main block evaluation ended by unconsumed @GOTO \"%S\" longjmp: -- apparently @GOTO longjmp: target label was not found") % mainblock_results.str; count_error(); wmain_rc = -1; return -1; } if (mainblock_results.return_flag) { M_out_emsg(L"main block evaluation ended by unconsumed @RETURN %S -- apparently @RETURN was issued in main block -- use @END instead") % str_value(mainblock_results); count_error(); wmain_rc = -1; return -1; } if (mainblock_results.xctl_flag) { M_out_emsg(L"main block evaluation ended by unconsumed @XCTL -- apparently @XCTL was issued in main block"); count_error(); wmain_rc = -1; return -1; } if (mainblock_results.quit_flag) { M_out_emsg(L"main block evaluation ended by unconsumed @QUIT -- apparently @QUIT was issued outside of any block passed to the @BLOCK verb -- use @END to end the main block"); count_error(); wmain_rc = -1; return -1; } if (mainblock_results.throw_flag) { M_out_emsg(L"main block evaluation ended by uncaught @THROW %S") % str_value(mainblock_results); count_error(); wmain_rc = -1; return -1; } if (mainblock_results.skip_flag) { M_out_emsg(L"main block evaluation ended by unconsumed @SKIPTO \"%S\"") % str_results_string(mainblock_results); count_error(); wmain_rc = -1; return -1; } if (mainblock_results.leave_flag) { M_out_emsg(L"main block evaluation ended by unconsumed @LEAVE \"%S\" -- apparently @LEAVE was issued outside of any block") % str_results_string(mainblock_results); count_error(); wmain_rc = -1; return -1; } if (mainblock_results.break_flag) { M_out_emsg(L"main block evaluation ended by unconsumed @BREAK -- apparently @BREAK was issued outside of any loop"); count_error(); wmain_rc = -1; return -1; } if (mainblock_results.continue_flag) { M_out_emsg(L"main block evaluation ended by unconsumed @CONTINUE -- apparently @CONTINUE was issued outside of any loop"); count_error(); wmain_rc = -1; return -1; } if (mainblock_results.error) { M_out_emsg(L"main block evaluation ended by error"); count_error(); wmain_rc = -1; return -1; } M_out_emsg(L"main block evaluation ended by unexpected special results"); count_error(); wmain_rc = -1; return -1; } wmain_rc = 0; // normal wmain_rc() -- nothing unusual return 0; // main block evaluation results are ignored } M_endf ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ //▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ //▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ //▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ //▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ //▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ //▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ //▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ //▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //╔══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════ //║╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳ //║╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳ //║╳╳╳╳╔═════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════ //║╳╳╳╳║ //║╳╳╳╳║ //║╳╳╳╳║ //║╳╳╳╳║ EEEEEEEEEE VV VV AA LL //║╳╳╳╳║ EEEEEEEEEE VV VV AAAA LL //║╳╳╳╳║ EE VV VV AA AA LL //║╳╳╳╳║ EE VV VV AA AA LL //║╳╳╳╳║ EEEEEEEE VV VV AA AA LL //║╳╳╳╳║ EEEEEEEE VV VV AAAAAAAAAA LL //║╳╳╳╳║ EE VV VV AAAAAAAAAA LL //║╳╳╳╳║ EE VV VV AA AA LL //║╳╳╳╳║ EEEEEEEEEE VVVV AA AA LLLLLLLLLL //║╳╳╳╳║ EEEEEEEEEE VV AA AA LLLLLLLLLL //║╳╳╳╳║ //║╳╳╳╳║ //║╳╳╳╳║ //║╳╳╳╳╚═════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════ //║╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳ //║╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳╳ //╚══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════ ////_________________________________________________________________________________________________________________________________________________________________ ////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ /////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ ////""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" //// //// //// eval_value() -- evaluate contents of an passed-in value -- value should be either identifier or expression //// -- passed-in value parm is replaced by the value (which can be another expression or variable -- no double evaluation -- they are left as-is) //// ////_________________________________________________________________________________________________________________________________________________________________ ////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ /////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ ////""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" // internal routine to call eval_value in a loop, as long as re_eval_expression_results flag is on // ----------------------------------------------------------------------------------------------- static int reeval_value(frame_S& frame, const value_S& value, results_S& results, const parmtype_S& eval_parmtype, bool debug = false) try { int loop_count {0}; int erc {0}; value_S in_value {value}; // loop to call eval_value() as required // ------------------------------------- do { erc = eval_value(frame, in_value, results, eval_parmtype, debug); if (erc != 0) return erc; // return immediately, if error if (results.re_eval_expression_results) in_value = results; // copy results over to input area for next call loop_count++; if ( debug && (loop_count > 1) ) { M__(M_out(L"reeval_value() -- loop count = %d") % loop_count;) } } while (results.re_eval_expression_results); return erc; } M_endf ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// int eval_value(frame_S& frame, const value_S& value, results_S& results, const parmtype_S& eval_parmtype, bool debug) try { int rc {0}; M__(display_value(results, L"eval_value() input results");) if (debug) { M__(M_out( L"*************************************** eval_value() -- called -- parmtype.no_eval_ident=%S parmtype.no_eval_expression=%S parmtype.no_eval_vlist=%S parmtype.no_eval_ref=%S parmtype.verbless=%S ") % M_bool_cstr(eval_parmtype.eval.no_eval_ident) % M_bool_cstr(eval_parmtype.eval.no_eval_expression) % M_bool_cstr(eval_parmtype.eval.no_eval_vlist) % M_bool_cstr(eval_parmtype.eval.no_eval_ref) % M_bool_cstr(eval_parmtype.eval.verbless);) M__(display_value(value, L"eval_value()");) } static_N::value_count++; // get local copy of effective evaluation flags for this value -- set flags to suppress evaluation, if value is flagged as "suppress evaluation" // ----------------------------------------------------------- arg_eval_S eval { eval_parmtype.eval }; // local copy of passed-in (constant) evaluation flags if (value.suppress_eval_once || value.suppress_eval) // set all no_eval_xxx flags, if suppressing evaluation of passed-in value this time { eval.no_eval_expression = true; eval.no_eval_vlist = true; eval.no_eval_ident = true; eval.no_eval_ident = true; } // evaluate nested expression, if required // --------------------------------------- if ( (value.ty == type_E::expression) && (!eval.no_eval_expression) ) { if (debug) { M__(M_out(L"*************************************** eval_value() -- evaluating nested expression");) } results_S expression_results { }; auto erc = eval_expression(frame, *(value.expression_sp), expression_results, debug); // pass expression attached to this value expression_results.token_ix1 = value.token_ix1; // copy original location info into results expression_results.token_ix2 = value.token_ix2; if (erc != 0) // error during expression evaluation { results = expression_results; // pass back results from expression evaluation rc = erc; // pass back r/c } else // no error during expression evaluation { if (debug) { M__(M_out(L"*************************************** eval_value() -- expression_results.ty=%S -- returned from nested expression evaluation") % type_str(expression_results.ty);) } if ( (expression_results.ty == type_E::identifier) // re-evaluate, if results is an identifier || (expression_results.ty == type_E::vlist) // re-evaluate, if results is a vlist || ( (expression_results.ty == type_E::ref) && (expression_results.ref_sp->auto_deref) ) // re-evaluate, if results is a reference, that should be automatically de-referenced ) { results = expression_results; // return (preliminary) results from expression evaluation results.re_eval_expression_results = true; // indicate that re-evaluation of these results is required } else // no further evaluation needed { results = expression_results; // return results from expression evaluation } } } // evaluate nested vlist, if required -- need to allocate a new one and attach it to the value -- in nested vlists, expressions, and variables always evaluated (according to flags in default plist_S ) // ------------------------------------------------------------------------------------------- else if ( (value.ty == type_E::vlist) && (!eval.no_eval_vlist) ) { if (debug) { M__(M_out(L"*************************************** eval_value() -- evaluating nested vlist");) } vlist_S temp_vlist {}; temp_vlist = *(value.vlist_sp); // can't update vlist pointed to by passed-in value -- need a new copy for updating if (eval_parmtype.plist_sp.get() == nullptr ) // nested plist not present? { M__(M_out(L" eval_value() -- calling eval_vlist() -- evaluating nested vlist - 1");) auto erc = eval_vlist(frame, temp_vlist, results, plist_S {}); // use default plist_S structure for nested vlist if (erc != 0) rc = erc; } else { M__(M_out(L" eval_value() -- calling eval_vlist() -- evaluating nested vlist - 2");) auto erc = eval_vlist(frame, temp_vlist, results, *(eval_parmtype.plist_sp)); // use nested plist from passed-in parmtype if (erc != 0) rc = erc; } if (rc == 0) // bypass vlist anchoring, if error occurred { M__(M_out(L"*************************************** eval_value() -- calling set_vlist_value()");) set_vlist_value(results, temp_vlist, true); // anchor new vlist in passed-in results M__(M_out(L"*************************************** eval_value() -- set_vlist_value() returned");) } results.token_ix1 = value.token_ix1; // save original location info into passed-in results results.token_ix2 = value.token_ix2; } // evaluate identifier, if required -- complain if not defined // ----------------------------------------------------------- else if ( (value.ty == type_E::identifier) && (!eval.no_eval_ident) ) { if (debug) { M__(M_out(L"*************************************** eval_value() -- evaluating identifier");) } auto grc = get_identifier(frame, value.string, results); results.token_ix1 = value.token_ix1; // save original location info into passed-in results results.token_ix2 = value.token_ix2; if (debug) { M__(display_value(value , L"eval_value() -- input value");) M__(display_value(results, L"eval_value() -- evaluated identifier ");) } if (grc != 0) { count_error(); M_out_emsg1(L"eval_value(): evaluating undefined identifier «%s» -- verb using this parameter will not be executed") % value.string; msgend_loc(value); rc = grc; } } // do auto dereference, if required -- complain if any errors // ---------------------------------------------------------- else if ( (value.ty == type_E::ref) && (value.ref_sp->auto_deref) && (!eval.no_eval_ref) ) { if (debug) { M__(M_out(L"*************************************** eval_value() -- doing auto dereference");) } value_S out_val { }; // output value_S from dereferenced value auto drc = dereference_value(out_val, value); if (debug) { M__(display_value(value , L"eval_value() -- input reference value");) M__(display_value(out_val, L"eval_value() -- dereferenced value ");) } if (drc != 0) { count_error(); M_out_emsg1(L"eval_value(): unexpected error while dereferencing value -- verb using this parameter will not be executed") % value.string; msgend_loc(value); rc = drc; } results = to_results(out_val); } else { // other values don't need to be evaluated -- int, float, string, block, unit, verbname etc. -- just copy value to output results // (control also gets here if evaluation is suppressed or evaluation flags call for no evalaution if (debug) { M__(M_out(L"*************************************** eval_value() -- copying value to output results");) } results = to_results(value); } // copy-over suppress evaluation flags into results, as appropriate // ---------------------------------------------------------------- if (value.suppress_eval) { results.suppress_eval = true; // "suppress_eval" stays on until explicitly turned off (this flag is probably already on from the copy of input value to results) } else if (value.suppress_eval_once) { if (eval.verbless) results.suppress_eval_once = true; // "suppress eval once" is not reset when evaluating a verbless expression (this flag is probably already on from the copy of input value to results) else results.suppress_eval_once = false; // "suppress eval once" is reset after 1st use, unless this is verbless expression } if (debug) { M__(M_out(L"********* eval_value() returning -- re-eval = %s <=========================") % M_bool_cstr(results.re_eval_expression_results);) } return rc; } M_endf ////_________________________________________________________________________________________________________________________________________________________________ ////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ /////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ ////""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" //// //// //// eval_vlist() -- evaluate contents of an passed-in vlist (values in passed-in vlist are updated in-place) //// //// ////_________________________________________________________________________________________________________________________________________________________________ ////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ /////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ ////""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" //////////////////////// helper function static parmtype_S get_keyword_parmtype(const plist_S& eval_plist, const std::wstring& keyname) try { if (eval_plist.keywords.count(keyname) > 0) // see if kw-name (or "") is missing in plist_S { return eval_plist.keywords.at(keyname); // return located parmtype_S for keyword name } else // no parmtype_S for this keyword name { if (eval_plist.keywords.count(std::wstring{ L"" }) > 0) // see if "" missing keyword parmtype_S is supplied in plist return eval_plist.keywords.at(std::wstring{ L"" }); // missing kw-name substitute parmtype_S supplied -- pass it back else return parmtype_S {}; // kw-name or "" not found -- use default evaluation parmtype_S } } M_endf ///////////////////////////////////////////////////////////////////////////////////////// int eval_vlist(frame_S& frame, vlist_S& vlist, results_S& results, const plist_S& eval_plist, bool debug) try { bool updated { false }; int rc { 0 }; M__(M_out(L"=========================================> eval_vlist() called");) M__(display_vlist(vlist, L"passed-in to eval_vlist()");) if ( vlist.val_expression || vlist.val_vlist || vlist.val_identifier || vlist.val_ref ) { M__(M_out(L"eval_vlist() -- evaluation is needed");) // build a temporary default parmtype_S with global evaluation flags -- used if no plist is completely empty (contains no parmtypes) for positional parms (this should be the case only when expression has no verb) parmtype_S default_eval_parmtype {}; // default parmtype default_eval_parmtype.eval = eval_plist.eval; // copy in parmtype flags from passed-in plist_S default_eval_parmtype.anything_ok = true; // suppress parm type checking by default // ------------------------------------------------------------------------------------------- // loop to look at each positional parm and do evaluation (subject to verb's evaluation flags) // (note: if plist is empty (verbless expression), use default_parmtype just set up) // if more values in vlist than in parmtypes in plist, use the last the last one for the additional values) // ------------------------------------------------------------------------------------------- for (int i = 0; i < vlist.values.size(); i++) { M__(M_out(L"eval_vlist() -- loop -- i = %d vlist.values.size() = %d" ) % i % vlist.values.size();) results_S val_results { }; if ( (vlist.values.at(i).ty == type_E::expression) || (vlist.values.at(i).ty == type_E::vlist) || (vlist.values.at(i).ty == type_E::identifier) || (vlist.values.at(i).ty == type_E::ref) ) { if (eval_plist.values.empty()) // no plist_S available? { M__(M_out(L"--------------------------------------->eval_vlist() calling eval_value() -- positional -- default_parmype_S");) auto erc = eval_value(frame, vlist.values.at(i), val_results, default_eval_parmtype); M__(M_out(L"--------------------------------------->eval_vlist() eval_value() returned");) if (erc != 0) rc = erc; // remember any error } else // some plist_S are available in values vector -- use i-th parmtype_S or last one, if not enough) { M__(M_out(L"--------------------------------------->eval_vlist() calling eval_value() -- positional -- supplied parmtype_S");) auto erc = eval_value(frame, vlist.values.at(i), val_results, eval_plist.values.at(std::min(i, (int)(eval_plist.values.size() - 1))) ); M__(M_out(L"--------------------------------------->eval_vlist() eval_value() returned");) if (erc != 0) rc = erc; // remember any error } } else // not expression, vlist, or identifier that requires evaluation { val_results = to_results(vlist.values.at(i)); // just copy value from vlist directly into results -- no need for evaluation } M__(M_out(L"eval_vlist() -- inside loop -- looking at results -- i = %d vlist.values.size() = %d" ) % i % vlist.values.size();) // ------------------------------------------------------------------ // look at results from evaluating this expression/value in the vlist // ------------------------------------------------------------------ // return immediately, if any special flags on in results if (val_results.special_results) { vlist.values.at(i) = val_results; // update value in_place in vlist, from values imbedded in results results = val_results; // pass back results with special flags return rc; // return with any errors } // handle usual (single) results from evaluation // --------------------------------------------- if (!val_results.multiple_results) { vlist.values.at(i) = val_results; // update value in_place in vlist, from values imbedded in results M__(M_out(L"eval_vlist() -- (only) value.ty %S %S") % type_str(val_results.ty) % val_results.string;) if (val_results.re_eval_expression_results) i--; // go back and re-evaluate results of expression value evaluation } // handle multiple results -- can be 0, 1, or more values in the multiple results vlist (or perhaps no vlist at all) // ------------------------------------------------------------------------------------- else { M__(M_out(L"eval_vlist() -- multiple results -- before -- i = %d vlist.values.size() = %d" ) % i % vlist.values.size();) M__(display_vlist(*(val_results.vlist_sp), L"eval_vlist() -- adding in multiple results");) auto vlist_it = vlist.values.begin() + i; // get iterator pointing to current (i-th) element in the positional values vector (guaranteed to exist at this point) uint64_t n_results { 0 }; // number of positional value results -- set to 0 in case vlist_sp is not initialized uint64_t n_keys { 0 }; // number of keyword value results -- set to 0 in case vlist_sp is not initialized if ( (!val_results.no_results) && (val_results.vlist_sp.use_count() > 0) ) // vlist_sp points to vlist (with multiple values)? { n_results = val_results.vlist_sp->values.size(); // number of positional results -- can be 0, 1, 2, ... if (val_results.vlist_sp->kw_eval_done) // Keywords in results vlist have been evaluated ? n_keys = val_results.vlist_sp->eval_kws.size(); // get number of keyword results from evaluated keywords multimap else // Keywords in results have not been evaluated ? n_keys = val_results.vlist_sp->keywords.size(); // get number of keyword results from unevaluated keywords vector M__(M_out(L"eval_vlist() -- n_results = %d n_keys = %d" ) % n_results % n_keys;) } if (n_results <= 0) // no results from expression evaluation? { vlist.values.erase(vlist_it); // just remove expression from vlist (don't replace with anything) i--; // reduce loop index, which will be incremented later to point to new (slid-down) element now in i-th vector position vlist.value_ct--; // also reduce number of values present in this vlist } else if (n_results == 1) // just one value in multiple results vlist? -- should not occur?? { vlist.values.at(i) = val_results.vlist_sp->values.at(0); // replace expression in i-th value with the first/only value from the expression evaluation results M__(M_out(L"eval_vlist() -- (multiple=one) value.ty %S %S") % type_str(val_results.vlist_sp->values.at(0).ty) % val_results.vlist_sp->values.at(0).string;) i--; // multiple results may need to be re-evaluated, since eval_value() doesn't do it (since it doesn't have access to n+1-th parmtype) } else // actually have multiple results from expression evaluation { vlist.values.at(i) = val_results.vlist_sp->values.at(0); // replace expression in i-th value with the first value from the expression evaluation results M__(M_out(L"eval_vlist() -- (multiple=0) value.ty %S %S") % type_str(val_results.vlist_sp->values.at(0).ty) % val_results.vlist_sp->values.at(0).string;) // inner loop to insert multiple results values into vlist being evaluated for (auto ii = 1; ii < n_results; ii++) { vlist_it = vlist.values.insert(vlist_it + 1, val_results.vlist_sp->values.at(ii)); // insert n-th multiple value after one that was just set in vlist M__(M_out(L"eval_vlist() -- (multiple=%d) value.ty %S %S") % ii % type_str(val_results.vlist_sp->values.at(ii).ty) % val_results.vlist_sp->values.at(ii).string;) // i++; // adjust vlist index for outer loop to skip past values just inserted vlist.value_ct++; // also increment number of values present in this vlist M__(M_out(L"eval_vlist() -- multiple results -- during -- i = %d vlist.values.size() = %d" ) % i % vlist.values.size();) } i--; // multiple results may need to be re-evaluated, since eval_value() doesn't do it (since it doesn't have access to n+1-th parmtype) } // Append any keywords in the results to the unevaluated keyword list in this vlist -- kw evaluation has not started yet for this vlist, so these should be picked up down below // (these are keywords in the results from evaluating a positional parm) if (n_keys > 0) { auto saved_kw_ct { vlist.kw_ct }; // unevaluated kw count before any additions if (val_results.vlist_sp->kw_eval_done) // if keywords are already evaluated, need to convert them into unevaluated format refresh_evaluated_vlist( *(val_results.vlist_sp) ); // convertback to unevaluated format vlist.keywords.insert(vlist.keywords.end(), val_results.vlist_sp->keywords.cbegin(), val_results.vlist_sp->keywords.cend()); // apppend all unevaluated keyword names/values from v2 (if any) to output vlist vlist.kw_ct = vlist.keywords.size(); // update unevaluated kw count M__(M_out(L"eval_vlist() -- vlist unevaluated kw_ct: before=%d after=%d") % saved_kw_ct % vlist.kw_ct;) } M__(M_out(L"eval_vlist() -- multiple results -- after -- i = %d vlist.values.size() = %d" ) % i % vlist.values.size();) } } updated = true; } else { M__(M_out(L"eval_vlist() -- evaluation not needed" );) } // ---------------------------------------------------------------------------------------------------------------------------------- // loop to evaluate (subject to verb's evaluation flags) each keyword in vlist keywords vector, and save results to eval_kws multimap // ---------------------------------------------------------------------------------------------------------------------------------- if (vlist.keywords.size() > 0) { // set up special parmtype, used to evaluate any expression for the keyword name itself. parmtype_S keyword_parmtype { }; // eval_value() looks at only "no_eval" flags, which are off with default initialization //keyword_parmtype.eval = eval_plist.eval; // copy in parmtype flag from passed-in plist_S -- never suppress KW name expression evaluation ???????? for (auto& elem : vlist.keywords) { value_S keyword_value { }; std::wstring keyword_name { }; // process simple keyword name or evaluate keyword name value, if required // ----------------------------------------------------------------------- if (elem.name.ty == type_E::keyname) // handle simple keyword name value in this keyword_S { keyword_name = elem.name.string; // keyword name is in string field } else // keyword name expression requires evaluation { M__(M_out(L"eval_vlist() -- evaluating keyword name expression");) // need to handle non-simple keyword name -- evaluate value and check for keyword type or string type that can be converted to keyword_name string results_S keyname_results { }; // results from verbname value evaluation auto evrc = reeval_value(frame, elem.name, keyname_results, keyword_parmtype, debug); if (evrc != 0) rc = evrc; if (keyname_results.special_results) { results = keyname_results; // pass back any unusual results from keyword name value evaluation return rc; } if (evrc != 0) { M_out_emsg1(L"eval_vlist() -- keyword name evaluation failed -- cannot continue processing keyword value"); M_out(L" keyword name location -- %s") % value_loc_str(elem.name); M_out(L" vlist location -- %s") % vlist_loc_str(vlist); M_out_emsgz(); results = error_results(); // pass back error results return -1; } // get string for keyword name, if evaluation results are string type or keyword type -- all other types not accepted if ( (keyname_results.ty == type_E::keyname) || (keyname_results.ty == type_E::string) ) { keyword_name = keyname_results.string; // set local keyword name from evaluated string result } else { M_out_emsg1(L"eval_vlist() -- keyword name evaluation did not yield a string type or keyword type -- cannot continue processing keyword value"); M_out(L" keyword name location -- %s") % value_loc_str(elem.name); M_out(L" vlist location -- %s") % vlist_loc_str(vlist); M_out_emsgz(); results = error_results(); // pass back error results return -1; } } M__(M_out(L"eval_vlist() -- keyword name = \"%S\"") % keyword_name;) // evaluate keyword value (now that name is known, can look at verb's keyword evaluation flags) // -------------------------------------------------------------------------------------------- parmtype_S eval_parmtype = get_keyword_parmtype(eval_plist, keyword_name); // will have to evaluate any name expressions here if ( (elem.value.ty == type_E::expression) || (elem.value.ty == type_E::vlist) || (elem.value.ty == type_E::identifier) || (elem.value.ty == type_E::ref) ) { M__(M_out(L"--------------------------------------->eval_vlist() calling eval_value() -- keyword");) results_S val_results { }; auto erc = eval_value(frame, elem.value, val_results, eval_parmtype); M__(M_out(L"---------------------------------------> eval_value() returned -- r/c = %d") % erc;) if (erc != 0) rc = erc; // remember any error if (val_results.special_results) { M__(M_out(L"---------------------------------------> eval_value() returned with special results");) results = val_results; // pass back results with special flags return rc; // return with any errors } // handle multiple results -- 0 or 1 result allowed -- no keyword results allowed // ------------------------------------------------------------------------------ M__(M_out(L"---------------------------------------> eval_value() returned with non-special results");) if (val_results.multiple_results) { if ( (val_results.no_results) || (val_results.vlist_sp.get() == nullptr) ) // if no vlist, assume number of results = 0 { M__(M_out(L"eval_vlist() -- handling multiple results (without vlist) from keyword value eval_value() call");) keyword_value = unit_val(); // no multiple results (?? should not occur??) -- just use unit keyword value } else if (val_results.vlist_sp->kw_ct > 0) { M_out_emsg1(L"eval_vlist() -- evaluation of expression supplied as keyword value returned with %d keywords -- none are allowed in a keyword value") % val_results.vlist_sp->kw_ct; msg_loc(elem.value, L"keyword value"); msgend_loc(vlist); results = error_results(); // pass back error results return -1; } else if (val_results.vlist_sp->value_ct == 0) { keyword_value = unit_val(); // no multiple results (?? should not occur??) -- just use unit keyword value } else if (val_results.vlist_sp->value_ct == 1) { keyword_value = val_results.vlist_sp->values.at(0); // one multiple result (?? should not occur??) -- just use 1st value in multiple results vlist } else // 2 or more values in multiple results -- not allowed for keyword { M_out_emsg1(L"eval_vlist() -- evaluation of expression supplied as keyword value returned with %d positional values -- max of one is allowed in a keyword value") % val_results.vlist_sp->value_ct; msg_loc(elem.value, L"keyword value"); msgend_loc(vlist); results = error_results(); // pass back error results return -1; } } else // must be single results -- not special { M__(M_out(L"eval_vlist() -- handling single (non-special) result from keyword value expression evaluation");) keyword_value = val_results; // set keyword value from evaluated value_S portion of results_S } } else // no need to evaluate supplied keyword value -- just use it directly { keyword_value = elem.value; // just copy unevaluated value } // Add evaluated keyword name (std::wstring) and evaluated keyword value to multimap of evaluated keywords // ------------------------------------------------------------------------------------------------------- // // Note: if evaluated keyword name is empty std::wstring, don't add this one to the evaluated keywords map -- note that keyword value (if any) has already been evaluated and may have caused side effects, etc. if (keyword_name.length() > 0) vlist.eval_kws.emplace(keyword_name, keyword_value); } updated = true; // indicate that vlist has been updated vlist.kw_eval_done = true; // indicate that eval_kws has been filled in vlist.kw_ct = vlist.eval_kws.size(); // update keyrord count o reflect number of evaluated keywords } if (updated) set_vlist_flags(vlist); if (rc != 0) { results = error_results(); // pass back error results } else { M__(M_out(L"=========================================> eval_vlist() setting up none results");) results = results_S { }; // uninitializedt results, when there is no error } M__(display_vlist(vlist, L"output from eval_vlist()");) M__(M_out(L"=========================================> eval_vlist() returning");) return rc; } M_endf ////_________________________________________________________________________________________________________________________________________________________________ ////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ /////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ ////""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" //// //// //// eval_expression() -- evaluate contents of a passed-in expression (values passed-in expression are updated in-place) //// //// ////_________________________________________________________________________________________________________________________________________________________________ ////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ /////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ ////""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // // eval_expression() -- called in a loop from eval_expression() // // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static int eval_expression_1(frame_S& frame, const a_expression_S& orig_expression, results_S& results, bool debug, bool noeval_verbless) try { e_expression_S eval_expression { }; int rc { 0 }; bool lparms_updated { false }; bool rparms_updated { false }; M__(M_out(L"*****************************************************eval_expression() called");) M__(display_expression(orig_expression, L"eval-before", L"", false);) // copy data members from original_expression to new expression // ---------------------------------------------------- eval_expression.has_verb = orig_expression.has_verb ; eval_expression.has_sigil = orig_expression.has_sigil ; eval_expression.sigil = orig_expression.sigil ; eval_expression.priority = orig_expression.priority ; eval_expression.right_associate = orig_expression.right_associate ; eval_expression.left_associate = orig_expression.left_associate ; eval_expression.token_ix1 = orig_expression.token_ix1 ; eval_expression.token_ix2 = orig_expression.token_ix2 ; eval_expression.lparms = orig_expression.lparms ; // nested complex values (pointed to by std::shared_ptr<> ) are shared with orig a_expression_S eval_expression.rparms = orig_expression.rparms ; // nested complex values (pointed to by std::shared_ptr<> ) are shared with orig a_expression_S // ========================================================== // get verbdef, etc, (if verb is present for this expression) // ========================================================== verbdef_S temp { }; verbset_S verbset { }; // will be filled in (overwritten), if real verb is present -- skeleton eval flags are filled in for verbless expressions verbset.verbs.push_back(temp); // default verbset_S, in case verb expression is empty string (and there is no verb) bool have_verbdef { false }; // set to true, once non-empty verbdef found if (orig_expression.has_verb) { // set evaluated verb name in e_expression_S -- either direct from a_expression_S verb_value string value, or by evaluation of a_expression_S verb_value expression if (orig_expression.verb_value.ty == type_E::verbname) // handle simple verbname in this expression { eval_expression.verb_name = orig_expression.verb_value.string; // simple verbname -- name is just string value eval_expression.verb_token_ix1 = orig_expression.verb_value.token_ix1; // copy over token indexes for debugging eval_expression.verb_token_ix2 = orig_expression.verb_value.token_ix2; } else // verb expression requires evaluation { // need to handle non-simple verbname -- evaluate value and check for verbset or string that can be converted to verb_name string // ------------------------------------------------------------------------------------------------------------------------------- results_S verbname_results { }; // results from verbname value evaluation (final) parmtype_S verbname_parmtype { }; // eval_value() uses only "no_eval" flags, which are off by default auto evrc = reeval_value(frame, orig_expression.verb_value, verbname_results, verbname_parmtype, false); if (evrc != 0) rc = evrc; if (verbname_results.special_results) { M__(M_out(L"eval_expression() -- special results from verbname expression = \"%S\"") % str_results_string(verbname_results);) results = verbname_results; // pass back unusual results from verb_value evaluation return rc; } if (evrc != 0) { M_out_emsg1(L"eval_expression() -- expression evaluation to obtain verbname/verbdef failed -- orig_expression.verb_value = %S -- cannot execute") % verb_name(orig_expression); msgend_loc(orig_expression); results = error_results(); // pass back error results return -1; } // get string for verbset_S or verb name, if evaluation results are string or verbname -- all other types not accepted if ( (verbname_results.ty == type_E::verbname) || (verbname_results.ty == type_E::string) ) { eval_expression.verb_name = verbname_results.string; // save away evaluated string eval_expression.verb_token_ix1 = orig_expression.verb_value.token_ix1; // copy over token indexes for debugging eval_expression.verb_token_ix2 = orig_expression.verb_value.token_ix2; } else if (verbname_results.ty == type_E::verbset) { verbset = *(verbname_results.verbset_sp); // just capture verbdef from verbname expression evaluation have_verbdef = true; // suppress verbdef lookup down below, and indicate verbdef is already available eval_expression.verb_token_ix1 = orig_expression.verb_value.token_ix1; // copy over token indexes for debugging eval_expression.verb_token_ix2 = orig_expression.verb_value.token_ix2; M__(M_out(L"eval_expression() -- verbdef results");) } else { M_out_emsg1(L"eval_expression() -- orig_expression.verb_value evaluation did not yield a string, verbname, or verbdef -- orig_expression.verb_value = %s -- verbname_results.ty = %S -- cannot execute") % verb_name(orig_expression) % type_str(verbname_results.ty); msgend_loc(orig_expression); results = error_results(); // pass back error results return -1; } } // get verbset for verb_name (if any) to see what type of variable and expression evaluation is needed in left and right parms -- end immediately, if unknown verb if ( (!have_verbdef) && (eval_expression.verb_name.size() > 0) ) // need to lookup verbdef -and- evaluated verb_name expression is non-empty string? { auto verbdef_rc = get_verb(frame, eval_expression.verb_name, verbset); // returns default, if undefined verb if (verbdef_rc != 0) // undefined verb? { M__(M_out(L"eval_expression() -- ix1/ix2 = %d/%d -- verb-ix1/ix2 = %d/%d") % eval_expression.token_ix1 % eval_expression.token_ix2 % eval_expression.verb_token_ix1 % eval_expression.verb_token_ix2;) if (is_identifier_defined(frame, eval_expression.verb_name)) M_out_emsg1(L"eval_expression() -- defined name \"%S\" is not the name of a verb -- cannot execute") % eval_expression.verb_name; else M_out_emsg1(L"eval_expression() -- verbname = \"%S\" is not defined -- cannot execute") % eval_expression.verb_name; msgend_loc(eval_expression); results = error_results(); // pass back error results return -1; } have_verbdef = true; // indicate that verbdef is now available } } else // this expression has no verb -- may need to suppress evaluation of values in vlist { // set up dummy verbset/verbdef for verbless expression // ---------------------------------------------------- verbset.verbless = true; // indicate that this is a verbless (dummy) verbset_S verbset.verbs.at(0).verbless = true; // indicate that this is a verbless (dummy) verbdef_S verbset.verbs.at(0).lparms.eval.verbless = true; // indicate that this is verbless evaluation verbset.verbs.at(0).rparms.eval.verbless = true; // indicate that this is verbless evaluation -- note: probably no right side vlist when verbless if (noeval_verbless) // should vlist ident, sub expression, etc. evaluation be suppressed when verbless? (configuration flag) { verbset.verbs.at(0).lparms.eval.no_eval_ident = true; verbset.verbs.at(0).lparms.eval.no_eval_vlist = true; // verbset.verbs.at(0).lparms.eval.no_eval_expression = true; // evaluate nested expressions, only verbset.verbs.at(0).lparms.eval.no_eval_ref = true; verbset.verbs.at(0).rparms.eval.no_eval_ident = true; // note: probably no right side vlist when verbless, so these aren't needed verbset.verbs.at(0).rparms.eval.no_eval_vlist = true; // verbset.verbs.at(0).rparms.eval.no_eval_expression = true; // evaluate nested expressions, only verbset.verbs.at(0).rparms.eval.no_eval_ref = true; } } // Process any nested expressions in left or right vlists -- replace expression with value -- updated value can be another expression or variable -- no double evaluation -- these will be left as-is here (verb checking may complain about them) // ------------------------------------------------------ if ( (eval_expression.lparms.value_ct > 0) || (eval_expression.lparms.kw_ct > 0) ) // un-evaluated kw count { M__(M_out(L"eval_expression() -- process left vlist (lparms) -- calling eval_vlist()");) results_S vlist_results {}; auto erc = eval_vlist(frame, eval_expression.lparms, vlist_results, verbset.verbs.at(0).lparms); if (erc != 0) rc = erc; if (vlist_results.special_results) { M__(M_out(L"eval_expression() -- special results from left-side eval_vlist() for verb = \"%S\" -- special results = \"%S\"") % verb_name(eval_expression) % str_results(vlist_results, true, false, true);) results = vlist_results; // pass back unusual results from vlist evaluation return rc; } } if ( (eval_expression.rparms.value_ct > 0) || (eval_expression.rparms.kw_ct > 0) ) // un-evaluated kw count { M__(M_out(L"eval_expression() -- process right vlist (rparms) -- calling eval_vlist()");) results_S vlist_results {}; auto erc = eval_vlist(frame, eval_expression.rparms, vlist_results, verbset.verbs.at(0).rparms); if (erc != 0) rc = erc; if (vlist_results.special_results) { M__(M_out(L"eval_expression() -- special results from right-side eval_vlist() for verb = \"%S\" -- special results = \"%S\"") % verb_name(eval_expression) % str_results(vlist_results, true, false, true);) results = vlist_results; // pass back unusual results from vlist evaluation return rc; } } M__(display_expression(eval_expression, L"eval-after", L"", false);) // don't evaluate the main verb, if any errors seen so far during vlist evaluation if (rc != 0) { M_out_emsg1(L"eval_expression() -- bypassing execution of verb= %s because of errors while evaluating parms") % verb_name(eval_expression); msgend_loc(eval_expression); results = error_results(); // pass back error results return rc; } // do preliminary parm checking based on verbdef_S for main verb (if any) // ---------------------------------------------------------------------- // ???????????????????? verbdef_S selection from the verbset_S returned from get_verb() will be required here ?????? verbdef_S verbdef = verbset.verbs.at(0); if (eval_expression.has_verb && have_verbdef) // bypass parm checking if no verbdef is available { M__(M_out(L"eval_expression() -- doing parm checking -- calling check_verb_parms()");) auto crc = check_verb_parms(frame, eval_expression, verbdef); if (crc != 0) rc = crc; } // don't evaluate the main verb, if any errors seen so far (during parm chedcking) if (rc != 0) { M_out_emsg1(L"eval_expression() -- bypassing execution of verb= %s because of errors while checking basic parm counts and types") % verb_name(eval_expression); msgend_loc(eval_expression); results = error_results(); // pass back error results return rc; } // ========================================== // evaluate the main verb for this expression // ========================================== if (eval_expression.has_verb) { // just return unit value, if no verbdef is available if (!have_verbdef) { results = unit_results(); // return unit results ??????? -- shold this be an eror message ??????? } // otherwise, invoke the verb to get results // ----------------------------------------- else // evaluated verb name is not empty string { if (verbdef.fcn_p != nullptr) { if (verbdef.simplified_call) { M__(M_out(L"eval_expression() -- doing simplified verb call <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");) // do simplified verb call -- non ex-non-internal predefined verbs int (*call_p)(const e_expression_S&, value_S&) = (int (*)(const e_expression_S&, value_S&))(verbdef.fcn_p); // simplified call pointer value_S result_value { }; // predefined uninitialized value auto prc = (*call_p)(eval_expression, result_value); // will pass back value_S converted to (non-special) result_S from verb call results = to_results(result_value); // convert return value to full (non-special) results if (prc != 0) rc = prc; // remember any error from verb execution } else { M__(M_out(L"eval_expression() -- doing regular verb call <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");) // do regular verb call -- ex-internal predefined verbs int (*call_p)(frame_S&, const e_expression_S&, const verbdef_S&, results_S&) = (int (*)(frame_S&, const e_expression_S&, const verbdef_S&, results_S&))(verbdef.fcn_p); // regular call pointer auto prc = (*call_p)(frame, eval_expression, verbdef, results); // will pass back result_S from verb call if (prc != 0) rc = prc; // remember any error from verb execution } frame.verb_eval_ct++; // accumulate verb calls in current stack frame static_N::verb_count++; // accumulate total verb calls // Indicate that these results are from a builtin verb, if the verbdef indicates built-in verb results.builtin_verb_results = verbdef.is_builtin; M__(M_out(L"eval_expression() -- results.builtin_verb_results = %d <<<<<<<<<<<<<<<<<<<<<<<<<") % ((int)(results.builtin_verb_results));) } else // should not happen { M_out_emsg1(L"eval_expression() -- verbdef.fcn_p = nullptr for verb=%S") % verb_name(eval_expression) ; M_throw_v( "eval_expression() -- verbdef.fcn_p = nullptr for verb=%S") % out_ws( verb_name(eval_expression)) )); } } } // no verb present -- should be empty parens, or parens with just left-side positional values/keywords present -- no right parms expected here // ------------------------------------------------------------------------------------------------------------------------------------------- else { if ( (eval_expression.rparms.value_ct > 0) // no right-side positional parms allowed without verb (should not happen) || (eval_expression.rparms.kw_ct > 0 ) // no right-side keywords allowed without verb (should not happen) ) { // invalid verbless expression -- error -- should not occur -- error should heve been found during parsing phase before evaluation started M_out_emsg1(L"eval_expression() -- verbless expression with right-side positional or keyword parms seen -- should not occur"); msgend_loc(eval_expression); M_throw("eval_expression() -- verbless expression with right-side positional or keyword parms") } else { M__(M_out(L"eval_expression() -- handling no-verb case <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");) ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////// ////// ////// ========================= ////// handle no-verb expression -- just empty expression or vlist with left-side positional/keyword parm(s) ////// ========================= ////// ////// ////// Just take left side vlist resulting from verbless evaluation and return it as the results from this expresion ////// ////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// M__(M_out( L"eval_expression() -- lparms.value_ct=%d lparms.kw_ct=%d rparms.value_ct=%d rparms.kw_ct=%d ") % eval_expression.lparms.value_ct % eval_expression.lparms.kw_ct % eval_expression.rparms.value_ct % eval_expression.rparms.kw_ct;) // make sure any keywords in verbless left-side parms vlist are in unevaluated format // ---------------------------------------------------------------------------------- if (eval_expression.lparms.kw_eval_done) // has keyword multimap been filled in? refresh_evaluated_vlist(eval_expression.lparms); // make it look like keywords have not been evaluated yet // pass back left-side vlist from earlier verbless evaluation // ---------------------------------------------------------- if ( (eval_expression.lparms.kw_ct > 0) || (eval_expression.lparms.value_ct > 1) ) { M__(display_vlist(eval_expression.lparms, L"eval_expression() -- passing back from verbless expression");) results = to_results(vlist_val(eval_expression.lparms)); // pass back whole left-side positional parm vlist -- will be multiple results results.multiple_results = true; // indicate that multiple results are being returned } else if (eval_expression.lparms.value_ct == 0) // just parens -- no parms inside (or they all went away during evaluation) { results = no_results(); // zero result values -- vlist_sp is not initialized } else // must be single positional value, with no keywords { results = to_results(eval_expression.lparms.values.at(0)); // pass back 1st/only left-side positional parm } } } M__(M_out(L"*****************************************************eval_expression() returning");) if (results.special_results) { M__(M_out(L"eval_expression() -- special results from eval_expresssion() for verb = \"%S\" -- special results = \"%S\"") % verb_name(eval_expression) % str_results(results, true, false, true);) } return rc; } M_endf ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // // eval_expression() -- call eval_expression_1() in loop, as long as @XCTL results are seen from expression execution // // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// int eval_expression(frame_S& frame, const a_expression_S& expression, results_S& results, bool debug) try { const a_expression_S *expression_p {&expression}; results_S results_x { }; // @XCTL results from eval_expression_1() -- should have shared ptr to expression_S for next loop pass // main loop to call eval_expression_1(), and repeat loop to handle any @XCTL results // ----------------------------------------------------------------------------- for (;;) { results_S results_1 { }; // results from eval_expression_1() auto rc = eval_expression_1(frame, *expression_p, results_1, debug, NOEVAL_VERBLESS); M__(M_out(L"eval_expression() -- eval_expression_1() returned <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"); ) if (rc != 0) { results = results_1; // pass back (error?) results from eval_expression_1() return rc; // pass back any errors from eval_expression_1() } if ( !(results_1.special_results && results_1.xctl_flag) ) { M__(M_out(L"eval_expression() -- returning (non-@XCTL results <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"); ) results = results_1; // pass back results from eval_expression_1() return rc; // pass back all results, except for @XCTL special results } // handle @XCTL results if (results_1.builtin_verb_results == true) { M__(M_out(L"eval_expression() -- processing @XCTL results -- from built-in verb <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");) results = results_1; // pass back special @XCTL results from eval_expression_1() -- don't action this time -- wait for user's verb (non-builtin) to come back before doing the @XCTL return rc; } M__(M_out(L"eval_expression() -- processing @XCTL results -- from user-defined verb <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");) results_x = results_1; // hold onto expression_S from @XCTL results via shared ptr until next call to eval_expression_1() expression_p = results_x.expression_sp.get(); // next pass -- use expression provided with with @XCTL results // (loop back to call eval_expression_1() with new expression setup by the @XCTL verb, in place of current expression) } } M_endf ////_________________________________________________________________________________________________________________________________________________________________ ////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ /////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ ////""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" //// //// //// eval_block() -- evaluate all expressions in a block -- return results from last expression evaluated (if any) //// //// ////_________________________________________________________________________________________________________________________________________________________________ ////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ /////\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ ////""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" int eval_block(frame_S& frame, const block_S& block, results_S& results) try { M__(M_out(L"eval_block() -- called");) int rc = 0; results_S block_results { no_results() }; // start with no results, in case 1st expression is something like @CONTINUE with ignored results auto expression_max = block.expressions.size(); decltype(expression_max) expression_ix = 0; M__(M_out(L"eval_block() -- expression_max=%d") % expression_max;) static_N::block_count++; // filter out empty block -- need to return 0 results from this (not just unit results) if (expression_max == 0) { results = no_results(); // zero result values M__(M_out(L"eval_block() -- multiple results = 0 results");) return 0; } // -------------------------------------------------------------- // main loop to process each statement (expression) in this block // -------------------------------------------------------------- for (;;) { M__(M_out(L"eval_block() -- top of for(;;) loop");) if (expression_ix >= expression_max) break; static_N::statement_count++; // evaluate n-th expression in block, and handle error r/c // ------------------------------------------------------- results_S expression_results { }; M__(M_out(L"eval_block() -- calling eval_expression(%d)") % expression_ix;) auto erc = eval_expression(frame, block.expressions.at(expression_ix), expression_results); if (erc != 0) { M_out_emsg1(L"eval_block() -- block evaluation ending immediately because of errors during expression evaluation at statement %d") % expression_ix; msgend_loc(block.expressions.at(expression_ix)); rc = erc; results = error_results(); return -1; } // save away expression results as the block results, unless the "ignore results" special flag is set if (!expression_results.ignore_results) block_results = expression_results; // ====================== // handle special results -- @LEAVE and @GOTO are processed at the block level -- may get consumed if label matches, or percolated otherwise -- other special results are passed back // ====================== if (expression_results.special_results) { M__(M_out(L"eval_block() -- handling special results");) // handle (plain) @LEAVE -or- @LEAVE "target block" // --------------------------------------------------------------- if (expression_results.leave_flag) { // if (plain) @LEAVE -or- @LEAVE target matches this block -- end processing of this block if ( expression_results.str.empty() || (expression_results.str == block.label) ) { M__(M_out(L"eval_block() -- @LEAVE target found in current block -- ending block with unit results");) expression_results.leave_flag = false; // consume the @LEAVE expression_results.special_results = false; results = expression_results; // pass back @LEAVE results -- @LEAVE is consumed return 0; } // @LEAVE is not targetting the current block -- need to "percolate" @LEAVE results upwards to enclosing blocks (if any) M__(M_out(L"eval_block() -- @LEAVE target not found in current block -- percolating upwards");) results = expression_results; break; } // handle @GOTO or @GOTO longjmp: // ------------------------------ if (expression_results.goto_flag || expression_results.lgoto_flag ) { // see if @GOTO target matches some label in this block auto target_ct = block.labels.count(expression_results.str); if (target_ct > 0) { // matching label found in this block -- reset expression_ix to label position and continue looping (label may point past last expression in this block expression_ix = block.labels.at(expression_results.str); M__(M_out(L"eval_block() -- @GOTO target found in current block -- restarting block evaluation at expression index = %d") % expression_ix;) continue; } // @GOTO target was not found in this block -- "percolate" @GOTO results upwards to enclosing blocks (if any) M__(M_out(L"eval_block() -- @GOTO target not found in current block -- percolating upwards");) results = expression_results; break; } // handle @SKIPTO // -------------- if (expression_results.skip_flag ) { // percolate @SKIPTO results M__(M_out(L"eval_block() -- percolating @SKIPTO results -- results = \"%S\"") % str_results_string(expression_results);) results = expression_results; break; } // any other special results (@RETURN, @XCTL, @QUIT, etc.) will cause block evaluation to end -- empty special results flags are passed back to block evaluator for handling or further percolation M__(M_out(L"eval_block() -- percolating special results upward -- results = \"%S\"") % str_results_string(block_results);) results = block_results; // pass back special results -- don't use expression_results here, since @CONTINUE results are not saved as the block results break; } // no error -- no special results -- normal advance to next expression in block M__(M_out(L"eval_block() -- no special results from expression(%d)") % expression_ix;) expression_ix++; } results = block_results; // return results from last expression evaluated -- no special results get here M__(M_out(L"eval_block() -- normal return at end");) return rc; } M_endf //_________________________________________________________________________________________________________________________________________________________________ //\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ //\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ //\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ //\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ //"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
64.04778
292
0.379234
dufferprog
19b625f3e035e438063835cbbb28712a695c16b1
505
cpp
C++
GraphGenerator/Testfiles/classes_simple.cpp
krystalsavv/Architecture-Mining
da47474f90bfb928ee65967610cb5ebb22057bb1
[ "MIT" ]
2
2021-03-31T19:14:51.000Z
2021-07-16T12:27:09.000Z
GraphGenerator/Testfiles/classes_simple.cpp
krystalsavv/Architecture-Mining
da47474f90bfb928ee65967610cb5ebb22057bb1
[ "MIT" ]
null
null
null
GraphGenerator/Testfiles/classes_simple.cpp
krystalsavv/Architecture-Mining
da47474f90bfb928ee65967610cb5ebb22057bb1
[ "MIT" ]
null
null
null
/* Classes Namespaces Inheritence */ namespace CS{ namespace CS_1{ class class_X; class class_B; class class_B {class_B* b;}; class class_A { class_B b;}; struct struct_S {}; class class_X : public class_A, class_B {}; } } namespace N_2 { class class_A{}; } using namespace CS::CS_1; int main(){ class_A a; class_A *pa = new class_A; struct_S s; struct_S *ps = new struct_S; class_X x; class_X *px = new class_X; return 0; }
14.852941
48
0.60198
krystalsavv
19b8212fc9e15dfbcddd0db48b11142eb8f30504
1,960
cpp
C++
Detector/Classifier.cpp
goddoe/Learner
c499adda2f341003c6a3ec35bf41f2ca05c98833
[ "MIT" ]
4
2016-05-19T08:40:43.000Z
2018-04-08T14:25:17.000Z
Detector/Classifier.cpp
goddoe/Learner
c499adda2f341003c6a3ec35bf41f2ca05c98833
[ "MIT" ]
null
null
null
Detector/Classifier.cpp
goddoe/Learner
c499adda2f341003c6a3ec35bf41f2ca05c98833
[ "MIT" ]
null
null
null
// Author : Sung-ju Kim // Email : goddoe2@gmail.com // github : https://github.com/goddoe // The MIT License (MIT) // Copyright (c) 2016 Sung-ju Kim #include "Classifier.h" using namespace cv; namespace CRVL { ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // Recognition Classifier::Classifier (char* recognitionPath, int m_learner, void (*getFeature)(Mat src, Mat& feature_CV_32FC1) ) { switch(m_learner) { case LEARNER_SVM: mode = LEARNER_SVM; svmRecognizer.load(recognitionPath); featureGenerator = getFeature; break; case LEARNER_MLP: mode = LEARNER_MLP; featureGenerator = getFeature; net = new sj::Net(); net->load(recognitionPath); break; } } int Classifier::recognize(cv::Mat _src) { switch(mode){ case LEARNER_SVM: { Mat feature; featureGenerator(_src, feature); if (svmRecognizer.predict(feature) >= 1) return true; else return false; } break; case LEARNER_MLP: { Mat feature; featureGenerator(_src,feature); net->feedforward((float*)feature.data); float max = -1; int response = -1; for(int i = 0 ; i < net->m_layersInfo.back()->numNeuron; ++i){ if( max < (float)(net->m_layersActivation.back()[i])){ max = (float)(net->m_layersActivation.back()[i]); response = i; } } return response; } break; } return -1; } }
25.454545
151
0.433163
goddoe
19c05d49bd2be73577bc76f88ad3dcf40e86c480
3,537
hpp
C++
library/src/main/jni/openslmediaplayer-jni/include/OpenSLMediaPlayerJNIBinder.hpp
cirnoftw/android-openslmediaplayer
6b363282dd0ac19bcb4e8ce52a4cb7bf35c58583
[ "Apache-2.0" ]
435
2015-01-16T14:36:07.000Z
2022-02-11T02:32:19.000Z
library/src/main/jni/openslmediaplayer-jni/include/OpenSLMediaPlayerJNIBinder.hpp
cirnoftw/android-openslmediaplayer
6b363282dd0ac19bcb4e8ce52a4cb7bf35c58583
[ "Apache-2.0" ]
59
2015-02-12T22:21:49.000Z
2021-06-16T11:48:15.000Z
library/src/main/jni/openslmediaplayer-jni/include/OpenSLMediaPlayerJNIBinder.hpp
cirnoftw/android-openslmediaplayer
6b363282dd0ac19bcb4e8ce52a4cb7bf35c58583
[ "Apache-2.0" ]
104
2015-01-16T14:36:07.000Z
2021-05-24T03:32:54.000Z
// // Copyright (C) 2014 Haruki Hasegawa // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #ifndef OPENSLMEDIAPLAYERJNIBINDER_HPP_ #define OPENSLMEDIAPLAYERJNIBINDER_HPP_ #include <jni.h> #include <jni_utils/jni_utils.hpp> #include <utils/RefBase.h> #include <oslmp/OpenSLMediaPlayer.hpp> namespace oslmp { namespace jni { class OpenSLMediaPlayerJNIBinder : public virtual android::RefBase, public oslmp::OpenSLMediaPlayer::InternalThreadEventListener, public oslmp::OpenSLMediaPlayer::OnCompletionListener, public oslmp::OpenSLMediaPlayer::OnPreparedListener, public oslmp::OpenSLMediaPlayer::OnSeekCompleteListener, public oslmp::OpenSLMediaPlayer::OnBufferingUpdateListener, public oslmp::OpenSLMediaPlayer::OnInfoListener, public oslmp::OpenSLMediaPlayer::OnErrorListener { public: OpenSLMediaPlayerJNIBinder(JNIEnv *env, jclass clazz, jobject weak_thiz); virtual ~OpenSLMediaPlayerJNIBinder(); void bind(const android::sp<OpenSLMediaPlayerContext> &context, const android::sp<OpenSLMediaPlayer> &player) noexcept; void unbind() noexcept; // implementations of InternalThreadEventListener virtual void onEnterInternalThread(OpenSLMediaPlayer *mp) noexcept override; virtual void onLeaveInternalThread(OpenSLMediaPlayer *mp) noexcept override; // implementations of OnCompletionListener virtual void onCompletion(OpenSLMediaPlayer *mp) noexcept override; // implementations of OnPreparedListener virtual void onPrepared(OpenSLMediaPlayer *mp) noexcept override; // implementations of OnSeekCompleteListener virtual void onSeekComplete(OpenSLMediaPlayer *mp) noexcept override; // implementations of OnBufferingUpdateListener virtual void onBufferingUpdate(OpenSLMediaPlayer *mp, int32_t percent) noexcept override; // implementations of OnInfoListener virtual bool onInfo(OpenSLMediaPlayer *mp, int32_t what, int32_t extra) noexcept override; // implementations of OnErrorListener virtual bool onError(OpenSLMediaPlayer *mp, int32_t what, int32_t extra) noexcept override; private: void postMessageToJava(int32_t what, int32_t arg1, int32_t arg2, jobject obj) noexcept; // inhibit copy operations OpenSLMediaPlayerJNIBinder(const OpenSLMediaPlayerJNIBinder &) = delete; OpenSLMediaPlayerJNIBinder &operator=(const OpenSLMediaPlayerJNIBinder &) = delete; private: JavaVM *jvm_; JNIEnv *env_; jglobal_ref_wrapper<jclass> jplayer_class_; jglobal_ref_wrapper<jobject> jplayer_weak_thiz_; jmethodID methodIdPostEventFromNative_; android::wp<OpenSLMediaPlayerContext> context_; android::wp<OpenSLMediaPlayer> player_; }; } // namespace jni } // namespace oslmp #endif // OPENSLMEDIAPLAYERJNIBINDER_HPP_
40.655172
96
0.723777
cirnoftw
19c488e72d0da13d0c145c5f8d6899ee126b5f45
2,133
cpp
C++
librf/src/mutex_v1.cpp
HungMingWu/librf
d3c568ca8c717e6e6d9607aee55e3da219a33c1e
[ "Apache-2.0" ]
null
null
null
librf/src/mutex_v1.cpp
HungMingWu/librf
d3c568ca8c717e6e6d9607aee55e3da219a33c1e
[ "Apache-2.0" ]
null
null
null
librf/src/mutex_v1.cpp
HungMingWu/librf
d3c568ca8c717e6e6d9607aee55e3da219a33c1e
[ "Apache-2.0" ]
null
null
null
#include "../librf.h" namespace resumef { namespace detail { mutex_impl::mutex_impl() { } void mutex_impl::unlock() { std::scoped_lock lock_(this->_lock); if (_owner != nullptr) { for (auto iter = _awakes.begin(); iter != _awakes.end(); ) { auto awaker = *iter; iter = _awakes.erase(iter); if (awaker->awake(this, 1)) { _owner = awaker; break; } } if (_awakes.size() == 0) { _owner = nullptr; } } } bool mutex_impl::lock_(const mutex_awaker_ptr& awaker) { assert(awaker); std::scoped_lock lock_(this->_lock); if (_owner == nullptr) { _owner = awaker; awaker->awake(this, 1); return true; } else { _awakes.push_back(awaker); return false; } } bool mutex_impl::try_lock_(const mutex_awaker_ptr& awaker) { assert(awaker); std::scoped_lock lock_(this->_lock); if (_owner == nullptr) { _owner = awaker; return true; } else { return false; } } } namespace mutex_v1 { mutex_t::mutex_t() : _locker(std::make_shared<detail::mutex_impl>()) { } future_t<bool> mutex_t::lock() const { awaitable_t<bool> awaitable; auto awaker = std::make_shared<detail::mutex_awaker>( [st = awaitable._state](detail::mutex_impl* e) -> bool { st->set_value(e ? true : false); return true; }); _locker->lock_(awaker); return awaitable.get_future(); } bool mutex_t::try_lock() const { auto dummy_awaker = std::make_shared<detail::mutex_awaker>( [](detail::mutex_impl*) -> bool { return true; }); return _locker->try_lock_(dummy_awaker); } future_t<bool> mutex_t::try_lock_until_(const clock_type::time_point& tp) const { awaitable_t<bool> awaitable; auto awaker = std::make_shared<detail::mutex_awaker>( [st = awaitable._state](detail::mutex_impl* e) -> bool { st->set_value(e ? true : false); return true; }); _locker->lock_(awaker); (void)this_scheduler()->timer()->add(tp, [awaker](bool) { awaker->awake(nullptr, 1); }); return awaitable.get_future(); } } }
16.534884
80
0.604313
HungMingWu
19c7f9f9d5c6a6f83e31670ed9696acdd4d9be52
2,516
cpp
C++
vox_nav_pose_navigator/src/behavior_tree.cpp
NMBURobotics/vox_nav
7d71c97166ce57680bf2e637cca7c745d55b045a
[ "Apache-2.0" ]
47
2021-06-03T08:46:51.000Z
2022-03-31T08:07:09.000Z
vox_nav_pose_navigator/src/behavior_tree.cpp
BADAL244/vox_nav
cd88c8a921feed65a92355d6246cf6cb8dd27939
[ "Apache-2.0" ]
6
2021-06-06T01:17:38.000Z
2022-01-06T10:01:53.000Z
vox_nav_pose_navigator/src/behavior_tree.cpp
BADAL244/vox_nav
cd88c8a921feed65a92355d6246cf6cb8dd27939
[ "Apache-2.0" ]
10
2021-06-03T08:46:53.000Z
2022-03-04T00:57:51.000Z
// Copyright (c) 2019 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "vox_nav_pose_navigator/behavior_tree.hpp" #include <memory> #include <string> #include <vector> #include "behaviortree_cpp_v3/xml_parsing.h" #include "behaviortree_cpp_v3/loggers/bt_cout_logger.h" #include "rclcpp/rclcpp.hpp" namespace vox_nav_pose_navigator { BehaviorTree::BehaviorTree( const std::string & bt_xml, const std::vector<std::string> & plugin_library_names) : xml_parser_(factory_) { // Load any specified BT plugins for (const auto & library_name : plugin_library_names) { factory_.registerFromPlugin(std::string{"lib" + library_name + ".so"}); } // Parse the input XML xml_parser_.loadFromText(bt_xml); // Create a blackboard for this Behavior Tree blackboard_ = BT::Blackboard::create(); } BtStatus BehaviorTree::execute( std::function<bool()> should_halt, std::function<void()> on_loop_iteration, std::chrono::milliseconds tick_period) { // Create the corresponding Behavior Tree BT::Tree tree = xml_parser_.instantiateTree(blackboard_); BT::StdCoutLogger logger(tree); // Set up a loop rate controller based on the desired tick period rclcpp::WallRate loop_rate(tick_period); // Loop until something happens with ROS or the node completes BT::NodeStatus result = BT::NodeStatus::RUNNING; while (rclcpp::ok() && result == BT::NodeStatus::RUNNING) { if (should_halt()) { tree.rootNode()->halt(); return BtStatus::HALTED; } // Execute one tick of the tree result = tree.rootNode()->executeTick(); // Give the caller a chance to do something on each loop iteration on_loop_iteration(); // Throttle the BT loop rate, based on the provided tick period value loop_rate.sleep(); } return (result == BT::NodeStatus::SUCCESS) ? BtStatus::SUCCEEDED : BtStatus::FAILED; } } // namespace vox_nav_pose_navigator
31.061728
88
0.703498
NMBURobotics
19c940869c24b2de99f6fc0dc97d39bb6d2e7226
749
cpp
C++
1-introduction/p097-05_imperial_lenght_to_metric.cpp
mohsend/Magnificent-University-projects
4b0f9df939a60ace45eeccb331db85af77d83ee9
[ "MIT" ]
null
null
null
1-introduction/p097-05_imperial_lenght_to_metric.cpp
mohsend/Magnificent-University-projects
4b0f9df939a60ace45eeccb331db85af77d83ee9
[ "MIT" ]
null
null
null
1-introduction/p097-05_imperial_lenght_to_metric.cpp
mohsend/Magnificent-University-projects
4b0f9df939a60ace45eeccb331db85af77d83ee9
[ "MIT" ]
null
null
null
// imperial_lenght_to_metric.cpp : Defines the entry point for the console application. // pgae 95 - 5 #include <iostream> using namespace std; int main() { double input_imperial(); double converter(double); void print(double); print(converter(input_imperial())); cin.ignore(); cin.get(); return 0; } double input_imperial() { double feet, inches; cout << "How many feet?\n"; cin >> feet; cout << "And how many inches?\n"; cin >> inches; inches += feet * 12.0; return inches; } double converter(double inches) { return inches * 2.54; } void print(double centimeters) { cout << "That's about " << int(centimeters)/100 << " meters and " << int(centimeters) % 100 << " centimeters.\n"; }
18.725
115
0.634179
mohsend
19dd748b5ed4ae157cf512f115218db8cee43f5f
250
cxx
C++
source/code/icelib/private/output/elements/alias.cxx
iceshard-engine/code-emitter
b86eda2bc0cbdc4302fb4b03ce012ca2a0f3aeea
[ "BSD-3-Clause-Clear" ]
null
null
null
source/code/icelib/private/output/elements/alias.cxx
iceshard-engine/code-emitter
b86eda2bc0cbdc4302fb4b03ce012ca2a0f3aeea
[ "BSD-3-Clause-Clear" ]
2
2019-09-30T05:20:37.000Z
2019-10-10T19:18:59.000Z
source/code/icelib/private/output/elements/alias.cxx
iceshard-engine/code-emitter
b86eda2bc0cbdc4302fb4b03ce012ca2a0f3aeea
[ "BSD-3-Clause-Clear" ]
null
null
null
#include <ice/output/elements/alias.hxx> namespace ice::output { template<> auto identifier(Alias const& data) noexcept -> std::string { return { "alias:" + data.name + "{" + data.type + "}" }; } } // namespace ice::output
19.230769
64
0.592
iceshard-engine
19e37a284ec00834886557f53a23cfb33b6480c8
604
cpp
C++
Longest Common Subsequence (DP)/main.cpp
AhmedAMorsy/Algorithms_
6f4b6d8a231e61e6e3d2289b7a42c6ef24224944
[ "Unlicense" ]
null
null
null
Longest Common Subsequence (DP)/main.cpp
AhmedAMorsy/Algorithms_
6f4b6d8a231e61e6e3d2289b7a42c6ef24224944
[ "Unlicense" ]
null
null
null
Longest Common Subsequence (DP)/main.cpp
AhmedAMorsy/Algorithms_
6f4b6d8a231e61e6e3d2289b7a42c6ef24224944
[ "Unlicense" ]
null
null
null
#include <iostream> #include <cstring> #include <algorithm> using namespace std; const int N=1005; string a,b; int mem[N][N]; int solve(int i,int j) { if(i==a.size()||j==b.size()) { return 0; } if(mem[i][j]!=-1) { return mem[i][j]; } if(a[i]==b[j]) { return mem[i][j]=solve(i+1,j+1)+1; } int op1=solve(i+1,j); int op2=solve(i,j+1); return mem[i][j]=max(op1,op2); } int main() { int t; cin>>t; while(t--) { memset(mem,-1,sizeof mem); cin>>a>>b; cout<<solve(0,0)<<endl; } return 0; }
15.1
42
0.478477
AhmedAMorsy
19e4dbe378a6c5ed210199c3f349e8f3ddb59976
1,155
hpp
C++
Mary-Lang/Utils/Memory.hpp
iamOgunyinka/Mary-Lang
025584184764ca0ca501ee4da9266d54067284a8
[ "MIT" ]
null
null
null
Mary-Lang/Utils/Memory.hpp
iamOgunyinka/Mary-Lang
025584184764ca0ca501ee4da9266d54067284a8
[ "MIT" ]
null
null
null
Mary-Lang/Utils/Memory.hpp
iamOgunyinka/Mary-Lang
025584184764ca0ca501ee4da9266d54067284a8
[ "MIT" ]
null
null
null
#include <memory> namespace MaryLang { namespace Support { #if __cplusplus != 201402L template<typename T> struct UniqueIf { typedef std::unique_ptr<T> SingleObject; }; template< typename T> struct UniqueIf<T[]> { typedef std::unique_ptr<T[]> UnknownBound; }; template<typename T, size_t N> struct UniqueIf<T[N]> { typedef void KnownBound; }; template<typename T, typename ...Args> typename UniqueIf<T>::SingleObject make_unique( Args &&... args ) { return std::unique_ptr<T>( new T( std::forward<Args>( args )... ) ); } template<typename T, typename ...Args> typename UniqueIf<T>::UnknownBound make_unique( size_t n ) { typedef typename std::remove_extent<T>::type U; return std::unique_ptr<T>( new U[n]() ); } template<typename T, typename ...Args> typename UniqueIf<T>::KnownBound make_unique( Args && ... ); #else using std::make_unique; #endif } } // namespace MaryLang
25.108696
80
0.544589
iamOgunyinka
19ee83333b4eae4d5b28fa524d4900ed25073038
4,704
cxx
C++
the/lib/ui/graphics.cxx
deni64k/the
c9451f03fe690d456bae89ac2d4a9303317dd8cd
[ "Apache-2.0" ]
null
null
null
the/lib/ui/graphics.cxx
deni64k/the
c9451f03fe690d456bae89ac2d4a9303317dd8cd
[ "Apache-2.0" ]
null
null
null
the/lib/ui/graphics.cxx
deni64k/the
c9451f03fe690d456bae89ac2d4a9303317dd8cd
[ "Apache-2.0" ]
null
null
null
#include <thread> #include "the/lib/ui/errors.hxx" #include "the/lib/ui/graphics.hxx" namespace the::ui { int Graphics::windowWidth_; int Graphics::windowHeight_; OglFallible<> Graphics::Init() { using namespace std::placeholders; glfwSetErrorCallback(Graphics::OnGlfwErrorCallback_); // start GL context and O/S window using the GLFW helper library if (!glfwInit()) { return {RuntimeError{"could not start GLFW3"}}; } glfwInitialized_ = true; #ifdef __APPLE__ // Get the newest available version of OpenGL on Apple, // which will be 4.1 or 3.3 on Mavericks, and 3.2 on // pre-Mavericks systems. // On other systems it will tend to pick 3.2 instead of // the newest version, which is unhelpful. glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #endif glfwWindowHint(GLFW_SAMPLES, 4); // GLFWmonitor *monitor = glfwGetPrimaryMonitor(); // GLFWvidmode const *vmode = glfwGetVideoMode(monitor); // window_ = glfwCreateWindow( // vmode->width, vmode->height, "Stars sky", monitor, NULL); window_ = glfwCreateWindow( WindowWidth(), WindowHeight(), "Stars sky", nullptr, nullptr); if (!window_) { return {RuntimeError{"could not open window with GLFW3"}}; } glfwGetFramebufferSize(window_, &Graphics::windowWidth_, &Graphics::windowHeight_); FALL_ON_GL_ERROR(); glfwSetWindowSizeCallback(window_, &Graphics::OnGlfwWindowSizeCallback_); FALL_ON_GL_ERROR(); glfwMakeContextCurrent(window_); FALL_ON_GL_ERROR(); // start GLEW extension handler glewExperimental = GL_TRUE; glewInit(); FALL_ON_GL_ERROR(); // tell GL to only draw onto a pixel if the shape is closer to the viewer glEnable(GL_DEPTH_TEST); // enable depth-testing FALL_ON_GL_ERROR(); glEnable(GL_VERTEX_PROGRAM_POINT_SIZE); FALL_ON_GL_ERROR(); glDepthFunc(GL_LESS); // depth-testing interprets a smaller value as "closer" FALL_ON_GL_ERROR(); return {}; } OglFallible<> Graphics::Deinit() { // close GL context and any other GLFW resources if (!glfwInitialized_) { glfwTerminate(); glfwInitialized_ = false; } // TODO: Delete only if it has been compiled before. glDeleteProgram(starsPipeline_.programme); glDeleteVertexArrays(1, &starsPipeline_.vao); FALL_ON_GL_ERROR(); return {}; } OglFallible<> Graphics::LoadShaders() { auto vertexShader = LoadFile("the/lib/ui/shaders/vertex.glsl"); auto fragmentShader = LoadFile("the/lib/ui/shaders/fragment.glsl"); if (auto rv = starsPipeline_.shader.CompileVertex(vertexShader); !rv) return rv; if (auto rv = starsPipeline_.shader.CompileFragment(fragmentShader); !rv) return rv; if (auto rv = starsPipeline_.shader.LinkProgramme(); !rv) return rv; starsPipeline_.programme = starsPipeline_.shader.Programme(); starsPipeline_.modelToWorldMatrix = glGetUniformLocation(starsPipeline_.programme, "modelToWorldMatrix"); return {}; } OglFallible<> Graphics::Loop() { using namespace std::literals::chrono_literals; static constexpr auto perfectFps = 60u; static constexpr auto frameTimeslice = 1s / perfectFps; while (!glfwWindowShouldClose(window_)) { auto const renderingAt = std::chrono::steady_clock::now(); if (auto rv = HandleInput(); !rv) { ERROR() << "failed to handle the input: " << rv.Err(); } glViewport(0, 0, windowWidth_, windowHeight_); FALL_ON_GL_ERROR(); // Wipe the drawing surface clear. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); FALL_ON_GL_ERROR(); if (auto rv = Render(); !rv) { ERROR() << "failed to render a frame: " << rv.Err(); } // Update other events like input handling. glfwPollEvents(); FALL_ON_GL_ERROR(); // Put the stuff we've been drawing onto the display. glfwSwapBuffers(window_); FALL_ON_GL_ERROR(); auto const finishedRenderingAt = std::chrono::steady_clock::now(); auto const renderingTook = finishedRenderingAt - renderingAt; lastFrameTook_ = renderingTook; if (renderingTook < frameTimeslice) { std::this_thread::sleep_for(frameTimeslice - renderingTook); } } return {}; } void Graphics::OnGlfwWindowSizeCallback_(GLFWwindow *window, int width, int height) { glfwGetFramebufferSize(window, &width, &height); // auto const dim = std::min(width, height); windowWidth_ = width; windowHeight_ = height; // TODO: update any perspective matrices used here } void Graphics::OnGlfwErrorCallback_(int error, char const *description) { ERROR() << "GLFW: code=" << error << ": " << description; } }
30.348387
107
0.716837
deni64k
19f1c46be7f69bd09adc9b06ce7ce97646dc05ec
2,008
hpp
C++
src/mge/graphics/vertex_layout.hpp
mge-engine/mge
e7a6253f99dd640a655d9a80b94118d35c7d8139
[ "MIT" ]
null
null
null
src/mge/graphics/vertex_layout.hpp
mge-engine/mge
e7a6253f99dd640a655d9a80b94118d35c7d8139
[ "MIT" ]
91
2019-03-09T11:31:29.000Z
2022-02-27T13:06:06.000Z
src/mge/graphics/vertex_layout.hpp
mge-engine/mge
e7a6253f99dd640a655d9a80b94118d35c7d8139
[ "MIT" ]
null
null
null
// mge - Modern Game Engine // Copyright (c) 2021 by Alexander Schroeder // All rights reserved. #pragma once #include "mge/core/small_vector.hpp" #include "mge/graphics/dllexport.hpp" #include "mge/graphics/vertex_format.hpp" #include <iosfwd> #include <string_view> namespace mge { /** * A vertex layout defines the layout of some vertex buffer, and such * is a list of vertex formats. */ class MGEGRAPHICS_EXPORT vertex_layout : public mge::small_vector<vertex_format, 5> { public: /** * Constructor. */ vertex_layout(); /** * @brief Constructor. * * @param l initializers */ vertex_layout(const std::initializer_list<vertex_format>& l); /** * Copy constructor. * * @param l copied layout */ vertex_layout(const vertex_layout& l) = default; /** * Move constructor. * * @param l moved layout */ vertex_layout(vertex_layout&& l) = default; /** * Destructor. */ ~vertex_layout() = default; /** * Assignment. * * @param l assigned layout * @return @c *this */ vertex_layout& operator=(const vertex_layout& l) = default; /** * Move assignment. * * @param l moved layout * @return @c *this */ vertex_layout& operator=(vertex_layout&& l) = default; /** * Get the binary size of one element as defined by the layout. * * @return bytes needed for one element */ size_t binary_size() const; }; MGEGRAPHICS_EXPORT std::ostream& operator<<(std::ostream& os, const vertex_layout& l); MGEGRAPHICS_EXPORT mge::vertex_layout parse_vertex_layout(std::string_view sv); } // namespace mge
25.417722
73
0.530876
mge-engine
19f59e49220a691eb33f1a9ef7a49f183683a43b
9,311
hpp
C++
VG-ArmaZ/ravage_dmd_edit.chernarusredux/dmd_respawn_config.hpp
Sausag3s/VG-A3-DEV
acf1c83a98b8f6aaef4c18ae0357197ae578ce56
[ "MIT" ]
null
null
null
VG-ArmaZ/ravage_dmd_edit.chernarusredux/dmd_respawn_config.hpp
Sausag3s/VG-A3-DEV
acf1c83a98b8f6aaef4c18ae0357197ae578ce56
[ "MIT" ]
null
null
null
VG-ArmaZ/ravage_dmd_edit.chernarusredux/dmd_respawn_config.hpp
Sausag3s/VG-A3-DEV
acf1c83a98b8f6aaef4c18ae0357197ae578ce56
[ "MIT" ]
null
null
null
class CfgRoles { class Survivalist { displayName = "01 - Survivalist"; icon = "\A3\ui_f\data\igui\cfg\simpleTasks\types\run_ca.paa"; }; class Mechanic { displayName = "02 - Mechanic"; icon = "\A3\ui_f\data\igui\cfg\simpleTasks\types\repair_ca.paa"; }; class Bandit { displayName = "03 - Bandit"; icon = "\A3\ui_f\data\igui\cfg\simpleTasks\types\kill_ca.paa"; }; }; class CfgRespawnInventory { /* Survivors have 2 FAK and a Pistol Mechanics have 1 FAK, 1 Toolkit and a Pistol Bandits have 0 FAK/Toolkit. But they have a primary Weapon Create your own classes in virtual arsenal. use ctrl+shift+c to export to clipboard in cfg format. */ class Survivor01 { displayName = "Survivor 01"; icon = "\A3\Ui_f\data\GUI\Cfg\Ranks\private_gs.paa"; role = "Survivalist"; uniformClass = "U_C_Poloshirt_blue"; backpack = "B_AssaultPack_rgr"; weapons[] = {"hgun_Pistol_heavy_01_F","Throw","Put"}; magazines[] = {"11Rnd_45ACP_Mag","11Rnd_45ACP_Mag","11Rnd_45ACP_Mag","11Rnd_45ACP_Mag","Chemlight_blue","Chemlight_blue","Chemlight_green","Chemlight_green","rvg_flare","rvg_flare"}; items[] = {"FirstAidKit","FirstAidKit"}; linkedItems[] = {"H_Cap_grn","rvg_ItemMap","ItemCompass","ItemWatch"}; }; class Survivor02 { displayName = "Survivor 02"; icon = "\A3\Ui_f\data\GUI\Cfg\Ranks\private_gs.paa"; role = "Survivalist"; uniformClass = "rvg_retro_grey"; backpack = "rvg_assault"; weapons[] = {"hgun_ACPC2_F","Throw","Put"}; magazines[] = {"9Rnd_45ACP_Mag","9Rnd_45ACP_Mag","9Rnd_45ACP_Mag","9Rnd_45ACP_Mag","Chemlight_blue","Chemlight_blue","Chemlight_green","Chemlight_green","rvg_flare","rvg_flare"}; items[] = {"FirstAidKit","FirstAidKit"}; linkedItems[] = {"H_Cap_usblack","rvg_ItemMap","ItemCompass","ItemWatch"}; }; class Survivor03 { displayName = "Survivor 03"; icon = "\A3\Ui_f\data\GUI\Cfg\Ranks\private_gs.paa"; role = "Survivalist"; uniformClass = "rvg_hoodie_kabeiroi"; backpack = "rvg_assault"; weapons[] = {"hgun_Rook40_F","Throw","Put"}; magazines[] = {"16Rnd_9x21_Mag","16Rnd_9x21_Mag","16Rnd_9x21_Mag","16Rnd_9x21_Mag","Chemlight_blue","Chemlight_blue","Chemlight_green","Chemlight_green","rvg_flare","rvg_flare"}; items[] = {"FirstAidKit","FirstAidKit"}; linkedItems[] = {"H_Booniehat_khk","rvg_ItemMap","ItemCompass","ItemWatch"}; }; class Survivor04 { displayName = "Survivor 04 (APEX DLC)"; icon = "\A3\Ui_f\data\GUI\Cfg\Ranks\private_gs.paa"; role = "Survivalist"; uniformClass = "U_I_C_Soldier_Bandit_5_F"; backpack = "B_AssaultPack_tna_F"; weapons[] = {"hgun_Pistol_01_F","Throw","Put"}; magazines[] = {"10Rnd_9x21_Mag","10Rnd_9x21_Mag","10Rnd_9x21_Mag","10Rnd_9x21_Mag","Chemlight_blue","Chemlight_blue","Chemlight_green","Chemlight_green","rvg_flare","rvg_flare"}; items[] = {"FirstAidKit","FirstAidKit"}; linkedItems[] = {"H_Booniehat_tna_F","rvg_ItemMap","ItemCompass","ItemWatch"}; }; class Survivor05 { displayName = "Survivor 05 (CONTACT DLC)"; icon = "\A3\Ui_f\data\GUI\Cfg\Ranks\private_gs.paa"; role = "Survivalist"; uniformClass = "U_C_Uniform_Farmer_01_F"; backpack = "B_FieldPack_green_F"; weapons[] = {"hgun_Pistol_heavy_01_green_F","Throw","Put"}; magazines[] = {"11Rnd_45ACP_Mag","11Rnd_45ACP_Mag","11Rnd_45ACP_Mag","Chemlight_blue","Chemlight_blue","Chemlight_green","Chemlight_green","rvg_flare","rvg_flare","11Rnd_45ACP_Mag"}; items[] = {"FirstAidKit","FirstAidKit"}; linkedItems[] = {"H_Booniehat_eaf","rvg_ItemMap","ItemCompass","ItemWatch"}; }; //////////////////////////////////////////////////// class Mechanic01 { displayName = "Mechanic 01"; icon = "\A3\Ui_f\data\GUI\Cfg\Ranks\private_gs.paa"; role = "Mechanic"; uniformClass = "U_C_WorkerCoverallsBlack"; backpack = "B_FieldPack_blk"; weapons[] = {"hgun_Pistol_heavy_02_F","Throw","Put"}; magazines[] = {"6Rnd_45ACP_Cylinder","6Rnd_45ACP_Cylinder","6Rnd_45ACP_Cylinder","6Rnd_45ACP_Cylinder","Chemlight_blue","rvg_flare","rvg_flare","Chemlight_blue","Chemlight_yellow","Chemlight_yellow"}; items[] = {"FirstAidKit","ToolKit"}; linkedItems[] = {"H_Bandanna_gry","rvg_ItemMap","ItemCompass","ItemWatch"}; }; class Mechanic02 { displayName = "Mechanic 02"; icon = "\A3\Ui_f\data\GUI\Cfg\Ranks\private_gs.paa"; role = "Mechanic"; uniformClass = "U_C_Driver_3"; backpack = "B_FieldPack_cbr"; weapons[] = {"hgun_Rook40_F","Throw","Put"}; magazines[] = {"16Rnd_9x21_Mag","16Rnd_9x21_Mag","16Rnd_9x21_Mag","16Rnd_9x21_Mag","Chemlight_blue","rvg_flare","rvg_flare","Chemlight_blue","Chemlight_yellow","Chemlight_yellow"}; items[] = {"FirstAidKit","ToolKit"}; linkedItems[] = {"H_RacingHelmet_1_red_F","rvg_ItemMap","ItemCompass","ItemWatch"}; }; class Mechanic03 { displayName = "Mechanic 03"; icon = "\A3\Ui_f\data\GUI\Cfg\Ranks\private_gs.paa"; role = "Mechanic"; uniformClass = "rvg_retro_grey"; backpack = "B_FieldPack_cbr"; weapons[] = {"hgun_P07_F","Throw","Put"}; magazines[] = {"16Rnd_9x21_Mag","16Rnd_9x21_Mag","16Rnd_9x21_Mag","16Rnd_9x21_Mag","Chemlight_blue","rvg_flare","rvg_flare","Chemlight_blue","Chemlight_yellow","Chemlight_yellow"}; items[] = {"FirstAidKit","ToolKit"}; linkedItems[] = {"rvg_construction_1","rvg_ItemMap","ItemCompass","ItemWatch"}; }; class Mechanic04 { displayName = "Mechanic 04 (APEX DLC)"; icon = "\A3\Ui_f\data\GUI\Cfg\Ranks\private_gs.paa"; role = "Mechanic"; uniformClass = "U_B_GEN_Soldier_F"; backpack = "B_FieldPack_ghex_F"; weapons[] = {"hgun_Pistol_01_F","Throw","Put"}; magazines[] = {"10Rnd_9x21_Mag","10Rnd_9x21_Mag","10Rnd_9x21_Mag","10Rnd_9x21_Mag","Chemlight_blue","rvg_flare","rvg_flare","Chemlight_blue","Chemlight_yellow","Chemlight_yellow"}; items[] = {"FirstAidKit","ToolKit"}; linkedItems[] = {"H_Helmet_Skate","G_Lowprofile","rvg_ItemMap","ItemCompass","ItemWatch"}; }; class Mechanic05 { displayName = "Mechanic 05 (CONTACT DLC)"; icon = "\A3\Ui_f\data\GUI\Cfg\Ranks\private_gs.paa"; role = "Mechanic"; uniformClass = "U_O_R_Gorka_01_black_F"; backpack = "B_RadioBag_01_black_F"; weapons[] = {"hgun_Pistol_01_F","Throw","Put"}; magazines[] = {"10Rnd_9x21_Mag","10Rnd_9x21_Mag","10Rnd_9x21_Mag","10Rnd_9x21_Mag","Chemlight_blue","rvg_flare","rvg_flare","Chemlight_blue","Chemlight_yellow","Chemlight_yellow"}; items[] = {"FirstAidKit"}; linkedItems[] = {"H_Tank_eaf_F","rvg_eyeprotector","rvg_ItemMap","ItemCompass","ItemWatch"}; }; //////////////////////////////////////////////////// class Bandit01 { displayName = "Bandit 01"; icon = "\A3\Ui_f\data\GUI\Cfg\Ranks\private_gs.paa"; role = "Bandit"; uniformClass = "U_I_G_resistanceLeader_F"; backpack = "B_FieldPack_blk"; weapons[] = {"SMG_01_F","Throw","Put"}; magazines[] = {"30Rnd_45ACP_Mag_SMG_01","30Rnd_45ACP_Mag_SMG_01","30Rnd_45ACP_Mag_SMG_01","rvg_flare","rvg_flare","Chemlight_red","Chemlight_red","Chemlight_red","Chemlight_red"}; items[] = {}; linkedItems[] = {"H_ShemagOpen_khk","rvg_ItemMap","ItemCompass","ItemWatch"}; }; class Bandit02 { displayName = "Bandit 02"; icon = "\A3\Ui_f\data\GUI\Cfg\Ranks\private_gs.paa"; role = "Bandit"; uniformClass = "rvg_hoodie_bandit"; backpack = "B_FieldPack_khk"; weapons[] = {"hgun_PDW2000_F","Throw","Put"}; magazines[] = {"30Rnd_9x21_Mag","30Rnd_9x21_Mag","30Rnd_9x21_Mag","rvg_flare","rvg_flare","Chemlight_red","Chemlight_red","Chemlight_red","Chemlight_red"}; items[] = {}; linkedItems[] = {"H_ShemagOpen_tan","rvg_ItemMap","ItemCompass","ItemWatch"}; }; class Bandit03 { displayName = "Bandit 03"; icon = "\A3\Ui_f\data\GUI\Cfg\Ranks\private_gs.paa"; role = "Bandit"; uniformClass = "rvg_bandit"; backpack = "B_FieldPack_khk"; weapons[] = {"SMG_03_TR_black","Throw","Put"}; magazines[] = {"50Rnd_570x28_SMG_03","50Rnd_570x28_SMG_03","rvg_flare","rvg_flare","Chemlight_red","Chemlight_red","Chemlight_red","Chemlight_red"}; items[] = {}; linkedItems[] = {"H_Shemag_olive","rvg_ItemMap","ItemCompass","ItemWatch"}; }; class Bandit04 { displayName = "Bandit 04 (APEX DLC)"; icon = "\A3\Ui_f\data\GUI\Cfg\Ranks\private_gs.paa"; role = "Bandit"; uniformClass = "U_I_C_Soldier_Para_1_F"; backpack = "B_FieldPack_ghex_F"; weapons[] = {"SMG_05_F","Throw","Put"}; magazines[] = {"30Rnd_9x21_Mag_SMG_02","30Rnd_9x21_Mag_SMG_02","30Rnd_9x21_Mag_SMG_02","rvg_flare","rvg_flare","Chemlight_red","Chemlight_red","Chemlight_red","Chemlight_red"}; items[] = {}; linkedItems[] = {"G_Balaclava_TI_blk_F","rvg_ItemMap","ItemCompass","ItemWatch"}; }; class Bandit05 { displayName = "Bandit 05 (CONTACT DLC)"; icon = "\A3\Ui_f\data\GUI\Cfg\Ranks\private_gs.paa"; role = "Bandit"; uniformClass = "U_O_R_Gorka_01_F"; backpack = "B_FieldPack_green_F"; weapons[] = {"sgun_HunterShotgun_01_sawedoff_F","Throw","Put"}; magazines[] = {"2Rnd_12Gauge_Pellets","2Rnd_12Gauge_Pellets","2Rnd_12Gauge_Pellets","2Rnd_12Gauge_Pellets","2Rnd_12Gauge_Pellets","2Rnd_12Gauge_Pellets","rvg_flare","rvg_flare","Chemlight_red","Chemlight_red","Chemlight_red","Chemlight_red","2Rnd_12Gauge_Slug","2Rnd_12Gauge_Slug","2Rnd_12Gauge_Slug","2Rnd_12Gauge_Slug","2Rnd_12Gauge_Slug"}; items[] = {}; linkedItems[] = {"G_AirPurifyingRespirator_02_olive_F","rvg_ItemMap","ItemCompass","ItemWatch"}; }; };
41.566964
344
0.70014
Sausag3s
19f5b9f1619481b5939c8f6c59155451b873c7cd
6,666
hpp
C++
Versionen/2021_06_15/RMF/rmf_ws/install/rmf_dispenser_msgs/include/rmf_dispenser_msgs/msg/detail/dispenser_state__struct.hpp
flitzmo-hso/flitzmo_agv_control_system
99e8006920c03afbd93e4c7d38b4efff514c7069
[ "MIT" ]
null
null
null
Versionen/2021_06_15/RMF/rmf_ws/install/rmf_dispenser_msgs/include/rmf_dispenser_msgs/msg/detail/dispenser_state__struct.hpp
flitzmo-hso/flitzmo_agv_control_system
99e8006920c03afbd93e4c7d38b4efff514c7069
[ "MIT" ]
null
null
null
Versionen/2021_06_15/RMF/rmf_ws/install/rmf_dispenser_msgs/include/rmf_dispenser_msgs/msg/detail/dispenser_state__struct.hpp
flitzmo-hso/flitzmo_agv_control_system
99e8006920c03afbd93e4c7d38b4efff514c7069
[ "MIT" ]
2
2021-06-21T07:32:09.000Z
2021-08-17T03:05:38.000Z
// generated from rosidl_generator_cpp/resource/idl__struct.hpp.em // with input from rmf_dispenser_msgs:msg/DispenserState.idl // generated code does not contain a copyright notice #ifndef RMF_DISPENSER_MSGS__MSG__DETAIL__DISPENSER_STATE__STRUCT_HPP_ #define RMF_DISPENSER_MSGS__MSG__DETAIL__DISPENSER_STATE__STRUCT_HPP_ #include <rosidl_runtime_cpp/bounded_vector.hpp> #include <rosidl_runtime_cpp/message_initialization.hpp> #include <algorithm> #include <array> #include <memory> #include <string> #include <vector> // Include directives for member types // Member 'time' #include "builtin_interfaces/msg/detail/time__struct.hpp" #ifndef _WIN32 # define DEPRECATED__rmf_dispenser_msgs__msg__DispenserState __attribute__((deprecated)) #else # define DEPRECATED__rmf_dispenser_msgs__msg__DispenserState __declspec(deprecated) #endif namespace rmf_dispenser_msgs { namespace msg { // message struct template<class ContainerAllocator> struct DispenserState_ { using Type = DispenserState_<ContainerAllocator>; explicit DispenserState_(rosidl_runtime_cpp::MessageInitialization _init = rosidl_runtime_cpp::MessageInitialization::ALL) : time(_init) { if (rosidl_runtime_cpp::MessageInitialization::ALL == _init || rosidl_runtime_cpp::MessageInitialization::ZERO == _init) { this->guid = ""; this->mode = 0l; this->seconds_remaining = 0.0f; } } explicit DispenserState_(const ContainerAllocator & _alloc, rosidl_runtime_cpp::MessageInitialization _init = rosidl_runtime_cpp::MessageInitialization::ALL) : time(_alloc, _init), guid(_alloc) { if (rosidl_runtime_cpp::MessageInitialization::ALL == _init || rosidl_runtime_cpp::MessageInitialization::ZERO == _init) { this->guid = ""; this->mode = 0l; this->seconds_remaining = 0.0f; } } // field types and members using _time_type = builtin_interfaces::msg::Time_<ContainerAllocator>; _time_type time; using _guid_type = std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other>; _guid_type guid; using _mode_type = int32_t; _mode_type mode; using _request_guid_queue_type = std::vector<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other>, typename ContainerAllocator::template rebind<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other>>::other>; _request_guid_queue_type request_guid_queue; using _seconds_remaining_type = float; _seconds_remaining_type seconds_remaining; // setters for named parameter idiom Type & set__time( const builtin_interfaces::msg::Time_<ContainerAllocator> & _arg) { this->time = _arg; return *this; } Type & set__guid( const std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other> & _arg) { this->guid = _arg; return *this; } Type & set__mode( const int32_t & _arg) { this->mode = _arg; return *this; } Type & set__request_guid_queue( const std::vector<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other>, typename ContainerAllocator::template rebind<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other>>::other> & _arg) { this->request_guid_queue = _arg; return *this; } Type & set__seconds_remaining( const float & _arg) { this->seconds_remaining = _arg; return *this; } // constant declarations static constexpr int32_t IDLE = 0; static constexpr int32_t BUSY = 1; static constexpr int32_t OFFLINE = 2; // pointer types using RawPtr = rmf_dispenser_msgs::msg::DispenserState_<ContainerAllocator> *; using ConstRawPtr = const rmf_dispenser_msgs::msg::DispenserState_<ContainerAllocator> *; using SharedPtr = std::shared_ptr<rmf_dispenser_msgs::msg::DispenserState_<ContainerAllocator>>; using ConstSharedPtr = std::shared_ptr<rmf_dispenser_msgs::msg::DispenserState_<ContainerAllocator> const>; template<typename Deleter = std::default_delete< rmf_dispenser_msgs::msg::DispenserState_<ContainerAllocator>>> using UniquePtrWithDeleter = std::unique_ptr<rmf_dispenser_msgs::msg::DispenserState_<ContainerAllocator>, Deleter>; using UniquePtr = UniquePtrWithDeleter<>; template<typename Deleter = std::default_delete< rmf_dispenser_msgs::msg::DispenserState_<ContainerAllocator>>> using ConstUniquePtrWithDeleter = std::unique_ptr<rmf_dispenser_msgs::msg::DispenserState_<ContainerAllocator> const, Deleter>; using ConstUniquePtr = ConstUniquePtrWithDeleter<>; using WeakPtr = std::weak_ptr<rmf_dispenser_msgs::msg::DispenserState_<ContainerAllocator>>; using ConstWeakPtr = std::weak_ptr<rmf_dispenser_msgs::msg::DispenserState_<ContainerAllocator> const>; // pointer types similar to ROS 1, use SharedPtr / ConstSharedPtr instead // NOTE: Can't use 'using' here because GNU C++ can't parse attributes properly typedef DEPRECATED__rmf_dispenser_msgs__msg__DispenserState std::shared_ptr<rmf_dispenser_msgs::msg::DispenserState_<ContainerAllocator>> Ptr; typedef DEPRECATED__rmf_dispenser_msgs__msg__DispenserState std::shared_ptr<rmf_dispenser_msgs::msg::DispenserState_<ContainerAllocator> const> ConstPtr; // comparison operators bool operator==(const DispenserState_ & other) const { if (this->time != other.time) { return false; } if (this->guid != other.guid) { return false; } if (this->mode != other.mode) { return false; } if (this->request_guid_queue != other.request_guid_queue) { return false; } if (this->seconds_remaining != other.seconds_remaining) { return false; } return true; } bool operator!=(const DispenserState_ & other) const { return !this->operator==(other); } }; // struct DispenserState_ // alias to use template instance with default allocator using DispenserState = rmf_dispenser_msgs::msg::DispenserState_<std::allocator<void>>; // constant definitions template<typename ContainerAllocator> constexpr int32_t DispenserState_<ContainerAllocator>::IDLE; template<typename ContainerAllocator> constexpr int32_t DispenserState_<ContainerAllocator>::BUSY; template<typename ContainerAllocator> constexpr int32_t DispenserState_<ContainerAllocator>::OFFLINE; } // namespace msg } // namespace rmf_dispenser_msgs #endif // RMF_DISPENSER_MSGS__MSG__DETAIL__DISPENSER_STATE__STRUCT_HPP_
33.164179
298
0.752475
flitzmo-hso
19f92ade6aeb4f31a86bce122c2887f699d51c23
817
cpp
C++
Camp_0-2563/1007-62_CrossC.cpp
MasterIceZ/POSN_BUU
56e176fb843d7ddcee0cf4acf2bb141576c260cf
[ "MIT" ]
null
null
null
Camp_0-2563/1007-62_CrossC.cpp
MasterIceZ/POSN_BUU
56e176fb843d7ddcee0cf4acf2bb141576c260cf
[ "MIT" ]
null
null
null
Camp_0-2563/1007-62_CrossC.cpp
MasterIceZ/POSN_BUU
56e176fb843d7ddcee0cf4acf2bb141576c260cf
[ "MIT" ]
null
null
null
#include<stdio.h> #include<math.h> int main (){ int q; scanf("%d",&q); while(q--){ double x1,x2,y1,y2,r1,r2; scanf("%lf %lf %lf %lf %lf %lf",&x1,&y1,&r1,&x2,&y2,&r2); double dist = sqrt(pow(x1-x2, 2) + pow(y1-y2,2)); if(dist > r1+r2){ printf("None"); } else if(x1 == x2 && y1 == y2 && r1 == r2){ printf("More"); } else if(dist < r1 && dist+r2 == r1){ printf("One"); } else if(dist < r2 && dist+r1 == r2){ printf("One"); } else if(dist < r1 && dist+r2 < r1){ printf("None"); } else if(dist < r2 && dist+r1 < r2){ printf("None"); } else if(dist < r1+r2){ printf("More"); } else if(dist == r1+r2 || dist+r1 == r2 || dist+r2 == r1){ printf("One"); } else{ printf("None"); } printf("\n"); } return 0; }
19.452381
60
0.468788
MasterIceZ
19fb2d62999fe9d77642334f2f3fd8abff9c3aa7
1,920
hpp
C++
CXX/include/euler/utils/maps.hpp
troberson/exercises-euler
03ffafb1016d252ca297f2ab6f02552df1377496
[ "BSD-3-Clause" ]
1
2020-02-12T20:40:39.000Z
2020-02-12T20:40:39.000Z
CXX/include/euler/utils/maps.hpp
troberson/exercises-euler
03ffafb1016d252ca297f2ab6f02552df1377496
[ "BSD-3-Clause" ]
null
null
null
CXX/include/euler/utils/maps.hpp
troberson/exercises-euler
03ffafb1016d252ca297f2ab6f02552df1377496
[ "BSD-3-Clause" ]
null
null
null
/* * Project Euler - Utils - maps * Tamara Roberson <tamara.roberson@gmail.com> * Copyright (c) 2019 Tamara Roberson * * Functions for operating on maps. */ #pragma once #include <algorithm> // std::transform #include <map> // std::map #include <vector> // std::vector namespace euler::utils { /** * Get one side of a map * * @tparam Output_t the type of the elements in the output vector * @tparam Key_t the type of the keys in the input map * @tparam Value_t the type of the values in the input map * @param input a map * @param key_side get the key side (true) or the value side (false) (default: true) * @returns a vector containing the keys or values from the map */ template<typename Output_t, typename Key_t, typename Value_t> std::vector<Output_t> get_map_side(std::map<Key_t, Value_t> input, bool key_side = true) { std::vector<Output_t> result{}; result.reserve(input.size()); std::transform(input.begin(), input.end(), std::back_inserter(result), [=] (const auto& pair) { return key_side ? pair.first : pair.second; } ); return result; } /** * Get map keys * * @tparam Key_t the type of the keys in the input map * @tparam Value_t the type of the values in the input map * @param input a map * @returns a vector containing the keys from the map */ template<typename Key_t, typename Value_t> std::vector<Key_t> get_map_keys(std::map<Key_t, Value_t> input) { return get_map_side<Key_t>(input, true); } /** * Get map values * * @tparam Key_t the type of the keys in the input map * @tparam Value_t the type of the values in the input map * @param input a map * @returns a vector containing the values from the map */ template<typename Key_t, typename Value_t> std::vector<Value_t> get_map_values(std::map<Key_t, Value_t> input) { return get_map_side<Value_t>(input, false); } } // end namespace euler::utils
25.6
88
0.688021
troberson
c2011b5e74589f80dc9ead7a4baeaaac7958febe
4,901
cpp
C++
practice/misc/tg02/main.cpp
rahulsrma26/ol_codes
dc599f5b70c14229a001c5239c366ba1b990f68b
[ "MIT" ]
2
2019-03-18T16:06:10.000Z
2019-04-07T23:17:06.000Z
practice/misc/tg02/main.cpp
rahulsrma26/ol_codes
dc599f5b70c14229a001c5239c366ba1b990f68b
[ "MIT" ]
null
null
null
practice/misc/tg02/main.cpp
rahulsrma26/ol_codes
dc599f5b70c14229a001c5239c366ba1b990f68b
[ "MIT" ]
1
2019-03-18T16:06:52.000Z
2019-03-18T16:06:52.000Z
#include <iostream> #include <vector> using namespace std; void fun(vector<int>& ary) { const int n = ary.size(); if (n == 1) { cout << ary[0] << '\n'; return; } vector<vector<int>> sols(n); sols[n - 1].push_back({ary[n - 1]}); sols[n - 2].push_back({ary[n - 2]}); vector<int> maxSum(n); maxSum[n - 1] = ary[n - 1]; maxSum[n - 2] = ary[n - 2]; for (int i = n - 3; i >= 0; i--) { if (ary[i] < 0 && (ary[i] < maxSum[i + 1] || ary[i] < maxSum[i + 1])) { int maxi = maxSum[i + 1] > maxSum[i + 2] ? 1 : 2; if (maxSum[i + 1] == maxSum[i + 2]) { int l = min(sols[i + 1].size(), sols[i + 2].size()); for (int j = 0; j < l; j++) { if (sols[i + 1][j] != sols[i + 2][j]) { maxi = sols[i + 1][j] > sols[i + 2][j] ? 1 : 2; break; } } } maxSum[i] = maxSum[i + maxi]; sols[i] = sols[i + maxi]; continue; } int maxi = 2; if (i + 3 < n) { maxi = maxSum[i + 2] > maxSum[i + 3] ? 2 : 3; if (maxSum[i + 2] == maxSum[i + 3]) { int l = min(sols[i + 2].size(), sols[i + 3].size()); for (int j = 0; j < l; j++) { if (sols[i + 2][j] != sols[i + 3][j]) { maxi = sols[i + 2][j] > sols[i + 3][j] ? 2 : 3; break; } } } } if (maxSum[i + maxi] > 0 || maxSum[i + maxi] > ary[i]) { maxSum[i] = maxSum[i + maxi]; sols[i] = sols[i + maxi]; } if (ary[i] > 0 || ary[i] > maxSum[maxi]) { maxSum[i] += ary[i]; sols[i].push_back(ary[i]); } } int maxi = maxSum[0] > maxSum[1] ? 0 : 1; if (maxSum[0] == maxSum[1]) { int l = min(sols[0].size(), sols[1].size()); for (int j = 0; j < l; j++) { if (sols[0][j] != sols[1][j]) { maxi = sols[0][j] > sols[1][j] ? 0 : 1; break; } } } for (auto& x : sols[maxi]) cout << x; cout << '\n'; } // struct solution { // int sum; // int soln; // int prev; // }; // void fun1(vector<int>& ary) { // const int n = ary.size(); // if (n == 1) { // cout << ary[0] << '\n'; // return; // } // vector<solution> sol(n); // sol[n - 1] = solution{ary[n - 1], n - 1, -1}; // sol[n - 2] = solution{ary[n - 2], n - 2, -1}; // for (int i = n - 3; i >= 0; i--) { // if (ary[i] < 0) { // int maxi = sol[i + 1].sum > sol[i + 2].sum ? 1 : 2; // if (sol[i + 1].sum == sol[i + 2].sum) { // int l1 = sol[i + 1].soln, l2 = sol[i + 2].soln; // while (l1 >= 0 && l2 >= 0) { // if (ary[l1] != ary[l2]) { // maxi = ary[l1] > ary[l2] ? 1 : 2; // break; // } // l1 = sol[l1].prev; // l2 = sol[l2].prev; // } // } // sol[i] = sol[i + maxi]; // continue; // } // int maxi = 2; // if (i + 3 < n) { // maxi = sol[i + 2].sum > sol[i + 3].sum ? 2 : 3; // if (sol[i + 2].sum == sol[i + 3].sum) { // int l1 = sol[i + 2].soln, l2 = sol[i + 3].soln; // while (l1 >= 0 && l2 >= 0) { // if (ary[l1] != ary[l2]) { // maxi = ary[l1] > ary[l2] ? 2 : 3; // break; // } // l1 = sol[l1].prev; // l2 = sol[l2].prev; // } // } // } // if (sol[i + maxi].sum > 0) { // sol[i] = sol[i + maxi]; // sol[i].sum += ary[i]; // sol[i + maxi].prev = i; // } else { // sol[i] = solution{ary[i], i, -1}; // } // } // int maxi = sol[0].sum > sol[1].sum ? 0 : 1; // if (sol[0].sum == sol[1].sum) { // int l1 = sol[0].soln, l2 = sol[1].soln; // while (l1 >= 0 && l2 >= 0) { // if (ary[l1] != ary[l2]) { // maxi = ary[l1] > ary[l2] ? 0 : 1; // break; // } // l1 = sol[l1].prev; // l2 = sol[l2].prev; // } // } // for (int l = sol[maxi].soln; l >= 0; l = sol[l].prev) // cout << ary[l]; // cout << '\n'; // } int main() { ios::sync_with_stdio(false); cin.tie(0); int t; cin >> t; while (t--) { int n; cin >> n; vector<int> a(n); for (auto& x : a) cin >> x; fun(a); } }
30.253086
79
0.322791
rahulsrma26
c202972bc0bda99085172701cf0f8652a95afccf
803
cc
C++
tests/error_msg_test.cc
RobDickinson/pmemkv
9f7de0cc1bb5a31c10d2feaa8d1c12cac1ab3b68
[ "BSD-3-Clause" ]
null
null
null
tests/error_msg_test.cc
RobDickinson/pmemkv
9f7de0cc1bb5a31c10d2feaa8d1c12cac1ab3b68
[ "BSD-3-Clause" ]
4
2017-02-20T17:14:10.000Z
2017-02-20T22:36:43.000Z
tests/error_msg_test.cc
RobDickinson/pmemkv
9f7de0cc1bb5a31c10d2feaa8d1c12cac1ab3b68
[ "BSD-3-Clause" ]
null
null
null
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2021, Intel Corporation */ #include <libpmemkv.hpp> #include "unittest.hpp" static void errormsg_cleared() { pmem::kv::db kv; auto s = kv.open("non-existing name"); ASSERT_STATUS(s, pmem::kv::status::WRONG_ENGINE_NAME); auto err = pmem::kv::errormsg(); UT_ASSERT(err.size() > 0); s = kv.open("blackhole"); ASSERT_STATUS(s, pmem::kv::status::OK); std::string value; s = kv.get("Nonexisting key:", &value); ASSERT_STATUS(s, pmem::kv::status::NOT_FOUND); err = pmem::kv::errormsg(); UT_ASSERT(err == ""); UT_ASSERTeq(err.size(), 0); s = kv.open("non-existing name"); ASSERT_STATUS(s, pmem::kv::status::WRONG_ENGINE_NAME); err = pmem::kv::errormsg(); UT_ASSERT(err.size() > 0); } int main() { errormsg_cleared(); return 0; }
20.589744
55
0.666252
RobDickinson
c2052ec4ae5fbf6537be4d3eedc18131f3128272
1,587
cpp
C++
Greet-core/src/ecs/components/Camera2DComponent.cpp
Thraix/Greet-Engine
9474a4f4b88a582289fc68e7fc3e62ba2c6d0ec8
[ "Apache-2.0" ]
null
null
null
Greet-core/src/ecs/components/Camera2DComponent.cpp
Thraix/Greet-Engine
9474a4f4b88a582289fc68e7fc3e62ba2c6d0ec8
[ "Apache-2.0" ]
1
2018-03-30T18:10:37.000Z
2018-03-30T18:10:37.000Z
Greet-core/src/ecs/components/Camera2DComponent.cpp
Thraix/Greet-Engine-Port
9474a4f4b88a582289fc68e7fc3e62ba2c6d0ec8
[ "Apache-2.0" ]
null
null
null
#include "Camera2DComponent.h" #include <utils/MetaFileLoading.h> namespace Greet { Camera2DComponent::Camera2DComponent(const Mat3& viewMatrix, bool active) : active{active}, projectionMatrix{Mat3::OrthographicViewport()}, viewMatrix{viewMatrix} {} Camera2DComponent::Camera2DComponent(const MetaFileClass& metaClass) : active{MetaFileLoading::LoadBool(metaClass, "active", false)}, projectionMatrix{Mat3::OrthographicViewport()}, viewMatrix{~Mat3::TransformationMatrix( MetaFileLoading::LoadVec2f(metaClass, "position", {0, 0}), MetaFileLoading::LoadVec2f(metaClass, "scale", {1, 1}), MetaFileLoading::LoadFloat(metaClass, "rotation", 0.0f) )} {} const Mat3& Camera2DComponent::GetViewMatrix() const { return viewMatrix; } const Mat3& Camera2DComponent::GetProjectionMatrix() const { return projectionMatrix; } void Camera2DComponent::SetProjectionMatrix(const Mat3& amProjectionMatrix) { projectionMatrix = amProjectionMatrix; } void Camera2DComponent::SetViewMatrix(const Mat3& amViewMatrix) { Mat3 invMatrix = ~viewMatrix; cameraPos = Vec2f{invMatrix.columns[2]}; viewMatrix = amViewMatrix; } void Camera2DComponent::SetShaderUniforms(const Ref<Shader>& shader) const { shader->SetUniform2f("uCameraPos", cameraPos); shader->SetUniformMat3("uViewMatrix", viewMatrix); shader->SetUniformMat3("uProjectionMatrix", projectionMatrix); } void Camera2DComponent::ViewportResize(ViewportResizeEvent& event) { SetProjectionMatrix(Mat3::OrthographicViewport()); } }
32.387755
92
0.73913
Thraix
c205e9ba64539097bc96f438934a81d0af0f9983
8,419
cpp
C++
Invaders-2/src/World.cpp
dalawr32/invaders-repository
7e9cdae877296b8149c2fa12b02af0c981a72a9d
[ "CC-BY-4.0" ]
null
null
null
Invaders-2/src/World.cpp
dalawr32/invaders-repository
7e9cdae877296b8149c2fa12b02af0c981a72a9d
[ "CC-BY-4.0" ]
null
null
null
Invaders-2/src/World.cpp
dalawr32/invaders-repository
7e9cdae877296b8149c2fa12b02af0c981a72a9d
[ "CC-BY-4.0" ]
null
null
null
/** * Created by Daniel. * Contains all the information for * running the internal logic of * the game, such as spawning * enemies and moving all objects. */ #include "World.h" #include "Enemy.h" #include "Player.h" #include "Basic_Enemy.h" #include "Basic_Shooter.h" #include "Repeater.h" #include "Weapon.h" #include "Spark.h" #include "Laser_Shooter.h" #include <mutex> #include <memory> #include <iostream> #include <cmath> #include <random> #include <map> #include <sys/time.h> #include <time.h> #include <chrono> using namespace std; using namespace proj; World::World(int difficulty) { difficulty_ = difficulty; player_ = make_shared<Player>(Player(make_shared<Weapon<Bullet>>(Repeater(30, true)), 100)); init(); /*enemies_.push_back(make_shared<Basic_Enemy>(Basic_Enemy(100, movementMap_.at(0), 150, 0))); enemies_.push_back(make_shared<Basic_Shooter>(Basic_Shooter(100, 10, movementMap_.at(3), 300, 0))); enemies_.push_back(make_shared<Laser_Shooter>(Laser_Shooter(200, 10, movementMap_.at(1), 300, -50)));*/ seed_seq seed = {0, 670}; mt19937 engine(seed); } void World::init() { //This function makes an enemy move in a straight line towards and away from the player. auto vertical = [](shared_ptr<Player> player, Enemy* e) { if (e->get_Y_Speed() == 0) { e->set_Y_Speed(3); } if (e->getY() > 700) { e->set_Y_Speed(-3); } else if (e->getY() < 0) { e->set_Y_Speed(3); } }; //This function makes an enemy move in a straight line against a random point on screen. auto horizontal = [](shared_ptr<Player> player, Enemy* e) { if (e->getY() < 300) { e->set_Y_Speed(7); } else { e->set_Y_Speed(0); if (e->get_X_Speed() == 0) { e->set_X_Speed(3); } if (e->getX() > 700 - e->getWidth()) { e->set_X_Speed(-3); } else if (e->getX() < 0) { e->set_X_Speed(3); } } }; //This function makes an enemy bounce against the sides of the screen as it moves. auto bounce = [](shared_ptr<Player> player, Enemy* e) { if (e->get_Y_Speed() == 0) { e->set_Y_Speed(3); } if (e->get_X_Speed() == 0) { e->set_X_Speed(5); } if (e->getY() > 700 - e->getHeight()) { e->set_Y_Speed(-3); } else if (e->getY() < 0) { e->set_Y_Speed(3); } if (e->getX() > 700 - e->getWidth()) { e->set_X_Speed(-5); } else if (e->getX() < 0) { e->set_X_Speed(5); } }; auto watch = [](shared_ptr<Player> player, Enemy* e) { //Let the enemy approach if (e->getY() < 200) { e->set_Y_Speed(5); } else { //Enemy stops moving once its in range. e->set_Y_Speed(0); //We rotate the enemy based on whether it's aiming at the player or not. if (e->getAngle() % 360 > (int)(atan2(e->getX() + e->getWidth()/2 - player->getX() + player->getWidth()/2, player->getY() - player->getHeight()/2 - e->getY() + e->getHeight()/2) * 57.3) % 360) { e->setAngle(e->getAngle() - 1); } else if (e->getAngle() % 360 < (int)(atan2(e->getX() + e->getWidth()/2 - player->getX() + player->getWidth()/2, player->getY() + player->getHeight()/2 - e->getY() + e->getHeight()/2) * 57.3) % 360) { e->setAngle(e->getAngle() + 1); } } }; //Add the functions to the map of movement types. this->movementMap_[0]= vertical; this->movementMap_[1] = horizontal; this->movementMap_[2] = bounce; this->movementMap_[3] = watch; seed_seq widthSeed = {0, 670}; this->engine_width_ = mt19937(widthSeed); seed_seq heightSeed = {-100, 0}; engine_height_ = mt19937(heightSeed); seed_seq functionSeed = {0, 3};//this->movementMap_.size()}; engine_fun_ = mt19937(functionSeed); seed_seq typeSeed = {0, 2}; engine_type_ = mt19937(typeSeed); } void World::update() { /**Updates every bullet in the world*/ unsigned int i = 0; while (i < bullets_.size() ) { shared_ptr<Bullet> b = bullets_.at(i); b->Sprite::move_sprite(); //Determines if bullet should be removed. bool collided = false; //Check bullet against player. if (b->isColliding(*player_) && !b->isFriendly()) { player_->changeHealth(player_->getHealth() - b->getDamage()); sparks_.push_back(make_shared<Spark>(Spark(b->getX(), b->getY(), false))); collided = true; } //Check bullet against every enemy. for (shared_ptr<Enemy> enemy : enemies_) { if (b->isColliding(*enemy) && b->isFriendly()) { enemy->changeHealth(enemy->getHealth() - b->getDamage()); sparks_.push_back(make_shared<Spark>(Spark(b->getX(), b->getY(), true))); collided = true; } } if (collided || b->getX() > 700 && b->get_X_Speed() >= 0 || b->getX() < 0 && b->get_X_Speed() <= 0 || b->getY() > 700 && b->get_Y_Speed() >= 0 || b->getY() < 0 && b->get_Y_Speed() <= 0) { bullets_.erase(bullets_.begin() + i); } else { i++; } } i = 0; while (i < sparks_.size()) { shared_ptr<Spark> spark = sparks_.at(i); if (spark->shouldEnd()) { sparks_.erase(sparks_.begin() + i); } else { spark->update(); i++; } } /**Updates every enemy in the world, removing it if necessary.*/ i = 0; while(i < enemies_.size()) { shared_ptr<Enemy> e = enemies_.at(i); if (e->getHealth() <= 0) { enemies_.erase(enemies_.begin() + i); } else { e->update(player_, bullets_); i++; } } if (player_->getHealth() <= 0) { //End the game. isOver_ = true; return; } int curDifficulty = 0; for (shared_ptr<Enemy> e : enemies_) { curDifficulty += e->getDifficulty(); } if (curDifficulty < difficulty_ / 2) { shared_ptr<Enemy> newEnemy = createEnemy(difficulty_ - curDifficulty); curDifficulty += newEnemy->getDifficulty(); enemies_.push_back(newEnemy); } player_->move_sprite(); } bool World::isOver() { return isOver_; } shared_ptr<Player> World::getPlayer() noexcept { return player_; } vector<shared_ptr<Enemy>> World::getEnemies() noexcept { return enemies_; } vector<shared_ptr<Bullet>> World::getBullets() noexcept { return bullets_; } vector<shared_ptr<Spark>> World::getSparks() noexcept { return sparks_; } void World::setBullets(vector<shared_ptr<Bullet>> bullets) { this->bullets_ = bullets; } shared_ptr<Enemy> World::createEnemy(int difficulty_spike) { uniform_int_distribution<int> widthPossible(0, 670); int x = widthPossible(engine_width_); uniform_int_distribution<int> heightPossible(-100, 0); int y = heightPossible(engine_height_); uniform_int_distribution<int> possible_function(0, movementMap_.size() - 1); int fun = possible_function(engine_fun_); uniform_int_distribution<int> possible_type(0, 100); int type = possible_type(engine_type_); if (type < 50) { return make_shared<Basic_Shooter>(Basic_Shooter(30, 3, movementMap_.at(fun), x, y)); } else if (type < 80) { if (fun > movementMap_.size()/2) { return make_shared<Basic_Enemy>(Basic_Enemy(100, movementMap_.at(2), x, y)); } else { return make_shared<Basic_Enemy>(100, movementMap_.at(0), x, y); } } else { return make_shared<Laser_Shooter>(200, 30, movementMap_.at(1), x, y); } }
30.284173
121
0.530229
dalawr32
c20af5889fe0358a83bf1bd6e73f7fd364a53973
1,950
hh
C++
mcg/src/external/BSR/include/io/serialization/serial_istream.hh
mouthwater/rgb
3fafca24ecc133910923182581a2133b8568bf77
[ "BSD-2-Clause" ]
392
2015-01-14T13:19:40.000Z
2022-02-12T08:47:33.000Z
mcg/src/external/BSR/include/io/serialization/serial_istream.hh
mouthwater/rgb
3fafca24ecc133910923182581a2133b8568bf77
[ "BSD-2-Clause" ]
45
2015-02-03T12:16:10.000Z
2022-03-07T00:25:09.000Z
mcg/src/external/BSR/include/io/serialization/serial_istream.hh
mouthwater/rgb
3fafca24ecc133910923182581a2133b8568bf77
[ "BSD-2-Clause" ]
168
2015-01-05T02:29:53.000Z
2022-02-22T04:32:04.000Z
/* * Serial input stream built on top of a standard istream. */ #ifndef IO__SERIALIZATION__SERIAL_ISTREAM_HH #define IO__SERIALIZATION__SERIAL_ISTREAM_HH #include "io/serialization/serial_input_stream.hh" #include "io/streams/istream.hh" namespace io { namespace serialization { /* * Imports. */ using io::streams::istream; /* * Serial input stream built on top of a standard istream. */ class serial_istream : public serial_input_stream { public: /* * Constructor. * Attach the istream for use as input. * The istream must be ready for reading. */ explicit serial_istream(istream&); /* * Copy constructor. */ explicit serial_istream(serial_istream&); /* * Destructor. */ virtual ~serial_istream(); /* * Deserialization operators. * Read the specified data from the file stream. */ virtual serial_istream& operator>>(bool&); virtual serial_istream& operator>>(char&); virtual serial_istream& operator>>(unsigned char&); virtual serial_istream& operator>>(short&); virtual serial_istream& operator>>(unsigned short&); virtual serial_istream& operator>>(int&); virtual serial_istream& operator>>(unsigned int&); virtual serial_istream& operator>>(long&); virtual serial_istream& operator>>(unsigned long&); virtual serial_istream& operator>>(long long&); virtual serial_istream& operator>>(unsigned long long&); virtual serial_istream& operator>>(float&); virtual serial_istream& operator>>(double&); virtual serial_istream& operator>>(long double&); protected: /* * Return a value that changes under byte-reversal. * This returns the same value as serial_ostream::endian_signature(). */ static unsigned short endian_signature(); istream& _is; /* attached istream */ bool _reverse_endian; /* reverse endianness of input? */ }; } /* namespace serialization */ } /* namespace io */ #endif
26.712329
72
0.697436
mouthwater
c20fef07b2bff7ad091c3c34183a18557ed007d5
20,431
cpp
C++
graphics.cpp
vladetaStoj/DirectX_11_Framework
19b38d4b192a303a2403e7509302d2d2af7a65e5
[ "MIT" ]
null
null
null
graphics.cpp
vladetaStoj/DirectX_11_Framework
19b38d4b192a303a2403e7509302d2d2af7a65e5
[ "MIT" ]
null
null
null
graphics.cpp
vladetaStoj/DirectX_11_Framework
19b38d4b192a303a2403e7509302d2d2af7a65e5
[ "MIT" ]
null
null
null
#include "graphics.h" #include "primitives.h" using namespace std; Graphics::Graphics() { SwapChain = 0; d3d11Device = 0; d3d11DevCon = 0; renderTargetView = 0; depthStencilView = 0; depthStencilBuffer = 0; m_renderState = 0; Transparency = 0; CCWcullMode = 0; CWcullMode = 0; NoCullMode = 0; cbPerObjectBuffer = 0; Adapter = 0; d3d101Device = 0; keyedMutex11 = 0; keyedMutex10 = 0; D2DRenderTarget = 0; Brush = 0; BackBuffer11 = 0; sharedTex11 = 0; d2dVertBuffer = 0; d2dIndexBuffer = 0; d2dTexture = 0; DWriteFactory = 0; TextFormat = 0; FontTransparency = 0; textSamplerState = 0; cbPerFrameBuffer = 0; } Graphics::Graphics(const Graphics& other) { } Graphics::~Graphics() { } bool Graphics::Init(int screenWidth, int screenHeight, HWND hwnd) { m_width = screenWidth; m_height = screenHeight; //Describe our Buffer DXGI_MODE_DESC bufferDesc; ZeroMemory(&bufferDesc, sizeof(DXGI_MODE_DESC)); bufferDesc.Width = m_width; bufferDesc.Height = m_height; bufferDesc.RefreshRate.Numerator = 60; bufferDesc.RefreshRate.Denominator = 1; bufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; //Appearently, the DXGI_FORMAT_B8G8R8A8_UNORM for text rendering, but using the default DXGI_FORMAT_R8G8B8A8_UNORM works just fine too... bufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; bufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; ZeroMemory(&swapChainDesc, sizeof(DXGI_SWAP_CHAIN_DESC)); swapChainDesc.BufferDesc = bufferDesc; swapChainDesc.SampleDesc.Count = 1; swapChainDesc.SampleDesc.Quality = 0; swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapChainDesc.BufferCount = 1; swapChainDesc.OutputWindow = hwnd; //handle to current window swapChainDesc.Windowed = TRUE; swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; //D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, NULL, NULL, NULL, D3D11_SDK_VERSION, &swapChainDesc, &SwapChain, &d3d11Device, NULL, &d3d11DevCon); IDXGIFactory1 *DXGIFactory; CreateDXGIFactory1(__uuidof(IDXGIFactory1), (void**)&DXGIFactory); DXGIFactory->EnumAdapters1(0, &Adapter); DXGIFactory->Release(); //Create our Direct3D 11 Device and SwapChain////////////////////////////////////////////////////////////////////////// D3D11CreateDeviceAndSwapChain(Adapter, D3D_DRIVER_TYPE_UNKNOWN, NULL, D3D11_CREATE_DEVICE_DEBUG | D3D11_CREATE_DEVICE_BGRA_SUPPORT, NULL, NULL, D3D11_SDK_VERSION, &swapChainDesc, &SwapChain, &d3d11Device, NULL, &d3d11DevCon); //Initialize Direct2D, Direct3D 10.1, DirectWrite InitD2D_D3D101_DWrite(); //Release the Adapter interface Adapter->Release(); //Depth buffer description D3D11_TEXTURE2D_DESC depthStencilDesc; depthStencilDesc.Width = m_width; depthStencilDesc.Height = m_height; depthStencilDesc.MipLevels = 1; depthStencilDesc.ArraySize = 1; depthStencilDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; depthStencilDesc.SampleDesc.Count = 1; depthStencilDesc.SampleDesc.Quality = 0; depthStencilDesc.Usage = D3D11_USAGE_DEFAULT; depthStencilDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL; depthStencilDesc.CPUAccessFlags = 0; depthStencilDesc.MiscFlags = 0; d3d11Device->CreateTexture2D(&depthStencilDesc, NULL, &depthStencilBuffer); d3d11Device->CreateDepthStencilView(depthStencilBuffer, NULL, &depthStencilView); //MVP buffer D3D11_BUFFER_DESC cbbd; ZeroMemory(&cbbd, sizeof(D3D11_BUFFER_DESC)); cbbd.Usage = D3D11_USAGE_DEFAULT; cbbd.ByteWidth = sizeof(cbPerObject); cbbd.BindFlags = D3D11_BIND_CONSTANT_BUFFER; cbbd.CPUAccessFlags = 0; cbbd.MiscFlags = 0; d3d11Device->CreateBuffer(&cbbd, NULL, &cbPerObjectBuffer); ZeroMemory(&cbbd, sizeof(D3D11_BUFFER_DESC)); cbbd.Usage = D3D11_USAGE_DEFAULT; //IMPORTANT: Use D3D11_USAGE_DYNAMIC if something needs to be updated cbbd.ByteWidth = sizeof(cbPerFrame); cbbd.BindFlags = D3D11_BIND_CONSTANT_BUFFER; cbbd.CPUAccessFlags = 0; // IMPORTANT: THis should also be set to D3D11_CPU_ACCESS_WRITE if any data is passed from the cpu... cbbd.MiscFlags = 0; d3d11Device->CreateBuffer(&cbbd, NULL, &cbPerFrameBuffer); //Create our BackBuffer SwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (void**)&BackBuffer11); //Create our Render Target d3d11Device->CreateRenderTargetView(BackBuffer11, NULL, &renderTargetView); //BackBuffer11->Release(); //Set our Render Target d3d11DevCon->OMSetRenderTargets(1, &renderTargetView, depthStencilView); //Setup render states ZeroMemory(&m_wfdesc, sizeof(D3D11_RASTERIZER_DESC)); m_wfdesc.FillMode = D3D11_FILL_WIREFRAME; m_wfdesc.CullMode = D3D11_CULL_NONE; d3d11Device->CreateRasterizerState(&m_wfdesc, &m_renderState); //Enable wireframe rendering d3d11DevCon->RSSetState(m_renderState); return true; } void Graphics::SetupLighting() { //Setup scene lighting parameters m_light.dir = XMFLOAT3(0.25f, 0.5f, -1.0f); m_light.ambient = XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f); m_light.diffuse = XMFLOAT4(1.0f, 0.5f, 0.0f, 1.0f); } void Graphics::InitD2D_D3D101_DWrite() { D3D10CreateDevice1(Adapter, D3D10_DRIVER_TYPE_HARDWARE, NULL, D3D10_CREATE_DEVICE_DEBUG | D3D10_CREATE_DEVICE_BGRA_SUPPORT, D3D10_FEATURE_LEVEL_9_3, D3D10_1_SDK_VERSION, &d3d101Device); //Create Shared Texture that Direct3D 10.1 will render on////////////////////////////////////////////////////////////// D3D11_TEXTURE2D_DESC sharedTexDesc; ZeroMemory(&sharedTexDesc, sizeof(sharedTexDesc)); sharedTexDesc.Width = m_width; sharedTexDesc.Height = m_height; sharedTexDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; sharedTexDesc.MipLevels = 1; sharedTexDesc.ArraySize = 1; sharedTexDesc.SampleDesc.Count = 1; sharedTexDesc.Usage = D3D11_USAGE_DEFAULT; sharedTexDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET; sharedTexDesc.MiscFlags = D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX; d3d11Device->CreateTexture2D(&sharedTexDesc, NULL, &sharedTex11); // Get the keyed mutex for the shared texture (for D3D11)/////////////////////////////////////////////////////////////// sharedTex11->QueryInterface(__uuidof(IDXGIKeyedMutex), (void**)&keyedMutex11); // Get the shared handle needed to open the shared texture in D3D10.1/////////////////////////////////////////////////// IDXGIResource *sharedResource10; HANDLE sharedHandle10; sharedTex11->QueryInterface(__uuidof(IDXGIResource), (void**)&sharedResource10); sharedResource10->GetSharedHandle(&sharedHandle10); sharedResource10->Release(); // Open the surface for the shared texture in D3D10.1/////////////////////////////////////////////////////////////////// IDXGISurface1 *sharedSurface10; d3d101Device->OpenSharedResource(sharedHandle10, __uuidof(IDXGISurface1), (void**)(&sharedSurface10)); sharedSurface10->QueryInterface(__uuidof(IDXGIKeyedMutex), (void**)&keyedMutex10); // Create D2D factory/////////////////////////////////////////////////////////////////////////////////////////////////// ID2D1Factory *D2DFactory; D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, __uuidof(ID2D1Factory), (void**)&D2DFactory); D2D1_RENDER_TARGET_PROPERTIES renderTargetProperties; ZeroMemory(&renderTargetProperties, sizeof(renderTargetProperties)); renderTargetProperties.type = D2D1_RENDER_TARGET_TYPE_HARDWARE; renderTargetProperties.pixelFormat = D2D1::PixelFormat(DXGI_FORMAT_UNKNOWN, D2D1_ALPHA_MODE_PREMULTIPLIED); D2DFactory->CreateDxgiSurfaceRenderTarget(sharedSurface10, &renderTargetProperties, &D2DRenderTarget); sharedSurface10->Release(); D2DFactory->Release(); // Create a solid color brush to draw something with D2DRenderTarget->CreateSolidColorBrush(D2D1::ColorF(1.0f, 1.0f, 0.0f, 1.0f), &Brush); //DirectWrite/////////////////////////////////////////////////////////////////////////////////////////////////////////// DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, __uuidof(IDWriteFactory), reinterpret_cast<IUnknown**>(&DWriteFactory)); DWriteFactory->CreateTextFormat( L"Script", NULL, DWRITE_FONT_WEIGHT_REGULAR, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL, 24.0f, L"en-us", &TextFormat ); TextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING); TextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR); d3d101Device->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_POINTLIST); } void Graphics::InitD2DScreenTexture() { Vertex_XYZTEX v[] = { // Front Face Vertex_XYZTEX(-1.0f, -1.0f, -1.0f, 0.0f, 1.0f), Vertex_XYZTEX(-1.0f, 1.0f, -1.0f, 0.0f, 0.0f), Vertex_XYZTEX(1.0f, 1.0f, -1.0f, 1.0f, 0.0f), Vertex_XYZTEX(1.0f, -1.0f, -1.0f, 1.0f, 1.0f), }; DWORD indices[] = { // Front Face 0, 1, 2, 0, 2, 3, }; D3D11_BUFFER_DESC indexBufferDesc; ZeroMemory(&indexBufferDesc, sizeof(indexBufferDesc)); indexBufferDesc.Usage = D3D11_USAGE_DEFAULT; indexBufferDesc.ByteWidth = sizeof(DWORD) * 2 * 3; indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER; indexBufferDesc.CPUAccessFlags = 0; indexBufferDesc.MiscFlags = 0; D3D11_SUBRESOURCE_DATA iinitData; iinitData.pSysMem = indices; d3d11Device->CreateBuffer(&indexBufferDesc, &iinitData, &d2dIndexBuffer); D3D11_BUFFER_DESC vertexBufferDesc; ZeroMemory(&vertexBufferDesc, sizeof(vertexBufferDesc)); vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT; vertexBufferDesc.ByteWidth = sizeof(Vertex_XYZTEX) * 4; vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; vertexBufferDesc.CPUAccessFlags = 0; vertexBufferDesc.MiscFlags = 0; D3D11_SUBRESOURCE_DATA vertexBufferData; ZeroMemory(&vertexBufferData, sizeof(vertexBufferData)); vertexBufferData.pSysMem = v; d3d11Device->CreateBuffer(&vertexBufferDesc, &vertexBufferData, &d2dVertBuffer); //Create A shader resource view from the texture D2D will render to, //So we can use it to texture a square which overlays our scene d3d11Device->CreateShaderResourceView(sharedTex11, NULL, &d2dTexture); //Set the d2d Index buffer d3d11DevCon->IASetIndexBuffer(d2dIndexBuffer, DXGI_FORMAT_R32_UINT, 0); //Set the d2d vertex buffer UINT stride = sizeof(Vertex_XYZTEX); UINT offset = 0; d3d11DevCon->IASetVertexBuffers(0, 1, &d2dVertBuffer, &stride, &offset); } void Graphics::RenderText(wstring text, float top, float left, float right, float bottom) { //Release the D3D 11 Device keyedMutex11->ReleaseSync(0); //Use D3D10.1 device keyedMutex10->AcquireSync(0, 5); //Draw D2D content D2DRenderTarget->BeginDraw(); //Clear D2D Background D2DRenderTarget->Clear(D2D1::ColorF(0.0f, 0.0f, 0.0f, 0.0f)); //Create our string wostringstream printString; printString << text; printText = printString.str(); //Set the Font Color D2D1_COLOR_F FontColor = D2D1::ColorF(1.0f, 1.0f, 1.0f, 1.0f); //Set the brush color D2D will use to draw with Brush->SetColor(FontColor); //Create the D2D Render Area D2D1_RECT_F layoutRect = D2D1::RectF(0, 0, right, bottom); //Draw the Text D2DRenderTarget->DrawText( printText.c_str(), wcslen(printText.c_str()), TextFormat, layoutRect, Brush ); D2DRenderTarget->EndDraw(); //Release the D3D10.1 Device keyedMutex10->ReleaseSync(1); //Use the D3D11 Device keyedMutex11->AcquireSync(1, 5); //Set the blend state for D2D render target texture objects d3d11DevCon->OMSetBlendState(FontTransparency, NULL, 0xffffffff); XMMATRIX wvp = XMMatrixIdentity(); cbPerObjAttributes.WVP = XMMatrixTranspose(wvp); cbPerObjAttributes.World = XMMatrixTranspose(wvp); d3d11DevCon->UpdateSubresource(cbPerObjectBuffer, 0, NULL, &cbPerObjAttributes, 0, 0); d3d11DevCon->VSSetConstantBuffers(0, 1, &cbPerObjectBuffer); d3d11DevCon->PSSetShaderResources(0, 1, &d2dTexture); d3d11DevCon->PSSetSamplers(0, 1, &textSamplerState); d3d11DevCon->DrawIndexed(6, 0, 0); } void Graphics::RenderText(ID3D11PixelShader* pixelShader, wstring text, int timerInfo, float top, float left, float right, float bottom) { //Release the D3D 11 Device keyedMutex11->ReleaseSync(0); //Use D3D10.1 device keyedMutex10->AcquireSync(0, 5); //Draw D2D content D2DRenderTarget->BeginDraw(); //Clear D2D Background D2DRenderTarget->Clear(D2D1::ColorF(0.0f, 0.0f, 0.0f, 0.0f)); //Create our string wostringstream printString; printString << text; wostringstream infoString; infoString << timerInfo; wostringstream infoString2; double mfps = 1.0 / timerInfo; infoString2 << mfps; printText = printString.str() + infoString.str() + L", " + infoString2.str(); //Set the Font Color D2D1_COLOR_F FontColor = D2D1::ColorF(1.0f, 1.0f, 1.0f, 1.0f); //Set the brush color D2D will use to draw with Brush->SetColor(FontColor); //Create the D2D Render Area D2D1_RECT_F layoutRect = D2D1::RectF(0, 0, right, bottom); //Draw the Text D2DRenderTarget->DrawText( printText.c_str(), wcslen(printText.c_str()), TextFormat, layoutRect, Brush ); D2DRenderTarget->EndDraw(); //Release the D3D10.1 Device keyedMutex10->ReleaseSync(1); //Use the D3D11 Device keyedMutex11->AcquireSync(1, 5); //Set the blend state for D2D render target texture objects d3d11DevCon->OMSetBlendState(FontTransparency, NULL, 0xffffffff); d3d11DevCon->PSSetShader(pixelShader, 0, 0); XMMATRIX wvp = XMMatrixIdentity(); cbPerObjAttributes.WVP = XMMatrixTranspose(wvp); cbPerObjAttributes.World = XMMatrixTranspose(wvp); d3d11DevCon->UpdateSubresource(cbPerObjectBuffer, 0, NULL, &cbPerObjAttributes, 0, 0); d3d11DevCon->VSSetConstantBuffers(0, 1, &cbPerObjectBuffer); d3d11DevCon->PSSetShaderResources(0, 1, &d2dTexture); d3d11DevCon->PSSetSamplers(0, 1, &textSamplerState); d3d11DevCon->DrawIndexed(6, 0, 0); } void Graphics::ChangeRenderState(int renderState) { //Add additional render state changes as required (e.g., culling on/off) switch (renderState) { case 0: ZeroMemory(&m_wfdesc, sizeof(D3D11_RASTERIZER_DESC)); m_wfdesc.FillMode = D3D11_FILL_SOLID; m_wfdesc.CullMode = D3D11_CULL_NONE; d3d11Device->CreateRasterizerState(&m_wfdesc, &m_renderState); d3d11DevCon->RSSetState(m_renderState); //cout << "Render stated changed to: D3D11_FILL_SOLID" << endl; break; case 1: ZeroMemory(&m_wfdesc, sizeof(D3D11_RASTERIZER_DESC)); m_wfdesc.FillMode = D3D11_FILL_WIREFRAME; m_wfdesc.CullMode = D3D11_CULL_NONE; d3d11Device->CreateRasterizerState(&m_wfdesc, &m_renderState); d3d11DevCon->RSSetState(m_renderState); //cout << "Render stated changed to: D3D11_FILL_WIREFRAME" << endl; break; default: //cout << "Invald render stated set" << endl; break; } } void Graphics::SetupAuxRenderStates() { //First set blending on D3D11_BLEND_DESC blendDesc; ZeroMemory(&blendDesc, sizeof(blendDesc)); D3D11_RENDER_TARGET_BLEND_DESC rtbd; ZeroMemory(&rtbd, sizeof(rtbd)); rtbd.BlendEnable = true; rtbd.SrcBlend = D3D11_BLEND_SRC_COLOR; rtbd.DestBlend = D3D11_BLEND_BLEND_FACTOR; //D3D11_BLEND_BLEND_FACTOR is default, or D3D11_BLEND_INV_SRC_ALPHA if text needs to be rendered specifically (though also works fine with the former parameter...so not sure why the later is needed for text rendering) rtbd.BlendOp = D3D11_BLEND_OP_ADD; rtbd.SrcBlendAlpha = D3D11_BLEND_ONE; rtbd.DestBlendAlpha = D3D11_BLEND_ZERO; rtbd.BlendOpAlpha = D3D11_BLEND_OP_ADD; rtbd.RenderTargetWriteMask = D3D10_COLOR_WRITE_ENABLE_ALL; blendDesc.AlphaToCoverageEnable = false; blendDesc.RenderTarget[0] = rtbd; d3d11Device->CreateBlendState(&blendDesc, &Transparency); //Texture for font rendering D3D11_SAMPLER_DESC sampDesc; ZeroMemory(&sampDesc, sizeof(sampDesc)); sampDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; //Experiment with no or point filtering for old-skool look sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; sampDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; sampDesc.ComparisonFunc = D3D11_COMPARISON_NEVER; sampDesc.MinLOD = 0; sampDesc.MaxLOD = D3D11_FLOAT32_MAX; //Create the Sample State d3d11Device->CreateSamplerState(&sampDesc, &textSamplerState); //Then set back culling on D3D11_RASTERIZER_DESC cmdesc; ZeroMemory(&cmdesc, sizeof(D3D11_RASTERIZER_DESC)); cmdesc.FillMode = D3D11_FILL_SOLID; cmdesc.CullMode = D3D11_CULL_BACK; cmdesc.FrontCounterClockwise = true; d3d11Device->CreateRasterizerState(&cmdesc, &CCWcullMode); cmdesc.FrontCounterClockwise = false; d3d11Device->CreateRasterizerState(&cmdesc, &CWcullMode); //No culling D3D11_RASTERIZER_DESC rastDescNoCull; ZeroMemory(&rastDescNoCull, sizeof(D3D11_RASTERIZER_DESC)); rastDescNoCull.FillMode = D3D11_FILL_SOLID; cmdesc.CullMode = D3D11_CULL_NONE; d3d11Device->CreateRasterizerState(&rastDescNoCull, &NoCullMode); } void Graphics::Shutdown() { SwapChain->Release(); d3d11Device->Release(); d3d11DevCon->Release(); depthStencilView->Release(); depthStencilBuffer->Release(); cbPerObjectBuffer->Release(); m_renderState->Release(); Transparency->Release(); CCWcullMode->Release(); CWcullMode->Release(); NoCullMode->Release(); Adapter->Release(); d3d101Device->Release(); keyedMutex11->Release(); keyedMutex10->Release(); D2DRenderTarget->Release(); Brush->Release(); BackBuffer11->Release(); sharedTex11->Release(); d2dVertBuffer->Release(); d2dIndexBuffer->Release(); d2dTexture->Release(); DWriteFactory->Release(); TextFormat->Release(); FontTransparency->Release(); textSamplerState->Release(); cbPerFrameBuffer->Release(); } void Graphics::UpdateCB(XMMATRIX wvp, XMMATRIX world) { cbPerObjAttributes.WVP = XMMatrixTranspose(wvp); cbPerObjAttributes.World = XMMatrixTranspose(world); d3d11DevCon->UpdateSubresource(cbPerObjectBuffer, 0, NULL, &cbPerObjAttributes, 0, 0); d3d11DevCon->VSSetConstantBuffers(0, 1, &cbPerObjectBuffer); } //Note: Blending operations only work if they are called called in-between FrameBegin() and FrameEnd() functions bool Graphics::FrameRenderAllOpaque() { d3d11DevCon->OMSetBlendState(0, 0, 0xffffffff); return true; } bool Graphics::FrameRenderAllBlending(float r, float g, float b, float a) { float blendFactor[] = { r, g, b, a }; d3d11DevCon->OMSetBlendState(Transparency, blendFactor, 0xffffffff); return true; } bool Graphics::FrameBegin() { RenderBegin(); return true; } bool Graphics::FrameBegin(float r, float g, float b, float a, bool clear) { RenderBegin(r, g, b, a, clear); return true; } bool Graphics::FrameEnd() { RenderEnd(); return true; } void Graphics::UpdateLighting() { //Default directional lighting constbuffPerFramePS.light = m_light; constbuffPerFramePS.useLight = 1; d3d11DevCon->UpdateSubresource(cbPerFrameBuffer, 0, NULL, &constbuffPerFramePS, 0, 0); d3d11DevCon->PSSetConstantBuffers(0, 1, &cbPerFrameBuffer); //This has to be updated using the mapped resource method (D3D11_MAPPED_SUBRESOURCE) //D3D11_MAPPED_SUBRESOURCE mappedResource; // Lock the constant buffer so it can be written to. //d3d11DevCon->Map(cbPerFrameBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource); // Get a pointer to the data in the constant buffer. //cbPerFrame* dataPtr = (cbPerFrame*)mappedResource.pData; //memcpy(dataPtr, constbuffPerFramePS, sizeof(cbPerFrame)); // Unlock the constant buffer. //d3d11DevCon->Unmap(cbPerFrameBuffer, 0); } bool Graphics::RenderBegin() { D3DXCOLOR bgColor(0.2f, 0.2f, 0.2f, 1.0f); d3d11DevCon->ClearRenderTargetView(renderTargetView, bgColor); d3d11DevCon->ClearDepthStencilView(depthStencilView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0); return true; } bool Graphics::RenderBegin(float r, float g, float b, float a, bool clear) { D3DXCOLOR bgColor(r, g, b, a); if (clear) { d3d11DevCon->ClearRenderTargetView(renderTargetView, bgColor); d3d11DevCon->ClearDepthStencilView(depthStencilView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0); } return true; } bool Graphics::RenderEnd() { //Present the backbuffer to the screen SwapChain->Present(0, 0); return true; }
30.769578
262
0.72713
vladetaStoj
c2129085e7d639b1e224f7381cb4bf0e437252a2
5,073
cpp
C++
rtl/eclrtl/rtlcommon.cpp
davidarcher/HPCC-Platform
fa817ab9ea7d8154ac08bc780ce9ce673f3e51e3
[ "Apache-2.0" ]
null
null
null
rtl/eclrtl/rtlcommon.cpp
davidarcher/HPCC-Platform
fa817ab9ea7d8154ac08bc780ce9ce673f3e51e3
[ "Apache-2.0" ]
null
null
null
rtl/eclrtl/rtlcommon.cpp
davidarcher/HPCC-Platform
fa817ab9ea7d8154ac08bc780ce9ce673f3e51e3
[ "Apache-2.0" ]
3
2021-05-02T17:01:57.000Z
2021-05-02T17:02:28.000Z
#include "jiface.hpp" #include "jbuff.hpp" #include "jstring.hpp" #include "junicode.hpp" #include "rtlcommon.hpp" CThorContiguousRowBuffer::CThorContiguousRowBuffer(ISerialStream * _in) : in(_in) { buffer = NULL; maxOffset = 0; readOffset = 0; } void CThorContiguousRowBuffer::doRead(size32_t len, void * ptr) { ensureAccessible(readOffset + len); memcpy(ptr, buffer+readOffset, len); readOffset += len; } size32_t CThorContiguousRowBuffer::read(size32_t len, void * ptr) { doRead(len, ptr); return len; } size32_t CThorContiguousRowBuffer::readSize() { size32_t value; doRead(sizeof(value), &value); return value; } size32_t CThorContiguousRowBuffer::readPackedInt(void * ptr) { size32_t size = sizePackedInt(); doRead(size, ptr); return size; } size32_t CThorContiguousRowBuffer::readUtf8(ARowBuilder & target, size32_t offset, size32_t fixedSize, size32_t len) { if (len == 0) return 0; size32_t size = sizeUtf8(len); byte * self = target.ensureCapacity(fixedSize + size, NULL); doRead(size, self+offset); return size; } size32_t CThorContiguousRowBuffer::readVStr(ARowBuilder & target, size32_t offset, size32_t fixedSize) { size32_t size = sizeVStr(); byte * self = target.ensureCapacity(fixedSize + size, NULL); doRead(size, self+offset); return size; } size32_t CThorContiguousRowBuffer::readVUni(ARowBuilder & target, size32_t offset, size32_t fixedSize) { size32_t size = sizeVUni(); byte * self = target.ensureCapacity(fixedSize + size, NULL); doRead(size, self+offset); return size; } size32_t CThorContiguousRowBuffer::sizePackedInt() { ensureAccessible(readOffset+1); return rtlGetPackedSizeFromFirst(buffer[readOffset]); } size32_t CThorContiguousRowBuffer::sizeUtf8(size32_t len) { if (len == 0) return 0; //The len is the number of utf characters, size depends on which characters are included. size32_t nextOffset = readOffset; while (len) { ensureAccessible(nextOffset+1); for (;nextOffset < maxOffset;) { nextOffset += readUtf8Size(buffer+nextOffset); // This function only accesses the first byte if (--len == 0) break; } } return nextOffset - readOffset; } size32_t CThorContiguousRowBuffer::sizeVStr() { size32_t nextOffset = readOffset; for (;;) { ensureAccessible(nextOffset+1); for (; nextOffset < maxOffset; nextOffset++) { if (buffer[nextOffset] == 0) return (nextOffset + 1) - readOffset; } } } size32_t CThorContiguousRowBuffer::sizeVUni() { size32_t nextOffset = readOffset; const size32_t sizeOfUChar = 2; for (;;) { ensureAccessible(nextOffset+sizeOfUChar); for (; nextOffset+1 < maxOffset; nextOffset += sizeOfUChar) { if (buffer[nextOffset] == 0 && buffer[nextOffset+1] == 0) return (nextOffset + sizeOfUChar) - readOffset; } } } void CThorContiguousRowBuffer::reportReadFail() { throwUnexpected(); } const byte * CThorContiguousRowBuffer::peek(size32_t maxSize) { if (maxSize+readOffset > maxOffset) doPeek(maxSize+readOffset); return buffer + readOffset; } offset_t CThorContiguousRowBuffer::beginNested() { size32_t len = readSize(); //Currently nested datasets are readahead by skipping the number of bytes in the datasets, rather than calling //beginNested(). If this function was ever called from readAhead() then it would need to call noteStartChild() //so that the self pointer is correct for the child rows return len+readOffset; } bool CThorContiguousRowBuffer::finishedNested(offset_t & endPos) { //See note above, if this was ever called from readAhead() then it would need to call noteFinishChild() and noteStartChild() if incomplete; return readOffset >= endPos; } void CThorContiguousRowBuffer::skip(size32_t size) { ensureAccessible(readOffset+size); readOffset += size; } void CThorContiguousRowBuffer::skipPackedInt() { size32_t size = sizePackedInt(); ensureAccessible(readOffset+size); readOffset += size; } void CThorContiguousRowBuffer::skipUtf8(size32_t len) { size32_t size = sizeUtf8(len); ensureAccessible(readOffset+size); readOffset += size; } void CThorContiguousRowBuffer::skipVStr() { size32_t size = sizeVStr(); ensureAccessible(readOffset+size); readOffset += size; } void CThorContiguousRowBuffer::skipVUni() { size32_t size = sizeVUni(); ensureAccessible(readOffset+size); readOffset += size; } const byte * CThorContiguousRowBuffer::querySelf() { if (maxOffset == 0) doPeek(0); if (childStartOffsets.ordinality()) return buffer + childStartOffsets.tos(); return buffer; } void CThorContiguousRowBuffer::noteStartChild() { childStartOffsets.append(readOffset); } void CThorContiguousRowBuffer::noteFinishChild() { childStartOffsets.pop(); }
24.272727
143
0.685196
davidarcher
c2146d653943a65008d6d88a20225c0a46d258f7
1,200
cpp
C++
RaychelEngine/src/Raychel/Engine/Interface/Camera.cpp
Weckyy702/RaychelCPU
a372ac0dfa3339cac19b06b11ec916ae275b67c0
[ "MIT" ]
4
2020-12-07T21:57:14.000Z
2021-12-06T10:39:18.000Z
RaychelEngine/src/Raychel/Engine/Interface/Camera.cpp
Weckyy702/RaychelCPU
a372ac0dfa3339cac19b06b11ec916ae275b67c0
[ "MIT" ]
null
null
null
RaychelEngine/src/Raychel/Engine/Interface/Camera.cpp
Weckyy702/RaychelCPU
a372ac0dfa3339cac19b06b11ec916ae275b67c0
[ "MIT" ]
2
2021-04-08T12:05:03.000Z
2021-12-06T09:23:32.000Z
#include "Raychel/Engine/Interface/Camera.h" namespace Raychel { vec3 Camera::forward() const noexcept { return normalize(g_forward * transform_.rotation); } vec3 Camera::up() const noexcept { return normalize(g_up * transform_.rotation); } vec3 Camera::right() const noexcept { return normalize(g_right * transform_.rotation); } void Camera::setRoll(float a) noexcept { transform_.rotation = Quaternion(forward(), a); } void Camera::setPitch(float a) noexcept { transform_.rotation = Quaternion(right(), a); } void Camera::setYaw(float a) noexcept { transform_.rotation = Quaternion(up(), a); } Quaternion Camera::updateRoll(float da) noexcept { transform_.rotation *= Quaternion(forward(), da); return transform_.rotation; } Quaternion Camera::updatePitch(float da) noexcept { transform_.rotation *= Quaternion(right(), da); return transform_.rotation; } Quaternion Camera::updateYaw(float da) noexcept { transform_.rotation *= Quaternion(up(), da); return transform_.rotation; } }
21.818182
58
0.6225
Weckyy702
c21b102e27678318ad8c8c568eca51682b1def63
19,535
cpp
C++
CollyraEngine/CollyraEngine/M_Scene.cpp
Collyra-Modding-Guild/CollyraEngine
c6c99160995dc2ed28a058df353f13d6ce8c3af4
[ "MIT" ]
null
null
null
CollyraEngine/CollyraEngine/M_Scene.cpp
Collyra-Modding-Guild/CollyraEngine
c6c99160995dc2ed28a058df353f13d6ce8c3af4
[ "MIT" ]
null
null
null
CollyraEngine/CollyraEngine/M_Scene.cpp
Collyra-Modding-Guild/CollyraEngine
c6c99160995dc2ed28a058df353f13d6ce8c3af4
[ "MIT" ]
null
null
null
#include "M_Scene.h" #include "GameObject.h" #include "p2Defs.h" #include <stack> #include <map> #include "Component.h" #include "C_Mesh.h" #include "C_Transform.h" #include "C_Material.h" #include "C_Camera.h" #include "C_Script.h" #include "Application.h" #include "M_Camera3D.h" #include "M_UIManager.h" #include "M_Renderer3D.h" #include "SceneLoader.h" #include "M_FileManager.h" #include "M_Resources.h" #include "Timer.h" #include "R_Resource.h" #include "R_Scene.h" #include "R_Material.h" #include "OpenGL.h" M_Scene::M_Scene(MODULE_TYPE type, bool startEnabled) : Module(type, startEnabled), focusedGameObject(nullptr), currentScene(nullptr), playedScene(0), savedScenePath() {} M_Scene::~M_Scene() {} bool M_Scene::Awake() { randomGenerator = LCG::LCG(); currentScene = (R_Scene*)App->resources->CreateResource(R_TYPE::SCENE); currentScene->referenceCount++; savedScenePath = currentScene->GetLibraryPath(); currentScene->root = new GameObject(DEFAULT_SCENE_NAME); currentScene->root->CreateComponent(COMPONENT_TYPE::TRANSFORM); currentScene->root->SetUid(0); SetSceneName(DEFAULT_SCENE_NAME); GameObject* camera = App->scene->CreateGameObject("Camera"); camera->CreateComponent(COMPONENT_TYPE::CAMERA); return true; } bool M_Scene::Start() { uint defaultSceneId = App->resources->LoadDefaultScene(); if (defaultSceneId != 0) { App->resources->RequestResource(defaultSceneId); } return true; } updateStatus M_Scene::Update(float dt) { std::stack<GameObject*> stack; GameObject* currNode = nullptr; if (currentScene->root == nullptr) { LOG("Root node did not exist!"); return UPDATE_STOP; } stack.push(currentScene->root); while (!stack.empty()) { currNode = stack.top(); stack.pop(); if (currNode != nullptr) { currNode->Update(dt); } else continue; int childNum = currNode->children.size(); for (int i = 0; i < childNum; i++) { stack.push(currNode->children[i]); } } return UPDATE_CONTINUE; } updateStatus M_Scene::PostUpdate(float dt) { std::stack<GameObject*> stack; GameObject* currNode = nullptr; if (currentScene->root == nullptr) { LOG("Root node did not exist!"); return UPDATE_STOP; } stack.push(currentScene->root); while (!stack.empty()) { currNode = stack.top(); stack.pop(); if (currNode != nullptr) { currNode->PostUpdate(dt); } else continue; if (currNode->SchedueledToDelte() == true) { DeleteGameObject(currNode); break; } int childNum = currNode->children.size(); for (int i = 0; i < childNum; i++) { stack.push(currNode->children[i]); } int checkCulling = 0; for (int i = 0; i < cameras.size(); i++) { C_Camera* currentCam = cameras[i]; if (CameraCuling(currNode, cameras[i])) checkCulling++; } if (App->camera->GetCamera()) { if (CameraCuling(currNode, App->camera->GetCamera())) checkCulling++; } if (currNode->GetComponent<C_Mesh>() != nullptr) { if (checkCulling > 0) { currNode->GetComponent<C_Mesh>()->SetActive(true); } else { currNode->GetComponent<C_Mesh>()->SetActive(false); } } } return UPDATE_CONTINUE; } updateStatus M_Scene::Draw(bool* drawState) { std::stack<GameObject*> stack; GameObject* currNode = nullptr; if (currentScene->root == nullptr) { LOG("Root node did not exist!"); return UPDATE_STOP; } stack.push(currentScene->root); while (!stack.empty()) { currNode = stack.top(); stack.pop(); if (currNode != nullptr && currNode->IsActive()) { DrawGameObject(currNode, drawState); } else continue; int childNum = currNode->children.size(); for (int i = 0; i < childNum; i++) { stack.push(currNode->children[i]); } } return UPDATE_CONTINUE; } updateStatus M_Scene::PreDraw(bool* drawState) { if (drawState[OUTLINE] == false) { if (focusedGameObject != nullptr) { C_Mesh* mesh = focusedGameObject->GetComponent<C_Mesh>(); C_Transform* transform = focusedGameObject->GetComponent<C_Transform>(); if ((mesh != nullptr && mesh->IsActive() == true) && transform != nullptr) { mesh->DrawOutline(transform->GetTGlobalTransform()); } } } else { std::stack<GameObject*> stack; GameObject* currNode = nullptr; if (currentScene->root == nullptr) { LOG("Root node did not exist!"); return UPDATE_STOP; } stack.push(currentScene->root); while (!stack.empty()) { currNode = stack.top(); stack.pop(); if (currNode != nullptr && currNode->IsActive()) { C_Mesh* mesh = currNode->GetComponent<C_Mesh>(); C_Transform* transform = currNode->GetComponent<C_Transform>(); if ((mesh != nullptr && mesh->IsActive() == true) && transform != nullptr) { mesh->DrawOutline(transform->GetTGlobalTransform()); } } else continue; int childNum = currNode->children.size(); for (int i = 0; i < childNum; i++) { stack.push(currNode->children[i]); } } } return UPDATE_CONTINUE; } bool M_Scene::CleanUp() { //RELEASE(currentScene->root); currentScene = nullptr; focusedGameObject = nullptr; cameras.clear(); allScriptComponents.clear(); return true; } GameObject* M_Scene::CreateGameObject(std::string name, GameObject* parent) { if (parent == nullptr) parent = currentScene->root; if (name == "") { name = "Empty GameObject"; } CheckSiblingsName(parent, name); GameObject* newGameObject = new GameObject(name); parent->children.push_back(newGameObject); newGameObject->SetParent(parent); newGameObject->SetUid(GenerateId()); newGameObject->CreateComponent(COMPONENT_TYPE::TRANSFORM); return newGameObject; } void M_Scene::ResetScene() { if (currentScene == nullptr) return; App->uiManager->SetFocusedGameObject(-1); focusedGameObject = nullptr; for (int i = 0; i < currentScene->root->children.size(); i++) { RELEASE(currentScene->root->children[i]); } currentScene->root->children.clear(); currentScene->root->SetName(DEFAULT_SCENE_NAME); } uint M_Scene::SaveScene() { App->physFS->DeleteFileIn(savedScenePath.c_str()); savedScenePath = currentScene->GetLibraryPath(); return App->resources->SaveResource(currentScene, "", false); } uint32 M_Scene::GenerateId() { return randomGenerator.Int(); } GameObject* M_Scene::GetRoot() { return currentScene->root; } std::string M_Scene::GetSceneName() const { return currentScene->root->GetName(); } void M_Scene::SetSceneName(const char* newName) { currentScene->root->SetName(newName); currentScene->SetName(newName); currentScene->SetLibraryPath(App->physFS->GetExtensionFolderLibraryFromType(R_TYPE::SCENE).append(currentScene->GetName().append(App->physFS->GetInternalExtensionFromType(R_TYPE::SCENE)))); savedScenePath = currentScene->GetLibraryPath(); } R_Scene* M_Scene::GetSceneResource() const { return currentScene; } void M_Scene::SetSceneResource(R_Scene* newScene) { currentScene->SetUid(newScene->GetUid()); } void M_Scene::ResoucesUpdated(std::map<uint, bool>* updatedId) { std::stack<GameObject*> stack; GameObject* currNode = nullptr; if (currentScene->root == nullptr) { LOG("Root node did not exist!"); return; } stack.push(currentScene->root); while (!stack.empty()) { currNode = stack.top(); stack.pop(); if (currNode != nullptr) { currNode->ResourcesUpdated(updatedId); } else continue; int childNum = currNode->children.size(); for (int i = 0; i < childNum; i++) { stack.push(currNode->children[i]); } } return; } void M_Scene::SetResourceToGameObject(uint resourceId, R_TYPE rType, GameObject* setTo) { if (setTo == nullptr) { setTo = focusedGameObject; if (setTo == nullptr) { LOG("You need to have a GameObject selected!!!"); return; } } switch (rType) { case R_TYPE::TEXTURE: { C_Material* cmp = setTo->GetComponent<C_Material>(); if (cmp == nullptr) { cmp = (C_Material*)setTo->CreateComponent(COMPONENT_TYPE::MATERIAL); } uint myResourceId = cmp->GetResourceId(); R_Material* myResource = nullptr; //No material loaded, let's create one if (myResourceId == 0) { myResourceId = App->resources->CreateResource(R_TYPE::MATERIAL)->GetUid(); cmp->SetResourceId(myResourceId); } myResource = cmp->GetResourcePointer(); myResource->SetTextureResourceId(resourceId); } break; case R_TYPE::MATERIAL: { C_Material* cmp = setTo->GetComponent<C_Material>(); if (cmp == nullptr) { cmp = (C_Material*)setTo->CreateComponent(COMPONENT_TYPE::MATERIAL); } cmp->SetResourceId(resourceId); } break; case R_TYPE::MESH: { C_Mesh* cmp = setTo->GetComponent<C_Mesh>(); if (cmp == nullptr) { cmp = (C_Mesh*)setTo->CreateComponent(COMPONENT_TYPE::MESH); } cmp->SetResourceId(resourceId); } break; default: break; } } void M_Scene::GenerateNewScene() { if (currentScene != nullptr) { ResetScene(); App->resources->UnloadResource(currentScene->GetUid()); } currentScene->SetUid(GenerateId()); SetSceneName(DEFAULT_SCENE_NAME); savedScenePath = currentScene->GetLibraryPath(); GameObject* camera = App->scene->CreateGameObject("Camera"); camera->CreateComponent(COMPONENT_TYPE::CAMERA); } void M_Scene::PreHotReload() { allScriptComponents = GetAllComponents<C_Script>(); for (int i = 0; i < allScriptComponents.size(); i++) { allScriptComponents[i]->SaveReflectableVariables(); allScriptComponents[i]->SaveSerilizableVariables(); allScriptComponents[i]->DeleteObjectData(false); } } void M_Scene::PostrHotReload() { for (int i = 0; i < allScriptComponents.size(); i++) { allScriptComponents[i]->GenerateObjectData(); allScriptComponents[i]->LoadReflectableVariables(); allScriptComponents[i]->LoadSerilizableVariables(); } } void M_Scene::CheckSiblingsName(GameObject* parent, std::string& myName) { uint siblingSameName = 0; for (int i = 0; i < parent->children.size(); i++) { std::size_t found = parent->children[i]->GetName().find(myName); if (found != std::string::npos) siblingSameName++; } if (siblingSameName > 0) { char str[10]; sprintf_s(str, 10, "%i", siblingSameName); std::string number = str; myName += " (" + number + ")"; } } void M_Scene::DrawGameObject(GameObject* gameObject, bool* drawState) { C_Mesh* mesh = gameObject->GetComponent<C_Mesh>(); C_Transform* transform = gameObject->GetComponent<C_Transform>(); C_Material* material = gameObject->GetComponent<C_Material>(); C_Camera* camera = gameObject->GetComponent<C_Camera>(); if ((mesh != nullptr && mesh->IsActive() == true) && transform != nullptr) { if (material != nullptr && material->IsActive() == true) { mesh->Render(drawState, transform->GetTGlobalTransform(), (int)material->GetTexture(), material->GetColor()); } else { mesh->Render(drawState, transform->GetTGlobalTransform()); } } if (transform != nullptr && drawState[BOUNDING_BOX]) DrawBoundingBox(gameObject); if (camera != nullptr && drawState[FRUSTUM]) DrawFrustum(gameObject); if (drawState[MOUSE_RAY]) DrawMouseRay(&App->camera->ray); } void M_Scene::DrawBoundingBox(GameObject* gameObject) { glDisable(GL_LIGHTING); glBegin(GL_LINES); glLineWidth(2.0f); glColor4f(1.0f, 0.0f, 1.0f, 1.0f); for (uint i = 0; i < gameObject->GetGameObjectAABB().NumEdges(); i++) { glVertex3f(gameObject->GetGameObjectAABB().Edge(i).a.x, gameObject->GetGameObjectAABB().Edge(i).a.y, gameObject->GetGameObjectAABB().Edge(i).a.z); glVertex3f(gameObject->GetGameObjectAABB().Edge(i).b.x, gameObject->GetGameObjectAABB().Edge(i).b.y, gameObject->GetGameObjectAABB().Edge(i).b.z); } glEnd(); glEnable(GL_LIGHTING); } void M_Scene::DrawFrustum(GameObject* gameObject) { glDisable(GL_LIGHTING); glBegin(GL_LINES); glLineWidth(2.0f); glColor4f(1.0f, 0.0f, 0.0f, 1.0f); Frustum frustum = gameObject->GetComponent<C_Camera>()->frustum; for (uint i = 0; i < frustum.NumEdges(); i++) { glVertex3f(frustum.Edge(i).a.x, frustum.Edge(i).a.y, frustum.Edge(i).a.z); glVertex3f(frustum.Edge(i).b.x, frustum.Edge(i).b.y, frustum.Edge(i).b.z); } glEnd(); glEnable(GL_LIGHTING); } void M_Scene::DrawMouseRay(LineSegment* mouseRay) { glDisable(GL_LIGHTING); glBegin(GL_LINES); glLineWidth(2.0f); glColor4f(1.0f, 0.0f, 1.0f, 1.0f); glVertex3f(mouseRay->a.x, mouseRay->a.y, mouseRay->a.z); glVertex3f(mouseRay->b.x, mouseRay->b.x, mouseRay->b.z); glEnd(); glEnable(GL_LIGHTING); } GameObject* M_Scene::GetGameObject(unsigned int id) { std::stack<GameObject*> stack; GameObject* currNode = nullptr; if (currentScene->root == nullptr) { LOG("Root node did not exist!"); return nullptr; } stack.push(currentScene->root); while (!stack.empty()) { currNode = stack.top(); stack.pop(); if (currNode->GetUid() == id) { return currNode; } int childNum = currNode->children.size(); for (int i = 0; i < childNum; i++) { stack.push(currNode->children[i]); } } return nullptr; } template<typename T> std::vector<T*> M_Scene::GetAllComponents() { std::vector<GameObject*> allGameObjects = GetAllGameobjects(); std::vector<T*> ret; for (int i = 0; i < allGameObjects.size(); i++) { const std::vector<Component*>* currentComponents = allGameObjects[i]->GetAllComponents(); for (int y = 0; y < currentComponents->size(); y++) { Component* currComponent = currentComponents->at(y); T* c = dynamic_cast<T*>(currComponent); if (c != nullptr) ret.push_back(c); } } return ret; } GameObject* M_Scene::GetGameObject(std::string name) { std::stack<GameObject*> stack; GameObject* currNode = nullptr; if (currentScene->root == nullptr) { LOG("Root node did not exist!"); return nullptr; } stack.push(currentScene->root); while (!stack.empty()) { currNode = stack.top(); stack.pop(); if (currNode->GetName() == name) { return currNode; } int childNum = currNode->children.size(); for (int i = 0; i < childNum; i++) { stack.push(currNode->children[i]); } } return nullptr; } std::vector<GameObject*> M_Scene::GetAllGameobjects() { std::vector<GameObject*> allGO; std::stack<GameObject*> stack; GameObject* currNode = nullptr; if (currentScene->root == nullptr) { LOG("Root node did not exist!"); return allGO; } stack.push(currentScene->root); while (!stack.empty()) { currNode = stack.top(); stack.pop(); allGO.push_back(currNode); int childNum = currNode->children.size(); for (int i = 0; i < childNum; i++) { stack.push(currNode->children[i]); } } return allGO; } bool M_Scene::DeleteGameObject(unsigned int id) { std::stack<GameObject*> stack; GameObject* currNode = nullptr; GameObject* toDelete = nullptr; if (currentScene->root == nullptr) { LOG("Root node did not exist!"); return UPDATE_STOP; } stack.push(currentScene->root); while (!stack.empty()) { currNode = stack.top(); stack.pop(); if (currNode->GetUid() == id) { toDelete = currNode; break; } int childNum = currNode->children.size(); for (int i = 0; i < childNum; i++) { stack.push(currNode->children[i]); } } bool ret = false; if (toDelete != nullptr) ret = DeleteGameObject(toDelete); return ret; } bool M_Scene::DeleteGameObject(GameObject* gameObject) { if (gameObject == nullptr) return false; NotifyGameObjectDeath(gameObject); RELEASE(gameObject); return true; } bool M_Scene::NotifyGameObjectDeath(GameObject* gameObject) { if (focusedGameObject == gameObject) focusedGameObject = nullptr; //Notify the UI that a GameObject has been destroyed--------- App->uiManager->GameObjectDestroyed(gameObject->GetUid()); //Notify the Parent that his child is going to die----------- if (gameObject->GetParent() != nullptr) gameObject->GetParent()->NotifyChildDeath(gameObject); return true; } void M_Scene::DeleteCamera(Component* component) { for (int i = 0; i < cameras.size(); i++) { if (cameras[i] == component) { App->renderer3D->CameraDied(cameras[i]); cameras.erase(cameras.begin() + i); } } } void M_Scene::StartGameObjects() { std::stack<GameObject*> stack; GameObject* currNode = nullptr; GameObject* toDelete = nullptr; if (currentScene->root == nullptr) { LOG("Root node did not exist!"); return; } stack.push(currentScene->root); while (!stack.empty()) { currNode = stack.top(); stack.pop(); currNode->Start(); int childNum = currNode->children.size(); for (int i = 0; i < childNum; i++) { stack.push(currNode->children[i]); } } } void M_Scene::OnClickFocusGameObject(const LineSegment& mouseRay) { std::stack<GameObject*> stack; std::map<float, GameObject*> inRay; GameObject* currNode = nullptr; if (currentScene->root == nullptr) { LOG("Root node did not exist!"); return; } stack.push(currentScene->root); while (!stack.empty()) { currNode = stack.top(); stack.pop(); float nearHit = 0.0f; float farHit = 0.0f; if (mouseRay.Intersects(currNode->GetGameObjectAABB(), nearHit, farHit) && currNode->GetUid() != ROOT_ID) { inRay.insert({ nearHit, currNode }); } int childNum = currNode->children.size(); for (int i = 0; i < childNum; i++) { stack.push(currNode->children[i]); } } std::map<float, GameObject*>::iterator iterator = inRay.begin(); for (int i = 0; i < inRay.size(); i++) { C_Mesh* mesh = iterator->second->GetComponent<C_Mesh>(); if (mesh != nullptr) { C_Transform* transform = iterator->second->GetComponent<C_Transform>(); LineSegment localRay = mouseRay; localRay.Transform(transform->GetGlobalTransform().Inverted()); std::vector<uint>* indices = mesh->GetIndices(); std::vector<float3>* vertices = mesh->GetVertices(); for (uint j = 0; j < mesh->GetIndicesSize() - 2; j++) { uint indexA = indices->at(j); uint indexB = indices->at(j + 1); uint indexC = indices->at(j + 2); vec verticeA(vertices->at(indexA)); vec verticeB(vertices->at(indexB)); vec verticeC(vertices->at(indexC)); Triangle meshTriangle(verticeA, verticeB, verticeC); if (localRay.Intersects(meshTriangle, nullptr, nullptr)) { App->uiManager->SetFocusedGameObject(iterator->second->GetUid()); return; } } } else { App->uiManager->SetFocusedGameObject(iterator->second->GetUid()); return; } iterator++; } App->uiManager->SetFocusedGameObject(-1); } bool M_Scene::CameraCuling(GameObject* current, C_Camera* myCam) { if (current->GetComponent<C_Mesh>() != nullptr && myCam->IsCulling() && myCam->frustum.ContainsAABBVertices(current->GetGameObjectAABB())) { return true; } else if (current->GetComponent<C_Mesh>() != nullptr && myCam->IsCulling()) { return false; } return false; } void M_Scene::Play() { if (App->uiManager->GetPlayCam() != nullptr) { App->gameClock->Start(); App->StartPlayMode(); App->renderer3D->SetPlayCam(App->uiManager->GetPlayCam()); } else LOG("A cam needs to be selected to start the scene!"); } updateStatus M_Scene::StartPlayMode() { SaveScene(); playedScene = this->GetSceneResource()->GetUid(); StartGameObjects(); return UPDATE_CONTINUE; } void M_Scene::Stop() { App->gameClock->Stop(); App->resources->LoadResource(playedScene); App->EndPlayMode(); } updateStatus M_Scene::StopPlayMode() { App->renderer3D->SetPlayCam(nullptr); return UPDATE_CONTINUE; } void M_Scene::Pause() { App->gameClock->Pause(); } void M_Scene::Resume() { App->gameClock->Resume(); } void M_Scene::Tick() { App->gameClock->Tick(true); }
19.772267
190
0.675557
Collyra-Modding-Guild
c22760fb1eaa3adbebe0a488774ba4de8a0f5b12
253
cpp
C++
codeforces/38A.cpp
Shisir/Online-Judge
e58c32eeb7ca18a19cc2a83ef016f9c3b124370a
[ "MIT" ]
null
null
null
codeforces/38A.cpp
Shisir/Online-Judge
e58c32eeb7ca18a19cc2a83ef016f9c3b124370a
[ "MIT" ]
null
null
null
codeforces/38A.cpp
Shisir/Online-Judge
e58c32eeb7ca18a19cc2a83ef016f9c3b124370a
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int arr[101]; int main() { int n,a,b,sum=0; scanf("%d",&n); for(int i=2; i<=n; i++) scanf("%d",&arr[i]); scanf("%d%d",&a,&b); for(int i=a+1; i<=b; i++)sum+=arr[i]; return printf("%d\n",sum ), 0; }
16.866667
45
0.525692
Shisir
c230eeb723c8e61bcc87afc39c6722f8e09f021d
1,466
hpp
C++
include/tkn/sky.hpp
nyorain/tokonoma
b3a4264ef4f9f40487c2f3280812bf7513b914bb
[ "MIT" ]
23
2019-07-11T14:47:39.000Z
2021-12-24T09:56:24.000Z
include/tkn/sky.hpp
nyorain/tokonoma
b3a4264ef4f9f40487c2f3280812bf7513b914bb
[ "MIT" ]
null
null
null
include/tkn/sky.hpp
nyorain/tokonoma
b3a4264ef4f9f40487c2f3280812bf7513b914bb
[ "MIT" ]
4
2021-04-06T18:20:43.000Z
2022-01-15T09:20:45.000Z
#pragma once #include <array> #include <vector> #include <tkn/types.hpp> // Utility for the hosek-wilkie sky model. The model was modified // to use a preetham-like zenith darkening and transitions to black // when the sky is below the horizon (the original model assumed // the sun above the horizon). // Can evaluate the model or bake tables that allow fast evaluation // on the gpu with just a single texture sample. // Unless otherwise specified, all color values are XYZ coordinates. namespace tkn::hosekSky { constexpr auto up = Vec3f{0, 1, 0}; struct Configuration { std::array<std::array<float, 9>, 3> coeffs; Vec3f radiance; // overall average radiance }; struct TableEntry { Vec3f f; Vec3f g; float h; Vec3f fh; }; struct Table { static constexpr auto numLevels = 8u; static constexpr auto numEntries = 64u; Vec3f f[numLevels][numEntries]; Vec3f g[numLevels][numEntries]; float h[numLevels][numEntries]; Vec3f fh[numLevels][numEntries]; }; struct Sky { Configuration config; Vec3f groundAlbedo; float turbidity; Vec3f toSun; }; Configuration bakeConfiguration(float turbidity, Vec3f ground, Vec3f toSun); Vec3f eval(const Configuration&, float cosTheta, float gamma, float cosGamma); Table generateTable(const Sky& sky); Vec3f eval(const Sky& sky, const Table&, Vec3f dir, float roughness); // Vec3f sunRadianceRGB(float cosTheta, float turbidity); // Vec3f sunIrradianceRGB(float cosTheta, float turbidity); } // namespace tkn
25.719298
78
0.749659
nyorain
ea4b4dcb3fb9241a65953d6a1362b41837b9c777
526
cpp
C++
src/duke/engine/rendering/ShaderConstants.cpp
hradec/duke
efacf7139cd1d7c2cd2f5127079721bd263dda50
[ "MIT" ]
51
2015-01-07T18:36:39.000Z
2021-11-30T15:24:44.000Z
src/duke/engine/rendering/ShaderConstants.cpp
virneo/duke
efacf7139cd1d7c2cd2f5127079721bd263dda50
[ "MIT" ]
1
2015-01-08T10:48:43.000Z
2015-02-11T19:32:14.000Z
src/duke/engine/rendering/ShaderConstants.cpp
virneo/duke
efacf7139cd1d7c2cd2f5127079721bd263dda50
[ "MIT" ]
18
2015-05-11T12:43:37.000Z
2019-11-29T11:15:41.000Z
#include "ShaderConstants.hpp" namespace duke { namespace shader { const char gTextureSampler[] = "gTextureSampler"; const char gViewport[] = "gViewport"; const char gImage[] = "gImage"; const char gPan[] = "gPan"; const char gPanAndChar[] = "gPanAndChar"; const char gZoom[] = "gZoom"; const char gAlpha[] = "gAlpha"; const char gExposure[] = "gExposure"; const char gGamma[] = "gGamma"; const char gShowChannel[] = "gShowChannel"; const char gSolidColor[] = "gSolidColor"; } /* namespace shader */ } /* namespace duke */
26.3
49
0.69962
hradec
ea4d95543b02650f0bc8968753c4cb5885e59d11
6,203
cpp
C++
NPSVisor/SVisor/svisor/source/D_Wait.cpp
NPaolini/NPS_OpenSource
0c7da066b02b57ce282a1903a3901a563d04a28f
[ "Unlicense" ]
null
null
null
NPSVisor/SVisor/svisor/source/D_Wait.cpp
NPaolini/NPS_OpenSource
0c7da066b02b57ce282a1903a3901a563d04a28f
[ "Unlicense" ]
null
null
null
NPSVisor/SVisor/svisor/source/D_Wait.cpp
NPaolini/NPS_OpenSource
0c7da066b02b57ce282a1903a3901a563d04a28f
[ "Unlicense" ]
null
null
null
//--------- d_wait.cpp ------------------------------------------------------- //---------------------------------------------------------------------------- #include "precHeader.h" //---------------------------------------------------------------------------- #include "d_wait.h" #include "p_base.h" #include "ptraspbitmap.h" #include "PTextPanel.h" //---------------------------------------------------------------------------- POINT operator +(const POINT& pt1, const POINT& pt2) { POINT pt = { pt1.x + pt2.x, pt1.y + pt2.y }; return pt; } //---------------------------------------------------------------------------- #define DIM_BALL 9 //#define DIM_BALL 14 #define DX (-(DIM_BALL / 2)) #define DY (-(DIM_BALL / 2)) #define POFFS(x, y) { (x) + DX, (y) + DY } #if (DIM_BALL < 10) #define OFFS_Y 10 #else #define OFFS_Y DIM_BALL #endif #define Y1 56 #define Y2 40 #define Y3 22 #define OFFS_SUB (Y3 - OFFS_Y) #define OFFS_ADD (Y3 + OFFS_Y) static const POINT howMove1[] = { POFFS(40,Y1), POFFS(52,Y1), POFFS(64,Y1), POFFS(76,Y1), POFFS(63,Y2), POFFS(50,Y3), POFFS(62,Y3), POFFS(74,Y3), POFFS(87,Y3), POFFS(97,Y3), }; static const POINT howMove2[] = { POFFS(80,OFFS_SUB), POFFS(90,OFFS_SUB), POFFS(94,OFFS_ADD), POFFS(104,OFFS_ADD) }; //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- enum tDir { LEFT, RIGHT }; //---------------------------------------------------------------------------- TD_Wait::TD_Wait(LPCTSTR msg, PWin* parent, uint resId, HINSTANCE hinstance) : baseClass(parent, resId, hinstance), Msg(msg), count(0), dir(LEFT) { ball = new PBitmap(IDB_BALL, getHInstance()); // bmp = new PBitmap(IDB_BKG_WAIT, getHInstance()); POINT pt = howMove1[0]; for(int i = 0; i < SIZE_A(tbmp); ++i) { tbmp[i] = new PTraspBitmap(this, ball, pt); if(i) tbmp[i]->setEnable(false); } } //---------------------------------------------------------------------------- TD_Wait::~TD_Wait() { destroy(); for(int i = 0; i < SIZE_A(tbmp); ++i) delete tbmp[i]; delete ball; } //---------------------------------------------------------------------------- #define OFFS_Y_GEN 5 bool TD_Wait::create() { Pt.x = -1; if(!baseClass::create()) return false; // SetDlgItemText(*this, IDC_STATICTEXT_WAIT, Msg); // ShowWindow(GetDlgItem(*this, IDC_STATICTEXT_WAIT), SW_HIDE); PBitmap bmp(IDB_BKG_WAIT, getHInstance()); PRect r; GetClientRect(*this, r); SIZE sz = bmp.getSize(); Pt.x = (r.Width() - sz.cx) / 2; Pt.y = OFFS_Y_GEN; POINT pt = Pt + howMove1[0]; tbmp[0]->moveToSimple(pt); SetTimer(*this, 100, 100, 0); InvalidateRect(*this, 0, true); return true; } //---------------------------------------------------------------------------- LRESULT TD_Wait::windowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { switch(message) { case WM_DESTROY: KillTimer(hwnd, 100); break; #define USE_MEMDC #ifdef USE_MEMDC case WM_ERASEBKGND: return 1; #endif case WM_PAINT: if(GetUpdateRect(hwnd, 0, 0)) { PAINTSTRUCT ps; HDC hdc = BeginPaint(hwnd, &ps); if(!hdc) { EndPaint(hwnd, &ps); break; } #ifdef USE_MEMDC PRect r; GetClientRect(*this, r); if(r.Width() && r.Height()) { HBITMAP hBmpWork = CreateCompatibleBitmap(hdc, r.Width(), r.Height()); if(hBmpWork) { HDC mdcWork = CreateCompatibleDC(hdc); HGDIOBJ oldObjWork = SelectObject(mdcWork, hBmpWork); COLORREF bkg = GetSysColor(COLOR_BTNFACE); HBRUSH br = CreateSolidBrush(bkg); FillRect(mdcWork, r, br); DeleteObject(br); evPaint(mdcWork); BitBlt(hdc, r.left, r.top, r.Width(), r.Height(), mdcWork, r.left, r.top, SRCCOPY); SelectObject(mdcWork, oldObjWork); DeleteDC(mdcWork); DeleteObject(hBmpWork); } } #else evPaint(hdc); #endif EndPaint(hwnd, &ps); } while(false); return 0; /* case WM_PAINT: do { PAINTSTRUCT ps; HDC hdc = BeginPaint(*this, &ps); evPaint(hdc); EndPaint(*this, &ps); } while(false); return 0; // break; */ case WM_TIMER: if(evTimer(wParam)) return 0; break; } return baseClass::windowProc(hwnd, message, wParam, lParam); } //---------------------------------------------------------------------------- void TD_Wait::evPaint(HDC hdc) { if(Pt.x < 0 || !hdc) return; #if 1 PBitmap bmp(IDB_BKG_WAIT, getHInstance()); PTraspBitmap bkg(this, &bmp, Pt); bkg.Draw(hdc); #endif for(int i = 0; i < SIZE_A(tbmp); ++i) tbmp[i]->Draw(hdc); PRect rect; GetClientRect(*this, rect); rect.top = rect.bottom - 22; PTextFixedPanel Text(Msg, rect, (HFONT)GetStockObject(DEFAULT_GUI_FONT), RGB(0, 0, 127), PPanel::NO, 0, PTextPanel::NO3D); Text.setAlign(TA_CENTER); Text.setVAlign(DT_CENTER); Text.draw(hdc); } //---------------------------------------------------------------------------- bool TD_Wait::evTimer(uint idTimer) { // if(true) if(100 != idTimer) return false; if(SIZE_A(howMove1) - 2 == count) { for(int i = 1; i < SIZE_A(tbmp); ++i) { tbmp[i]->setEnable(true); POINT pt = howMove2[(i - 1) * 2] + Pt; tbmp[i]->moveToSimple(pt); } } else if(SIZE_A(howMove1) - 2 < count) { for(int i = 1; i < SIZE_A(tbmp); ++i) { POINT pt = howMove2[(i - 1) * 2 + 1] + Pt; tbmp[i]->moveToSimple(pt); } } else if(SIZE_A(howMove1) - 3 == count) { for(int i = 1; i < SIZE_A(tbmp); ++i) { tbmp[i]->setEnable(false); } } POINT pt = howMove1[count] + Pt; tbmp[0]->moveToSimple(pt); if(LEFT == dir) ++count; else --count; if(SIZE_A(howMove1) == count) { dir = RIGHT; count -= 2; // --count; } else if(count < 0) { dir = LEFT; count += 2; // ++count; } InvalidateRect(*this, 0, 0); return true; }
25.953975
124
0.482992
NPaolini
ea4e9e1b585af2bdbed9114638ad9b4c58417e04
3,223
cpp
C++
Source/Analyzer/WfAnalyzer_CheckScope_DuplicatedSymbol.cpp
vczh2/Workflow
7ad7d53927ee66ae1df7d68b35e185ce9edcfcf1
[ "RSA-MD" ]
1
2018-10-17T16:00:38.000Z
2018-10-17T16:00:38.000Z
Source/Analyzer/WfAnalyzer_CheckScope_DuplicatedSymbol.cpp
vczh2/Workflow
7ad7d53927ee66ae1df7d68b35e185ce9edcfcf1
[ "RSA-MD" ]
null
null
null
Source/Analyzer/WfAnalyzer_CheckScope_DuplicatedSymbol.cpp
vczh2/Workflow
7ad7d53927ee66ae1df7d68b35e185ce9edcfcf1
[ "RSA-MD" ]
null
null
null
#include "WfAnalyzer.h" namespace vl { namespace workflow { namespace analyzer { using namespace collections; /*********************************************************************** CheckScopes_DuplicatedSymbol ***********************************************************************/ bool CheckScopes_DuplicatedSymbol(WfLexicalScopeManager* manager) { vint errorCount = manager->errors.Count(); FOREACH(Ptr<WfLexicalScope>, scope, manager->nodeScopes.Values()) { if (!manager->checkedScopes_DuplicatedSymbol.Contains(scope.Obj())) { manager->checkedScopes_DuplicatedSymbol.Add(scope.Obj()); for (vint i = 0; i < scope->symbols.Count(); i++) { const auto& symbols = scope->symbols.GetByIndex(i); if (symbols.Count() > 1) { if (!scope->ownerNode.Cast<WfModule>() && !scope->ownerNode.Cast<WfNamespaceDeclaration>()) { if (symbols.Count() > 1) { FOREACH(Ptr<WfLexicalSymbol>, symbol, From(symbols)) { if (auto decl = symbol->creatorNode.Cast<WfDeclaration>()) { if (!decl.Cast<WfFunctionDeclaration>()) { manager->errors.Add(WfErrors::DuplicatedSymbol(decl.Obj(), symbol)); } } else if (auto arg = symbol->creatorNode.Cast<WfFunctionArgument>()) { manager->errors.Add(WfErrors::DuplicatedSymbol(arg.Obj(), symbol)); } else if (auto stat = symbol->creatorNode.Cast<WfStatement>()) { manager->errors.Add(WfErrors::DuplicatedSymbol(stat.Obj(), symbol)); } else if (auto expr = symbol->creatorNode.Cast<WfExpression>()) { manager->errors.Add(WfErrors::DuplicatedSymbol(expr.Obj(), symbol)); } else if (auto input = symbol->creatorNode.Cast<WfStateInput>()) { if (symbols.Count() == 2) { // Ignore the generated function from the state input auto methodSymbol = symbols[1 - symbols.IndexOf(symbol.Obj())]; auto funcDecl = methodSymbol->creatorNode.Cast<WfFunctionDeclaration>(); vint index = manager->declarationMemberInfos.Keys().IndexOf(funcDecl.Obj()); if (index != -1) { auto methodInfo = manager->declarationMemberInfos.Values()[index]; if (manager->stateInputMethods[input.Obj()].Obj() == methodInfo.Obj()) { goto NO_ERROR; } } } manager->errors.Add(WfErrors::DuplicatedSymbol(input.Obj(), symbol)); NO_ERROR:; } else if (auto state = symbol->creatorNode.Cast<WfStateDeclaration>()) { manager->errors.Add(WfErrors::DuplicatedSymbol(state.Obj(), symbol)); } else if (auto sarg = symbol->creatorNode.Cast<WfStateSwitchArgument>()) { manager->errors.Add(WfErrors::DuplicatedSymbol(sarg.Obj(), symbol)); } } } } } } } } return errorCount == manager->errors.Count(); } } } }
34.287234
99
0.530872
vczh2
ea4fc20bd01161d9343ff5b423394a5386703cf1
1,771
cpp
C++
codes/HDU/hdu1298.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
codes/HDU/hdu1298.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
codes/HDU/hdu1298.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int maxn = 100005; const int maxm = 105; const int sigma_size = 26; const char dir[15][10] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; struct Tire { int sz, g[maxn][sigma_size], val[maxn]; void init(); int idx(char ch); void insert(char *s, int x); }T; int N, Q, c[maxm]; char ans[maxm][maxm], w[maxm], r[maxm]; void dfs (int d, int u) { if (d) { if (T.val[u] > c[d]) { c[d] = T.val[u]; strncpy(ans[d], r, d); } } if (w[d] == 0 || w[d] == '1') return; int x = w[d] - '0'; for (int i = 0; dir[x][i]; i++) { int v = dir[x][i] - 'a'; if (T.g[u][v] == 0) continue; r[d] = dir[x][i]; dfs(d + 1, T.g[u][v]); } } int main () { int cas; scanf("%d", &cas); for (int kcas = 1; kcas <= cas; kcas++) { T.init(); scanf("%d", &N); int x; for (int i = 0; i < N; i++) { scanf("%s%d", w, &x); T.insert(w, x); } printf("Scenario #%d:\n", kcas); scanf("%d", &Q); for (int i = 0; i < Q; i++) { scanf("%s", w); memset(c, 0, sizeof(c)); dfs(0, 0); for (int x = 1; w[x-1] != '1'; x++) { // printf("<%c> %d:", w[x], c[x]); if (c[x] == 0) printf("MANUALLY\n"); else { for (int j = 0; j < x; j++) printf("%c", ans[x][j]); printf("\n"); } } printf("\n"); } printf("\n"); } return 0; } void Tire::init() { sz = 1; val[0] = 0; memset(g[0], 0, sizeof(g[0])); } int Tire::idx(char ch) { return ch - 'a'; } void Tire::insert(char* s, int x) { int u = 0, n = strlen(s); for (int i = 0; i < n; i++) { int v = idx(s[i]); if (g[u][v] == 0) { g[u][v] = sz; memset(g[sz], 0, sizeof(g[sz])); val[sz++] = 0; } u = g[u][v]; val[u] += x; } }
16.866667
92
0.455675
JeraKrs
ea50b4403bade635f9e36de4236f8e74defa4081
2,986
cc
C++
src/CaliceDetectorConstruction.cc
lopezzot/CALICESiWTB
ea1cdbdad0c406d27065e350bf6cc2256aceedfa
[ "MIT" ]
1
2022-02-28T16:19:38.000Z
2022-02-28T16:19:38.000Z
src/CaliceDetectorConstruction.cc
lopezzot/CALICESiWTB
ea1cdbdad0c406d27065e350bf6cc2256aceedfa
[ "MIT" ]
null
null
null
src/CaliceDetectorConstruction.cc
lopezzot/CALICESiWTB
ea1cdbdad0c406d27065e350bf6cc2256aceedfa
[ "MIT" ]
null
null
null
//************************************************** // \file CaliceDetectorConstruction.cc // \brief: Implementation of // CaliceDetectorConstruction class // \author: Lorenzo Pezzotti (CERN EP-SFT-sim) // @lopezzot // \start date: 17 February 2022 //************************************************** //Includers from Geant4 // #include "G4SDManager.hh" #include "G4GDMLParser.hh" //Includers from project files // #include "CaliceDetectorConstruction.hh" //#include "CaliceSensitiveCalorimeter.hh" #include "CaliceEcalSD.hh" //Constructor definition // CaliceDetectorConstruction::CaliceDetectorConstruction(const G4GDMLParser& parser) : G4VUserDetectorConstruction(), // theSensitiveCalorimeter( 0 ), fParser(parser) { } //Construct() method definition // G4VPhysicalVolume* CaliceDetectorConstruction::Construct() { ConstructSDandField(); return fParser.GetWorldVolume(); } //ConstructSDandField() method definition // void CaliceDetectorConstruction::ConstructSDandField() { auto ecalSD = new CaliceEcalSD("EcalSD", "CaloHitsCollection"); G4SDManager::GetSDMpointer()->AddNewDetector(ecalSD); //G4cout << "Constructing Sensitive Detector..." << G4endl; /////////////////////////////////////////////////////////////////////// // Example how to retrieve Auxiliary Information for sensitive detector // const G4GDMLAuxMapType* auxmap = fParser.GetAuxMap(); G4cout << "Found " << auxmap->size() << " volume(s) with auxiliary information." << G4endl << G4endl; for(G4GDMLAuxMapType::const_iterator iter=auxmap->begin(); iter!=auxmap->end(); iter++) { G4cout << "Volume " << ((*iter).first)->GetName() << " has the following list of auxiliary information: " << G4endl << G4endl; for (G4GDMLAuxListType::const_iterator vit=(*iter).second.begin(); vit!=(*iter).second.end(); vit++) { G4cout << "--> Type: " << (*vit).type << " Value: " << (*vit).value << G4endl; } } G4cout<<G4endl; // The same as above, but now we are looking for // sensitive detectors setting them for the volumes // for(G4GDMLAuxMapType::const_iterator iter=auxmap->begin(); iter!=auxmap->end(); iter++) { G4cout << "Volume " << ((*iter).first)->GetName() << " has the following list of auxiliary information: " << G4endl << G4endl; for (G4GDMLAuxListType::const_iterator vit=(*iter).second.begin(); vit!=(*iter).second.end();vit++) { if ((*vit).type=="SensDet") { G4cout << "Attaching sensitive detector " << (*vit).value << " to volume " << ((*iter).first)->GetName() << G4endl << G4endl; G4LogicalVolume* myvol = (*iter).first; myvol->SetSensitiveDetector(ecalSD); } } } } //**************************************************
34.321839
110
0.570328
lopezzot
ea533bb5004ff5315c56c2b433485a927e7a300e
3,023
cpp
C++
core/src/main/cpp/process/facedetector/FaceDetector.cpp
caolongcl/OpenImage
d29e0309bc35ff1766e0c81bfba82b185a7aabb6
[ "BSD-3-Clause" ]
2
2021-09-16T15:14:39.000Z
2021-09-17T14:39:52.000Z
core/src/main/cpp/process/facedetector/FaceDetector.cpp
caolongcl/OpenImage
d29e0309bc35ff1766e0c81bfba82b185a7aabb6
[ "BSD-3-Clause" ]
null
null
null
core/src/main/cpp/process/facedetector/FaceDetector.cpp
caolongcl/OpenImage
d29e0309bc35ff1766e0c81bfba82b185a7aabb6
[ "BSD-3-Clause" ]
null
null
null
// // Created by caolong on 2020/8/10. // #include <res/ResManager.hpp> #include <utils/Utils.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/imgcodecs.hpp> #include <process/facedetector/FaceDetector.hpp> #include <render/Flow.hpp> #include <render/polygon/Polygon.hpp> #include <softarch/Msg.hpp> #include <render/copier/Copier.hpp> using namespace clt; FaceDetector::FaceDetector() : m_faceCascade(new CascadeClassifierFaceDetector()), m_timeStatics() { } bool FaceDetector::Init() { Log::v(target, "FaceDetector::Init"); const std::string file = ResManager::Self()->GetResAbsolutePath("/opencv/haarcascade_frontalface_alt.xml"); m_faceCascade->Init(file); m_timeStatics.Init(); return true; } void FaceDetector::DeInit() { // 清空人脸检测绘制消息 Flow::Self()->SendMsg(PolygonMsg(Copier::target, Copier::msg_process)); Flow::Self()->SendMsg(TextMsg(Copier::target, Copier::msg_process_info)); m_faceCascade->DeInit(); m_timeStatics.DeInit(); Log::v(target, "FaceDetector::DeInit"); } void FaceDetector::Process(std::shared_ptr<Buffer> buf) { long lastTime = Utils::CurTimeMilli(); process(*buf); Log::n(target, "face detect period %d ms", (Utils::CurTimeMilli() - lastTime)); Log::debug([this, lastTime]() { m_timeStatics.Update(lastTime, [](long period) { TextInfo textInfo("face_detect:" + std::to_string(period) + "ms"); textInfo.position = {100.0f, 200.0f}; Flow::Self()->SendMsg( TextMsg(Copier::target, Copier::msg_process_info, std::make_shared<TextMsgData>(std::move(textInfo)))); }); }); } void FaceDetector::Process(std::shared_ptr<Buffer> buf, Task &&task) { Process(buf); task(); } void FaceDetector::process(const Buffer &buf) { std::vector<cv::Rect> faces; try { cv::Mat frame(buf.height, buf.width, CV_8UC4, buf.data.get()); // buf是RGBA的,frame把它当成BGRA的 cv::Mat frameGray; cv::cvtColor(frame, frameGray, cv::COLOR_RGBA2GRAY); cv::flip(frameGray, frameGray, 0); // 上下翻转 // ResManager::Self()->SaveMatImage("FaceDetectorGray", frameGray); cv::equalizeHist(frameGray, frameGray); m_faceCascade->Detect(frameGray, faces); } catch (std::exception &e) { Log::e(target, "face detect exception occur %s", e.what()); } if (faces.empty()) { Flow::Self()->SendMsg(PolygonMsg(Copier::target, Copier::msg_process)); return; } std::vector<PolygonObject> objects; objects.reserve(faces.size()); for (auto &face : faces) { Log::n(target, "face region (%d %d %d %d)", face.x, face.y, face.width, face.height); objects.emplace_back(Float2(buf.width, buf.height), Float4{(float) face.x, (float) face.y, (float) face.width, (float) face.height}, GreenColor, "face_" + std::to_string(objects.size())); } Flow::Self()->SendMsg( PolygonMsg(Copier::target, Copier::msg_process, std::make_shared<PolygonMsgData>(std::move(objects)))); }
27.733945
94
0.656632
caolongcl
ea53d8043af247cd7bf81dfa7a1687b2023f438b
1,580
hpp
C++
src/merge/feature_sample_merge.hpp
toppic-suite/toppic-suite
b5f0851f437dde053ddc646f45f9f592c16503ec
[ "Apache-2.0" ]
8
2018-05-23T14:37:31.000Z
2022-02-04T23:48:38.000Z
src/merge/feature_sample_merge.hpp
toppic-suite/toppic-suite
b5f0851f437dde053ddc646f45f9f592c16503ec
[ "Apache-2.0" ]
9
2019-08-31T08:17:45.000Z
2022-02-11T20:58:06.000Z
src/merge/feature_sample_merge.hpp
toppic-suite/toppic-suite
b5f0851f437dde053ddc646f45f9f592c16503ec
[ "Apache-2.0" ]
4
2018-04-25T01:39:38.000Z
2020-05-20T19:25:07.000Z
//Copyright (c) 2014 - 2020, The Trustees of Indiana University. // //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. #ifndef TOPPIC_MERGE_FEATURE_SAMPLE_MERGE_HPP_ #define TOPPIC_MERGE_FEATURE_SAMPLE_MERGE_HPP_ #include "merge/feature_prsm.hpp" namespace toppic { class FeatureSampleMerge { public: FeatureSampleMerge(const std::vector<std::string> &input_file_names, const std::string &output_file_name, const std::string &db_file_name, const std::string &fix_mod_str, const std::string &tool_name, double error_tole); void process(); void outputTable(FeaturePrsmPtrVec2D &table, FeaturePrsmPtrVec &examples, int sample_num); private: std::vector<std::string> input_file_names_; std::string output_file_name_; std::string db_file_name_; std::string fix_mod_str_; std::string tool_name_; double error_tole_; }; typedef std::shared_ptr<FeatureSampleMerge> FeatureSampleMergePtr; } // namespace toppic #endif
30.980392
74
0.705063
toppic-suite
ea53fdedf8e355b51193835f6c8197b60cc5f999
306
cpp
C++
module04/ex00/Cat.cpp
JohnnyZaev/CPP-Piscine
f1d0f0164131094823bb911c084d5075b0aee392
[ "MIT" ]
null
null
null
module04/ex00/Cat.cpp
JohnnyZaev/CPP-Piscine
f1d0f0164131094823bb911c084d5075b0aee392
[ "MIT" ]
null
null
null
module04/ex00/Cat.cpp
JohnnyZaev/CPP-Piscine
f1d0f0164131094823bb911c084d5075b0aee392
[ "MIT" ]
null
null
null
// // Created by Johnny Zaev on 25.05.2022. // #include "Cat.hpp" Cat::Cat() { type = "Cat"; } Cat::~Cat() {} Cat::Cat(const Cat &b) { *this = b; } Cat &Cat::operator=(const Cat &other) { this->type = other.type; return *this; } void Cat::makeSound() const { std::cout << "Meow!" << std::endl; }
12.75
40
0.568627
JohnnyZaev
ea548247736f817f178157d2aa51d6afe5857ed4
1,050
hpp
C++
include/tdc/pred/result.hpp
herlez/tdc
3b85ae183c21410e65f1e739736287df46c38d1d
[ "MIT" ]
1
2021-05-06T13:39:22.000Z
2021-05-06T13:39:22.000Z
include/tdc/pred/result.hpp
herlez/tdc
3b85ae183c21410e65f1e739736287df46c38d1d
[ "MIT" ]
1
2020-03-07T08:05:20.000Z
2020-03-07T08:05:20.000Z
include/tdc/pred/result.hpp
herlez/tdc
3b85ae183c21410e65f1e739736287df46c38d1d
[ "MIT" ]
2
2020-05-27T07:54:43.000Z
2021-11-18T13:29:14.000Z
#pragma once #include <utility> namespace tdc { namespace pred { /// \brief The result of a predecessor or successor query, wrapping the position of the located key. struct PosResult { /// \brief Whether the predecessor or successor exists. bool exists; /// \brief The position of the predecessor or successor, only meaningful if \ref exists is \c true. size_t pos; inline operator bool() const { return exists; } inline operator size_t() const { return pos; } }; /// \brief The result of a predecessor or successor query, wrapping the located key. /// \tparam key_t the key type template<typename key_t> struct KeyResult { /// \brief Whether the predecessor or successor exists. bool exists; /// \brief The position of the predecessor or successor, only meaningful if \ref exists is \c true. key_t key; inline operator bool() const { return exists; } inline operator key_t() const { return key; } }; }} // namespace tdc::pred
23.333333
103
0.657143
herlez
ea564452fd2f84743d55951770c638d2d9d9124b
2,856
cpp
C++
Practice/2019.7.10/UOJ242.cpp
SYCstudio/OI
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
[ "MIT" ]
4
2017-10-31T14:25:18.000Z
2018-06-10T16:10:17.000Z
Practice/2019.7.10/UOJ242.cpp
SYCstudio/OI
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
[ "MIT" ]
null
null
null
Practice/2019.7.10/UOJ242.cpp
SYCstudio/OI
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; #define double long double const int maxN=101000; const double Pi=acos(-1); const double eps=1e-10; class Point{ public: double x,y; double len(){ return sqrt(x*x+y*y); } double angle(){ return atan2(y,x); } }; class Line{ public: Point p,f; }; int n; Point A[maxN],B[maxN],C[maxN]; int Id[maxN],mxcnt; double Angle[maxN]; multiset<double> S; Point operator + (Point A,Point B); Point operator - (Point A,Point B); Point operator * (Point A,double B); ostream & operator << (ostream &os,Point A); double Cross(Point A,Point B); Point Cross(Line A,Line B); bool idcmp(int x,int y); void Insert(int id); void Delete(int id); bool check(double A,double B,bool f); int main(){ scanf("%d",&n); for (int i=1;i<=n+1;i++){ Point a,b;scanf("%LF%LF%LF%LF",&a.x,&a.y,&b.x,&b.y); A[i]=a;B[i]=b-a; } for (int i=1;i<=n;i++) C[i]=Cross((Line){A[i],B[i]},(Line){A[n+1],B[n+1]}),Id[i]=i; sort(&Id[1],&Id[n+1],idcmp); for (int i=1;i<=n;i++){ if (Cross(B[i],B[n+1])>=0) Angle[i]=B[i].angle(); else Angle[i]=B[i].angle()+Pi; while (Angle[i]<0) Angle[i]+=Pi+Pi; while (Angle[i]>=Pi+Pi) Angle[i]-=Pi+Pi; Insert(i); } printf("%d",(mxcnt==0)); for (int i=1;i<=n;i++){ Delete(Id[i]);Angle[Id[i]]=Angle[Id[i]]+Pi; while (Angle[Id[i]]<0) Angle[Id[i]]+=Pi+Pi; while (Angle[Id[i]]>=Pi+Pi) Angle[Id[i]]-=Pi+Pi; Insert(Id[i]); printf("%d",(mxcnt==0)); } puts(""); return 0; } Point operator + (Point A,Point B){ return ((Point){A.x+B.x,A.y+B.y}); } Point operator - (Point A,Point B){ return ((Point){A.x-B.x,A.y-B.y}); } Point operator * (Point A,double B){ return ((Point){A.x*B,A.y*B}); } ostream & operator << (ostream &os,Point A){ os<<"("<<A.x<<","<<A.y<<")";return os; } double Cross(Point A,Point B){ return A.x*B.y-A.y*B.x; } Point Cross(Line A,Line B){ double rate=Cross(B.f,A.p-B.p)/Cross(A.f,B.f); return A.p+A.f*rate; } bool idcmp(int x,int y){ return C[x].x<C[y].x; } void Insert(int id){ S.insert(Angle[id]); if (S.size()==1) return; if (S.size()==2){ multiset<double>::iterator i1=S.begin(),i2=--S.end(); mxcnt+=check(*i1,*i2,0); mxcnt+=check(*i2,*i1,1); return; } multiset<double>::iterator it=S.find(Angle[id]),pre,nxt; pre=nxt=it;bool f1=0,f2=0; if (it==S.begin()) pre=--S.end(),f1=1;else --pre; if (it==--S.end()) nxt=S.begin(),f2=1;else ++nxt; mxcnt-=check(*pre,*nxt,f1|f2); mxcnt+=check(*pre,*it,f1); mxcnt+=check(*it,*nxt,f2); return; } void Delete(int id){ multiset<double>::iterator it=S.find(Angle[id]),pre,nxt; pre=nxt=it;bool f1=0,f2=0; if (it==S.begin()) pre=--S.end(),f1=1;else --pre; if (it==--S.end()) nxt=S.begin(),f2=1;else ++nxt; mxcnt+=check(*pre,*nxt,f1|f2); mxcnt-=check(*pre,*it,f1); mxcnt-=check(*it,*nxt,f2); S.erase(it); return; } bool check(double l,double r,bool f){ if (f) r+=Pi+Pi; return r-l+eps>=Pi; }
23.032258
84
0.598039
SYCstudio
ea57a38efd0da9b8e4ed5f8cb14a592aeb757b1a
894
hpp
C++
includes/eeros/control/ros/RosPublisherDoubleArray.hpp
jonas-frei/eeros-framework
d3cf6b04f724d06cb45a512b9ff56e057fcfbb28
[ "Apache-2.0" ]
null
null
null
includes/eeros/control/ros/RosPublisherDoubleArray.hpp
jonas-frei/eeros-framework
d3cf6b04f724d06cb45a512b9ff56e057fcfbb28
[ "Apache-2.0" ]
null
null
null
includes/eeros/control/ros/RosPublisherDoubleArray.hpp
jonas-frei/eeros-framework
d3cf6b04f724d06cb45a512b9ff56e057fcfbb28
[ "Apache-2.0" ]
null
null
null
#ifndef ORG_EEROS_CONTROL_ROSPUBLISHER_DOUBLEARRAY_HPP #define ORG_EEROS_CONTROL_ROSPUBLISHER_DOUBLEARRAY_HPP #include <eeros/control/ros/RosPublisher.hpp> #include <eeros/math/Matrix.hpp> #include <std_msgs/Float64MultiArray.h> namespace eeros { namespace control { template < typename SigInType > class RosPublisherDoubleArray : public RosPublisher<std_msgs::Float64MultiArray::Type, SigInType> { typedef std_msgs::Float64MultiArray::Type TRosMsg; public: RosPublisherDoubleArray(const std::string& topic, const uint32_t queueSize=1000) : RosPublisher<TRosMsg, SigInType>(topic, queueSize) { } void setRosMsg(TRosMsg& msg) { if (this->in.isConnected()) { auto val = this->in.getSignal().getValue(); auto valTmpDouble = val.getColVector(0); msg.data = valTmpDouble; } } }; }; }; #endif // ORG_EEROS_CONTROL_ROSPUBLISHER_DOUBLEARRAY_HPP
30.827586
101
0.750559
jonas-frei
ea5c768d3cdf67c57ce452050d6b0e7caa15c2bf
1,788
cpp
C++
src/ros/master.cpp
Xamla/torch-ros
1f42cd4863d68bc4f9134bd1932988c1d5d1e7ca
[ "BSD-3-Clause" ]
26
2016-03-16T06:21:16.000Z
2021-01-04T05:37:07.000Z
src/ros/master.cpp
Xamla/torch-ros
1f42cd4863d68bc4f9134bd1932988c1d5d1e7ca
[ "BSD-3-Clause" ]
15
2016-04-04T21:31:29.000Z
2021-08-20T05:27:34.000Z
src/ros/master.cpp
Xamla/torch-ros
1f42cd4863d68bc4f9134bd1932988c1d5d1e7ca
[ "BSD-3-Clause" ]
10
2016-04-04T21:07:43.000Z
2018-05-17T12:54:27.000Z
#include "torch-ros.h" #include <ros/master.h> ROSIMP(bool, Master, execute)( const char *method, xamla::Variable *request, xamla::Variable *response, xamla::Variable *payload, bool wait_for_master) { XmlRpc::XmlRpcValue request_; VariableToXmlRpcValue(*request, request_); // copy request XmlRpc::XmlRpcValue response_, payload_; bool result = ros::master::execute(method, request_, response_, payload_, wait_for_master); XmlRpcValueToVariable(response_, *response); // copy response XmlRpcValueToVariable(payload_, *payload); return result; } ROSIMP(const char*, Master, getHost)() { return ros::master::getHost().c_str(); } ROSIMP(int, Master, getPort)() { return static_cast<int>(ros::master::getPort()); } ROSIMP(const char*, Master, getURI)() { return ros::master::getURI().c_str(); } ROSIMP(bool, Master, check)() { return ros::master::check(); } ROSIMP(bool, Master, getTopics)(xamla::VariableTable_ptr *output) { if (!*output) { output->reset(new xamla::VariableTable()); } xamla::VariableTable& output_table = **output; // call to maste api ros::master::V_TopicInfo topics; bool result = ros::master::getTopics(topics); // store result in table ros::master::V_TopicInfo::const_iterator i = topics.begin(); for (; i != topics.end(); ++i) { const ros::master::TopicInfo& topic = *i; xamla::VariableTable_ptr t(new xamla::VariableTable()); (*t)["topic"] = topic.name; (*t)["datatype"] = topic.datatype; output_table[topic.name] = t; } return result; } ROSIMP(bool, Master, getNodes)(std::vector<std::string> *output) { return ros::master::getNodes(*output); } ROSIMP(void, Master, setRetryTimeout)(int sec, int nsec) { ros::master::setRetryTimeout(ros::WallDuration(sec, nsec)); }
26.294118
93
0.685682
Xamla
ea5cece6ddc18b993b4689b60269abf1be39f44e
7,211
cpp
C++
Code/max/Containers/PointTest.cpp
ProgramMax/max
174b0501463dde4263813371546667763478e75e
[ "BSD-3-Clause" ]
1
2015-12-30T08:22:26.000Z
2015-12-30T08:22:26.000Z
Code/max/Containers/PointTest.cpp
ProgramMax/max
174b0501463dde4263813371546667763478e75e
[ "BSD-3-Clause" ]
55
2015-10-16T06:13:16.000Z
2020-11-16T06:45:07.000Z
Code/max/Containers/PointTest.cpp
ProgramMax/max
174b0501463dde4263813371546667763478e75e
[ "BSD-3-Clause" ]
1
2019-01-03T11:21:59.000Z
2019-01-03T11:21:59.000Z
// Copyright 2021, The max Contributors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "PointTest.hpp" #include <max/Containers/Point.hpp> #include <max/Testing/TestSuite.hpp> #include <max/Testing/CoutResultPolicy.hpp> #include <utility> namespace maxAutomatedTests { namespace Containers { void RunPointTestSuite() { max::Testing::CoutResultPolicy ResultPolicy; auto CartesianPointTestSuite = max::Testing::TestSuite< max::Testing::CoutResultPolicy >{ "max::Containers::CartesianPoint test suite", std::move( ResultPolicy ) }; CartesianPointTestSuite.AddTest( max::Testing::Test< max::Testing::CoutResultPolicy >{ "initializer_list constructor populates elements", []( max::Testing::Test< max::Testing::CoutResultPolicy > & CurrentTest, max::Testing::CoutResultPolicy const & ResultPolicy ) { max::Containers::CartesianPoint< int, 3 > Test = { 1, 2, 3 }; CurrentTest.MAX_TESTING_ASSERT( Test[ 0 ] == 1 ); CurrentTest.MAX_TESTING_ASSERT( Test[ 1 ] == 2 ); CurrentTest.MAX_TESTING_ASSERT( Test[ 2 ] == 3 ); } } ); CartesianPointTestSuite.AddTest( max::Testing::Test< max::Testing::CoutResultPolicy >{ "1D constructor sets X", []( max::Testing::Test< max::Testing::CoutResultPolicy > & CurrentTest, max::Testing::CoutResultPolicy const & ResultPolicy ) { auto Test = max::Containers::CartesianPoint< int, 1 >{ 42 }; CurrentTest.MAX_TESTING_ASSERT( Test.X() == 42 ); } } ); CartesianPointTestSuite.AddTest( max::Testing::Test< max::Testing::CoutResultPolicy >{ "2D constructor sets X and Y correctly", []( max::Testing::Test< max::Testing::CoutResultPolicy > & CurrentTest, max::Testing::CoutResultPolicy const & ResultPolicy ) { auto Test = max::Containers::CartesianPoint< int, 2 >{ 42, 100 }; CurrentTest.MAX_TESTING_ASSERT( Test.X() == 42 ); CurrentTest.MAX_TESTING_ASSERT( Test.Y() == 100 ); } } ); CartesianPointTestSuite.AddTest( max::Testing::Test< max::Testing::CoutResultPolicy >{ "3D constructor sets X, Y, and Z correctly", []( max::Testing::Test< max::Testing::CoutResultPolicy > & CurrentTest, max::Testing::CoutResultPolicy const & ResultPolicy ) { auto Test = max::Containers::CartesianPoint< int, 3 >{ 42, 100, 1 }; CurrentTest.MAX_TESTING_ASSERT( Test.X() == 42 ); CurrentTest.MAX_TESTING_ASSERT( Test.Y() == 100 ); CurrentTest.MAX_TESTING_ASSERT( Test.Z() == 1 ); } } ); CartesianPointTestSuite.AddTest( max::Testing::Test< max::Testing::CoutResultPolicy >{ "4D constructor sets X, Y, Z, and 4th element correctly", []( max::Testing::Test< max::Testing::CoutResultPolicy > & CurrentTest, max::Testing::CoutResultPolicy const & ResultPolicy ) { auto Test = max::Containers::CartesianPoint< int, 4 >{ 42, 100, 1, 4 }; CurrentTest.MAX_TESTING_ASSERT( Test.X() == 42 ); CurrentTest.MAX_TESTING_ASSERT( Test.Y() == 100 ); CurrentTest.MAX_TESTING_ASSERT( Test.Z() == 1 ); CurrentTest.MAX_TESTING_ASSERT( Test[ 3 ] == 4 ); } } ); CartesianPointTestSuite.AddTest( max::Testing::Test< max::Testing::CoutResultPolicy >{ "copy constructor copies elements", []( max::Testing::Test< max::Testing::CoutResultPolicy > & CurrentTest, max::Testing::CoutResultPolicy const & ResultPolicy ) { max::Containers::CartesianPoint< int, 3 > Original = { 1, 2, 3 }; max::Containers::CartesianPoint< int, 3 > Test = Original; CurrentTest.MAX_TESTING_ASSERT( Test[ 0 ] == 1 ); CurrentTest.MAX_TESTING_ASSERT( Test[ 1 ] == 2 ); CurrentTest.MAX_TESTING_ASSERT( Test[ 2 ] == 3 ); } } ); CartesianPointTestSuite.AddTest( max::Testing::Test< max::Testing::CoutResultPolicy >{ "move constructor moves elements", []( max::Testing::Test< max::Testing::CoutResultPolicy > & CurrentTest, max::Testing::CoutResultPolicy const & ResultPolicy ) { max::Containers::CartesianPoint< int, 3 > Original = { 1, 2, 3 }; max::Containers::CartesianPoint< int, 3 > Test = std::move( Original ); CurrentTest.MAX_TESTING_ASSERT( Test[ 0 ] == 1 ); CurrentTest.MAX_TESTING_ASSERT( Test[ 1 ] == 2 ); CurrentTest.MAX_TESTING_ASSERT( Test[ 2 ] == 3 ); } } ); CartesianPointTestSuite.AddTest( max::Testing::Test< max::Testing::CoutResultPolicy >{ "copy assignment operator copies elements", []( max::Testing::Test< max::Testing::CoutResultPolicy > & CurrentTest, max::Testing::CoutResultPolicy const & ResultPolicy ) { max::Containers::CartesianPoint< int, 3 > Original = { 1, 2, 3 }; max::Containers::CartesianPoint< int, 3 > Test; Test = Original; CurrentTest.MAX_TESTING_ASSERT( Test[ 0 ] == 1 ); CurrentTest.MAX_TESTING_ASSERT( Test[ 1 ] == 2 ); CurrentTest.MAX_TESTING_ASSERT( Test[ 2 ] == 3 ); } } ); CartesianPointTestSuite.AddTest( max::Testing::Test< max::Testing::CoutResultPolicy >{ "move assignment operator moves elements", []( max::Testing::Test< max::Testing::CoutResultPolicy > & CurrentTest, max::Testing::CoutResultPolicy const & ResultPolicy ) { max::Containers::CartesianPoint< int, 3 > Original = { 1, 2, 3 }; max::Containers::CartesianPoint< int, 3 > Test; Test = std::move( Original ); CurrentTest.MAX_TESTING_ASSERT( Test[ 0 ] == 1 ); CurrentTest.MAX_TESTING_ASSERT( Test[ 1 ] == 2 ); CurrentTest.MAX_TESTING_ASSERT( Test[ 2 ] == 3 ); } } ); CartesianPointTestSuite.AddTest( max::Testing::Test< max::Testing::CoutResultPolicy >{ "index operator gets correct value", []( max::Testing::Test< max::Testing::CoutResultPolicy > & CurrentTest, max::Testing::CoutResultPolicy const & ResultPolicy ) { max::Containers::CartesianPoint< int, 3 > Test = { 4, 5, 6 }; Test[ 0 ] = 1; Test[ 1 ] = 2; Test[ 2 ] = 3; CurrentTest.MAX_TESTING_ASSERT( Test[ 0 ] == 1 ); CurrentTest.MAX_TESTING_ASSERT( Test[ 1 ] == 2 ); CurrentTest.MAX_TESTING_ASSERT( Test[ 2 ] == 3 ); } } ); CartesianPointTestSuite.AddTest( max::Testing::Test< max::Testing::CoutResultPolicy >{ "const index operator gets correct value", []( max::Testing::Test< max::Testing::CoutResultPolicy > & CurrentTest, max::Testing::CoutResultPolicy const & ResultPolicy ) { max::Containers::CartesianPoint< int, 3 > Test = { 1, 2, 3 }; CurrentTest.MAX_TESTING_ASSERT( Test[ 0 ] == 1 ); CurrentTest.MAX_TESTING_ASSERT( Test[ 1 ] == 2 ); CurrentTest.MAX_TESTING_ASSERT( Test[ 2 ] == 3 ); } } ); CartesianPointTestSuite.AddTest( max::Testing::Test< max::Testing::CoutResultPolicy >{ "data function returns contiguous pointer with elements", []( max::Testing::Test< max::Testing::CoutResultPolicy > & CurrentTest, max::Testing::CoutResultPolicy const & ResultPolicy ) { max::Containers::CartesianPoint< int, 3 > Original = { 1, 2, 3 }; auto Test = Original.data(); CurrentTest.MAX_TESTING_ASSERT( Test[ 0 ] == 1 ); CurrentTest.MAX_TESTING_ASSERT( Test[ 1 ] == 2 ); CurrentTest.MAX_TESTING_ASSERT( Test[ 2 ] == 3 ); } } ); CartesianPointTestSuite.RunTests(); auto PolarPointTestSuite = max::Testing::TestSuite< max::Testing::CoutResultPolicy >{ "max::Containers::PolarPoint test suite", std::move( ResultPolicy ) }; PolarPointTestSuite.RunTests(); } } // namespace Containers } // namespace maxAutomatedTests
48.722973
274
0.694772
ProgramMax
ea5f953aee9951ebc5acf8ea06ea9f7ba95c419e
1,513
hpp
C++
complex_crawler/crawler/action/PageStorage.hpp
AlaoPrado/search_engine
6be1f0beb95ca23c5979e60d55a10eeb4fbc1aa1
[ "MIT" ]
null
null
null
complex_crawler/crawler/action/PageStorage.hpp
AlaoPrado/search_engine
6be1f0beb95ca23c5979e60d55a10eeb4fbc1aa1
[ "MIT" ]
null
null
null
complex_crawler/crawler/action/PageStorage.hpp
AlaoPrado/search_engine
6be1f0beb95ca23c5979e60d55a10eeb4fbc1aa1
[ "MIT" ]
null
null
null
/* Copyright 2021 Alan Prado Araújo Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Author: alanpradoaraujo@gmail.com (Alan Prado Araújo) */ #pragma once #include <CkSpider.h> #include <pthread.h> #include <string> namespace search_engine { class PageStorage { private: static const std::string indexName; PageStorage() {} public: static void storePage(std::string directory, CkSpider &spider, std::size_t pageId, pthread_mutex_t *mutex = NULL); }; } // namespace search_engine
37.825
80
0.763384
AlaoPrado
ea8068f277ab570eeead0e8ab31d860b7208d376
4,946
cpp
C++
src/Query.cpp
2coding/UseSQLite
710880de66895d05e96a4fce48ce8b30a1c5842e
[ "BSD-2-Clause" ]
null
null
null
src/Query.cpp
2coding/UseSQLite
710880de66895d05e96a4fce48ce8b30a1c5842e
[ "BSD-2-Clause" ]
null
null
null
src/Query.cpp
2coding/UseSQLite
710880de66895d05e96a4fce48ce8b30a1c5842e
[ "BSD-2-Clause" ]
null
null
null
/** Copyright (c) 2015, 2coding 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. 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 "StdCpp.hpp" #include "Query.hpp" #include "Statement.hpp" #include "Connection.hpp" namespace usql { Result Query::next() { return _stmt->query(); } Result Query::reset() { return _stmt->reset(); } int Query::columnCount() const { return _stmt->columnCount(); } bool Query::availableIndex(int idx) const { return idx >= 0 && idx < columnCount(); } int Query::columnIndexForName(const std::string &name) const { return _stmt->columnIndexForName(name); } ColumnType Query::typeForName(const std::string &name) const { int i = columnIndexForName(name); return typeForColumn(i); } ColumnType Query::typeForColumn(int i) const { if (!availableIndex(i)) { return _USQL_ENUM_VALUE(ColumnType, InvalidType); } return _stmt->typeForColumnIndex(i); } int Query::intForName(const std::string &name) { int i = columnIndexForName(name); return intForColumnIndex(i); } int Query::intForColumnIndex(int idx) { return _stmt->staticValueForColumnIndex<int>(idx, _USQL_ENUM_VALUE(ColumnType, Integer), sqlite3_column_int, USQL_ERROR_INTEGER); } bool Query::booleanForName(const std::string &name) { int i = columnIndexForName(name); return booleanForColumnIndex(i); } bool Query::booleanForColumnIndex(int idx) { return intForColumnIndex(idx); } int64_t Query::int64ForName(const std::string &name) { int i = columnIndexForName(name); return int64ForColumnIndex(i); } int64_t Query::int64ForColumnIndex(int idx) { return _stmt->staticValueForColumnIndex<sqlite3_int64>(idx, _USQL_ENUM_VALUE(ColumnType, Integer), sqlite3_column_int64, USQL_ERROR_INTEGER); } std::string Query::textForName(const std::string &name) { int i = columnIndexForName(name); return textForColumnIndex(i); } std::string Query::textForColumnIndex(int idx) { const unsigned char *txt = cstrForColumnIndex(idx); return std::string(txt ? (const char *)txt : USQL_ERROR_TEXT); } const unsigned char *Query::cstrForColumnIndex(int idx) { return _stmt->staticValueForColumnIndex<const unsigned char *>(idx, _USQL_ENUM_VALUE(ColumnType, Text), sqlite3_column_text, nullptr); } double Query::floatForName(const std::string &name) { int i = columnIndexForName(name); return floatForColumnIndex(i); } double Query::floatForColumnIndex(int idx) { return _stmt->staticValueForColumnIndex<double>(idx, _USQL_ENUM_VALUE(ColumnType, Float), sqlite3_column_double, USQL_ERROR_FLOAT); } std::time_t Query::datetimeForName(const std::string &name) { int i = columnIndexForName(name); return datetimeForColumnIndex(i); } std::time_t Query::datetimeForColumnIndex(int idx) { auto type = typeForColumn(idx); std::time_t ts = -1; if (type == _USQL_ENUM_VALUE(ColumnType, Integer)) { ts = intForColumnIndex(idx); } else if (type == _USQL_ENUM_VALUE(ColumnType, Text)) { std::string str = textForColumnIndex(idx); ts = Utils::str2tm(str); } else if (type == _USQL_ENUM_VALUE(ColumnType, Float)) { double day = floatForColumnIndex(idx); double t = (day - 2440587.5) * 86400.0; ts = static_cast<std::time_t>(t); } return ts; } }
35.582734
149
0.670441
2coding
ea89601e7eaa15abece31770109696744ab9c061
1,951
cpp
C++
src/test_ang.cpp
esromneb/DoubleRay
40b6bbadbceae9add732f8ae453cc94333729a02
[ "BSD-3-Clause" ]
1
2020-06-14T12:55:43.000Z
2020-06-14T12:55:43.000Z
src/test_ang.cpp
esromneb/hack-ray
232dae15627f6d1068604dd817c86963a88b08fc
[ "BSD-3-Clause" ]
5
2020-04-10T07:40:09.000Z
2020-04-13T10:14:52.000Z
src/test_ang.cpp
esromneb/DoubleRay
40b6bbadbceae9add732f8ae453cc94333729a02
[ "BSD-3-Clause" ]
null
null
null
#include "Vec3.hpp" #include "Vec.hpp" #include <iostream> #include <cmath> using namespace std; #ifdef asdf Left: [-0.894874,-0.446318,0.001119] Right: [-0.894874,0.446318,0.001119] #endif int main3(void) { cout << "Hello World\n"; Vec v0(2); v0.data[1] = 43; return 0; } int main2(void) { cout << "foo\n"; Vec v0(2); v0.data[0] = 2; v0.data[1] = sqrt(12); double _len = pow(v0.data[0],2) + pow(v0.data[1],2); double len = sqrt(_len); double fnLen = v0.mag(); cout << "Len: " << len << "\n"; cout << "FnLen: " << fnLen << "\n"; return 0; } int main4(void) { cout << "foo\n"; Vec v0(2); v0.data[0] = -0.894874; v0.data[1] = -0.446318; Vec v1(2); v1.data[0] = -0.894874; v1.data[1] = 0.446318; double dotprod = v0.dot(v1); double inner = dotprod / (v0.mag()*v1.mag()); double outer = acos(inner) * 180.0 / M_PI; double fnAngle0 = Vec::angle(v0,v1); double fnAngle1 = Vec::angle<false>(v0,v1); cout << "our: " << outer << "\n"; cout << "fn : " << fnAngle0 << "\n"; cout << "fn : " << fnAngle1 << "\n"; // cout << v0.str(false) << "\n"; // cout << v1.str(false) << "\n"; return 0; } int main5(void) { // cout << "foo\n"; Vec v0(2); v0.data[0] = 1; v0.data[1] = 1; Vec v1(2); v1.data[0] = 1; v1.data[1] = 1; double fnAngle0 = Vec::angle(v0,v1); cout << "fn : " << fnAngle0 << "\n"; // cout << v0.str(false) << "\n"; // cout << v1.str(false) << "\n"; return 0; } int main(void) { // cout << "foo\n"; Vec v0(3, 0,1,3); cout << "Loaded " << v0.str(false) << "\n"; Vec v1(3); v1.data[0] = 1; v1.data[1] = 1; v1.data[2] = 3; double fnAngle0 = Vec::angle(v0,v1); cout << "fn : " << fnAngle0 << "\n"; // cout << v0.str(false) << "\n"; // cout << v1.str(false) << "\n"; return 0; }
14.89313
56
0.476679
esromneb
ea8e33a7070d6c9de8bccb03a786d456cba26401
3,452
hh
C++
src/cpu/dtu-accel/syscallsm.hh
utcs-scea/gem5-dtu
0922df0e8f47fe3bd2fbad9f57b1b855181c64dd
[ "BSD-3-Clause" ]
3
2016-03-23T09:21:51.000Z
2019-07-22T22:07:26.000Z
src/cpu/dtu-accel/syscallsm.hh
TUD-OS/gem5-dtu
0922df0e8f47fe3bd2fbad9f57b1b855181c64dd
[ "BSD-3-Clause" ]
null
null
null
src/cpu/dtu-accel/syscallsm.hh
TUD-OS/gem5-dtu
0922df0e8f47fe3bd2fbad9f57b1b855181c64dd
[ "BSD-3-Clause" ]
6
2018-01-01T02:15:26.000Z
2021-11-03T10:54:04.000Z
/* * Copyright (c) 2016, Nils Asmussen * All rights reserved. * * Redistribution and use in source and binary forms, with or without * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY 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. * * The views and conclusions contained in the software and documentation are * those of the authors and should not be interpreted as representing official * policies, either expressed or implied, of the FreeBSD Project. */ #ifndef __CPU_DTU_ACCEL_SYSCALLSM_HH__ #define __CPU_DTU_ACCEL_SYSCALLSM_HH__ #include "cpu/dtu-accel/accelerator.hh" #include "sim/system.hh" class SyscallSM { public: enum Operation { // sent by the DTU if the PF handler is not reachable PAGEFAULT = 0, // capability creations CREATE_SRV, CREATE_SESS, CREATE_RGATE, CREATE_SGATE, CREATE_MGATE, CREATE_MAP, CREATE_VPEGRP, CREATE_VPE, // capability operations ACTIVATE, SRV_CTRL, VPE_CTRL, VPE_WAIT, DERIVE_MEM, OPEN_SESS, // capability exchange DELEGATE, OBTAIN, EXCHANGE, REVOKE, // forwarding FORWARD_MSG, FORWARD_MEM, FORWARD_REPLY, // misc NOOP, }; enum VPEOp { VCTRL_INIT, VCTRL_START, VCTRL_YIELD, VCTRL_STOP, }; enum State { SYSC_SEND, SYSC_WAIT, SYSC_FETCH, SYSC_READ_ADDR, SYSC_ACK, }; explicit SyscallSM(DtuAccel *_accel) : accel(_accel), state(), stateChanged(), waitForReply(), fetched(), replyAddr(), syscallSize() {} std::string stateName() const; bool isWaiting() const { return state == SYSC_FETCH; } bool hasStateChanged() const { return stateChanged; } void retryFetch() { fetched = false; } void start(Addr size, bool wait = true, bool resume = false) { syscallSize = size; state = resume ? SYSC_FETCH : SYSC_SEND; fetched = false; waitForReply = wait; } PacketPtr tick(); bool handleMemResp(PacketPtr pkt); private: DtuAccel *accel; State state; bool stateChanged; bool waitForReply; bool fetched; Addr replyAddr; Addr syscallSize; }; #endif /* __CPU_DTU_ACCEL_SYSCALLSM_HH__ */
26.553846
79
0.661645
utcs-scea
ea91a1c56ba3a43756fdef5aba4969294318ebdb
699
cc
C++
tests/day_05_tests.cc
tamaroth/AdventOfCode2017
0c0f93590068b6b8fa6ed7f5d53c9fecede632bb
[ "MIT" ]
2
2017-12-01T09:18:03.000Z
2017-12-13T12:59:40.000Z
tests/day_05_tests.cc
tamaroth/AdventOfCode2017
0c0f93590068b6b8fa6ed7f5d53c9fecede632bb
[ "MIT" ]
null
null
null
tests/day_05_tests.cc
tamaroth/AdventOfCode2017
0c0f93590068b6b8fa6ed7f5d53c9fecede632bb
[ "MIT" ]
null
null
null
/// @file /// /// Tests for Day01. /// #include <string> #include <vector> #include <gtest/gtest.h> #include "advent/days/05/maze.hh" #include "tests/tests_base.hh" namespace advent::tests { using TestData = std::pair<std::vector<int>, int>; class Day05Tests: public TestsBase, public Day05 {}; TEST_F(Day05Tests, part_one_is_computed_correctly) { TestData test_value { {0, 3, 0, 1, -3}, 5 }; auto& [input, expected] = test_value; EXPECT_EQ(solve_part_one_for_input(input), expected); } TEST_F(Day05Tests, part_two_is_computed_correctly) { TestData test_value { {0, 3, 0, 1, -3}, 10 }; auto& [input, expected] = test_value; EXPECT_EQ(solve_part_two_for_input(input), expected); } }
19.971429
54
0.705293
tamaroth
ea986f18ec2e4ef75733ff8d003535057b82c935
1,730
hpp
C++
include/glcxx/Texture.hpp
holtrop/glcxx
c55c2ae3b58d621d3127af7ed5980f7055cba486
[ "MIT" ]
4
2017-01-24T17:56:02.000Z
2020-01-30T09:28:32.000Z
include/glcxx/Texture.hpp
holtrop/glcxx
c55c2ae3b58d621d3127af7ed5980f7055cba486
[ "MIT" ]
1
2016-07-10T20:13:44.000Z
2016-07-10T20:13:44.000Z
include/glcxx/Texture.hpp
holtrop/glcxx
c55c2ae3b58d621d3127af7ed5980f7055cba486
[ "MIT" ]
null
null
null
/** * @file * * C++ wrapper for an OpenGL texture object. */ #ifndef GLCXX_TEXTURE_HPP #define GLCXX_TEXTURE_HPP #include "glcxx/gl.hpp" #include <memory> namespace glcxx { /** * C++ wrapper for an OpenGL texture object. */ class Texture { public: /** * Construct and allocate an OpenGL texture object. */ Texture(); /** * Destroy the texture object. */ ~Texture(); /** * Get the texture object's ID. * * @return The texture object's ID. */ GLuint id() const { return m_id; } /** * Bind the texture object. */ void bind(GLenum target) const { glBindTexture(target, m_id); } /** * Factory method to construct a Texture. * * @return std::shared_ptr to the created Texture. */ static std::shared_ptr<Texture> create() { return std::make_shared<Texture>(); } /** * Return the lowest power-of-2 integer greater than or equal to n. * * @param n Minimum bound for return value. * * @return Lowest power-of-2 integer greater than or equal to n. */ static uint32_t next_power_of_2(uint32_t n); protected: /** * The texture object's ID. */ GLuint m_id; /** * Allocate the OpenGL texture object. */ void allocate(); }; }; #endif
22.763158
79
0.447977
holtrop
ea9fd863ddb4531d03a943deaf7c17af8908f57f
3,142
cpp
C++
OpenTESArena/src/Interface/MainQuestSplashPanel.cpp
michealccc/OpenTESArena
7b4fd688677abea2ef03fa655b6d1669b1c8d77d
[ "MIT" ]
null
null
null
OpenTESArena/src/Interface/MainQuestSplashPanel.cpp
michealccc/OpenTESArena
7b4fd688677abea2ef03fa655b6d1669b1c8d77d
[ "MIT" ]
null
null
null
OpenTESArena/src/Interface/MainQuestSplashPanel.cpp
michealccc/OpenTESArena
7b4fd688677abea2ef03fa655b6d1669b1c8d77d
[ "MIT" ]
null
null
null
#include "MainQuestSplashPanel.h" #include "MainQuestSplashUiController.h" #include "MainQuestSplashUiModel.h" #include "MainQuestSplashUiView.h" #include "../Game/Game.h" #include "../UI/CursorData.h" #include "components/utilities/String.h" MainQuestSplashPanel::MainQuestSplashPanel(Game &game) : Panel(game) { } bool MainQuestSplashPanel::init(int provinceID) { auto &game = this->getGame(); auto &renderer = game.getRenderer(); const auto &fontLibrary = game.getFontLibrary(); const std::string descriptionText = MainQuestSplashUiModel::getDungeonText(game, provinceID); const TextBox::InitInfo descriptionTextBoxInitInfo = MainQuestSplashUiView::getDescriptionTextBoxInitInfo(descriptionText, fontLibrary); if (!this->textBox.init(descriptionTextBoxInitInfo, descriptionText, renderer)) { DebugLogError("Couldn't init description text box."); return false; } this->exitButton = Button<Game&>( MainQuestSplashUiView::ExitButtonX, MainQuestSplashUiView::ExitButtonY, MainQuestSplashUiView::ExitButtonWidth, MainQuestSplashUiView::ExitButtonHeight, MainQuestSplashUiController::onExitButtonSelected); // Get the texture filename of the staff dungeon splash image. this->splashTextureAssetRef = TextureAssetReference(MainQuestSplashUiModel::getSplashFilename(game, provinceID)); return true; } std::optional<CursorData> MainQuestSplashPanel::getCurrentCursor() const { return this->getDefaultCursor(); } void MainQuestSplashPanel::handleEvent(const SDL_Event &e) { // When the exit button is clicked, go to the game world panel. const auto &inputManager = this->getGame().getInputManager(); const bool leftClick = inputManager.mouseButtonPressed(e, SDL_BUTTON_LEFT); if (leftClick) { const Int2 mousePosition = inputManager.getMousePosition(); const Int2 originalPoint = this->getGame().getRenderer() .nativeToOriginal(mousePosition); if (this->exitButton.contains(originalPoint)) { this->exitButton.click(this->getGame()); } } } void MainQuestSplashPanel::render(Renderer &renderer) { // Clear full screen. renderer.clear(); // Draw staff dungeon splash image. auto &textureManager = this->getGame().getTextureManager(); const TextureAssetReference &paletteTextureAssetRef = this->splashTextureAssetRef; const std::optional<PaletteID> splashPaletteID = textureManager.tryGetPaletteID(paletteTextureAssetRef); if (!splashPaletteID.has_value()) { DebugLogError("Couldn't get splash palette ID for \"" + paletteTextureAssetRef.filename + "\"."); return; } const TextureAssetReference &textureAssetRef = this->splashTextureAssetRef; const std::optional<TextureBuilderID> splashTextureBuilderID = textureManager.tryGetTextureBuilderID(textureAssetRef); if (!splashTextureBuilderID.has_value()) { DebugLogError("Couldn't get splash texture builder ID for \"" + textureAssetRef.filename + "\"."); return; } renderer.drawOriginal(*splashTextureBuilderID, *splashPaletteID, textureManager); // Draw text. const Rect &textBoxRect = this->textBox.getRect(); renderer.drawOriginal(this->textBox.getTexture(), textBoxRect.getLeft(), textBoxRect.getTop()); }
33.425532
119
0.777849
michealccc
eaa5ee40e8048a393996373e41f64ef747c29463
5,484
cpp
C++
tests/test_qprotobuf_serializer_plugin/serialization/qprotobufserializerimpl.cpp
pontaoski/qtprotobuf
7225e6e324aa38c1bbeac1c0829cef73650e9d6f
[ "MIT" ]
139
2019-06-28T10:35:07.000Z
2022-03-23T05:54:26.000Z
tests/test_qprotobuf_serializer_plugin/serialization/qprotobufserializerimpl.cpp
pontaoski/qtprotobuf
7225e6e324aa38c1bbeac1c0829cef73650e9d6f
[ "MIT" ]
165
2019-10-22T14:51:10.000Z
2022-02-24T22:46:56.000Z
tests/test_qprotobuf_serializer_plugin/serialization/qprotobufserializerimpl.cpp
pontaoski/qtprotobuf
7225e6e324aa38c1bbeac1c0829cef73650e9d6f
[ "MIT" ]
29
2019-08-06T11:15:41.000Z
2022-01-04T02:51:43.000Z
/* * MIT License * * Copyright (c) 2019 Alexey Edelev <semlanik@gmail.com>, Viktor Kopp <vifactor@gmail.com> * * This file is part of QtProtobuf project https://git.semlanik.org/semlanik/qtprotobuf * * 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 "qprotobufserializerimpl.h" #include "qprotobufmetaproperty.h" #include "qprotobufmetaobject.h" QProtobufSerializerImpl::QProtobufSerializerImpl() { } QProtobufSerializerImpl::~QProtobufSerializerImpl() { } QByteArray QProtobufSerializerImpl::serializeMessage(const QObject *object, const QtProtobuf::QProtobufMetaObject &metaObject) const { Q_UNUSED(object) Q_UNUSED(metaObject) return QByteArray(); } void QProtobufSerializerImpl::deserializeMessage(QObject *object, const QtProtobuf::QProtobufMetaObject &metaObject, const QByteArray &data) const { Q_UNUSED(object) Q_UNUSED(data) Q_UNUSED(metaObject) } QByteArray QProtobufSerializerImpl::serializeObject(const QObject *object, const QtProtobuf::QProtobufMetaObject &metaObject, const QtProtobuf::QProtobufMetaProperty &metaProperty) const { Q_UNUSED(object) Q_UNUSED(metaProperty) Q_UNUSED(metaObject) return QByteArray(); } void QProtobufSerializerImpl::deserializeObject(QObject *object, const QtProtobuf::QProtobufMetaObject &metaObject, QtProtobuf::QProtobufSelfcheckIterator &it) const { Q_UNUSED(object) Q_UNUSED(it) Q_UNUSED(metaObject) } QByteArray QProtobufSerializerImpl::serializeListObject(const QObject *object, const QtProtobuf::QProtobufMetaObject &metaObject, const QtProtobuf::QProtobufMetaProperty &metaProperty) const { return serializeObject(object, metaObject, metaProperty); } bool QProtobufSerializerImpl::deserializeListObject(QObject *object, const QtProtobuf::QProtobufMetaObject &metaObject, QtProtobuf::QProtobufSelfcheckIterator &it) const { deserializeObject(object, metaObject, it); return true; } QByteArray QProtobufSerializerImpl::serializeMapPair(const QVariant &key, const QVariant &value, const QtProtobuf::QProtobufMetaProperty &metaProperty) const { Q_UNUSED(value) Q_UNUSED(metaProperty) Q_UNUSED(key) return QByteArray(); } bool QProtobufSerializerImpl::deserializeMapPair(QVariant &key, QVariant &value, QtProtobuf::QProtobufSelfcheckIterator &it) const { Q_UNUSED(value) Q_UNUSED(it) Q_UNUSED(key) return true; } QByteArray QProtobufSerializerImpl::serializeEnum(QtProtobuf::int64 value, const QMetaEnum &/*metaEnum*/, const QtProtobuf::QProtobufMetaProperty &metaProperty) const { Q_UNUSED(value) Q_UNUSED(metaProperty) return QByteArray(); } QByteArray QProtobufSerializerImpl::serializeEnumList(const QList<QtProtobuf::int64> &value, const QMetaEnum &/*metaEnum*/, const QtProtobuf::QProtobufMetaProperty &metaProperty) const { Q_UNUSED(value) Q_UNUSED(metaProperty) return QByteArray(); } void QProtobufSerializerImpl::deserializeEnum(QtProtobuf::int64 &value, const QMetaEnum &/*metaEnum*/, QtProtobuf::QProtobufSelfcheckIterator &it) const { Q_UNUSED(value) Q_UNUSED(it) } void QProtobufSerializerImpl::deserializeEnumList(QList<QtProtobuf::int64> &value, const QMetaEnum &/*metaEnum*/, QtProtobuf::QProtobufSelfcheckIterator &it) const { Q_UNUSED(value) Q_UNUSED(it) }
38.619718
116
0.61415
pontaoski
eaa7bc0e3ea3a9bea8bf1f03d114879cf2243138
1,385
cpp
C++
Section_11/FunctionDefinitions/main.cpp
ftfoi71/BeginningCpp
6acd8a9842f86791d87afbbc9716ff2ee994f4dc
[ "Unlicense" ]
1
2021-02-11T23:08:00.000Z
2021-02-11T23:08:00.000Z
Section_11/FunctionDefinitions/main.cpp
d-fect/BeginningCpp
6acd8a9842f86791d87afbbc9716ff2ee994f4dc
[ "Unlicense" ]
null
null
null
Section_11/FunctionDefinitions/main.cpp
d-fect/BeginningCpp
6acd8a9842f86791d87afbbc9716ff2ee994f4dc
[ "Unlicense" ]
null
null
null
#include <iostream> #define _USE_MATH_DEFINES // Need this to use m_PI. Must be added before #include <cmath>. Legacy C feature and not part of standard C++. #include <cmath> const static double pi {3.14159}; // Use this if M_PI doesn't work. M_PI is non-standard, so this might be best option. using namespace std; // BAD PRACTICE! Don't use using!! But since I'm lazy I'll use it during this course. double calc_area_circle(double radius) { // return pi * radius * radius; // return M_PI * pow(radius,2); return pi * pow(radius,2); // Use this line if M_PI doesn't work } double calc_volume_cylinder(double radius, double height) { return calc_area_circle(radius) * height; } void area_circle() { double radius {}; cout << "\nEnter radius: "; cin >> radius; cout << "The area of a circle with radius " << radius << " is " << calc_area_circle(radius) << endl; } void volume_cylinder() { double height {}, radius {}; cout << "\nEnter the radius: "; cin >> radius; cout << "Enter the height: "; cin >> height; cout << "The volum of a cylinder with radius " << radius << " and height " << height << " is " << calc_volume_cylinder(radius, height) << endl; } int main() { cout << "C++ defines PI as: " << M_PI << endl; area_circle(); volume_cylinder(); cout << endl; return 0; }
30.777778
147
0.629603
ftfoi71
eaadd4ae1597d38d447d910fc28b5f197a72bb85
1,204
cpp
C++
Test/ExceptionTests.cpp
deepdubey06/WMI
6cba31cf8ddc8fc3ad9767507690f6d11a9c3bb5
[ "MIT" ]
49
2015-08-10T09:53:45.000Z
2021-05-31T23:12:56.000Z
Test/ExceptionTests.cpp
deepdubey06/WMI
6cba31cf8ddc8fc3ad9767507690f6d11a9c3bb5
[ "MIT" ]
null
null
null
Test/ExceptionTests.cpp
deepdubey06/WMI
6cba31cf8ddc8fc3ad9767507690f6d11a9c3bb5
[ "MIT" ]
22
2015-10-27T13:53:06.000Z
2021-12-01T07:36:03.000Z
//////////////////////////////////////////////////////////////////////////////// //! \file ExceptionTests.cpp //! \brief The unit tests for the Exception class. //! \author Chris Oldwood #include "Common.hpp" #include <Core/UnitTest.hpp> #include <WMI/Exception.hpp> #include <wbemidl.h> #include <WCL/ComPtr.hpp> TEST_SET(Exception) { TEST_CASE("exception can be constructed with a generic HRESULT and message") { const HRESULT result = E_FAIL; const tchar* message = TXT("Unit Test"); WMI::Exception e(result, message); TEST_TRUE(e.m_result == result); TEST_TRUE(tstrstr(e.twhat(), message) != nullptr); } TEST_CASE_END TEST_CASE("exception constructed with a WMI error code has WMI error message") { typedef WCL::ComPtr<IWbemLocator> IWbemLocatorPtr; const HRESULT result = WBEM_E_DATABASE_VER_MISMATCH; const tchar* myMessage = TXT("Unit Test"); const tchar* wmiMessage = TXT("version mismatch"); IWbemLocatorPtr locator(CLSID_WbemAdministrativeLocator); WMI::Exception e(result, locator, myMessage); TEST_TRUE(e.m_result == result); TEST_TRUE(tstrstr(e.twhat(), myMessage) != nullptr); TEST_TRUE(tstrstr(e.twhat(), wmiMessage) != nullptr); } TEST_CASE_END } TEST_SET_END
25.617021
80
0.694352
deepdubey06
eab53c1767a50a0fd27f01abd5613dcfb9775df9
1,112
cpp
C++
client/clientservice/src/event_service.cpp
myh1000/concord-bft
1790aee3705c0f0571215abde2b0433564ff16a4
[ "Apache-2.0" ]
null
null
null
client/clientservice/src/event_service.cpp
myh1000/concord-bft
1790aee3705c0f0571215abde2b0433564ff16a4
[ "Apache-2.0" ]
null
null
null
client/clientservice/src/event_service.cpp
myh1000/concord-bft
1790aee3705c0f0571215abde2b0433564ff16a4
[ "Apache-2.0" ]
null
null
null
// Concord // // Copyright (c) 2021 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. #include <iostream> #include "event_service.hpp" using grpc::Status; using grpc::ServerContext; using grpc::ServerWriter; using vmware::concord::client::v1::StreamEventGroupsRequest; using vmware::concord::client::v1::EventGroup; namespace concord::client { Status EventServiceImpl::StreamEventGroups(ServerContext* context, const StreamEventGroupsRequest* request, ServerWriter<EventGroup>* stream) { std::cout << "EventServiceImpl::StreamEventGroups called" << std::endl; return grpc::Status::OK; } } // namespace concord::client
33.69697
119
0.703237
myh1000
eab5d685052b9959401cbc3ff12e412fbfae2b90
159,574
cpp
C++
Examples/SDKLibrary/interface/common/portable/data_types/events/content_filter/type_conversion_t.cpp
beeond/robot-examples
afc6b8b10809988b03663d703203625927e66e8f
[ "MIT" ]
1
2018-03-29T21:03:31.000Z
2018-03-29T21:03:31.000Z
Examples/SDKLibrary/interface/common/portable/data_types/events/content_filter/type_conversion_t.cpp
JayeshThamke/robot-examples
afc6b8b10809988b03663d703203625927e66e8f
[ "MIT" ]
null
null
null
Examples/SDKLibrary/interface/common/portable/data_types/events/content_filter/type_conversion_t.cpp
JayeshThamke/robot-examples
afc6b8b10809988b03663d703203625927e66e8f
[ "MIT" ]
4
2018-04-05T21:16:55.000Z
2019-10-15T19:01:46.000Z
/* ----------------------------------------------------------------------------------------------------------------- COPYRIGHT (c) 2009 - 2017 HONEYWELL INC., ALL RIGHTS RESERVED This software is a copyrighted work and/or information protected as a trade secret. Legal rights of Honeywell Inc. in this software are distinct from ownership of any medium in which the software is embodied. Copyright or trade secret notices included must be reproduced in any copies authorized by Honeywell Inc. The information in this software is subject to change without notice and should not be considered as a commitment by Honeywell Inc. ----------------------------------------------------------------------------------------------------------------- */ #include "type_conversion_t.h" #if (UASDK_INCLUDE_EVENTS > 0) #include "opcua_boolean_t.h" #include "opcua_byte_t.h" #include "opcua_double_t.h" #include "opcua_float_t.h" #include "opcua_int16_t.h" #include "opcua_int32_t.h" #include "opcua_int64_t.h" #include "opcua_sbyte_t.h" #include "opcua_uint16_t.h" #include "opcua_uint32_t.h" #include "opcua_uint64_t.h" #include "opcua_bytestring_t.h" #include "opcua_string_t.h" #include "opcua_date_time_t.h" #include "opcua_guid_t.h" #include "opcua_status_code_t.h" #include "opcua_node_id_t.h" #include "opcua_expanded_node_id_t.h" #include "opcua_localized_text_t.h" #include "opcua_qualified_name_t.h" #include "opcua_xml_element_t.h" #include "safe_ref_count_t.h" #include "opcua_node_id_string_t.h" #include "opcua_node_id_guid_t.h" #include "opcua_node_id_numeric_t.h" #include "opcua_node_id_opaque_t.h" namespace uasdk { TypeConversion_t::TypeConversion_t() { } TypeConversion_t::~TypeConversion_t() { } int64_t TypeConversion_t::Ifloor(float x) { if (x >= 0) { return static_cast<int64_t>(x); } else { int64_t y = static_cast<int64_t>(x); return ((float)y == x) ? y : y - 1; } } Status_t TypeConversion_t::ConvertGuidToString(IntrusivePtr_t<Guid_t>& guidPtr, IntrusivePtr_t<String_t>& sourceValue) { int i; int32_t len; uint32_t data1; uint16_t data2; uint16_t data3; uint8_t data4[8]; uint16_t data5[4]; uint32_t pos = 0; char cstr[37]; if (!guidPtr.is_set() || !sourceValue.is_set()) { return OpcUa_BadFilterOperandInvalid; } uint32_t *pData1 = reinterpret_cast<uint32_t *>(guidPtr->Value()); data1 = *pData1; uint16_t *pData2 = reinterpret_cast<uint16_t *>(guidPtr->Value() + 4); data2 = *pData2; uint16_t *pData3 = reinterpret_cast<uint16_t *>(guidPtr->Value() + 6); data3 = *pData3; uint8_t *pData4[8]; for (i = 0; i < 8; i++) { pData4[i] = static_cast<uint8_t *>(guidPtr->Value() + 8 + i); data4[i] = *pData4[i]; } for (i = 0; i < 4; i++) { data5[i] = (((data4[2 * i] << 8) & 0xff00) | (data4[2 * i + 1] & 0xff)); } sourceValue->Payload().Initialise(36); len = UASDK_unsigned_integer_to_hex_string(data1, 8, cstr+pos, 10); if (len < 0) { return OpcUa_BadFilterOperandInvalid; } pos += len; cstr[pos++] = '-'; len = UASDK_unsigned_integer_to_hex_string(data2, 4, cstr+pos, 6); if (len < 0) { return OpcUa_BadFilterOperandInvalid; } pos += len; cstr[pos++] = '-'; len = UASDK_unsigned_integer_to_hex_string(data3, 4, cstr+pos, 6); if (len < 0) { return OpcUa_BadFilterOperandInvalid; } pos += len; cstr[pos++] = '-'; len = UASDK_unsigned_integer_to_hex_string(data5[0], 4, cstr+pos, 6); if (len < 0) { return OpcUa_BadFilterOperandInvalid; } pos += len; cstr[pos++] = '-'; for (i = 1; i < 4; i++) { len = UASDK_unsigned_integer_to_hex_string(data5[i], 4, cstr+pos, 6); if (len < 0) { return OpcUa_BadFilterOperandInvalid; } pos += len; } UASDK_memcpy(sourceValue->Payload().Data(), cstr, pos); return OpcUa_Good; } Status_t TypeConversion_t::ConvertStringToGuid(IntrusivePtr_t<String_t>& sourceValue, IntrusivePtr_t<Guid_t>& guidPtr) { int i; int32_t len; uint32_t data1; uint16_t data2; uint16_t data3; uint16_t data5[4]; uint64_t u64; char cstr[37]; char csubstr[5]; char *end; if (!guidPtr.is_set() || !sourceValue.is_set()) { return OpcUa_BadFilterOperandInvalid; } len = sourceValue->Payload().Length(); if (len != 36) { return OpcUa_BadFilterOperandInvalid; } //validate string first for (int32_t i = 0; i < len; i++) { if ((8 == i) || (13 == i) || (18 == i) || (23 == i)) { if (sourceValue->Payload().Data()[i] != '-') { return OpcUa_BadFilterOperandInvalid; } } else { if (!((sourceValue->Payload().Data()[i] >= '0' && sourceValue->Payload().Data()[i] <= '9') || (sourceValue->Payload().Data()[i] >= 'A' && sourceValue->Payload().Data()[i] <= 'F') || (sourceValue->Payload().Data()[i] >= 'a' && sourceValue->Payload().Data()[i] <= 'f'))) { return OpcUa_BadFilterOperandInvalid; } } } UASDK_memcpy(cstr, sourceValue->Payload().Data(), len); cstr[36] = '\0'; cstr[8] = '\0'; end = 0; u64 = UASDK_strtoull(cstr, &end, 16); if ( (end == cstr) || (*end != '\0') ) { return OpcUa_BadFilterOperandInvalid; } if (u64 > UINT32_MAX) { return OpcUa_BadFilterOperandInvalid; } data1 = static_cast<uint32_t>(u64); UASDK_memcpy(guidPtr->Value(), &data1, 4); cstr[13] = '\0'; end = 0; u64 = UASDK_strtoull(cstr+9, &end, 16); if ( (end == cstr+9) || (*end != '\0') ) { return OpcUa_BadFilterOperandInvalid; } if (u64 > UINT16_MAX) { return OpcUa_BadFilterOperandInvalid; } data2 = static_cast<uint16_t>(u64); UASDK_memcpy(guidPtr->Value()+4, &data2, 2); cstr[18] = '\0'; end = 0; u64 = UASDK_strtoull(cstr+14, &end, 16); if ( (end == cstr+14) || (*end != '\0') ) { return OpcUa_BadFilterOperandInvalid; } if (u64 > UINT16_MAX) { return OpcUa_BadFilterOperandInvalid; } data3 = static_cast<uint16_t>(u64); UASDK_memcpy(guidPtr->Value()+6, &data3, 2); cstr[23] = '\0'; end = 0; u64 = UASDK_strtoull(cstr+19, &end, 16); if ( (end == cstr+19) || (*end != '\0') ) { return OpcUa_BadFilterOperandInvalid; } if (u64 > UINT16_MAX) { return OpcUa_BadFilterOperandInvalid; } data5[0] = static_cast<uint16_t>(u64); data5[0] = ((data5[0] & 0xff) << 8) | ((data5[0] >> 8) & 0xff); UASDK_memcpy(guidPtr->Value()+8, &data5[0], 2); for (i = 1; i<4; i++) { UASDK_memcpy(csubstr, cstr+20+i*4, 4); csubstr[4] = '\0'; end = 0; u64 = UASDK_strtoull(csubstr, &end, 16); if ( (end == csubstr) || (*end != '\0') ) { return OpcUa_BadFilterOperandInvalid; } if (u64 > UINT16_MAX) { return OpcUa_BadFilterOperandInvalid; } data5[i] = static_cast<uint16_t>(u64); data5[i] = ((data5[i] & 0xff) << 8) | ((data5[i] >> 8) & 0xff); UASDK_memcpy(guidPtr->Value()+8+i*2, &data5[i], 2); } return OpcUa_Good; } int32_t TypeConversion_t::FindFirstSubstr(IntrusivePtr_t<String_t>& strPtr, const char *substrPtr, int32_t startPos) { int32_t i, j, k; int32_t strLen; int32_t substrLen; char *ptr = (char *)substrPtr; bool found = false; if (!strPtr.is_set() || NULL == substrPtr) { return -1; } strLen = (int32_t)strPtr->Payload().Length(); substrLen = 0; while(*ptr++ != '\0') { substrLen++; } if ( (substrLen > strLen) || (startPos > (strLen-substrLen))) { return -1; } for (i = startPos; i <= (strLen-substrLen); i++) { k = 0; for (j = 0; j<substrLen; j++) { if (strPtr->Payload().Data()[i+j] == substrPtr[j]) { k++; } else { break; } } if (k == substrLen) { found = true; break; } } if (found) { return i; } else { return -1; } } Status_t TypeConversion_t::ConvertNodeIdToString(IntrusivePtr_t<NodeId_t>& nodeidPtr, IntrusivePtr_t<String_t>& sourceValue) { uint16_t namespaceIndex = 0; uint32_t pos = 0; int32_t len; uint32_t precision = 1; //ns=65536;g=36+1 //ns=65536;i=10+1 char cstr[48]; if (!nodeidPtr.is_set()) { return OpcUa_BadFilterOperandInvalid; } IntrusivePtr_t<String_t> strPtr = new SafeRefCount_t<String_t>(); if (!strPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value namespaceIndex = nodeidPtr->NamespaceIndex().Value(); if (namespaceIndex != 0) { cstr[pos++] = 'n'; cstr[pos++] = 's'; cstr[pos++] = '='; len = UASDK_unsigned_integer_to_string(namespaceIndex, precision, cstr+pos, 5); if (len < 0) { return OpcUa_BadFilterOperandInvalid; } pos += len; cstr[pos++] = ';'; } switch (nodeidPtr->NodeIdIdentiferType()) { case NodeId_t::NODEID_IDENTIFIER_NUMERIC: { IntrusivePtr_t<NodeIdNumeric_t> nnodeidPtr = RuntimeCast<NodeIdNumeric_t*>(*nodeidPtr); if (!nnodeidPtr.is_set()) { return OpcUa_BadFilterOperandInvalid; } cstr[pos++] = 'i'; cstr[pos++] = '='; len = UASDK_unsigned_integer_to_string(nnodeidPtr->Identifer().Value(), precision, cstr+pos, 10); if (len < 0) { return OpcUa_BadFilterOperandInvalid; } pos += len; strPtr->Payload().Initialise(pos); UASDK_memcpy(strPtr->Payload().Data(), cstr, pos); } break; case NodeId_t::NODEID_IDENTIFIER_STRING: { IntrusivePtr_t<NodeIdString_t> snodeidPtr = RuntimeCast<NodeIdString_t*>(*nodeidPtr); if (!snodeidPtr.is_set()) { return OpcUa_BadFilterOperandInvalid; } len = snodeidPtr->Identifer().Payload().Length(); if (len < 1) { return OpcUa_BadFilterOperandInvalid; } cstr[pos++] = 's'; cstr[pos++] = '='; strPtr->Payload().Initialise(pos+len); UASDK_memcpy(strPtr->Payload().Data(), cstr, pos); UASDK_memcpy(strPtr->Payload().Data()+pos, snodeidPtr->Identifer().Payload().Data(), len); } break; case NodeId_t::NODEID_IDENTIFIER_GUID: { IntrusivePtr_t<NodeIdGuid_t> gnodeidPtr = RuntimeCast<NodeIdGuid_t*>(*nodeidPtr); if (!gnodeidPtr.is_set()) { return OpcUa_BadFilterOperandInvalid; } //prepare to convert a Guid to a sub-String first IntrusivePtr_t<String_t> gstrPtr = new SafeRefCount_t<String_t>(); if (!gstrPtr.is_set()) { return OpcUa_BadOutOfMemory; } IntrusivePtr_t<Guid_t> guidPtr = new SafeRefCount_t<Guid_t>(); if (!guidPtr.is_set()) { return OpcUa_BadOutOfMemory; } Status_t status = guidPtr->CopyFrom(gnodeidPtr->Identifer()); if (status.IsBad()) { return status; } status = ConvertGuidToString(guidPtr, gstrPtr); if (status.IsBad()) { return status; } len = gstrPtr->Payload().Length(); if (len < 1) { return OpcUa_BadFilterOperandInvalid; } cstr[pos++] = 'g'; cstr[pos++] = '='; strPtr->Payload().Initialise(pos+len); UASDK_memcpy(strPtr->Payload().Data(), cstr, pos); UASDK_memcpy(strPtr->Payload().Data()+pos, gstrPtr->Payload().Data(), len); } break; case NodeId_t::NODEID_IDENTIFIER_OPAQUE: { IntrusivePtr_t<NodeIdOpaque_t> onodeidPtr = RuntimeCast<NodeIdOpaque_t*>(*nodeidPtr); if (!onodeidPtr.is_set()) { return OpcUa_BadFilterOperandInvalid; } len = onodeidPtr->Identifer().Length(); if (len < 1) { return OpcUa_BadFilterOperandInvalid; } cstr[pos++] = 'b'; cstr[pos++] = '='; strPtr->Payload().Initialise(pos+len); UASDK_memcpy(strPtr->Payload().Data(), cstr, pos); UASDK_memcpy(strPtr->Payload().Data()+pos, onodeidPtr->Identifer().Data(), len); } break; default: return OpcUa_BadFilterOperandInvalid; break; } sourceValue = strPtr; return OpcUa_Good; } Status_t TypeConversion_t::ConvertStringToNodeId(IntrusivePtr_t<String_t>& sourceValue, IntrusivePtr_t<NodeId_t>& nodeidPtr, bool uriPresent) { uint16_t namespaceIndex = 0; int32_t pos, prev_pos; int32_t Len; char *end; if (!sourceValue.is_set()) { return OpcUa_BadFilterOperandInvalid; } Len = sourceValue->Payload().Length(); if (Len < 1) { return OpcUa_BadFilterOperandInvalid; } prev_pos = 0; if (!uriPresent) { pos = FindFirstSubstr(sourceValue, "ns="); if (pos >= 0) { prev_pos = pos; pos = FindFirstSubstr(sourceValue, ";", prev_pos); if (pos < 0) { return OpcUa_BadFilterOperandInvalid; } if ( (pos - prev_pos) <= 3 ) { return OpcUa_BadFilterOperandInvalid; } char u16[6]; if (pos-(prev_pos+3) > 5) { return OpcUa_BadFilterOperandInvalid; } UASDK_memcpy(u16, sourceValue->Payload().Data()+prev_pos+3, pos-(prev_pos+3)); u16[pos-(prev_pos+3)] = '\0'; end = 0; uint64_t ul = UASDK_strtoull(u16, &end, 10); if ( (end == u16) || (*end != '\0') ) { return OpcUa_BadFilterOperandInvalid; } if (ul > UINT16_MAX) { return OpcUa_BadFilterOperandInvalid; } namespaceIndex = static_cast<uint16_t>(ul); prev_pos = pos; } else { pos = 0; prev_pos = pos; } } pos = FindFirstSubstr(sourceValue, "i=", prev_pos); if (pos >= 0) { //numeric nodeid uint32_t identifier; char u32[11]; if ((Len - pos -2) > 10) { return OpcUa_BadFilterOperandInvalid; } UASDK_memcpy(u32, sourceValue->Payload().Data()+pos+2, (Len-pos-2)); u32[Len-pos-2] = '\0'; end = 0; uint64_t ul = UASDK_strtoull(u32, &end, 10); if ( (end == u32) || (*end != '\0') ) { return OpcUa_BadFilterOperandInvalid; } if (ul > UINT32_MAX) { return OpcUa_BadFilterOperandInvalid; } IntrusivePtr_t<NodeIdNumeric_t> nPtr = new SafeRefCount_t<NodeIdNumeric_t>(); if (!nPtr.is_set()) { return OpcUa_BadOutOfMemory; } identifier = static_cast<uint32_t>(ul); nPtr->Initialise(namespaceIndex, identifier); nodeidPtr = nPtr; return OpcUa_Good; } else { pos = FindFirstSubstr(sourceValue, "s=", prev_pos); if (pos >= 0) { //string nodeid int32_t identifierLen; IntrusivePtr_t<NodeIdString_t> sPtr = new SafeRefCount_t<NodeIdString_t>(); if (!sPtr.is_set()) { return OpcUa_BadOutOfMemory; } identifierLen = Len - (pos+2); if (0 == identifierLen) { //so null identifier sPtr->Identifer().Payload().Initialise(-1); } else { sPtr->Identifer().Payload().Initialise(identifierLen); UASDK_memcpy(sPtr->Identifer().Payload().Data(), sourceValue->Payload().Data() + (pos+2), identifierLen); } nodeidPtr = sPtr; nodeidPtr->NamespaceIndex() = namespaceIndex; return OpcUa_Good; } else { pos = FindFirstSubstr(sourceValue, "g=", prev_pos); if (pos >= 0) { //guid nodeid int32_t identifierLen; IntrusivePtr_t<NodeIdGuid_t> gPtr = new SafeRefCount_t<NodeIdGuid_t>(); if (!gPtr.is_set()) { return OpcUa_BadOutOfMemory; } IntrusivePtr_t<Guid_t> guidPtr = new SafeRefCount_t<Guid_t>(); if (!guidPtr.is_set()) { return OpcUa_BadOutOfMemory; } IntrusivePtr_t<String_t> gStrPtr = new SafeRefCount_t<String_t>(); if (!gStrPtr.is_set()) { return OpcUa_BadOutOfMemory; } identifierLen = Len - (pos+2); if (identifierLen < 36) { return OpcUa_BadOutOfMemory; } gStrPtr->Payload().Initialise(identifierLen); UASDK_memcpy(gStrPtr->Payload().Data(), sourceValue->Payload().Data()+(pos+2), identifierLen); Status_t status = ConvertStringToGuid(gStrPtr, guidPtr); if (status.IsBad()) { return status; } gPtr->Identifer().CopyFrom(*guidPtr); nodeidPtr = gPtr; nodeidPtr->NamespaceIndex() = namespaceIndex; return OpcUa_Good; } else { pos = FindFirstSubstr(sourceValue, "b=", prev_pos); if (pos < 0) { return OpcUa_BadFilterOperandInvalid; } //opague nodeid int32_t identifierLen; IntrusivePtr_t<NodeIdOpaque_t> oPtr = new SafeRefCount_t<NodeIdOpaque_t>(); if (!oPtr.is_set()) { return OpcUa_BadOutOfMemory; } identifierLen = Len - (pos+2); if (0 == identifierLen) { //so null identifier oPtr->Identifer().Initialise(-1); } else { oPtr->Identifer().Initialise(identifierLen); UASDK_memcpy(oPtr->Identifer().Data(), sourceValue->Payload().Data() + (pos+2), identifierLen); } nodeidPtr = oPtr; nodeidPtr->NamespaceIndex() = namespaceIndex; return OpcUa_Good; } } } return OpcUa_BadFilterOperandInvalid; } Status_t TypeConversion_t::ConvertExpandedNodeidToString(IntrusivePtr_t<ExpandedNodeId_t>& expandednodeidPtr, IntrusivePtr_t<String_t>& sourceValue) { Status_t status = OpcUa_Good; int32_t len; uint32_t pos = 0; //svr=4294967296;nsu=x; x=1003 char cstr[MAX_STR_LEN_FOR_EXP_NODEID_NAMESPACE_URI+224]; if (!expandednodeidPtr.is_set()) { return OpcUa_BadFilterOperandInvalid; } if (!expandednodeidPtr->Nodeid().is_set()) { return OpcUa_BadFilterOperandInvalid; } IntrusivePtr_t<String_t> strPtr = new SafeRefCount_t<String_t>(); if (!strPtr.is_set()) { return OpcUa_BadOutOfMemory; } if (expandednodeidPtr->ServerIndex().Value() != 0) { cstr[pos++] = 's'; cstr[pos++] = 'v'; cstr[pos++] = 'r'; cstr[pos++] = '='; len = UASDK_unsigned_integer_to_string(expandednodeidPtr->ServerIndex().Value(), 0, cstr+pos, 10); if (len < 0) { return OpcUa_BadFilterOperandInvalid; } pos += len; cstr[pos++] = ';'; } len = expandednodeidPtr->NamespaceUri().Payload().Length(); if (len > MAX_STR_LEN_FOR_EXP_NODEID_NAMESPACE_URI) { return OpcUa_BadFilterOperandInvalid; } if (len > 0) { cstr[pos++] = 'n'; cstr[pos++] = 's'; cstr[pos++] = 'u'; cstr[pos++] = '='; for (int32_t i = 0; i < len; i++) { if (';' == expandednodeidPtr->NamespaceUri().Payload().Data()[i]) { cstr[pos++] = '%'; cstr[pos++] = '3'; cstr[pos++] = 'B'; } else if ('%' == expandednodeidPtr->NamespaceUri().Payload().Data()[i]) { cstr[pos++] = '%'; cstr[pos++] = '2'; cstr[pos++] = '5'; } else { UASDK_memcpy(cstr+pos, (expandednodeidPtr->NamespaceUri().Payload().Data()+i), 1); pos += 1; } } cstr[pos++] = ';'; } IntrusivePtr_t<String_t> nodeidStrPtr; status = ConvertNodeIdToString(expandednodeidPtr->Nodeid(), nodeidStrPtr); if (!nodeidStrPtr.is_set() || nodeidStrPtr->Payload().Length() < 1 || status.IsBad()) { return OpcUa_BadFilterOperandInvalid; } len = nodeidStrPtr->Payload().Length(); strPtr->Payload().Initialise(pos+len); UASDK_memcpy(strPtr->Payload().Data(), cstr, pos); UASDK_memcpy(strPtr->Payload().Data()+pos, nodeidStrPtr->Payload().Data(), len); sourceValue = strPtr; return OpcUa_Good; } Status_t TypeConversion_t::ConvertStringToExpandedNodeid(IntrusivePtr_t<String_t>& sourceValue, IntrusivePtr_t<ExpandedNodeId_t>& expandednodeidPtr) { UInt32_t serverindex = 0; int32_t pos, prev_pos; int32_t Len; char *end; bool uriPresent = false; if (!sourceValue.is_set()) { return OpcUa_BadFilterOperandInvalid; } Len = sourceValue->Payload().Length(); if (Len < 1) { return OpcUa_BadFilterOperandInvalid; } IntrusivePtr_t<String_t> uriPtr = new SafeRefCount_t<String_t>(); if (!uriPtr.is_set()) { return OpcUa_BadOutOfMemory; } uriPtr->Payload().Initialise(-1); prev_pos = 0; pos = FindFirstSubstr(sourceValue, "svr=", prev_pos); if (pos >= 0) { prev_pos = pos; pos = FindFirstSubstr(sourceValue, ";", prev_pos); if (pos < 0) { return OpcUa_BadFilterOperandInvalid; } if ((pos - prev_pos) <= 4) { return OpcUa_BadFilterOperandInvalid; } char u32[11]; if ((pos -prev_pos - 4) > 10) { return OpcUa_BadFilterOperandInvalid; } UASDK_memcpy(u32, sourceValue->Payload().Data()+prev_pos+4, (pos -prev_pos - 4)); u32[pos -prev_pos - 4] = '\0'; end = 0; uint64_t ul = UASDK_strtoull(u32, &end, 10); if ( (end == u32) || (*end != '\0') ) { return OpcUa_BadFilterOperandInvalid; } if (ul > UINT32_MAX) { return OpcUa_BadFilterOperandInvalid; } serverindex = (uint32_t)ul; prev_pos = pos; } else { pos = 0; prev_pos = pos; } pos = FindFirstSubstr(sourceValue, "nsu=", prev_pos); if (pos >= 0) { prev_pos = pos; pos = FindFirstSubstr(sourceValue, ";", prev_pos); if (pos < 0) { return OpcUa_BadFilterOperandInvalid; } if ((pos - prev_pos) <= 4) { return OpcUa_BadFilterOperandInvalid; } uriPtr->Payload().Initialise(pos - (prev_pos + 4)); UASDK_memcpy(uriPtr->Payload().Data(), sourceValue->Payload().Data()+prev_pos+4, pos - (prev_pos + 4)); uriPresent = true; prev_pos = pos; } else { pos = prev_pos; } if (Len - pos < 3) { return OpcUa_BadFilterOperandInvalid; } IntrusivePtr_t<String_t> substrPtr = new SafeRefCount_t<String_t>(); if (!substrPtr.is_set()) { return OpcUa_BadOutOfMemory; } substrPtr->Payload().Initialise(Len-pos-1); UASDK_memcpy(substrPtr->Payload().Data(), sourceValue->Payload().Data()+pos+1, Len-pos-1); IntrusivePtr_t<NodeId_t> nodeidPtr; Status_t status = ConvertStringToNodeId(substrPtr, nodeidPtr, uriPresent); if (!nodeidPtr.is_set() || status.IsBad()) { return OpcUa_BadFilterOperandInvalid; } IntrusivePtr_t<ExpandedNodeId_t> expNodeidPtr = new SafeRefCount_t<ExpandedNodeId_t>(); if (!expNodeidPtr.is_set()) { return OpcUa_BadOutOfMemory; } //set value expNodeidPtr->Nodeid() = nodeidPtr; expNodeidPtr->ServerIndex().CopyFrom(serverindex); expNodeidPtr->NamespaceUri().CopyFrom(*uriPtr); expandednodeidPtr = expNodeidPtr; return OpcUa_Good; } Status_t TypeConversion_t::ConvertBooleanTo(IntrusivePtr_t<BaseDataType_t>& sourceType, IntrusivePtr_t<BaseDataType_t>& targetType) { uint16_t targetNamespaceIndex; Status_t status = OpcUa_Good; IntrusivePtr_t<Boolean_t> sourceValue; sourceValue.reset(new SafeRefCount_t<Boolean_t>()); if (!sourceValue.is_set()) { return OpcUa_BadOutOfMemory; } status = sourceValue->CopyFrom(*sourceType); if (status.IsBad()) { return status; } switch (targetType->TypeId(targetNamespaceIndex)) { case OpcUaId_Boolean: { targetType = sourceValue; break; } case OpcUaId_Byte: { IntrusivePtr_t<Byte_t> tPtr = new SafeRefCount_t<Byte_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value tPtr->Value(static_cast<uint8_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_Double: { IntrusivePtr_t<Double_t> tPtr = new SafeRefCount_t<Double_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value tPtr->Value(static_cast<double>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_Float: { IntrusivePtr_t<Float_t> tPtr = new SafeRefCount_t<Float_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value tPtr->Value(static_cast<float>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_Int16: { IntrusivePtr_t<Int16_t> tPtr = new SafeRefCount_t<Int16_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value tPtr->Value(static_cast<int16_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_Int32: { IntrusivePtr_t<Int32_t> tPtr = new SafeRefCount_t<Int32_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value tPtr->Value(static_cast<int32_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_Int64: { IntrusivePtr_t<Int64_t> tPtr = new SafeRefCount_t<Int64_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value tPtr->Value(static_cast<int64_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_SByte: { IntrusivePtr_t<SByte_t> tPtr = new SafeRefCount_t<SByte_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value tPtr->Value(static_cast<int8_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_String: { IntrusivePtr_t<String_t> tPtr = new SafeRefCount_t<String_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if (sourceValue->Value()) { uint8_t data[] = "true"; tPtr->Payload().Initialise(sizeof(data)); UASDK_memcpy(tPtr->Payload().Data(), data, sizeof(data)); } else { uint8_t data[] = "false"; tPtr->Payload().Initialise(sizeof(data)); UASDK_memcpy(tPtr->Payload().Data(), data, sizeof(data)); } targetType = tPtr; break; } case OpcUaId_UInt16: { IntrusivePtr_t<UInt16_t> tPtr = new SafeRefCount_t<UInt16_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value tPtr->Value(static_cast<uint16_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_UInt32: { IntrusivePtr_t<UInt32_t> tPtr = new SafeRefCount_t<UInt32_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value tPtr->Value(static_cast<uint32_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_UInt64: { IntrusivePtr_t<UInt64_t> tPtr = new SafeRefCount_t<UInt64_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value tPtr->Value(static_cast<uint64_t>(sourceValue->Value())); targetType = tPtr; break; } default: return OpcUa_BadFilterOperandInvalid; break; } return status; } Status_t TypeConversion_t::ConvertByteTo(IntrusivePtr_t<BaseDataType_t>& sourceType, IntrusivePtr_t<BaseDataType_t>& targetType) { uint16_t targetNamespaceIndex; Status_t status = OpcUa_Good; IntrusivePtr_t<Byte_t> sourceValue; sourceValue.reset(new SafeRefCount_t<Byte_t>()); if (!sourceValue.is_set()) { return OpcUa_BadOutOfMemory; } status = sourceValue->CopyFrom(*sourceType); if (status.IsBad()) { return status; } switch (targetType->TypeId(targetNamespaceIndex)) { case OpcUaId_Boolean: { IntrusivePtr_t<Boolean_t> tPtr = new SafeRefCount_t<Boolean_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value tPtr->Value(sourceValue->Value() > 0 ? 1 : 0); targetType = tPtr; break; } case OpcUaId_Byte: { targetType = sourceValue; break; } case OpcUaId_Double: { IntrusivePtr_t<Double_t> tPtr = new SafeRefCount_t<Double_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value tPtr->Value(static_cast<double>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_Float: { IntrusivePtr_t<Float_t> tPtr = new SafeRefCount_t<Float_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value tPtr->Value(static_cast<float>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_Int16: { IntrusivePtr_t<Int16_t> tPtr = new SafeRefCount_t<Int16_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value tPtr->Value(static_cast<int16_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_Int32: { IntrusivePtr_t<Int32_t> tPtr = new SafeRefCount_t<Int32_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value tPtr->Value(static_cast<int32_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_Int64: { IntrusivePtr_t<Int64_t> tPtr = new SafeRefCount_t<Int64_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value tPtr->Value(static_cast<int64_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_SByte: { IntrusivePtr_t<SByte_t> tPtr = new SafeRefCount_t<SByte_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if (sourceValue->Value() > INT8_MAX) { return OpcUa_BadFilterOperandInvalid; } //transfer value tPtr->Value(static_cast<int8_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_String: { IntrusivePtr_t<String_t> tPtr = new SafeRefCount_t<String_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } char cstr[MAX_STR_LEN_FOR_64_BIT_INTEGER + 1]; int32_t len = 0; uint32_t precision = 0; len = UASDK_unsigned_integer_to_string(sourceValue->Value(), precision, cstr, MAX_STR_LEN_FOR_64_BIT_INTEGER); if (len < 1) { return OpcUa_BadFilterOperandInvalid; } tPtr->Payload().Initialise(len); UASDK_memcpy(tPtr->Payload().Data(), cstr, len); targetType = tPtr; break; } case OpcUaId_UInt16: { IntrusivePtr_t<UInt16_t> tPtr = new SafeRefCount_t<UInt16_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value tPtr->Value(static_cast<uint16_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_UInt32: { IntrusivePtr_t<UInt32_t> tPtr = new SafeRefCount_t<UInt32_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value tPtr->Value(static_cast<uint32_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_UInt64: { IntrusivePtr_t<UInt64_t> tPtr = new SafeRefCount_t<UInt64_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value tPtr->Value(static_cast<uint64_t>(sourceValue->Value())); targetType = tPtr; break; } default: return OpcUa_BadFilterOperandInvalid; break; } return status; } Status_t TypeConversion_t::ConvertDoubleTo(IntrusivePtr_t<BaseDataType_t>& sourceType, IntrusivePtr_t<BaseDataType_t>& targetType) { uint16_t targetNamespaceIndex; Status_t status = OpcUa_Good; IntrusivePtr_t<Double_t> sourceValue; sourceValue.reset(new SafeRefCount_t<Double_t>()); if (!sourceValue.is_set()) { return OpcUa_BadOutOfMemory; } status = sourceValue->CopyFrom(*sourceType); if (status.IsBad()) { return status; } switch (targetType->TypeId(targetNamespaceIndex)) { case OpcUaId_Boolean: { IntrusivePtr_t<Boolean_t> tPtr = new SafeRefCount_t<Boolean_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } int64_t integer = Ifloor((float)(sourceValue->Value() + 0.5)); if (integer < 0) { return OpcUa_BadFilterOperandInvalid; } //transfer value if (integer > 0) { tPtr->Value(true); } else { tPtr->Value(false); } targetType = tPtr; break; } case OpcUaId_Byte: { IntrusivePtr_t<Byte_t> tPtr = new SafeRefCount_t<Byte_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } int64_t integer = Ifloor((float)(sourceValue->Value() + 0.5)); if ((integer < 0) || (integer > UINT8_MAX)) { return OpcUa_BadFilterOperandInvalid; } //transfer value tPtr->Value(static_cast<uint8_t>(integer)); targetType = tPtr; break; } case OpcUaId_Double: { targetType = sourceValue; break; } case OpcUaId_Float: { IntrusivePtr_t<Float_t> tPtr = new SafeRefCount_t<Float_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value tPtr->Value(static_cast<float>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_Int16: { IntrusivePtr_t<Int16_t> tPtr = new SafeRefCount_t<Int16_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } int64_t integer = Ifloor((float)(sourceValue->Value() + 0.5)); if ((integer < INT16_MIN) || (integer > INT16_MAX)) { return OpcUa_BadFilterOperandInvalid; } //transfer value tPtr->Value(static_cast<int16_t>(integer)); targetType = tPtr; break; } case OpcUaId_Int32: { IntrusivePtr_t<Int32_t> tPtr = new SafeRefCount_t<Int32_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } int64_t integer = Ifloor((float)(sourceValue->Value() + 0.5)); if ((integer < INT32_MIN) || (integer > INT32_MAX)) { return OpcUa_BadFilterOperandInvalid; } //transfer value tPtr->Value(static_cast<int32_t>(integer)); targetType = tPtr; break; } case OpcUaId_Int64: { IntrusivePtr_t<Int64_t> tPtr = new SafeRefCount_t<Int64_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } int64_t integer = Ifloor((float)(sourceValue->Value() + 0.5)); //transfer value tPtr->Value(static_cast<int64_t>(integer)); targetType = tPtr; break; } case OpcUaId_SByte: { IntrusivePtr_t<SByte_t> tPtr = new SafeRefCount_t<SByte_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } int64_t integer = Ifloor((float)(sourceValue->Value() + 0.5)); if ((integer < INT8_MIN) || (integer > INT8_MAX)) { return OpcUa_BadFilterOperandInvalid; } //transfer value tPtr->Value(static_cast<int8_t>(integer)); targetType = tPtr; break; } case OpcUaId_String: { IntrusivePtr_t<String_t> tPtr = new SafeRefCount_t<String_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } char cstr[MAX_STR_LEN_FOR_DOUBLE + 1]; int32_t len = 0; uint32_t precision = 0; len = UASDK_double_to_string(sourceValue->Value(), precision, cstr, MAX_STR_LEN_FOR_DOUBLE); if (len < 1) { return OpcUa_BadFilterOperandInvalid; } tPtr->Payload().Initialise(len); UASDK_memcpy(tPtr->Payload().Data(), cstr, len); targetType = tPtr; break; } case OpcUaId_UInt16: { IntrusivePtr_t<UInt16_t> tPtr = new SafeRefCount_t<UInt16_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } int64_t integer = Ifloor((float)(sourceValue->Value() + 0.5)); if ((integer < 0) || (integer > INT16_MAX)) { return OpcUa_BadFilterOperandInvalid; } //transfer value tPtr->Value(static_cast<uint16_t>(integer)); targetType = tPtr; break; } case OpcUaId_UInt32: { IntrusivePtr_t<UInt32_t> tPtr = new SafeRefCount_t<UInt32_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } int64_t integer = Ifloor((float)(sourceValue->Value() + 0.5)); if ((integer < 0) || (integer > INT32_MAX)) { return OpcUa_BadFilterOperandInvalid; } //transfer value tPtr->Value(static_cast<uint32_t>(integer)); targetType = tPtr; break; } case OpcUaId_UInt64: { IntrusivePtr_t<UInt64_t> tPtr = new SafeRefCount_t<UInt64_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } int64_t integer = Ifloor((float)(sourceValue->Value() + 0.5)); if (integer < 0) { return OpcUa_BadFilterOperandInvalid; } //transfer value tPtr->Value(static_cast<uint64_t>(integer)); targetType = tPtr; break; } default: return OpcUa_BadFilterOperandInvalid; break; } return status; } Status_t TypeConversion_t::ConvertFloatTo(IntrusivePtr_t<BaseDataType_t>& sourceType, IntrusivePtr_t<BaseDataType_t>& targetType) { uint16_t targetNamespaceIndex; Status_t status = OpcUa_Good; IntrusivePtr_t<Float_t> sourceValue; sourceValue.reset(new SafeRefCount_t<Float_t>()); if (!sourceValue.is_set()) { return OpcUa_BadOutOfMemory; } status = sourceValue->CopyFrom(*sourceType); if (status.IsBad()) { return status; } switch (targetType->TypeId(targetNamespaceIndex)) { case OpcUaId_Boolean: { IntrusivePtr_t<Boolean_t> tPtr = new SafeRefCount_t<Boolean_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } int64_t integer = Ifloor((float)(sourceValue->Value() + 0.5)); if (integer < 0) { return OpcUa_BadFilterOperandInvalid; } //transfer value if (integer > 0) { tPtr->Value(true); } else { tPtr->Value(false); } targetType = tPtr; break; } case OpcUaId_Byte: { IntrusivePtr_t<Byte_t> tPtr = new SafeRefCount_t<Byte_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } int64_t integer = Ifloor((float)(sourceValue->Value() + 0.5)); if ((integer < 0) || (integer > UINT8_MAX)) { return OpcUa_BadFilterOperandInvalid; } //transfer value tPtr->Value(static_cast<uint8_t>(integer)); targetType = tPtr; break; } case OpcUaId_Double: { IntrusivePtr_t<Double_t> tPtr = new SafeRefCount_t<Double_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value tPtr->Value(static_cast<double>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_Float: { targetType = sourceValue; break; } case OpcUaId_Int16: { IntrusivePtr_t<Int16_t> tPtr = new SafeRefCount_t<Int16_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } int64_t integer = Ifloor((float)(sourceValue->Value() + 0.5)); if ((integer < INT16_MIN) || (integer > INT16_MAX)) { return OpcUa_BadFilterOperandInvalid; } //transfer value tPtr->Value(static_cast<int16_t>(integer)); targetType = tPtr; break; } case OpcUaId_Int32: { IntrusivePtr_t<Int32_t> tPtr = new SafeRefCount_t<Int32_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } int64_t integer = Ifloor((float)(sourceValue->Value() + 0.5)); if ((integer < INT32_MIN) || (integer > INT32_MAX)) { return OpcUa_BadFilterOperandInvalid; } //transfer value tPtr->Value(static_cast<int32_t>(integer)); targetType = tPtr; break; } case OpcUaId_Int64: { IntrusivePtr_t<Int64_t> tPtr = new SafeRefCount_t<Int64_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } int64_t integer = Ifloor((float)(sourceValue->Value() + 0.5)); //transfer value tPtr->Value(static_cast<int64_t>(integer)); targetType = tPtr; break; } case OpcUaId_SByte: { IntrusivePtr_t<SByte_t> tPtr = new SafeRefCount_t<SByte_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } int64_t integer = Ifloor((float)(sourceValue->Value() + 0.5)); if ((integer < INT8_MIN) || (integer > INT8_MAX)) { return OpcUa_BadFilterOperandInvalid; } //transfer value tPtr->Value(static_cast<int8_t>(integer)); targetType = tPtr; break; } case OpcUaId_String: { IntrusivePtr_t<String_t> tPtr = new SafeRefCount_t<String_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } char cstr[MAX_STR_LEN_FOR_FLOAT + 1]; int32_t len = 0; uint32_t precision = 0; len = UASDK_float_to_string(sourceValue->Value(), precision, cstr, MAX_STR_LEN_FOR_FLOAT); if (len < 1) { return OpcUa_BadFilterOperandInvalid; } tPtr->Payload().Initialise(len); UASDK_memcpy(tPtr->Payload().Data(), cstr, len); targetType = tPtr; break; } case OpcUaId_UInt16: { IntrusivePtr_t<UInt16_t> tPtr = new SafeRefCount_t<UInt16_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } int64_t integer = Ifloor((float)(sourceValue->Value() + 0.5)); if ((integer < 0) || (integer > INT16_MAX)) { return OpcUa_BadFilterOperandInvalid; } //transfer value tPtr->Value(static_cast<uint16_t>(integer)); targetType = tPtr; break; } case OpcUaId_UInt32: { IntrusivePtr_t<UInt32_t> tPtr = new SafeRefCount_t<UInt32_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } int64_t integer = Ifloor((float)(sourceValue->Value() + 0.5)); if ((integer < 0) || (integer > INT32_MAX)) { return OpcUa_BadFilterOperandInvalid; } //transfer value tPtr->Value(static_cast<uint32_t>(integer)); targetType = tPtr; break; } case OpcUaId_UInt64: { IntrusivePtr_t<UInt64_t> tPtr = new SafeRefCount_t<UInt64_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } int64_t integer = Ifloor((float)(sourceValue->Value() + 0.5)); if (integer < 0) { return OpcUa_BadFilterOperandInvalid; } //transfer value tPtr->Value(static_cast<uint64_t>(integer)); targetType = tPtr; break; } default: return OpcUa_BadFilterOperandInvalid; break; } return status; } Status_t TypeConversion_t::ConvertInt16To(IntrusivePtr_t<BaseDataType_t>& sourceType, IntrusivePtr_t<BaseDataType_t>& targetType) { uint16_t targetNamespaceIndex; Status_t status = OpcUa_Good; IntrusivePtr_t<Int16_t> sourceValue; sourceValue.reset(new SafeRefCount_t<Int16_t>()); if (!sourceValue.is_set()) { return OpcUa_BadOutOfMemory; } status = sourceValue->CopyFrom(*sourceType); if (status.IsBad()) { return status; } switch (targetType->TypeId(targetNamespaceIndex)) { case OpcUaId_Boolean: { IntrusivePtr_t<Boolean_t> tPtr = new SafeRefCount_t<Boolean_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if (sourceValue->Value() < 0) { return OpcUa_BadFilterOperandInvalid; } //transfer value if (sourceValue->Value() > 0) { tPtr->Value(true); } else { tPtr->Value(false); } targetType = tPtr; break; } case OpcUaId_Byte: { IntrusivePtr_t<Byte_t> tPtr = new SafeRefCount_t<Byte_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if ((sourceValue->Value() < 0) || (sourceValue->Value() > UINT8_MAX)) { return OpcUa_BadFilterOperandInvalid; } //transfer value tPtr->Value(static_cast<uint8_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_Double: { IntrusivePtr_t<Double_t> tPtr = new SafeRefCount_t<Double_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value tPtr->Value(static_cast<double>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_Float: { IntrusivePtr_t<Float_t> tPtr = new SafeRefCount_t<Float_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value tPtr->Value(static_cast<float>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_SByte: { IntrusivePtr_t<SByte_t> tPtr = new SafeRefCount_t<SByte_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if ((sourceValue->Value() < INT8_MIN) || (sourceValue->Value() > INT8_MAX)) { return OpcUa_BadFilterOperandInvalid; } //transfer value tPtr->Value(static_cast<int8_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_Int16: { targetType = sourceValue; break; } case OpcUaId_Int32: { IntrusivePtr_t<Int32_t> tPtr = new SafeRefCount_t<Int32_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value tPtr->Value(static_cast<int32_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_Int64: { IntrusivePtr_t<Int64_t> tPtr = new SafeRefCount_t<Int64_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value tPtr->Value(static_cast<int64_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_String: { IntrusivePtr_t<String_t> tPtr = new SafeRefCount_t<String_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } char cstr[MAX_STR_LEN_FOR_64_BIT_INTEGER + 1]; int32_t len = 0; uint32_t precision = 0; len = UASDK_signed_integer_to_string((int64_t)sourceValue->Value(), precision, cstr, MAX_STR_LEN_FOR_64_BIT_INTEGER); if (len < 1) { return OpcUa_BadFilterOperandInvalid; } tPtr->Payload().Initialise(len); UASDK_memcpy(tPtr->Payload().Data(), cstr, len); targetType = tPtr; break; } case OpcUaId_UInt16: { IntrusivePtr_t<UInt16_t> tPtr = new SafeRefCount_t<UInt16_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if (sourceValue->Value() < 0) { return OpcUa_BadFilterOperandInvalid; } //transfer value tPtr->Value(static_cast<uint16_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_UInt32: { IntrusivePtr_t<UInt32_t> tPtr = new SafeRefCount_t<UInt32_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if (sourceValue->Value() < 0) { return OpcUa_BadFilterOperandInvalid; } //transfer value tPtr->Value(static_cast<uint32_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_UInt64: { IntrusivePtr_t<UInt64_t> tPtr = new SafeRefCount_t<UInt64_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if (sourceValue->Value() < 0) { return OpcUa_BadFilterOperandInvalid; } //transfer value tPtr->Value(static_cast<uint64_t>(sourceValue->Value())); targetType = tPtr; break; } default: return OpcUa_BadFilterOperandInvalid; break; } return status; } Status_t TypeConversion_t::ConvertInt32To(IntrusivePtr_t<BaseDataType_t>& sourceType, IntrusivePtr_t<BaseDataType_t>& targetType) { uint16_t targetNamespaceIndex; Status_t status = OpcUa_Good; IntrusivePtr_t<Int32_t> sourceValue; sourceValue.reset(new SafeRefCount_t<Int32_t>()); if (!sourceValue.is_set()) { return OpcUa_BadOutOfMemory; } status = sourceValue->CopyFrom(*sourceType); if (status.IsBad()) { return status; } switch (targetType->TypeId(targetNamespaceIndex)) { case OpcUaId_Boolean: { IntrusivePtr_t<Boolean_t> tPtr = new SafeRefCount_t<Boolean_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if (sourceValue->Value() < 0) { return OpcUa_BadFilterOperandInvalid; } //transfer value if (sourceValue->Value() > 0) { tPtr->Value(true); } else { tPtr->Value(false); } targetType = tPtr; break; } case OpcUaId_Byte: { IntrusivePtr_t<Byte_t> tPtr = new SafeRefCount_t<Byte_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if ((sourceValue->Value() < 0) || (sourceValue->Value() > UINT8_MAX)) { return OpcUa_BadFilterOperandInvalid; } //transfer value tPtr->Value(static_cast<uint8_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_Double: { IntrusivePtr_t<Double_t> tPtr = new SafeRefCount_t<Double_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value tPtr->Value(static_cast<double>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_Float: { IntrusivePtr_t<Float_t> tPtr = new SafeRefCount_t<Float_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value tPtr->Value(static_cast<float>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_SByte: { IntrusivePtr_t<SByte_t> tPtr = new SafeRefCount_t<SByte_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if ((sourceValue->Value() < INT8_MIN) || (sourceValue->Value() > INT8_MAX)) { return OpcUa_BadFilterOperandInvalid; } //transfer value tPtr->Value(static_cast<int8_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_Int16: { IntrusivePtr_t<Int16_t> tPtr = new SafeRefCount_t<Int16_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if ((sourceValue->Value() < INT16_MIN) || (sourceValue->Value() > INT16_MAX)) { return OpcUa_BadFilterOperandInvalid; } //transfer value tPtr->Value(static_cast<int16_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_Int32: { targetType = sourceValue; break; } case OpcUaId_Int64: { IntrusivePtr_t<Int64_t> tPtr = new SafeRefCount_t<Int64_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value tPtr->Value(static_cast<int64_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_StatusCode: { IntrusivePtr_t<StatusCode_t> tPtr = new SafeRefCount_t<StatusCode_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value uint32_t u32 = sourceValue->Value(); tPtr->Value().Value(u32); targetType = tPtr; break; } case OpcUaId_String: { IntrusivePtr_t<String_t> tPtr = new SafeRefCount_t<String_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } char cstr[MAX_STR_LEN_FOR_64_BIT_INTEGER + 1]; int32_t len = 0; uint32_t precision = 0; len = UASDK_signed_integer_to_string(sourceValue->Value(), precision, cstr, MAX_STR_LEN_FOR_64_BIT_INTEGER); if (len < 1) { return OpcUa_BadFilterOperandInvalid; } tPtr->Payload().Initialise(len); UASDK_memcpy(tPtr->Payload().Data(), cstr, len); targetType = tPtr; break; } case OpcUaId_UInt16: { IntrusivePtr_t<UInt16_t> tPtr = new SafeRefCount_t<UInt16_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if ((sourceValue->Value() < 0) || (sourceValue->Value() > UINT16_MAX)) { return OpcUa_BadFilterOperandInvalid; } //transfer value tPtr->Value(static_cast<uint16_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_UInt32: { IntrusivePtr_t<UInt32_t> tPtr = new SafeRefCount_t<UInt32_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if (sourceValue->Value() < 0) { return OpcUa_BadFilterOperandInvalid; } //transfer value tPtr->Value(static_cast<uint32_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_UInt64: { IntrusivePtr_t<UInt64_t> tPtr = new SafeRefCount_t<UInt64_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if (sourceValue->Value() < 0) { return OpcUa_BadFilterOperandInvalid; } //transfer value tPtr->Value(static_cast<uint64_t>(sourceValue->Value())); targetType = tPtr; break; } default: return OpcUa_BadFilterOperandInvalid; break; } return status; } Status_t TypeConversion_t::ConvertInt64To(IntrusivePtr_t<BaseDataType_t>& sourceType, IntrusivePtr_t<BaseDataType_t>& targetType) { uint16_t targetNamespaceIndex; Status_t status = OpcUa_Good; IntrusivePtr_t<Int64_t> sourceValue; sourceValue.reset(new SafeRefCount_t<Int64_t>()); if (!sourceValue.is_set()) { return OpcUa_BadOutOfMemory; } status = sourceValue->CopyFrom(*sourceType); if (status.IsBad()) { return status; } switch (targetType->TypeId(targetNamespaceIndex)) { case OpcUaId_Boolean: { IntrusivePtr_t<Boolean_t> tPtr = new SafeRefCount_t<Boolean_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if (sourceValue->Value() < 0) { return OpcUa_BadFilterOperandInvalid; } //transfer value if (sourceValue->Value() > 0) { tPtr->Value(true); } else { tPtr->Value(false); } targetType = tPtr; break; } case OpcUaId_Byte: { IntrusivePtr_t<Byte_t> tPtr = new SafeRefCount_t<Byte_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if ((sourceValue->Value() < 0) || (sourceValue->Value() > UINT8_MAX)) { return OpcUa_BadFilterOperandInvalid; } //transfer value tPtr->Value(static_cast<uint8_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_Double: { IntrusivePtr_t<Double_t> tPtr = new SafeRefCount_t<Double_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value tPtr->Value(static_cast<double>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_Float: { IntrusivePtr_t<Float_t> tPtr = new SafeRefCount_t<Float_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value tPtr->Value(static_cast<float>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_Int16: { IntrusivePtr_t<Int16_t> tPtr = new SafeRefCount_t<Int16_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if ((sourceValue->Value() < INT16_MIN) || (sourceValue->Value() > INT16_MAX)) { return OpcUa_BadFilterOperandInvalid; } //transfer value tPtr->Value(static_cast<int16_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_Int32: { IntrusivePtr_t<Int32_t> tPtr = new SafeRefCount_t<Int32_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if ((sourceValue->Value() < INT32_MIN) || (sourceValue->Value() > INT32_MAX)) { return OpcUa_BadFilterOperandInvalid; } //transfer value tPtr->Value(static_cast<int32_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_Int64: { targetType = sourceValue; break; } case OpcUaId_SByte: { IntrusivePtr_t<SByte_t> tPtr = new SafeRefCount_t<SByte_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if ((sourceValue->Value() < INT8_MIN) || (sourceValue->Value() > INT8_MAX)) { return OpcUa_BadFilterOperandInvalid; } //transfer value tPtr->Value(static_cast<int8_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_StatusCode: { IntrusivePtr_t<StatusCode_t> tPtr = new SafeRefCount_t<StatusCode_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if ((sourceValue->Value() < INT32_MIN) || (sourceValue->Value() > INT32_MAX)) { return OpcUa_BadFilterOperandInvalid; } //transfer value tPtr->Value() = static_cast<uint32_t>(sourceValue->Value()); targetType = tPtr; break; } case OpcUaId_String: { IntrusivePtr_t<String_t> tPtr = new SafeRefCount_t<String_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } char cstr[MAX_STR_LEN_FOR_64_BIT_INTEGER + 1]; int32_t len = 0; uint32_t precision = 0; len = UASDK_signed_integer_to_string(sourceValue->Value(), precision, cstr, MAX_STR_LEN_FOR_64_BIT_INTEGER); if (len < 1) { return OpcUa_BadFilterOperandInvalid; } tPtr->Payload().Initialise(len); UASDK_memcpy(tPtr->Payload().Data(), cstr, len); targetType = tPtr; break; } case OpcUaId_UInt16: { IntrusivePtr_t<UInt16_t> tPtr = new SafeRefCount_t<UInt16_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if ((sourceValue->Value() < 0) || (sourceValue->Value() > UINT16_MAX)) { return OpcUa_BadFilterOperandInvalid; } //transfer value tPtr->Value(static_cast<uint16_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_UInt32: { IntrusivePtr_t<UInt32_t> tPtr = new SafeRefCount_t<UInt32_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if ((sourceValue->Value() < 0) || (sourceValue->Value() > UINT32_MAX)) { return OpcUa_BadFilterOperandInvalid; } //transfer value tPtr->Value(static_cast<uint32_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_UInt64: { IntrusivePtr_t<UInt64_t> tPtr = new SafeRefCount_t<UInt64_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if (sourceValue->Value() < 0) { return OpcUa_BadFilterOperandInvalid; } //transfer value tPtr->Value(static_cast<uint64_t>(sourceValue->Value())); targetType = tPtr; break; } default: return OpcUa_BadFilterOperandInvalid; break; } return status; } Status_t TypeConversion_t::ConvertSByteTo(IntrusivePtr_t<BaseDataType_t>& sourceType, IntrusivePtr_t<BaseDataType_t>& targetType) { uint16_t targetNamespaceIndex; Status_t status = OpcUa_Good; IntrusivePtr_t<SByte_t> sourceValue; sourceValue.reset(new SafeRefCount_t<SByte_t>()); if (!sourceValue.is_set()) { return OpcUa_BadOutOfMemory; } status = sourceValue->CopyFrom(*sourceType); if (status.IsBad()) { return status; } switch (targetType->TypeId(targetNamespaceIndex)) { case OpcUaId_Boolean: { IntrusivePtr_t<Boolean_t> tPtr = new SafeRefCount_t<Boolean_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if (sourceValue->Value() < 0) { return OpcUa_BadFilterOperandInvalid; } //transfer value if (sourceValue->Value() > 0) { tPtr->Value(true); } else { tPtr->Value(false); } targetType = tPtr; break; } case OpcUaId_Double: { IntrusivePtr_t<Double_t> tPtr = new SafeRefCount_t<Double_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value tPtr->Value(static_cast<double>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_Float: { IntrusivePtr_t<Float_t> tPtr = new SafeRefCount_t<Float_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value tPtr->Value(static_cast<float>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_Int16: { IntrusivePtr_t<Int16_t> tPtr = new SafeRefCount_t<Int16_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value tPtr->Value(static_cast<int16_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_Int32: { IntrusivePtr_t<Int32_t> tPtr = new SafeRefCount_t<Int32_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value tPtr->Value(static_cast<int32_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_Int64: { IntrusivePtr_t<Int64_t> tPtr = new SafeRefCount_t<Int64_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value tPtr->Value(static_cast<int64_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_Byte: { IntrusivePtr_t<Byte_t> tPtr = new SafeRefCount_t<Byte_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if (sourceValue->Value() < 0) { return OpcUa_BadFilterOperandInvalid; } //transfer value tPtr->Value(static_cast<uint8_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_SByte: { targetType = sourceValue; break; } case OpcUaId_String: { IntrusivePtr_t<String_t> tPtr = new SafeRefCount_t<String_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } char cstr[MAX_STR_LEN_FOR_64_BIT_INTEGER + 1]; int32_t len = 0; uint32_t precision = 1; len = UASDK_signed_integer_to_string(sourceValue->Value(), precision, cstr, MAX_STR_LEN_FOR_64_BIT_INTEGER); if (len < 1) { return OpcUa_BadFilterOperandInvalid; } tPtr->Payload().Initialise(len); UASDK_memcpy(tPtr->Payload().Data(), cstr, len); targetType = tPtr; break; } case OpcUaId_UInt16: { IntrusivePtr_t<UInt16_t> tPtr = new SafeRefCount_t<UInt16_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if (sourceValue->Value() < 0) { return OpcUa_BadFilterOperandInvalid; } //transfer value tPtr->Value(static_cast<uint16_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_UInt32: { IntrusivePtr_t<UInt32_t> tPtr = new SafeRefCount_t<UInt32_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if (sourceValue->Value() < 0) { return OpcUa_BadFilterOperandInvalid; } //transfer value tPtr->Value(static_cast<uint32_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_UInt64: { IntrusivePtr_t<UInt64_t> tPtr = new SafeRefCount_t<UInt64_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if (sourceValue->Value() < 0) { return OpcUa_BadFilterOperandInvalid; } //transfer value tPtr->Value(static_cast<uint64_t>(sourceValue->Value())); targetType = tPtr; break; } default: return OpcUa_BadFilterOperandInvalid; break; } return status; } Status_t TypeConversion_t::ConvertStringTo(IntrusivePtr_t<BaseDataType_t>& sourceType, IntrusivePtr_t<BaseDataType_t>& targetType) { char *end; int32_t len; uint16_t targetNamespaceIndex; char cstr[MAX_STR_LEN_FOR_64_BIT_INTEGER + 1]; Status_t status = OpcUa_Good; IntrusivePtr_t<String_t> sourceValue; sourceValue.reset(new SafeRefCount_t<String_t>()); if (!sourceValue.is_set()) { return OpcUa_BadOutOfMemory; } status = sourceValue->CopyFrom(*sourceType); if (status.IsBad()) { return status; } len = sourceValue->Payload().Length(); if ((len < 1) || (sourceValue->Payload().Data() == 0)) { return OpcUa_BadFilterOperandInvalid; } switch (targetType->TypeId(targetNamespaceIndex)) { case OpcUaId_Boolean: { IntrusivePtr_t<Boolean_t> tPtr = new SafeRefCount_t<Boolean_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value uint8_t data0[] = "true"; uint8_t data1[] = "1"; if ((0 == UASDK_memcmp(sourceValue->Payload().Data(), data0, sourceValue->Payload().Length())) || (0 == UASDK_memcmp(sourceValue->Payload().Data(), data1, sourceValue->Payload().Length()))) { tPtr->Value(true); } else { uint8_t data2[] = "false"; uint8_t data3[] = "0"; if ((0 == UASDK_memcmp(sourceValue->Payload().Data(), data2, sourceValue->Payload().Length())) || (0 == UASDK_memcmp(sourceValue->Payload().Data(), data3, sourceValue->Payload().Length()))) { tPtr->Value(false); } else { return OpcUa_BadFilterOperandInvalid; } } targetType = tPtr; break; } case OpcUaId_Byte: { IntrusivePtr_t<Byte_t> tPtr = new SafeRefCount_t<Byte_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if (len > MAX_STR_LEN_FOR_64_BIT_INTEGER) { return OpcUa_BadFilterOperandInvalid; } UASDK_memcpy(cstr, sourceValue->Payload().Data(), len); cstr[len] = '\0'; end = 0; int64_t lnum = UASDK_strtoll(cstr, &end, 10); if ((end == cstr) || (*end != '\0') ) { return OpcUa_BadFilterOperandInvalid; } if ((lnum > UINT8_MAX) || (lnum < 0)) { return OpcUa_BadFilterOperandInvalid; } tPtr->Value(static_cast<uint8_t>(lnum)); targetType = tPtr; break; } case OpcUaId_DateTime: { IntrusivePtr_t<DateTime_t> tPtr = new SafeRefCount_t<DateTime_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if (len > MAX_STR_LEN_FOR_64_BIT_INTEGER) { return OpcUa_BadFilterOperandInvalid; } UASDK_memcpy(cstr, sourceValue->Payload().Data(), len); cstr[len] = '\0'; end = 0; int64_t lnum = UASDK_strtoll(cstr, &end, 10); if ((end == cstr) || (*end != '\0') ) { return OpcUa_BadFilterOperandInvalid; } if (lnum > INT64_MAX || lnum < INT64_MIN) { return OpcUa_BadFilterOperandInvalid; } tPtr->Value(lnum); targetType = tPtr; break; } case OpcUaId_Double: { IntrusivePtr_t<Double_t> tPtr = new SafeRefCount_t<Double_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if (len > MAX_STR_LEN_FOR_64_BIT_INTEGER) { return OpcUa_BadFilterOperandInvalid; } UASDK_memcpy(cstr, sourceValue->Payload().Data(), len); cstr[len] = '\0'; double dnum = UASDK_strtod(cstr, &end); if (end == cstr) { return OpcUa_BadFilterOperandInvalid; } tPtr->Value(dnum); targetType = tPtr; break; } case OpcUaId_ExpandedNodeId: { IntrusivePtr_t<ExpandedNodeId_t> tPtr; status = ConvertStringToExpandedNodeid(sourceValue, tPtr); if (status.IsBad()) { return status; } targetType = tPtr; break; } case OpcUaId_Float: { IntrusivePtr_t<Float_t> tPtr = new SafeRefCount_t<Float_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if (len > MAX_STR_LEN_FOR_64_BIT_INTEGER) { return OpcUa_BadFilterOperandInvalid; } UASDK_memcpy(cstr, sourceValue->Payload().Data(), len); cstr[len] = '\0'; float fnum = UASDK_strtof(cstr, &end); if (end == cstr) { return OpcUa_BadFilterOperandInvalid; } tPtr->Value(fnum); targetType = tPtr; break; } case OpcUaId_Guid: { IntrusivePtr_t<Guid_t> tPtr = new SafeRefCount_t<Guid_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } status = ConvertStringToGuid(sourceValue, tPtr); if (status.IsBad()) { return status; } targetType = tPtr; break; } case OpcUaId_Int16: { IntrusivePtr_t<Int16_t> tPtr = new SafeRefCount_t<Int16_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if (len > MAX_STR_LEN_FOR_64_BIT_INTEGER) { return OpcUa_BadFilterOperandInvalid; } UASDK_memcpy(cstr, sourceValue->Payload().Data(), len); cstr[len] = '\0'; end = 0; int64_t lnum = UASDK_strtoll(cstr, &end, 10); if ((end == cstr) || (*end != '\0') ) { return OpcUa_BadFilterOperandInvalid; } if (lnum > INT16_MAX || lnum < INT16_MIN) { return OpcUa_BadFilterOperandInvalid; } tPtr->Value(static_cast<int16_t>(lnum)); targetType = tPtr; break; } case OpcUaId_Int32: { IntrusivePtr_t<Int32_t> tPtr = new SafeRefCount_t<Int32_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if (len > MAX_STR_LEN_FOR_64_BIT_INTEGER) { return OpcUa_BadFilterOperandInvalid; } UASDK_memcpy(cstr, sourceValue->Payload().Data(), len); cstr[len] = '\0'; end = 0; int64_t lnum = UASDK_strtoll(cstr, &end, 10); if ((end == cstr) || (*end != '\0') ) { return OpcUa_BadFilterOperandInvalid; } if (lnum > INT32_MAX || lnum < INT32_MIN) { return OpcUa_BadFilterOperandInvalid; } tPtr->Value(static_cast<int32_t>(lnum)); targetType = tPtr; break; } case OpcUaId_Int64: { IntrusivePtr_t<Int64_t> tPtr = new SafeRefCount_t<Int64_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if (len > MAX_STR_LEN_FOR_64_BIT_INTEGER) { return OpcUa_BadFilterOperandInvalid; } UASDK_memcpy(cstr, sourceValue->Payload().Data(), len); cstr[len] = '\0'; end = 0; int64_t lnum = UASDK_strtoll(cstr, &end, 10); if ((end == cstr) || (*end != '\0') ) { return OpcUa_BadFilterOperandInvalid; } if (lnum > INT64_MAX || lnum < INT64_MIN) { return OpcUa_BadFilterOperandInvalid; } tPtr->Value(lnum); targetType = tPtr; break; } case OpcUaId_NodeId: { IntrusivePtr_t<NodeId_t> tPtr; status = ConvertStringToNodeId(sourceValue, tPtr); if (status.IsBad()) { return status; } targetType = tPtr; break; } case OpcUaId_SByte: { IntrusivePtr_t<SByte_t> tPtr = new SafeRefCount_t<SByte_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if (len > MAX_STR_LEN_FOR_64_BIT_INTEGER) { return OpcUa_BadFilterOperandInvalid; } UASDK_memcpy(cstr, sourceValue->Payload().Data(), len); cstr[len] = '\0'; end = 0; int64_t lnum = UASDK_strtoll(cstr, &end, 10); if ((end == cstr) || (*end != '\0') ) { return OpcUa_BadFilterOperandInvalid; } if (lnum > INT8_MAX || lnum < INT8_MIN) { return OpcUa_BadFilterOperandInvalid; } tPtr->Value(static_cast<int8_t>(lnum)); targetType = tPtr; break; } case OpcUaId_String: { targetType = sourceValue; break; } case OpcUaId_LocalizedText: { IntrusivePtr_t<LocalizedText_t> tPtr = new SafeRefCount_t<LocalizedText_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } IntrusivePtr_t<String_t> nullStrPtr = new SafeRefCount_t<String_t>(); if (!nullStrPtr.is_set()) { return OpcUa_BadOutOfMemory; } //set to a NuLL string nullStrPtr->Payload().Initialise(-1); //transfer value tPtr->Locale().CopyFrom(*nullStrPtr); tPtr->Text().CopyFrom(*sourceValue); targetType = tPtr; break; } case OpcUaId_QualifiedName: { IntrusivePtr_t<QualifiedName_t> tPtr = new SafeRefCount_t<QualifiedName_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value tPtr->NamespaceIndex().Value(0); tPtr->Name().CopyFrom(*sourceValue); targetType = tPtr; break; } case OpcUaId_UInt16: { IntrusivePtr_t<UInt16_t> tPtr = new SafeRefCount_t<UInt16_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if (len > MAX_STR_LEN_FOR_64_BIT_INTEGER) { return OpcUa_BadFilterOperandInvalid; } UASDK_memcpy(cstr, sourceValue->Payload().Data(), len); cstr[len] = '\0'; end = 0; int64_t lnum = UASDK_strtoll(cstr, &end, 10); if ((end == cstr) || (*end != '\0') ) { return OpcUa_BadFilterOperandInvalid; } if ((lnum > UINT16_MAX) || (lnum < 0)) { return OpcUa_BadFilterOperandInvalid; } tPtr->Value(static_cast<uint16_t>(lnum)); targetType = tPtr; break; } case OpcUaId_UInt32: { IntrusivePtr_t<UInt32_t> tPtr = new SafeRefCount_t<UInt32_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if (len > MAX_STR_LEN_FOR_64_BIT_INTEGER) { return OpcUa_BadFilterOperandInvalid; } UASDK_memcpy(cstr, sourceValue->Payload().Data(), len); cstr[len] = '\0'; end = 0; int64_t lnum = UASDK_strtoll(cstr, &end, 10); if ((end == cstr) || (*end != '\0') ) { return OpcUa_BadFilterOperandInvalid; } if ((lnum > UINT32_MAX) || (lnum < 0)) { return OpcUa_BadFilterOperandInvalid; } tPtr->Value(static_cast<uint32_t>(lnum)); targetType = tPtr; break; } case OpcUaId_UInt64: { IntrusivePtr_t<UInt64_t> tPtr = new SafeRefCount_t<UInt64_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if (len > MAX_STR_LEN_FOR_64_BIT_INTEGER) { return OpcUa_BadFilterOperandInvalid; } UASDK_memcpy(cstr, sourceValue->Payload().Data(), len); cstr[len] = '\0'; end = 0; int64_t lnum = UASDK_strtoll(cstr, &end, 10); if ((end == cstr) || (*end != '\0') ) { return OpcUa_BadFilterOperandInvalid; } if ((lnum > UINT64_MAX) || (lnum < 0)) { return OpcUa_BadFilterOperandInvalid; } tPtr->Value(static_cast<uint64_t>(lnum)); targetType = tPtr; break; } default: return OpcUa_BadFilterOperandInvalid; break; } return status; } Status_t TypeConversion_t::ConvertUInt16To(IntrusivePtr_t<BaseDataType_t>& sourceType, IntrusivePtr_t<BaseDataType_t>& targetType) { uint16_t targetNamespaceIndex; Status_t status = OpcUa_Good; IntrusivePtr_t<UInt16_t> sourceValue; sourceValue.reset(new SafeRefCount_t<UInt16_t>()); if (!sourceValue.is_set()) { return OpcUa_BadOutOfMemory; } status = sourceValue->CopyFrom(*sourceType); if (status.IsBad()) { return status; } switch (targetType->TypeId(targetNamespaceIndex)) { case OpcUaId_Boolean: { IntrusivePtr_t<Boolean_t> tPtr = new SafeRefCount_t<Boolean_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value if (sourceValue->Value() > 0) { tPtr->Value(true); } else { tPtr->Value(false); } targetType = tPtr; break; } case OpcUaId_Byte: { IntrusivePtr_t<Byte_t> tPtr = new SafeRefCount_t<Byte_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if (sourceValue->Value() > UINT8_MAX) { return OpcUa_BadFilterOperandInvalid; } //transfer value tPtr->Value(static_cast<uint8_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_Double: { IntrusivePtr_t<Double_t> tPtr = new SafeRefCount_t<Double_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value tPtr->Value(static_cast<double>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_Float: { IntrusivePtr_t<Float_t> tPtr = new SafeRefCount_t<Float_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value tPtr->Value(static_cast<float>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_SByte: { IntrusivePtr_t<SByte_t> tPtr = new SafeRefCount_t<SByte_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if (sourceValue->Value() > INT8_MAX) { return OpcUa_BadFilterOperandInvalid; } //transfer value tPtr->Value(static_cast<int8_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_Int16: { IntrusivePtr_t<Int16_t> tPtr = new SafeRefCount_t<Int16_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if (sourceValue->Value() > INT16_MAX) { return OpcUa_BadFilterOperandInvalid; } //transfer value tPtr->Value(static_cast<int16_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_Int32: { IntrusivePtr_t<Int32_t> tPtr = new SafeRefCount_t<Int32_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value tPtr->Value(static_cast<int32_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_Int64: { IntrusivePtr_t<Int64_t> tPtr = new SafeRefCount_t<Int64_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value tPtr->Value(static_cast<int64_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_StatusCode: { IntrusivePtr_t<StatusCode_t> tPtr = new SafeRefCount_t<StatusCode_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value uint16_t u16 = sourceValue->Value(); uint32_t value = tPtr->Value().Value(); value = (value & 0xffff) | ((u16 << 16) & 0xffff0000); tPtr->Value().Value(value); targetType = tPtr; break; } case OpcUaId_String: { IntrusivePtr_t<String_t> tPtr = new SafeRefCount_t<String_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } char cstr[MAX_STR_LEN_FOR_64_BIT_INTEGER + 1]; int32_t len = 0; uint32_t precision = 0; len = UASDK_unsigned_integer_to_string(sourceValue->Value(), precision, cstr, MAX_STR_LEN_FOR_64_BIT_INTEGER); if (len < 1) { return OpcUa_BadFilterOperandInvalid; } tPtr->Payload().Initialise(len); UASDK_memcpy(tPtr->Payload().Data(), cstr, len); targetType = tPtr; break; } case OpcUaId_UInt16: { targetType = sourceValue; break; } case OpcUaId_UInt32: { IntrusivePtr_t<UInt32_t> tPtr = new SafeRefCount_t<UInt32_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value tPtr->Value(static_cast<uint32_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_UInt64: { IntrusivePtr_t<UInt64_t> tPtr = new SafeRefCount_t<UInt64_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value tPtr->Value(static_cast<uint64_t>(sourceValue->Value())); targetType = tPtr; break; } default: return OpcUa_BadFilterOperandInvalid; break; } return status; } Status_t TypeConversion_t::ConvertUInt32To(IntrusivePtr_t<BaseDataType_t>& sourceType, IntrusivePtr_t<BaseDataType_t>& targetType) { uint16_t targetNamespaceIndex; Status_t status = OpcUa_Good; IntrusivePtr_t<UInt32_t> sourceValue; sourceValue.reset(new SafeRefCount_t<UInt32_t>()); if (!sourceValue.is_set()) { return OpcUa_BadOutOfMemory; } status = sourceValue->CopyFrom(*sourceType); if (status.IsBad()) { return status; } switch (targetType->TypeId(targetNamespaceIndex)) { case OpcUaId_Boolean: { IntrusivePtr_t<Boolean_t> tPtr = new SafeRefCount_t<Boolean_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value if (sourceValue->Value() > 0) { tPtr->Value(true); } else { tPtr->Value(false); } targetType = tPtr; break; } case OpcUaId_Byte: { IntrusivePtr_t<Byte_t> tPtr = new SafeRefCount_t<Byte_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if (sourceValue->Value() > UINT8_MAX) { return OpcUa_BadFilterOperandInvalid; } //transfer value tPtr->Value(static_cast<uint8_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_Double: { IntrusivePtr_t<Double_t> tPtr = new SafeRefCount_t<Double_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value tPtr->Value(static_cast<double>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_Float: { IntrusivePtr_t<Float_t> tPtr = new SafeRefCount_t<Float_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value tPtr->Value(static_cast<float>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_SByte: { IntrusivePtr_t<SByte_t> tPtr = new SafeRefCount_t<SByte_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if (sourceValue->Value() > INT8_MAX) { return OpcUa_BadFilterOperandInvalid; } //transfer value tPtr->Value(static_cast<int8_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_Int16: { IntrusivePtr_t<Int16_t> tPtr = new SafeRefCount_t<Int16_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if (sourceValue->Value() > INT16_MAX) { return OpcUa_BadFilterOperandInvalid; } //transfer value tPtr->Value(static_cast<int16_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_Int32: { IntrusivePtr_t<Int32_t> tPtr = new SafeRefCount_t<Int32_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if (sourceValue->Value() > INT32_MAX) { return OpcUa_BadFilterOperandInvalid; } //transfer value tPtr->Value(static_cast<int32_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_Int64: { IntrusivePtr_t<Int64_t> tPtr = new SafeRefCount_t<Int64_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value tPtr->Value(static_cast<int64_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_StatusCode: { IntrusivePtr_t<StatusCode_t> tPtr = new SafeRefCount_t<StatusCode_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value uint32_t u32 = sourceValue->Value(); tPtr->Value().Value(u32); targetType = tPtr; break; } case OpcUaId_String: { IntrusivePtr_t<String_t> tPtr = new SafeRefCount_t<String_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } char cstr[MAX_STR_LEN_FOR_64_BIT_INTEGER + 1]; int32_t len = 0; uint32_t precision = 1; len = UASDK_unsigned_integer_to_string(sourceValue->Value(), precision, cstr, MAX_STR_LEN_FOR_64_BIT_INTEGER); if (len < 1) { return OpcUa_BadFilterOperandInvalid; } tPtr->Payload().Initialise(len); UASDK_memcpy(tPtr->Payload().Data(), cstr, len); targetType = tPtr; break; } case OpcUaId_UInt16: { IntrusivePtr_t<UInt16_t> tPtr = new SafeRefCount_t<UInt16_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if (sourceValue->Value() > UINT16_MAX) { return OpcUa_BadFilterOperandInvalid; } //transfer value tPtr->Value(static_cast<uint16_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_UInt32: { targetType = sourceValue; break; } case OpcUaId_UInt64: { IntrusivePtr_t<UInt64_t> tPtr = new SafeRefCount_t<UInt64_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value tPtr->Value(static_cast<uint64_t>(sourceValue->Value())); targetType = tPtr; break; } default: return OpcUa_BadFilterOperandInvalid; break; } return status; } Status_t TypeConversion_t::ConvertUInt64To(IntrusivePtr_t<BaseDataType_t>& sourceType, IntrusivePtr_t<BaseDataType_t>& targetType) { uint16_t targetNamespaceIndex; Status_t status = OpcUa_Good; IntrusivePtr_t<UInt64_t> sourceValue; sourceValue.reset(new SafeRefCount_t<UInt64_t>()); if (!sourceValue.is_set()) { return OpcUa_BadOutOfMemory; } status = sourceValue->CopyFrom(*sourceType); if (status.IsBad()) { return status; } switch (targetType->TypeId(targetNamespaceIndex)) { case OpcUaId_Boolean: { IntrusivePtr_t<Boolean_t> tPtr = new SafeRefCount_t<Boolean_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value if (sourceValue->Value() > 0) { tPtr->Value(true); } else { tPtr->Value(false); } targetType = tPtr; break; } case OpcUaId_Byte: { IntrusivePtr_t<Byte_t> tPtr = new SafeRefCount_t<Byte_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if (sourceValue->Value() > UINT8_MAX) { return OpcUa_BadFilterOperandInvalid; } //transfer value tPtr->Value(static_cast<uint8_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_Double: { IntrusivePtr_t<Double_t> tPtr = new SafeRefCount_t<Double_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value tPtr->Value(static_cast<double>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_Float: { IntrusivePtr_t<Float_t> tPtr = new SafeRefCount_t<Float_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value tPtr->Value(static_cast<float>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_Int16: { IntrusivePtr_t<Int16_t> tPtr = new SafeRefCount_t<Int16_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if (sourceValue->Value() > INT16_MAX) { return OpcUa_BadFilterOperandInvalid; } //transfer value tPtr->Value(static_cast<int16_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_Int32: { IntrusivePtr_t<Int32_t> tPtr = new SafeRefCount_t<Int32_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if (sourceValue->Value() > INT32_MAX) { return OpcUa_BadFilterOperandInvalid; } //transfer value tPtr->Value(static_cast<int32_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_Int64: { IntrusivePtr_t<Int64_t> tPtr = new SafeRefCount_t<Int64_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if (sourceValue->Value() > INT64_MAX) { return OpcUa_BadFilterOperandInvalid; } //transfer value tPtr->Value(static_cast<int64_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_SByte: { IntrusivePtr_t<SByte_t> tPtr = new SafeRefCount_t<SByte_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if (sourceValue->Value() > INT8_MAX) { return OpcUa_BadFilterOperandInvalid; } //transfer value tPtr->Value(static_cast<int8_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_StatusCode: { IntrusivePtr_t<StatusCode_t> tPtr = new SafeRefCount_t<StatusCode_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if (sourceValue->Value() > UINT32_MAX) { return OpcUa_BadFilterOperandInvalid; } //transfer value tPtr->Value() = static_cast<uint32_t>(sourceValue->Value()); targetType = tPtr; break; } case OpcUaId_String: { IntrusivePtr_t<String_t> tPtr = new SafeRefCount_t<String_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } char cstr[MAX_STR_LEN_FOR_64_BIT_INTEGER + 1]; int32_t len = 0; uint32_t precision = 0; len = UASDK_unsigned_integer_to_string(sourceValue->Value(), precision, cstr, MAX_STR_LEN_FOR_64_BIT_INTEGER); if (len < 1) { return OpcUa_BadFilterOperandInvalid; } tPtr->Payload().Initialise(len); UASDK_memcpy(tPtr->Payload().Data(), cstr, len); targetType = tPtr; break; } case OpcUaId_UInt16: { IntrusivePtr_t<UInt16_t> tPtr = new SafeRefCount_t<UInt16_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if (sourceValue->Value() > UINT16_MAX) { return OpcUa_BadFilterOperandInvalid; } //transfer value tPtr->Value(static_cast<uint16_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_UInt32: { IntrusivePtr_t<UInt32_t> tPtr = new SafeRefCount_t<UInt32_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if (sourceValue->Value() > UINT32_MAX) { return OpcUa_BadFilterOperandInvalid; } //transfer value tPtr->Value(static_cast<uint32_t>(sourceValue->Value())); targetType = tPtr; break; } case OpcUaId_UInt64: { targetType = sourceValue; break; } default: return OpcUa_BadFilterOperandInvalid; break; } return status; } Status_t TypeConversion_t::ConvertByteStringTo(IntrusivePtr_t<BaseDataType_t>& sourceType, IntrusivePtr_t<BaseDataType_t>& targetType) { uint16_t targetNamespaceIndex; Status_t status = OpcUa_Good; IntrusivePtr_t<ByteString_t> sPtr; sPtr.reset(new SafeRefCount_t<ByteString_t>()); if (!sPtr.is_set()) { return OpcUa_BadOutOfMemory; } status = sPtr->CopyFrom(*sourceType); if (status.IsBad()) { return status; } switch (targetType->TypeId(targetNamespaceIndex)) { case OpcUaId_Guid: { IntrusivePtr_t<Guid_t> tPtr = new SafeRefCount_t<Guid_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } if (sPtr->Length() != Guid_t::GUID_LENGTH) { return OpcUa_BadFilterOperandInvalid; } //transfer value UASDK_memcpy(tPtr->Value(), sPtr->Data(), Guid_t::GUID_LENGTH); targetType = tPtr; break; } case OpcUaId_ByteString: { targetType = sPtr; break; } default: return OpcUa_BadFilterOperandInvalid; break; } return status; } Status_t TypeConversion_t::ConvertDateTimeTo(IntrusivePtr_t<BaseDataType_t>& sourceType, IntrusivePtr_t<BaseDataType_t>& targetType) { uint16_t targetNamespaceIndex; Status_t status = OpcUa_Good; IntrusivePtr_t<DateTime_t> sPtr; sPtr.reset(new SafeRefCount_t<DateTime_t>()); if (!sPtr.is_set()) { return OpcUa_BadOutOfMemory; } status = sPtr->CopyFrom(*sourceType); if (status.IsBad()) { return status; } switch (targetType->TypeId(targetNamespaceIndex)) { case OpcUaId_String: { IntrusivePtr_t<String_t> tPtr = new SafeRefCount_t<String_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } char cstr[MAX_STR_LEN_FOR_64_BIT_INTEGER + 1]; int32_t len = 0; uint32_t precision = 1; len = UASDK_signed_integer_to_string(sPtr->Value(), precision, cstr, MAX_STR_LEN_FOR_64_BIT_INTEGER); if (len < 1) { return OpcUa_BadFilterOperandInvalid; } tPtr->Payload().Initialise(len); UASDK_memcpy(tPtr->Payload().Data(), cstr, len); targetType = tPtr; break; } case OpcUaId_DateTime: { targetType = sPtr; break; } default: return OpcUa_BadFilterOperandInvalid; break; } return status; } Status_t TypeConversion_t::ConvertExpandedNodeIdTo(IntrusivePtr_t<BaseDataType_t>& sourceType, IntrusivePtr_t<BaseDataType_t>& targetType) { uint16_t targetNamespaceIndex; Status_t status = OpcUa_Good; IntrusivePtr_t<ExpandedNodeId_t> sPtr; sPtr.reset(new SafeRefCount_t<ExpandedNodeId_t>()); if (!sPtr.is_set()) { return OpcUa_BadOutOfMemory; } status = sPtr->CopyFrom(*sourceType); if (status.IsBad()) { return status; } switch (targetType->TypeId(targetNamespaceIndex)) { case OpcUaId_NodeId: { IntrusivePtr_t<NodeId_t> tPtr; //transfer value status = sPtr->Nodeid()->CopyToNodeId(tPtr); if (status.IsBad()) { return status; } targetType = tPtr; break; } case OpcUaId_String: { IntrusivePtr_t<String_t> tPtr; status = ConvertExpandedNodeidToString(sPtr, tPtr); if (status.IsBad()) { return status; } targetType = tPtr; break; } case OpcUaId_ExpandedNodeId: { targetType = sPtr; break; } default: return OpcUa_BadFilterOperandInvalid; break; } return status; } Status_t TypeConversion_t::ConvertGuidTo(IntrusivePtr_t<BaseDataType_t>& sourceType, IntrusivePtr_t<BaseDataType_t>& targetType) { uint16_t targetNamespaceIndex; Status_t status = OpcUa_Good; IntrusivePtr_t<Guid_t> sPtr; sPtr.reset(new SafeRefCount_t<Guid_t>()); if (!sPtr.is_set()) { return OpcUa_BadOutOfMemory; } status = sPtr->CopyFrom(*sourceType); if (status.IsBad()) { return status; } switch (targetType->TypeId(targetNamespaceIndex)) { case OpcUaId_ByteString: { IntrusivePtr_t<ByteString_t> tPtr = new SafeRefCount_t<ByteString_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value status = tPtr->Initialise(Guid_t::GUID_LENGTH); if (status.IsBad()) { return status; } UASDK_memcpy(tPtr->Data(), sPtr->Value(), Guid_t::GUID_LENGTH); targetType = tPtr; break; } case OpcUaId_String: { IntrusivePtr_t<String_t> tPtr = new SafeRefCount_t<String_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value status = ConvertGuidToString(sPtr, tPtr); if (status.IsBad()) { return status; } targetType = tPtr; break; } case OpcUaId_Guid: { targetType = sPtr; break; } default: return OpcUa_BadFilterOperandInvalid; break; } return status; } Status_t TypeConversion_t::ConvertNodeIdTo(IntrusivePtr_t<BaseDataType_t>& sourceType, IntrusivePtr_t<BaseDataType_t>& targetType) { uint16_t targetNamespaceIndex; Status_t status = OpcUa_Good; IntrusivePtr_t<NodeId_t> sPtr = RuntimeCast<NodeId_t*>(*sourceType); if (status.IsBad()) { return status; } switch (targetType->TypeId(targetNamespaceIndex)) { case OpcUaId_ExpandedNodeId: { IntrusivePtr_t<ExpandedNodeId_t> tPtr = new SafeRefCount_t<ExpandedNodeId_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } sPtr->CopyToNodeId(tPtr->Nodeid()); if (status.IsBad()) { return status; } tPtr->NamespaceUri().Payload().Initialise(-1); tPtr->ServerIndex().Value(0); targetType = tPtr; break; } case OpcUaId_String: { IntrusivePtr_t<String_t> tPtr; status = ConvertNodeIdToString(sPtr, tPtr); if (status.IsBad()) { return status; } targetType = tPtr; break; } case OpcUaId_NodeId: { targetType = sPtr; break; } default: return OpcUa_BadFilterOperandInvalid; break; } return status; } Status_t TypeConversion_t::ConvertStatusCodeTo(IntrusivePtr_t<BaseDataType_t>& sourceType, IntrusivePtr_t<BaseDataType_t>& targetType) { uint16_t targetNamespaceIndex; Status_t status = OpcUa_Good; IntrusivePtr_t<StatusCode_t> suPtr; suPtr.reset(new SafeRefCount_t<StatusCode_t>()); if (!suPtr.is_set()) { return OpcUa_BadOutOfMemory; } status = suPtr->CopyFrom(*sourceType); if (status.IsBad()) { return status; } IntrusivePtr_t<UInt32_t> sPtr; sPtr.reset(new SafeRefCount_t<UInt32_t>()); if (!sPtr.is_set()) { return OpcUa_BadOutOfMemory; } status = sPtr->CopyFrom(suPtr->Value()); if (status.IsBad()) { return status; } switch (targetType->TypeId(targetNamespaceIndex)) { case OpcUaId_Int32: { IntrusivePtr_t<Int32_t> tPtr = new SafeRefCount_t<Int32_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value tPtr->Value(static_cast<int32_t>(sPtr->Value())); targetType = tPtr; break; } case OpcUaId_Int64: { IntrusivePtr_t<Int64_t> tPtr = new SafeRefCount_t<Int64_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value tPtr->Value(static_cast<int64_t>(sPtr->Value())); targetType = tPtr; break; } case OpcUaId_UInt16: { IntrusivePtr_t<UInt16_t> tPtr = new SafeRefCount_t<UInt16_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value uint16_t u16 = (sPtr->Value() >> 16) & 0xffff; tPtr->Value(u16); targetType = tPtr; break; } case OpcUaId_UInt32: { IntrusivePtr_t<UInt32_t> tPtr = new SafeRefCount_t<UInt32_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value tPtr->Value(static_cast<uint32_t>(sPtr->Value())); targetType = tPtr; break; } case OpcUaId_UInt64: { IntrusivePtr_t<UInt64_t> tPtr = new SafeRefCount_t<UInt64_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value tPtr->Value(static_cast<uint64_t>(sPtr->Value())); targetType = tPtr; break; } case OpcUaId_StatusCode: { targetType = suPtr; break; } default: return OpcUa_BadFilterOperandInvalid; break; } return status; } Status_t TypeConversion_t::ConvertLocalizedTextTo(IntrusivePtr_t<BaseDataType_t>& sourceType, IntrusivePtr_t<BaseDataType_t>& targetType) { uint16_t targetNamespaceIndex; Status_t status = OpcUa_Good; IntrusivePtr_t<LocalizedText_t> sPtr; sPtr.reset(new SafeRefCount_t<LocalizedText_t>()); if (!sPtr.is_set()) { return OpcUa_BadOutOfMemory; } status = sPtr->CopyFrom(*sourceType); if (status.IsBad()) { return status; } switch (targetType->TypeId(targetNamespaceIndex)) { case OpcUaId_String: { IntrusivePtr_t<String_t> tPtr = new SafeRefCount_t<String_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value tPtr->CopyFrom(sPtr->Text()); targetType = tPtr; break; } case OpcUaId_LocalizedText: { targetType = sPtr; break; } default: return OpcUa_BadFilterOperandInvalid; break; } return status; } Status_t TypeConversion_t::ConvertQualifiedNameTo(IntrusivePtr_t<BaseDataType_t>& sourceType, IntrusivePtr_t<BaseDataType_t>& targetType) { uint16_t targetNamespaceIndex; Status_t status = OpcUa_Good; IntrusivePtr_t<QualifiedName_t> sPtr; sPtr.reset(new SafeRefCount_t<QualifiedName_t>()); if (!sPtr.is_set()) { return OpcUa_BadOutOfMemory; } status = sPtr->CopyFrom(*sourceType); if (status.IsBad()) { return status; } switch (targetType->TypeId(targetNamespaceIndex)) { case OpcUaId_LocalizedText: { IntrusivePtr_t<LocalizedText_t> tPtr = new SafeRefCount_t<LocalizedText_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } IntrusivePtr_t<String_t> springptr = new SafeRefCount_t<String_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //set to a NuLL string springptr->Payload().Initialise(-1); //transfer value tPtr->Text().CopyFrom(sPtr->Name()); tPtr->Locale().CopyFrom(*springptr); targetType = tPtr; break; } case OpcUaId_String: { IntrusivePtr_t<String_t> tPtr = new SafeRefCount_t<String_t>(); if (!tPtr.is_set()) { return OpcUa_BadOutOfMemory; } //transfer value tPtr->CopyFrom(sPtr->Name()); targetType = tPtr; break; } case OpcUaId_QualifiedName: { targetType = sPtr; break; } default: return OpcUa_BadFilterOperandInvalid; break; } return status; } Status_t TypeConversion_t::ConvertXmlElementTo(IntrusivePtr_t<BaseDataType_t>& sourceType, IntrusivePtr_t<BaseDataType_t>& targetType) { uint16_t targetNamespaceIndex; Status_t status = OpcUa_Good; IntrusivePtr_t<XmlElement_t> sPtr; sPtr.reset(new SafeRefCount_t<XmlElement_t>()); if (!sPtr.is_set()) { return OpcUa_BadOutOfMemory; } status = sPtr->CopyFrom(*sourceType); if (status.IsBad()) { return status; } switch (targetType->TypeId(targetNamespaceIndex)) { case OpcUaId_XmlElement: { targetType = sPtr; break; } default: return OpcUa_BadFilterOperandInvalid; break; } return status; } // this function is called only if the data type of sourceType is different from the data type of targetType Status_t TypeConversion_t::TypeConversionRule(IntrusivePtr_t<BaseDataType_t>& sourceType, IntrusivePtr_t<BaseDataType_t>& targetType) { uint16_t sourceNamespaceIndex; Status_t status = OpcUa_Good; if (!sourceType.is_set()) { return OpcUa_BadFilterOperandInvalid; } switch (sourceType->TypeId(sourceNamespaceIndex)) { case OpcUaId_Boolean: { status = ConvertBooleanTo(sourceType, targetType); if (status.IsBad()) { return status; } break; } case OpcUaId_Byte: { status = ConvertByteTo(sourceType, targetType); if (status.IsBad()) { return status; } break; } case OpcUaId_ByteString: { status = ConvertByteStringTo(sourceType, targetType); if (status.IsBad()) { return status; } break; } case OpcUaId_DateTime: { status = ConvertDateTimeTo(sourceType, targetType); if (status.IsBad()) { return status; } break; } case OpcUaId_Double: { status = ConvertDoubleTo(sourceType, targetType); if (status.IsBad()) { return status; } break; } case OpcUaId_ExpandedNodeId: { status = ConvertExpandedNodeIdTo(sourceType, targetType); if (status.IsBad()) { return status; } break; } case OpcUaId_Float: { status = ConvertFloatTo(sourceType, targetType); if (status.IsBad()) { return status; } break; } case OpcUaId_Guid: { status = ConvertGuidTo(sourceType, targetType); if (status.IsBad()) { return status; } break; } case OpcUaId_Int16: { status = ConvertInt16To(sourceType, targetType); if (status.IsBad()) { return status; } break; } case OpcUaId_Int32: { status = ConvertInt32To(sourceType, targetType); if (status.IsBad()) { return status; } break; } case OpcUaId_Int64: { status = ConvertInt64To(sourceType, targetType); if (status.IsBad()) { return status; } break; } case OpcUaId_NodeId: { status = ConvertNodeIdTo(sourceType, targetType); if (status.IsBad()) { return status; } break; } case OpcUaId_SByte: { status = ConvertSByteTo(sourceType, targetType); if (status.IsBad()) { return status; } break; } case OpcUaId_StatusCode: { status = ConvertStatusCodeTo(sourceType, targetType); if (status.IsBad()) { return status; } break; } case OpcUaId_String: { status = ConvertStringTo(sourceType, targetType); if (status.IsBad()) { return status; } break; } case OpcUaId_LocalizedText: { status = ConvertLocalizedTextTo(sourceType, targetType); if (status.IsBad()) { return status; } break; } case OpcUaId_QualifiedName: { status = ConvertQualifiedNameTo(sourceType, targetType); if (status.IsBad()) { return status; } break; } case OpcUaId_UInt16: { status = ConvertUInt16To(sourceType, targetType); if (status.IsBad()) { return status; } break; } case OpcUaId_UInt32: { status = ConvertUInt32To(sourceType, targetType); if (status.IsBad()) { return status; } break; } case OpcUaId_UInt64: { status = ConvertUInt64To(sourceType, targetType); if (status.IsBad()) { return status; } break; } case OpcUaId_XmlElement: { status = ConvertXmlElementTo(sourceType, targetType); if (status.IsBad()) { return status; } break; } default: return OpcUa_BadFilterOperandInvalid; break; } return OpcUa_Good; } Status_t TypeConversion_t::IsValidPrecedenceType(IntrusivePtr_t<BaseDataType_t> operandValue) { uint16_t namespaceIndex; Status_t status = OpcUa_Good; if (operandValue.is_set()) { switch (operandValue->TypeId(namespaceIndex)) { case OpcUaId_Boolean: case OpcUaId_Byte: case OpcUaId_Double: case OpcUaId_ExpandedNodeId: case OpcUaId_Float: case OpcUaId_Guid: case OpcUaId_Int16: case OpcUaId_Int32: case OpcUaId_Int64: case OpcUaId_NodeId: case OpcUaId_SByte: case OpcUaId_StatusCode: case OpcUaId_String: case OpcUaId_LocalizedText: case OpcUaId_QualifiedName: case OpcUaId_UInt16: case OpcUaId_UInt32: case OpcUaId_UInt64: break; default: status = OpcUa_BadFilterOperandInvalid; break; } } else { status = OpcUa_BadFilterOperandInvalid; } return status; } Status_t TypeConversion_t::UseTypePrecedenceConvertToOrFromBoolean(IntrusivePtr_t<BaseDataType_t>& aType, IntrusivePtr_t<BaseDataType_t>& bType, IntrusivePtr_t<BaseDataType_t>& dest, bool &convertedToFirstArgType, bool &firstArgConversionFail, bool &secondArgConversionFail) { uint16_t bNamespaceIndex; Status_t status = OpcUa_Good; IntrusivePtr_t<Boolean_t> tptr; tptr.reset(new RefCount_t<Boolean_t>()); if (!tptr.is_set()) { return OpcUa_BadOutOfMemory; } switch (bType->TypeId(bNamespaceIndex)) { case OpcUaId_Boolean: { dest = bType; convertedToFirstArgType = true; break; } case OpcUaId_String: { dest = tptr; status = TypeConversionRule(bType, dest); if (status.IsBad()) { secondArgConversionFail = true; return status; } convertedToFirstArgType = true; break; } case OpcUaId_SByte: { IntrusivePtr_t<SByte_t> ptr; ptr.reset(new RefCount_t<SByte_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_Byte: { IntrusivePtr_t<Byte_t> ptr; ptr.reset(new RefCount_t<Byte_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_Double: { IntrusivePtr_t<Double_t> ptr; ptr.reset(new RefCount_t<Double_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_Float: { IntrusivePtr_t<Float_t> ptr; ptr.reset(new RefCount_t<Float_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_Int64: { IntrusivePtr_t<Int64_t> ptr; ptr.reset(new RefCount_t<Int64_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_UInt64: { IntrusivePtr_t<UInt64_t> ptr; ptr.reset(new RefCount_t<UInt64_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_Int32: { IntrusivePtr_t<Int32_t> ptr; ptr.reset(new RefCount_t<Int32_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_UInt32: { IntrusivePtr_t<UInt32_t> ptr; ptr.reset(new RefCount_t<UInt32_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_Int16: { IntrusivePtr_t<Int16_t> ptr; ptr.reset(new RefCount_t<Int16_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_UInt16: { IntrusivePtr_t<UInt16_t> ptr; ptr.reset(new RefCount_t<UInt16_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_StatusCode: firstArgConversionFail = true; return OpcUa_BadFilterOperandInvalid; break; default: secondArgConversionFail = true; return OpcUa_BadFilterOperandInvalid; break; } return status; } Status_t TypeConversion_t::UseTypePrecedenceConvertToOrFromByte(IntrusivePtr_t<BaseDataType_t>& aType, IntrusivePtr_t<BaseDataType_t>& bType, IntrusivePtr_t<BaseDataType_t>& dest, bool &convertedToFirstArgType, bool &firstArgConversionFail, bool &secondArgConversionFail) { uint16_t bNamespaceIndex; Status_t status = OpcUa_Good; IntrusivePtr_t<Byte_t> tptr; tptr.reset(new RefCount_t<Byte_t>()); if (!tptr.is_set()) { return OpcUa_BadOutOfMemory; } switch (bType->TypeId(bNamespaceIndex)) { case OpcUaId_Byte: { dest = bType; convertedToFirstArgType = true; break; } case OpcUaId_String: case OpcUaId_Boolean: { dest = tptr; status = TypeConversionRule(bType, dest); if (status.IsBad()) { secondArgConversionFail = true; return status; } convertedToFirstArgType = true; break; } case OpcUaId_SByte: { IntrusivePtr_t<SByte_t> ptr; ptr.reset(new RefCount_t<SByte_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_Double: { IntrusivePtr_t<Double_t> ptr; ptr.reset(new RefCount_t<Double_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_Float: { IntrusivePtr_t<Float_t> ptr; ptr.reset(new RefCount_t<Float_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_Int64: { IntrusivePtr_t<Int64_t> ptr; ptr.reset(new RefCount_t<Int64_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_UInt64: { IntrusivePtr_t<UInt64_t> ptr; ptr.reset(new RefCount_t<UInt64_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_Int32: { IntrusivePtr_t<Int32_t> ptr; ptr.reset(new RefCount_t<Int32_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_UInt32: { IntrusivePtr_t<UInt32_t> ptr; ptr.reset(new RefCount_t<UInt32_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_Int16: { IntrusivePtr_t<Int16_t> ptr; ptr.reset(new RefCount_t<Int16_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_UInt16: { IntrusivePtr_t<UInt16_t> ptr; ptr.reset(new RefCount_t<UInt16_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_StatusCode: firstArgConversionFail = true; return OpcUa_BadFilterOperandInvalid; break; default: secondArgConversionFail = true; return OpcUa_BadFilterOperandInvalid; break; } return status; } Status_t TypeConversion_t::UseTypePrecedenceConvertToOrFromSByte(IntrusivePtr_t<BaseDataType_t>& aType, IntrusivePtr_t<BaseDataType_t>& bType, IntrusivePtr_t<BaseDataType_t>& dest, bool &convertedToFirstArgType, bool &firstArgConversionFail, bool &secondArgConversionFail) { uint16_t bNamespaceIndex; Status_t status = OpcUa_Good; IntrusivePtr_t<SByte_t> tptr; tptr.reset(new RefCount_t<SByte_t>()); if (!tptr.is_set()) { return OpcUa_BadOutOfMemory; } switch (bType->TypeId(bNamespaceIndex)) { case OpcUaId_SByte: { dest = bType; convertedToFirstArgType = true; break; } case OpcUaId_String: case OpcUaId_Boolean: case OpcUaId_Byte: { dest = tptr; status = TypeConversionRule(bType, dest); if (status.IsBad()) { secondArgConversionFail = true; return status; } convertedToFirstArgType = true; break; } case OpcUaId_Double: { IntrusivePtr_t<Double_t> ptr; ptr.reset(new RefCount_t<Double_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_Float: { IntrusivePtr_t<Float_t> ptr; ptr.reset(new RefCount_t<Float_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_Int64: { IntrusivePtr_t<Int64_t> ptr; ptr.reset(new RefCount_t<Int64_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_UInt64: { IntrusivePtr_t<UInt64_t> ptr; ptr.reset(new RefCount_t<UInt64_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_Int32: { IntrusivePtr_t<Int32_t> ptr; ptr.reset(new RefCount_t<Int32_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_UInt32: { IntrusivePtr_t<UInt32_t> ptr; ptr.reset(new RefCount_t<UInt32_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_Int16: { IntrusivePtr_t<Int16_t> ptr; ptr.reset(new RefCount_t<Int16_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_UInt16: { IntrusivePtr_t<UInt16_t> ptr; ptr.reset(new RefCount_t<UInt16_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_StatusCode: firstArgConversionFail = true; return OpcUa_BadFilterOperandInvalid; break; default: secondArgConversionFail = true; return OpcUa_BadFilterOperandInvalid; break; } return status; } Status_t TypeConversion_t::UseTypePrecedenceConvertToOrFromUInt16(IntrusivePtr_t<BaseDataType_t>& aType, IntrusivePtr_t<BaseDataType_t>& bType, IntrusivePtr_t<BaseDataType_t>& dest, bool &convertedToFirstArgType, bool &firstArgConversionFail, bool &secondArgConversionFail) { uint16_t bNamespaceIndex; Status_t status = OpcUa_Good; IntrusivePtr_t<UInt16_t> tptr; tptr.reset(new RefCount_t<UInt16_t>()); if (!tptr.is_set()) { return OpcUa_BadOutOfMemory; } switch (bType->TypeId(bNamespaceIndex)) { case OpcUaId_UInt16: { dest = bType; convertedToFirstArgType = true; break; } case OpcUaId_String: case OpcUaId_Boolean: case OpcUaId_Byte: case OpcUaId_SByte: { dest = tptr; status = TypeConversionRule(bType, dest); if (status.IsBad()) { secondArgConversionFail = true; return status; } convertedToFirstArgType = true; break; } case OpcUaId_Double: { IntrusivePtr_t<Double_t> ptr; ptr.reset(new RefCount_t<Double_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_Float: { IntrusivePtr_t<Float_t> ptr; ptr.reset(new RefCount_t<Float_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_Int64: { IntrusivePtr_t<Int64_t> ptr; ptr.reset(new RefCount_t<Int64_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_UInt64: { IntrusivePtr_t<UInt64_t> ptr; ptr.reset(new RefCount_t<UInt64_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_Int32: { IntrusivePtr_t<Int32_t> ptr; ptr.reset(new RefCount_t<Int32_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_UInt32: { IntrusivePtr_t<UInt32_t> ptr; ptr.reset(new RefCount_t<UInt32_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_Int16: { IntrusivePtr_t<Int16_t> ptr; ptr.reset(new RefCount_t<Int16_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_StatusCode: { IntrusivePtr_t<StatusCode_t> ptr; ptr.reset(new RefCount_t<StatusCode_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } default: secondArgConversionFail = true; return OpcUa_BadFilterOperandInvalid; break; } return status; } Status_t TypeConversion_t::UseTypePrecedenceConvertToOrFromInt16(IntrusivePtr_t<BaseDataType_t>& aType, IntrusivePtr_t<BaseDataType_t>& bType, IntrusivePtr_t<BaseDataType_t>& dest, bool &convertedToFirstArgType, bool &firstArgConversionFail, bool &secondArgConversionFail) { uint16_t bNamespaceIndex; Status_t status = OpcUa_Good; IntrusivePtr_t<Int16_t> tptr; tptr.reset(new RefCount_t<Int16_t>()); if (!tptr.is_set()) { return OpcUa_BadOutOfMemory; } switch (bType->TypeId(bNamespaceIndex)) { case OpcUaId_Int16: { dest = bType; convertedToFirstArgType = true; break; } case OpcUaId_String: case OpcUaId_Boolean: case OpcUaId_Byte: case OpcUaId_SByte: case OpcUaId_UInt16: { dest = tptr; status = TypeConversionRule(bType, dest); if (status.IsBad()) { secondArgConversionFail = true; return status; } convertedToFirstArgType = true; break; } case OpcUaId_Double: { IntrusivePtr_t<Double_t> ptr; ptr.reset(new RefCount_t<Double_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_Float: { IntrusivePtr_t<Float_t> ptr; ptr.reset(new RefCount_t<Float_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_Int64: { IntrusivePtr_t<Int64_t> ptr; ptr.reset(new RefCount_t<Int64_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_UInt64: { IntrusivePtr_t<UInt64_t> ptr; ptr.reset(new RefCount_t<UInt64_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_Int32: { IntrusivePtr_t<Int32_t> ptr; ptr.reset(new RefCount_t<Int32_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_UInt32: { IntrusivePtr_t<UInt32_t> ptr; ptr.reset(new RefCount_t<UInt32_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_StatusCode: firstArgConversionFail = true; return OpcUa_BadFilterOperandInvalid; break; default: secondArgConversionFail = true; return OpcUa_BadFilterOperandInvalid; break; } return status; } Status_t TypeConversion_t::UseTypePrecedenceConvertToOrFromUInt32(IntrusivePtr_t<BaseDataType_t>& aType, IntrusivePtr_t<BaseDataType_t>& bType, IntrusivePtr_t<BaseDataType_t>& dest, bool &convertedToFirstArgType, bool &firstArgConversionFail, bool &secondArgConversionFail) { uint16_t bNamespaceIndex; Status_t status = OpcUa_Good; IntrusivePtr_t<UInt32_t> tptr; tptr.reset(new RefCount_t<UInt32_t>()); if (!tptr.is_set()) { return OpcUa_BadOutOfMemory; } switch (bType->TypeId(bNamespaceIndex)) { case OpcUaId_UInt32: { dest = bType; convertedToFirstArgType = true; break; } case OpcUaId_StatusCode: case OpcUaId_String: case OpcUaId_Boolean: case OpcUaId_Byte: case OpcUaId_Int16: case OpcUaId_SByte: case OpcUaId_UInt16: { dest = tptr; status = TypeConversionRule(bType, dest); if (status.IsBad()) { secondArgConversionFail = true; return status; } convertedToFirstArgType = true; break; } case OpcUaId_Int32: { IntrusivePtr_t<Int32_t> ptr; ptr.reset(new RefCount_t<Int32_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_UInt64: { IntrusivePtr_t<UInt64_t> ptr; ptr.reset(new RefCount_t<UInt64_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_Int64: { IntrusivePtr_t<Int64_t> ptr; ptr.reset(new RefCount_t<Int64_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_Float: { IntrusivePtr_t<Float_t> ptr; ptr.reset(new RefCount_t<Float_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_Double: { IntrusivePtr_t<Double_t> ptr; ptr.reset(new RefCount_t<Double_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } default: secondArgConversionFail = true; return OpcUa_BadFilterOperandInvalid; break; } return status; } Status_t TypeConversion_t::UseTypePrecedenceConvertToOrFromInt32(IntrusivePtr_t<BaseDataType_t>& aType, IntrusivePtr_t<BaseDataType_t>& bType, IntrusivePtr_t<BaseDataType_t>& dest, bool &convertedToFirstArgType, bool &firstArgConversionFail, bool &secondArgConversionFail) { uint16_t bNamespaceIndex; Status_t status = OpcUa_Good; IntrusivePtr_t<Int32_t> tptr; tptr.reset(new RefCount_t<Int32_t>()); if (!tptr.is_set()) { return OpcUa_BadOutOfMemory; } switch (bType->TypeId(bNamespaceIndex)) { case OpcUaId_Int32: { dest = bType; convertedToFirstArgType = true; break; } case OpcUaId_StatusCode: case OpcUaId_String: case OpcUaId_Boolean: case OpcUaId_Byte: case OpcUaId_Int16: case OpcUaId_SByte: case OpcUaId_UInt16: case OpcUaId_UInt32: { dest = tptr; status = TypeConversionRule(bType, dest); if (status.IsBad()) { secondArgConversionFail = true; return status; } convertedToFirstArgType = true; break; } case OpcUaId_UInt64: { IntrusivePtr_t<UInt64_t> ptr; ptr.reset(new RefCount_t<UInt64_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_Int64: { IntrusivePtr_t<Int64_t> ptr; ptr.reset(new RefCount_t<Int64_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_Float: { IntrusivePtr_t<Float_t> ptr; ptr.reset(new RefCount_t<Float_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_Double: { IntrusivePtr_t<Double_t> ptr; ptr.reset(new RefCount_t<Double_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } default: secondArgConversionFail = true; return OpcUa_BadFilterOperandInvalid; break; } return status; } Status_t TypeConversion_t::UseTypePrecedenceConvertToOrFromUInt64(IntrusivePtr_t<BaseDataType_t>& aType, IntrusivePtr_t<BaseDataType_t>& bType, IntrusivePtr_t<BaseDataType_t>& dest, bool &convertedToFirstArgType, bool &firstArgConversionFail, bool &secondArgConversionFail) { uint16_t bNamespaceIndex; Status_t status = OpcUa_Good; IntrusivePtr_t<UInt64_t> tptr; tptr.reset(new RefCount_t<UInt64_t>()); if (!tptr.is_set()) { return OpcUa_BadOutOfMemory; } switch (bType->TypeId(bNamespaceIndex)) { case OpcUaId_UInt64: { dest = bType; convertedToFirstArgType = true; break; } case OpcUaId_StatusCode: case OpcUaId_String: case OpcUaId_Boolean: case OpcUaId_Byte: case OpcUaId_Int16: case OpcUaId_Int32: case OpcUaId_SByte: case OpcUaId_UInt16: case OpcUaId_UInt32: { dest = tptr; status = TypeConversionRule(bType, dest); if (status.IsBad()) { secondArgConversionFail = true; return status; } convertedToFirstArgType = true; break; } case OpcUaId_Int64: { IntrusivePtr_t<Int64_t> ptr; ptr.reset(new RefCount_t<Int64_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_Float: { IntrusivePtr_t<Float_t> ptr; ptr.reset(new RefCount_t<Float_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_Double: { IntrusivePtr_t<Double_t> ptr; ptr.reset(new RefCount_t<Double_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } default: secondArgConversionFail = true; return OpcUa_BadFilterOperandInvalid; break; } return status; } Status_t TypeConversion_t::UseTypePrecedenceConvertToOrFromInt64(IntrusivePtr_t<BaseDataType_t>& aType, IntrusivePtr_t<BaseDataType_t>& bType, IntrusivePtr_t<BaseDataType_t>& dest, bool &convertedToFirstArgType, bool &firstArgConversionFail, bool &secondArgConversionFail) { uint16_t bNamespaceIndex; Status_t status = OpcUa_Good; IntrusivePtr_t<Int64_t> tptr; tptr.reset(new RefCount_t<Int64_t>()); if (!tptr.is_set()) { return OpcUa_BadOutOfMemory; } switch (bType->TypeId(bNamespaceIndex)) { case OpcUaId_Int64: { dest = bType; convertedToFirstArgType = true; break; } case OpcUaId_StatusCode: case OpcUaId_String: case OpcUaId_Boolean: case OpcUaId_Byte: case OpcUaId_Int16: case OpcUaId_Int32: case OpcUaId_SByte: case OpcUaId_UInt16: case OpcUaId_UInt32: case OpcUaId_UInt64: { dest = tptr; status = TypeConversionRule(bType, dest); if (status.IsBad()) { secondArgConversionFail = true; return status; } convertedToFirstArgType = true; break; } case OpcUaId_Float: { IntrusivePtr_t<Float_t> ptr; ptr.reset(new RefCount_t<Float_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_Double: { IntrusivePtr_t<Double_t> ptr; ptr.reset(new RefCount_t<Double_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } default: secondArgConversionFail = true; return OpcUa_BadFilterOperandInvalid; break; } return status; } Status_t TypeConversion_t::UseTypePrecedenceConvertToOrFromFloat(IntrusivePtr_t<BaseDataType_t>& aType, IntrusivePtr_t<BaseDataType_t>& bType, IntrusivePtr_t<BaseDataType_t>& dest, bool &convertedToFirstArgType, bool &firstArgConversionFail, bool &secondArgConversionFail) { uint16_t bNamespaceIndex; Status_t status = OpcUa_Good; IntrusivePtr_t<Float_t> tptr; tptr.reset(new RefCount_t<Float_t>()); if (!tptr.is_set()) { return OpcUa_BadOutOfMemory; } switch (bType->TypeId(bNamespaceIndex)) { case OpcUaId_Float: { dest = bType; convertedToFirstArgType = true; break; } case OpcUaId_StatusCode: case OpcUaId_String: case OpcUaId_Boolean: case OpcUaId_Byte: case OpcUaId_Int16: case OpcUaId_Int32: case OpcUaId_Int64: case OpcUaId_SByte: case OpcUaId_UInt16: case OpcUaId_UInt32: case OpcUaId_UInt64: { dest = tptr; status = TypeConversionRule(bType, dest); if (status.IsBad()) { secondArgConversionFail = true; return status; } convertedToFirstArgType = true; break; } case OpcUaId_Double: { IntrusivePtr_t<Double_t> ptr; ptr.reset(new RefCount_t<Double_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } default: secondArgConversionFail = true; return OpcUa_BadFilterOperandInvalid; break; } return status; } Status_t TypeConversion_t::UseTypePrecedenceConvertToOrFromDouble(IntrusivePtr_t<BaseDataType_t>& bType, IntrusivePtr_t<BaseDataType_t>& dest, bool &convertedToFirstArgType, bool &secondArgConversionFail) { uint16_t bNamespaceIndex; Status_t status = OpcUa_Good; IntrusivePtr_t<Double_t> tptr; tptr.reset(new RefCount_t<Double_t>()); if (!tptr.is_set()) { return OpcUa_BadOutOfMemory; } switch (bType->TypeId(bNamespaceIndex)) { case OpcUaId_Double: { dest = bType; convertedToFirstArgType = true; break; } case OpcUaId_StatusCode: case OpcUaId_String: case OpcUaId_Boolean: case OpcUaId_Byte: case OpcUaId_Float: case OpcUaId_Int16: case OpcUaId_Int32: case OpcUaId_Int64: case OpcUaId_SByte: case OpcUaId_UInt16: case OpcUaId_UInt32: case OpcUaId_UInt64: { dest = tptr; status = TypeConversionRule(bType, dest); if (status.IsBad()) { secondArgConversionFail = true; return status; } convertedToFirstArgType = true; break; } default: secondArgConversionFail = true; return OpcUa_BadFilterOperandInvalid; break; } return status; } Status_t TypeConversion_t::UseTypePrecedenceConvertToOrFromStatusCode(IntrusivePtr_t<BaseDataType_t>& aType, IntrusivePtr_t<BaseDataType_t>& bType, IntrusivePtr_t<BaseDataType_t>& dest, bool &convertedToFirstArgType, bool &firstArgConversionFail, bool &secondArgConversionFail) { uint16_t bNamespaceIndex; Status_t status = OpcUa_Good; IntrusivePtr_t<StatusCode_t> tptr; tptr.reset(new RefCount_t<StatusCode_t>()); if (!tptr.is_set()) { return OpcUa_BadOutOfMemory; } switch (bType->TypeId(bNamespaceIndex)) { case OpcUaId_StatusCode: { dest = bType; convertedToFirstArgType = true; break; } case OpcUaId_UInt16: { dest = tptr; status = TypeConversionRule(bType, dest); if (status.IsBad()) { secondArgConversionFail = true; return status; } convertedToFirstArgType = true; break; } case OpcUaId_Int64: { IntrusivePtr_t<Int64_t> ptr; ptr.reset(new RefCount_t<Int64_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_UInt64: { IntrusivePtr_t<UInt64_t> ptr; ptr.reset(new RefCount_t<UInt64_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_Int32: { IntrusivePtr_t<Int32_t> ptr; ptr.reset(new RefCount_t<Int32_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_UInt32: { IntrusivePtr_t<UInt32_t> ptr; ptr.reset(new RefCount_t<UInt32_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_Guid: case OpcUaId_String: case OpcUaId_ExpandedNodeId: case OpcUaId_NodeId: case OpcUaId_LocalizedText: case OpcUaId_QualifiedName: secondArgConversionFail = true; return OpcUa_BadFilterOperandInvalid; break; default: firstArgConversionFail = true; return OpcUa_BadFilterOperandInvalid; break; } return status; } Status_t TypeConversion_t::UseTypePrecedenceConvertToOrFromGuid(IntrusivePtr_t<BaseDataType_t>& bType, IntrusivePtr_t<BaseDataType_t>& dest, bool &convertedToFirstArgType, bool &firstArgConversionFail, bool &secondArgConversionFail) { uint16_t bNamespaceIndex; Status_t status = OpcUa_Good; IntrusivePtr_t<Guid_t> tptr; tptr.reset(new RefCount_t<Guid_t>()); if (!tptr.is_set()) { return OpcUa_BadOutOfMemory; } switch (bType->TypeId(bNamespaceIndex)) { case OpcUaId_Guid: { dest = bType; convertedToFirstArgType = true; break; } case OpcUaId_String: { dest = tptr; status = TypeConversionRule(bType, dest); if (status.IsBad()) { secondArgConversionFail = true; return status; } convertedToFirstArgType = true; break; } case OpcUaId_ExpandedNodeId: case OpcUaId_NodeId: case OpcUaId_LocalizedText: case OpcUaId_QualifiedName: secondArgConversionFail = true; return OpcUa_BadFilterOperandInvalid; break; default: firstArgConversionFail = true; return OpcUa_BadFilterOperandInvalid; break; } return status; } Status_t TypeConversion_t::UseTypePrecedenceConvertToOrFromString(IntrusivePtr_t<BaseDataType_t>& aType, IntrusivePtr_t<BaseDataType_t>& bType, IntrusivePtr_t<BaseDataType_t>& dest, bool &convertedToFirstArgType, bool &firstArgConversionFail, bool &secondArgConversionFail) { uint16_t bNamespaceIndex; Status_t status = OpcUa_Good; IntrusivePtr_t<String_t> tptr; tptr.reset(new RefCount_t<String_t>()); if (!tptr.is_set()) { return OpcUa_BadOutOfMemory; } switch (bType->TypeId(bNamespaceIndex)) { case OpcUaId_String: { dest = bType; convertedToFirstArgType = true; break; } case OpcUaId_ExpandedNodeId: case OpcUaId_NodeId: case OpcUaId_LocalizedText: case OpcUaId_QualifiedName: { dest = tptr; status = TypeConversionRule(bType, dest); if (status.IsBad()) { secondArgConversionFail = true; return status; } convertedToFirstArgType = true; break; } case OpcUaId_Guid: { IntrusivePtr_t<Guid_t> ptr; ptr.reset(new RefCount_t<Guid_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_Boolean: { IntrusivePtr_t<Boolean_t> ptr; ptr.reset(new RefCount_t<Boolean_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_SByte: { IntrusivePtr_t<SByte_t> ptr; ptr.reset(new RefCount_t<SByte_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_Byte: { IntrusivePtr_t<Byte_t> ptr; ptr.reset(new RefCount_t<Byte_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_Double: { IntrusivePtr_t<Double_t> ptr; ptr.reset(new RefCount_t<Double_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_Float: { IntrusivePtr_t<Float_t> ptr; ptr.reset(new RefCount_t<Float_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_Int64: { IntrusivePtr_t<Int64_t> ptr; ptr.reset(new RefCount_t<Int64_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_UInt64: { IntrusivePtr_t<UInt64_t> ptr; ptr.reset(new RefCount_t<UInt64_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_Int32: { IntrusivePtr_t<Int32_t> ptr; ptr.reset(new RefCount_t<Int32_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_UInt32: { IntrusivePtr_t<UInt32_t> ptr; ptr.reset(new RefCount_t<UInt32_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_Int16: { IntrusivePtr_t<Int16_t> ptr; ptr.reset(new RefCount_t<Int16_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_UInt16: { IntrusivePtr_t<UInt16_t> ptr; ptr.reset(new RefCount_t<UInt16_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } default: firstArgConversionFail = true; return OpcUa_BadFilterOperandInvalid; break; } return status; } Status_t TypeConversion_t::UseTypePrecedenceConvertToOrFromExpandedNodeid(IntrusivePtr_t<BaseDataType_t>& aType, IntrusivePtr_t<BaseDataType_t>& bType, IntrusivePtr_t<BaseDataType_t>& dest, bool &convertedToFirstArgType, bool &firstArgConversionFail, bool &secondArgConversionFail) { uint16_t bNamespaceIndex; Status_t status = OpcUa_Good; IntrusivePtr_t<ExpandedNodeId_t> tptr; tptr.reset(new RefCount_t<ExpandedNodeId_t>()); if (!tptr.is_set()) { return OpcUa_BadOutOfMemory; } tptr->Nodeid() = new RefCount_t<NodeIdNumeric_t>(); if (!tptr->Nodeid().is_set()) { return OpcUa_BadOutOfMemory; } switch (bType->TypeId(bNamespaceIndex)) { case OpcUaId_ExpandedNodeId: { dest = bType; convertedToFirstArgType = true; break; } case OpcUaId_NodeId: { dest = tptr; status = TypeConversionRule(bType, dest); if (status.IsBad()) { secondArgConversionFail = true; return status; } convertedToFirstArgType = true; break; } case OpcUaId_String: { IntrusivePtr_t<String_t> ptr; ptr.reset(new RefCount_t<String_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_LocalizedText: case OpcUaId_QualifiedName: secondArgConversionFail = true; return OpcUa_BadFilterOperandInvalid; break; default: firstArgConversionFail = true; return OpcUa_BadFilterOperandInvalid; break; } return status; } Status_t TypeConversion_t::UseTypePrecedenceConvertToOrFromNodeId(IntrusivePtr_t<BaseDataType_t>& aType, IntrusivePtr_t<BaseDataType_t>& bType, IntrusivePtr_t<BaseDataType_t>& dest, bool &convertedToFirstArgType, bool &firstArgConversionFail, bool &secondArgConversionFail) { uint16_t bNamespaceIndex; Status_t status = OpcUa_Good; IntrusivePtr_t<ExpandedNodeId_t> tptr; tptr.reset(new RefCount_t<ExpandedNodeId_t>()); if (!tptr.is_set()) { return OpcUa_BadOutOfMemory; } tptr->Nodeid() = new RefCount_t<NodeIdNumeric_t>(); if (!tptr->Nodeid().is_set()) { return OpcUa_BadOutOfMemory; } switch (bType->TypeId(bNamespaceIndex)) { case OpcUaId_NodeId: { dest = bType; convertedToFirstArgType = true; break; } case OpcUaId_ExpandedNodeId: { dest = tptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_String: { IntrusivePtr_t<String_t> ptr; ptr.reset(new RefCount_t<String_t>()); if (!ptr.is_set()) { return OpcUa_BadOutOfMemory; } dest = ptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_LocalizedText: case OpcUaId_QualifiedName: secondArgConversionFail = true; return OpcUa_BadFilterOperandInvalid; break; default: firstArgConversionFail = true; return OpcUa_BadFilterOperandInvalid; break; } return status; } Status_t TypeConversion_t::UseTypePrecedenceConvertToOrFromLocalizedText(IntrusivePtr_t<BaseDataType_t>& aType, IntrusivePtr_t<BaseDataType_t>& bType, IntrusivePtr_t<BaseDataType_t>& dest, bool &convertedToFirstArgType, bool &firstArgConversionFail, bool &secondArgConversionFail) { uint16_t bNamespaceIndex; Status_t status = OpcUa_Good; IntrusivePtr_t<String_t> tptr; tptr.reset(new RefCount_t<String_t>()); if (!tptr.is_set()) { return OpcUa_BadOutOfMemory; } switch (bType->TypeId(bNamespaceIndex)) { case OpcUaId_LocalizedText: { dest = bType; convertedToFirstArgType = true; break; } case OpcUaId_String: { dest = tptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } case OpcUaId_QualifiedName: secondArgConversionFail = true; return OpcUa_BadFilterOperandInvalid; break; default: firstArgConversionFail = true; return OpcUa_BadFilterOperandInvalid; break; } return status; } Status_t TypeConversion_t::UseTypePrecedenceConvertToOrFromQualifiedName(IntrusivePtr_t<BaseDataType_t>& aType, IntrusivePtr_t<BaseDataType_t>& bType, IntrusivePtr_t<BaseDataType_t>& dest, bool &convertedToFirstArgType, bool &firstArgConversionFail) { uint16_t bNamespaceIndex; Status_t status = OpcUa_Good; IntrusivePtr_t<String_t> tptr; tptr.reset(new RefCount_t<String_t>()); if (!tptr.is_set()) { return OpcUa_BadOutOfMemory; } switch (bType->TypeId(bNamespaceIndex)) { case OpcUaId_QualifiedName: { dest = bType; convertedToFirstArgType = true; break; } case OpcUaId_String: { dest = tptr; status = TypeConversionRule(aType, dest); if (status.IsBad()) { firstArgConversionFail = true; return status; } break; } default: firstArgConversionFail = true; return OpcUa_BadFilterOperandInvalid; break; } return status; } // The data type of 'aType' must be different from the data type of 'bType' Status_t TypeConversion_t::TypePrecedenceRule(IntrusivePtr_t<BaseDataType_t>& aType, IntrusivePtr_t<BaseDataType_t>& bType, IntrusivePtr_t<BaseDataType_t>& dest, bool &convertedToFirstArgType, bool &firstArgConversionFail, bool &secondArgConversionFail) { uint16_t aNamespaceIndex; Status_t status = OpcUa_Good; if (!aType.is_set() || !bType.is_set()) { return OpcUa_BadFilterOperandInvalid; } status = IsValidPrecedenceType(aType); if (status.IsBad()) { return status; } status = IsValidPrecedenceType(bType); if (status.IsBad()) { return status; } convertedToFirstArgType = false; firstArgConversionFail = false; secondArgConversionFail = false; switch (aType->TypeId(aNamespaceIndex)) { case OpcUaId_Boolean: status = UseTypePrecedenceConvertToOrFromBoolean(aType, bType, dest, convertedToFirstArgType, firstArgConversionFail, secondArgConversionFail); if (status.IsBad()) { return status; } break; case OpcUaId_Byte: status = UseTypePrecedenceConvertToOrFromByte(aType, bType, dest, convertedToFirstArgType, firstArgConversionFail, secondArgConversionFail); if (status.IsBad()) { return status; } break; case OpcUaId_SByte: status = UseTypePrecedenceConvertToOrFromSByte(aType, bType, dest, convertedToFirstArgType, firstArgConversionFail, secondArgConversionFail); if (status.IsBad()) { return status; } break; case OpcUaId_UInt16: status = UseTypePrecedenceConvertToOrFromUInt16(aType, bType, dest, convertedToFirstArgType, firstArgConversionFail, secondArgConversionFail); if (status.IsBad()) { return status; } break; case OpcUaId_Int16: status = UseTypePrecedenceConvertToOrFromInt16(aType, bType, dest, convertedToFirstArgType, firstArgConversionFail, secondArgConversionFail); if (status.IsBad()) { return status; } break; case OpcUaId_UInt32: status = UseTypePrecedenceConvertToOrFromUInt32(aType, bType, dest, convertedToFirstArgType, firstArgConversionFail, secondArgConversionFail); if (status.IsBad()) { return status; } break; case OpcUaId_Int32: status = UseTypePrecedenceConvertToOrFromInt32(aType, bType, dest, convertedToFirstArgType, firstArgConversionFail, secondArgConversionFail); if (status.IsBad()) { return status; } break; case OpcUaId_UInt64: status = UseTypePrecedenceConvertToOrFromUInt64(aType, bType, dest, convertedToFirstArgType, firstArgConversionFail, secondArgConversionFail); if (status.IsBad()) { return status; } break; case OpcUaId_Int64: status = UseTypePrecedenceConvertToOrFromInt64(aType, bType, dest, convertedToFirstArgType, firstArgConversionFail, secondArgConversionFail); if (status.IsBad()) { return status; } break; case OpcUaId_Float: status = UseTypePrecedenceConvertToOrFromFloat(aType, bType, dest, convertedToFirstArgType, firstArgConversionFail, secondArgConversionFail); if (status.IsBad()) { return status; } break; case OpcUaId_Double: status = UseTypePrecedenceConvertToOrFromDouble(bType, dest, convertedToFirstArgType, secondArgConversionFail); if (status.IsBad()) { return status; } break; case OpcUaId_StatusCode: status = UseTypePrecedenceConvertToOrFromStatusCode(aType, bType, dest, convertedToFirstArgType, firstArgConversionFail, secondArgConversionFail); if (status.IsBad()) { return status; } break; case OpcUaId_Guid: status = UseTypePrecedenceConvertToOrFromGuid(bType, dest, convertedToFirstArgType, firstArgConversionFail, secondArgConversionFail); if (status.IsBad()) { return status; } break; case OpcUaId_String: status = UseTypePrecedenceConvertToOrFromString(aType, bType, dest, convertedToFirstArgType, firstArgConversionFail, secondArgConversionFail); if (status.IsBad()) { return status; } break; case OpcUaId_ExpandedNodeId: status = UseTypePrecedenceConvertToOrFromExpandedNodeid(aType, bType, dest, convertedToFirstArgType, firstArgConversionFail, secondArgConversionFail); if (status.IsBad()) { return status; } break; case OpcUaId_NodeId: status = UseTypePrecedenceConvertToOrFromNodeId(aType, bType, dest, convertedToFirstArgType, firstArgConversionFail, secondArgConversionFail); if (status.IsBad()) { return status; } break; case OpcUaId_LocalizedText: status = UseTypePrecedenceConvertToOrFromLocalizedText(aType, bType, dest, convertedToFirstArgType, firstArgConversionFail, secondArgConversionFail); if (status.IsBad()) { return status; } break; case OpcUaId_QualifiedName: status = UseTypePrecedenceConvertToOrFromQualifiedName(aType, bType, dest, convertedToFirstArgType, firstArgConversionFail); if (status.IsBad()) { return status; } break; default: firstArgConversionFail = true; return OpcUa_BadFilterOperandInvalid; break; } return OpcUa_Good; } //Bitwise Operators Related Conversion Methods bool TypeConversion_t::IsIntegerType(uint32_t typeID) { bool result = false; switch (typeID) { //As per Part 3 - Section 8.24, Integer ==> Int16, Int32, Int64 case OpcUaId_Int16: case OpcUaId_Int32: case OpcUaId_Int64: result = true; break; default: break; } return result; } uint32_t TypeConversion_t::GetIntegerSizePriority(uint32_t typeID) { uint32_t result = 0; switch (typeID) { case OpcUaId_Int16: result = 4; break; case OpcUaId_Int32: result = 6; break; case OpcUaId_Int64: result = 8; break; default: result = 0; break; } return result; } bool TypeConversion_t::CanConvertToIntegerType(uint32_t typeID) { bool result = true; //Only Boolean, Float, Double, String, StatusCode can be converted to integer type switch (typeID) { case OpcUaId_Boolean: case OpcUaId_Float: case OpcUaId_Double: case OpcUaId_UInt64: case OpcUaId_UInt32: case OpcUaId_UInt16: case OpcUaId_SByte: case OpcUaId_Byte: case OpcUaId_String: case OpcUaId_StatusCode: result = true; break; default: result = false; break; } return result; } uint32_t TypeConversion_t::GetTargetTypeForNonIntegers(uint32_t typeID) { uint32_t result = 0; //Only Boolean, Float, Double, String, StatusCode can be converted to integer type switch (typeID) { case OpcUaId_Boolean: case OpcUaId_SByte: case OpcUaId_Byte: result = OpcUaId_Int16;//Converting Byte, SByte, Boolean to Int16 break; case OpcUaId_Float: case OpcUaId_Double: case OpcUaId_UInt64: result = OpcUaId_Int64; break; case OpcUaId_String: result = OpcUaId_Int64;//Converting String to Int64 which is the largest integer break; case OpcUaId_StatusCode: case OpcUaId_UInt32: result = OpcUaId_Int32; break; case OpcUaId_UInt16: result = OpcUaId_Int16; break; default: result = 0; break; } return result; } Status_t TypeConversion_t::ConvertToIntegerType(IntrusivePtr_t<BaseDataType_t>& source, IntrusivePtr_t<BaseDataType_t>& target, uint32_t targetType) { Status_t status = OpcUa_Good; switch (targetType) { case OpcUaId_Int16: target = new SafeRefCount_t<Int16_t>(); break; case OpcUaId_Int32: target = new SafeRefCount_t<Int32_t>(); break; case OpcUaId_Int64: target = new SafeRefCount_t<Int64_t>(); break; default: break; } if (!target.is_set()) { status = OpcUa_BadOutOfMemory; } else { status = TypeConversionRule(source, target); } return status; } //Check and convert both inputs values to integer types or return error code. Status_t TypeConversion_t::CheckAndConvertInputValuesToIntegerType(IntrusivePtr_t<BaseDataType_t>& value1, IntrusivePtr_t<BaseDataType_t>& value2, bool& isNULL) { IntrusivePtr_t<BaseDataType_t> dest, destTemp; IntrusivePtr_t<BaseDataType_t> dest1, dest2; uint16_t namespaceIndex1 = 0; uint16_t namespaceIndex2 = 0; uint32_t typeId1 = 0, typeId2 = 0; Status_t status = OpcUa_Good; typeId1 = value1->TypeId(namespaceIndex1); typeId2 = value2->TypeId(namespaceIndex2); if (IsIntegerType(typeId1) && IsIntegerType(typeId2))//If both are integer type { if (typeId1 == typeId2)//Both are of same type. { //Return success. Both are of same integer types status = OpcUa_Good; } else { //Both are integers. Now, Convert both operands to same type as they are different if (GetIntegerSizePriority(typeId1) > GetIntegerSizePriority(typeId2)) { status = ConvertToIntegerType(value2, dest, typeId1); if (status.IsGood()) { status = dest->CopyTo(value2); } } else { status = ConvertToIntegerType(value1, dest, typeId2); if (status.IsGood()) { status = dest->CopyTo(value1); } } } } else if (IsIntegerType(typeId1))//First operand is integer { if (CanConvertToIntegerType(typeId2))//Check if second operand can be converted to integer? { status = ConvertToIntegerType(value2, dest, typeId1);//Convert second operand to first operand type if (status.IsGood()) { status = dest->CopyTo(value2); } } else { isNULL = true;//Conversion failed. Hence we need to return NULL in the out parameter status = OpcUa_BadFilterOperandInvalid; } } else if (IsIntegerType(typeId2))//Second operand is integer { if (CanConvertToIntegerType(typeId1))//Check if first operand can be converted to integer? { status = ConvertToIntegerType(value1, dest, typeId2);//Convert first operand to second operand type if (status.IsGood()) { status = dest->CopyTo(value1); } } else { isNULL = true;//Conversion failed. Hence we need to return NULL in the out parameter status = OpcUa_BadFilterOperandInvalid; } } else//Both operands are non-integers { if (CanConvertToIntegerType(typeId1) && CanConvertToIntegerType(typeId2))//Check if both operands can be converted to integer? { uint32_t targetType1 = GetTargetTypeForNonIntegers(typeId1); uint32_t targetType2 = GetTargetTypeForNonIntegers(typeId2); status = ConvertToIntegerType(value1, dest1, targetType1);//Convert first operand to the target type if (status.IsGood()) { status = ConvertToIntegerType(value2, dest2, targetType2);//Convert second operand to the target type } if (status.IsBad()) { isNULL = true;//Conversion failed. Hence we need to return NULL in the out parameter status = OpcUa_BadFilterOperandInvalid; } else { //Here, both the operands are converted to integer types now. //Now, Convert both operands to same type if they are different if (dest1->TypeId(namespaceIndex1) != dest2->TypeId(namespaceIndex2)) { //Compare the size of both operands and convert it to the type of larger integer if (GetIntegerSizePriority(dest1->TypeId(namespaceIndex1)) > GetIntegerSizePriority(dest2->TypeId(namespaceIndex2))) { status = ConvertToIntegerType(dest2, destTemp, dest1->TypeId(namespaceIndex1)); if (status.IsGood()) { status = destTemp->CopyTo(dest2); } } else { status = ConvertToIntegerType(dest1, destTemp, dest2->TypeId(namespaceIndex2)); if (status.IsGood()) { status = destTemp->CopyTo(dest1); } } if (status.IsGood()) { //Overwrite value1 and value2 with dest1 and dest2 so that final operation can be done on value1 and value2 in one place itself status = dest1->CopyTo(value1); if (status.IsGood()) { status = dest2->CopyTo(value2); } } } else { status = dest1->CopyTo(value1); if (status.IsGood()) { status = dest2->CopyTo(value2); } } } } else { isNULL = true;//Conversion failed. Hence we need to return NULL in the out parameter status = OpcUa_BadFilterOperandInvalid; } } return status; } } // namespace uasdk #endif // UASDK_INCLUDE_EVENTS
19.659234
193
0.653465
beeond
eac113310c8ceacc07411f140e4693bdfa4be60d
1,500
cpp
C++
src/versions.cpp
rvianello/chemicalite
0feb0d122e2f38730e2033e76681699c12eb1b23
[ "BSD-3-Clause" ]
29
2015-03-07T14:40:35.000Z
2022-02-05T21:17:42.000Z
src/versions.cpp
rvianello/chemicalite
0feb0d122e2f38730e2033e76681699c12eb1b23
[ "BSD-3-Clause" ]
3
2015-11-18T05:04:48.000Z
2020-12-16T22:37:25.000Z
src/versions.cpp
rvianello/chemicalite
0feb0d122e2f38730e2033e76681699c12eb1b23
[ "BSD-3-Clause" ]
3
2020-05-13T19:02:07.000Z
2021-08-02T10:45:32.000Z
#include <sqlite3ext.h> extern const sqlite3_api_routines *sqlite3_api; #include <RDGeneral/versions.h> #include "versions.hpp" #include "utils.hpp" /* ** Return the version info for this extension */ static void chemicalite_version(sqlite3_context* ctx, int /*argc*/, sqlite3_value** /*argv*/) { sqlite3_result_text(ctx, XSTRINGIFY(CHEMICALITE_VERSION), -1, SQLITE_STATIC); } static void rdkit_version(sqlite3_context* ctx, int /*argc*/, sqlite3_value** /*argv*/) { sqlite3_result_text(ctx, RDKit::rdkitVersion, -1, SQLITE_STATIC); } static void rdkit_build(sqlite3_context* ctx, int /*argc*/, sqlite3_value** /*argv*/) { sqlite3_result_text(ctx, RDKit::rdkitBuild, -1, SQLITE_STATIC); } static void boost_version(sqlite3_context* ctx, int /*argc*/, sqlite3_value** /*argv*/) { sqlite3_result_text(ctx, RDKit::boostVersion, -1, SQLITE_STATIC); } int chemicalite_init_versions(sqlite3 *db) { int rc = SQLITE_OK; if (rc == SQLITE_OK) rc = sqlite3_create_function(db, "chemicalite_version", 0, SQLITE_UTF8 | SQLITE_DETERMINISTIC, 0, chemicalite_version, 0, 0); if (rc == SQLITE_OK) rc = sqlite3_create_function(db, "rdkit_version", 0, SQLITE_UTF8 | SQLITE_DETERMINISTIC, 0, rdkit_version, 0, 0); if (rc == SQLITE_OK) rc = sqlite3_create_function(db, "rdkit_build", 0, SQLITE_UTF8 | SQLITE_DETERMINISTIC, 0, rdkit_build, 0, 0); if (rc == SQLITE_OK) rc = sqlite3_create_function(db, "boost_version", 0, SQLITE_UTF8 | SQLITE_DETERMINISTIC, 0, boost_version, 0, 0); return rc; }
36.585366
148
0.740667
rvianello
eac77fc16f68df4fef903990a8e28d255e7c94ab
15,854
cc
C++
python/ora/ext/functions.cc
alexhsamuel/ora
89358d9193d86fbc7752270f1e35ee6ddcdcd206
[ "BSD-3-Clause" ]
10
2018-03-03T02:02:19.000Z
2020-04-02T22:47:55.000Z
python/ora/ext/functions.cc
alexhsamuel/ora
89358d9193d86fbc7752270f1e35ee6ddcdcd206
[ "BSD-3-Clause" ]
13
2018-01-28T15:20:55.000Z
2022-01-27T23:32:41.000Z
python/ora/ext/functions.cc
alexhsamuel/ora
89358d9193d86fbc7752270f1e35ee6ddcdcd206
[ "BSD-3-Clause" ]
null
null
null
#include <cassert> #include <cstring> #include <time.h> #include "ora.hh" #include "py.hh" #include "py_date.hh" #include "py_time.hh" #include "util.hh" using namespace std::string_literals; //------------------------------------------------------------------------------ namespace ora { namespace py { //------------------------------------------------------------------------------ // Docstrings //------------------------------------------------------------------------------ namespace docstring { using doct_t = char const* const; #include "functions.docstrings.hh.inc" #include "functions.docstrings.cc.inc" } // namespace docstring //------------------------------------------------------------------------------ namespace { Exception parse_error( size_t const string_pos) { static auto exc_type = import("ora", "ParseError"); return Exception( exc_type, "parse error at pos "s + to_string<int>(string_pos)); } Exception parse_error( size_t const pattern_pos, size_t const string_pos) { static auto exc_type = import("ora", "ParseError"); return Exception( exc_type, "parse error at pattern pos "s + to_string<int>(pattern_pos) + ", string pos " + to_string<int>(string_pos)); } //------------------------------------------------------------------------------ ref<Object> days_in_month( Module* /* module */, Tuple* const args, Dict* const kw_args) { static char const* arg_names[] = {"year", "month", nullptr}; ora::Year year; ora::Month month; static_assert( sizeof(ora::Year) == sizeof(unsigned short), "wrong type for year"); static_assert( sizeof(ora::Month) == sizeof(unsigned char), "wrong type for month"); Arg::ParseTupleAndKeywords(args, kw_args, "Hb", arg_names, &year, &month); if (ora::year_is_valid(year) && ora::month_is_valid(month)) return Long::FromLong(ora::days_in_month(year, month)); else throw Exception(PyExc_ValueError, "invalid year"); } ref<Object> days_in_year( Module* /* module */, Tuple* const args, Dict* const kw_args) { static char const* arg_names[] = {"year", nullptr}; ora::Year year; static_assert( sizeof(ora::Year) == sizeof(unsigned short), "wrong type for year"); Arg::ParseTupleAndKeywords(args, kw_args, "H", arg_names, &year); if (ora::year_is_valid(year)) return Long::FromLong(ora::days_in_year(year)); else throw ValueError("invalid year"); } ref<Object> format_daytime_iso( Module* /* module */, Tuple* const args, Dict* const kw_args) { static char const* const arg_names[] = {"daytime", "precision", nullptr}; Object* daytime_arg; int precision = -1; Arg::ParseTupleAndKeywords( args, kw_args, "O|i", arg_names, &daytime_arg, &precision); auto api = PyDaytimeAPI::get(daytime_arg); if (api == nullptr) throw TypeError("not a Daytime"); if (api->is_invalid(daytime_arg)) return Unicode::from("INVALID"); else if (api->is_missing(daytime_arg)) return Unicode::from("MISSING"); StringBuilder sb; daytime::format_iso_daytime( sb, daytick_to_hms(api->get_daytick(daytime_arg)), precision); return Unicode::FromStringAndSize(sb, sb.length()); } ref<Object> format_time( Module* /* module */, Tuple* const args, Dict* const kw_args) { static char const* const arg_names[] = {"pattern", "time", "time_zone", nullptr}; Object* time_arg; char* pattern; Object* time_zone = nullptr; Arg::ParseTupleAndKeywords( args, kw_args, "sO|O", arg_names, &pattern, &time_arg, &time_zone); auto api = PyTimeAPI::get(time_arg); if (api == nullptr) throw TypeError("not a Time"); auto const tz = time_zone == nullptr ? ora::UTC : convert_to_time_zone(time_zone); ora::time::TimeFormat const fmt(pattern); return Unicode::from( api->is_invalid(time_arg) ? fmt.get_invalid() : api->is_missing(time_arg) ? fmt.get_missing() : fmt(api->to_local_datenum_daytick(time_arg, *tz))); } ref<Object> format_time_iso( Module* /* module */, Tuple* const args, Dict* const kw_args) { static char const* arg_names[] = {"time", "time_zone", "precision", nullptr}; Object* time_arg; Object* tz_arg = nullptr; int precision = -1; Arg::ParseTupleAndKeywords( args, kw_args, "O|Oi", arg_names, &time_arg, &tz_arg, &precision); auto api = PyTimeAPI::get(time_arg); if (api == nullptr) throw TypeError("not a Time"); if (api->is_invalid(time_arg)) return Unicode::from("INVALID"); else if (api->is_missing(time_arg)) return Unicode::from("MISSING"); auto const tz = tz_arg == nullptr ? UTC : convert_to_time_zone(tz_arg); auto ldd = api->to_local_datenum_daytick(time_arg, *tz); StringBuilder sb; time::format_iso_time( sb, datenum_to_ymd(ldd.datenum), daytick_to_hms(ldd.daytick), ldd.time_zone, precision); return Unicode::FromStringAndSize(sb, sb.length()); } ref<Object> from_local( Module* /* module */, Tuple* const args, Dict* const kw_args) { static char const* arg_names[] = {"local_time", "time_zone", "first", "Time", nullptr}; Object* date_arg; Object* daytime_arg; Object* tz_arg; int first = true; Object* time_type = (Object*) &PyTimeDefault::type_; Arg::ParseTupleAndKeywords( args, kw_args, "(OO)O|pO", arg_names, &date_arg, &daytime_arg, &tz_arg, &first, &time_type); // Make sure the time type is a PyTime instance, and get its virtual API. if (!Type::Check(time_type)) throw TypeError("not a type: "s + *time_type->Repr()); auto const api = PyTimeAPI::get((PyTypeObject*) time_type); if (api == nullptr) throw TypeError("not a time type: "s + *time_type->Repr()); auto const datenum = to_datenum(date_arg); auto const daytick = to_daytick(daytime_arg); auto const tz = convert_to_time_zone(tz_arg); return api->from_local_datenum_daytick(datenum, daytick, *tz, first); } ref<Object> get_display_time_zone( Module* /* module */, Tuple* const args, Dict* const kw_args) { static char const* arg_names[] = {nullptr}; Arg::ParseTupleAndKeywords(args, kw_args, "", arg_names); return PyTimeZone::create(ora::get_display_time_zone()); } ref<Object> get_system_time_zone( Module* /* module */, Tuple* const args, Dict* const kw_args) { static char const* arg_names[] = {nullptr}; Arg::ParseTupleAndKeywords(args, kw_args, "", arg_names); return PyTimeZone::create(ora::get_system_time_zone()); } ref<Object> get_zoneinfo_dir( Module* /* module */, Tuple* const args, Dict* const kw_args) { static char const* arg_names[] = {nullptr}; Arg::ParseTupleAndKeywords(args, kw_args, "", arg_names); return Unicode::from(ora::get_zoneinfo_dir()); } ref<Object> is_leap_year( Module* /* module */, Tuple* const args, Dict* const kw_args) { static char const* arg_names[] = {"year", nullptr}; ora::Year year; static_assert( sizeof(ora::Year) == sizeof(unsigned short), "wrong type for year"); Arg::ParseTupleAndKeywords(args, kw_args, "H", arg_names, &year); if (ora::year_is_valid(year)) return Bool::from(ora::is_leap_year(year)); else throw ValueError("invalid year"); } ref<Object> now( Module* /* module */, Tuple* const args, Dict* const kw_args) { static char const* arg_names[] = {"Time", nullptr}; PyTypeObject* time_type = &PyTimeDefault::type_; // A bit hacky, but we don't check that time_type is a type object because // PyTimeAPI won't accept anything else. Arg::ParseTupleAndKeywords(args, kw_args, "|O", arg_names, &time_type); auto const api = PyTimeAPI::get(time_type); if (api == nullptr) throw TypeError("not a time type"); else return api->now(); } ref<Object> parse_date( Module* /* module */, Tuple* const args, Dict* const kw_args) { static char const* arg_names[] = {"pattern", "string", "Date", nullptr}; char const* pattern; char const* string; PyTypeObject* date_type = &PyDateDefault::type_; Arg::ParseTupleAndKeywords( args, kw_args, "ss|$O", arg_names, &pattern, &string, &date_type); auto const api = PyDateAPI::get(date_type); if (api == nullptr) throw TypeError("not a date type"); FullDate parts; char const* p = pattern; char const* s = string; if (ora::date::parse_date_parts(p, s, parts)) return api->from_parts(parts); else throw parse_error(p - pattern, s - string); } ref<Object> parse_daytime( Module* /* module */, Tuple* const args, Dict* const kw_args) { static char const* arg_names[] = {"pattern", "string", "Daytime", nullptr}; char const* pattern; char const* string; PyTypeObject* daytime_type = &PyDaytimeDefault::type_; Arg::ParseTupleAndKeywords( args, kw_args, "ss|$O", arg_names, &pattern, &string, &daytime_type); auto const api = PyDaytimeAPI::get(daytime_type); if (api == nullptr) throw TypeError("not a daytime type"); HmsDaytime parts; char const* p = pattern; char const* s = string; if (ora::daytime::parse_daytime_parts(p, s, parts)) return api->from_hms(parts); else throw parse_error(p - pattern, s - string); } ref<Object> parse_time( Module* /* module */, Tuple* const args, Dict* const kw_args) { static char const* arg_names[] = {"pattern", "string", "time_zone", "first", "Time", nullptr}; char const* pattern; char const* string; Object* tz_arg = nullptr; int first = true; PyTypeObject* time_type = &PyTimeDefault::type_; Arg::ParseTupleAndKeywords( args, kw_args, "ss|O$pO", arg_names, &pattern, &string, &tz_arg, &first, &time_type); auto const api = PyTimeAPI::get(time_type); if (api == nullptr) throw TypeError("not a time type"); auto const tz = tz_arg == nullptr ? nullptr : convert_to_time_zone(tz_arg); FullDate date; HmsDaytime hms; ora::time::TimeZoneInfo tz_info; char const* p = pattern; char const* s = string; if (ora::time::parse_time_parts(p, s, date, hms, tz_info)) { // FIXME: Factor this logic into a function. auto const datenum = parts_to_datenum(date); auto const daytick = hms_to_daytick(hms.hour, hms.minute, hms.second); if (!tz_info.name.empty()) { TimeZone_ptr tz; try { tz = get_time_zone(tz_info.name); } catch (ora::lib::ValueError const&) { throw py::ValueError(std::string("not a time zone: ") + tz_info.name); } return api->from_local_datenum_daytick(datenum, daytick, *tz, first); } else if (time_zone_offset_is_valid(tz_info.offset)) return api->from_local_datenum_daytick(datenum, daytick, tz_info.offset); else if (tz != nullptr) return api->from_local_datenum_daytick(datenum, daytick, *tz, first); else throw py::ValueError("no time zone"); } else throw parse_error(p - pattern, s - string); } ref<Object> parse_time_iso( Module* /* module */, Tuple* const args, Dict* const kw_args) { static char const* arg_names[] = {"string", "Time", nullptr}; char const* string; PyTypeObject* time_type = &PyTimeDefault::type_; Arg::ParseTupleAndKeywords( args, kw_args, "s|$O", arg_names, &string, &time_type); auto const api = PyTimeAPI::get(time_type); if (api == nullptr) throw TypeError("not a time type"); YmdDate ymd; HmsDaytime hms; TimeZoneOffset tz_offset; char const* s = string; if (ora::time::parse_iso_time(s, ymd, hms, tz_offset) && *s == 0) { auto const datenum = ymd_to_datenum(ymd.year, ymd.month, ymd.day); auto const daytick = hms_to_daytick(hms.hour, hms.minute, hms.second); return api->from_local_datenum_daytick(datenum, daytick, tz_offset); } else throw parse_error(s - string); } ref<Object> set_display_time_zone( Module* /* module */, Tuple* const args, Dict* const kw_args) { static char const* arg_names[] = {"time_zone", nullptr}; Object* tz_arg; Arg::ParseTupleAndKeywords(args, kw_args, "O", arg_names, &tz_arg); auto tz = convert_to_time_zone(tz_arg); ora::set_display_time_zone(std::move(tz)); return none_ref(); } ref<Object> set_zoneinfo_dir( Module* /* module */, Tuple* const args, Dict* const kw_args) { static char const* arg_names[] = {"path", nullptr}; char* path; Arg::ParseTupleAndKeywords(args, kw_args, "s", arg_names, &path); ora::set_zoneinfo_dir(path); return none_ref(); } ref<Object> to_local( Module* /* module */, Tuple* const args, Dict* const kw_args) { Object* time; Object* tz_arg; PyTypeObject* date_type = &PyDateDefault::type_; PyTypeObject* daytime_type = &PyDaytimeDefault::type_; static char const* const arg_names[] = {"time", "time_zone", "Date", "Daytime", nullptr}; Arg::ParseTupleAndKeywords( args, kw_args, "OO|O!O!", arg_names, &time, &tz_arg, &PyType_Type, &date_type, &PyType_Type, &daytime_type); auto const tz = convert_to_time_zone(tz_arg); auto api = PyTimeAPI::get(time); auto local = // If this is a PyTime object and we have an API, use it. api != nullptr ? api->to_local_datenum_daytick(time, *tz) // Otherwise, convert to a time and then proceed. : ora::time::to_local_datenum_daytick( convert_to_time<ora::time::Time>(time), *tz); return PyLocal::create( make_date(local.datenum, date_type), make_daytime(local.daytick, daytime_type)); } ref<Object> today( Module* /* module */, Tuple* const args, Dict* const kw_args) { static char const* const arg_names[] = {"time_zone", "Date", nullptr}; Object* tz; PyTypeObject* date_type = &PyDateDefault::type_; // A bit hacky, but we don't check that date_type is a type object because // PyDateAPI won't accept anything else. Arg::ParseTupleAndKeywords( args, kw_args, "O|O!", arg_names, &tz, &PyType_Type, &date_type); auto api = PyDateAPI::get(date_type); if (api == nullptr) throw TypeError("not a date type"); else return api->today(*convert_to_time_zone(tz)); } } // anonymous namespace //------------------------------------------------------------------------------ Methods<Module>& add_functions( Methods<Module>& methods) { return methods .add<days_in_month> ("days_in_month", docstring::days_in_month) .add<days_in_year> ("days_in_year", docstring::days_in_year) .add<format_daytime_iso> ("format_daytime_iso", docstring::format_daytime_iso) .add<format_time> ("format_time", docstring::format_time) .add<format_time_iso> ("format_time_iso", docstring::format_time_iso) .add<from_local> ("from_local", docstring::from_local) .add<get_display_time_zone> ("get_display_time_zone", docstring::get_display_time_zone) .add<get_system_time_zone> ("get_system_time_zone", docstring::get_system_time_zone) .add<get_zoneinfo_dir> ("get_zoneinfo_dir", docstring::get_zoneinfo_dir) .add<is_leap_year> ("is_leap_year", docstring::is_leap_year) .add<now> ("now", docstring::now) .add<parse_date> ("parse_date", docstring::parse_date) .add<parse_daytime> ("parse_daytime", docstring::parse_daytime) .add<parse_time> ("parse_time", docstring::parse_time) .add<parse_time_iso> ("parse_time_iso", docstring::parse_time_iso) .add<set_display_time_zone> ("set_display_time_zone", docstring::set_display_time_zone) .add<set_zoneinfo_dir> ("set_zoneinfo_dir", docstring::set_zoneinfo_dir) .add<to_local> ("to_local", docstring::to_local) .add<today> ("today", docstring::today) ; } } // namespace py } // namespace ora
28.412186
97
0.643686
alexhsamuel
eacbd83cb2653718f0b0812fb072d28b0fdb0e7f
6,481
cc
C++
test/sagtension/cable_component_elongation_model_test.cc
Overhead-Transmission-Line-Software/Models
c270d48dc9d8a6eaed1d13851da7207474356342
[ "Unlicense" ]
null
null
null
test/sagtension/cable_component_elongation_model_test.cc
Overhead-Transmission-Line-Software/Models
c270d48dc9d8a6eaed1d13851da7207474356342
[ "Unlicense" ]
null
null
null
test/sagtension/cable_component_elongation_model_test.cc
Overhead-Transmission-Line-Software/Models
c270d48dc9d8a6eaed1d13851da7207474356342
[ "Unlicense" ]
null
null
null
// This is free and unencumbered software released into the public domain. // For more information, please refer to <http://unlicense.org/> #include "models/sagtension/cable_component_elongation_model.h" #include "gtest/gtest.h" #include "models/base/helper.h" #include "test/factory.h" class CableComponentElongationModelTest : public ::testing::Test { protected: CableComponentElongationModelTest() { // builds dependency object - component cable_ = factory::BuildSagTensionCable(); const SagTensionCableComponent* component = cable_->component_shell(); // builds dependency object - state state_.temperature = 70; state_.type_polynomial = SagTensionCableComponent::PolynomialType::kLoadStrain; // builds dependency object - stretch state state_stretch_.load = 5000; state_stretch_.temperature = 70; state_stretch_.type_polynomial = SagTensionCableComponent::PolynomialType::kLoadStrain; // builds fixture object c_.set_component_cable(component); c_.set_state(&state_); c_.set_state_stretch(&state_stretch_); c_.set_temperature_reference(cable_->temperature_properties_components()); } ~CableComponentElongationModelTest() { factory::DestroySagTensionCable(cable_); } // allocated dependency objects SagTensionCable* cable_; CableState state_; CableStretchState state_stretch_; // test object CableComponentElongationModel c_; }; TEST_F(CableComponentElongationModelTest, Load) { double value = -999999; // compressed region value = c_.Load(-0.0010); EXPECT_EQ(-211.1, helper::Round(value, 1)); // stretched region value = c_.Load(0.0010); EXPECT_EQ(289.3, helper::Round(value, 1)); value = c_.Load(0.0020); EXPECT_EQ(4938.2, helper::Round(value, 1)); // polynomial region value = c_.Load(0.0030); EXPECT_EQ(7301.6, helper::Round(value, 1)); value = c_.Load(0.0040); EXPECT_EQ(9187, helper::Round(value, 1)); value = c_.Load(0.0050); EXPECT_EQ(10645.4, helper::Round(value, 1)); // extrapolated region value = c_.Load(0.010); EXPECT_EQ(15851.8, helper::Round(value, 1)); // adjusts to creep stretch state and repeats tests // this should stretch the component more than before state_stretch_.load = 1500; state_stretch_.type_polynomial = SagTensionCableComponent::PolynomialType::kCreep; c_.set_state_stretch(&state_stretch_); // compressed region value = c_.Load(-0.0010); EXPECT_EQ(-224.0, helper::Round(value, 1)); // stretched region value = c_.Load(0.0010); EXPECT_EQ(-6.1, helper::Round(value, 1)); value = c_.Load(0.0020); EXPECT_EQ(4390.0, helper::Round(value, 1)); // polynomial region value = c_.Load(0.0030); EXPECT_EQ(7301.6, helper::Round(value, 1)); value = c_.Load(0.0040); EXPECT_EQ(9187, helper::Round(value, 1)); value = c_.Load(0.0050); EXPECT_EQ(10645.4, helper::Round(value, 1)); // extrapolated region value = c_.Load(0.0100); EXPECT_EQ(15851.8, helper::Round(value, 1)); } TEST_F(CableComponentElongationModelTest, PointsRegions) { std::vector<Point2d<double>> points = c_.PointsRegions(); Point2d<double> p; p = points.at(0); EXPECT_EQ(0.000938, helper::Round(p.x, 6)); EXPECT_EQ(0, helper::Round(p.y, 1)); p = points.at(1); EXPECT_EQ(0.0020, helper::Round(p.x, 4)); EXPECT_EQ(5000, helper::Round(p.y, 1)); p = points.at(2); EXPECT_EQ(0.0091, helper::Round(p.x, 4)); EXPECT_EQ(14711.1, helper::Round(p.y, 1)); } TEST_F(CableComponentElongationModelTest, Slope) { double value = -999999; // compressed region value = c_.Slope(-0.001); EXPECT_EQ(108960, helper::Round(value, 0)); // stretched region value = c_.Slope(0.001); EXPECT_EQ(4648960, helper::Round(value, 0)); value = c_.Slope(0.002); EXPECT_EQ(4648960, helper::Round(value, 0)); // polynomial region value = c_.Slope(0.003); EXPECT_EQ(2111035, helper::Round(value, 0)); value = c_.Slope(0.004); EXPECT_EQ(1663528, helper::Round(value, 0)); value = c_.Slope(0.005); EXPECT_EQ(1265984, helper::Round(value, 0)); // extrapolated region value = c_.Slope(0.010); EXPECT_EQ(1310911, helper::Round(value, 0)); } TEST_F(CableComponentElongationModelTest, Strain) { double value = -999999; // compressed region value = c_.Strain(-211.1); EXPECT_EQ(-0.0010, helper::Round(value, 4)); // stretched region value = c_.Strain(289.3); EXPECT_EQ(0.0010, helper::Round(value, 4)); value = c_.Strain(4938.2); EXPECT_EQ(0.0020, helper::Round(value, 4)); // polynomial region value = c_.Strain(7301.6); EXPECT_EQ(0.0030, helper::Round(value, 4)); value = c_.Strain(9187.0); EXPECT_EQ(0.0040, helper::Round(value, 4)); value = c_.Strain(10645.4); EXPECT_EQ(0.0050, helper::Round(value, 4)); // extrapolated region value = c_.Strain(15851.8); EXPECT_EQ(0.0100, helper::Round(value, 4)); // adjusts to creep stretch state and repeats tests // this should stretch the component more than before state_stretch_.load = 1500; state_stretch_.type_polynomial = SagTensionCableComponent::PolynomialType::kCreep; c_.set_state_stretch(&state_stretch_); // compressed region value = c_.Strain(-211.1); EXPECT_EQ(-0.0009, helper::Round(value, 4)); // stretched region value = c_.Strain(289.3); EXPECT_EQ(0.0011, helper::Round(value, 4)); value = c_.Strain(4938.2); EXPECT_EQ(0.0021, helper::Round(value, 4)); // polynomial region value = c_.Strain(7301.6); EXPECT_EQ(0.0030, helper::Round(value, 4)); value = c_.Strain(9187.0); EXPECT_EQ(0.0040, helper::Round(value, 4)); value = c_.Strain(10645.4); EXPECT_EQ(0.0050, helper::Round(value, 4)); // extrapolated region value = c_.Strain(15851.8); EXPECT_EQ(0.0100, helper::Round(value, 4)); } TEST_F(CableComponentElongationModelTest, StrainThermal) { double value = -999999; // at reference temperature value = c_.StrainThermal(); EXPECT_EQ(0, helper::Round(value, 7)); // above reference temperature state_.temperature = 212; c_.set_state(&state_); value = c_.StrainThermal(); EXPECT_EQ(0.0018176, helper::Round(value, 7)); // below reference temperature state_.temperature = 0; c_.set_state(&state_); value = c_.StrainThermal(); EXPECT_EQ(-0.000896, helper::Round(value, 7)); } TEST_F(CableComponentElongationModelTest, Validate) { // when checking for warnings, it does not pass the polynomial slope // validation EXPECT_TRUE(c_.Validate(false, nullptr)); }
28.550661
78
0.697115
Overhead-Transmission-Line-Software
eacefc9136158f0ef866fe94caff8ff231980ddc
2,966
hpp
C++
include/codegen/include/UnityEngine/GL.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/UnityEngine/GL.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/UnityEngine/GL.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:28 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "utils/typedefs.h" // Including type: System.Object #include "System/Object.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: UnityEngine namespace UnityEngine { // Forward declaring type: Color struct Color; } // Completed forward declares // Type namespace: UnityEngine namespace UnityEngine { // Autogenerated type: UnityEngine.GL class GL : public ::Il2CppObject { public: // static public System.Void Vertex3(System.Single x, System.Single y, System.Single z) // Offset: 0x12F7210 static void Vertex3(float x, float y, float z); // static public System.Void TexCoord3(System.Single x, System.Single y, System.Single z) // Offset: 0x12F726C static void TexCoord3(float x, float y, float z); // static public System.Void TexCoord2(System.Single x, System.Single y) // Offset: 0x12F72C8 static void TexCoord2(float x, float y); // static public System.Boolean get_invertCulling() // Offset: 0x12F7318 static bool get_invertCulling(); // static public System.Void set_invertCulling(System.Boolean value) // Offset: 0x12F734C static void set_invertCulling(bool value); // static public System.Void Flush() // Offset: 0x12F738C static void Flush(); // static public System.Void PushMatrix() // Offset: 0x12F73C0 static void PushMatrix(); // static public System.Void PopMatrix() // Offset: 0x12F73F4 static void PopMatrix(); // static public System.Void LoadOrtho() // Offset: 0x12F7428 static void LoadOrtho(); // static public System.Void Begin(System.Int32 mode) // Offset: 0x12F745C static void Begin(int mode); // static public System.Void End() // Offset: 0x12F749C static void End(); // static private System.Void GLClear(System.Boolean clearDepth, System.Boolean clearColor, UnityEngine.Color backgroundColor, System.Single depth) // Offset: 0x12F74D0 static void GLClear(bool clearDepth, bool clearColor, UnityEngine::Color backgroundColor, float depth); // static public System.Void Clear(System.Boolean clearDepth, System.Boolean clearColor, UnityEngine.Color backgroundColor) // Offset: 0x12F75B0 static void Clear(bool clearDepth, bool clearColor, UnityEngine::Color backgroundColor); // static private System.Void GLClear_Injected(System.Boolean clearDepth, System.Boolean clearColor, UnityEngine.Color backgroundColor, System.Single depth) // Offset: 0x12F7548 static void GLClear_Injected(bool clearDepth, bool clearColor, UnityEngine::Color& backgroundColor, float depth); }; // UnityEngine.GL } DEFINE_IL2CPP_ARG_TYPE(UnityEngine::GL*, "UnityEngine", "GL"); #pragma pack(pop)
42.371429
160
0.711059
Futuremappermydud
ead5e80a50f623e4ff2b096693d17975324d081f
1,771
hpp
C++
modules/engine/include/randar/Input/InputController.hpp
litty-studios/randar
95daae57b1ec7d87194cdbcf6e3946b4ed9fc79b
[ "MIT" ]
1
2016-11-12T02:43:29.000Z
2016-11-12T02:43:29.000Z
modules/engine/include/randar/Input/InputController.hpp
litty-studios/randar
95daae57b1ec7d87194cdbcf6e3946b4ed9fc79b
[ "MIT" ]
null
null
null
modules/engine/include/randar/Input/InputController.hpp
litty-studios/randar
95daae57b1ec7d87194cdbcf6e3946b4ed9fc79b
[ "MIT" ]
null
null
null
#ifndef RANDAR_SYSTEM_INPUT_CONTROLLER_HPP #define RANDAR_SYSTEM_INPUT_CONTROLLER_HPP #include <set> #include <randar/Math/Vector2.hpp> namespace randar { class InputController { protected: /** * List of currently pressed keys. */ std::set<unsigned int> pressedKeys; /** * List of currently pressed mouse buttons. */ std::set<unsigned int> pressedMouseButtons; /** * Most recently known position of the mouse. */ randar::Vector2<float> mousePosition; public: /** * Destructor. */ virtual ~InputController(); /** * Handles a raw key press. */ void handleRawKeyPress(unsigned int key); /** * Handles a raw key release. */ void handleRawKeyRelease(unsigned int key); /** * Handles a raw mouse button press. */ void handleRawMouseButtonPress(unsigned int button); /** * Handles a raw mouse button release. */ void handleRawMouseButtonRelease(unsigned int button); /** * Handles a raw mouse position update. */ void handleRawMousePosition(float x, float y); /** * Whether a key is being pressed. */ bool isKeyPressed(unsigned int key) const; /** * Handles an interpreted key press. */ virtual void onKeyPress(unsigned int key); /** * Handles an interpreted key release. */ virtual void onKeyRelease(unsigned int key); /** * Performs custom input handling. */ virtual void handleInput(); }; } #endif
21.864198
62
0.543761
litty-studios
ead687194f9426bc1d97327d336c404863ccb06a
144
cpp
C++
babelBubel/delayer.cpp
dorianJaniak/koty_inne
aace956718d6a7540a438c7ccc3b43a35842b646
[ "Apache-2.0" ]
null
null
null
babelBubel/delayer.cpp
dorianJaniak/koty_inne
aace956718d6a7540a438c7ccc3b43a35842b646
[ "Apache-2.0" ]
null
null
null
babelBubel/delayer.cpp
dorianJaniak/koty_inne
aace956718d6a7540a438c7ccc3b43a35842b646
[ "Apache-2.0" ]
null
null
null
#include <ctime> void delay_ms(int ms_time) { clock_t pocz = clock(); clock_t koniec; do{ koniec = clock(); }while(koniec-pocz<ms_time); }
14.4
29
0.680556
dorianJaniak
ead6f86d2ae97ef3320ca65f33ae6a8372b68e13
11,098
cpp
C++
jfs/LBMSolver.cpp
jackm97/jfs
49b0f4d999ddd215ef9fb574ba92314e48437c2e
[ "MIT" ]
null
null
null
jfs/LBMSolver.cpp
jackm97/jfs
49b0f4d999ddd215ef9fb574ba92314e48437c2e
[ "MIT" ]
null
null
null
jfs/LBMSolver.cpp
jackm97/jfs
49b0f4d999ddd215ef9fb574ba92314e48437c2e
[ "MIT" ]
null
null
null
#include "LBMSolver.h" #include <cmath> #include <cstring> #include <iostream> namespace jfs { JFS_INLINE LBMSolver::LBMSolver(unsigned int N, float L, BoundType btype, float rho0, float visc, float uref) { Initialize(N, L, btype, rho0, visc, uref); } JFS_INLINE void LBMSolver::Initialize(unsigned int N, float L, BoundType btype, float rho0, float visc, float uref) { this->rho0_ = rho0; this->visc_ = visc; this->uref_ = uref; ClearGrid(); // lattice scaling stuff cs_ = 1 / std::sqrt(3); us_ = cs_ / lat_uref_ * uref; // dummy dt_ because it is calculated float dummy_dt; initializeGrid(N, L, btype, dummy_dt); lat_visc_ = lat_uref_ / (uref * dx_) * visc; lat_tau_ = (3 * lat_visc_ + .5); dt_ = lat_uref_ / uref * dx_ * lat_dt_; f_grid_ = new float[9 * N * N]; f0_grid_ = new float[9 * N * N]; rho_ = new float[N*N]; rho_mapped_ = new float[3*N*N]; u_grid_ = new float[2 * N * N]; force_grid_ = new float[2 * N * N]; ResetFluid(); is_initialized_ = true; } JFS_INLINE void LBMSolver::SetDensityMapping(float minrho, float maxrho) { minrho_ = minrho; maxrho_ = maxrho; } JFS_INLINE void LBMSolver::DensityExtrema(float *minmax_rho) { float minrho_ = rho_[0]; float maxrho_ = rho_[0]; for (int i=0; i < N*N; i++) { if (rho_[i] < minrho_) minrho_ = rho_[i]; } for (int i=0; i < N*N; i++) { if (rho_[i] > maxrho_) maxrho_ = rho_[i]; } minmax_rho[0] = minrho_; minmax_rho[1] = maxrho_; } JFS_INLINE void LBMSolver::ResetFluid() { for (int i = 0; i < N*N; i++) { u_grid_[2 * i + 0] = 0; u_grid_[2 * i + 1] = 0; force_grid_[2 * i + 0] = 0; force_grid_[2 * i + 1] = 0; rho_[i] = rho0_; } // reset distribution for (int j=0; j < N; j++) for (int k=0; k < N; k++) for (int i=0; i < 9; i++) f_grid_[N * 9 * k + 9 * j + i] = CalcEquilibriumDistribution(i, j, k); time_ = 0; } JFS_INLINE void LBMSolver::MapDensity() { auto btype = this->bound_type_; auto L = this->L; auto N = this->N; auto D = this->D; float minrho = rho_[0]; float maxrho = rho_[0]; float meanrho = 0; for (int i = 0; i < N*N; i++) meanrho += rho_[i]; meanrho /= N*N; for (int i=0; i < N*N && minrho_ == -1; i++) { if (rho_[i] < minrho) minrho = rho_[i]; } if (minrho_ != -1) minrho = minrho_; for (int i=0; i < N*N && maxrho_ == -1; i++) { if (rho_[i] > maxrho) maxrho = rho_[i]; } if (maxrho_ == -1 && minrho_ == -1) { if (maxrho - meanrho > meanrho - minrho) minrho = meanrho - (maxrho - meanrho); else maxrho = meanrho - (minrho - meanrho); } if (maxrho_ != -1) maxrho = maxrho_; for (int i=0; i < N; i++) for (int j=0; j < N; j++) { int indices[2]{i, j}; float rho; indexGrid(&rho, indices, rho_, SCALAR_FIELD, 1); if ((maxrho - minrho) != 0) rho = (rho- minrho)/(maxrho - minrho); else rho = 0 * rho; // rho = (rho < 0) ? 0 : rho; // rho = (rho > 1) ? 1 : rho; float rho_gray[3]{rho, rho, rho}; insertIntoGrid(indices, rho_gray, rho_mapped_, SCALAR_FIELD, 3); } } JFS_INLINE void LBMSolver::ForceVelocity(int i, int j, float ux, float uy) { int indices[2]{i, j}; float u[2]{ux, uy}; float u_prev[2]; indexGrid(u_prev, indices, u_grid_, VECTOR_FIELD); float rho; indexGrid(&rho, indices, rho_, SCALAR_FIELD); float f[2]{ (u[0] - u_prev[0]) * rho / this->dt_, (u[1] - u_prev[1]) * rho / this->dt_ }; insertIntoGrid(indices, f, force_grid_, VECTOR_FIELD, 1, Add); } JFS_INLINE void LBMSolver::DoBoundaryDamping() { for (int i = 0; i < N; i+=(N-1)) { int step; if (i == 0) step = 1; else step = -1; for (int j = 0; j < N; j++) { int indices[2]{ i + step, j }; float u[2]; indexGrid(u, indices, u_grid_, VECTOR_FIELD); float rho; indexGrid(&rho, indices, rho_, SCALAR_FIELD); indices[0] = i; insertIntoGrid(indices, &rho, rho_, SCALAR_FIELD); insertIntoGrid(indices, u, u_grid_, VECTOR_FIELD, 1); float fbar[9]; for (int k = 0; k < 9; k++) { fbar[k] = CalcEquilibriumDistribution(k, i, j); } insertIntoGrid(indices, fbar, f_grid_, SCALAR_FIELD, 9); CalcPhysicalVals(i, j); } } for (int i = 0; i < N; i+=(N-1)) { int step; if (i == 0) step = 1; else step = -1; for (int j = 0; j < N; j++) { int indices[2]{ j, i + step }; float u[2]; indexGrid(u, indices, u_grid_, VECTOR_FIELD); float rho; indexGrid(&rho, indices, rho_, SCALAR_FIELD); indices[1] = i; insertIntoGrid(indices, &rho, rho_, SCALAR_FIELD); insertIntoGrid(indices, u, u_grid_, VECTOR_FIELD, 1); float fbar[9]; for (int k = 0; k < 9; k++) { fbar[k] = CalcEquilibriumDistribution(k, j, i); } insertIntoGrid(indices, fbar, f_grid_, SCALAR_FIELD, 9); CalcPhysicalVals(j, i); } } } JFS_INLINE bool LBMSolver::calcNextStep() { BoundType btype = this->bound_type_; // collide for (int idx=0; idx<(N*N*9); idx++) { float fi; float fbari; float Omegai; float lat_force; int idx_tmp = idx; int j = idx_tmp / (N * 9); idx_tmp -= j * (N * 9); int i = idx_tmp / 9; idx_tmp -= i * 9; int alpha = idx_tmp; fi = f_grid_[N * 9 * j + 9 * i + alpha]; fbari = CalcEquilibriumDistribution(alpha, i, j); lat_force = CalcLatticeForce(alpha, i, j); Omegai = -(fi - fbari) / lat_tau_; f_grid_[N * 9 * j + 9 * i + alpha] = fi + Omegai + lat_force; } std::memcpy(f0_grid_, f_grid_, 9 * N * N * sizeof(float)); // stream for (int idx=0; idx<(N*N*9); idx++) { float fiStar; int idx_tmp = idx; int j = idx_tmp / (N * 9); idx_tmp -= j * (N * 9); int i = idx_tmp / 9; idx_tmp -= i * 9; int alpha = idx_tmp; int cix = c[alpha][0]; int ciy = c[alpha][1]; if ((j - ciy) >= 0 && (j - ciy) < N && (i - cix) >= 0 && (i - cix) < N) fiStar = f0_grid_[N * 9 * (j - ciy) + 9 * (i - cix) + alpha]; else { int alpha_bounce = bounce_back_indices_[alpha]; fiStar = f0_grid_[N * 9 * j + 9 * i + alpha_bounce]; } f_grid_[N * 9 * j + 9 * i + alpha] = fiStar; CalcPhysicalVals(i, j); float u[2]; int indices[2]{i, j}; indexGrid(u, indices, u_grid_, VECTOR_FIELD); if (std::isinf(u[0]) || std::isinf(u[1]) || std::isnan(u[0]) || std::isnan(u[1])) return true; } // do any field manipulations before collision step if (btype == DAMPED) DoBoundaryDamping(); time_ += dt_; return false; } JFS_INLINE bool LBMSolver::CalcNextStep(const std::vector<Force> forces) { bool failedStep = false; try { for (int i = 0; i < forces.size(); i++) { float force[3] = { forces[i].force[0], forces[i].force[1], forces[i].force[2] }; float point[3] = { forces[i].pos[0]/this->D, forces[i].pos[1]/this->D, forces[i].pos[2]/this->D }; this->interpPointToGrid(force, point, force_grid_, VECTOR_FIELD, 1, Add); } failedStep = calcNextStep(); for (int i = 0; i < N*N; i++) { force_grid_[2 * i + 0] = 0; force_grid_[2 * i + 1] = 0; } } catch(const std::exception& e) { std::cerr << e.what() << '\n'; failedStep = true; } if (failedStep) ResetFluid(); return failedStep; } JFS_INLINE void LBMSolver::ClearGrid() { if (!is_initialized_) return; delete [] f_grid_; delete [] f0_grid_; delete [] rho_; delete [] rho_mapped_; delete [] u_grid_; delete [] force_grid_; is_initialized_ = false; } JFS_INLINE float LBMSolver::CalcEquilibriumDistribution(int i, int j, int k) { int indices[2]{j, k}; float fbari; float rho_jk; // rho_ at point P -> (j,k) indexGrid(&rho_jk, indices, rho_, SCALAR_FIELD); float wi = w[i]; float u[2]; indexGrid(u, indices, u_grid_, VECTOR_FIELD); u[0] *= lat_uref_ / uref_; u[1] *= lat_uref_ / uref_; float ci[2]{c[i][0], c[i][1]}; float ci_dot_u = ci[0]*u[0] + ci[1]*u[1]; float u_dot_u = u[0]*u[0] + u[1]*u[1]; fbari = wi * rho_jk / rho0_ * (1 + ci_dot_u / (std::pow(cs_, 2)) + std::pow(ci_dot_u, 2) / (2 * std::pow(cs_, 4)) - u_dot_u / (2 * std::pow(cs_, 2)) ); return fbari; } JFS_INLINE float LBMSolver::CalcLatticeForce(int i, int j, int k) { int indices[2]{j, k}; float wi = w[i]; float u[2]; indexGrid(u, indices, u_grid_, VECTOR_FIELD); u[0] *= lat_uref_ / uref_; u[1] *= lat_uref_ / uref_; float ci[2]{c[i][0], c[i][1]}; float ci_dot_u = ci[0]*u[0] + ci[1]*u[1]; float F_jk[2]; indexGrid(F_jk, indices, force_grid_, VECTOR_FIELD); F_jk[0] *= (1 / rho0_ * dx_ * std::pow(lat_uref_ / uref_, 2) ); F_jk[1] *= (1 / rho0_ * dx_ * std::pow(lat_uref_ / uref_, 2) ); float Fi = (1 - lat_tau_ / 2) * wi * ( ((1/std::pow(cs_, 2)) * (ci[0] - u[0]) + (ci_dot_u / std::pow(cs_, 4)) * ci[0] ) * F_jk[0] + ((1/std::pow(cs_, 2)) * (ci[1] - u[1]) + (ci_dot_u / std::pow(cs_, 4)) * ci[1] ) * F_jk[1] ); return Fi; } JFS_INLINE void LBMSolver::CalcPhysicalVals(int j, int k) { float rho_jk = 0; float momentum_jk[2]{0, 0}; for (int i=0; i<9; i++) { rho_jk += f_grid_[N * 9 * k + 9 * j + i]; momentum_jk[0] += c[i][0] * f_grid_[N * 9 * k + 9 * j + i]; momentum_jk[1] += c[i][1] * f_grid_[N * 9 * k + 9 * j + i]; } float* u = momentum_jk; u[0] = uref_ / lat_uref_ * (momentum_jk[0] / rho_jk); u[1] = uref_ / lat_uref_ * (momentum_jk[1] / rho_jk); rho_jk = rho0_ * rho_jk; int indices[2]{j, k}; insertIntoGrid(indices, &rho_jk, rho_, SCALAR_FIELD); insertIntoGrid(indices, u, u_grid_, VECTOR_FIELD); } } // namespace jfs
24.126087
155
0.492341
jackm97
46ae67bfe10d2324d2a838ec62212a97ead1c18f
3,245
cxx
C++
src/converter/opengm2uai.cxx
burcin/opengm
a1b21eecb93c6c5a7b11ab312d26b1c98c55ff41
[ "MIT" ]
318
2015-01-07T15:22:02.000Z
2022-01-22T10:10:29.000Z
src/converter/opengm2uai.cxx
burcin/opengm
a1b21eecb93c6c5a7b11ab312d26b1c98c55ff41
[ "MIT" ]
89
2015-03-24T14:33:01.000Z
2020-07-10T13:59:13.000Z
src/converter/opengm2uai.cxx
burcin/opengm
a1b21eecb93c6c5a7b11ab312d26b1c98c55ff41
[ "MIT" ]
119
2015-01-13T08:35:03.000Z
2022-03-01T01:49:08.000Z
#include <string> #include <vector> #include <iostream> #include <fstream> #include <opengm/graphicalmodel/graphicalmodel.hxx> #include <opengm/graphicalmodel/graphicalmodel_hdf5.hxx> #include <opengm/operations/minimizer.hxx> #include <opengm/operations/adder.hxx> #include <opengm/functions/explicit_function.hxx> #include <opengm/functions/potts.hxx> #include <opengm/functions/pottsn.hxx> #include <opengm/functions/pottsg.hxx> #include "opengm/functions/truncated_absolute_difference.hxx" #include "opengm/functions/truncated_squared_difference.hxx" int main(int argc, const char* argv[] ) { typedef double ValueType; typedef size_t IndexType; typedef size_t LabelType; typedef opengm::Adder OperatorType; typedef opengm::Minimizer AccumulatorType; typedef opengm::DiscreteSpace<IndexType, LabelType> SpaceType; // Set functions for graphical model typedef opengm::meta::TypeListGenerator< opengm::ExplicitFunction<ValueType, IndexType, LabelType>, opengm::PottsFunction<ValueType, IndexType, LabelType>, opengm::PottsNFunction<ValueType, IndexType, LabelType>, opengm::PottsGFunction<ValueType, IndexType, LabelType>, opengm::TruncatedSquaredDifferenceFunction<ValueType, IndexType, LabelType>, opengm::TruncatedAbsoluteDifferenceFunction<ValueType, IndexType, LabelType> >::type FunctionTypeList; typedef opengm::GraphicalModel< ValueType, OperatorType, FunctionTypeList, SpaceType > GmType; GmType gm; std::string opengmfile = argv[1]; std::string uaifile = argv[2]; opengm::hdf5::load(gm, opengmfile,"gm"); std::ofstream myuaifile; myuaifile.open(uaifile.c_str()); myuaifile << "MARKOV" << std::endl; myuaifile << gm.numberOfVariables() << std::endl; for(IndexType var=0; var<gm.numberOfVariables(); ++var){ myuaifile << gm.numberOfLabels(var) << " "; } myuaifile << std::endl; myuaifile << gm.numberOfFactors() << std::endl; for(IndexType f=0; f<gm.numberOfFactors(); ++f){ myuaifile << gm[f].numberOfVariables() << " " ; for(IndexType i=0; i<gm[f].numberOfVariables(); ++i){ myuaifile << gm[f].variableIndex(i) << " "; } myuaifile << std::endl; } LabelType l[3] = {0,0,0}; for(IndexType f=0; f<gm.numberOfFactors(); ++f){ myuaifile << std::endl; myuaifile << gm[f].size() << std::endl; if(gm[f].numberOfVariables()==0){ l[0]=0; myuaifile << std::exp(-gm[f](l)) << std::endl; } else if(gm[f].numberOfVariables()==1){ for(l[0]=0; l[0]<gm[f].numberOfLabels(0); ++l[0]){ myuaifile << std::exp(-gm[f](l)) << " "; } myuaifile << std::endl; } else if(gm[f].numberOfVariables()==2){ for(l[0]=0; l[0]<gm[f].numberOfLabels(0); ++l[0]){ for(l[1]=0; l[1]<gm[f].numberOfLabels(1); ++l[1]){ myuaifile << std::exp(-gm[f](l)) << " "; } myuaifile << std::endl; } } else{ std::cout << "Factors of order higher than 2 are so far not supported !" <<std::endl; myuaifile.close(); return 1; } } myuaifile.close(); return 0; }
31.813725
94
0.630508
burcin
46b3184221e6d42c5d054424875e2a3fb4ab4201
1,243
cpp
C++
tests/dense_like.cpp
ivansipiran/numpyeigen
48c6ccc5724572c6107240fa472d3c1ff04d679d
[ "MIT" ]
null
null
null
tests/dense_like.cpp
ivansipiran/numpyeigen
48c6ccc5724572c6107240fa472d3c1ff04d679d
[ "MIT" ]
null
null
null
tests/dense_like.cpp
ivansipiran/numpyeigen
48c6ccc5724572c6107240fa472d3c1ff04d679d
[ "MIT" ]
null
null
null
#include <tuple> #include <Eigen/Core> #include <iostream> #include <npe.h> npe_function(dense_like_1) npe_arg(a, sparse_double, sparse_float) npe_arg(b, npe_dense_like(a)) npe_begin_code() npe_Matrix_b ret1 = a * b; return npe::move(ret1); npe_end_code() npe_function(dense_like_2) npe_arg(a, sparse_double, sparse_float) npe_arg(b, npe_dense_like(a)) npe_arg(c, npe_dense_like(a)) npe_begin_code() npe_Matrix_b ret1 = b; return npe::move(ret1); npe_end_code() npe_function(dense_like_3) npe_arg(a, sparse_double, sparse_float) npe_arg(b, npe_dense_like(a)) npe_arg(c, npe_dense_like(b)) npe_begin_code() npe_Matrix_b ret1 = b; return npe::move(ret1); npe_end_code() npe_function(dense_like_4) npe_arg(a, dense_double, dense_float) npe_arg(b, npe_dense_like(a)) npe_arg(c, npe_dense_like(b)) npe_begin_code() npe_Matrix_b ret1 = b; return npe::move(ret1); npe_end_code() npe_function(dense_like_5) npe_arg(a, sparse_double, sparse_float) npe_arg(b, npe_dense_like(a)) npe_arg(c, npe_sparse_like(b)) npe_arg(d, npe_matches(c)) npe_arg(e, npe_matches(b)) npe_arg(f, npe_dense_like(b)) npe_arg(g, npe_matches(b)) npe_arg(h, npe_matches(a)) npe_begin_code() npe_Matrix_b ret1 = a * b; return npe::move(ret1); npe_end_code()
17.507042
39
0.76428
ivansipiran
46c1498aea47b7400764f73ec8f23e668cca2f67
4,844
cpp
C++
MainViewer_CellMakingViewer_PartsAssembler_Workspace.cpp
sknjpn/SyLife
b215cba87096db52ac63931db64c967f906b9172
[ "MIT" ]
5
2022-01-05T10:04:40.000Z
2022-01-11T13:23:43.000Z
MainViewer_CellMakingViewer_PartsAssembler_Workspace.cpp
sknjpn/SyLife
b215cba87096db52ac63931db64c967f906b9172
[ "MIT" ]
1
2022-01-05T10:51:42.000Z
2022-01-05T13:25:41.000Z
MainViewer_CellMakingViewer_PartsAssembler_Workspace.cpp
sknjpn/SyLife
b215cba87096db52ac63931db64c967f906b9172
[ "MIT" ]
null
null
null
#include "CellAsset.h" #include "GUIButton.h" #include "MainViewer.h" #include "PartAsset.h" #include "PartConfig.h" #include "Part_BodyAsset.h" #include "Part_NucleusAsset.h" void MainViewer::CellMakingViewer::PartsAssembler::Workspace::init() { setBackgroundColor(Palette::Black); setViewerRectInLocal(200, 0, 800, 800); addChildViewer<TrashBox>(); } void MainViewer::CellMakingViewer::PartsAssembler::Workspace::update() { auto t = Transformer2D(Mat3x2::Scale(4).translated(400, 400), TransformCursor::Yes); // 描画 for (const auto& partConfig : m_cellAsset->getPartConfigs()) { { auto t2 = Transformer2D(partConfig->getMat3x2()); partConfig->getPartAsset()->draw(0.5); partConfig->getPartAsset()->getShape().getPolygon().drawFrame(1.0, Palette::Black); } // 回転の中心 if (m_state == State::RotateMode && !std::dynamic_pointer_cast<Part_BodyAsset>(partConfig->getPartAsset())) Circle(partConfig->getPosition(), 2.0).draw(Palette::Yellow).drawFrame(1.0, Palette::Black); } // 描画 if (m_selectedPartConfig) { auto t2 = Transformer2D(Mat3x2::Rotate(m_selectedPartConfig->getRotation() + m_deltaRotation).translated(m_selectedPartConfig->getPosition() + m_deltaPosition)); if (m_state == State::MoveMode && getChildViewer<TrashBox>()->isMouseover()) getChildViewer<TrashBox>()->select(); else { bool canSetPart = m_cellAsset->getBodyAsset()->getShape().getPolygon().contains(m_selectedPartConfig->getPosition() + m_deltaPosition); auto color = canSetPart ? Palette::Green : Palette::Red; m_selectedPartConfig->getPartAsset()->draw(0.5); m_selectedPartConfig->getPartAsset()->getShape().getPolygon().draw(ColorF(color, 0.5)); } } // 適用 if (MouseL.up() && m_selectedPartConfig) { if (m_state == State::MoveMode) { if (getChildViewer<TrashBox>()->isMouseover()) { m_cellAsset->removePartConfig(m_selectedPartConfig); } else { bool canSetPart = m_cellAsset->getBodyAsset()->getShape().getPolygon().contains(m_selectedPartConfig->getPosition() + m_deltaPosition); if (canSetPart) m_selectedPartConfig->setPosition(m_selectedPartConfig->getPosition() + m_deltaPosition); } } if (m_state == State::RotateMode) m_selectedPartConfig->setRotation(m_selectedPartConfig->getRotation() + m_deltaRotation); m_selectedPartConfig = nullptr; } // 移動 if (m_selectedPartConfig) { if (m_state == State::MoveMode) m_deltaPosition += Cursor::DeltaF(); if (m_state == State::RotateMode) { const auto t2 = Transformer2D(Mat3x2::Translate(m_selectedPartConfig->getPosition()), TransformCursor::Yes); if (!Cursor::PreviousPosF().isZero() && !Cursor::PosF().isZero()) m_deltaRotation += Cursor::PreviousPosF().getAngle(Cursor::PosF()); } } // 選択 if (!m_selectedPartConfig && MouseL.down() && isMouseover()) { for (const auto& partConfig : m_cellAsset->getPartConfigs()) { if (std::dynamic_pointer_cast<Part_BodyAsset>(partConfig->getPartAsset())) continue; if (std::dynamic_pointer_cast<Part_NucleusAsset>(partConfig->getPartAsset())) continue; auto t2 = Transformer2D(partConfig->getMat3x2(), TransformCursor::Yes); if (partConfig->getPartAsset()->getShape().getPolygon().mouseOver()) { m_selectedPartConfig = partConfig; m_deltaPosition = Vec2::Zero(); m_deltaRotation = 0.0; } } } // selectedPart if (auto& selectedPart = getParentViewer()->getChildViewer<PartList>()->getSelectedPart()) { bool canSetPart = m_cellAsset->getBodyAsset()->getShape().getPolygon().contains(Cursor::PosF()); if (isMouseover()) { { auto t2 = Transformer2D(Mat3x2::Translate(Cursor::PosF())); selectedPart->draw(0.5); } if (MouseL.up() && canSetPart) { const auto& partConfig = m_cellAsset->addPartConfig(); partConfig->setPartAsset(selectedPart); partConfig->setPosition(Vec2(Cursor::PosF().x, Cursor::PosF().y)); partConfig->setRotation(0.0); } selectedPart->getShape().getPolygon().movedBy(Cursor::PosF()).draw(ColorF(canSetPart ? Palette::Green : Palette::Red, 0.5)); } if (!MouseL.pressed()) getParentViewer()->getChildViewer<PartList>()->clearSelectedPart(); } } void MainViewer::CellMakingViewer::PartsAssembler::Workspace::setMoveMode() { m_state = State::MoveMode; getParentViewer()->getChildViewer<GUIButton>(U"移動モード")->setIsEnabled(false); getParentViewer()->getChildViewer<GUIButton>(U"回転モード")->setIsEnabled(true); } void MainViewer::CellMakingViewer::PartsAssembler::Workspace::setRotateMode() { m_state = State::RotateMode; getParentViewer()->getChildViewer<GUIButton>(U"移動モード")->setIsEnabled(true); getParentViewer()->getChildViewer<GUIButton>(U"回転モード")->setIsEnabled(false); }
36.977099
204
0.692609
sknjpn
46c9f204917b13c79a08ac42e71b8d6dfc4605ca
944
cpp
C++
Cpp/fost-core/json-iterator-tests.cpp
KayEss/fost-base
05ac1b6a1fb672c61ba6502efea86f9c5207e28f
[ "BSL-1.0" ]
2
2016-05-25T22:17:38.000Z
2019-04-02T08:34:17.000Z
Cpp/fost-core/json-iterator-tests.cpp
KayEss/fost-base
05ac1b6a1fb672c61ba6502efea86f9c5207e28f
[ "BSL-1.0" ]
5
2018-07-13T10:43:05.000Z
2019-09-02T14:54:42.000Z
Cpp/fost-core/json-iterator-tests.cpp
KayEss/fost-base
05ac1b6a1fb672c61ba6502efea86f9c5207e28f
[ "BSL-1.0" ]
1
2020-10-22T20:44:24.000Z
2020-10-22T20:44:24.000Z
/** Copyright 1999-2019 Red Anchor Trading Co. Ltd. Distributed under the Boost Software License, Version 1.0. See <http://www.boost.org/LICENSE_1_0.txt> */ #include "fost-core-test.hpp" #include <fost/unicode> using namespace fostlib; FSL_TEST_SUITE(json_iterator); FSL_TEST_FUNCTION(empty) { json empty; fostlib::test::default_copy_constructable<json::const_iterator>(); FSL_CHECK(json::const_iterator() == empty.begin()); } FSL_TEST_FUNCTION(key_object) { json object = json::object_t(); jcursor("key1").insert(object, "value1"); jcursor("key2").insert(object, "value2"); json::const_iterator p = object.begin(); FSL_CHECK_EQ(*p, json("value1")); FSL_CHECK_EQ(p->get<f5::u8view>().value(), "value1"); FSL_CHECK_EQ(p.key(), json("key1")); FSL_CHECK_NOTHROW(++p); FSL_CHECK_EQ(*p, json("value2")); FSL_CHECK_EQ(p.key(), json("key2")); FSL_CHECK_NOTHROW(++p); }
23.02439
70
0.668432
KayEss
46ca8514dd32be49ab847b6f4c38ce8f83b354b8
13,306
cpp
C++
iniplus.cpp
solariun/libsolar
5964054b4064a231280b3c2df1e205cabe66ac9f
[ "MIT" ]
null
null
null
iniplus.cpp
solariun/libsolar
5964054b4064a231280b3c2df1e205cabe66ac9f
[ "MIT" ]
null
null
null
iniplus.cpp
solariun/libsolar
5964054b4064a231280b3c2df1e205cabe66ac9f
[ "MIT" ]
null
null
null
// // iniplus.cpp // LibSolar++ // // Created by GUSTAVO CAMPOS on 26/03/18. // Copyright © 2018 GUSTAVO CAMPOS. All rights reserved. // #include "iniplus.hpp" #include <iostream> #include <new> #include <sstream> #include <stdlib.h> #include <cctype> iniplusException::iniplusException (std::string strMessage, uint nErrorID): Exception ("iniplus", strMessage, nErrorID) {} iniplus::iniplus (const string strINIFileName) : strFileName(strINIFileName) { ifstream* ifsFile; Verify(Util::getFileSize(strINIFileName) > 0, "Errro, file is zero or does not exist.", EXCEPT_INI_FILE_DOSENT_EXIST_OR_ZERO, iniplusException); ifsFile = new ifstream (strINIFileName); //int errn = errno; Verify((ifsFile->rdstate() & std::ifstream::failbit) == 0, "File could not be read.", EXCEPT_INI_FILE_NOT_READ, iniplusException); this->isIn = ifsFile; char chCinbuffer [64 * 1024]; // 64k buffer; this->isIn->rdbuf()->pubsetbuf(chCinbuffer, sizeof (chCinbuffer)); //Starting creating the structure of the data try { parseINI(); } catch (...) { this->isIn->close(); throw; } this->isIn->close(); } void iniplus::parseINI (string strPath, uint32_t nDepth) { iniParserItemRet lexItem; string strValue = ""; string strAttribute = ""; string strTempValue = ""; uint nType = none_tag; if (strPath.length() > 0) { NOTRACE << "Entering level (" << nDepth << ") [" << strPath << "]" << endl; } while (getNextLexicalItem(lexItem) != NULL) { NOTRACE << ">>>>> PARSER <<<<< :" << "strPath: [" << strPath.length() << "] Received Lex Item: (" << lexItem.nType << ") [" << lexItem.strValue << "]" << endl; if (lexItem.nType == session_tag) { strPath = lexItem.strValue; } else if (strPath.length() > 0) { if (nType == none_tag) { if (lexItem.nType == string_tag) { strAttribute = lexItem.strValue; nType = value_tag; } else if (lexItem.nType == close_struct_tag) { NOTRACE << "---------------------------------" << endl; NOTRACE << "Leving Level " << nDepth << "..." << endl << endl; return; } } if (nType == value_tag) { Verify (strAttribute.length() > 0, "Error, no Attribute value available.", EXCEPT_INI_INVALID_ATTRIBUTE_VALUE, iniplusException); if (lexItem.nType == attributive_tag) { Verify (getNextLexicalItem(lexItem) != NULL && lexItem.nType == string_tag, "Syntatic Error, no correct value given", EXCEPT_INI_SYNT_ERROR_INVALID_VALUE, iniplusException); strTempValue = strPath + "." + strAttribute; mapIniData.insert (pair<string, string> (Util::strToUpper(strTempValue), lexItem.strValue)); NOTRACE << "Adding: [" << strPath << "." << strAttribute << "] = [" << lexItem.strValue << "]" << endl; nType = none_tag; } else if (lexItem.nType == open_struct_tag) { parseINI(strPath + "." + strAttribute, nDepth + 1); NOTRACE << "Returned to: [" << strPath << "]" << endl; nType = none_tag; } } } else { Verify (strPath.length() == 0 && lexItem.nType == session_tag, "Error, Trying to add values with no session open, please revise the ini structure.", EXCEPT_INI_FAIL_ADD_VALUE_NO_SESSION, iniplusException); } } } inline bool isAlphaData (char chChar) { return (isdigit (chChar) || isalpha(chChar) || Util::isBetween(chChar, "_-\\", 3)); } iniParserItemRet* iniplus::getNextLexicalItem (iniParserItemRet& iniParserItem) { string strData = ""; char stzTemp [2]= { '\0', '\0' }; char chChar; if (isIn->eof()) return NULL; bool boolString = false; bool boolOverload = false; bool boolDiscartComment = false; while (isIn->good()) { chChar = isIn->get(); stzTemp [0] = chChar; //securely stringfing chChar... NOTRACE "boolString: [" << boolString << "], " << chChar << "(" << static_cast<int>(chChar) << ") tp: " << nType << " : String: [" << strData << "]" << " EOF: " << isIn->eof () << endl; if (boolDiscartComment == true) { if (chChar == '\n') { boolDiscartComment = false; isIn->putback(chChar); } NOTRACE << chChar; } else if (nType != string_quote_tag && chChar == '#') { boolDiscartComment = true; NOTRACE << "Starting Discarting..." << endl; } else if (nType == none_tag) { if (chChar == '[') { nType = open_session_tag; boolString = true; } else if (chChar == '{') { strData = "{"; iniParserItem.assign (open_struct_tag, strData); return &iniParserItem; } else if (chChar == '}') { strData = "}"; iniParserItem.assign (close_struct_tag, strData); return &iniParserItem; } else if (chChar == '=') { nType = attributive_tag; strData = "="; iniParserItem.assign (attributive_tag, strData); return &iniParserItem; } else if (isAlphaData(chChar) == true) { if (chChar == '"') nType = string_quote_tag; else nType = string_tag; isIn->putback(chChar); boolString = true; } } else if (nType == attributive_tag) { if (chChar == '"') { nType = string_quote_tag; boolString = true; } else if (isgraph (chChar) != 0) { nType = string_line_tag; isIn->putback(chChar); boolString = true; } } else if (nType == string_tag && (! isAlphaData (chChar))) { nType = none_tag; iniParserItem.assign (string_tag, strData); return &iniParserItem; } else if (nType == string_quote_tag && boolOverload == false && Util::isBetween(chChar, "\"\\", 2)) { if(chChar == '\\') { boolOverload = true; continue; } else if (chChar == '"') { nType = none_tag; iniParserItem.assign (string_tag, strData); return &iniParserItem; } } else if (nType == string_line_tag && chChar == '\n') { nType = none_tag; Util::trim(strData); iniParserItem.assign (string_tag, strData); return &iniParserItem; } else if (nType == open_session_tag && chChar == ']') { nType = none_tag; iniParserItem.assign (session_tag, strData); return &iniParserItem; } else if (boolString == true) { if (nType == string_quote_tag || chChar == '\t' || chChar >= ' ') strData += chChar; boolOverload = false; } } if (nType == string_line_tag && strData.length() > 0) { iniParserItem.assign (string_tag, strData); return &iniParserItem; } nType = none_tag; return NULL; } /* * Check if exists any inipath; */ bool iniplus::Exists (const string strINIPath) { return mapIniData.find(Util::strToUpper (strINIPath)) != mapIniData.end() ? true : false; } /* * Conversion types lookup functions functions */ void iniplus::getStringFromRef (string& strRet, const string strINIPath) { strRet = getRawString(strINIPath); } /* getRawString This funciton will return the same data available at the INI without interpreting any value at all.... */ string iniplus::getRawString (const string strINIPath) { map<string,string>::iterator mapPos; string strValue = strINIPath; mapPos = mapIniData.find( Util::strToUpper(strValue).c_str()); NOTRACE << "Looking for: [" << Util::strToUpper(strValue) << "]" << endl << endl; Verify (mapPos != mapIniData.end(), "Error, element (" + Util::strToUpper(strValue) + ") was not found.", EXCEPT_INI_NO_INIPATH_FOUND, iniplusException); return mapPos->second; } int iniplus::getInteger (const string strINIPath) { return std::stoi (((const string) getRawString (strINIPath)), nullptr, 0); } /* * The Long and Long Long conversion hereby implemented * are capable of selecting from decimal and hexadecimal automatically * and extra is supplied for binary only conversion. I know one can argue * the auto select could be implemented for binary too, but it could pose * an extra layer of processing, losing precious time that could be, otherwise, * used for processing, thus, I decided against it. */ long iniplus::getLong (const string strINIPath) { return std::stol ((const string)getRawString (strINIPath), nullptr, 0); } long long iniplus::getLongLong (const string strINIPath) { return std::stoll (getRawString (strINIPath).c_str(), nullptr, 0); } long long iniplus::getULongLongFromBinary (const string strINIPath) { return std::stoll (getRawString (strINIPath).c_str(), nullptr, 2); } long iniplus::getULong (const string strINIPath) { return std::stoul (getRawString (strINIPath).c_str()); } long long iniplus::getULongLong (const string strINIPath) { return std::stoull (getRawString (strINIPath).c_str()); } float iniplus::getfloat (const string strINIPath) { return std::stof (getRawString (strINIPath).c_str()); } double iniplus::getDouble (const string strINIPath) { return std::stof (getRawString (strINIPath).c_str()); } /* getString This is by far the most advanced capability from this lib, since it can interpret 3 levels of information, replacing any ${look_up_date}, for one found on the 3 level of looking up data. The looking up priority is as followed: Dynamic: 1. pVarMap, by default it is null, but once providade, it can overide a INI path while it is in use by the getString, no data will EVER change the in memory data stored. Statics: 2. The in memory iniPath data stored, provided by the INI read itself. 3. the Environment variables, is the lower orther and can be overide by both iniPath and pVarMap. */ std::string iniplus::getString(string strINIPath, map<std::string, std::string> *pVarMap) { string strValueof = getRawString(strINIPath); string strVariableName; string strReplace; size_t nStart, nStop; while ((nStart= strValueof.find("${", 0)) != string::npos) { NOTRACE << endl << endl << "Value: [" << strValueof << "]" << endl; if ((nStop = strValueof.find("}", 0)) != string::npos) { strVariableName = strValueof.substr (nStart+2, (nStop - nStart) - 2); strReplace = ""; if (pVarMap != nullptr && pVarMap->find(strVariableName) != pVarMap->end()) { strReplace = (*pVarMap)[strVariableName]; } else if (Exists(strVariableName.c_str())) { strReplace = getRawString(strVariableName.c_str()); } else if (getenv(strVariableName.c_str()) != nullptr) { strReplace = getenv(strVariableName.c_str()); } NOTRACE << "Found nStart: (" << nStart << "), nStop: (" << nStop << "), Variable: [" << strVariableName << "]" << endl; strValueof.replace(nStart, (nStop-nStart)+1, strReplace); } else { strValueof.replace(nStart, 2, "--ERROR-->"); } NOTRACE << "--------------------------" << endl << strValueof << endl << "---------------------------" << endl; } NOTRACE "String: [" << strValueof << "]" << endl; return strValueof; } //protocolo correios 2931802247702
28.553648
217
0.517962
solariun
46d15d6488e2a31fce4678f759a447b7719b4679
3,621
cpp
C++
src/graph.cpp
Liu-Cheng/graph_accelerator
38e33215a73611dd8d0a8d8231a89aad185bea33
[ "MIT" ]
9
2017-11-03T09:12:25.000Z
2021-08-05T08:51:12.000Z
src/graph.cpp
Liu-Cheng/graph_accelerator
38e33215a73611dd8d0a8d8231a89aad185bea33
[ "MIT" ]
1
2019-12-16T02:55:09.000Z
2020-03-23T08:01:10.000Z
src/graph.cpp
Liu-Cheng/graph_accelerator
38e33215a73611dd8d0a8d8231a89aad185bea33
[ "MIT" ]
2
2019-04-09T02:23:35.000Z
2019-12-10T02:18:47.000Z
#include "graph.h" void Graph::loadFile( const std::string& fname, std::vector<std::vector<int>> &data ){ std::ifstream fhandle(fname.c_str()); if(!fhandle.is_open()){ HERE; std::cout << "Failed to open " << fname << std::endl; exit(EXIT_FAILURE); } std::string line; while(std::getline(fhandle, line)){ std::istringstream iss(line); data.push_back( std::vector<int>(std::istream_iterator<int>(iss), std::istream_iterator<int>()) ); } fhandle.close(); } // Check the number of vertices without out going neighbors, // as it affects the BFS results. void Graph::getStat(){ int zero_outgoing_vertex_num = 0; for(auto it = vertices.begin(); it != vertices.end(); it++){ if((*it)->out_vids.empty()){ zero_outgoing_vertex_num++; } } std::cout << "Zero outgoing vertex percentage is " << zero_outgoing_vertex_num * 1.0 / vertex_num << std::endl; } int Graph::getMaxIdx(const std::vector<std::vector<int>> &data){ int max_idx = data[0][0]; for(auto it1 = data.begin(); it1 != data.end(); it1++){ for(auto it2 = it1->begin(); it2 != it1->end(); it2++){ if(max_idx <= (*it2)){ max_idx = *it2; } } } return max_idx; } int Graph::getMinIdx(const std::vector<std::vector<int>> &data){ int min_idx = data[0][0]; for(auto it1 = data.begin(); it1 != data.end(); it1++){ for(auto it2 = it1->begin(); it2 != it1->end(); it2++){ if(min_idx >= (*it2)){ min_idx = *it2; } } } return min_idx; } void Graph::getRandomStartIndices(std::vector<int> &start_indices){ start_indices.clear(); int n = 0; while(n < GL::startNum){ int max_idx = vertex_num - 1; int idx = rand()%max_idx; if(vertices[idx]->out_vids.empty() || std::find(start_indices.begin(), start_indices.end(), idx) != start_indices.end()){ continue; } start_indices.push_back(idx); n++; } } void Graph::printOngb(int vidx){ std::cout << vidx << " outgoing neighbors: "; for(auto x : vertices[vidx]->out_vids){ std::cout << x << " "; } std::cout << std::endl; } Graph::Graph(const std::string& fname){ // Check if it is undirectional graph auto found = fname.find("ungraph", 0); if(found != std::string::npos) isUgraph = true; else isUgraph = false; std::vector<std::vector<int>> data; loadFile(fname, data); vertex_num = getMaxIdx(data) + 1; edge_num = (int)data.size(); if(isUgraph) edge_num *= 2; if(GL::logon != 0){ std::cout << "vertex num: " << vertex_num << std::endl; std::cout << "edge num: " << edge_num << std::endl; } for(int i = 0; i < vertex_num; i++){ Vertex* v = new Vertex(i); vertices.push_back(v); } for(auto it = data.begin(); it != data.end(); it++){ int src_idx = (*it)[0]; int dst_idx = (*it)[1]; vertices[src_idx]->out_vids.push_back(dst_idx); vertices[dst_idx]->in_vids.push_back(src_idx); if(isUgraph && src_idx != dst_idx){ vertices[dst_idx]->out_vids.push_back(src_idx); vertices[src_idx]->in_vids.push_back(dst_idx); } } for(auto it = vertices.begin(); it != vertices.end(); it++){ (*it)->in_deg = (int)(*it)->in_vids.size(); (*it)->out_deg = (int)(*it)->out_vids.size(); } }
28.968
129
0.537973
Liu-Cheng
46d18ae5c9c0cde575ff2ca65ae4553321d6b397
769
cpp
C++
src/SumaKontrolnaPliku.cpp
klusekrules/tools
f740c073298b1477a2260cdb5425899ea0d7e102
[ "MIT" ]
null
null
null
src/SumaKontrolnaPliku.cpp
klusekrules/tools
f740c073298b1477a2260cdb5425899ea0d7e102
[ "MIT" ]
null
null
null
src/SumaKontrolnaPliku.cpp
klusekrules/tools
f740c073298b1477a2260cdb5425899ea0d7e102
[ "MIT" ]
null
null
null
#include "SumaKontrolnaPliku.h" #include "Logger\Logger.h" #include "krypto\Hex.h" #pragma warning( disable : 4996 ) namespace SpEx{ const std::string SumaKontrolnaPliku::NazwaTypu_ = "sha3"; SumaKontrolnaPliku::SumaKontrolnaPliku(const std::string& plik) : Zasob(plik), fp_(fopen(plik.c_str(), "rb")), sumaKontrolna_(fp_) { if(fp_ != nullptr) fclose(fp_); fp_ = nullptr; } bool SumaKontrolnaPliku::inicjalizuj(){ return true; } std::string SumaKontrolnaPliku::napis() const{ SLog::Logger log(NAZWAKLASY(SumaKontrolnaPliku)); log.dodajPole(NAZWAPOLA(plik_), "std::string", pobierzAdresPliku()); log.dodajPole(NAZWAPOLA(sumaKontrolna_), NAZWAKLASY2(sumaKontrolna_), sumaKontrolna_.pobierzNapis<Hex>()); return std::move(log.napis()); } }
28.481481
108
0.726918
klusekrules
46d66d0c3cd7aff8f33778c7e8381fb5a6274e52
4,270
cpp
C++
control/unsupported/servos_mix_birotor.cpp
jlecoeur/MAVRIC_Library
56281851da7541d5c1199490a8621d7f18482be1
[ "BSD-3-Clause" ]
12
2016-07-12T10:26:47.000Z
2021-12-14T10:03:11.000Z
control/unsupported/servos_mix_birotor.cpp
jlecoeur/MAVRIC_Library
56281851da7541d5c1199490a8621d7f18482be1
[ "BSD-3-Clause" ]
183
2015-01-22T12:35:18.000Z
2017-06-09T10:11:26.000Z
control/unsupported/servos_mix_birotor.cpp
jlecoeur/MAVRIC_Library
56281851da7541d5c1199490a8621d7f18482be1
[ "BSD-3-Clause" ]
25
2015-02-03T15:15:48.000Z
2021-12-14T08:55:04.000Z
/******************************************************************************* * Copyright (c) 2009-2016, MAV'RIC Development Team * 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. ******************************************************************************/ /******************************************************************************* * \file torque_controller_birotor.cpp * * \author MAV'RIC Team * \author Julien Lecoeur * \author Basil Huber * * \brief Links between torque commands and servos PWM command for birotoers * ******************************************************************************/ #include "control/servos_mix_birotor.hpp" Servos_mix_birotor::Servos_mix_birotor(args_t& args, const conf_t& config) : motor_left_dir_(config.motor_left_dir), motor_right_dir_(config.motor_right_dir), servo_left_dir_(config.servo_left_dir), servo_right_dir_(config.servo_right_dir), min_servo_(config.min_servo), max_servo_(config.max_servo), min_thrust_(config.min_thrust), max_thrust_(config.max_thrust), motor_left_(args.motor_left), motor_right_(args.motor_right), servo_left_(args.servo_left), servo_right_(args.servo_right), dc_motors_(args.dc_motors) { } void Servos_mix_birotor::update() { float motor[4]; // torque_command->xyz[0] ==== ROLL // torque_command->xyz[1] ==== PITCH // torque_command->xyz[2] ==== YAW // Motor left motor[0] = torq_command_.thrust + (+ torq_command_.torq[2]); // Motor right motor[1] = torq_command_.thrust + (- torq_command_.torq[2]); // Servo left motor[2] = mix->servo_left_dir * (+ torq_command_.torq[0] + torq_command_.torq[1]); // Servo right motor[3] = mix->servo_right_dir * (- torq_command_.torq[0] + torq_command_.torq[1]); // Clip values /*for (i=0; i<2; i++) { if ( motor[i] < min_thrust_ ) { motor[i] = min_thrust_; } else if ( motor[i] > max_thrust_ ) { motor[i] = max_thrust_; } } int i=0; for (i=2; i<4; i++) { if ( motor[i] < min_servo_ ) { motor[i] = min_servo_; } else if ( motor[i] > max_servo_ ) { motor[i] = max_servo_; } } */ motor_left.write(motor[0]); motor_right.write(motor[1]); servo_left.write(motor[2]); servo_right.write(motor[3]); dc_motors.wingrons_angle[0] = motor[2]; dc_motors.wingrons_angle[1] = motor[3]; return true; }
33.100775
81
0.591803
jlecoeur
46d8b053a15f65ff4d94f53e47729ec6a68e7b37
4,135
cpp
C++
tst_gjsonlocalserver.cpp
echowalways/GJsonLocalServer
b70a68334ec564cee29177acdedf88e8096d6517
[ "BSD-3-Clause" ]
null
null
null
tst_gjsonlocalserver.cpp
echowalways/GJsonLocalServer
b70a68334ec564cee29177acdedf88e8096d6517
[ "BSD-3-Clause" ]
null
null
null
tst_gjsonlocalserver.cpp
echowalways/GJsonLocalServer
b70a68334ec564cee29177acdedf88e8096d6517
[ "BSD-3-Clause" ]
1
2018-09-15T00:16:00.000Z
2018-09-15T00:16:00.000Z
#include <QtCore> #include <QtTest> #include <GJsonAccessManager> #include <GJsonRequest> #include <GJsonResponse> #include <GEchoLocalServer> class GJsonLocalServerTest : public QObject { Q_OBJECT public: GJsonLocalServerTest(); private Q_SLOTS: void testRequestLoop(); }; GJsonLocalServerTest::GJsonLocalServerTest() { } void GJsonLocalServerTest::testRequestLoop() { GEchoLocalServer localServer; localServer.listen(QLatin1Literal("com.localServer.echoLocalServer"), QLatin1Literal("/com/localServer/echo")); GJsonAccessManager accessManager; // 测试全内容. qDebug() << "测试全内容"; do { GJsonRequest req(QLatin1Literal("com.localServer.echoLocalServer"), QLatin1Literal("/com/localServer/echo"), QLatin1Literal("com.localServer.echoLocalServer.interface"), QLatin1Literal("echo"), QLatin1Literal("Hello.")); GJsonResponse resp = accessManager.call(req); QVERIFY(!resp.isError()); QVERIFY(resp.statusCode() == GJsonResponse::Ok); qDebug() << resp.request().value().toString() << resp.value().toString(); } while (false); // 测试不带值. qDebug() << "测试不带值"; do { GJsonRequest req(QLatin1Literal("com.localServer.echoLocalServer"), QLatin1Literal("/com/localServer/echo"), QLatin1Literal("com.localServer.echoLocalServer.interface"), QLatin1Literal("echo")); GJsonResponse resp = accessManager.call(req); QVERIFY(!resp.isError()); QVERIFY(resp.statusCode() == GJsonResponse::Ok); qDebug() << resp.value().toString(); } while (false); // 测试不设置方法名. qDebug() << "测试不设置方法名"; do { GJsonRequest req(QLatin1Literal("com.localServer.echoLocalServer"), QLatin1Literal("/com/localServer/echo"), QLatin1Literal("com.localServer.echoLocalServer.interface")); GJsonResponse resp = accessManager.call(req); QVERIFY(!resp.isError()); QVERIFY(resp.statusCode() == GJsonResponse::BadRequest); } while (false); // 测试设置无意义方法名. qDebug() << "测试设置无意义方法名"; do { GJsonRequest req(QLatin1Literal("com.localServer.echoLocalServer"), QLatin1Literal("/com/localServer/echo"), QLatin1Literal("com.localServer.echoLocalServer.interface"), QLatin1Literal("unknownMethod")); GJsonResponse resp = accessManager.call(req); QVERIFY(!resp.isError()); QVERIFY(resp.statusCode() == GJsonResponse::NotImplemented); } while (false); // 测试不指定服务. qDebug() << "测试不指定服务"; do { GJsonRequest req(QString(), QLatin1Literal("/com/localServer/echo"), QLatin1Literal("com.localServer.echoLocalServer.interface"), QLatin1Literal("echo"), QLatin1Literal("Hello.")); GJsonResponse resp = accessManager.call(req); QVERIFY(resp.isError()); } while (false); // 测试不指定路径. qDebug() << "测试不指定路径"; do { GJsonRequest req(QLatin1Literal("com.localServer.echoLocalServer"), QString(), QLatin1Literal("com.localServer.echoLocalServer.interface"), QLatin1Literal("echo"), QLatin1Literal("Hello.")); GJsonResponse resp = accessManager.call(req); QVERIFY(resp.isError()); } while (false); // 测试不指定接口. qDebug() << "测试不指定接口"; do { GJsonRequest req(QLatin1Literal("com.localServer.echoLocalServer"), QLatin1Literal("/com/localServer/echo"), QString(), QLatin1Literal("echo"), QLatin1Literal("Hello.")); GJsonResponse resp = accessManager.call(req); QVERIFY(!resp.isError()); qDebug() << resp.value().toString(); } while (false); } QTEST_GUILESS_MAIN(GJsonLocalServerTest) #include "tst_gjsonlocalservertest.moc"
32.559055
86
0.596372
echowalways
46de71bc836c78a5eb8d481ff0eddef7efc288c8
1,506
cpp
C++
source/String/UUID.cpp
Fabrice-Praxinos/ULIS
232ad5c0804da1202d8231fda67ff4aea70f57ef
[ "RSA-MD" ]
30
2020-09-16T17:39:36.000Z
2022-02-17T08:32:53.000Z
source/String/UUID.cpp
Fabrice-Praxinos/ULIS
232ad5c0804da1202d8231fda67ff4aea70f57ef
[ "RSA-MD" ]
7
2020-11-23T14:37:15.000Z
2022-01-17T11:35:32.000Z
source/String/UUID.cpp
Fabrice-Praxinos/ULIS
232ad5c0804da1202d8231fda67ff4aea70f57ef
[ "RSA-MD" ]
5
2020-09-17T00:39:14.000Z
2021-08-30T16:14:07.000Z
// IDDN FR.001.250001.004.S.X.2019.000.00000 // ULIS is subject to copyright laws and is the legal and intellectual property of Praxinos,Inc /* * ULIS *__________________ * @file UUID.cpp * @author Clement Berthaud * @brief This file provides definition for weak UUID functions. * @copyright Copyright 2018-2021 Praxinos, Inc. All Rights Reserved. * @license Please refer to LICENSE.md */ #include "String/UUID.h" #include <iostream> #include <sstream> #include <random> ULIS_NAMESPACE_BEGIN ///////////////////////////////////////////////////// // Weak UUID //-------------------------------------------------------------------------------------- //---------------------------------------------------------- Private Unit Implementation unsigned char random_char() { return static_cast< unsigned char >( rand() % 256 ); } std::string generate_hex( const unsigned int len ) { std::stringstream ss; for( unsigned int i = 0; i < len; i++) { auto rc = random_char(); std::stringstream hexstream; hexstream << std::hex << int( rc ); auto hex = hexstream.str(); ss << ( hex.length() < 2 ? '0' + hex : hex ); } return ss.str(); } //-------------------------------------------------------------------------------------- //---------------------------------------------------------------- Public Implementation std::string GenerateWeakUUID( uint8 len ) { return generate_hex( len ); } ULIS_NAMESPACE_END
30.12
95
0.497344
Fabrice-Praxinos
46e1c22be7d562c925f12b4281503e3c2920048e
1,001
cpp
C++
leetcode/tests/LinkedList.cpp
longztian/cpp
59203f41162f40a46badf69093d287250e5cbab6
[ "MIT" ]
null
null
null
leetcode/tests/LinkedList.cpp
longztian/cpp
59203f41162f40a46badf69093d287250e5cbab6
[ "MIT" ]
null
null
null
leetcode/tests/LinkedList.cpp
longztian/cpp
59203f41162f40a46badf69093d287250e5cbab6
[ "MIT" ]
null
null
null
#include "LinkedList.hpp" namespace LinkedList { Node::Node(int d) : val(d), next(nullptr) {} bool Node::operator ==(const Node& rhs) const { if (this == &rhs) return true; bool isEqual = val == rhs.val; if (isEqual) { isEqual = equal(next, rhs.next); } return isEqual; } bool equal(const Node* list1, const Node* list2) { if (list1 == nullptr && list2 == nullptr) return true; if (list1 == nullptr || list2 == nullptr) return false; return *list1 == *list2; } Node* create(std::initializer_list<int> il) { Node* head(nullptr); auto node = head; for (auto i = il.begin(); i != il.end(); ++i) { if (node) { node->next = new Node(*i); node = node->next; } else { head = new Node(*i); node = head; } } return head; } std::vector<int> toVector(const Node* head) { std::vector<int> ret; auto node = head; while (node) { ret.push_back(node->val); node = node->next; } return ret; } } // namespace LinkedList
18.2
57
0.587413
longztian
46efaccabbc653ff1d81e2ec250efb24719fc2b2
4,357
cpp
C++
__unit_tests/gv_framework_unit_test/first_online_game_2d_bricks.cpp
dragonsn/gv_game_engine
dca6c1fb1f8d96e9a244f157a63f8a69da084b0f
[ "MIT" ]
2
2018-12-03T13:17:31.000Z
2020-04-08T07:00:02.000Z
__unit_tests/gv_framework_unit_test/first_online_game_2d_bricks.cpp
dragonsn/gv_game_engine
dca6c1fb1f8d96e9a244f157a63f8a69da084b0f
[ "MIT" ]
null
null
null
__unit_tests/gv_framework_unit_test/first_online_game_2d_bricks.cpp
dragonsn/gv_game_engine
dca6c1fb1f8d96e9a244f157a63f8a69da084b0f
[ "MIT" ]
null
null
null
#include "stdafx.h" using namespace gv; namespace game_2d_bricks { #include "2d_bricks_maps.h" #include "2d_bricks_online.h" //====================================================================== class gv_game_2d_bricks:public gv_unit_test_with_renderer { public: virtual gv_string name() { return "game_2d_bricks"; } map m_map; gv_uint m_max_frame; gv_double m_last_tick_time; gv_double m_delta_time; gv_uint m_tick_count; actor* m_main_actor; bool m_is_drag; gv_double m_start_drag_time; gv_vector2i m_start_drag_pos; bool m_pause; gv_game_2d_bricks() {} virtual void initialize() { if(gv_global::command_line_options.size() ) { gv_global::command_line_options[0]>>m_max_frame; } else m_max_frame=1000; m_last_tick_time=gv_global::time->get_sec_from_start(); m_delta_time=0; m_map.init(the_map,map_width,map_height); m_map.spawn_actors(2000); //m_map.init(the_map2,map_width2,map_height2); //m_map.spawn_actors(10); m_main_actor=NULL; m_is_drag=false; m_tick_count=0; m_pause=false; }; bool update_map_view_mode( float dt) { gv_string_tmp title="MAP VIEW MODE ====>>"; gv_global::debug_draw.get()->draw_string(*title,gv_vector2i(60,120),gv_color::RED()); float step=200.0f*dt; if (gv_global::input->is_key_down(e_key_up) ) { m_map.m_camera_pos.y-=step; } if (gv_global::input->is_key_down(e_key_down) ) { m_map.m_camera_pos.y+=step; } if (gv_global::input->is_key_down(e_key_left)) { m_map.m_camera_pos.x-=step; } if (gv_global::input->is_key_down(e_key_right)) { m_map.m_camera_pos.x+=step; } return true; } bool update_play_ball_view_mode( float dt) { { bool down= gv_global::input->is_key_down(e_key_lbutton); if(m_is_drag && !down) { gv_global::debug_draw->release_mouse(); gv_double time=gv_global::time->get_sec_from_start(); time-=m_start_drag_time; gv_vector2i cu_mouse_pos; gv_global::input->get_mouse_pos(cu_mouse_pos); cu_mouse_pos-=m_start_drag_pos; m_main_actor->m_speed.x+=(gv_float)(cu_mouse_pos.x*0.5f)/(gv_float)time; m_main_actor->m_speed.y+=(gv_float)(cu_mouse_pos.y*0.5f)/(gv_float)time; m_main_actor->m_speed.x=gvt_clamp(m_main_actor->m_speed.x, -100.f, 100.f); m_main_actor->m_speed.y=gvt_clamp(m_main_actor->m_speed.y, -100.f, 100.f); } if (down && !m_is_drag ) { gv_global::debug_draw->capture_mouse(); m_start_drag_time=gv_global::time->get_sec_from_start(); gv_global::input->get_mouse_pos(m_start_drag_pos); } m_is_drag=down; } return true; } virtual void render() { GV_PROFILE_EVENT(render_all,0 ); gv_double cu=gv_global::time->get_sec_from_start(); m_delta_time=gvt_clamp ( cu-m_last_tick_time, 0.01, 0.1); m_last_tick_time=cu; int cell_drawed=0; gv_string_tmp s="[BRICK2D]>>"; s<< "fps: "<<1.0/m_delta_time; if (!m_pause) {//UPDATE GV_PROFILE_EVENT(m_map_update,0 ); //update_map_view_mode((gv_float) m_delta_time); update_play_ball_view_mode((gv_float) m_delta_time); m_map.update((gv_float) m_delta_time); //m_map.update(0.03f); } {//RENDER GV_PROFILE_EVENT(m_map_render,0 ); if (!m_main_actor) m_main_actor=*m_map.m_actor_list.begin(); if (m_main_actor) { m_map.m_camera_pos=m_main_actor->m_location; m_map.m_camera_zoom=2; gv_string_tmp title="GAME SCORE:"; title<<m_main_actor->m_score; gv_global::debug_draw.get()->draw_string(*title,gv_vector2i(60,120),gv_color::RED()); } cell_drawed=m_map.render(); } s<<" cell in view "<<cell_drawed; gv_global::debug_draw.get()->draw_string(*s,gv_vector2i(60,60),gv_color::RED()); if (gv_global::input->is_key_down(e_key_return)) { m_tick_count=m_max_frame; } static bool bool_is_space_down=false; if (gv_global::input->is_key_down(e_key_space) && !bool_is_space_down) { m_pause=!m_pause; } bool_is_space_down=gv_global::input->is_key_down(e_key_space); m_tick_count++; }; virtual bool is_finished () { if (m_tick_count<m_max_frame) return false; return true; } virtual void destroy() { m_map.destroy(); } }test; gv_unit_test_with_renderer* ptest=&test; }; #include "2d_bricks_online.hpp"
27.23125
90
0.677071
dragonsn
2000343dff49bb55190db0282ef7a2893c1ad331
916
cpp
C++
18.05/lamaba1.cpp
dengxianglong/cplusplusprimerplusstudy
eefc5d7bf5ab31186c04171fadade3552838f4b2
[ "MIT" ]
null
null
null
18.05/lamaba1.cpp
dengxianglong/cplusplusprimerplusstudy
eefc5d7bf5ab31186c04171fadade3552838f4b2
[ "MIT" ]
null
null
null
18.05/lamaba1.cpp
dengxianglong/cplusplusprimerplusstudy
eefc5d7bf5ab31186c04171fadade3552838f4b2
[ "MIT" ]
1
2018-08-29T07:40:20.000Z
2018-08-29T07:40:20.000Z
#include <iostream> #include <vector> #include <algorithm> #include <cmath> #include <ctime> const long Size = 390000L; int main() { using namespace std; vector<int> numbers (Size); srand(time(0)); std::generate(numbers.begin(), numbers.end(), std::rand); cout << "Sample size = " << Size << '\n'; int count3 = std::count_if(numbers.begin(), numbers.end(), [](int x){return x % 3 == 0;}); cout << "Count of number divisible by 3 : " << count3 << '\n'; int count13 = 0; std::for_each(numbers.begin(), numbers.end(), [&count13](int x) {count13 += x % 13 == 0;}); cout << "Count of numbers divisible by 13: " << count13 << '\n'; count3 = count13 = 0; std::for_each(numbers.begin(), numbers.end(), [&](int x){count3 += x % 3 == 0; count13 += x % 13 == 0;}); cout << "Count of number divisible by 3 : " << count3 << '\n'; cout << "Count of number divisible by 13 : " << count13 << '\n'; return 0; }
31.586207
65
0.599345
dengxianglong
20099382fe55b82a5165036e4edd885ba94bd679
372
cpp
C++
sprint00/t02/walletManager.cpp
Hvvang/CppTrack
3e1854d626d153f5597459200f715a91f6a03107
[ "MIT" ]
1
2020-08-27T23:41:48.000Z
2020-08-27T23:41:48.000Z
sprint00/t02/walletManager.cpp
Hvvang/CppTrack
3e1854d626d153f5597459200f715a91f6a03107
[ "MIT" ]
null
null
null
sprint00/t02/walletManager.cpp
Hvvang/CppTrack
3e1854d626d153f5597459200f715a91f6a03107
[ "MIT" ]
null
null
null
#include "walletManager.h" Wallet* createWallet(const int& septs) { Wallet* wallet = new Wallet; wallet->septims = septs; return wallet; } void destroyWallet(Wallet* wallet) { delete wallet; } Wallet* createWallets(const int& amount) { Wallet* wallets = new Wallet[amount]; return wallets; } void destroyWallets(Wallet* wallets) { delete [] wallets; }
16.173913
42
0.704301
Hvvang
200a35ba4197520bce5fbe6495031fc667186ff9
633
cpp
C++
sma_backtester/src/utility.cpp
ayan11-11/console_based_sma_backtester
a0fccec0251eed9507f4aaa262037148d3f2c6c7
[ "MIT" ]
null
null
null
sma_backtester/src/utility.cpp
ayan11-11/console_based_sma_backtester
a0fccec0251eed9507f4aaa262037148d3f2c6c7
[ "MIT" ]
null
null
null
sma_backtester/src/utility.cpp
ayan11-11/console_based_sma_backtester
a0fccec0251eed9507f4aaa262037148d3f2c6c7
[ "MIT" ]
null
null
null
#include "utility.hpp" //Find epoch time from normal DD-MM-YYYY long int get_epoch_time(string date) { struct tm t = {0}; time_t timeSinceEpoch; istringstream ss(date); if(ss >> get_time(&t, "%d-%m-%Y")) { timeSinceEpoch = mktime(&t); } // cout << "timeSinceEpoch: " << timeSinceEpoch << endl;; return long(timeSinceEpoch); } //Find normal time DD-MM-YYYY from epoch time // Find normal time YYYY-MM-DD from epoch time string get_std_time(long int epochtime) { time_t t = epochtime; char string[80]; strftime(string, 80, "%d-%m-%Y", gmtime(&t)); return string; }
23.444444
61
0.624013
ayan11-11
200b0d2de487e3b239b54f5e1f5cddec919f136b
265
hpp
C++
external/luabinding/lua_wuziqi_manual.hpp
striver-ing/WuZiQi
0372cbbea0c8e8c02adc625eda5b745c0faad8f8
[ "MIT" ]
4
2020-06-09T17:05:41.000Z
2021-08-21T06:19:35.000Z
external/luabinding/lua_wuziqi_manual.hpp
striver-ing/WuZiQi
0372cbbea0c8e8c02adc625eda5b745c0faad8f8
[ "MIT" ]
null
null
null
external/luabinding/lua_wuziqi_manual.hpp
striver-ing/WuZiQi
0372cbbea0c8e8c02adc625eda5b745c0faad8f8
[ "MIT" ]
null
null
null
#include "base/ccConfig.h" #ifndef __wuziqi_manual_h__ #define __wuziqi_manual_h__ #ifdef __cplusplus extern "C" { #endif #include "tolua++.h" #ifdef __cplusplus } #endif extern int register_all_wuziqi_manual(lua_State* tolua_S); #endif // __wuziqi_manual__h__
16.5625
58
0.784906
striver-ing
200f4f5d30e42fbcb1b652fc64eaf52fa6ad00be
3,310
cpp
C++
tests/connection.cpp
amanda-wee/sqlitemm
2c38ea99c6a5864a0f1f03c472908fb893c8993f
[ "Apache-2.0" ]
null
null
null
tests/connection.cpp
amanda-wee/sqlitemm
2c38ea99c6a5864a0f1f03c472908fb893c8993f
[ "Apache-2.0" ]
null
null
null
tests/connection.cpp
amanda-wee/sqlitemm
2c38ea99c6a5864a0f1f03c472908fb893c8993f
[ "Apache-2.0" ]
null
null
null
/************************************************************************************************************ * SQLitemm tests source file primarily for testing sqlitemm::Connection * * Copyright 2020 Amanda Wee * * 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 "sqlitemm.hpp" #include "catch.hpp" TEST_CASE("in-memory database can be opened and closed") { SECTION("using an empty database connection") { sqlitemm::Connection conn; REQUIRE_NOTHROW(conn.open(":memory:")); REQUIRE_NOTHROW(conn.close()); } SECTION("using a constructor") { REQUIRE_NOTHROW([]() { sqlitemm::Connection conn(":memory:"); }()); } } TEST_CASE("extended result codes are enabled") { sqlitemm::Connection conn(":memory:"); REQUIRE_NOTHROW(conn.execute("CREATE TABLE person (id INTEGER PRIMARY KEY, name TEXT UNIQUE);" "INSERT INTO person (name) VALUES ('Alice');")); try { conn.execute("INSERT INTO person (name) VALUES ('Alice');"); REQUIRE(!"exception must be thrown"); } catch (const sqlitemm::Error& e) { REQUIRE(e.code() == SQLITE_CONSTRAINT_UNIQUE); } } TEST_CASE("changes") { sqlitemm::Connection conn(":memory:"); REQUIRE_NOTHROW(conn.execute("CREATE TABLE person (id INTEGER PRIMARY KEY, name TEXT);")); SECTION("no changes") { REQUIRE(conn.changes() == 0); } SECTION("insert one row") { conn.execute("INSERT INTO person (name) VALUES ('Alice');"); REQUIRE(conn.changes() == 1); } SECTION("insert three rows then delete two rows") { conn.execute("INSERT INTO person (name) VALUES ('Alice'), ('Bob'), ('Charlie');"); REQUIRE(conn.changes() == 3); conn.execute("DELETE FROM person WHERE name IN ('Alice', 'Bob');"); REQUIRE(conn.changes() == 2); } } TEST_CASE("execute") { SECTION("using valid SQL") { sqlitemm::Connection conn(":memory:"); REQUIRE_NOTHROW(conn.execute("SELECT DATE('2001-01-01');")); } SECTION("using invalid SQL") { sqlitemm::Connection conn(":memory:"); REQUIRE_THROWS(conn.execute("SELECT;")); } } TEST_CASE("last_insert_rowid") { sqlitemm::Connection conn(":memory:"); REQUIRE_NOTHROW(conn.execute("CREATE TABLE person (id INTEGER PRIMARY KEY, name TEXT UNIQUE);")); SECTION("no successful inserts") { REQUIRE(conn.last_insert_rowid() == 0); } SECTION("one successful insert") { conn.execute("INSERT INTO person (name) VALUES ('Alice');"); REQUIRE(conn.last_insert_rowid() == 1); } }
30.090909
110
0.584894
amanda-wee
2012e6eb460ba0f990ffba16824bda999a5b43b4
189
cpp
C++
SIMULATION.cpp
YecidMorenoUSP/ExoControl
d0c95690e23314ce3e4c0421e1de4167bfa752e2
[ "MIT" ]
null
null
null
SIMULATION.cpp
YecidMorenoUSP/ExoControl
d0c95690e23314ce3e4c0421e1de4167bfa752e2
[ "MIT" ]
null
null
null
SIMULATION.cpp
YecidMorenoUSP/ExoControl
d0c95690e23314ce3e4c0421e1de4167bfa752e2
[ "MIT" ]
null
null
null
#ifndef SIMULATION_H #include "SIMULATION.h" #endif namespace SIM{ void setLOG(std::string txt){ if(txt == "") GUI::LOG_MSG = ""; else GUI::LOG_MSG = txt; } };
18.9
40
0.566138
YecidMorenoUSP
20138d4df7498c45f6b3ab0a7926b05a04faae57
13,741
hpp
C++
Nstate.hpp
hostilefork/nocycle
71e48484ae6eef74ba92d72ed4f0d62bff5a7e4e
[ "BSL-1.0" ]
25
2015-01-01T03:38:28.000Z
2021-12-28T15:38:20.000Z
Nstate.hpp
hostilefork/nocycle
71e48484ae6eef74ba92d72ed4f0d62bff5a7e4e
[ "BSL-1.0" ]
1
2019-03-26T15:08:22.000Z
2019-04-07T11:06:28.000Z
Nstate.hpp
hostilefork/nocycle
71e48484ae6eef74ba92d72ed4f0d62bff5a7e4e
[ "BSL-1.0" ]
5
2017-09-05T02:09:25.000Z
2020-08-19T21:48:03.000Z
// // Nstate.hpp - Template for variable that can only take on values // from [0..radix-1], and an array type which is able to // store a series of these variables and take advantage of // the knowledge of the constraint in order to compact them // closer to their fundamentally minimal size. // // Copyright (c) 2009-2012 HostileFork.com // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://hostilefork.com/nstate for documentation. // #pragma once #include "NocycleConfig.hpp" #include <vector> #include <map> #include <exception> #include <cmath> // REVIEW: std::numeric_limits? #include <climits> #include <cassert> // // NSTATE // namespace nocycle { // see: http://www.cplusplus.com/doc/tutorial/exceptions.html class bad_nstate : public std::exception { virtual const char* what() const throw() { return "Invalid Nstate value"; } }; typedef unsigned PackedTypeForNstate; template<int radix> class Nstate { private: unsigned m_value; // ranges from [0..radix-1] private: void ThrowExceptionIfBadValue() { if (m_value >= radix) { bad_nstate bt; throw bt; } } public: // constructor is also implicit cast operator from unsigned // see: http://www.acm.org/crossroads/xrds3-1/ovp3-1.html Nstate(unsigned value) : m_value (value) { ThrowExceptionIfBadValue(); } // default constructor setting value to zero... good idea? Bad idea? Nstate() : m_value (0) { ThrowExceptionIfBadValue(); } // implicit cast operator to unsigned operator unsigned() const { return m_value; } // "A base class destructor should be either public and virtual, // or protected and nonvirtual." // http://www.gotw.ca/publications/mill18.htm public: virtual ~Nstate() { } #if NSTATE_SELFTEST public: static bool SelfTest(); // Class is self-testing for regression #endif }; class PowerTable { private: std::vector<unsigned> m_table; public: PowerTable (unsigned radix) { unsigned nstatesInUnsigned = static_cast<unsigned>(floor(log(2)/log(radix)*CHAR_BIT*sizeof(unsigned))); PackedTypeForNstate value = 1; for (unsigned index = 0; index < nstatesInUnsigned; index++) { m_table.push_back(value); value = value * radix; } } inline size_t NstatesInPackedType() const { return m_table.size(); } inline PackedTypeForNstate PowerForDigit(unsigned digit) const { assert(digit < m_table.size()); return m_table[digit]; } public: virtual ~PowerTable () { } }; // // NSTATE ARRAY // // TODO: // * iterators? // * 64-bit packing or something more clever? // * memory-mapped file implementation, with standardized packing/order // (to work across platforms)? template <int radix> class NstateArray { private: // Note: Typical library limits of the STL for vector lengths // are things like 1,073,741,823... std::vector<PackedTypeForNstate> m_buffer; size_t m_max; private: static const PowerTable& GetPowerTableInstance() { // We wish to cache the PowerTable so that all NstateArray instances of the same // radix share the same one. This is hard to do correctly and/or elegantly in // a way that is befitting a "general" class library. // http://stackoverflow.com/questions/9507973/how-to-mitigate-user-facing-api-effect-of-shared-members-in-templated-classes // The power tables are not that large, and in C++11 code this is guaranteed to static const PowerTable instance (radix); return instance; } static size_t NstatesInPackedType() { return GetPowerTableInstance().NstatesInPackedType(); } static PackedTypeForNstate PowerForDigit(unsigned digit) { return GetPowerTableInstance().PowerForDigit(digit); } private: Nstate<radix> GetDigitInPackedValue(PackedTypeForNstate packed, unsigned digit) const; PackedTypeForNstate SetDigitInPackedValue(PackedTypeForNstate packed, unsigned digit, Nstate<radix> t) const; public: // Derived from boost's dynamic_bitset // http://www.boost.org/doc/libs/1_36_0/libs/dynamic_bitset/dynamic_bitset.html class reference; friend class NstateArray<radix>::reference; class reference { friend class NstateArray<radix>; private: NstateArray<radix>& m_na; unsigned m_indexIntoBuffer; unsigned m_digit; reference(NstateArray<radix> &na, size_t indexIntoBuffer, unsigned digit) : m_na (na), m_indexIntoBuffer (indexIntoBuffer), m_digit (digit) { } void operator&(); // not defined void do_assign(Nstate<radix> x) { m_na.m_buffer[m_indexIntoBuffer] = m_na.SetDigitInPackedValue(m_na.m_buffer[m_indexIntoBuffer], m_digit, x); } public: // An automatically generated copy constructor. reference& operator=(Nstate<radix> x) { do_assign(x); return *this; } // for b[i] = x reference& operator=(const reference& rhs) { do_assign(rhs); return *this; } // for b[i] = b[j] operator Nstate<radix>() const { return m_na.GetDigitInPackedValue(m_na.m_buffer[m_indexIntoBuffer], m_digit); } operator unsigned() const { return m_na.GetDigitInPackedValue(m_na.m_buffer[m_indexIntoBuffer], m_digit); } }; reference operator[](size_t pos) { assert(pos < m_max); // STL will only check bounds on integer boundaries size_t indexIntoBuffer = pos / NstatesInPackedType(); unsigned digit = pos % NstatesInPackedType(); return reference (*this, indexIntoBuffer, digit); } Nstate<radix> operator[](size_t pos) const { assert(pos < m_max); // STL will only check bounds on integer boundaries. size_t indexIntoBuffer = pos / NstatesInPackedType(); unsigned digit = pos % NstatesInPackedType(); return GetDigitInPackedValue(m_buffer[indexIntoBuffer], digit); } // by convention, we resize and fill available space with zeros if expanding void ResizeWithZeros(size_t max) { size_t oldBufferSize = m_buffer.size(); size_t newBufferSize = max / NstatesInPackedType() + (max % NstatesInPackedType() == 0 ? 0 : 1); unsigned oldMaxDigitNeeded = m_max % NstatesInPackedType(); if ((oldMaxDigitNeeded == 0) && (m_max > 0)) oldMaxDigitNeeded = NstatesInPackedType(); unsigned newMaxDigitNeeded = max % NstatesInPackedType(); if ((newMaxDigitNeeded == 0) && (max > 0)) newMaxDigitNeeded = NstatesInPackedType(); m_buffer.resize(newBufferSize, 0 /* fill value */); m_max = max; if ((newBufferSize == oldBufferSize) && (newMaxDigitNeeded < oldMaxDigitNeeded)) { // If we did not change the size of the buffer but merely the number of // nstates we are fitting in the lastmost packed value, we must set // the trailing unused nstates to zero if we are using fewer nstates // than we were before for (auto eraseDigit = newMaxDigitNeeded; eraseDigit < oldMaxDigitNeeded; eraseDigit++) { m_buffer[newBufferSize - 1] = SetDigitInPackedValue(m_buffer[newBufferSize - 1], eraseDigit, 0); } } else if ((newBufferSize < oldBufferSize) && (newMaxDigitNeeded > 0)) { // If the number of tristates we are using isn't an even multiple of the // # of states that fit in a packed type, then shrinking will leave some // residual values we need to reset to zero in the last element of the vector. for (auto eraseDigit = newMaxDigitNeeded; eraseDigit < NstatesInPackedType(); eraseDigit++) { m_buffer[newBufferSize - 1] = SetDigitInPackedValue(m_buffer[newBufferSize - 1], eraseDigit, 0); } } } size_t Length() const { return m_max; } // Constructors and destructors public: NstateArray<radix>(const size_t initial_size) : m_max (0) { ResizeWithZeros(initial_size); } virtual ~NstateArray<radix> () { } #if NSTATE_SELFTEST public: static bool SelfTest(); // Class is self-testing for regression #endif }; // // Static member functions // template <int radix> Nstate<radix> NstateArray<radix>::GetDigitInPackedValue(PackedTypeForNstate packed, unsigned digit) const { // Generalized from Mark Bessey's post in the Joel on Software forum // http://discuss.joelonsoftware.com/default.asp?joel.3.205331.14 assert(digit < NstatesInPackedType()); // lop off unused top digits - you can skip this // for the most-significant digit PackedTypeForNstate value = packed; if (digit < (NstatesInPackedType()-1)) { value = value % PowerForDigit(digit+1); } // truncate lower digit value = value / PowerForDigit(digit); return value; } template <int radix> PackedTypeForNstate NstateArray<radix>::SetDigitInPackedValue(PackedTypeForNstate packed, unsigned digit, Nstate<radix> t) const { assert(digit < NstatesInPackedType()); PackedTypeForNstate powForDigit = PowerForDigit(digit); PackedTypeForNstate upperPart = 0; if (digit < (NstatesInPackedType() - 1)) { PackedTypeForNstate powForDigitPlusOne = PowerForDigit(digit + 1); upperPart = (packed / powForDigitPlusOne) * powForDigitPlusOne; } PackedTypeForNstate setPart = t * powForDigit; PackedTypeForNstate lowerPart = 0; if (digit > 0) lowerPart = packed % powForDigit; return upperPart + setPart + lowerPart; } } // temporary end of namespace nocycle #if NSTATE_SELFTEST // // CODE FOR SELF-TESTS // // See: http://gcc.gnu.org/ml/gcc-bugs/2000-12/msg00168.html // "If the definitions of member functions of a template aren't visible // when the template is instantiated, they won't be instantiated. You // must define template member functions in the header file itself, at // least until the `export' keyword is implemented." // #include <cstdlib> #include <iostream> namespace nocycle { template <int radix> bool Nstate<radix>::SelfTest() { for (unsigned test = 0; test < radix; test++) { Nstate<radix> t (test); if (t != test) { std::cout << "FAILURE: Nstates did not preserve values properly." << std::endl; return false; } } try { Nstate<radix> t3 (radix); std::cout << "FAILURE: Did not detect bad Nstate construction." << std::endl; return false; } catch (bad_nstate& e) { } try { Nstate<radix> tSet (0); tSet = radix; std::cout << "FAILURE: Did not detect bad Nstate SetValue." << std::endl; return false; } catch (bad_nstate& e) { } return true; } template <int radix> bool NstateArray<radix>::SelfTest() { // Basic allocation and set test for (size_t initialSize = 0; initialSize < 1024; initialSize++) { NstateArray<radix> nv (initialSize); std::vector<unsigned> v (initialSize); for (size_t index = 0; index < initialSize; index++) { Nstate<radix> tRand (rand() % radix); nv[index] = tRand; v[index] = tRand; } for (size_t index = 0; index < initialSize; index++) { if (nv[index] != v[index]) { std::cout << "FAILURE: On NstateArray[" << initialSize << "] for size " << initialSize << ", a value was recorded as " << static_cast<int>(nv[index]) << " when it should have been " << static_cast<int>(v[index]) << std::endl; return false; } } // Try resizing it to some smaller size size_t newSmallerSize; if (initialSize == 0) newSmallerSize = 0; else { newSmallerSize = (rand() % initialSize); nv.ResizeWithZeros(newSmallerSize); v.resize(newSmallerSize, 0); assert(nv.Length() == v.size()); for (size_t index = 0; index < newSmallerSize; index++) { if (nv[index] != v[index]) { std::cout << "FAILURE: On NstateArray[" << initialSize << "] after resize from " << initialSize << " to " << newSmallerSize << ", a value was recorded as " << static_cast<int>(nv[index]) << " when it should have been " << static_cast<int>(v[index]) << std::endl; return false; } } } // Try resizing it to some larger size size_t newLargerSize = newSmallerSize + (rand() % 128); nv.ResizeWithZeros(newLargerSize); v.resize(newLargerSize, 0); assert(nv.Length() == v.size()); for (size_t index = 0; index < newLargerSize; index++) { if (nv[index] != v[index]) { std::cout << "FAILURE: On NstateArray[" << initialSize << "] after resize from " << newSmallerSize << " to " << newLargerSize << ", a value was recorded as " << static_cast<int>(nv[index]) << " when it should have been " << static_cast<int>(v[index]) << std::endl; return false; } } } return true; } } // end namespace nocycle #endif
32.638955
131
0.623099
hostilefork
2018d8b1dbdefad2698827b0679e3e8a69d0c86f
15,001
cpp
C++
nImO/nImOlogical.cpp
opendragon/nImO
cf1ca52781bf03e82a5886dafc16ec39b1e29ba5
[ "BSD-3-Clause" ]
null
null
null
nImO/nImOlogical.cpp
opendragon/nImO
cf1ca52781bf03e82a5886dafc16ec39b1e29ba5
[ "BSD-3-Clause" ]
null
null
null
nImO/nImOlogical.cpp
opendragon/nImO
cf1ca52781bf03e82a5886dafc16ec39b1e29ba5
[ "BSD-3-Clause" ]
null
null
null
//-------------------------------------------------------------------------------------------------- // // File: nImO/nImOlogical.cpp // // Project: nImO // // Contains: The class definition for nImO logical values. // // Written by: Norman Jaffe // // Copyright: (c) 2016 by OpenDragon. // // All rights reserved. Redistribution and use in source and binary forms, with or // without modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright notice, this list // of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, this // list of conditions and the following disclaimer in the documentation and / or // other materials provided with the distribution. // * Neither the name of the copyright holders nor the names of its contributors may // be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT // SHALL THE COPYRIGHT 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. // // Created: 2016-03-21 // //-------------------------------------------------------------------------------------------------- #include "nImOlogical.hpp" #include <nImOarray.hpp> #include <nImOmessage.hpp> #include <nImOstringBuffer.hpp> //#include <odlEnable.h> #include <odlInclude.h> #if defined(__APPLE__) # pragma clang diagnostic push # pragma clang diagnostic ignored "-Wunknown-pragmas" # pragma clang diagnostic ignored "-Wdocumentation-unknown-command" #endif // defined(__APPLE__) /*! @file @brief The class definition for %nImO logical values. */ #if defined(__APPLE__) # pragma clang diagnostic pop #endif // defined(__APPLE__) #if defined(__APPLE__) # pragma mark Namespace references #endif // defined(__APPLE__) #if defined(__APPLE__) # pragma mark Private structures, constants and variables #endif // defined(__APPLE__) /*! @brief The standard textual representation of a @c false value. */ static const std::string kCanonicalFalse{"false"}; /*! @brief The standard textual representation of a @c true value. */ static const std::string kCanonicalTrue{"true"}; #if defined(__APPLE__) # pragma mark Global constants and variables #endif // defined(__APPLE__) #if defined(__APPLE__) # pragma mark Local functions #endif // defined(__APPLE__) #if defined(__APPLE__) # pragma mark Class methods #endif // defined(__APPLE__) #if defined(__APPLE__) # pragma mark Constructors and Destructors #endif // defined(__APPLE__) nImO::Logical::Logical (void) : inherited(), _value(false) { ODL_ENTER(); //#### ODL_EXIT_P(this); //#### } // nImO::Logical::Logical nImO::Logical::Logical (const bool initialValue) : inherited(), _value(initialValue) { ODL_ENTER(); //#### ODL_B1("initialValue = ", initialValue); //#### ODL_EXIT_P(this); //#### } // nImO::Logical::Logical nImO::Logical::Logical (const nImO::Logical & other) : inherited(), _value(other._value) { ODL_ENTER(); //#### ODL_P1("other = ", &other); //#### ODL_EXIT_P(this); //#### } // nImO::Logical::Logical nImO::Logical::~Logical (void) { ODL_OBJENTER(); //#### ODL_OBJEXIT(); //#### } // nImO::Logical::~Logical #if defined(__APPLE__) # pragma mark Actions and Accessors #endif // defined(__APPLE__) const nImO::Logical * nImO::Logical::asLogical (void) const { ODL_OBJENTER(); //#### ODL_OBJEXIT_P(this); //#### return this; } // nImO::Logical::asLogical bool nImO::Logical::deeplyEqualTo (const nImO::Value & other) const { ODL_OBJENTER(); //#### ODL_P1("other = ", &other); //#### bool result = (&other == this); if (! result) { const Logical * otherPtr = other.asLogical(); if (nullptr != otherPtr) { result = (_value == otherPtr->_value); } } ODL_OBJEXIT_B(result); //#### return result; } // nImO::Logical::deeplyEqualTo nImO::Enumerable nImO::Logical::enumerationType (void) const { ODL_OBJENTER(); //#### Enumerable result = Enumerable::Logical; ODL_OBJEXIT_I(StaticCast(int, result)); //#### return result; } // nImO::Logical::enumerationType nImO::ComparisonStatus nImO::Logical::equalTo (const nImO::Value & other) const { ODL_OBJENTER(); //#### ODL_P1("other = ", &other); //#### ComparisonStatus result; if (&other != this) { const Logical * otherPtr = other.asLogical(); if (nullptr == otherPtr) { if (nullptr == other.asContainer()) { result.clear(); } else { result = other.equalTo(*this); } } else { result = (_value == otherPtr->_value); } } ODL_OBJEXIT(); //#### return result; } // nImO::Logical::equalTo nImO::SpValue nImO::Logical::extractValue (const nImO::Message & NOT_USED_(theMessage), const int leadByte, size_t & position, nImO::SpArray parentValue) { ODL_ENTER(); //#### //ODL_P1("theMessage = ", &theMessage); ODL_P2("position = ", &position, "parentValue = ", parentValue.get()); //#### ODL_X1("leadByte = ", leadByte); //#### auto result{std::make_shared<Logical>(DataKind::OtherLogicalTrueValue == (DataKind::OtherLogicalValueMask & leadByte))}; ++position; // We will always accept the lead byte ODL_I1("position <- ", position); //#### if ((nullptr != parentValue) && (nullptr != result)) { ODL_LOG("((nullptr != parentValue) && (nullptr != result))"); //#### parentValue->addValue(result); } ODL_EXIT_P(result.get()); //#### return result; } // nImO::Logical::extractValue const std::string & nImO::Logical::getCanonicalRepresentation (const bool aValue) { ODL_ENTER(); //#### const std::string & result = (aValue ? kCanonicalTrue : kCanonicalFalse); ODL_EXIT_P(&result); //#### return result; } // nImO::Logical::getCanonicalRepresentation void nImO::Logical::getExtractionInfo (DataKind & aByte, DataKind & aMask, nImO::Value::Extractor & theExtractor) { ODL_ENTER(); //#### ODL_P3("aByte = ", &aByte, "aMask = ", &aMask, "theExtractor = ", &theExtractor); //#### aByte = (DataKind::Other | DataKind::OtherLogical); aMask = (DataKind::Mask | DataKind::OtherTypeMask); theExtractor = extractValue; ODL_EXIT(); //#### } // nImO::Logical::getExtractionInfo const char * nImO::Logical::getInitialCharacters (void) { ODL_ENTER(); //#### static const char * initialChars = "ftFT"; ODL_EXIT_S(initialChars); //#### return initialChars; } // nImO::Logical::getInitialCharacters nImO::DataKind nImO::Logical::getTypeTag (void) const { ODL_OBJENTER(); //#### DataKind result = DataKind::OtherMessageExpectedOtherValue; ODL_OBJEXIT_I(StaticCast(int, result)); //#### return result; } // nImO::Logical::getTypeTag nImO::ComparisonStatus nImO::Logical::greaterThan (const nImO::Value & other) const { ODL_OBJENTER(); //#### ODL_P1("other = ", &other); //#### ComparisonStatus result; if (&other == this) { result = false; } else { const Logical * otherPtr = other.asLogical(); if (nullptr == otherPtr) { if (nullptr == other.asContainer()) { result.clear(); } else { result = other.lessThan(*this); } } else { result = (_value > otherPtr->_value); } } ODL_OBJEXIT(); //#### return result; } // nImO::Logical::greaterThan nImO::ComparisonStatus nImO::Logical::greaterThanOrEqual (const nImO::Value & other) const { ODL_OBJENTER(); //#### ODL_P1("other = ", &other); //#### ComparisonStatus result; if (&other != this) { const Logical * otherPtr = other.asLogical(); if (nullptr == otherPtr) { if (nullptr == other.asContainer()) { result.clear(); } else { result = other.lessThanOrEqual(*this); } } else { result = (_value >= otherPtr->_value); } } ODL_OBJEXIT(); //#### return result; } // nImO::Logical::greaterThanOrEqual nImO::ComparisonStatus nImO::Logical::lessThan (const nImO::Value & other) const { ODL_OBJENTER(); //#### ODL_P1("other = ", &other); //#### ComparisonStatus result; if (&other == this) { result = false; } else { const Logical * otherPtr = other.asLogical(); if (nullptr == otherPtr) { if (nullptr == other.asContainer()) { result.clear(); } else { result = other.greaterThan(*this); } } else { result = (_value < otherPtr->_value); } } ODL_OBJEXIT(); //#### return result; } // nImO::Logical::lessThan nImO::ComparisonStatus nImO::Logical::lessThanOrEqual (const nImO::Value & other) const { ODL_OBJENTER(); //#### ODL_P1("other = ", &other); //#### ComparisonStatus result; if (&other != this) { const Logical * otherPtr = other.asLogical(); if (nullptr == otherPtr) { if (nullptr == other.asContainer()) { result.clear(); } else { result = other.greaterThanOrEqual(*this); } } else { result = (_value <= otherPtr->_value); } } ODL_OBJEXIT(); //#### return result; } // nImO::Logical::lessThanOrEqual nImO::Logical & nImO::Logical::operator = (const nImO::Logical & other) { ODL_OBJENTER(); //#### ODL_P1("other = ", &other); //#### if (this != &other) { _value = other._value; } ODL_OBJEXIT_P(this); //#### return *this; } // nImO::Logical::operator= nImO::Logical & nImO::Logical::operator = (const bool value) { ODL_OBJENTER(); //#### ODL_B1("value = ", value); //#### _value = value; ODL_OBJEXIT_P(this); //#### return *this; } // nImO::Logical::operator= std::ostream & nImO::Logical::operator << (std::ostream & out) const { ODL_OBJENTER(); //#### ODL_P1("out = ", &out); //#### std::ios_base::fmtflags originalFormat = out.flags(); out << std::boolalpha << _value; out.flags(originalFormat); ODL_OBJEXIT_P(&out); //#### return out; } // nImO::Logical::operator << void nImO::Logical::printToStringBuffer (nImO::StringBuffer & outBuffer, const bool NOT_USED_(squished)) const { ODL_OBJENTER(); //#### ODL_P1("outBuffer = ", &outBuffer); //#### //ODL_B1("squished = ", squished); //#### outBuffer.addBool(_value); ODL_OBJEXIT(); //#### } // nImO::Logical::printToStringBuffer nImO::SpValue nImO::Logical::readFromStringBuffer (const nImO::StringBuffer & inBuffer, size_t & position) { ODL_ENTER(); //#### ODL_P2("inBuffer = ", &inBuffer, "position = ", &position); //#### bool atEnd; bool candidateValue = false; SpValue result; size_t localIndex = position; int aChar = inBuffer.getChar(localIndex++, atEnd); const std::string * candidate = nullptr; // Select which form of the value that is in the buffer: if (! atEnd) { if (('f' == aChar) || ('F' == aChar)) { candidate = &kCanonicalFalse; } else if (('t' == aChar) || ('T' == aChar)) { candidate = &kCanonicalTrue; candidateValue = true; } } if (nullptr != candidate) { bool done = false; bool valid = false; for (size_t ii = 1, len = candidate->length(); ! done; ) { aChar = tolower(inBuffer.getChar(localIndex, atEnd)); if (atEnd || isLegalTerminator(aChar)) { done = valid = true; // the character seen is a valid terminator } else if ((*candidate)[ii] == aChar) { ++localIndex; if (len == ++ii) { // the last character of the reference value was seen valid = isLegalTerminator(inBuffer.getChar(localIndex, atEnd)); if (atEnd) { valid = true; } done = true; } } else { // valid so far done = true; } } if (valid) { result.reset(new Logical(candidateValue)); } } if (nullptr != result) { position = localIndex; } ODL_EXIT_P(result.get()); //#### return result; } // nImO::Logical::readFromStringBuffer void nImO::Logical::writeToMessage (nImO::Message & outMessage) const { ODL_ENTER(); //#### ODL_P1("outMessage = ", &outMessage); //#### DataKind stuff = (DataKind::Other | DataKind::OtherLogical | (_value ? DataKind::OtherLogicalTrueValue : DataKind::OtherLogicalFalseValue)); outMessage.appendBytes(&stuff, sizeof(stuff)); ODL_EXIT(); //#### } // nImO::Logical::writeToMessage #if defined(__APPLE__) # pragma mark Global functions #endif // defined(__APPLE__)
26.931777
127
0.548963
opendragon
201b3f0ef1f204f63dc20d9a9668759eb52623aa
329
hpp
C++
swizzle/include/swizzle/script/Script.hpp
deathcleaver/swizzle
1a1cc114841ea7de486cf94c6cafd9108963b4da
[ "MIT" ]
2
2020-02-10T07:58:21.000Z
2022-03-15T19:13:28.000Z
swizzle/include/swizzle/script/Script.hpp
deathcleaver/swizzle
1a1cc114841ea7de486cf94c6cafd9108963b4da
[ "MIT" ]
null
null
null
swizzle/include/swizzle/script/Script.hpp
deathcleaver/swizzle
1a1cc114841ea7de486cf94c6cafd9108963b4da
[ "MIT" ]
null
null
null
#ifndef SCRIPT_HPP #define SCRIPT_HPP #include "Api.hpp" namespace script { class SWIZZLE_API Script { public: Script(); virtual ~Script(); void load(const char* binary); void loadFromFile(const char* binaryFile); void compile(const char* source); void compileFromFile(const char* sourceFile); }; } #endif
13.16
47
0.711246
deathcleaver
201cce23bc3253149a714f3ee2cb89bf17666306
865
cpp
C++
LabelDemux/LabelDemux.cpp
jimcavoy/ConfLabelReader
6a0483f8810e3f0bdae748b51119bb4ce4e98f4c
[ "MIT" ]
null
null
null
LabelDemux/LabelDemux.cpp
jimcavoy/ConfLabelReader
6a0483f8810e3f0bdae748b51119bb4ce4e98f4c
[ "MIT" ]
null
null
null
LabelDemux/LabelDemux.cpp
jimcavoy/ConfLabelReader
6a0483f8810e3f0bdae748b51119bb4ce4e98f4c
[ "MIT" ]
null
null
null
#ifdef WIN32 #define _CRT_SECURE_NO_WARNINGS #endif #include "pch.h" #include "LabelDemux.h" #include "LabelDemuxImpl.h" #include <string.h> namespace ThetaStream { LabelDemux::LabelDemux() :_pimpl(new LabelDemuxImpl) , _label(nullptr) , _length(0) { } LabelDemux::~LabelDemux() { delete _pimpl; delete[] _label; } void LabelDemux::parse(const BYTE* stream, UINT32 len) { delete[] _label; _label = nullptr; _length = 0; _pimpl->parse(stream, len); const AccessUnit& au = _pimpl->label(); if (au.length() > 0) { _label = new BYTE[au.length()]; _length = au.length(); std::copy(au.begin(), au.end(), _label); } } bool LabelDemux::hasLabelStream() const { return _pimpl->hasLabel(); } const BYTE* LabelDemux::label() const { return _label; } UINT32 LabelDemux::labelSize() const { return _length; } }
15.446429
55
0.65896
jimcavoy
202921fcc9274470129779f795617510d33d5e6c
7,194
cpp
C++
TestsValidation/TVNetwork/TVNetworkServer/Server.cpp
benkaraban/anima-games-engine
8aa7a5368933f1b82c90f24814f1447119346c3b
[ "BSD-3-Clause" ]
2
2015-04-16T01:05:53.000Z
2019-08-26T07:38:43.000Z
TestsValidation/TVNetwork/TVNetworkServer/Server.cpp
benkaraban/anima-games-engine
8aa7a5368933f1b82c90f24814f1447119346c3b
[ "BSD-3-Clause" ]
null
null
null
TestsValidation/TVNetwork/TVNetworkServer/Server.cpp
benkaraban/anima-games-engine
8aa7a5368933f1b82c90f24814f1447119346c3b
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2010, Anima Games, Benjamin Karaban, Laurent Schneider, * Jérémie Comarmond, Didier Colin. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * - Neither the name of the copyright 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 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 "Server.h" #include "BenchNetworkMessage.h" #include <Network/Message.h> #include <iostream> Server::Server() : _engine(Network::NetworkEngine(&_condition, &_conditionMutex)), _nbMessageSent(0), _totalMessageSizeSent(0), _isBeingKilled(false) { for(int32 iThread = 0; iThread<NB_THREADS; ++iThread) _threads[iThread] = NULL; for(int32 iSession = 0; iSession<Network::SOCKET_MAX_CONNECTION; ++iSession) _sessions[iSession].setIdSession(iSession); } Server::~Server() { for(int32 ii = 0; ii<NB_THREADS; ++ii) { if(_threads[ii] != NULL) { delete _threads[ii]; _threads[ii] = NULL; } } } void Server::launch() { std::cout<<"Listening on 192.168.0.19:31337"<<std::endl; _engine.open(L"192.168.0.19", 31337); _engine.launch(); for(int32 ii = 0; ii<NB_THREADS; ++ii) { _threads[ii] = new Core::Thread(&Server::run, *this); } while(!_isBeingKilled) { Core::Thread::sleep(20); } { Core::ScopedCondLock lock(_conditionMutex); _condition.notifyAll(); } for(int32 ii = 0; ii<NB_THREADS; ++ii) { _threads[ii]->join(); } } void Server::run() { while(!_isBeingKilled) { Network::Message * message = NULL; { Core::ScopedCondLock lock(_conditionMutex); while(!_isBeingKilled && !_engine.getMessage(message)) _condition.wait(lock); } if(!_isBeingKilled) { int32 sessionId = message->getSessionId(); Network::EMessageType type = message->getMessageType(); if(type == Network::NETWORK_OPEN_SESSION_MESSAGE) { if(!_sessions[sessionId].isOpened()) _sessions[sessionId].open(); } else if(type == Network::NETWORK_CLOSE_SESSION_MESSAGE)//La connexion r�seau a �t� ferm�e. { if(_sessions[sessionId].isOpened()) _sessions[sessionId].close(); } else if(type == Network::APPLICATION_MESSAGE) { BenchNetworkMessage benchMessage; message->getMessage(benchMessage); bool broadcast = false; BenchNetworkMessage answer; try { _sessions[sessionId].processMessage(benchMessage, answer, broadcast); if(_sessions[sessionId].isOpened()) manageAnswer(broadcast, sessionId, answer); }catch(Core::Exception & e) { std::cout<<"ProcessMessage : "<<String8(e.getMessage()).c_str()<<std::endl; _isBeingKilled = true; } } else//Message non g�r�! { std::cout<<"Unknown message type : "<<type<<std::endl; } delete message; message = NULL; } } } void Server::manageAnswer(bool broadcast, int32 sessionId, BenchNetworkMessage & answer) { if(broadcast) { for(int32 iSession = 0; iSession<Network::SOCKET_MAX_CONNECTION; ++iSession) { if(_sessions[iSession].isOpened()) { Network::Message messageToSend(Network::APPLICATION_MESSAGE, answer, iSession); int32 messageSize = messageToSend.getSize(); try { _engine.sendMessage(messageToSend); //On arrive ici que si le message a bien �t� envoy� { Core::ScopedLock lock(_mutex); _nbMessageSent++; _totalMessageSizeSent += messageSize; } }catch(Core::Exception & e) { std::cout<<"Broadcast : "<<String8(e.getMessage()).c_str()<< " Session : "<< iSession <<std::endl; _sessions[iSession].close(); } } } } else//On envoie � la premi�re session ouverte { int32 iSession = sessionId; bool notFound = true; do { iSession++; iSession = iSession % Network::SOCKET_MAX_CONNECTION; if(iSession != sessionId && _sessions[iSession].isOpened()) { notFound = false; Network::Message messageToSend(Network::APPLICATION_MESSAGE, answer, iSession); int32 messageSize = messageToSend.getSize(); try { _engine.sendMessage(messageToSend); //On arrive ici que si le message a bien �t� envoy� { Core::ScopedLock lock(_mutex); _nbMessageSent++; _totalMessageSizeSent += messageSize; } }catch(Core::Exception & e) { std::cout<<"Unicast : "<<String8(e.getMessage()).c_str()<< " Session : "<< iSession <<std::endl; _sessions[iSession].close(); } } }while(notFound && iSession != sessionId); } }
34.753623
119
0.549347
benkaraban